code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
prim = cls()
for coord in coordinates:
pm = PseudoMonomer(ampal_parent=prim)
pa = PseudoAtom(coord, ampal_parent=pm)
pm.atoms = OrderedDict([('CA', pa)])
prim.append(pm)
prim.relabel_all()
return prim | def from_coordinates(cls, coordinates) | Creates a `Primitive` from a list of coordinates. | 6.555618 | 6.337419 | 1.03443 |
rprs = [distance(self[i]['CA'], self[i + 1]['CA'])
for i in range(len(self) - 1)]
rprs.append(None)
return rprs | def rise_per_residue(self) | The rise per residue at each point on the Primitive.
Notes
-----
Each element of the returned list is the rise per residue,
at a point on the Primitive. Element i is the distance
between primitive[i] and primitive[i + 1]. The final value
is None. | 4.629147 | 4.08983 | 1.131868 |
rocs = []
for i in range(len(self)):
if 0 < i < len(self) - 1:
rocs.append(radius_of_circumcircle(
self[i - 1]['CA'], self[i]['CA'], self[i + 1]['CA']))
else:
rocs.append(None)
return rocs | def radii_of_curvature(self) | The radius of curvature at each point on the Polymer primitive.
Notes
-----
Each element of the returned list is the radius of curvature,
at a point on the Polymer primitive. Element i is the radius
of the circumcircle formed from indices [i-1, i, i+1] of the
primitve. T... | 3.352524 | 2.793354 | 1.200179 |
seq = [x.mol_code for x in self._monomers]
return ' '.join(seq) | def sequence(self) | Returns the sequence of the `Polynucleotide` as a string.
Returns
-------
sequence : str
String of the monomer sequence of the `Polynucleotide`. | 9.367103 | 9.359747 | 1.000786 |
if not path:
if type(pdb) == str:
pdb = pdb.encode()
try:
temp_pdb = tempfile.NamedTemporaryFile(delete=False)
temp_pdb.write(pdb)
temp_pdb.seek(0)
dssp_out = subprocess.check_output(
[global_settings['dssp']['path'], t... | def run_dssp(pdb, path=True, outfile=None) | Uses DSSP to find helices and extracts helices from a pdb file or string.
Parameters
----------
pdb : str
Path to pdb file or string.
path : bool, optional
Indicates if pdb is a path or a string.
outfile : str, optional
Filepath for storing the dssp output.
Returns
... | 2.087238 | 2.15063 | 0.970524 |
if path:
with open(in_dssp, 'r') as inf:
dssp_out = inf.read()
else:
dssp_out = in_dssp[:]
dssp_residues = []
go = False
for line in dssp_out.splitlines():
if go:
try:
res_num = int(line[5:10].strip())
chain = line[... | def extract_solvent_accessibility_dssp(in_dssp, path=True) | Uses DSSP to extract solvent accessibilty information on every residue.
Notes
-----
For more information on the solvent accessibility metrics used in dssp, see:
http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC
In the dssp files value is labeled 'ACC'.
Parameters
----------
in_dssp... | 3.511914 | 3.290321 | 1.067347 |
from ampal.pdb_parser import split_pdb_lines
dssp_out = subprocess.check_output(
[global_settings['dssp']['path'], in_pdb])
helix = 0
helices = []
h_on = False
for line in dssp_out.splitlines():
dssp_line = line.split()
try:
if dssp_line[4] == 'H':
... | def extract_helices_dssp(in_pdb) | Uses DSSP to find alpha-helices and extracts helices from a pdb file.
Returns a length 3 list with a helix id, the chain id and a dict
containing the coordinates of each residues CA.
Parameters
----------
in_pdb : string
Path to a PDB file. | 2.546655 | 2.535832 | 1.004268 |
t_phi = -75.0
t_phi_d = 29.0
t_psi = 145.0
t_psi_d = 29.0
pph_dssp = subprocess.check_output(
[global_settings['dssp']['path'], in_pdb])
dssp_residues = []
go = False
for line in pph_dssp.splitlines():
if go:
res_num = int(line[:5].strip())
c... | def extract_pp_helices(in_pdb) | Uses DSSP to find polyproline helices in a pdb file.
Returns a length 3 list with a helix id, the chain id and a dict
containing the coordinates of each residues CA.
Parameters
----------
in_pdb : string
Path to a PDB file. | 2.457994 | 2.478995 | 0.991528 |
loops = [' ', 'B', 'S', 'T']
current_ele = None
fragment = []
fragments = []
first = True
for ele in dssp_residues:
if first:
first = False
fragment.append(ele)
elif current_ele in loops:
if ele[1] in loops:
fragment.appen... | def find_ss_regions(dssp_residues) | Separates parsed DSSP data into groups of secondary structure.
Notes
-----
Example: all residues in a single helix/loop/strand will be gathered
into a list, then the next secondary structure element will be
gathered into a separate list, and so on.
Parameters
----------
dssp_residues :... | 2.535975 | 2.510044 | 1.010331 |
# Parse command line arguments
args = get_args()
# Instantiate the TestRail client
# Use the CLI argument to identify which project to work with
tr = TestRail(project_dict[args.project])
# Get a reference to the current project
project = tr.project(project_dict[args.project])
# T... | def main() | This will offer a step by step guide to create a new run in TestRail,
update tests in the run with results, and close the run | 4.471963 | 4.245202 | 1.053416 |
mem_info = {}
if platform.linux_distribution()[0]:
with open('/proc/meminfo') as file:
c = 0
for line in file:
lst = line.split()
if str(lst[0]) == 'MemTotal:':
mem_info['total'] = int(lst[1])
elif str(lst... | def memory() | Determine the machine's memory specifications.
Returns
-------
mem_info : dictonary
Holds the current values for the total, free and used memory of the system. | 2.428287 | 2.433478 | 0.997867 |
mem_free = memory()['free']
if mem_free > 60000000:
chunks_size = int(((mem_free - 10000000) * 1000) / (4 * n * N))
return chunks_size
elif mem_free > 40000000:
chunks_size = int(((mem_free - 7000000) * 1000) / (4 * n * N))
return chunks_size
elif mem_free > 1400000... | def get_chunk_size(N, n) | Given a dimension of size 'N', determine the number of rows or columns
that can fit into memory.
Parameters
----------
N : int
The size of one of the dimension of a two-dimensional array.
n : int
The number of times an 'N' by 'chunks_size' array can fit in memory.
Return... | 1.887797 | 1.867248 | 1.011005 |
if self.api_version == 2:
json = self.request('/floating_ips')
return json['floating_ips']
else:
raise DoError(v2_api_required_str) | def all_floating_ips(self) | Lists all of the Floating IPs available on the account. | 8.588125 | 7.758513 | 1.106929 |
droplet_id = kwargs.get('droplet_id')
region = kwargs.get('region')
if self.api_version == 2:
if droplet_id is not None and region is not None:
raise DoError('Only one of droplet_id and region is required to create a Floating IP. ' \
'Set... | def new_floating_ip(self, **kwargs) | Creates a Floating IP and assigns it to a Droplet or reserves it to a region. | 2.650426 | 2.440815 | 1.085878 |
if self.api_version == 2:
self.request('/floating_ips/' + ip_addr, method='DELETE')
else:
raise DoError(v2_api_required_str) | def destroy_floating_ip(self, ip_addr) | Deletes a Floating IP and removes it from the account. | 7.575467 | 7.327957 | 1.033776 |
if self.api_version == 2:
params = {'type': 'assign','droplet_id': droplet_id}
json = self.request('/floating_ips/' + ip_addr + '/actions', params=params, method='POST')
return json['action']
else:
raise DoError(v2_api_required_str) | def assign_floating_ip(self, ip_addr, droplet_id) | Assigns a Floating IP to a Droplet. | 5.27275 | 5.130366 | 1.027753 |
if self.api_version == 2:
params = {'type': 'unassign'}
json = self.request('/floating_ips/' + ip_addr + '/actions', params=params, method='POST')
return json['action']
else:
raise DoError(v2_api_required_str) | def unassign_floating_ip(self, ip_addr) | Unassign a Floating IP from a Droplet.
The Floating IP will be reserved in the region but not assigned to a Droplet. | 6.185214 | 5.587175 | 1.107038 |
if self.api_version == 2:
json = self.request('/floating_ips/' + ip_addr + '/actions')
return json['actions']
else:
raise DoError(v2_api_required_str) | def list_floating_ip_actions(self, ip_addr) | Retrieve a list of all actions that have been executed on a Floating IP. | 6.815708 | 6.573449 | 1.036854 |
if self.api_version == 2:
json = self.request('/floating_ips/' + ip_addr + '/actions/' + action_id)
return json['action']
else:
raise DoError(v2_api_required_str) | def get_floating_ip_action(self, ip_addr, action_id) | Retrieve the status of a Floating IP action. | 6.273571 | 6.133654 | 1.022811 |
digest = hmac.new(secret, message, hashlib.sha256).digest()
return base64.b64encode(digest) | def raw_sign(message, secret) | Sign a message. | 2.066366 | 2.176037 | 0.949601 |
template = ('Signature keyId="%(keyId)s",algorithm="hmac-sha256",'
'headers="%(headers)s",signature="%(signature)s"')
headers = ['(request-target)', 'host', 'accept', 'date']
return template % {
'keyId': key_id,
'signature': signature,
'headers': ' '.join(headers... | def http_signature(message, key_id, signature) | Return a tuple (message signature, HTTP header message signature). | 2.423373 | 2.389167 | 1.014317 |
match = self.SIGNATURE_RE.search(signature)
if not match:
return None
return match.group(1) | def get_signature_from_signature_string(self, signature) | Return the signature from the signature header or None. | 3.461476 | 2.734364 | 1.265916 |
match = self.SIGNATURE_HEADERS_RE.search(signature)
if not match:
return ['date']
headers_string = match.group(1)
return headers_string.split() | def get_headers_from_signature(self, signature) | Returns a list of headers fields to sign.
According to http://tools.ietf.org/html/draft-cavage-http-signatures-03
section 2.1.3, the headers are optional. If not specified, the single
value of "Date" must be used. | 4.51522 | 3.846837 | 1.173749 |
# Translate as stated in the docs:
# https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.META
header_name = header_name.lower()
if header_name == 'content-type':
return 'CONTENT-TYPE'
elif header_name == 'content-length':
... | def header_canonical(self, header_name) | Translate HTTP headers to Django header names. | 2.539985 | 2.192585 | 1.158443 |
d = {}
for header in signature_headers:
if header == '(request-target)':
continue
d[header] = request.META.get(self.header_canonical(header))
return d | def build_dict_to_sign(self, request, signature_headers) | Build a dict with headers and values used in the signature.
"signature_headers" is a list of lowercase header names. | 3.959368 | 4.07637 | 0.971297 |
path = request.get_full_path()
sent_signature = request.META.get(
self.header_canonical('Authorization'))
signature_headers = self.get_headers_from_signature(sent_signature)
unsigned = self.build_dict_to_sign(request, signature_headers)
# Sign string and com... | def build_signature(self, user_api_key, user_secret, request) | Return the signature for the request. | 4.456148 | 4.350091 | 1.02438 |
s = _1.sub(r'\1_\2', string)
return _2.sub(r'\1_\2', s).lower() | def camel_to_snake_case(string) | Converts 'string' presented in camel case to snake case.
e.g.: CamelCase => snake_case | 4.086844 | 7.358139 | 0.555418 |
params = [('q', query_string.encode("utf-8")), ('format', 'json')]
if no_redirect:
params.append(('no_redirect', 1))
if no_html:
params.append(('no_html', 1))
if skip_disambig:
params.append(('skip_disambig', 1))
return '/?' + urlencode(params) | def url_assembler(query_string, no_redirect=0, no_html=0, skip_disambig=0) | Assembler of parameters for building request query.
Args:
query_string: Query to be passed to DuckDuckGo API.
no_redirect: Skip HTTP redirects (for !bang commands). Default - False.
no_html: Remove HTML from text, e.g. bold and italics. Default - False.
skip_disambig: Skip disambigu... | 1.883103 | 2.304651 | 0.817088 |
if container not in Hook.containers:
raise exc.DuckDuckArgumentError(
"Argument 'container' must be one of the values: "
"{0}".format(', '.join(Hook.containers)))
headers = {"User-Agent": user_agent}
url = url_assembler(
query_string,
no_redirect=no_redi... | def query(query_string, secure=False, container='namedtuple', verbose=False,
user_agent=api.USER_AGENT, no_redirect=False, no_html=False,
skip_disambig=False) | Generates and sends a query to DuckDuckGo API.
Args:
query_string: Query to be passed to DuckDuckGo API.
secure: Use secure SSL/TLS connection. Default - False.
Syntactic sugar is secure_query function which is passed the same
parameters.
container: Indicates how dic... | 2.70955 | 2.992091 | 0.905571 |
global Scanner
try:
cls = str(cls)
mod = __import__(str(module), globals(), locals(), [cls], 1)
Scanner = getattr(mod, cls)
except ImportError:
pass | def _import(module, cls) | A messy way to import library-specific classes.
TODO: I should really make a factory class or something, but I'm lazy.
Plus, factories remind me a lot of java... | 4.225318 | 4.791419 | 0.881851 |
assert len(type_parameters) == 1
klazz = TypeFactory.new(type_dict, *type_parameters[0])
assert isclass(klazz)
assert issubclass(klazz, Object)
return TypeMetaclass('%sList' % klazz.__name__, (ListContainer,), {'TYPE': klazz}) | def create(type_dict, *type_parameters) | Construct a List containing type 'klazz'. | 5.29643 | 4.209941 | 1.258077 |
"Runs the given scent.py file."
mod_name = '.'.join(os.path.basename(filename).split('.')[:-1])
mod_path = os.path.dirname(filename)
if mod_name in sys.modules:
del sys.modules[mod_name]
if mod_path not in set(sys.modules.keys()):
sys.path.insert(0, mod_path)
return ScentModule(... | def load_file(filename) | Runs the given scent.py file. | 4.313875 | 3.579365 | 1.205207 |
if dirname is None:
dirname = os.getcwd()
files = os.listdir(dirname)
if scent not in files:
return None
return load_file(os.path.join(dirname, scent)) | def exec_from_dir(dirname=None, scent="scent.py") | Runs the scent.py file from the given directory (cwd if None given).
Returns module if loaded a scent, None otherwise. | 2.704192 | 2.716863 | 0.995336 |
type_tuple = (type_factory,) + type_parameters
if type_tuple not in type_dict:
factory = TypeFactory.get_factory(type_factory)
reified_type = factory.create(type_dict, *type_parameters)
type_dict[type_tuple] = reified_type
return type_dict[type_tuple] | def new(type_dict, type_factory, *type_parameters) | Create a fully reified type from a type schema. | 2.655422 | 2.283829 | 1.162706 |
type_dict = {}
TypeFactory.new(type_dict, *type_tuple)
deposit = into if (into is not None and isinstance(into, dict)) else {}
for reified_type in type_dict.values():
deposit[reified_type.__name__] = reified_type
return deposit | def load(type_tuple, into=None) | Determine all types touched by loading the type and deposit them into
the particular namespace. | 4.979169 | 4.022284 | 1.237896 |
def l2t(obj):
if isinstance(obj, list):
return tuple(l2t(L) for L in obj)
elif isinstance(obj, dict):
return frozendict(obj)
else:
return obj
return TypeFactory.load(l2t(json_list), into=into) | def load_json(json_list, into=None) | Determine all types touched by loading the type and deposit them into
the particular namespace. | 4.078162 | 3.725062 | 1.09479 |
name, values = type_parameters
assert isinstance(values, (list, tuple))
for value in values:
assert isinstance(value, Compatibility.stringy)
return TypeMetaclass(str(name), (EnumContainer,), { 'VALUES': values }) | def create(type_dict, *type_parameters) | EnumFactory.create(*type_parameters) expects:
enumeration name, (enumeration values) | 8.512126 | 6.770976 | 1.257149 |
if isclass(sig) and issubclass(sig, Object):
return TypeSignature(sig)
elif isinstance(sig, TypeSignature):
return sig | def wrap(sig) | Convert a Python class into a type signature. | 4.651227 | 3.546849 | 1.311369 |
name, parameters = type_parameters
for param in parameters:
assert isinstance(param, tuple)
typemap = dict((attr, TypeSignature.deserialize(param, type_dict))
for attr, param in parameters)
attributes = {'TYPEMAP': typemap}
return TypeMetaclass(str(name), (Structural,),... | def create(type_dict, *type_parameters) | StructFactory.create(*type_parameters) expects:
class name,
((binding requirement1,),
(binding requirement2, bound_to_scope),
...),
((attribute_name1, attribute_sig1 (serialized)),
(attribute_name2, attribute_sig2 ...),
...
(attribute_nameN, ...)) | 8.37396 | 7.597635 | 1.10218 |
mod_time = self._get_modified_time(filepath)
if mod_time > self._watched_files.get(filepath, 0):
self._trigger('modified', filepath)
self._watched_files[filepath] = mod_time | def trigger_modified(self, filepath) | Triggers modified event if the given filepath mod time is newer. | 2.829828 | 2.476154 | 1.142832 |
if os.path.exists(filepath):
self._trigger('created', filepath) | def trigger_created(self, filepath) | Triggers created event if file exists. | 5.129606 | 3.1602 | 1.62319 |
if not os.path.exists(filepath):
self._trigger('deleted', filepath) | def trigger_deleted(self, filepath) | Triggers deleted event if the flie doesn't exist. | 4.767642 | 2.893326 | 1.647807 |
if self._logger is None:
return
s = " ".join([str(m) for m in message])
self._logger.write(s+'\n')
self._logger.flush() | def log(self, *message) | Logs a messate to a defined io stream if available. | 2.504249 | 2.445236 | 1.024134 |
self.log('event: %s' % event_name, *args)
for f in self._events[event_name]:
f(*args, **kwargs) | def _trigger(self, event_name, *args, **kwargs) | Triggers a given event with the following *args and **kwargs
parameters. | 3.757251 | 3.976974 | 0.944751 |
return filepath.endswith('.py') and \
not os.path.basename(filepath).startswith('.') | def default_validator(self, filepath) | The default validator only accepts files ending in .py
(and not prefixed by a period). | 6.248531 | 4.136514 | 1.510579 |
filepath = set(filepath.replace('\\', '/').split('/'))
for p in ('.git', '.hg', '.svn', '.cvs', '.bzr'):
if p in filepath:
return True
return False | def in_repo(self, filepath) | This excludes repository directories because they cause some exceptions
occationally. | 4.010427 | 3.581549 | 1.119746 |
if self.in_repo(filepath):
return False
validators = self._validators
if len(validators) == 0:
validators = [self.default_validator]
if any([hasattr(v, 'runnable') for v in self._validators]):
# case where we select the runnable function by ... | def is_valid_type(self, filepath) | Returns True if the given filepath is a valid watchable filetype.
The filepath can be assumed to be a file (not a directory). | 5.269399 | 5.380917 | 0.979275 |
if event_name not in self.ALL_EVENTS:
raise TypeError(('event_name ("%s") can only be one of the '
'following: %s') % (event_name,
repr(self.ALL_EVENTS)))
if not isinstance(func, collections.Callable):
... | def _modify_event(self, event_name, method, func) | Wrapper to call a list's method from one of the events | 3.456784 | 3.439609 | 1.004993 |
if isinstance(event_name, list) or isinstance(event_name, tuple):
for name in event_name:
self.observe(name, func)
return
self.log(func.__name__, "attached to", event_name)
self._modify_event(event_name, 'append', func) | def observe(self, event_name, func) | event_name := {'created', 'modified', 'deleted'}, list, tuple
Attaches a function to run to a particular event. The function must be
unique to be removed cleanly. Alternatively, event_name can be an list/
tuple if any of the string possibilities to be added on multiple events | 3.418013 | 3.598957 | 0.949723 |
is_new = filepath not in self._watched_files
if trigger_event:
if is_new:
self.trigger_created(filepath)
else:
self.trigger_modified(filepath)
try:
self._watched_files[filepath] = self._get_modified_time(filepath)
... | def _watch_file(self, filepath, trigger_event=True) | Adds the file's modified time into its internal watchlist. | 2.858624 | 2.517464 | 1.135517 |
if filepath not in self._watched_files:
return
if trigger_event:
self.trigger_deleted(filepath)
del self._watched_files[filepath] | def _unwatch_file(self, filepath, trigger_event=True) | Removes the file from the internal watchlist if exists. | 2.807851 | 2.510735 | 1.118338 |
if self._is_new(filepath):
return False
mtime = self._get_modified_time(filepath)
return self._watched_files[filepath] < mtime | def _is_modified(self, filepath) | Returns True if the file has been modified since last seen.
Will return False if the file has not been seen before. | 4.439044 | 3.901003 | 1.137924 |
self.log("No supported libraries found: using polling-method.")
self._running = True
self.trigger_init()
self._scan(trigger=False) # put after the trigger
if self._warn:
print()
while self._running:
self._scan()
if isinstance... | def loop(self, sleep_time=1, callback=None) | Goes into a blocking IO loop. If polling is used, the sleep_time is
the interval, in seconds, between polls. | 10.020275 | 9.472845 | 1.057789 |
changed = False
files_seen = set()
os_path_join = os.path.join
for path in self.paths:
for root, dirs, files in os.walk(path):
for f in files:
fpath = os_path_join(root, f)
if not self.is_valid_type(fpath):
... | def _scan(self, trigger=True) | Walks through the directory to look for changes of the given file
types.
Returns True if changes occurred (False otherwise).
Returns None if polling method isn't being used. | 2.679714 | 2.525714 | 1.060973 |
if sniffer_instance is None:
sniffer_instance = ScentSniffer()
if debug:
scanner = Scanner(
sniffer_instance.watch_paths,
scent=sniffer_instance.scent, logger=sys.stdout)
else:
scanner = Scanner(
sniffer_instance.watch_paths, scent=sniffer_in... | def run(sniffer_instance=None, wait_time=0.5, clear=True, args=(),
debug=False) | Runs the auto tester loop. Internally, the runner instanciates the sniffer_cls and
scanner class.
``sniffer_instance`` The class to run. Usually this is set to but a subclass of scanner.
Defaults to Sniffer. Sniffer class documentation for more information.
``wait_time`` The time, in ... | 4.063756 | 4.224593 | 0.961928 |
parser = OptionParser(version="%prog " + __version__)
parser.add_option('-w', '--wait', dest="wait_time", metavar="TIME",
default=0.5, type="float",
help="Wait time, in seconds, before possibly rerunning"
"tests. (default: %default)")
pa... | def main(sniffer_instance=None, test_args=(), progname=sys.argv[0],
args=sys.argv[1:]) | Runs the program. This is used when you want to run this program standalone.
``sniffer_instance`` A class (usually subclassed of Sniffer) that hooks into the
scanner and handles running the test framework. Defaults to
Sniffer instance.
``test_args`` This function norma... | 2.599268 | 2.640267 | 0.984472 |
self.test_args = test_args
self.debug, self.clear = debug, clear | def set_up(self, test_args=(), clear=True, debug=False) | Sets properties right before calling run.
``test_args`` The arguments to pass to the test runner.
``clear`` Boolean. Set to True if we should clear console before
running the tests.
``debug`` Boolean. Set to True if we want to print debugging
... | 4.121737 | 4.734588 | 0.870559 |
@wraps(func)
def wrapper(*args, **kwargs):
return func()
return wrapper | def absorb_args(self, func) | Calls a function without any arguments. The returned caller function
accepts any arguments (and throws them away). | 4.225066 | 3.579193 | 1.180452 |
scanner.observe(scanner.ALL_EVENTS,
self.absorb_args(self.modules.restore))
if self.clear:
scanner.observe(scanner.ALL_EVENTS,
self.absorb_args(self.clear_on_run))
scanner.observe(scanner.ALL_EVENTS, self.absorb_args(self._... | def observe_scanner(self, scanner) | Hooks into multiple events of a scanner. | 4.784186 | 4.48805 | 1.065983 |
if platform.system() == 'Windows':
os.system('cls')
else:
os.system('clear')
if prefix:
print(prefix) | def clear_on_run(self, prefix="Running Tests:") | Clears console before running the tests. | 2.859464 | 2.740188 | 1.043529 |
try:
if self.run():
broadcaster.success(self)
else:
broadcaster.failure(self)
except StandardError:
import traceback
traceback.print_exc()
self._stop()
raise
except Exception:
... | def _run(self) | Calls self.run() and wraps for errors. | 4.822667 | 4.351514 | 1.108273 |
try:
import nose
arguments = [sys.argv[0]] + list(self.test_args)
return nose.run(argv=arguments)
except ImportError:
print()
print("*** Nose library missing. Please install it. ***")
print()
raise | def run(self) | Runs the unit test framework. Can be overridden to run anything.
Returns True on passing and False on failure. | 4.60814 | 4.246355 | 1.085199 |
if not self.scent or len(self.scent.runners) == 0:
print("Did not find 'scent.py', running nose:")
return super(ScentSniffer, self).run()
else:
print("Using scent:")
arguments = [sys.argv[0]] + list(self.test_args)
return self.scent.ru... | def run(self) | Runs the CWD's scent file. | 7.751001 | 5.875318 | 1.319248 |
self_copy = self.dup()
self_copy._scopes = copy.copy(self._scopes)
return self_copy | def copy(self) | Return a copy of this object. | 5.860809 | 5.421566 | 1.081018 |
new_self = self.copy()
new_scopes = Object.translate_to_scopes(*args, **kw)
new_self._scopes = tuple(reversed(new_scopes)) + new_self._scopes
return new_self | def bind(self, *args, **kw) | Bind environment variables into this object's scope. | 6.44497 | 5.278038 | 1.221092 |
new_self = self.copy()
new_scopes = Object.translate_to_scopes(*args, **kw)
new_self._scopes = new_self._scopes + new_scopes
return new_self | def in_scope(self, *args, **kw) | Scope this object to a parent environment (like bind but reversed.) | 5.890767 | 4.920193 | 1.197263 |
try:
si, uninterp = self.interpolate()
# TODO(wickman) This should probably be pushed out to the interpolate leaves.
except (Object.CoercionError, MustacheParser.Uninterpolatable) as e:
return TypeCheck(False, "Unable to interpolate: %s" % e)
return self.checker(si) | def check(self) | Type check this object. | 17.634077 | 15.832389 | 1.113798 |
sys = set(self._sys_modules.keys())
for mod_name in sys.difference(self._saved_modules):
del self._sys_modules[mod_name] | def restore(self) | Unloads all modules that weren't loaded when save_modules was called. | 5.123166 | 3.849366 | 1.330912 |
isplits = []
unbound = []
for ref in splits:
if isinstance(ref, Ref):
resolved = False
for namable in namables:
try:
value = namable.find(ref)
resolved = True
break
except Namable.Error:
continue
if resolv... | def join(cls, splits, *namables) | Interpolate strings.
:params splits: The output of Parser.split(string)
:params namables: A sequence of Namable objects in which the interpolation should take place.
Returns 2-tuple containing:
joined string, list of unbound object ids (potentially empty) | 3.641564 | 3.1617 | 1.151774 |
if len(args) == 2:
name, alternatives = args
else:
name = "Choice_" + "_".join(a.__name__ for a in args[0])
alternatives = args[0]
assert isinstance(name, Compatibility.stringy)
assert all(issubclass(t, Type) for t in alternatives)
return TypeFactory.new({}, ChoiceFactory.PROVIDES, name,
... | def Choice(*args) | Helper function for creating new choice types.
This can be called either as:
Choice(Name, [Type1, Type2, ...])
or:
Choice([Type1, Type2, ...])
In the latter case, the name of the new type will be autogenerated, and will
look like "Choice_Type1_Type2". | 7.136583 | 5.439975 | 1.311878 |
assert len(type_parameters) == 2
name = type_parameters[0]
alternatives = type_parameters[1]
assert isinstance(name, Compatibility.stringy)
assert isinstance(alternatives, (list, tuple))
choice_types = []
for c in alternatives:
choice_types.append(TypeFactory.new(type_dict, *c))
... | def create(type_dict, *type_parameters) | type_parameters should be:
(name, (alternative1, alternative2, ...))
where name is a string, and the alternatives are all valid serialized
types. | 4.234108 | 3.948283 | 1.072392 |
for opt in self.CHOICES:
if isinstance(self._value, opt):
return ret_fun(self._value)
else:
try:
o = opt(self._value)
ret = ret_fun(o)
if ret:
return ret
except (self.CoercionError, ValueError):
pass
return err_fun(self... | def _unwrap(self, ret_fun, err_fun) | Iterate over the options in the choice type, and try to perform some
action on them. If the action fails (returns None or raises either CoercionError
or ValueError), then it goes on to the next type.
Args:
ret_fun: a function that takes a wrapped option value, and either returns a successful
... | 3.696123 | 3.10121 | 1.191833 |
out(title)
max_key_len = max(len(key) for key, _ in elems) + 1
for key, val in elems:
key_spaced = ('%s:' % key).ljust(max_key_len)
out('%s%s %s' % (indent * ' ', key_spaced, val))
out() | def outitem(title, elems, indent=4) | Output formatted as list item. | 2.755273 | 2.82725 | 0.974541 |
if name:
possible_path = Path(name)
if possible_path.exists():
return possible_path
profiles = list(read_profiles())
try:
if name:
profile = next(p for p in profiles if p.name == name)
else:
profile = next(p for p in profiles if p.defa... | def profile_dir(name) | Return path to FF profile for a given profile name or path. | 2.781093 | 2.53842 | 1.0956 |
metadata = {'arg_params': (args, kwargs)}
return attrib(default=arg_default(*args, **kwargs), metadata=metadata) | def arg(*args, **kwargs) | Return an attrib() that can be fed as a command-line argument.
This function is a wrapper for an attr.attrib to create a corresponding
command line argument for it. Use it with the same arguments as argparse's
add_argument().
Example:
>>> @attrs
... class MyFeature(Feature):
... my_nu... | 13.07869 | 16.763083 | 0.780208 |
parser = argparse.ArgumentParser()
parser.add_argument(*args, **kwargs)
args = vars(parser.parse_args([]))
_, default = args.popitem()
return default | def arg_default(*args, **kwargs) | Return default argument value as given by argparse's add_argument().
The argument is passed through a mocked-up argument parser. This way, we
get default parameters even if the feature is called directly and not
through the CLI. | 3.718203 | 3.611128 | 1.029651 |
def decorator(func):
func._output_format = dict(name=name, default=default)
return func
return decorator | def formatter(name, default=False) | Decorate a Feature method to register it as an output formatter.
All formatters are picked up by the argument parser so that they can be
listed and selected on the CLI via the -f, --format argument. | 4.525695 | 5.562226 | 0.813648 |
if column_map is None:
column_map = {}
db_path = self.profile_path(db, must_exist=True)
def obj_factory(cursor, row):
dict_ = {}
for idx, col in enumerate(cursor.description):
new_name = column_map.get(col[0], col[0])
... | def load_sqlite(self, db, query=None, table=None, cls=None,
column_map=None) | Load data from sqlite db and return as list of specified objects. | 2.190307 | 2.215092 | 0.988811 |
with open(self.profile_path(path, must_exist=True),
encoding='utf-8') as f:
data = json.load(f)
return data | def load_json(self, path) | Load a JSON file from the user profile. | 4.273685 | 3.490441 | 1.224397 |
with open(self.profile_path(path, must_exist=True), 'rb') as f:
if f.read(8) != b'mozLz40\0':
raise NotMozLz4Error('Not Mozilla LZ4 format.')
data = lz4.block.decompress(f.read())
return data | def load_mozlz4(self, path) | Load a Mozilla LZ4 file from the user profile.
Mozilla LZ4 is regular LZ4 with a custom string prefix. | 3.846183 | 3.785006 | 1.016163 |
items = iter(items)
first = next(items)
cls = first.__class__
if stream is None:
stream = sys.stdout
fields = [f.name for f in attr.fields(cls)]
writer = csv.DictWriter(stream, fieldnames=fields)
writer.writeheader()
writer.writerow(at... | def csv_from_items(items, stream=None) | Write a list of items to stream in CSV format.
The items need to be attrs-decorated. | 2.188277 | 2.073728 | 1.055238 |
full_path = self.session.profile / path
if must_exist and not full_path.exists():
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
PurePath(full_path).name,
)
return full_path | def profile_path(self, path, must_exist=False) | Return path from current profile. | 3.318799 | 3.059336 | 1.08481 |
# ~~~ hack: ~~~
if not self.is_alive():
self.close() # force close for safety
self.open() # reopen
# ~~~ end hack ~~~
result = self._execute_rpc(rpc_command)
return ET.tostring(result) | def make_rpc_call(self, rpc_command) | Allow a user to query a device directly using XML-requests.
:param rpc_command: (str) rpc command such as:
<Get><Operational><LLDP><NodeTable></NodeTable></LLDP></Operational></Get> | 7.103468 | 6.963383 | 1.020117 |
try:
self.device = ConnectHandler(device_type='cisco_xr',
ip=self.hostname,
port=self.port,
username=self.username,
password=se... | def open(self) | Open a connection to an IOS-XR device.
Connects to the device using SSH and drops into XML mode. | 4.204395 | 3.648132 | 1.152479 |
if hasattr(self.device, 'remote_conn'):
return self.device.remote_conn.transport.is_active() and self._xml_agent_alive
return False | def is_alive(self) | Returns the XML agent connection state (and SSH connection state). | 8.065001 | 4.852992 | 1.661862 |
rpc_command = '<CLI><Exec>{show_command}</Exec></CLI>'.format(
show_command=escape_xml(show_command)
)
response = self._execute_rpc(rpc_command)
raw_response = response.xpath('.//CLI/Exec')[0].text
return raw_response.strip() if raw_response else '' | def _execute_show(self, show_command) | Executes an operational show-type command. | 4.13655 | 3.935236 | 1.051157 |
rpc_command = '<CLI><Configuration>{show_command}</Configuration></CLI>'.format(
show_command=escape_xml(show_command)
)
response = self._execute_rpc(rpc_command, delay_factor=delay_factor)
raw_response = response.xpath('.//CLI/Configuration')[0].text
return ... | def _execute_config_show(self, show_command, delay_factor=.1) | Executes a configuration show-type command. | 3.4393 | 3.285786 | 1.046721 |
if self.lock_on_connect or self.locked:
self.unlock() # this refers to the config DB
self._unlock_xml_agent() # this refers to the XML agent
if hasattr(self.device, 'remote_conn'):
self.device.remote_conn.close() | def close(self) | Close the connection to the IOS-XR device.
Clean up after you are done and explicitly close the router connection. | 10.486041 | 8.917188 | 1.175936 |
if not self.locked:
rpc_command = '<Lock/>'
try:
self._execute_rpc(rpc_command)
except XMLCLIError:
raise LockError('Unable to enter in configure exclusive mode!', self)
self.locked = True | def lock(self) | Lock the config database.
Use if Locking/Unlocking is not performaed automatically by lock=False | 10.763794 | 10.284214 | 1.046633 |
if self.locked:
rpc_command = '<Unlock/>'
try:
self._execute_rpc(rpc_command)
except XMLCLIError:
raise UnlockError('Unable to unlock the config!', self)
self.locked = False | def unlock(self) | Unlock the IOS-XR device config.
Use if Locking/Unlocking is not performaed automatically by lock=False | 8.214975 | 7.352322 | 1.117331 |
configuration = ''
if filename is None:
configuration = config
else:
with open(filename) as f:
configuration = f.read()
rpc_command = '<CLI><Configuration>{configuration}</Configuration></CLI>'.format(
configuration=escape_xm... | def load_candidate_config(self, filename=None, config=None) | Load candidate confguration.
Populate the attribute candidate_config with the desired
configuration and loads it into the router. You can populate it from
a file or from a string. If you send both a filename and a string
containing the configuration, the file takes precedence.
... | 4.831194 | 5.500734 | 0.878282 |
command = "show configuration"
if merge:
command += " merge"
if formal:
command += " formal"
response = self._execute_config_show(command)
match = re.search(".*(!! IOS XR Configuration.*)$", response, re.DOTALL)
if match is not None:
... | def get_candidate_config(self, merge=False, formal=False) | Retrieve the configuration loaded as candidate config in your configuration session.
:param merge: Merge candidate config with running config to return
the complete configuration including all changed
:param formal: Return configuration in IOS-XR formal config format | 4.242713 | 4.388774 | 0.966719 |
_show_merge = self._execute_config_show('show configuration merge')
_show_run = self._execute_config_show('show running-config')
diff = difflib.unified_diff(_show_run.splitlines(1)[2:-2], _show_merge.splitlines(1)[2:-2])
return ''.join([x.replace('\r', '') for x in diff]) | def compare_config(self) | Compare configuration to be merged with the one on the device.
Compare executed candidate config with the running config and
return a diff, assuming the loaded config will be merged with the
existing one.
:return: Config diff. | 3.724171 | 3.417665 | 1.089683 |
rpc_command = '<Commit'
if label:
rpc_command += ' Label="%s"' % label
if comment:
rpc_command += ' Comment="%s"' % comment[:60]
if confirmed:
if 30 <= int(confirmed) <= 300:
rpc_command += ' Confirmed="%d"' % int(confirmed)
... | def commit_config(self, label=None, comment=None, confirmed=None) | Commit the candidate config.
:param label: Commit comment, displayed in the commit entry on the device.
:param comment: Commit label, displayed instead of the commit ID on the device. (Max 60 characters)
:param confirmed: Commit with auto-rollback if new commit is not made in 30 to 300 se... | 3.12552 | 2.934234 | 1.065191 |
rpc_command = '<Unlock/><Rollback><Previous>{rb_id}</Previous></Rollback><Lock/>'.format(rb_id=rb_id)
self._execute_rpc(rpc_command) | def rollback(self, rb_id=1) | Rollback the last committed configuration.
:param rb_id: Rollback a specific number of steps. Default: 1 | 8.3651 | 9.042319 | 0.925106 |
'''
Invoke the peforth interpreter.
An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="")
is like a breakpoint. The prompt indicates which breakpoint it is if there are
many. Arguments loc (locals) and glo (globals) along with the prompt are the
debuggee's informations t... | def ok(prompt='OK ', loc={}, glo={}, cmd="") | Invoke the peforth interpreter.
An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="")
is like a breakpoint. The prompt indicates which breakpoint it is if there are
many. Arguments loc (locals) and glo (globals) along with the prompt are the
debuggee's informations that is packe... | 12.723236 | 5.103814 | 2.492888 |
import sys
def log(message):
print(message)
def print_usage():
log('usage: %s <application key> <application secret> send <number> <message> <from_number>' % sys.argv[0])
log(' %s <application key> <application secret> status <message_id>' % sys.argv[0])
if len(sys.... | def _main() | A simple demo to be used from command line. | 1.916966 | 1.885658 | 1.016603 |
if values:
json_data = json.dumps(values)
request = urllib2.Request(url, json_data.encode())
request.add_header('content-type', 'application/json')
request.add_header('authorization', self._auth)
connection = urllib2.urlopen(request)
... | def _request(self, url, values=None) | Send a request and read response.
Sends a get request if values are None, post request otherwise. | 1.889318 | 1.902214 | 0.993221 |
values = {'Message': message}
if from_number is not None:
values['From'] = from_number
return self._request(self.SEND_SMS_URL + to_number, values) | def send_message(self, to_number, message, from_number=None) | Send a message to the specified number and return a response dictionary.
The numbers must be specified in international format starting with a '+'.
Returns a dictionary that contains a 'MessageId' key with the sent message id value or
contains 'errorCode' and 'message' on error.
... | 3.897791 | 4.229541 | 0.921564 |
# Fields
fields = []
fallbacks = []
schema = tableschema.Schema(descriptor)
for index, field in enumerate(schema.fields):
converted_type = self.convert_type(field.type)
if not converted_type:
converted_type = 'STRING'
... | def convert_descriptor(self, descriptor) | Convert descriptor to BigQuery | 3.006233 | 2.894318 | 1.038667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.