code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def coverage_score(gold, pred, ignore_in_gold=[], ignore_in_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 ...
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 ...
def pruneUI(dupeList, mainPos=1, mainLen=1): """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 dupeLi...
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: ...
def get_all_names(offset=None, count=None, include_expired=False, proxy=None, hostport=None): """ Get all names within the given range. Return the list of names on success Return {'error': ...} on failure """ assert proxy or hostport, 'Need proxy or hostport' if proxy is None: proxy ...
Get all names within the given range. Return the list of names on success Return {'error': ...} on failure
def _flush_ndb_deletes(self, items, options): """Flush all deletes to datastore.""" assert ndb is not None ndb.delete_multi(items, config=self._create_config(options))
Flush all deletes to datastore.
def send_message(self): """Send message over UDP. If tracking is disables, the bytes_sent will always be set to -1 Returns: (bytes_sent, time_taken) """ start = time.time() message = None if not self.initialized: message = self.construct_...
Send message over UDP. If tracking is disables, the bytes_sent will always be set to -1 Returns: (bytes_sent, time_taken)
def list_to_csv(my_list, csv_file): """ 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_cs...
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 ...
def feed(self, char, char_len): """feed a character with known length""" if char_len == 2: # we only care about 2-bytes character in our distribution analysis order = self.get_order(char) else: order = -1 if order >= 0: self._total_chars +=...
feed a character with known length
def _calculate_aes_cipher(key): """ 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" ...
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"
def copy(self, src, dst, other_system=None): """ 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. """ ...
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.
def add(self, req: Request): """ Add the specified request to this request store. """ key = req.key if key not in self: self[key] = ReqState(req) return self[key]
Add the specified request to this request store.
def get_home_dir(): """ Return user home directory """ try: # expanduser() returns a raw byte string which needs to be # decoded with the codec that the OS is using to represent # file paths. path = encoding.to_unicode_from_fs(osp.expanduser('~')) except Exce...
Return user home directory
def decode_text(s): """Decodes a PDFDocEncoding string to Unicode.""" if s.startswith(b'\xfe\xff'): return unicode(s[2:], 'utf-16be', 'ignore') else: return ''.join(PDFDocEncoding[ord(c)] for c in s)
Decodes a PDFDocEncoding string to Unicode.
def P1(self, value): """Set private ``_P1`` and reset ``_block_matcher``.""" if value < self.P2: self._P1 = value else: raise InvalidFirstDisparityChangePenaltyError("P1 must be less " "than P2.") self._rep...
Set private ``_P1`` and reset ``_block_matcher``.
def export_public_key(user_id, env=None, sp=subprocess): """Export GPG public key for specified `user_id`.""" args = gpg_command(['--export', user_id]) result = check_output(args=args, env=env, sp=sp) if not result: log.error('could not find public key %r in local GPG keyring', user_id) ...
Export GPG public key for specified `user_id`.
def InstanceOf(cls, **kwargs): """A property that is an instance of `cls`.""" return Property(types=cls, load=cls.load, **kwargs)
A property that is an instance of `cls`.
def _MultipleModulesFoundError(path, candidates): """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 Assertion...
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...
def prepare_outputs(self, job): """ Called before job is started. If output is a `FileSystemTarget`, create parent directories so the hive command won't fail """ outputs = flatten(job.output()) for o in outputs: if isinstance(o, FileSystemTarget): ...
Called before job is started. If output is a `FileSystemTarget`, create parent directories so the hive command won't fail
def POST(self, path, body, xml=True): """ 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`) """ url = self._absolute_url(path) headers ...
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`)
def get_catalog(self, catalog_id): """ Return specified course catalog. Returns: dict: catalog details if it is available for the user. """ 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.
def run(configobj=None): """ TEAL interface for the `acscteforwardmodel` function. """ acscteforwardmodel(configobj['input'], exec_path=configobj['exec_path'], time_stamps=configobj['time_stamps'], verbose=configobj['verbose'], ...
TEAL interface for the `acscteforwardmodel` function.
def _adjust_font(self): """Ensure the font name is from our list and correctly spelled. """ 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 = ...
Ensure the font name is from our list and correctly spelled.
def _send_cmd(self, cmd): """Write command to remote process """ self._process.stdin.write("{}\n".format(cmd).encode("utf-8")) self._process.stdin.flush()
Write command to remote process
def software_fibonacci(n): """ a normal old python function to return the Nth fibonacci number. """ 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.
def _do_crop(self, lines, width, height, x_crop, y_crop): '''Crops a list of strings to the specified width/height ''' lines = crop_or_expand( lines, height, default=[self.fillchar * width], scheme=self._schemes[y_crop]) for i, line in enumerate(lines): ...
Crops a list of strings to the specified width/height
def createPropagate( request: Union[Request, dict], client_name) -> Propagate: """ Create a new PROPAGATE for the given REQUEST. :param request: the client REQUEST :return: a new PROPAGATE msg """ if not isinstance(request, (Request, dict)): logge...
Create a new PROPAGATE for the given REQUEST. :param request: the client REQUEST :return: a new PROPAGATE msg
def is_flash_encryption_key_valid(self): """ Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1 this bit is at position 16 in EFUSE_BLK0_RDATA0_REG """ word0 = self.read_efuse(0) rd_disable = (word0 >> 16) & 0x1 # reading of BLOCK1 is NOT ALLOWED so we assume valid key is progr...
Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1 this bit is at position 16 in EFUSE_BLK0_RDATA0_REG
def precompute_raveled_slices(coeff_shapes, axes=None): """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 --...
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...
def guess_filename(self, basedir, kind=None): """ 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: basedi...
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...
def path(self, tax_ids): """Get the node at the end of the path described by 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 StopIter...
Get the node at the end of the path described by tax_ids.
def send_frame(self, frame): """ 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 ...
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 ...
def reset_new_request(self): """Remove the non-sense args from the self.ignore, return self.new_request""" raw_url = self.new_request['url'] 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...
Remove the non-sense args from the self.ignore, return self.new_request
def execute(task_function, *args, **kwargs): """Run a task asynchronously """ if get_setting('TEST_DISABLE_ASYNC_DELAY'): # Delay disabled, run synchronously logger.debug('Running function "%s" synchronously because '\ 'TEST_DISABLE_ASYNC_DELAY is True' ...
Run a task asynchronously
def workspaces(self): """ Retrieve a list of currently active workspaces. :rtype: List of :class:`Con`. """ workspaces = [] def collect_workspaces(con): if con.type == "workspace" and not con.name.startswith('__'): workspaces.append(con) ...
Retrieve a list of currently active workspaces. :rtype: List of :class:`Con`.
def iter_starred(self, login=None, sort=None, direction=None, number=-1, etag=None): """Iterate over repositories starred by ``login`` or the authenticated user. .. versionchanged:: 0.5 Added sort and direction parameters (optional) as per the change in ...
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...
def PATTERN(self): u""" Uses the mapping of names to features to return a PATTERN suitable for using the lib2to3 patcomp. """ 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.
def run_script(self, requires, script_name): """Locate distribution for `requires` and run `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name self.require(requires)[0].run_script(script_name, ns)
Locate distribution for `requires` and run `script_name` script
def fitcircle(n, x, y): # n points, x points, y points """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.""" # adding in normalize vectors step #x = numpy.array(x) / max(x) #y...
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.
def pre_filter(self, conditions, user): ''' Returns all of the items from conditions which are enabled by a user being member of a Django Auth Group. ''' 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.
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....
Function that transform the `datasets` in a `DataBunch` for classification. Passes `**dl_kwargs` on to `DataLoader()`
def measure_residence_time(self, cutoff = 3.5): """ 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 r...
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...
def parseStr(self, st) : """Parses a string""" self.data = st.replace('\r', '\n') self.data = self.data.replace('\n\n', '\n') self.data = self.data.split('\n')
Parses a string
def get_display_types(): """ Get ordered dict containing available display types from available luma sub-projects. :rtype: collections.OrderedDict """ display_types = OrderedDict() for namespace in get_supported_libraries(): display_types[namespace] = get_choices('luma.{0}.device'.f...
Get ordered dict containing available display types from available luma sub-projects. :rtype: collections.OrderedDict
def pole2plunge_bearing(strike, dip): """ 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 az...
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 "...
def upload_image(self, media_file): """ 上传群发消息内的图片 详情请参考 http://mp.weixin.qq.com/wiki/15/5380a4e6f02f2ffdc7981a8ed7a40753.html :param media_file: 要上传的文件,一个 File-object :return: 上传成功时返回图片 URL """ res = self._post( url='media/uploadimg', ...
上传群发消息内的图片 详情请参考 http://mp.weixin.qq.com/wiki/15/5380a4e6f02f2ffdc7981a8ed7a40753.html :param media_file: 要上传的文件,一个 File-object :return: 上传成功时返回图片 URL
def clear_buffer(self, 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. ...
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.
def rename_categories(self, key: str, categories: Sequence[Any]): """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`` - ...
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 ...
def log_context(trace_level, stream): ''' To be used to temporarily change the logging settings. ''' original_trace_level = DebugInfoHolder.DEBUG_TRACE_LEVEL original_stream = DebugInfoHolder.DEBUG_STREAM DebugInfoHolder.DEBUG_TRACE_LEVEL = trace_level DebugInfoHolder.DEBUG_STREAM = stream ...
To be used to temporarily change the logging settings.
def regexp(__string: str, __pattern: str, __repl: Union[Callable, str], *, count: int = 0, flags: int = 0) -> str: """Jinja filter for regexp replacements. See :func:`re.sub` for documentation. Returns: Text with substitutions applied """ return re.sub(__pattern, __repl, __strin...
Jinja filter for regexp replacements. See :func:`re.sub` for documentation. Returns: Text with substitutions applied
def read_data( self, step, filename = None ): """Point data only!""" filename = get_default( filename, self.filename ) out = {} fd = open( self.filename, 'r' ) while 1: line = skip_read_line(fd, no_eof=True).split() if line[0] == 'POINT_DATA': ...
Point data only!
def get_alignment_df_from_file(alignment_file, a_seq_id=None, b_seq_id=None): """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...
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...
def _DecodeURL(self, url): """Decodes the URL, replaces %XX to their corresponding characters. Args: url (str): encoded URL. Returns: str: decoded URL. """ if not url: return '' decoded_url = urlparse.unquote(url) if isinstance(decoded_url, py2to3.BYTES_TYPE): try:...
Decodes the URL, replaces %XX to their corresponding characters. Args: url (str): encoded URL. Returns: str: decoded URL.
def make_executable(script_path): """Make `script_path` executable. :param script_path: The file to change """ 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
def get_name(self): """Get the host name. Try several attributes before returning UNNAMED* :return: The name of the host :rtype: str """ if not self.is_tpl(): try: return self.host_name except AttributeError: # outch, no hostname ...
Get the host name. Try several attributes before returning UNNAMED* :return: The name of the host :rtype: str
def htseq_stats_table(self): """ Take the parsed stats from the HTSeq Count report and add them to the basic stats table at the top of the report """ headers = OrderedDict() headers['percent_assigned'] = { 'title': '% Assigned', 'description': '% Assigned reads',...
Take the parsed stats from the HTSeq Count report and add them to the basic stats table at the top of the report
def get_single_external_tool_courses(self, course_id, external_tool_id): """ Get a single external tool. Returns the specified external tool. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["cou...
Get a single external tool. Returns the specified external tool.
def emit(self, object, *args): """Emit the signal.""" for cb in self.map.get(object, []): cb(*args)
Emit the signal.
def rlm(data, xseq, **params): """ Fit RLM """ X = sm.add_constant(data['x']) Xseq = sm.add_constant(xseq) init_kwargs, fit_kwargs = separate_method_kwargs( params['method_args'], sm.RLM, sm.RLM.fit) model = sm.RLM(data['y'], X, **init_kwargs) results = model.fit(**fit_kwargs) ...
Fit RLM
def parse(self, rrstr): # type: (bytes) -> None ''' Parse a Rock Ridge Alternate Name record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing. ''' if self._initialized: raise pycdlibexcepti...
Parse a Rock Ridge Alternate Name record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing.
def cudaDriverGetVersion(): """ 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. """ version = ctypes.c_int() status = _libcudart.cu...
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.
def set(self, value): """ 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 """ if not...
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
def Ry_matrix(theta): """Rotation matrix around the Y axis""" 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
def compute_bootci(x, y=None, func='pearson', method='cper', paired=False, confidence=.95, n_boot=2000, decimals=2, seed=None, return_dist=False): """Bootstrapped confidence intervals of univariate and bivariate functions. Parameters ---------- x : 1D-array or list...
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...
def setCurrentMode( self, mode ): """ Sets the current mode that this calendar will be displayed in. :param mode | <XCalendarWidget.Mode> """ self.scene().setCurrentMode(mode) self.scene().setSceneRect(0, 0, self.width() - 5, self.height() - 5) if ...
Sets the current mode that this calendar will be displayed in. :param mode | <XCalendarWidget.Mode>
def split_last_dimension(x, 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] """ x_shape = common_layers.shape_list(x) m = x_shape[-1] ...
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]
def list_lights(self, selector='all'): """Given a selector (defaults to all), return a list of lights. Without a selector provided, return list of all lights. """ return self.client.perform_request( method='get', endpoint='lights/{}', endpoint_args=[selector], pa...
Given a selector (defaults to all), return a list of lights. Without a selector provided, return list of all lights.
def initialize_converter(): """ :rtype: None """ 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 impo...
:rtype: None
def statusBar(step, total, bar_len=20, onlyReturn=False): """ 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 ...
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 ...
def select_bucket_region(custom_bucket, hook_region, stacker_bucket_region, 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...
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):...
def assemble_content_aad(message_id, aad_content_string, seq_num, length): """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_sd...
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...
def _get_summary_struct(self): """ 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 lis...
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...
def enable_busy_cursor(self): """Set the hourglass enabled.""" QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor) )
Set the hourglass enabled.
def _required_byte_num(mode, fmt, n_samp): """ 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 forma...
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...
def write_county_estimate(self, table, variable, code, datum): """ Creates new estimate from a census series. Data has following signature from API: { 'B00001_001E': '5373', 'NAME': 'Anderson County, Texas', 'county': '001', 'state': '4...
Creates new estimate from a census series. Data has following signature from API: { 'B00001_001E': '5373', 'NAME': 'Anderson County, Texas', 'county': '001', 'state': '48' }
def write_out_sitemap(self, opath): """ Banana banana """ if opath not in self.written_out_sitemaps: Extension.formatted_sitemap = self.formatter.format_navigation( self.app.project) if Extension.formatted_sitemap: escaped_sitemap =...
Banana banana
def log(*args, **attrs): """Override log file location.""" attrs.setdefault("metavar", "PATH") attrs.setdefault("show_default", False) return option(log, *args, **attrs)
Override log file location.
def _on_report(_loop, adapter, conn_id, report): """Callback when a report is received.""" conn_string = None if conn_id is not None: conn_string = adapter._get_property(conn_id, 'connection_string') if isinstance(report, BroadcastReport): adapter.notify_event_nowait(conn_string, 'broa...
Callback when a report is received.
def sampling_shap_1000(model, data): """ IME 1000 color = red_blue_circle(0.5) linestyle = dashed """ return lambda X: SamplingExplainer(model.predict, data).shap_values(X, nsamples=1000)
IME 1000 color = red_blue_circle(0.5) linestyle = dashed
def render_filter(self, next_filter): """ Produce formatted output from the raw data stream. """ 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.
def ExpireObject(self, key): """Expire a specific object from cache.""" 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.
def update_trackers(self): """ Updates the denormalized trackers associated with the topic instance. """ self.posts_count = self.posts.filter(approved=True).count() first_post = self.posts.all().order_by('created').first() last_post = self.posts.filter(approved=True).order_by('-created')...
Updates the denormalized trackers associated with the topic instance.
def _get_zipped_rows(self, soup): """ Returns all 'tr' tag rows as a list of tuples. Each tuple is for a single story. """ # the table with all submissions table = soup.findChildren('table')[2] # get all rows but last 2 rows = table.findChildren(['...
Returns all 'tr' tag rows as a list of tuples. Each tuple is for a single story.
def _maybe_check_valid_shape(shape, validate_args): """Check that a shape Tensor is int-type and otherwise sane.""" if not dtype_util.is_integer(shape.dtype): raise TypeError('{} dtype ({}) should be `int`-like.'.format( shape, dtype_util.name(shape.dtype))) assertions = [] message = '`{}` rank sh...
Check that a shape Tensor is int-type and otherwise sane.
def append(self, item): """ append item and print it to stdout """ print(item) super(MyList, self).append(item)
append item and print it to stdout
def make_request_log_message(**args): ''' 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 requ...
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 ...
def _read_name_file(self, filename): """Read a name file from the data directory :param filename: Name of the file to read. :return: A list of name entries. """ file_path = os.path.join(self._DATA_DIR, filename) with open(file_path) as f: names = json.load(f)...
Read a name file from the data directory :param filename: Name of the file to read. :return: A list of name entries.
def get_display_name(self): """Gets a display name for this service implementation. return: (osid.locale.DisplayText) - a display name *compliance: mandatory -- This method must be implemented.* """ return DisplayText( text=profile.DISPLAYNAME, language_...
Gets a display name for this service implementation. return: (osid.locale.DisplayText) - a display name *compliance: mandatory -- This method must be implemented.*
def gettextvalue(self, window_name, object_name, startPosition=0, endPosition=0): """ 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...
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...
def compile(self, ops): """ 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. """ def _compile(): co...
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.
def buildingname(ddtt): """return building name""" idf = ddtt.theidf building = idf.idfobjects['building'.upper()][0] return building.Name
return building name
def debug_sphere_out(self, p: Union[Unit, Point2, Point3], r: Union[int, float], color=None): """ Draws a sphere at point p with radius r. Don't forget to add 'await self._client.send_debug'. """ self._debug_spheres.append( debug_pb.DebugSphere(p=self.to_debug_point(p), r=r, color=self.to_de...
Draws a sphere at point p with radius r. Don't forget to add 'await self._client.send_debug'.
def plot_lc(d): """plot learning curve Arguments: d Returned by model function. Dictionary containing information about the model. """ costs = np.squeeze(d['costs']) plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(d[...
plot learning curve Arguments: d Returned by model function. Dictionary containing information about the model.
def _to_uniform_pwm(self, values): """ Convert raw pwm values to uniform values. :param values: The raw pwm values. :return: Converted, uniform pwm values (0.0-1.0). """ 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).
def print_results(args): """Print comics.""" min_comics, filename = args with codecs.open(filename, 'a', 'utf-8') as fp: for name, url in sorted(load_result(json_file).items()): if name in exclude_comics: continue if has_gocomics_comic(name): p...
Print comics.
def top_articles( self, project, access='all-access', year=None, month=None, day=None, limit=1000): """ Get pageview counts for one or more articles See `<https://wikimedia.org/api/rest_v1/metrics/pageviews/?doc\\ #!/Pageviews_data/get_metrics_pageviews_to...
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...
def render_summary(self, include_title=True): """Render the traceback for the interactive console.""" title = '' description = '' frames = [] classes = ['traceback'] if not self.frames: classes.append('noframe-traceback') if include_title: ...
Render the traceback for the interactive console.
async def disconnect(self, sid, namespace=None): """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....
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.
def weather_at_id(self, id): """ 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 availa...
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...
def verify_visible(self, locator, msg=None): """ 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 """ try: se...
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
def recompute_tabs_titles(self): """Updates labels on all tabs. This is required when `self.abbreviate` changes """ use_vte_titles = self.settings.general.get_boolean("use-vte-titles") if not use_vte_titles: return # TODO NOTEBOOK this code only works if ther...
Updates labels on all tabs. This is required when `self.abbreviate` changes
def fill_round_rect(setter, x, y, w, h, r, color=None, aa=False): """Draw solid rectangle with top-left corner at x,y, width w, height h, and corner radius r""" 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 ...
Draw solid rectangle with top-left corner at x,y, width w, height h, and corner radius r