Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
362,000
def coverage_score(gold, pred, ignore_in_gold=[], ignore_in_pred=[]): gold, pred = _preprocess(gold, pred, ignore_in_gold, ignore_in_pred) return np.sum(pred != 0) / len(pred)
Calculate (global) coverage. Args: gold: A 1d array-like of gold labels pred: A 1d array-like of predicted labels (assuming abstain = 0) ignore_in_gold: A list of labels for which elements having that gold label will be ignored. ignore_in_pred: A list of labels for which ...
362,001
def pruneUI(dupeList, mainPos=1, mainLen=1): dupeList = sorted(dupeList) print for pos, val in enumerate(dupeList): print "%d) %s" % (pos + 1, val) while True: choice = raw_input("[%s/%s] Keepers: " % (mainPos, mainLen)).strip() if not choice: print ("Please ente...
Display a list of files and prompt for ones to be kept. The user may enter ``all`` or one or more numbers separated by spaces and/or commas. .. note:: It is impossible to accidentally choose to keep none of the displayed files. :param dupeList: A list duplicate file paths :param mainPos: ...
362,002
def get_all_names(offset=None, count=None, include_expired=False, proxy=None, hostport=None): assert proxy or hostport, if proxy is None: proxy = connect_hostport(hostport) offset = 0 if offset is None else offset if count is None: count = get_num_names(proxy=proxy, host...
Get all names within the given range. Return the list of names on success Return {'error': ...} on failure
362,003
def _flush_ndb_deletes(self, items, options): assert ndb is not None ndb.delete_multi(items, config=self._create_config(options))
Flush all deletes to datastore.
362,004
def send_message(self): start = time.time() message = None if not self.initialized: message = self.construct_start_message() self.initialized = True else: message = self.construct_end_message() self.send_UDP_message(message) e...
Send message over UDP. If tracking is disables, the bytes_sent will always be set to -1 Returns: (bytes_sent, time_taken)
362,005
def list_to_csv(my_list, csv_file): if PY3: csv_handler = open(csv_file, , newline=) else: csv_handler = open(csv_file, ) try: writer = csv.writer(csv_handler, delimiter=, quoting=csv.QUOTE_ALL) writer.writerows(my_list) finally: csv_handler.close()
Save a matrix (list of lists) to a file as a CSV .. code:: python my_list = [["Name", "Location"], ["Chris", "South Pole"], ["Harry", "Depth of Winter"], ["Bob", "Skull"]] reusables.list_to_csv(my_list, "example.csv") example.csv ...
362,006
def feed(self, char, char_len): if char_len == 2: order = self.get_order(char) else: order = -1 if order >= 0: self._total_chars += 1 if order < self._table_size: if 512 > self._char_to_freq_order[...
feed a character with known length
362,007
def _calculate_aes_cipher(key): if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( , len(key) )) if len(key) == 16: cipher = elif len(key) == 24: cipher = elif len(key) == 32: cipher = return cipher
Determines if the key is a valid AES 128, 192 or 256 key :param key: A byte string of the key to use :raises: ValueError - when an invalid key is provided :return: A unicode string of the AES variation - "aes128", "aes192" or "aes256"
362,008
def copy(self, src, dst, other_system=None): with _handle_azure_exception(): self.client.copy_file( copy_source=(other_system or self)._format_src_url(src, self), **self.get_client_kwargs(dst))
Copy object of the same storage. Args: src (str): Path or URL. dst (str): Path or URL. other_system (pycosio.storage.azure._AzureBaseSystem subclass): The source storage system.
362,009
def add(self, req: Request): key = req.key if key not in self: self[key] = ReqState(req) return self[key]
Add the specified request to this request store.
362,010
def get_home_dir(): try: path = encoding.to_unicode_from_fs(osp.expanduser()) except Exception: path = if osp.isdir(path): return path else: for env_var in (, , ): pat...
Return user home directory
362,011
def decode_text(s): if s.startswith(b): return unicode(s[2:], , ) else: return .join(PDFDocEncoding[ord(c)] for c in s)
Decodes a PDFDocEncoding string to Unicode.
362,012
def P1(self, value): if value < self.P2: self._P1 = value else: raise InvalidFirstDisparityChangePenaltyError("P1 must be less " "than P2.") self._replace_bm()
Set private ``_P1`` and reset ``_block_matcher``.
362,013
def export_public_key(user_id, env=None, sp=subprocess): args = gpg_command([, user_id]) result = check_output(args=args, env=env, sp=sp) if not result: log.error(, user_id) raise KeyError(user_id) return result
Export GPG public key for specified `user_id`.
362,014
def InstanceOf(cls, **kwargs): return Property(types=cls, load=cls.load, **kwargs)
A property that is an instance of `cls`.
362,015
def _MultipleModulesFoundError(path, candidates): assert len(candidates) > 1 params = [path] + _StripCommonPathPrefix(candidates[:2]) if len(candidates) == 2: fmt = ERROR_LOCATION_MULTIPLE_MODULES_3 else: fmt = ERROR_LOCATION_MULTIPLE_MODULES_4 params.append(str(len(candidates) - 2)) return fmt...
Generates an error message to be used when multiple matches are found. Args: path: The breakpoint location path that the user provided. candidates: List of paths that match the user provided path. Must contain at least 2 entries (throws AssertionError otherwise). Returns: A (format, parameters...
362,016
def prepare_outputs(self, job): outputs = flatten(job.output()) for o in outputs: if isinstance(o, FileSystemTarget): parent_dir = os.path.dirname(o.path) if parent_dir and not o.fs.exists(parent_dir): logger.info("Creating parent ...
Called before job is started. If output is a `FileSystemTarget`, create parent directories so the hive command won't fail
362,017
def POST(self, path, body, xml=True): url = self._absolute_url(path) headers = dict(self.headers) if xml: headers[] = headers[] = else: headers[] = headers[] = resp = requests.post(url, data=body, headers=headers, veri...
Raw POST to the MISP server :param path: URL fragment (ie /events/) :param body: HTTP Body (raw bytes) :returns: HTTP raw content (as seen by :class:`requests.Response`)
362,018
def get_catalog(self, catalog_id): return self._load_data( self.CATALOGS_ENDPOINT, default=[], resource_id=catalog_id )
Return specified course catalog. Returns: dict: catalog details if it is available for the user.
362,019
def run(configobj=None): acscteforwardmodel(configobj[], exec_path=configobj[], time_stamps=configobj[], verbose=configobj[], quiet=configobj[], single_core=configobj[] )
TEAL interface for the `acscteforwardmodel` function.
362,020
def _adjust_font(self): fnames = [k for k in Widget_fontdict.keys()] fl = list(map(str.lower, fnames)) if (not self.text_font) or self.text_font.lower() not in fl: self.text_font = "helv" i = fl.index(self.text_font.lower()) self.text_font = fnames[i] ...
Ensure the font name is from our list and correctly spelled.
362,021
def _send_cmd(self, cmd): self._process.stdin.write("{}\n".format(cmd).encode("utf-8")) self._process.stdin.flush()
Write command to remote process
362,022
def software_fibonacci(n): a, b = 0, 1 for i in range(n): a, b = b, a + b return a
a normal old python function to return the Nth fibonacci number.
362,023
def _do_crop(self, lines, width, height, x_crop, y_crop): lines = crop_or_expand( lines, height, default=[self.fillchar * width], scheme=self._schemes[y_crop]) for i, line in enumerate(lines): lines[i] = crop_or_expand( line, width, default=se...
Crops a list of strings to the specified width/height
362,024
def createPropagate( request: Union[Request, dict], client_name) -> Propagate: if not isinstance(request, (Request, dict)): logger.error("{}Request not formatted properly to create propagate" .format(THREE_PC_PREFIX)) return logger.tr...
Create a new PROPAGATE for the given REQUEST. :param request: the client REQUEST :return: a new PROPAGATE msg
362,025
def is_flash_encryption_key_valid(self): word0 = self.read_efuse(0) rd_disable = (word0 >> 16) & 0x1 if rd_disable: return True else: key_word = [0] * 7 for i in range(len(key_word)): key_word[i] = self....
Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1 this bit is at position 16 in EFUSE_BLK0_RDATA0_REG
362,026
def precompute_raveled_slices(coeff_shapes, axes=None): a_shape = coeff_shapes[0] a_size = np.prod(a_shape) if len(coeff_shapes) == 1: return [slice(a_size), ] a_slice = slice(a_size) coeff_slices = [] coeff_slices.append(a_slice) details_list = coeff...
Return slices and shapes for raveled multilevel wavelet coefficients. The output is equivalent to the ``coeff_slices`` output of `pywt.ravel_coeffs`, but this function does not require computing a wavelet transform first. Parameters ---------- coeff_shapes : array-like A list of multil...
362,027
def guess_filename(self, basedir, kind=None): if kind: filepath = os.path.join(basedir, self.engines[kind]._default_filename) if os.path.exists(filepath): return filepath, self.engines[kind] for filename, kind in self....
Try to find existing settings filename from base directory using default filename from available engines. First finded filename from available engines win. So registred engines order matter. Arguments: basedir (string): Directory path where to search for. Keyword A...
362,028
def path(self, tax_ids): assert tax_ids[0] == self.tax_id if len(tax_ids) == 1: return self n = tax_ids[1] try: child = next(i for i in self.children if i.tax_id == n) except StopIteration: raise ValueError(n) return child.pa...
Get the node at the end of the path described by tax_ids.
362,029
def send_frame(self, frame): data = self._send_framer.to_bytes(frame, self._send_state) self._transport.write(data)
Called by the client protocol to send a frame to the remote peer. This method does not block; it buffers the data and arranges for it to be sent out asynchronously. :param frame: The frame to send to the peer. Must be in the format expected by the currently active send ...
362,030
def reset_new_request(self): raw_url = self.new_request[] parsed_url = urlparse(raw_url) qsl = parse_qsl(parsed_url.query) new_url = self._join_url( parsed_url, [i for i in qsl if i not in self.ignore[]]) self.new_request[] = new_url self.logger_funct...
Remove the non-sense args from the self.ignore, return self.new_request
362,031
def execute(task_function, *args, **kwargs): if get_setting(): logger.debug(\ % task_function.__name__) return task_function(*args, **kwargs) db.connections.close_all() task_function.delay(*args, **kwargs)
Run a task asynchronously
362,032
def workspaces(self): workspaces = [] def collect_workspaces(con): if con.type == "workspace" and not con.name.startswith(): workspaces.append(con) return for c in con.nodes: collect_workspaces(c) collect_workspa...
Retrieve a list of currently active workspaces. :rtype: List of :class:`Con`.
362,033
def iter_starred(self, login=None, sort=None, direction=None, number=-1, etag=None): if login: return self.user(login).iter_starred(sort, direction) params = {: sort, : direction} self._remove_none(params) url = self._build_url(, ) retur...
Iterate over repositories starred by ``login`` or the authenticated user. .. versionchanged:: 0.5 Added sort and direction parameters (optional) as per the change in GitHub's API. :param str login: (optional), name of user whose stars you want to see :param str so...
362,034
def PATTERN(self): u self.update_mapping() return u" |\n".join([pattern_unformatted % (f.name, f._pattern) for f in iter(self)])
u""" Uses the mapping of names to features to return a PATTERN suitable for using the lib2to3 patcomp.
362,035
def run_script(self, requires, script_name): ns = sys._getframe(1).f_globals name = ns[] ns.clear() ns[] = name self.require(requires)[0].run_script(script_name, ns)
Locate distribution for `requires` and run `script_name` script
362,036
def fitcircle(n, x, y): sx, sx2, sx3, sy, sy2, sy3, sxy, sxy2, syx2 = (0,) * 9 print(type(sx), sx) for i in range(n): sx = sx + x[i] sx2 = sx2 + x[i]**2 sx3 = sx3 + x[i]**3 sy = sy + y[i] sy2 = sy2 + y[i]**2 sy3 = sy3 + y[i]**3 ...
c Fit circle to arbitrary number of x,y pairs, based on the c modified least squares method of Umback and Jones (2000), c IEEE Transactions on Instrumentation and Measurement.
362,037
def pre_filter(self, conditions, user): return conditions.filter(group__in=user.groups.all())
Returns all of the items from conditions which are enabled by a user being member of a Django Auth Group.
362,038
def create(cls, train_ds, valid_ds, test_ds=None, path:PathOrStr=, bs:int=32, val_bs:int=None, pad_idx=1, pad_first=True, device:torch.device=None, no_check:bool=False, backwards:bool=False, **dl_kwargs) -> DataBunch: "Function that transform the `datasets` in a `DataBunch` for classification. Pa...
Function that transform the `datasets` in a `DataBunch` for classification. Passes `**dl_kwargs` on to `DataLoader()`
362,039
def measure_residence_time(self, cutoff = 3.5): i=0 data = namedtuple("contacts","frame time ligandatomname ligandatomindex cutoff proteinatomname proteinatomindex resname resid segid") for traj in self.trajectory: start = timer() prog = ProgressBar("Residence_ti...
This function measures the residence time of all residues within the cutoff distance from the ligand. Takes: * cutoff * - cutoff distance in angstroms Output: * self.residue_counts * - dictionary of all residues that have made contact with the ligand (i.e. hav...
362,040
def parseStr(self, st) : self.data = st.replace(, ) self.data = self.data.replace(, ) self.data = self.data.split()
Parses a string
362,041
def get_display_types(): display_types = OrderedDict() for namespace in get_supported_libraries(): display_types[namespace] = get_choices(.format( namespace)) return display_types
Get ordered dict containing available display types from available luma sub-projects. :rtype: collections.OrderedDict
362,042
def pole2plunge_bearing(strike, dip): strike, dip = np.atleast_1d(strike, dip) bearing = strike - 90 plunge = 90 - dip bearing[bearing < 0] += 360 return plunge, bearing
Converts the given *strike* and *dip* in dgrees of a plane(s) to a plunge and bearing of its pole. Parameters ---------- strike : number or sequence of numbers The strike of the plane(s) in degrees, with dip direction indicated by the azimuth (e.g. 315 vs. 135) specified following the "...
362,043
def upload_image(self, media_file): res = self._post( url=, files={ : media_file }, result_processor=lambda x: x[] ) return res
上传群发消息内的图片 详情请参考 http://mp.weixin.qq.com/wiki/15/5380a4e6f02f2ffdc7981a8ed7a40753.html :param media_file: 要上传的文件,一个 File-object :return: 上传成功时返回图片 URL
362,044
def clear_buffer(self, fg, attr, bg): self._buffer.clear(fg, attr, bg)
Clear the current double-buffer used by this object. :param fg: The foreground colour to use for the new buffer. :param attr: The attribute value to use for the new buffer. :param bg: The background colour to use for the new buffer.
362,045
def rename_categories(self, key: str, categories: Sequence[Any]): if isinstance(categories, Mapping): raise ValueError() if key in self.obs: old_categories = self.obs[key].cat.categories.tolist() self.obs[key].cat.rename_categories(categories, inplace=True) ...
Rename categories of annotation ``key`` in :attr:`obs`, :attr:`var` and :attr:`uns`. Only supports passing a list/array-like ``categories`` argument. Besides calling ``self.obs[key].cat.categories = categories`` - similar for :attr:`var` - this also renames categories in unstructured ...
362,046
def log_context(trace_level, stream): original_trace_level = DebugInfoHolder.DEBUG_TRACE_LEVEL original_stream = DebugInfoHolder.DEBUG_STREAM DebugInfoHolder.DEBUG_TRACE_LEVEL = trace_level DebugInfoHolder.DEBUG_STREAM = stream try: yield finally: DebugInfoHolder.DEBUG_TRAC...
To be used to temporarily change the logging settings.
362,047
def regexp(__string: str, __pattern: str, __repl: Union[Callable, str], *, count: int = 0, flags: int = 0) -> str: return re.sub(__pattern, __repl, __string, count, flags)
Jinja filter for regexp replacements. See :func:`re.sub` for documentation. Returns: Text with substitutions applied
362,048
def read_data( self, step, filename = None ): filename = get_default( filename, self.filename ) out = {} fd = open( self.filename, ) while 1: line = skip_read_line(fd, no_eof=True).split() if line[0] == : break n_nod = int(line...
Point data only!
362,049
def get_alignment_df_from_file(alignment_file, a_seq_id=None, b_seq_id=None): alignments = list(AlignIO.parse(alignment_file, "emboss")) alignment_df = pd.DataFrame(columns=[, , , , , , ]) for alignment in alignments: if not a_seq_id: a_seq_id = list(alignment)[0].id a_seq ...
Get a Pandas DataFrame of the Needle alignment results. Contains all positions of the sequences. Args: alignment_file: a_seq_id: Optional specification of the ID of the reference sequence b_seq_id: Optional specification of the ID of the aligned sequence Returns: Pandas DataFra...
362,050
def _DecodeURL(self, url): if not url: return decoded_url = urlparse.unquote(url) if isinstance(decoded_url, py2to3.BYTES_TYPE): try: decoded_url = decoded_url.decode() except UnicodeDecodeError as exception: decoded_url = decoded_url.decode(, errors=) logger...
Decodes the URL, replaces %XX to their corresponding characters. Args: url (str): encoded URL. Returns: str: decoded URL.
362,051
def make_executable(script_path): status = os.stat(script_path) os.chmod(script_path, status.st_mode | stat.S_IEXEC)
Make `script_path` executable. :param script_path: The file to change
362,052
def get_name(self): if not self.is_tpl(): try: return self.host_name except AttributeError: return else: try: return self.name except AttributeError: return
Get the host name. Try several attributes before returning UNNAMED* :return: The name of the host :rtype: str
362,053
def htseq_stats_table(self): headers = OrderedDict() headers[] = { : , : , : 100, : 0, : , : } headers[] = { : .format(config.read_count_prefix), : .format(config.read_count_desc), ...
Take the parsed stats from the HTSeq Count report and add them to the basic stats table at the top of the report
362,054
def get_single_external_tool_courses(self, course_id, external_tool_id): path = {} data = {} params = {} path["course_id"] = course_id path["external_tool_id"] = external_tool_id self.logger.debug("GET /api/v1/co...
Get a single external tool. Returns the specified external tool.
362,055
def emit(self, object, *args): for cb in self.map.get(object, []): cb(*args)
Emit the signal.
362,056
def rlm(data, xseq, **params): X = sm.add_constant(data[]) Xseq = sm.add_constant(xseq) init_kwargs, fit_kwargs = separate_method_kwargs( params[], sm.RLM, sm.RLM.fit) model = sm.RLM(data[], X, **init_kwargs) results = model.fit(**fit_kwargs) data = pd.DataFrame({: xseq}) data...
Fit RLM
362,057
def parse(self, rrstr): if self._initialized: raise pycdlibexception.PyCdlibInternalError() (su_len, su_entry_version_unused, self.posix_name_flags) = struct.unpack_from(, rrstr[:5], 2) self.posix_name += rrstr[5:5 + name_len] self._...
Parse a Rock Ridge Alternate Name record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing.
362,058
def cudaDriverGetVersion(): version = ctypes.c_int() status = _libcudart.cudaDriverGetVersion(ctypes.byref(version)) cudaCheckStatus(status) return version.value
Get installed CUDA driver version. Return the version of the installed CUDA driver as an integer. If no driver is detected, 0 is returned. Returns ------- version : int Driver version.
362,059
def set(self, value): if not isinstance(value, str_cls): raise TypeError(unwrap( , type_name(self), type_name(value) )) self._native = value if self._map is not None: if value in self._reverse_map: ...
Sets the value of the object :param value: A unicode string. May be a dotted integer string, or if _map is provided, one of the mapped values. :raises: ValueError - when an invalid value is passed
362,060
def Ry_matrix(theta): return np.array([ [np.cos(theta), 0, np.sin(theta)], [0, 1, 0], [-np.sin(theta), 0, np.cos(theta)] ])
Rotation matrix around the Y axis
362,061
def compute_bootci(x, y=None, func=, method=, paired=False, confidence=.95, n_boot=2000, decimals=2, seed=None, return_dist=False): from inspect import isfunction from scipy.stats import norm x = np.asarray(x) n = x.size assert x.ndim == 1 assert n > 1...
Bootstrapped confidence intervals of univariate and bivariate functions. Parameters ---------- x : 1D-array or list First sample. Required for both bivariate and univariate functions. y : 1D-array, list, or None Second sample. Required only for bivariate functions. func : str or cus...
362,062
def setCurrentMode( self, mode ): self.scene().setCurrentMode(mode) self.scene().setSceneRect(0, 0, self.width() - 5, self.height() - 5) if ( not self.signalsBlocked() ): self.currentModeChanged.emit(mode)
Sets the current mode that this calendar will be displayed in. :param mode | <XCalendarWidget.Mode>
362,063
def split_last_dimension(x, n): x_shape = common_layers.shape_list(x) m = x_shape[-1] if isinstance(m, int) and isinstance(n, int): assert m % n == 0 return tf.reshape(x, x_shape[:-1] + [n, m // n])
Reshape x so that the last dimension becomes two dimensions. The first of these two dimensions is n. Args: x: a Tensor with shape [..., m] n: an integer. Returns: a Tensor with shape [..., n, m/n]
362,064
def list_lights(self, selector=): return self.client.perform_request( method=, endpoint=, endpoint_args=[selector], parse_data=False)
Given a selector (defaults to all), return a list of lights. Without a selector provided, return list of all lights.
362,065
def initialize_converter(): import datetime import inspect from bunq.sdk import client from bunq.sdk import context from bunq.sdk.model import core from bunq.sdk.json import adapters from bunq.sdk.json import converter from bunq.sdk.model.generated import object_ from bunq.sdk...
:rtype: None
362,066
def statusBar(step, total, bar_len=20, onlyReturn=False): norm = 100.0 / total step *= norm step = int(step) increment = 100 // bar_len n = step // increment m = bar_len - n text = "\r[" + "=" * n + "o" + "-" * m + "]" + str(step) + "%" if onlyReturn: return text stdout...
print a ASCI-art statusbar of variable length e.g.showing 25%: >>> step = 25 >>> total = 100 >>> print( statusBar(step, total, bar_len=20, onlyReturn=True) ) \r[=====o---------------]25% as default onlyReturn is set to False in this case the last printed line would be flushed every time when ...
362,067
def select_bucket_region(custom_bucket, hook_region, stacker_bucket_region, provider_region): region = None if custom_bucket: region = hook_region else: region = stacker_bucket_region return region or provider_region
Returns the appropriate region to use when uploading functions. Select the appropriate region for the bucket where lambdas are uploaded in. Args: custom_bucket (str, None): The custom bucket name provided by the `bucket` kwarg of the aws_lambda hook, if provided. hook_region (str):...
362,068
def assemble_content_aad(message_id, aad_content_string, seq_num, length): if not isinstance(aad_content_string, aws_encryption_sdk.identifiers.ContentAADString): raise SerializationError("Unknown aad_content_string") fmt = ">16s{}sIQ".format(len(aad_content_string.value)) return struct.pack(fm...
Assembles the Body AAD string for a message body structure. :param message_id: Message ID :type message_id: str :param aad_content_string: ContentAADString object for frame type :type aad_content_string: aws_encryption_sdk.identifiers.ContentAADString :param seq_num: Sequence number of frame :t...
362,069
def _get_summary_struct(self): data_fields = [ (, ), (, ), (, )] if in self._list_fields(): data_fields.append((, )) training_fields = [ ("Number of trees", ), ("Max tree depth", ), ("Training time (se...
Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of list of tuples) A list of summary sections...
362,070
def enable_busy_cursor(self): QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor) )
Set the hourglass enabled.
362,071
def _required_byte_num(mode, fmt, n_samp): if fmt == : n_bytes = math.ceil(n_samp*1.5) elif fmt in [, ]: n_extra = n_samp % 3 if n_extra == 2: if fmt == : n_bytes = upround(n_samp * 4/3, 4) else: if mode == : ...
Determine how many signal bytes are needed to read or write a number of desired samples from a dat file. Parameters ---------- mode : str Whether the file is to be read or written: 'read' or 'write'. fmt : str The wfdb dat format. n_samp : int The number of samples wante...
362,072
def write_county_estimate(self, table, variable, code, datum): try: division = Division.objects.get( code="{}{}".format(datum["state"], datum["county"]), level=self.COUNTY_LEVEL, ) CensusEstimate.objects.update_or_create( ...
Creates new estimate from a census series. Data has following signature from API: { 'B00001_001E': '5373', 'NAME': 'Anderson County, Texas', 'county': '001', 'state': '48' }
362,073
def write_out_sitemap(self, opath): if opath not in self.written_out_sitemaps: Extension.formatted_sitemap = self.formatter.format_navigation( self.app.project) if Extension.formatted_sitemap: escaped_sitemap = Extension.formatted_sitemap.replace(...
Banana banana
362,074
def log(*args, **attrs): attrs.setdefault("metavar", "PATH") attrs.setdefault("show_default", False) return option(log, *args, **attrs)
Override log file location.
362,075
def _on_report(_loop, adapter, conn_id, report): conn_string = None if conn_id is not None: conn_string = adapter._get_property(conn_id, ) if isinstance(report, BroadcastReport): adapter.notify_event_nowait(conn_string, , report) elif conn_string is not None: adapter.notif...
Callback when a report is received.
362,076
def sampling_shap_1000(model, data): return lambda X: SamplingExplainer(model.predict, data).shap_values(X, nsamples=1000)
IME 1000 color = red_blue_circle(0.5) linestyle = dashed
362,077
def render_filter(self, next_filter): next(next_filter) while True: data = (yield) res = [self.cell_format(access(data)) for access in self.accessors] next_filter.send(res)
Produce formatted output from the raw data stream.
362,078
def ExpireObject(self, key): node = self._hash.pop(key, None) if node: self._age.Unlink(node) self.KillObject(node.data) return node.data
Expire a specific object from cache.
362,079
def update_trackers(self): self.posts_count = self.posts.filter(approved=True).count() first_post = self.posts.all().order_by().first() last_post = self.posts.filter(approved=True).order_by().first() self.first_post = first_post self.last_post = last_post self.la...
Updates the denormalized trackers associated with the topic instance.
362,080
def _get_zipped_rows(self, soup): table = soup.findChildren()[2] rows = table.findChildren([])[:-2] spacing = range(2, len(rows), 3) rows = [row for (i, row) in enumerate(rows) if (i not in spacing)] info = [row for (i, ...
Returns all 'tr' tag rows as a list of tuples. Each tuple is for a single story.
362,081
def _maybe_check_valid_shape(shape, validate_args): if not dtype_util.is_integer(shape.dtype): raise TypeError(.format( shape, dtype_util.name(shape.dtype))) assertions = [] message = if tensorshape_util.rank(shape.shape) is not None: if tensorshape_util.rank(shape.shape) > 1: raise ...
Check that a shape Tensor is int-type and otherwise sane.
362,082
def append(self, item): print(item) super(MyList, self).append(item)
append item and print it to stdout
362,083
def make_request_log_message(**args): s response. :op: The library operation during which the request was sent. :payload: Optional. The payload sent with the request. :return: A formatted string. ophandleurlheadersverifyresppayload\n \nop handleURL: urlHEADERS: headersVERIFY...
Creates a string containing all relevant information about a request made to the Handle System, for logging purposes. :handle: The handle that the request is about. :url: The url the request is sent to. :headers: The headers sent along with the request. :verify: Boolean parameter passed to the ...
362,084
def _read_name_file(self, filename): file_path = os.path.join(self._DATA_DIR, filename) with open(file_path) as f: names = json.load(f) return names
Read a name file from the data directory :param filename: Name of the file to read. :return: A list of name entries.
362,085
def get_display_name(self): return DisplayText( text=profile.DISPLAYNAME, language_type=Type(**profile.LANGUAGETYPE), script_type=Type(**profile.SCRIPTTYPE), format_type=Type(**profile.FORMATTYPE))
Gets a display name for this service implementation. return: (osid.locale.DisplayText) - a display name *compliance: mandatory -- This method must be implemented.*
362,086
def gettextvalue(self, window_name, object_name, startPosition=0, endPosition=0): object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) return object_handle.AXVal...
Get text value @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name...
362,087
def compile(self, ops): def _compile(): code = [] for op in ops: if isinstance(op, SyscallInvoke): code.extend(self.syscall(op)) elif isinstance(op, LoadRegister): code.extend(self.reg_load(op.register, op...
Translate a list of operations into its assembler source. Arguments: ops(list): A list of shellcode operations. Returns: str: The assembler source code that implements the shellcode.
362,088
def buildingname(ddtt): idf = ddtt.theidf building = idf.idfobjects[.upper()][0] return building.Name
return building name
362,089
def debug_sphere_out(self, p: Union[Unit, Point2, Point3], r: Union[int, float], color=None): self._debug_spheres.append( debug_pb.DebugSphere(p=self.to_debug_point(p), r=r, color=self.to_debug_color(color)) )
Draws a sphere at point p with radius r. Don't forget to add 'await self._client.send_debug'.
362,090
def plot_lc(d): costs = np.squeeze(d[]) plt.plot(costs) plt.ylabel() plt.xlabel() plt.title("Learning rate =" + str(d["learning_rate"])) plt.show()
plot learning curve Arguments: d Returned by model function. Dictionary containing information about the model.
362,091
def _to_uniform_pwm(self, values): return [self._to_single_uniform_pwm(values[i]) for i in range(len(self._pins))]
Convert raw pwm values to uniform values. :param values: The raw pwm values. :return: Converted, uniform pwm values (0.0-1.0).
362,092
def print_results(args): min_comics, filename = args with codecs.open(filename, , ) as fp: for name, url in sorted(load_result(json_file).items()): if name in exclude_comics: continue if has_gocomics_comic(name): prefix = u else: ...
Print comics.
362,093
def top_articles( self, project, access=, year=None, month=None, day=None, limit=1000): yesterday = date.today() - timedelta(days=1) year = str(year or yesterday.year) month = str(month or yesterday.month).rjust(2, ) day = str(day or yesterday.day).rjust(...
Get pageview counts for one or more articles See `<https://wikimedia.org/api/rest_v1/metrics/pageviews/?doc\\ #!/Pageviews_data/get_metrics_pageviews_top_project\\ _access_year_month_day>`_ :Parameters: project : str a wikimedia project such a...
362,094
def render_summary(self, include_title=True): title = description = frames = [] classes = [] if not self.frames: classes.append() if include_title: if self.is_syntax_error: title = text_() else: ...
Render the traceback for the interactive console.
362,095
async def disconnect(self, sid, namespace=None): namespace = namespace or if self.manager.is_connected(sid, namespace=namespace): self.logger.info(, sid, namespace) self.manager.pre_disconnect(sid, namespace=namespace) await self._send_packet(sid, packet.Pac...
Disconnect a client. :param sid: Session ID of the client. :param namespace: The Socket.IO namespace to disconnect. If this argument is omitted the default namespace is used. Note: this method is a coroutine.
362,096
def weather_at_id(self, id): assert type(id) is int, " must be an int" if id < 0: raise ValueError(" value must be greater than 0") params = {: id, : self._language} uri = http_client.HttpClient.to_url(OBSERVATION_URL, self...
Queries the OWM Weather API for the currently observed weather at the specified city ID (eg: 5128581) :param id: the location's city ID :type id: int :returns: an *Observation* instance or ``None`` if no weather data is available :raises: *ParseResponseException* whe...
362,097
def verify_visible(self, locator, msg=None): try: self.assert_visible(locator, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
Soft assert for whether and element is present and visible in the current window/frame :params locator: the locator of the element to search for :params msg: (Optional) msg explaining the difference
362,098
def recompute_tabs_titles(self): use_vte_titles = self.settings.general.get_boolean("use-vte-titles") if not use_vte_titles: return for terminal in self.get_notebook().iter_terminals(): page_num = self.get_notebook().page_num(terminal.get_paren...
Updates labels on all tabs. This is required when `self.abbreviate` changes
362,099
def fill_round_rect(setter, x, y, w, h, r, color=None, aa=False): fill_rect(setter, x + r, y, w - 2 * r, h, color, aa) _fill_circle_helper(setter, x + w - r - 1, y + r, r, 1, h - 2 * r - 1, color, aa) _fill_circle_helper(setter, x + r, y + r, r, 2, h - 2 * r - 1, color, aa)
Draw solid rectangle with top-left corner at x,y, width w, height h, and corner radius r