_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q19100
SDOSPlotter.dos_plot_data
train
def dos_plot_data(self, yscale=1, xmin=-6., xmax=6., colours=None, plot_total=True, legend_cutoff=3, subplot=False, zero_to_efermi=True, cache=None): """Get the plotting data. Args: yscale (:obj:`float`, optional): Scaling factor for the y-axis. ...
python
{ "resource": "" }
q19101
get_projections_by_branches
train
def get_projections_by_branches(bs, selection, normalise=None): """Returns orbital projections for each branch in a band structure. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): The band structure. selection (list): A list of :obj:`tuple` or :...
python
{ "resource": "" }
q19102
get_projections
train
def get_projections(bs, selection, normalise=None): """Returns orbital projections from a band structure. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): The band structure. selection (list): A list of :obj:`tuple` or :obj:`string` i...
python
{ "resource": "" }
q19103
SBSPlotter._makeplot
train
def _makeplot(self, ax, fig, data, zero_to_efermi=True, vbm_cbm_marker=False, ymin=-6., ymax=6., height=None, width=None, dos_plotter=None, dos_options=None, dos_label=None, aspect=None): """Tidy the band structure & add the density of stat...
python
{ "resource": "" }
q19104
SBSPlotter._makedos
train
def _makedos(self, ax, dos_plotter, dos_options, dos_label=None): """This is basically the same as the SDOSPlotter get_plot function.""" # don't use first 4 colours; these are the band structure line colours cycle = cycler( 'color', rcParams['axes.prop_cycle'].by_key()['color'][4:])...
python
{ "resource": "" }
q19105
Kpath.correct_structure
train
def correct_structure(self, atol=1e-8): """Determine if the structure matches the standard primitive structure. The standard primitive will be different between seekpath and pymatgen high-symmetry paths, but this is handled by the specific subclasses. Args: atol (:obj:`floa...
python
{ "resource": "" }
q19106
Kpath.get_kpoints
train
def get_kpoints(self, line_density=20, cart_coords=False, phonopy=False): r"""Return a list of k-points and labels along the high-symmetry path. The format of the returned data will be different if phonopy is ``True`` or ``False``. This is because phonopy requires the labels and kpoints...
python
{ "resource": "" }
q19107
Kpath.get_lattice_type
train
def get_lattice_type(number): """Return the lattice crystal system. Hexagonal cells are differentiated into rhombohedral and hexagonal lattices. Args: number (int): The international space group number. Returns: str: The lattice crystal system. ...
python
{ "resource": "" }
q19108
get_fitting_data
train
def get_fitting_data(bs, spin, band_id, kpoint_id, num_sample_points=3): """Extract fitting data for band extrema based on spin, kpoint and band. Searches forward and backward from the extrema point, but will only sample there data if there are enough points in that direction. Args: bs (:obj:`...
python
{ "resource": "" }
q19109
fit_effective_mass
train
def fit_effective_mass(distances, energies, parabolic=True): """Fit the effective masses using either a parabolic or nonparabolic fit. Args: distances (:obj:`numpy.ndarray`): The x-distances between k-points in reciprocal Angstroms, normalised to the band extrema. energies (:obj:`nu...
python
{ "resource": "" }
q19110
get_path_data
train
def get_path_data(structure, mode='bradcrack', symprec=0.01, spg=None, line_density=60, cart_coords=False, kpt_list=None, labels=None, phonopy=False): r"""Get the k-point path, coordinates and symmetry labels for a structure. If a manual :obj:`list` of kpoints is supplied us...
python
{ "resource": "" }
q19111
write_kpoint_files
train
def write_kpoint_files(filename, kpoints, labels, make_folders=False, ibzkpt=None, kpts_per_split=None, directory=None, cart_coords=False): r"""Write the k-points data to VASP KPOINTS files. Folders are named as 'split-01', 'split-02', etc ... KPOINTS files are...
python
{ "resource": "" }
q19112
styled_plot
train
def styled_plot(*style_sheets): """Return a decorator that will apply matplotlib style sheets to a plot. ``style_sheets`` is a base set of styles, which will be ignored if ``no_base_style`` is set in the decorated function arguments. The style will further be overwritten by any styles in the ``style``...
python
{ "resource": "" }
q19113
power_tick
train
def power_tick(val, pos, times_sign=r'\times'): """Custom power ticker function. """ if val == 0: return r'$\mathregular{0}$' elif val < 0: exponent = int(np.log10(-val)) else: exponent = int(np.log10(val)) coeff = val / 10**exponent return r'$\mathregular{{{:.1f} {} 10^...
python
{ "resource": "" }
q19114
rgbline
train
def rgbline(x, y, red, green, blue, alpha=1, linestyles="solid", linewidth=2.5): """Get a RGB coloured line for plotting. Args: x (list): x-axis data. y (list): y-axis data (can be multidimensional array). red (list): Red data (must have same shape as ``y``). green (...
python
{ "resource": "" }
q19115
broaden_eps
train
def broaden_eps(dielectric, sigma): """Apply gaussian broadening to the dielectric response. Args: dielectric_data (tuple): The high-frequency dielectric data, following the same format as :attr:`pymatgen.io.vasp.outputs.Vasprun.dielectric`. This is a :obj:`tuple` co...
python
{ "resource": "" }
q19116
write_files
train
def write_files(abs_data, basename='absorption', prefix=None, directory=None): """Write the absorption or loss spectra to a file. Note that this function expects to receive an iterable series of spectra. Args: abs_data (tuple): Series (either :obj:`list` or :obj:`tuple`) of optical abs...
python
{ "resource": "" }
q19117
load_phonopy
train
def load_phonopy(filename, structure, dim, symprec=0.01, primitive_matrix=None, factor=VaspToTHz, symmetrise=True, born=None, write_fc=False): """Load phonopy output and return an ``phonopy.Phonopy`` object. Args: filename (str): Path to phonopy output. Can be any of ``FORCE_SETS``, ...
python
{ "resource": "" }
q19118
load_dos
train
def load_dos(vasprun, elements=None, lm_orbitals=None, atoms=None, gaussian=None, total_only=False, log=False, adjust_fermi=True): """Load a vasprun and extract the total and projected density of states. Args: vasprun (str): Path to a vasprun.xml or vasprun.xml.gz file or ...
python
{ "resource": "" }
q19119
get_pdos
train
def get_pdos(dos, lm_orbitals=None, atoms=None, elements=None): """Extract the projected density of states from a CompleteDos object. Args: dos (:obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The density of states. elements (:obj:`dict`, optional): The elements and orbitals...
python
{ "resource": "" }
q19120
get_element_pdos
train
def get_element_pdos(dos, element, sites, lm_orbitals=None, orbitals=None): """Get the projected density of states for an element. Args: dos (:obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The density of states. element (str): Element symbol. E.g. 'Zn'. sites (tuple...
python
{ "resource": "" }
q19121
write_files
train
def write_files(dos, pdos, prefix=None, directory=None, zero_to_efermi=True): """Write the density of states data to disk. Args: dos (:obj:`~pymatgen.electronic_structure.dos.Dos` or \ :obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The total density of states. ...
python
{ "resource": "" }
q19122
sort_orbitals
train
def sort_orbitals(element_pdos): """Sort the orbitals of an element's projected density of states. Sorts the orbitals based on a standard format. E.g. s < p < d. Will also sort lm decomposed orbitals. This is useful for plotting/saving. Args: element_pdos (dict): An element's pdos. Should be f...
python
{ "resource": "" }
q19123
bandstats
train
def bandstats(filenames=None, num_sample_points=3, temperature=None, degeneracy_tol=1e-4, parabolic=True): """Calculate the effective masses of the bands of a semiconductor. Args: filenames (:obj:`str` or :obj:`list`, optional): Path to vasprun.xml or vasprun.xml.gz file. If n...
python
{ "resource": "" }
q19124
_log_band_gap_information
train
def _log_band_gap_information(bs): """Log data about the direct and indirect band gaps. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): """ bg_data = bs.get_band_gap() if not bg_data['direct']: logging.info('Indirect band gap: {:.3f} eV'.format(...
python
{ "resource": "" }
q19125
_log_band_edge_information
train
def _log_band_edge_information(bs, edge_data): """Log data about the valence band maximum or conduction band minimum. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): The band structure. edge_data (dict): The :obj:`dict` from ``bs.get_vbm()`` or ...
python
{ "resource": "" }
q19126
_log_effective_mass_data
train
def _log_effective_mass_data(data, is_spin_polarized, mass_type='m_e'): """Log data about the effective masses and their directions. Args: data (dict): The effective mass data. Formatted as a :obj:`dict` with the keys: 'effective_mass' (:obj:`float`) The effecti...
python
{ "resource": "" }
q19127
SPhononBSPlotter._makeplot
train
def _makeplot(self, ax, fig, data, ymin=None, ymax=None, height=6, width=6, dos=None, color=None): """Utility method to tidy phonon band structure diagrams. """ # Define colours if color is None: color = 'C0' # Default to first colour in matplotlib series ...
python
{ "resource": "" }
q19128
find_vasprun_files
train
def find_vasprun_files(): """Search for vasprun files from the current directory. The precedence order for file locations is: 1. First search for folders named: 'split-0*' 2. Else, look in the current directory. The split folder names should always be zero based, therefore easily sortable...
python
{ "resource": "" }
q19129
save_data_files
train
def save_data_files(vr, bs, prefix=None, directory=None): """Write the band structure data files to disk. Args: vs (`Vasprun`): Pymatgen `Vasprun` object. bs (`BandStructureSymmLine`): Calculated band structure. prefix (`str`, optional): Prefix for data file. directory (`str`, o...
python
{ "resource": "" }
q19130
save_data_files
train
def save_data_files(bs, prefix=None, directory=None): """Write the phonon band structure data files to disk. Args: bs (:obj:`~pymatgen.phonon.bandstructure.PhononBandStructureSymmLine`): The phonon band structure. prefix (:obj:`str`, optional): Prefix for data file. director...
python
{ "resource": "" }
q19131
kgen
train
def kgen(filename='POSCAR', directory=None, make_folders=False, symprec=0.01, kpts_per_split=None, ibzkpt=None, spg=None, density=60, mode='bradcrack', cart_coords=False, kpt_list=None, labels=None): """Generate KPOINTS files for VASP band structure calculations. This script provides a wrappe...
python
{ "resource": "" }
q19132
dosplot
train
def dosplot(filename=None, prefix=None, directory=None, elements=None, lm_orbitals=None, atoms=None, subplot=False, shift=True, total_only=False, plot_total=True, legend_on=True, legend_frame_on=False, legend_cutoff=3., gaussian=None, height=6., width=8., xmin=-6., xmax=6...
python
{ "resource": "" }
q19133
_atoms
train
def _atoms(atoms_string): """Parse the atom string. Args: atoms_string (str): The atoms to plot, in the form ``"C.1.2.3,"``. Returns: dict: The atomic indices over which to sum the DOS. Formatted as:: {Element: [atom_indices]}. Indices are zero indexed for each atomic...
python
{ "resource": "" }
q19134
f
train
def f(s): """ Basic support for 3.6's f-strings, in 3.5! Formats "s" using appropriate globals and locals dictionaries. This f-string: f"hello a is {a}" simply becomes f("hello a is {a}") In other words, just throw parentheses around the string, and you're done! Implem...
python
{ "resource": "" }
q19135
which
train
def which(cmd, path="PATH"): """Find cmd on PATH.""" if os.path.exists(cmd): return cmd if cmd[0] == '/': return None for segment in os.getenv(path).split(":"): program = os.path.normpath(os.path.join(segment, cmd)) if os.path.exists(program): return program ...
python
{ "resource": "" }
q19136
help
train
def help(subcommand=None): """ Print help for subcommands. Prints the help text for the specified subcommand. If subcommand is not specified, prints one-line summaries for every command. """ if not subcommand: print("blurb version", __version__) print() print("Management tool for C...
python
{ "resource": "" }
q19137
release
train
def release(version): """ Move all new blurbs to a single blurb file for the release. This is used by the release manager when cutting a new release. """ if version == ".": # harvest version number from dirname of repo # I remind you, we're in the Misc subdir right now version = os....
python
{ "resource": "" }
q19138
Blurbs.load
train
def load(self, filename, *, metadata=None): """ Read a blurb file. Broadly equivalent to blurb.parse(open(filename).read()). """ with open(filename, "rt", encoding="utf-8") as file: text = file.read() self.parse(text, metadata=metadata, filename=filename)
python
{ "resource": "" }
q19139
Blurbs._parse_next_filename
train
def _parse_next_filename(filename): """ Parses a "next" filename into its equivalent blurb metadata. Returns a dict. """ components = filename.split(os.sep) section, filename = components[-2:] section = unsanitize_section(section) assert section in sections, f("Unknown se...
python
{ "resource": "" }
q19140
Blurbs.save_split_next
train
def save_split_next(self): """ Save out blurbs created from "blurb split". They don't have dates, so we have to get creative. """ filenames = [] # the "date" MUST have a leading zero. # this ensures these files sort after all # newly created blurbs. ...
python
{ "resource": "" }
q19141
cherry_pick_cli
train
def cherry_pick_cli( ctx, dry_run, pr_remote, abort, status, push, config_path, commit_sha1, branches ): """cherry-pick COMMIT_SHA1 into target BRANCHES.""" click.echo("\U0001F40D \U0001F352 \u26CF") chosen_config_path, config = load_config(config_path) try: cherry_picker = CherryPicker( ...
python
{ "resource": "" }
q19142
get_base_branch
train
def get_base_branch(cherry_pick_branch): """ return '2.7' from 'backport-sha-2.7' raises ValueError if the specified branch name is not of a form that cherry_picker would have created """ prefix, sha, base_branch = cherry_pick_branch.split("-", 2) if prefix != "backport": raise...
python
{ "resource": "" }
q19143
validate_sha
train
def validate_sha(sha): """ Validate that a hexdigest sha is a valid commit in the repo raises ValueError if the sha does not reference a commit within the repo """ cmd = ["git", "log", "-r", sha] try: subprocess.check_output(cmd, stderr=subprocess.STDOUT) except subprocess.Subproces...
python
{ "resource": "" }
q19144
version_from_branch
train
def version_from_branch(branch): """ return version information from a git branch name """ try: return tuple( map( int, re.match(r"^.*(?P<version>\d+(\.\d+)+).*$", branch) .groupdict()["version"] .split("."), ...
python
{ "resource": "" }
q19145
get_current_branch
train
def get_current_branch(): """ Return the current branch """ cmd = ["git", "rev-parse", "--abbrev-ref", "HEAD"] output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) return output.strip().decode("utf-8")
python
{ "resource": "" }
q19146
normalize_commit_message
train
def normalize_commit_message(commit_message): """ Return a tuple of title and body from the commit message """ split_commit_message = commit_message.split("\n") title = split_commit_message[0] body = "\n".join(split_commit_message[1:]) return title, body.lstrip("\n")
python
{ "resource": "" }
q19147
is_git_repo
train
def is_git_repo(): """Check whether the current folder is a Git repo.""" cmd = "git", "rev-parse", "--git-dir" try: subprocess.run(cmd, stdout=subprocess.DEVNULL, check=True) return True except subprocess.CalledProcessError: return False
python
{ "resource": "" }
q19148
find_config
train
def find_config(revision): """Locate and return the default config for current revison.""" if not is_git_repo(): return None cfg_path = f"{revision}:.cherry_picker.toml" cmd = "git", "cat-file", "-t", cfg_path try: output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) ...
python
{ "resource": "" }
q19149
load_config
train
def load_config(path=None): """Choose and return the config path and it's contents as dict.""" # NOTE: Initially I wanted to inherit Path to encapsulate Git access # there but there's no easy way to subclass pathlib.Path :( head_sha = get_sha1_from("HEAD") revision = head_sha saved_config_path =...
python
{ "resource": "" }
q19150
save_cfg_vals_to_git_cfg
train
def save_cfg_vals_to_git_cfg(**cfg_map): """Save a set of options into Git config.""" for cfg_key_suffix, cfg_val in cfg_map.items(): cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}' cmd = "git", "config", "--local", cfg_key, cfg_val subprocess.check_call(cmd, stderr=subproc...
python
{ "resource": "" }
q19151
wipe_cfg_vals_from_git_cfg
train
def wipe_cfg_vals_from_git_cfg(*cfg_opts): """Remove a set of options from Git config.""" for cfg_key_suffix in cfg_opts: cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}' cmd = "git", "config", "--local", "--unset-all", cfg_key subprocess.check_call(cmd, stderr=subprocess.ST...
python
{ "resource": "" }
q19152
load_val_from_git_cfg
train
def load_val_from_git_cfg(cfg_key_suffix): """Retrieve one option from Git config.""" cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}' cmd = "git", "config", "--local", "--get", cfg_key try: return ( subprocess.check_output(cmd, stderr=subprocess.DEVNULL) .st...
python
{ "resource": "" }
q19153
from_git_rev_read
train
def from_git_rev_read(path): """Retrieve given file path contents of certain Git revision.""" if ":" not in path: raise ValueError("Path identifier must start with a revision hash.") cmd = "git", "show", "-t", path try: return subprocess.check_output(cmd).rstrip().decode("utf-8") ex...
python
{ "resource": "" }
q19154
CherryPicker.set_paused_state
train
def set_paused_state(self): """Save paused progress state into Git config.""" if self.chosen_config_path is not None: save_cfg_vals_to_git_cfg(config_path=self.chosen_config_path) set_state(WORKFLOW_STATES.BACKPORT_PAUSED)
python
{ "resource": "" }
q19155
CherryPicker.upstream
train
def upstream(self): """Get the remote name to use for upstream branches Uses "upstream" if it exists, "origin" otherwise """ cmd = ["git", "remote", "get-url", "upstream"] try: subprocess.check_output(cmd, stderr=subprocess.DEVNULL) except subprocess.CalledPro...
python
{ "resource": "" }
q19156
CherryPicker.checkout_default_branch
train
def checkout_default_branch(self): """ git checkout default branch """ set_state(WORKFLOW_STATES.CHECKING_OUT_DEFAULT_BRANCH) cmd = "git", "checkout", self.config["default_branch"] self.run_cmd(cmd) set_state(WORKFLOW_STATES.CHECKED_OUT_DEFAULT_BRANCH)
python
{ "resource": "" }
q19157
CherryPicker.create_gh_pr
train
def create_gh_pr(self, base_branch, head_branch, *, commit_message, gh_auth): """ Create PR in GitHub """ request_headers = sansio.create_headers(self.username, oauth_token=gh_auth) title, body = normalize_commit_message(commit_message) if not self.prefix_commit: ...
python
{ "resource": "" }
q19158
CherryPicker.open_pr
train
def open_pr(self, url): """ open url in the web browser """ if self.dry_run: click.echo(f" dry-run: Create new PR: {url}") else: click.echo("Backport PR URL:") click.echo(url) webbrowser.open_new_tab(url)
python
{ "resource": "" }
q19159
CherryPicker.cleanup_branch
train
def cleanup_branch(self, branch): """Remove the temporary backport branch. Switch to the default branch before that. """ set_state(WORKFLOW_STATES.REMOVING_BACKPORT_BRANCH) self.checkout_default_branch() try: self.delete_branch(branch) except subproce...
python
{ "resource": "" }
q19160
CherryPicker.get_state_and_verify
train
def get_state_and_verify(self): """Return the run progress state stored in the Git config. Raises ValueError if the retrieved state is not of a form that cherry_picker would have stored in the config. """ try: state = get_state() except KeyE...
python
{ "resource": "" }
q19161
openDatFile
train
def openDatFile(datpath): ''' Open a file-like object using a pkg relative path. Example: fd = openDatFile('foopkg.barpkg/wootwoot.bin') ''' pkgname, filename = datpath.split('/', 1) pkgmod = s_dyndeps.getDynMod(pkgname) # are we a regular file? pkgfile = os.path.abspath(pkgm...
python
{ "resource": "" }
q19162
scrape
train
def scrape(text, ptype=None): ''' Scrape types from a blob of text and return node tuples. Args: text (str): Text to scrape. ptype (str): Optional ptype to scrape. If present, only scrape rules which match the provided type. Returns: (str, str): Yield tuples of type, valu strin...
python
{ "resource": "" }
q19163
en
train
def en(item): ''' Use msgpack to serialize a compatible python object. Args: item (obj): The object to serialize Notes: String objects are encoded using utf8 encoding. In order to handle potentially malformed input, ``unicode_errors='surrogatepass'`` is set to allow en...
python
{ "resource": "" }
q19164
un
train
def un(byts): ''' Use msgpack to de-serialize a python object. Args: byts (bytes): The bytes to de-serialize Notes: String objects are decoded using utf8 encoding. In order to handle potentially malformed input, ``unicode_errors='surrogatepass'`` is set to allow decodi...
python
{ "resource": "" }
q19165
iterfd
train
def iterfd(fd): ''' Generator which unpacks a file object of msgpacked content. Args: fd: File object to consume data from. Notes: String objects are decoded using utf8 encoding. In order to handle potentially malformed input, ``unicode_errors='surrogatepass'`` is set ...
python
{ "resource": "" }
q19166
iterfile
train
def iterfile(path, since=-1): ''' Generator which yields msgpack objects from a file path. Args: path: File path to open and consume data from. Notes: String objects are decoded using utf8 encoding. In order to handle potentially malformed input, ``unicode_errors='surrogatepas...
python
{ "resource": "" }
q19167
dumpfile
train
def dumpfile(item, path): ''' Dump an object to a file by path. Args: item (object): The object to serialize. path (str): The file path to save. Returns: None ''' with io.open(path, 'wb') as fd: fd.write(en(item))
python
{ "resource": "" }
q19168
Unpk.feed
train
def feed(self, byts): ''' Feed bytes to the unpacker and return completed objects. Args: byts (bytes): Bytes to unpack. Notes: It is intended that this function is called multiple times with bytes from some sort of a stream, as it will unpack and ret...
python
{ "resource": "" }
q19169
SynModule._onCoreModuleLoad
train
def _onCoreModuleLoad(self, event): ''' Clear the cached model rows and rebuild them only if they have been loaded already. ''' if not self._modelRuntsByBuid: return # Discard previously cached data. It will be computed upon the next # lift that needs it. ...
python
{ "resource": "" }
q19170
Log.encodeMsg
train
def encodeMsg(self, mesg): '''Get byts for a message''' fmt = self.locs.get('log:fmt') if fmt == 'jsonl': s = json.dumps(mesg, sort_keys=True) + '\n' buf = s.encode() return buf elif fmt == 'mpk': buf = s_msgpack.en(mesg) retu...
python
{ "resource": "" }
q19171
imeicsum
train
def imeicsum(text): ''' Calculate the imei check byte. ''' digs = [] for i in range(14): v = int(text[i]) if i % 2: v *= 2 [digs.append(int(x)) for x in str(v)] chek = 0 valu = sum(digs) remd = valu % 10 if remd != 0: chek = 10 - remd ...
python
{ "resource": "" }
q19172
executor
train
async def executor(func, *args, **kwargs): ''' Execute a function in an executor thread. Args: todo ((func,args,kwargs)): A todo tuple. ''' def syncfunc(): return func(*args, **kwargs) loop = asyncio.get_running_loop() return await loop.run_in_executor(None, syncfunc)
python
{ "resource": "" }
q19173
varget
train
def varget(name, defval=None, task=None): ''' Access a task local variable by name Precondition: If task is None, this must be called from task context ''' taskdict = _taskdict(task) retn = taskdict.get(name, s_common.NoValu) if retn is not s_common.NoValu: return retn ...
python
{ "resource": "" }
q19174
getPhoneInfo
train
def getPhoneInfo(numb): ''' Walk the phone info tree to find the best-match info for the given number. Example: info = getPhoneInfo(17035551212) country = info.get('cc') ''' text = str(numb) info = {} node = phonetree # make decisions down the tree (but only keep inf...
python
{ "resource": "" }
q19175
Hive.dict
train
async def dict(self, full): ''' Open a HiveDict at the given full path. ''' node = await self.open(full) return await HiveDict.anit(self, node)
python
{ "resource": "" }
q19176
Hive.add
train
async def add(self, full, valu): ''' Atomically increments a node's value. ''' node = await self.open(full) oldv = node.valu newv = oldv + valu node.valu = await self.storNodeValu(full, node.valu + valu) await node.fire('hive:set', path=full, valu=valu,...
python
{ "resource": "" }
q19177
Hive.pop
train
async def pop(self, full): ''' Remove and return the value for the given node. ''' node = self.nodes.get(full) if node is None: return valu = await self._popHiveNode(node) return valu
python
{ "resource": "" }
q19178
CryoTank.puts
train
async def puts(self, items, seqn=None): ''' Add the structured data from items to the CryoTank. Args: items (list): A list of objects to store in the CryoTank. seqn (iden, offs): An iden / offset pair to record. Returns: int: The ending offset of th...
python
{ "resource": "" }
q19179
CryoTank.metrics
train
async def metrics(self, offs, size=None): ''' Yield metrics rows starting at offset. Args: offs (int): The index offset. size (int): The maximum number of records to yield. Yields: ((int, dict)): An index offset, info tuple for metrics. ''' ...
python
{ "resource": "" }
q19180
CryoTank.slice
train
async def slice(self, offs, size=None, iden=None): ''' Yield a number of items from the CryoTank starting at a given offset. Args: offs (int): The index of the desired datum (starts at 0) size (int): The max number of items to yield. Yields: ((index,...
python
{ "resource": "" }
q19181
CryoTank.rows
train
async def rows(self, offs, size=None, iden=None): ''' Yield a number of raw items from the CryoTank starting at a given offset. Args: offs (int): The index of the desired datum (starts at 0) size (int): The max number of items to yield. Yields: ((ind...
python
{ "resource": "" }
q19182
CryoTank.info
train
async def info(self): ''' Returns information about the CryoTank instance. Returns: dict: A dict containing items and metrics indexes. ''' stat = self._items.stat() return {'indx': self._items.index(), 'metrics': self._metrics.index(), 'stat': stat}
python
{ "resource": "" }
q19183
CryoCell.init
train
async def init(self, name, conf=None): ''' Generate a new CryoTank with a given name or get an reference to an existing CryoTank. Args: name (str): Name of the CryoTank. Returns: CryoTank: A CryoTank instance. ''' tank = self.tanks.get(name) ...
python
{ "resource": "" }
q19184
hashitem
train
def hashitem(item): ''' Generate a uniq hash for the JSON compatible primitive data structure. ''' norm = normitem(item) byts = s_msgpack.en(norm) return hashlib.md5(byts).hexdigest()
python
{ "resource": "" }
q19185
getVolInfo
train
def getVolInfo(*paths): ''' Retrieve volume usage info for the given path. ''' path = os.path.join(*paths) path = os.path.expanduser(path) st = os.statvfs(path) free = st.f_bavail * st.f_frsize total = st.f_blocks * st.f_frsize return { 'free': free, 'used': total ...
python
{ "resource": "" }
q19186
parse_cmd_string
train
def parse_cmd_string(text, off, trim=True): ''' Parse in a command line string which may be quoted. ''' if trim: _, off = nom(text, off, whites) if isquote(text, off): return parse_string(text, off, trim=trim) if nextchar(text, off, '('): return parse_list(text, off) ...
python
{ "resource": "" }
q19187
parse_valu
train
def parse_valu(text, off=0): ''' Special syntax for the right side of equals in a macro ''' _, off = nom(text, off, whites) if nextchar(text, off, '('): return parse_list(text, off) if isquote(text, off): return parse_string(text, off) # since it's not quoted, we can assum...
python
{ "resource": "" }
q19188
Parser.editunivset
train
def editunivset(self): ''' .foo = bar ''' self.ignore(whitespace) if not self.nextstr('.'): self._raiseSyntaxExpects('.') univ = self.univprop() self.ignore(whitespace) self.nextmust('=') self.ignore(whitespace) valu = self...
python
{ "resource": "" }
q19189
parse
train
def parse(text, base=None, chop=False): ''' Parse a time string into an epoch millis value. ''' #TODO: use base to facilitate relative time offsets text = text.strip().lower() text = (''.join([c for c in text if c.isdigit()])) if chop: text = text[:17] # TODO: support relative ...
python
{ "resource": "" }
q19190
repr
train
def repr(tick, pack=False): ''' Return a date string for an epoch-millis timestamp. Args: tick (int): The timestamp in milliseconds since the epoch. Returns: (str): A date time string ''' if tick == 0x7fffffffffffffff: return '?' dt = datetime.datetime(1970, 1, 1)...
python
{ "resource": "" }
q19191
delta
train
def delta(text): ''' Parse a simple time delta string and return the delta. ''' text = text.strip().lower() _, offs = _noms(text, 0, ' \t\r\n') sign = '+' if text and text[0] in ('+', '-'): sign = text[0] offs += 1 _, offs = _noms(text, offs, ' \t\r\n') sizetext, ...
python
{ "resource": "" }
q19192
TinFoilHat.enc
train
def enc(self, byts, asscd=None): ''' Encrypt the given bytes and return an envelope dict in msgpack form. Args: byts (bytes): The message to be encrypted. asscd (bytes): Extra data that needs to be authenticated (but not encrypted). Returns: bytes: T...
python
{ "resource": "" }
q19193
TinFoilHat.dec
train
def dec(self, byts): ''' Decode an envelope dict and decrypt the given bytes. Args: byts (bytes): Bytes to decrypt. Returns: bytes: Decrypted message. ''' envl = s_msgpack.un(byts) iv = envl.get('iv', b'') asscd = envl.get('asscd'...
python
{ "resource": "" }
q19194
CryptSeq.encrypt
train
def encrypt(self, mesg): ''' Wrap a message with a sequence number and encrypt it. Args: mesg: The mesg to encrypt. Returns: bytes: The encrypted message. ''' seqn = next(self._tx_sn) rv = self._tx_tinh.enc(s_msgpack.en((seqn, mesg))) ...
python
{ "resource": "" }
q19195
CryptSeq.decrypt
train
def decrypt(self, ciphertext): ''' Decrypt a message, validating its sequence number is as we expect. Args: ciphertext (bytes): The message to decrypt and verify. Returns: mesg: A mesg. Raises: s_exc.CryptoErr: If the message decryption fail...
python
{ "resource": "" }
q19196
parseSemver
train
def parseSemver(text): ''' Parse a Semantic Version string into is component parts. Args: text (str): A text string to parse into semver components. This string has whitespace and leading 'v' characters stripped off of it. Examples: Parse a string into it semvar parts:: ...
python
{ "resource": "" }
q19197
unpackVersion
train
def unpackVersion(ver): ''' Unpack a system normalized integer representing a softare version into its component parts. Args: ver (int): System normalized integer value to unpack into a tuple. Returns: (int, int, int): A tuple containing the major, minor and patch values shifted out of...
python
{ "resource": "" }
q19198
fmtVersion
train
def fmtVersion(*vsnparts): ''' Join a string of parts together with a . separator. Args: *vsnparts: Returns: ''' if len(vsnparts) < 1: raise s_exc.BadTypeValu(valu=repr(vsnparts), name='fmtVersion', mesg='Not enough version parts to form a versi...
python
{ "resource": "" }
q19199
SlabDict.set
train
def set(self, name, valu): ''' Set a name in the SlabDict. Args: name (str): The key name. valu (obj): A msgpack compatible value. Returns: None ''' byts = s_msgpack.en(valu) lkey = self.pref + name.encode('utf8') self...
python
{ "resource": "" }