repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
mosdef-hub/foyer
foyer/smarts_graph.py
SMARTSGraph.find_matches
python
def find_matches(self, topology): # Note: Needs to be updated in sync with the grammar in `smarts.py`. ring_tokens = ['ring_size', 'ring_count'] has_ring_rules = any(self.ast.select(token) for token in ring_tokens) _prepare_atoms(topology, compute_cycles=has_...
Return sets of atoms that match this SMARTS pattern in a topology. Notes: ------ When this function gets used in atomtyper.py, we actively modify the white- and blacklists of the atoms in `topology` after finding a match. This means that between every successive call of ...
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L150-L203
[ "def _prepare_atoms(topology, compute_cycles=False):\n \"\"\"Compute cycles and add white-/blacklists to atoms.\"\"\"\n atom1 = next(topology.atoms())\n has_whitelists = hasattr(atom1, 'whitelist')\n has_cycles = hasattr(atom1, 'cycles')\n compute_cycles = compute_cycles and not has_cycles\n\n if ...
class SMARTSGraph(nx.Graph): """A graph representation of a SMARTS pattern. Attributes ---------- smarts_string : str parser : foyer.smarts.SMARTS name : str overrides : set Other Parameters ---------- args kwargs """ # Because the first atom in a SMARTS string is a...
mosdef-hub/foyer
foyer/smarts_graph.py
SMARTSMatcher.candidate_pairs_iter
python
def candidate_pairs_iter(self): # All computations are done using the current state! G2_nodes = self.G2_nodes # First we compute the inout-terminal sets. T1_inout = set(self.inout_1.keys()) - set(self.core_1.keys()) T2_inout = set(self.inout_2.keys()) - set(self.core_2.keys()) ...
Iterator over candidate pairs of nodes in G1 and G2.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L216-L236
null
class SMARTSMatcher(isomorphism.vf2userfunc.GraphMatcher): def __init__(self, G1, G2, node_match, element): super(SMARTSMatcher, self).__init__(G1, G2, node_match) self.element = element if element not in [None, '*']: self.valid_nodes = [n for n, atom in nx.get_node_attributes(G1...
mosdef-hub/foyer
foyer/atomtyper.py
find_atomtypes
python
def find_atomtypes(topology, forcefield, max_iter=10): rules = _load_rules(forcefield) # Only consider rules for elements found in topology subrules = dict() system_elements = {a.element.symbol for a in topology.atoms()} for key,val in rules.items(): atom = val.node[0]['atom'] if le...
Determine atomtypes for all atoms. Parameters ---------- topology : simtk.openmm.app.Topology The topology that we are trying to atomtype. forcefield : foyer.Forcefield The forcefield object. max_iter : int, optional, default=10 The maximum number of iterations.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L7-L43
[ "def _load_rules(forcefield):\n \"\"\"Load atomtyping rules from a forcefield into SMARTSGraphs. \"\"\"\n rules = dict()\n for rule_name, smarts in forcefield.atomTypeDefinitions.items():\n overrides = forcefield.atomTypeOverrides.get(rule_name)\n if overrides is not None:\n overri...
from warnings import warn from foyer.exceptions import FoyerError from foyer.smarts_graph import SMARTSGraph def _load_rules(forcefield): """Load atomtyping rules from a forcefield into SMARTSGraphs. """ rules = dict() for rule_name, smarts in forcefield.atomTypeDefinitions.items(): overrides = ...
mosdef-hub/foyer
foyer/atomtyper.py
_load_rules
python
def _load_rules(forcefield): rules = dict() for rule_name, smarts in forcefield.atomTypeDefinitions.items(): overrides = forcefield.atomTypeOverrides.get(rule_name) if overrides is not None: overrides = set(overrides) else: overrides = set() rules[rule_nam...
Load atomtyping rules from a forcefield into SMARTSGraphs.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L46-L59
null
from warnings import warn from foyer.exceptions import FoyerError from foyer.smarts_graph import SMARTSGraph def find_atomtypes(topology, forcefield, max_iter=10): """Determine atomtypes for all atoms. Parameters ---------- topology : simtk.openmm.app.Topology The topology that we are trying...
mosdef-hub/foyer
foyer/atomtyper.py
_iterate_rules
python
def _iterate_rules(rules, topology, max_iter): atoms = list(topology.atoms()) for _ in range(max_iter): max_iter -= 1 found_something = False for rule in rules.values(): for match_index in rule.find_matches(topology): atom = atoms[match_index] ...
Iteratively run all the rules until the white- and backlists converge. Parameters ---------- rules : dict A dictionary mapping rule names (typically atomtype names) to SMARTSGraphs that evaluate those rules. topology : simtk.openmm.app.Topology The topology that we are trying to...
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L62-L90
null
from warnings import warn from foyer.exceptions import FoyerError from foyer.smarts_graph import SMARTSGraph def find_atomtypes(topology, forcefield, max_iter=10): """Determine atomtypes for all atoms. Parameters ---------- topology : simtk.openmm.app.Topology The topology that we are trying...
mosdef-hub/foyer
foyer/atomtyper.py
_resolve_atomtypes
python
def _resolve_atomtypes(topology): for atom in topology.atoms(): atomtype = [rule_name for rule_name in atom.whitelist - atom.blacklist] if len(atomtype) == 1: atom.id = atomtype[0] elif len(atomtype) > 1: raise FoyerError("Found multiple types for atom {} ({}): {}.".f...
Determine the final atomtypes from the white- and blacklists.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L93-L104
null
from warnings import warn from foyer.exceptions import FoyerError from foyer.smarts_graph import SMARTSGraph def find_atomtypes(topology, forcefield, max_iter=10): """Determine atomtypes for all atoms. Parameters ---------- topology : simtk.openmm.app.Topology The topology that we are trying...
mosdef-hub/foyer
foyer/forcefield.py
generate_topology
python
def generate_topology(non_omm_topology, non_element_types=None, residues=None): if non_element_types is None: non_element_types = set() if isinstance(non_omm_topology, pmd.Structure): return _topology_from_parmed(non_omm_topology, non_element_types) elif has_mbuild: mb = imp...
Create an OpenMM Topology from another supported topology structure.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L87-L105
[ "def import_(module):\n \"\"\"Import a module, and issue a nice message to stderr if the module isn't installed.\n Parameters\n ----------\n module : str\n The module you'd like to import, as a string\n Returns\n -------\n module : {module, object}\n The module object\n Example...
import collections import glob import itertools import os from tempfile import mktemp, mkstemp import xml.etree.ElementTree as ET try: from cStringIO import StringIO except ImportError: from io import StringIO from pkg_resources import resource_filename import requests import warnings import re import numpy a...
mosdef-hub/foyer
foyer/forcefield.py
_topology_from_parmed
python
def _topology_from_parmed(structure, non_element_types): topology = app.Topology() residues = dict() for pmd_residue in structure.residues: chain = topology.addChain() omm_residue = topology.addResidue(pmd_residue.name, chain) residues[pmd_residue] = omm_residue atoms = dict() #...
Convert a ParmEd Structure to an OpenMM Topology.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L108-L143
null
import collections import glob import itertools import os from tempfile import mktemp, mkstemp import xml.etree.ElementTree as ET try: from cStringIO import StringIO except ImportError: from io import StringIO from pkg_resources import resource_filename import requests import warnings import re import numpy a...
mosdef-hub/foyer
foyer/forcefield.py
_topology_from_residue
python
def _topology_from_residue(res): topology = app.Topology() chain = topology.addChain() new_res = topology.addResidue(res.name, chain) atoms = dict() # { omm.Atom in res : omm.Atom in *new* topology } for res_atom in res.atoms(): topology_atom = topology.addAtom(name=res_atom.name, ...
Converts a openmm.app.Topology.Residue to openmm.app.Topology. Parameters ---------- res : openmm.app.Topology.Residue An individual residue in an openmm.app.Topology Returns ------- topology : openmm.app.Topology The generated topology
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L146-L180
null
import collections import glob import itertools import os from tempfile import mktemp, mkstemp import xml.etree.ElementTree as ET try: from cStringIO import StringIO except ImportError: from io import StringIO from pkg_resources import resource_filename import requests import warnings import re import numpy a...
mosdef-hub/foyer
foyer/forcefield.py
_check_independent_residues
python
def _check_independent_residues(topology): for res in topology.residues(): atoms_in_residue = set([atom for atom in res.atoms()]) bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for item in sublist] # Handle the case of a 'residue' with no neighbo...
Check to see if residues will constitute independent graphs.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L183-L193
null
import collections import glob import itertools import os from tempfile import mktemp, mkstemp import xml.etree.ElementTree as ET try: from cStringIO import StringIO except ImportError: from io import StringIO from pkg_resources import resource_filename import requests import warnings import re import numpy a...
mosdef-hub/foyer
foyer/forcefield.py
_update_atomtypes
python
def _update_atomtypes(unatomtyped_topology, res_name, prototype): for res in unatomtyped_topology.residues(): if res.name == res_name: for old_atom, new_atom_id in zip([atom for atom in res.atoms()], [atom.id for atom in prototype.atoms()]): old_atom.id = new_atom_id
Update atomtypes in residues in a topology using a prototype topology. Atomtypes are updated when residues in each topology have matching names. Parameters ---------- unatomtyped_topology : openmm.app.Topology Topology lacking atomtypes defined by `find_atomtypes`. prototype : openmm.app.T...
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L196-L212
null
import collections import glob import itertools import os from tempfile import mktemp, mkstemp import xml.etree.ElementTree as ET try: from cStringIO import StringIO except ImportError: from io import StringIO from pkg_resources import resource_filename import requests import warnings import re import numpy a...
mosdef-hub/foyer
foyer/forcefield.py
Forcefield.registerAtomType
python
def registerAtomType(self, parameters): name = parameters['name'] if name in self._atomTypes: raise ValueError('Found multiple definitions for atom type: ' + name) atom_class = parameters['class'] mass = _convertParameterToNumber(parameters['mass']) element = None ...
Register a new atom type.
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L307-L341
[ "def _create_element(self, element, mass):\n if not isinstance(element, elem.Element):\n try:\n element = elem.get_by_symbol(element)\n except KeyError:\n # Enables support for non-atomistic \"element types\"\n if element not in self.non_element_types:\n ...
class Forcefield(app.ForceField): """Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping. Parameters ---------- forcefield_files : list of str, optional, default=None List of forcefield files to load. name : str, optional, default=None Name of a forcefield to load...
mosdef-hub/foyer
foyer/forcefield.py
Forcefield.apply
python
def apply(self, topology, references_file=None, use_residue_map=True, assert_bond_params=True, assert_angle_params=True, assert_dihedral_params=True, assert_improper_params=False, *args, **kwargs): if self.atomTypeDefinitions == {}: raise FoyerError('Attempt...
Apply the force field to a molecular structure Parameters ---------- topology : openmm.app.Topology or parmed.Structure or mbuild.Compound Molecular structure to apply the force field to references_file : str, optional, default=None Name of file where force field...
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L343-L450
[ "def generate_topology(non_omm_topology, non_element_types=None,\n residues=None):\n \"\"\"Create an OpenMM Topology from another supported topology structure.\"\"\"\n if non_element_types is None:\n non_element_types = set()\n\n if isinstance(non_omm_topology, pmd.Structure):\n return...
class Forcefield(app.ForceField): """Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping. Parameters ---------- forcefield_files : list of str, optional, default=None List of forcefield files to load. name : str, optional, default=None Name of a forcefield to load...
mosdef-hub/foyer
foyer/forcefield.py
Forcefield.run_atomtyping
python
def run_atomtyping(self, topology, use_residue_map=True): if use_residue_map: independent_residues = _check_independent_residues(topology) if independent_residues: residue_map = dict() for res in topology.residues(): if res.name not i...
Atomtype the topology Parameters ---------- topology : openmm.app.Topology Molecular structure to find atom types of use_residue_map : boolean, optional, default=True Store atomtyped topologies of residues to a dictionary that maps them to residue nam...
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L452-L493
[ "def find_atomtypes(topology, forcefield, max_iter=10):\n \"\"\"Determine atomtypes for all atoms.\n\n Parameters\n ----------\n topology : simtk.openmm.app.Topology\n The topology that we are trying to atomtype.\n forcefield : foyer.Forcefield\n The forcefield object.\n max_iter : i...
class Forcefield(app.ForceField): """Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping. Parameters ---------- forcefield_files : list of str, optional, default=None List of forcefield files to load. name : str, optional, default=None Name of a forcefield to load...
mosdef-hub/foyer
foyer/forcefield.py
Forcefield.createSystem
python
def createSystem(self, topology, nonbondedMethod=NoCutoff, nonbondedCutoff=1.0 * u.nanometer, constraints=None, rigidWater=True, removeCMMotion=True, hydrogenMass=None, **args): # Overwrite previous _SystemData object self._SystemData = app...
Construct an OpenMM System representing a Topology with this force field. Parameters ---------- topology : Topology The Topology for which to create a System nonbondedMethod : object=NoCutoff The method to use for nonbonded interactions. Allowed values are ...
train
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L495-L734
null
class Forcefield(app.ForceField): """Specialization of OpenMM's Forcefield allowing SMARTS based atomtyping. Parameters ---------- forcefield_files : list of str, optional, default=None List of forcefield files to load. name : str, optional, default=None Name of a forcefield to load...
20c/vaping
vaping/plugins/vodka.py
probe_to_graphsrv
python
def probe_to_graphsrv(probe): config = probe.config # manual group set up via `group` config key if "group" in config: source, group = config["group"].split(".") group_field = config.get("group_field", "host") group_value = config[group_field] graphsrv.group.add(source, gr...
takes a probe instance and generates a graphsrv data group for it using the probe's config
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/vodka.py#L20-L49
null
from __future__ import absolute_import import vaping import vaping.config try: import vodka import vodka.data except ImportError: pass try: import graphsrv import graphsrv.group except ImportError: graphsrv = None @vaping.plugin.register('vodka') class VodkaPlugin(vaping.plugins.EmitBase):...
20c/vaping
vaping/plugins/__init__.py
PluginBase.new_message
python
def new_message(self): msg = {} msg['data'] = [] msg['type'] = self.plugin_type msg['source'] = self.name msg['ts'] = (datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() return msg
creates a new message, setting `type`, `source`, `ts`, `data` - `data` is initialized to an empty array
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L51-L61
null
class PluginBase(vaping.io.Thread): """ Base plugin class Initializes: - `self.config` as plugins config - `self.log` as a logging object for plugin - `self.vaping` as a reference to the main vaping object Then calls alls `self.init()` prefork while loading all modules, init() should ...
20c/vaping
vaping/plugins/__init__.py
PluginBase.popen
python
def popen(self, args, **kwargs): self.log.debug("popen %s", ' '.join(args)) return vaping.io.subprocess.Popen(args, **kwargs)
creates a subprocess with passed args
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L63-L68
null
class PluginBase(vaping.io.Thread): """ Base plugin class Initializes: - `self.config` as plugins config - `self.log` as a logging object for plugin - `self.vaping` as a reference to the main vaping object Then calls alls `self.init()` prefork while loading all modules, init() should ...
20c/vaping
vaping/plugins/__init__.py
ProbeBase.queue_emission
python
def queue_emission(self, msg): if not msg: return for _emitter in self._emit: if not hasattr(_emitter, 'emit'): continue def emit(emitter=_emitter): self.log.debug("emit to {}".format(emitter.name)) emitter.emit(msg) ...
queue an emission of a message for all output plugins
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L131-L145
null
class ProbeBase(with_metaclass(abc.ABCMeta, PluginBase)): """ Base class for probe plugin, used for getting data expects method probe() to be defined """ def init(self): pass @abc.abstractmethod def probe(self): """ probe for data, return a list of dicts ""...
20c/vaping
vaping/plugins/__init__.py
ProbeBase.send_emission
python
def send_emission(self): if self._emit_queue.empty(): return emit = self._emit_queue.get() emit()
emit and remove the first emission in the queue
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L147-L154
null
class ProbeBase(with_metaclass(abc.ABCMeta, PluginBase)): """ Base class for probe plugin, used for getting data expects method probe() to be defined """ def init(self): pass @abc.abstractmethod def probe(self): """ probe for data, return a list of dicts ""...
20c/vaping
vaping/plugins/__init__.py
FileProbe.validate_file_handler
python
def validate_file_handler(self): if self.fh.closed: try: self.fh = open(self.path, "r") self.fh.seek(0, 2) except OSError as err: logging.error("Could not reopen file: {}".format(err)) return False open_stat = os.fs...
Here we validate that our filehandler is pointing to an existing file. If it doesnt, because file has been deleted, we close the filehander and try to reopen
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L245-L273
null
class FileProbe(ProbeBase): """ Probes a file and emits everytime a new line is read Config: `path`: path to file `backlog`: number of bytes to read from backlog (default 0) `max_lines`: maximum number of lines to read during probe (default 1000) """ def __init_...
20c/vaping
vaping/plugins/__init__.py
FileProbe.probe
python
def probe(self): # make sure the filehandler is still valid # (e.g. file stat hasnt changed, file exists etc.) if not self.validate_file_handler(): return [] messages = [] # read any new lines and push them onto the stack for line in self.fh.readlines(self....
Probe the file for new lines
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L276-L310
[ "def validate_file_handler(self):\n \"\"\"\n Here we validate that our filehandler is pointing\n to an existing file.\n\n If it doesnt, because file has been deleted, we close\n the filehander and try to reopen\n \"\"\"\n if self.fh.closed:\n try:\n self.fh = open(self.path, \...
class FileProbe(ProbeBase): """ Probes a file and emits everytime a new line is read Config: `path`: path to file `backlog`: number of bytes to read from backlog (default 0) `max_lines`: maximum number of lines to read during probe (default 1000) """ def __init_...
20c/vaping
vaping/plugins/__init__.py
TimeSeriesDB.filename_formatters
python
def filename_formatters(self, data, row): r = { "source" : data.get("source"), "field" : self.field, "type" : data.get("type") } r.update(**row) return r
Returns a dict containing the various filename formatter values Values are gotten from the vaping data message as well as the currently processed row in the message - `data`: vaping message - `row`: vaping message data row
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L394-L411
null
class TimeSeriesDB(EmitBase): """ Base class for timeseries db storage plugins """ def __init__(self, config, ctx): super(TimeSeriesDB, self).__init__(config, ctx) # filename template self.filename = self.config.get("filename") # field name to read the value from ...
20c/vaping
vaping/plugins/__init__.py
TimeSeriesDB.format_filename
python
def format_filename(self, data, row): return self.filename.format(**self.filename_formatters(data, row))
Returns a formatted filename using the template stored in self.filename - `data`: vaping message - `row`: vaping message data row
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L413-L421
[ "def filename_formatters(self, data, row):\n \"\"\"\n Returns a dict containing the various filename formatter values\n\n Values are gotten from the vaping data message as well as the\n currently processed row in the message\n\n - `data`: vaping message\n - `row`: vaping message data row\n \"\"...
class TimeSeriesDB(EmitBase): """ Base class for timeseries db storage plugins """ def __init__(self, config, ctx): super(TimeSeriesDB, self).__init__(config, ctx) # filename template self.filename = self.config.get("filename") # field name to read the value from ...
20c/vaping
vaping/plugins/__init__.py
TimeSeriesDB.emit
python
def emit(self, message): # handle vaping data that arrives in a list if isinstance(message.get("data"), list): for row in message.get("data"): # format filename from data filename = self.format_filename(message, row) # create database file i...
emit to database
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L423-L442
[ "def create(self, filename):\n \"\"\"\n Create database\n\n - `filename`: database filename\n \"\"\"\n raise NotImplementedError()\n", "def update(self, filename, time, value):\n \"\"\"\n Update database\n\n - `filename`: database filename\n - `time`: timestamp\n - `value`\n \"\"\...
class TimeSeriesDB(EmitBase): """ Base class for timeseries db storage plugins """ def __init__(self, config, ctx): super(TimeSeriesDB, self).__init__(config, ctx) # filename template self.filename = self.config.get("filename") # field name to read the value from ...
20c/vaping
vaping/config.py
parse_interval
python
def parse_interval(val): re_intv = re.compile(r"([\d\.]+)([a-zA-Z]+)") val = val.strip() total = 0.0 for match in re_intv.findall(val): unit = match[1] count = float(match[0]) if unit == 's': total += count elif unit == 'm': total += count * 60 ...
converts a string to float of seconds .5 = 500ms 90 = 1m30s
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/config.py#L8-L33
null
from __future__ import division import re import munge class Config(munge.Config): defaults = { 'config': { 'vaping': { 'home_dir': None, 'pidfile': 'vaping.pid', 'plugin_path': [], }, }, 'config_dir': '~/.va...
20c/vaping
vaping/plugins/fping.py
FPingBase.hosts_args
python
def hosts_args(self): host_args = [] for row in self.hosts: if isinstance(row, dict): host_args.append(row["host"]) else: host_args.append(row) # using a set changes the order dedupe = list() for each in host_args: ...
hosts list can contain strings specifying a host directly or dicts containing a "host" key to specify the host this way we can allow passing further config details (color, name etc.) with each host as well as simply dropping in addresses for quick setup depending on the user's needs
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/fping.py#L39-L61
null
class FPingBase(vaping.plugins.TimedProbe): """ FPing base plugin config: `command` command to run `interval` time between pings `count` number of pings to send `period` time in milliseconds that fping waits between successive packets to an individual target """ def...
20c/vaping
vaping/plugins/fping.py
FPingBase.parse_verbose
python
def parse_verbose(self, line): try: logging.debug(line) (host, pings) = line.split(' : ') cnt = 0 lost = 0 times = [] pings = pings.strip().split(' ') cnt = len(pings) for latency in pings: if latency...
parse output from verbose format
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/fping.py#L63-L100
null
class FPingBase(vaping.plugins.TimedProbe): """ FPing base plugin config: `command` command to run `interval` time between pings `count` number of pings to send `period` time in milliseconds that fping waits between successive packets to an individual target """ def...
20c/vaping
vaping/cli.py
start
python
def start(ctx, **kwargs): update_context(ctx, kwargs) daemon = mk_daemon(ctx) if ctx.debug or kwargs['no_fork']: daemon.run() else: daemon.start()
start a vaping process
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/cli.py#L52-L63
[ "def update_context(ctx, kwargs):\n ctx.update_options(kwargs)\n\n if not isinstance(ctx.config['vaping']['plugin_path'], list):\n raise ValueError('config item vaping.plugin_path must be a list')\n # set plugin search path to defined + home/plugins\n searchpath = ctx.config['vaping']['plugin_pat...
from __future__ import absolute_import import os import click import munge import munge.click import vaping import vaping.daemon class Context(munge.click.Context): app_name = 'vaping' config_class = vaping.Config def update_context(ctx, kwargs): ctx.update_options(kwargs) if not isinstance(ctx....
20c/vaping
vaping/cli.py
stop
python
def stop(ctx, **kwargs): update_context(ctx, kwargs) daemon = mk_daemon(ctx) daemon.stop()
stop a vaping process
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/cli.py#L70-L77
[ "def update_context(ctx, kwargs):\n ctx.update_options(kwargs)\n\n if not isinstance(ctx.config['vaping']['plugin_path'], list):\n raise ValueError('config item vaping.plugin_path must be a list')\n # set plugin search path to defined + home/plugins\n searchpath = ctx.config['vaping']['plugin_pat...
from __future__ import absolute_import import os import click import munge import munge.click import vaping import vaping.daemon class Context(munge.click.Context): app_name = 'vaping' config_class = vaping.Config def update_context(ctx, kwargs): ctx.update_options(kwargs) if not isinstance(ctx....
20c/vaping
vaping/cli.py
restart
python
def restart(ctx, **kwargs): update_context(ctx, kwargs) daemon = mk_daemon(ctx) daemon.stop() daemon.start()
restart a vaping process
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/cli.py#L84-L92
[ "def update_context(ctx, kwargs):\n ctx.update_options(kwargs)\n\n if not isinstance(ctx.config['vaping']['plugin_path'], list):\n raise ValueError('config item vaping.plugin_path must be a list')\n # set plugin search path to defined + home/plugins\n searchpath = ctx.config['vaping']['plugin_pat...
from __future__ import absolute_import import os import click import munge import munge.click import vaping import vaping.daemon class Context(munge.click.Context): app_name = 'vaping' config_class = vaping.Config def update_context(ctx, kwargs): ctx.update_options(kwargs) if not isinstance(ctx....
20c/vaping
vaping/daemon.py
Vaping._exec
python
def _exec(self, detach=True): kwargs = { 'pidfile': self.pidfile, 'working_directory': self.home_dir, } # FIXME - doesn't work if not detach: kwargs.update({ 'detach_process': False, 'files_preserve': [0,1,2], ...
daemonize and exec main()
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/daemon.py#L97-L118
[ "def _main(self):\n \"\"\"\n process\n \"\"\"\n probes = self.config.get('probes', None)\n if not probes:\n raise ValueError('no probes specified')\n\n for probe_config in self.config['probes']:\n probe = plugin.get_probe(probe_config, self.plugin_context)\n # FIXME - needs to...
class Vaping(object): """ Vaping daemon class """ def __init__(self, config=None, config_dir=None): """ must either pass config as a dict or vaping.config.Config or config_dir as a path to where the config dir is located """ if config: if isinstance(config, d...
20c/vaping
vaping/daemon.py
Vaping._main
python
def _main(self): probes = self.config.get('probes', None) if not probes: raise ValueError('no probes specified') for probe_config in self.config['probes']: probe = plugin.get_probe(probe_config, self.plugin_context) # FIXME - needs to check for output defined...
process
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/daemon.py#L120-L146
null
class Vaping(object): """ Vaping daemon class """ def __init__(self, config=None, config_dir=None): """ must either pass config as a dict or vaping.config.Config or config_dir as a path to where the config dir is located """ if config: if isinstance(config, d...
20c/vaping
vaping/daemon.py
Vaping.stop
python
def stop(self): try: with self.pidfile: self.log.error("failed to stop, missing pid file or not running") except pidfile.PidFileError: # this isn't exposed in pidfile :o with open(self.pidfile.filename) as fobj: pid = int(fobj.readline...
stop daemon
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/daemon.py#L152-L166
null
class Vaping(object): """ Vaping daemon class """ def __init__(self, config=None, config_dir=None): """ must either pass config as a dict or vaping.config.Config or config_dir as a path to where the config dir is located """ if config: if isinstance(config, d...
20c/vaping
vaping/daemon.py
Vaping.run
python
def run(self): # FIXME - not detaching doesn't work, just run directly for now # self._exec(detach=False) try: with self.pidfile: return self._main() except pidfile.PidFileError: # this isn't exposed in pidfile :o self.log.error("faile...
run daemon
train
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/daemon.py#L168-L185
[ "def _main(self):\n \"\"\"\n process\n \"\"\"\n probes = self.config.get('probes', None)\n if not probes:\n raise ValueError('no probes specified')\n\n for probe_config in self.config['probes']:\n probe = plugin.get_probe(probe_config, self.plugin_context)\n # FIXME - needs to...
class Vaping(object): """ Vaping daemon class """ def __init__(self, config=None, config_dir=None): """ must either pass config as a dict or vaping.config.Config or config_dir as a path to where the config dir is located """ if config: if isinstance(config, d...
toastdriven/restless
restless/resources.py
skip_prepare
python
def skip_prepare(func): @wraps(func) def _wrapper(self, *args, **kwargs): value = func(self, *args, **kwargs) return Data(value, should_prepare=False) return _wrapper
A convenience decorator for indicating the raw data should not be prepared.
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L12-L20
null
from functools import wraps import sys from .constants import OK, CREATED, ACCEPTED, NO_CONTENT from .data import Data from .exceptions import MethodNotImplemented, Unauthorized from .preparers import Preparer from .serializers import JSONSerializer from .utils import format_traceback class Resource(object): ""...
toastdriven/restless
restless/resources.py
Resource.as_view
python
def as_view(cls, view_type, *init_args, **init_kwargs): @wraps(cls) def _wrapper(request, *args, **kwargs): # Make a new instance so that no state potentially leaks between # instances. inst = cls(*init_args, **init_kwargs) inst.request = request ...
Used for hooking up the all endpoints (including custom ones), this returns a wrapper function that creates a new instance of the resource class & calls the correct view method for it. :param view_type: Should be one of ``list``, ``detail`` or ``custom``. :type view_type: string ...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L119-L144
null
class Resource(object): """ Defines a RESTful resource. Users are expected to subclass this object & implement a handful of methods: * ``list`` * ``detail`` * ``create`` (requires authentication) * ``update`` (requires authentication) * ``delete`` (requires authentication) Additio...
toastdriven/restless
restless/resources.py
Resource.build_error
python
def build_error(self, err): data = { 'error': err.args[0], } if self.is_debug(): # Add the traceback. data['traceback'] = format_traceback(sys.exc_info()) body = self.serializer.serialize(data) status = getattr(err, 'status', 500) ret...
When an exception is encountered, this generates a JSON error message for display to the user. :param err: The exception seen. The message is exposed to the user, so beware of sensitive data leaking. :type err: Exception :returns: A response object
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L192-L213
[ "def format_traceback(exc_info):\n stack = traceback.format_stack()\n stack = stack[:-2]\n stack.extend(traceback.format_tb(exc_info[2]))\n stack.extend(traceback.format_exception_only(exc_info[0], exc_info[1]))\n stack_str = \"Traceback (most recent call last):\\n\"\n stack_str += \"\".join(stack...
class Resource(object): """ Defines a RESTful resource. Users are expected to subclass this object & implement a handful of methods: * ``list`` * ``detail`` * ``create`` (requires authentication) * ``update`` (requires authentication) * ``delete`` (requires authentication) Additio...
toastdriven/restless
restless/resources.py
Resource.deserialize
python
def deserialize(self, method, endpoint, body): if endpoint == 'list': return self.deserialize_list(body) return self.deserialize_detail(body)
A convenience method for deserializing the body of a request. If called on a list-style endpoint, this calls ``deserialize_list``. Otherwise, it will call ``deserialize_detail``. :param method: The HTTP method of the current request :type method: string :param endpoint: The en...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L310-L332
[ "def deserialize_list(self, body):\n \"\"\"\n Given a string of text, deserializes a (presumed) list out of the body.\n\n :param body: The body of the current request\n :type body: string\n\n :returns: The deserialized body or an empty ``list``\n \"\"\"\n if body:\n return self.serialize...
class Resource(object): """ Defines a RESTful resource. Users are expected to subclass this object & implement a handful of methods: * ``list`` * ``detail`` * ``create`` (requires authentication) * ``update`` (requires authentication) * ``delete`` (requires authentication) Additio...
toastdriven/restless
restless/resources.py
Resource.serialize
python
def serialize(self, method, endpoint, data): if endpoint == 'list': # Create is a special-case, because you POST it to the collection, # not to a detail. if method == 'POST': return self.serialize_detail(data) return self.serialize_list(data) ...
A convenience method for serializing data for a response. If called on a list-style endpoint, this calls ``serialize_list``. Otherwise, it will call ``serialize_detail``. :param method: The HTTP method of the current request :type method: string :param endpoint: The endpoint s...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L362-L388
[ "def serialize_list(self, data):\n \"\"\"\n Given a collection of data (``objects`` or ``dicts``), serializes them.\n\n :param data: The collection of items to serialize\n :type data: list or iterable\n\n :returns: The serialized body\n :rtype: string\n \"\"\"\n if data is None:\n ret...
class Resource(object): """ Defines a RESTful resource. Users are expected to subclass this object & implement a handful of methods: * ``list`` * ``detail`` * ``create`` (requires authentication) * ``update`` (requires authentication) * ``delete`` (requires authentication) Additio...
toastdriven/restless
restless/resources.py
Resource.serialize_list
python
def serialize_list(self, data): if data is None: return '' # Check for a ``Data``-like object. We should assume ``True`` (all # data gets prepared) unless it's explicitly marked as not. if not getattr(data, 'should_prepare', True): prepped_data = data.value ...
Given a collection of data (``objects`` or ``dicts``), serializes them. :param data: The collection of items to serialize :type data: list or iterable :returns: The serialized body :rtype: string
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L390-L411
[ "def wrap_list_response(self, data):\n response_dict = super(DjangoResource, self).wrap_list_response(data)\n\n if hasattr(self, 'page'):\n next_page = self.page.has_next() and self.page.next_page_number() or None\n previous_page = self.page.has_previous() and self.page.previous_page_number() or...
class Resource(object): """ Defines a RESTful resource. Users are expected to subclass this object & implement a handful of methods: * ``list`` * ``detail`` * ``create`` (requires authentication) * ``update`` (requires authentication) * ``delete`` (requires authentication) Additio...
toastdriven/restless
restless/resources.py
Resource.serialize_detail
python
def serialize_detail(self, data): if data is None: return '' # Check for a ``Data``-like object. We should assume ``True`` (all # data gets prepared) unless it's explicitly marked as not. if not getattr(data, 'should_prepare', True): prepped_data = data.value ...
Given a single item (``object`` or ``dict``), serializes it. :param data: The item to serialize :type data: object or dict :returns: The serialized body :rtype: string
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L413-L433
[ "def prepare(self, data):\n \"\"\"\n Given an item (``object`` or ``dict``), this will potentially go through\n & reshape the output based on ``self.prepare_with`` object.\n\n :param data: An item to prepare for serialization\n :type data: object or dict\n\n :returns: A potentially reshaped dict\n...
class Resource(object): """ Defines a RESTful resource. Users are expected to subclass this object & implement a handful of methods: * ``list`` * ``detail`` * ``create`` (requires authentication) * ``update`` (requires authentication) * ``delete`` (requires authentication) Additio...
toastdriven/restless
restless/tnd.py
_method
python
def _method(self, *args, **kwargs): yield self.resource_handler.handle(self.__resource_view_type__, *args, **kwargs)
the body of those http-methods used in tornado.web.RequestHandler
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/tnd.py#L36-L40
null
from tornado import web, gen from .constants import OK, NO_CONTENT from .resources import Resource from .exceptions import MethodNotImplemented, Unauthorized import weakref import inspect try: from tornado.concurrent import is_future except ImportError: is_future = None if is_future is None: """ Ple...
toastdriven/restless
restless/tnd.py
TornadoResource.as_view
python
def as_view(cls, view_type, *init_args, **init_kwargs): global _method new_cls = type( cls.__name__ + '_' + _BridgeMixin.__name__ + '_restless', (_BridgeMixin, cls._request_handler_base_,), dict( __resource_cls__=cls, __resource_args__...
Return a subclass of tornado.web.RequestHandler and apply required setting.
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/tnd.py#L95-L123
null
class TornadoResource(Resource): """ A Tornado-specific ``Resource`` subclass. """ _request_handler_base_ = web.RequestHandler """ To override ``tornado.web.RequestHandler`` we used, please assign your RequestHandler via this attribute. """ def __init__(self, *args, **kwargs): ...
toastdriven/restless
restless/tnd.py
TornadoResource.handle
python
def handle(self, endpoint, *args, **kwargs): method = self.request_method() try: if not method in self.http_methods.get(endpoint, {}): raise MethodNotImplemented( "Unsupported method '{}' for {} endpoint.".format( method, ...
almost identical to Resource.handle, except the way we handle the return value of view_method.
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/tnd.py#L147-L177
[ "def handle_error(self, err):\n \"\"\"\n When an exception is encountered, this generates a serialized error\n message to return the user.\n\n :param err: The exception seen. The message is exposed to the user, so\n beware of sensitive data leaking.\n :type err: Exception\n\n :returns: A re...
class TornadoResource(Resource): """ A Tornado-specific ``Resource`` subclass. """ _request_handler_base_ = web.RequestHandler """ To override ``tornado.web.RequestHandler`` we used, please assign your RequestHandler via this attribute. """ def __init__(self, *args, **kwargs): ...
toastdriven/restless
restless/preparers.py
FieldsPreparer.prepare
python
def prepare(self, data): result = {} if not self.fields: # No fields specified. Serialize everything. return data for fieldname, lookup in self.fields.items(): if isinstance(lookup, SubPreparer): result[fieldname] = lookup.prepare(data) ...
Handles transforming the provided data into the fielded data that should be exposed to the end user. Uses the ``lookup_data`` method to traverse dotted paths. Returns a dictionary of data as the response.
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/preparers.py#L42-L63
[ "def lookup_data(self, lookup, data):\n \"\"\"\n Given a lookup string, attempts to descend through nested data looking for\n the value.\n\n Can work with either dictionary-alikes or objects (or any combination of\n those).\n\n Lookups should be a string. If it is a dotted path, it will be split o...
class FieldsPreparer(Preparer): """ A more complex preparation object, this will return a given set of fields. This takes a ``fields`` parameter, which should be a dictionary of keys (fieldnames to expose to the user) & values (a dotted lookup path to the desired attribute/key on the object). ...
toastdriven/restless
restless/preparers.py
FieldsPreparer.lookup_data
python
def lookup_data(self, lookup, data): value = data parts = lookup.split('.') if not parts or not parts[0]: return value part = parts[0] remaining_lookup = '.'.join(parts[1:]) if callable(getattr(data, 'keys', None)) and hasattr(data, '__getitem__'): ...
Given a lookup string, attempts to descend through nested data looking for the value. Can work with either dictionary-alikes or objects (or any combination of those). Lookups should be a string. If it is a dotted path, it will be split on ``.`` & it will traverse through to fin...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/preparers.py#L65-L123
[ "def lookup_data(self, lookup, data):\n \"\"\"\n Given a lookup string, attempts to descend through nested data looking for\n the value.\n\n Can work with either dictionary-alikes or objects (or any combination of\n those).\n\n Lookups should be a string. If it is a dotted path, it will be split o...
class FieldsPreparer(Preparer): """ A more complex preparation object, this will return a given set of fields. This takes a ``fields`` parameter, which should be a dictionary of keys (fieldnames to expose to the user) & values (a dotted lookup path to the desired attribute/key on the object). ...
toastdriven/restless
restless/preparers.py
CollectionSubPreparer.prepare
python
def prepare(self, data): result = [] for item in self.get_inner_data(data): result.append(self.preparer.prepare(item)) return result
Handles passing each item in the collection data to the configured subpreparer. Uses a loop and the ``get_inner_data`` method to provide the correct item of the data. Returns a list of data as the response.
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/preparers.py#L201-L216
[ "def get_inner_data(self, data):\n \"\"\"\n Used internally so that the correct data is extracted out of the\n broader dataset, allowing the preparer being called to deal with just\n the expected subset.\n \"\"\"\n return self.lookup_data(self.lookup, data)\n" ]
class CollectionSubPreparer(SubPreparer): """ A preparation class designed to handle collections of data. This is useful in the case where you have a 1-to-many or many-to-many relationship of data to expose as part of the parent data. Example:: # First, set up a preparer that handles the ...
toastdriven/restless
restless/dj.py
DjangoResource.build_url_name
python
def build_url_name(cls, name, name_prefix=None): if name_prefix is None: name_prefix = 'api_{}'.format( cls.__name__.replace('Resource', '').lower() ) name_prefix = name_prefix.rstrip('_') return '_'.join([name_prefix, name])
Given a ``name`` & an optional ``name_prefix``, this generates a name for a URL. :param name: The name for the URL (ex. 'detail') :type name: string :param name_prefix: (Optional) A prefix for the URL's name (for resolving). The default is ``None``, which will autocreate a ...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/dj.py#L90-L113
null
class DjangoResource(Resource): """ A Django-specific ``Resource`` subclass. Doesn't require any special configuration, but helps when working in a Django environment. """ def serialize_list(self, data): if data is None: return super(DjangoResource, self).serialize_list(dat...
toastdriven/restless
restless/dj.py
DjangoResource.urls
python
def urls(cls, name_prefix=None): return [ url(r'^$', cls.as_list(), name=cls.build_url_name('list', name_prefix)), url(r'^(?P<pk>[\w-]+)/$', cls.as_detail(), name=cls.build_url_name('detail', name_prefix)), ]
A convenience method for hooking up the URLs. This automatically adds a list & a detail endpoint to your URLconf. :param name_prefix: (Optional) A prefix for the URL's name (for resolving). The default is ``None``, which will autocreate a prefix based on the class name. Ex: ``B...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/dj.py#L116-L133
[ "def as_list(self, *args, **kwargs):\n return csrf_exempt(super(DjangoResource, self).as_list(*args, **kwargs))\n", "def as_detail(self, *args, **kwargs):\n return csrf_exempt(super(DjangoResource, self).as_detail(*args, **kwargs))\n", "def build_url_name(cls, name, name_prefix=None):\n \"\"\"\n Giv...
class DjangoResource(Resource): """ A Django-specific ``Resource`` subclass. Doesn't require any special configuration, but helps when working in a Django environment. """ def serialize_list(self, data): if data is None: return super(DjangoResource, self).serialize_list(dat...
toastdriven/restless
restless/fl.py
FlaskResource.build_endpoint_name
python
def build_endpoint_name(cls, name, endpoint_prefix=None): if endpoint_prefix is None: endpoint_prefix = 'api_{}'.format( cls.__name__.replace('Resource', '').lower() ) endpoint_prefix = endpoint_prefix.rstrip('_') return '_'.join([endpoint_prefix, name])
Given a ``name`` & an optional ``endpoint_prefix``, this generates a name for a URL. :param name: The name for the URL (ex. 'detail') :type name: string :param endpoint_prefix: (Optional) A prefix for the URL's name (for resolving). The default is ``None``, which will autoc...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/fl.py#L59-L82
null
class FlaskResource(Resource): """ A Flask-specific ``Resource`` subclass. Doesn't require any special configuration, but helps when working in a Flask environment. """ @classmethod def as_list(cls, *init_args, **init_kwargs): # Overridden here, because Flask uses a global ``request...
toastdriven/restless
restless/fl.py
FlaskResource.add_url_rules
python
def add_url_rules(cls, app, rule_prefix, endpoint_prefix=None): methods = ['GET', 'POST', 'PUT', 'DELETE'] app.add_url_rule( rule_prefix, endpoint=cls.build_endpoint_name('list', endpoint_prefix), view_func=cls.as_list(), methods=methods ) ...
A convenience method for hooking up the URLs. This automatically adds a list & a detail endpoint to your routes. :param app: The ``Flask`` object for your app. :type app: ``flask.Flask`` :param rule_prefix: The start of the URL to handle. :type rule_prefix: string :pa...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/fl.py#L85-L118
[ "def as_list(cls, *init_args, **init_kwargs):\n # Overridden here, because Flask uses a global ``request`` object\n # rather than passing it to each view.\n def _wrapper(*args, **kwargs):\n # Make a new instance so that no state potentially leaks between\n # instances.\n inst = cls(*in...
class FlaskResource(Resource): """ A Flask-specific ``Resource`` subclass. Doesn't require any special configuration, but helps when working in a Flask environment. """ @classmethod def as_list(cls, *init_args, **init_kwargs): # Overridden here, because Flask uses a global ``request...
toastdriven/restless
restless/pyr.py
PyramidResource.build_routename
python
def build_routename(cls, name, routename_prefix=None): if routename_prefix is None: routename_prefix = 'api_{}'.format( cls.__name__.replace('Resource', '').lower() ) routename_prefix = routename_prefix.rstrip('_') return '_'.join([routename_prefix, name]...
Given a ``name`` & an optional ``routename_prefix``, this generates a name for a URL. :param name: The name for the URL (ex. 'detail') :type name: string :param routename_prefix: (Optional) A prefix for the URL's name (for resolving). The default is ``None``, which will aut...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/pyr.py#L41-L64
null
class PyramidResource(Resource): """ A Pyramid-specific ``Resource`` subclass. Doesn't require any special configuration, but helps when working in a Pyramid environment. """ @classmethod def as_list(cls, *args, **kwargs): return super(PyramidResource, cls).as_list(*args, **kwargs)...
toastdriven/restless
restless/pyr.py
PyramidResource.add_views
python
def add_views(cls, config, rule_prefix, routename_prefix=None): methods = ('GET', 'POST', 'PUT', 'DELETE') config.add_route( cls.build_routename('list', routename_prefix), rule_prefix ) config.add_view( cls.as_list(), route_name=cls.build_...
A convenience method for registering the routes and views in pyramid. This automatically adds a list and detail endpoint to your routes. :param config: The pyramid ``Configurator`` object for your app. :type config: ``pyramid.config.Configurator`` :param rule_prefix: The start of the ...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/pyr.py#L67-L107
[ "def as_list(cls, *args, **kwargs):\n return super(PyramidResource, cls).as_list(*args, **kwargs)\n", "def as_detail(cls, *init_args, **init_kwargs):\n def _wrapper(request):\n # Make a new instance so that no state potentially leaks between\n # instances.\n inst = cls(*init_args, **ini...
class PyramidResource(Resource): """ A Pyramid-specific ``Resource`` subclass. Doesn't require any special configuration, but helps when working in a Pyramid environment. """ @classmethod def as_list(cls, *args, **kwargs): return super(PyramidResource, cls).as_list(*args, **kwargs)...
toastdriven/restless
restless/serializers.py
JSONSerializer.deserialize
python
def deserialize(self, body): try: if isinstance(body, bytes): return json.loads(body.decode('utf-8')) return json.loads(body) except ValueError: raise BadRequest('Request body is not valid JSON')
The low-level deserialization. Underpins ``deserialize``, ``deserialize_list`` & ``deserialize_detail``. Has no built-in smarts, simply loads the JSON. :param body: The body of the current request :type body: string :returns: The deserialized data :rtype: ``li...
train
https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/serializers.py#L47-L67
null
class JSONSerializer(Serializer): def serialize(self, data): """ The low-level serialization. Underpins ``serialize``, ``serialize_list`` & ``serialize_detail``. Has no built-in smarts, simply dumps the JSON. :param data: The body for the response :type d...
jasonrollins/shareplum
shareplum/shareplum.py
Office365.GetSecurityToken
python
def GetSecurityToken(self, username, password): url = 'https://login.microsoftonline.com/extSTS.srf' body = """ <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open...
Grabs a security Token to authenticate to Office 365 services
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L20-L68
null
class Office365(object): """ Class to authenticate Office 365 Sharepoint """ def __init__(self, share_point_site, username, password): self.Username = username self.Password = password self.share_point_site = share_point_site def GetCookies(self): """ Grabs...
jasonrollins/shareplum
shareplum/shareplum.py
Office365.GetCookies
python
def GetCookies(self): sectoken = self.GetSecurityToken(self.Username, self.Password) url = self.share_point_site+ '/_forms/default.aspx?wa=wsignin1.0' response = requests.post(url, data=sectoken) return response.cookies
Grabs the cookies form your Office Sharepoint site and uses it as Authentication for the rest of the calls
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L70-L78
[ "def GetSecurityToken(self, username, password):\n \"\"\"\n Grabs a security Token to authenticate to Office 365 services\n \"\"\"\n url = 'https://login.microsoftonline.com/extSTS.srf'\n body = \"\"\"\n <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"\n xmlns:a...
class Office365(object): """ Class to authenticate Office 365 Sharepoint """ def __init__(self, share_point_site, username, password): self.Username = username self.Password = password self.share_point_site = share_point_site def GetSecurityToken(self, username, password): ...
jasonrollins/shareplum
shareplum/shareplum.py
Site.AddList
python
def AddList(self, listName, description, templateID): templateIDs = {'Announcements': '104', 'Contacts': '105', 'Custom List': '100', 'Custom List in Datasheet View': '120', 'DataSources': '110', '...
Create a new List Provide: List Name, List Description, and List Template Templates Include: Announcements Contacts Custom List Custom List in Datasheet View DataSources Discussion Board Docume...
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L140-L205
[ "def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n", "def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soa...
class Site(object): """Connect to SharePoint Site """ def __init__(self, site_url, auth=None,authcookie=None, verify_ssl=True, ssl_version=None, huge_tree=False, timeout=None): self.site_url = site_url self._verify_ssl = verify_ssl self._session = requests.Session() if ssl_...
jasonrollins/shareplum
shareplum/shareplum.py
Site.DeleteList
python
def DeleteList(self, listName): # Build Request soap_request = soap('DeleteList') soap_request.add_parameter('listName', listName) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Lists'), ...
Delete a List with given name
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L207-L226
[ "def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n", "def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soa...
class Site(object): """Connect to SharePoint Site """ def __init__(self, site_url, auth=None,authcookie=None, verify_ssl=True, ssl_version=None, huge_tree=False, timeout=None): self.site_url = site_url self._verify_ssl = verify_ssl self._session = requests.Session() if ssl_...
jasonrollins/shareplum
shareplum/shareplum.py
Site.GetListCollection
python
def GetListCollection(self): # Build Request soap_request = soap('GetListCollection') self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('SiteData'), headers=self._headers('GetListCollection'), ...
Returns List information for current Site
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L228-L257
[ "def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n", "def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soa...
class Site(object): """Connect to SharePoint Site """ def __init__(self, site_url, auth=None,authcookie=None, verify_ssl=True, ssl_version=None, huge_tree=False, timeout=None): self.site_url = site_url self._verify_ssl = verify_ssl self._session = requests.Session() if ssl_...
jasonrollins/shareplum
shareplum/shareplum.py
Site.GetUsers
python
def GetUsers(self, rowlimit=0): # Build Request soap_request = soap('GetListItems') soap_request.add_parameter('listName', 'UserInfo') # Set Row Limit soap_request.add_parameter('rowLimit', str(rowlimit)) self.last_request = str(soap_request) # Send Request ...
Get Items from current list rowlimit defaulted to 0 (no limit)
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L259-L293
[ "def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n", "def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soa...
class Site(object): """Connect to SharePoint Site """ def __init__(self, site_url, auth=None,authcookie=None, verify_ssl=True, ssl_version=None, huge_tree=False, timeout=None): self.site_url = site_url self._verify_ssl = verify_ssl self._session = requests.Session() if ssl_...
jasonrollins/shareplum
shareplum/shareplum.py
Site.List
python
def List(self, listName, exclude_hidden_fields=False): return _List(self._session, listName, self._url, self._verify_ssl, self.users, self.huge_tree, self.timeout, exclude_hidden_fields=exclude_hidden_fields)
Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files.
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L297-L303
null
class Site(object): """Connect to SharePoint Site """ def __init__(self, site_url, auth=None,authcookie=None, verify_ssl=True, ssl_version=None, huge_tree=False, timeout=None): self.site_url = site_url self._verify_ssl = verify_ssl self._session = requests.Session() if ssl_...
jasonrollins/shareplum
shareplum/shareplum.py
_List._convert_to_internal
python
def _convert_to_internal(self, data): """From 'Column Title' to 'Column_x0020_Title'""" for _dict in data: keys = list(_dict.keys())[:] for key in keys: if key not in self._disp_cols: raise Exception(key + ' not a column in current List.') ...
From 'Column Title' to 'Column_x0020_Title
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L358-L365
[ "def _sp_type(self, key, value):\n \"\"\"Returns proper type from the schema\"\"\"\n try:\n field_type = self._disp_cols[key]['type']\n if field_type in ['Number', 'Currency']:\n return value\n elif field_type == 'DateTime':\n return value.strftime('%Y-%m-%d %H:%M:%S...
class _List(object): """Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. """ def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclud...
jasonrollins/shareplum
shareplum/shareplum.py
_List._convert_to_display
python
def _convert_to_display(self, data): """From 'Column_x0020_Title' to 'Column Title'""" for _dict in data: keys = list(_dict.keys())[:] for key in keys: if key not in self._sp_cols: raise Exception(key + ' not a column in current List.') ...
From 'Column_x0020_Title' to 'Column Title
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L367-L374
null
class _List(object): """Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. """ def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclud...
jasonrollins/shareplum
shareplum/shareplum.py
_List._python_type
python
def _python_type(self, key, value): try: field_type = self._sp_cols[key]['type'] if field_type in ['Number', 'Currency']: return float(value) elif field_type == 'DateTime': # Need to remove the '123;#' from created dates, but we will do it fo...
Returns proper type from the schema
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L376-L411
null
class _List(object): """Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. """ def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclud...
jasonrollins/shareplum
shareplum/shareplum.py
_List._sp_type
python
def _sp_type(self, key, value): try: field_type = self._disp_cols[key]['type'] if field_type in ['Number', 'Currency']: return value elif field_type == 'DateTime': return value.strftime('%Y-%m-%d %H:%M:%S') elif field_type == 'Boole...
Returns proper type from the schema
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L413-L433
null
class _List(object): """Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. """ def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclud...
jasonrollins/shareplum
shareplum/shareplum.py
_List.GetListItems
python
def GetListItems(self, viewname=None, fields=None, query=None, rowlimit=0, debug=False): # Build Request soap_request = soap('GetListItems') soap_request.add_parameter('listName', self.listName) # Convert Displayed View Name to View ID if viewname: soap_request.add_p...
Get Items from current list rowlimit defaulted to 0 (unlimited)
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L435-L521
[ "def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n", "def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soa...
class _List(object): """Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. """ def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclud...
jasonrollins/shareplum
shareplum/shareplum.py
_List.GetList
python
def GetList(self): # Build Request soap_request = soap('GetList') soap_request.add_parameter('listName', self.listName) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Lists'), heade...
Get Info on Current List This is run in __init__ so you don't have to run it again. Access from self.schema
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L523-L560
[ "def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n", "def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soa...
class _List(object): """Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. """ def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclud...
jasonrollins/shareplum
shareplum/shareplum.py
_List.GetView
python
def GetView(self, viewname): # Build Request soap_request = soap('GetView') soap_request.add_parameter('listName', self.listName) if viewname == None: views = self.GetViewCollection() for view in views: if 'DefaultView' in view: ...
Get Info on View Name
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L562-L600
[ "def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n", "def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soa...
class _List(object): """Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. """ def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclud...
jasonrollins/shareplum
shareplum/shareplum.py
_List.GetViewCollection
python
def GetViewCollection(self): # Build Request soap_request = soap('GetViewCollection') soap_request.add_parameter('listName', self.listName) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Views'), ...
Get Views for Current List This is run in __init__ so you don't have to run it again. Access from self.views
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L602-L634
[ "def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n", "def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soa...
class _List(object): """Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. """ def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclud...
jasonrollins/shareplum
shareplum/shareplum.py
_List.UpdateListItems
python
def UpdateListItems(self, data, kind): if type(data) != list: raise Exception('data must be a list of dictionaries') # Build Request soap_request = soap('UpdateListItems') soap_request.add_parameter('listName', self.listName) if kind != 'Delete': self._con...
Update List Items kind = 'New', 'Update', or 'Delete' New: Provide data like so: data = [{'Title': 'New Title', 'Col1': 'New Value'}] Update: Provide data like so: data = [{'ID': 23, 'Title': 'Updated Title'}, ...
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L658-L704
[ "def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n", "def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soa...
class _List(object): """Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. """ def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclud...
jasonrollins/shareplum
shareplum/shareplum.py
_List.GetAttachmentCollection
python
def GetAttachmentCollection(self, _id): # Build Request soap_request = soap('GetAttachmentCollection') soap_request.add_parameter('listName', self.listName) soap_request.add_parameter('listItemID', _id) self.last_request = str(soap_request) # Send Request respon...
Get Attachments for given List Item ID
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L706-L731
[ "def _url(self, service):\n \"\"\"Full SharePoint Service URL\"\"\"\n return ''.join([self.site_url, self._services_url[service]])\n", "def _headers(self, soapaction):\n headers = {\"Content-Type\": \"text/xml; charset=UTF-8\",\n \"SOAPAction\": \"http://schemas.microsoft.com/sharepoint/soa...
class _List(object): """Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. """ def __init__(self, session, listName, url, verify_ssl, users, huge_tree, timeout, exclud...
jasonrollins/shareplum
shareplum/ListDict.py
changes
python
def changes(new_cmp_dict, old_cmp_dict, id_column, columns): update_ldict = [] same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict)) for same_key in same_keys: # Get the Union of the set of keys # for both dictionaries to account # for missing keys old_dict = old_cmp...
Return a list dict of the changes of the rows that exist in both dictionaries User must provide an ID column for old_cmp_dict
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L4-L33
null
# This is a group of small functions # used to work with a list of dictionaries def unique(new_cmp_dict, old_cmp_dict): """Return a list dict of the unique keys in new_cmp_dict """ newkeys = set(new_cmp_dict) oldkeys = set(old_cmp_dict) unique = newkeys - oldkeys unique_ldict = [] f...
jasonrollins/shareplum
shareplum/ListDict.py
unique
python
def unique(new_cmp_dict, old_cmp_dict): newkeys = set(new_cmp_dict) oldkeys = set(old_cmp_dict) unique = newkeys - oldkeys unique_ldict = [] for key in unique: unique_ldict.append(new_cmp_dict[key]) return unique_ldict
Return a list dict of the unique keys in new_cmp_dict
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L35-L45
null
# This is a group of small functions # used to work with a list of dictionaries def changes(new_cmp_dict, old_cmp_dict, id_column, columns): """Return a list dict of the changes of the rows that exist in both dictionaries User must provide an ID column for old_cmp_dict """ update_ldict = [] ...
jasonrollins/shareplum
shareplum/ListDict.py
full_dict
python
def full_dict(ldict, keys): if type(keys) == str: keys = [keys] else: keys = keys cmp_dict = {} for line in ldict: index = [] for key in keys: index.append(str(line.get(key, ''))) index = '-'.join(index) cmp_dict[index] = line return cmp_...
Return Comparison Dictionaries from list dict on keys keys: a list of keys that when combined make the row in the list unique
train
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L47-L66
null
# This is a group of small functions # used to work with a list of dictionaries def changes(new_cmp_dict, old_cmp_dict, id_column, columns): """Return a list dict of the changes of the rows that exist in both dictionaries User must provide an ID column for old_cmp_dict """ update_ldict = [] ...
sloria/konch
docopt.py
transform
python
def transform(pattern): result = [] groups = [[pattern]] while groups: children = groups.pop(0) parents = [Required, Optional, OptionsShortcut, Either, OneOrMore] if any(t in map(type, children) for t in parents): child = [c for c in children if type(c) in parents][0] ...
Expand pattern into an (almost) equivalent one, but with single Either. Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d) Quirks: [-a] => (-a), (-a...) => (-a -a)
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L73-L97
null
# flake8: noqa """Pythonic command-line interface parser that will make you smile. * http://docopt.org * Repository and issue-tracker: https://github.com/docopt/docopt * Licensed under terms of MIT license (see LICENSE-MIT) * Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com """ import sys import re _...
sloria/konch
docopt.py
parse_long
python
def parse_long(tokens, options): long, eq, value = tokens.move().partition('=') assert long.startswith('--') value = None if eq == value == '' else value similar = [o for o in options if o.long == long] if tokens.error is DocoptExit and similar == []: # if no exact match similar = [o for o ...
long ::= '--' chars [ ( ' ' | '=' ) chars ] ;
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L302-L332
null
# flake8: noqa """Pythonic command-line interface parser that will make you smile. * http://docopt.org * Repository and issue-tracker: https://github.com/docopt/docopt * Licensed under terms of MIT license (see LICENSE-MIT) * Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com """ import sys import re _...
sloria/konch
docopt.py
parse_shorts
python
def parse_shorts(tokens, options): token = tokens.move() assert token.startswith('-') and not token.startswith('--') left = token.lstrip('-') parsed = [] while left != '': short, left = '-' + left[0], left[1:] similar = [o for o in options if o.short == short] if len(similar)...
shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L335-L367
null
# flake8: noqa """Pythonic command-line interface parser that will make you smile. * http://docopt.org * Repository and issue-tracker: https://github.com/docopt/docopt * Licensed under terms of MIT license (see LICENSE-MIT) * Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com """ import sys import re _...
sloria/konch
docopt.py
docopt
python
def docopt(doc, argv=None, help=True, version=None, options_first=False): argv = sys.argv[1:] if argv is None else argv usage_sections = parse_section('usage:', doc) if len(usage_sections) == 0: raise DocoptLanguageError('"usage:" (case-insensitive) not found.') if len(usage_sections) > 1: ...
Parse `argv` based on command-line interface described in `doc`. `docopt` creates your command-line interface based on its description that you pass as `doc`. Such description can contain --options, <positional-argument>, commands, which could be [optional], (required), (mutually | exclusive) or repeat...
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L491-L582
[ "def extras(help, version, options, doc):\n if help and any((o.name in ('-h', '--help')) and o.value for o in options):\n print(doc.strip(\"\\n\"))\n sys.exit()\n if version and any(o.name == '--version' and o.value for o in options):\n print(version)\n sys.exit()\n", "def parse_...
# flake8: noqa """Pythonic command-line interface parser that will make you smile. * http://docopt.org * Repository and issue-tracker: https://github.com/docopt/docopt * Licensed under terms of MIT license (see LICENSE-MIT) * Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com """ import sys import re _...
sloria/konch
docopt.py
Pattern.fix_identities
python
def fix_identities(self, uniq=None): if not hasattr(self, 'children'): return self uniq = list(set(self.flat())) if uniq is None else uniq for i, child in enumerate(self.children): if not hasattr(child, 'children'): assert child in uniq sel...
Make pattern-tree tips point to same object if they are equal.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L46-L56
null
class Pattern(object): def __eq__(self, other): return repr(self) == repr(other) def __hash__(self): return hash(repr(self)) def fix(self): self.fix_identities() self.fix_repeating_arguments() return self def fix_repeating_arguments(self): """Fix elem...
sloria/konch
docopt.py
Pattern.fix_repeating_arguments
python
def fix_repeating_arguments(self): either = [list(child.children) for child in transform(self).children] for case in either: for e in [child for child in case if case.count(child) > 1]: if type(e) is Argument or type(e) is Option and e.argcount: if e.value...
Fix elements that should accumulate/increment values.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L58-L70
[ "def transform(pattern):\n \"\"\"Expand pattern into an (almost) equivalent one, but with single Either.\n\n Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)\n Quirks: [-a] => (-a), (-a...) => (-a -a)\n\n \"\"\"\n result = []\n groups = [[pattern]]\n while groups:\n chil...
class Pattern(object): def __eq__(self, other): return repr(self) == repr(other) def __hash__(self): return hash(repr(self)) def fix(self): self.fix_identities() self.fix_repeating_arguments() return self def fix_identities(self, uniq=None): """Make pa...
sloria/konch
setup.py
find_version
python
def find_version(fname): version = "" with open(fname, "r") as fp: reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]') for line in fp: m = reg.match(line) if m: version = m.group(1) break if not version: raise RuntimeError("C...
Attempts to find the version number in the file names fname. Raises RuntimeError if not found.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/setup.py#L46-L60
null
import re from setuptools import setup, Command EXTRAS_REQUIRE = { "tests": ["pytest", "mock", "scripttest==1.3", "ipython", "bpython"], "lint": [ "mypy==0.701", "flake8==3.7.7", "flake8-bugbear==19.3.0", "pre-commit==1.15.2", ], } EXTRAS_REQUIRE["dev"] = ( EXTRAS_REQUI...
sloria/konch
konch.py
format_context
python
def format_context( context: Context, formatter: typing.Union[str, Formatter] = "full" ) -> str: if not context: return "" if callable(formatter): formatter_func = formatter else: if formatter in CONTEXT_FORMATTERS: formatter_func = CONTEXT_FORMATTERS[formatter] ...
Output the a context dictionary as a string.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L245-L259
[ "def my_formatter(ctx):\n return \"*\".join(sorted(ctx.keys()))\n" ]
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
make_banner
python
def make_banner( text: typing.Optional[str] = None, context: typing.Optional[Context] = None, banner_template: typing.Optional[str] = None, context_format: ContextFormat = "full", ) -> str: banner_text = text or speak() banner_template = banner_template or BANNER_TEMPLATE ctx = format_contex...
Generates a full banner with version info, the given text, and a formatted list of context variables.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L269-L282
[ "def format_context(\n context: Context, formatter: typing.Union[str, Formatter] = \"full\"\n) -> str:\n \"\"\"Output the a context dictionary as a string.\"\"\"\n if not context:\n return \"\"\n\n if callable(formatter):\n formatter_func = formatter\n else:\n if formatter in CON...
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
context_list2dict
python
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context: return {obj.__name__.split(".")[-1]: obj for obj in context_list}
Converts a list of objects (functions, classes, or modules) to a dictionary mapping the object names to the objects.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L285-L289
null
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
start
python
def start( context: typing.Optional[typing.Mapping] = None, banner: typing.Optional[str] = None, shell: typing.Type[Shell] = AutoShell, prompt: typing.Optional[str] = None, output: typing.Optional[str] = None, context_format: str = "full", **kwargs: typing.Any, ) -> None: logger.debug(f"...
Start up the konch shell. Takes the same parameters as Shell.__init__.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L794-L825
[ "def speak() -> str:\n return random.choice(CONCHES)\n", "def start(self) -> None:\n shell_args = {\n \"context\": self.context,\n \"banner\": self.banner,\n \"prompt\": self.prompt,\n \"output\": self.output,\n \"context_format\": self.context_format,\n }\n shell_ar...
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
config
python
def config(config_dict: typing.Mapping) -> Config: logger.debug(f"Updating with {config_dict}") _cfg.update(config_dict) return _cfg
Configures the konch shell. This function should be called in a .konchrc file. :param dict config_dict: Dict that may contain 'context', 'banner', and/or 'shell' (default shell class to use).
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L828-L837
null
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
named_config
python
def named_config(name: str, config_dict: typing.Mapping) -> None: names = ( name if isinstance(name, Iterable) and not isinstance(name, (str, bytes)) else [name] ) for each in names: _config_registry[each] = Config(**config_dict)
Adds a named config to the config registry. The first argument may either be a string or a collection of strings. This function should be called in a .konchrc file.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L840-L852
null
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
__ensure_directory_in_path
python
def __ensure_directory_in_path(filename: Path) -> None: directory = Path(filename).parent.resolve() if directory not in sys.path: logger.debug(f"Adding {directory} to sys.path") sys.path.insert(0, str(directory))
Ensures that a file's directory is in the Python path.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L861-L867
null
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
confirm
python
def confirm(text: str, default: bool = False) -> bool: choices = "Y/n" if default else "y/N" prompt = f"{style(text, bold=True)} [{choices}]: " while 1: try: print(prompt, end="") value = input("").lower().strip() except (KeyboardInterrupt, EOFError): sys....
Display a confirmation prompt.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L875-L895
[ "def style(\n text: str,\n fg: typing.Optional[int] = None,\n *,\n bold: bool = False,\n file: typing.IO = sys.stdout,\n) -> str:\n use_color = not os.environ.get(\"NO_COLOR\") and file.isatty()\n if use_color:\n parts = [\n fg and f\"\\033[{fg}m\",\n bold and f\"\\...
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
use_file
python
def use_file( filename: typing.Union[Path, str, None], trust: bool = False ) -> typing.Union[types.ModuleType, None]: config_file = filename or resolve_path(CONFIG_FILE) def preview_unauthorized() -> None: if not config_file: return None print(SEPARATOR, file=sys.stderr) ...
Load filename as a python file. Import ``filename`` and return it as a module.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L898-L954
[ "def resolve_path(filename: Path) -> typing.Union[Path, None]:\n \"\"\"Find a file by walking up parent directories until the file is found.\n Return the absolute path of the file.\n \"\"\"\n current = Path.cwd()\n # Stop search at home directory\n sentinel_dir = Path.home().parent.resolve()\n ...
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
resolve_path
python
def resolve_path(filename: Path) -> typing.Union[Path, None]: current = Path.cwd() # Stop search at home directory sentinel_dir = Path.home().parent.resolve() while current != sentinel_dir: target = Path(current) / Path(filename) if target.exists(): return target.resolve() ...
Find a file by walking up parent directories until the file is found. Return the absolute path of the file.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L957-L971
null
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
parse_args
python
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]: return docopt(__doc__, argv=argv, version=__version__)
Exposes the docopt command-line arguments parser. Return a dictionary of arguments.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L1132-L1136
[ "def docopt(doc, argv=None, help=True, version=None, options_first=False):\n \"\"\"Parse `argv` based on command-line interface described in `doc`.\n\n `docopt` creates your command-line interface based on its\n description that you pass as `doc`. Such description can contain\n --options, <positional-ar...
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
main
python
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn: args = parse_args(argv) if args["--debug"]: logging.basicConfig( format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG ) logger.debug(args) config_file: typing.Union[Path, None] ...
Main entry point for the konch CLI.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L1139-L1184
[ "def start(\n context: typing.Optional[typing.Mapping] = None,\n banner: typing.Optional[str] = None,\n shell: typing.Type[Shell] = AutoShell,\n prompt: typing.Optional[str] = None,\n output: typing.Optional[str] = None,\n context_format: str = \"full\",\n **kwargs: typing.Any,\n) -> None:\n ...
#!/usr/bin/env python3 """konch: Customizes your Python shell. Usage: konch konch init [<config_file>] [-d] konch edit [<config_file>] [-d] konch allow [<config_file>] [-d] konch deny [<config_file>] [-d] konch [--name=<name>] [--file=<file>] [--shell=<shell_name>] [-d] Options: -h --help ...
sloria/konch
konch.py
IPythonShell.init_autoreload
python
def init_autoreload(mode: int) -> None: from IPython.extensions import autoreload ip = get_ipython() # type: ignore # noqa: F821 autoreload.load_ipython_extension(ip) ip.magics_manager.magics["line"]["autoreload"](str(mode))
Load and initialize the IPython autoreload extension.
train
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L427-L433
null
class IPythonShell(Shell): """The IPython shell. :param list ipy_extensions: List of IPython extension names to load upon startup. :param bool ipy_autoreload: Whether to load and initialize the IPython autoreload extension upon startup. Can also be an integer, which will be passed as the ar...
GiulioRossetti/ndlib
ndlib/models/opinions/CognitiveOpDynModel.py
CognitiveOpDynModel.set_initial_status
python
def set_initial_status(self, configuration=None): super(CognitiveOpDynModel, self).set_initial_status(configuration) # set node status for node in self.status: self.status[node] = np.random.random_sample() self.initial_status = self.status.copy() # set new node para...
Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. Generates random node profiles.
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/CognitiveOpDynModel.py#L92-L133
[ "def set_initial_status(self, configuration):\n \"\"\"\n Set the initial model configuration\n\n :param configuration: a ```ndlib.models.ModelConfig.Configuration``` object\n \"\"\"\n\n self.__validate_configuration(configuration)\n\n nodes_cfg = configuration.get_nodes_configuration()\n # Set ...
class CognitiveOpDynModel(DiffusionModel): """ Model Parameters to be specified via ModelConfig :param I: external information value in [0,1] :param T_range_min: the minimum of the range of initial values for T. Range [0,1]. :param T_range_max: the maximum of the range of initial values for T. Ra...
GiulioRossetti/ndlib
ndlib/models/opinions/CognitiveOpDynModel.py
CognitiveOpDynModel.iteration
python
def iteration(self, node_status=True): # One iteration changes the opinion of all agents using the following procedure: # - first all agents communicate with institutional information I using a deffuant like rule # - then random pairs of agents are selected to interact (N pairs) # - int...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/CognitiveOpDynModel.py#L140-L220
[ "def clean_initial_status(self, valid_status=None):\n for n, s in future.utils.iteritems(self.status):\n if s > 1 or s < 0:\n self.status[n] = 0\n", "def status_delta(self, actual_status):\n \"\"\"\n Compute the point-to-point variations for each status w.r.t. the previous system config...
class CognitiveOpDynModel(DiffusionModel): """ Model Parameters to be specified via ModelConfig :param I: external information value in [0,1] :param T_range_min: the minimum of the range of initial values for T. Range [0,1]. :param T_range_max: the maximum of the range of initial values for T. Ra...
GiulioRossetti/ndlib
ndlib/models/epidemics/GeneralisedThresholdModel.py
GeneralisedThresholdModel.iteration
python
def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: self.actual_iteration += 1 self.params['model']['qu...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/epidemics/GeneralisedThresholdModel.py#L58-L115
[ "def clean_initial_status(self, valid_status=None):\n \"\"\"\n Check the consistency of initial status\n :param valid_status: valid node configurations\n \"\"\"\n for n, s in future.utils.iteritems(self.status):\n if s not in valid_status:\n self.status[n] = 0\n" ]
class GeneralisedThresholdModel(DiffusionModel): """ Node Parameters to be specified via ModelConfig :param threshold: The node threshold. If not specified otherwise a value of 0.1 is assumed for all nodes. """ def __init__(self, graph): """ Model Constructor ...
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_node_configuration
python
def add_node_configuration(self, param_name, node_id, param_value): if param_name not in self.config['nodes']: self.config['nodes'][param_name] = {node_id: param_value} else: self.config['nodes'][param_name][node_id] = param_value
Set a parameter for a given node :param param_name: parameter identifier (as specified by the chosen model) :param node_id: node identifier :param param_value: parameter value
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L72-L83
null
class Configuration(object): """ Configuration Object """ def __init__(self): self.config = { 'nodes': {}, 'edges': {}, 'model': {}, 'status': {} } def get_nodes_configuration(self): """ Nodes configurations ...
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_node_set_configuration
python
def add_node_set_configuration(self, param_name, node_to_value): for nid, val in future.utils.iteritems(node_to_value): self.add_node_configuration(param_name, nid, val)
Set Nodes parameter :param param_name: parameter identifier (as specified by the chosen model) :param node_to_value: dictionary mapping each node a parameter value
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L85-L93
[ "def add_node_configuration(self, param_name, node_id, param_value):\n \"\"\"\n Set a parameter for a given node\n\n :param param_name: parameter identifier (as specified by the chosen model)\n :param node_id: node identifier\n :param param_value: parameter value\n \"\"\"\n if param_name not in...
class Configuration(object): """ Configuration Object """ def __init__(self): self.config = { 'nodes': {}, 'edges': {}, 'model': {}, 'status': {} } def get_nodes_configuration(self): """ Nodes configurations ...