code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return self.post(self.get_url("/kv/txn"),
data=json.dumps(txn)) | def transaction(self, txn) | Txn processes multiple requests in a single transaction.
A txn request increments the revision of the key-value store and
generates events with the same revision for every completed request.
It is not allowed to modify the same key several times within one txn.
:param txn:
:ret... | 10.279646 | 10.759866 | 0.955369 |
event_queue = queue.Queue()
def callback(event):
event_queue.put(event)
w = watch.Watcher(self, key, callback, **kwargs)
canceled = threading.Event()
def cancel():
canceled.set()
event_queue.put(None)
w.stop()
d... | def watch(self, key, **kwargs) | Watch a key.
:param key: key to watch
:returns: tuple of ``events_iterator`` and ``cancel``.
Use ``events_iterator`` to get the events of key changes
and ``cancel`` to cancel the watch request | 2.656126 | 2.723701 | 0.97519 |
kwargs['range_end'] = \
_increment_last_byte(key_prefix)
return self.watch(key_prefix, **kwargs) | def watch_prefix(self, key_prefix, **kwargs) | The same as ``watch``, but watches a range of keys with a prefix. | 7.370318 | 7.092127 | 1.039225 |
event_queue = queue.Queue()
def callback(event):
event_queue.put(event)
w = watch.Watcher(self, key, callback, **kwargs)
try:
return event_queue.get(timeout=timeout)
except queue.Empty:
raise exceptions.WatchTimedOut()
finall... | def watch_once(self, key, timeout=None, **kwargs) | Watch a key and stops after the first event.
:param key: key to watch
:param timeout: (optional) timeout in seconds.
:returns: event | 2.756823 | 2.94667 | 0.935572 |
kwargs['range_end'] = \
_increment_last_byte(key_prefix)
return self.watch_once(key_prefix, timeout=timeout, **kwargs) | def watch_prefix_once(self, key_prefix, timeout=None, **kwargs) | Watches a range of keys with a prefix, similar to watch_once | 5.785433 | 5.85387 | 0.988309 |
'''
Schedule a timer with the given callable and the interval in seconds.
The interval value is also passed to the callable.
If the callable takes longer than the timer interval, all accumulated
callable's tasks will be cancelled when the timer is cancelled.
Args:
cb: TODO - fill argume... | def create_timer(cb: Callable[[float], None], interval: float,
delay_policy: TimerDelayPolicy = TimerDelayPolicy.DEFAULT,
loop: Optional[asyncio.BaseEventLoop] = None) -> asyncio.Task | Schedule a timer with the given callable and the interval in seconds.
The interval value is also passed to the callable.
If the callable takes longer than the timer interval, all accumulated
callable's tasks will be cancelled when the timer is cancelled.
Args:
cb: TODO - fill argument descripti... | 3.350039 | 1.785432 | 1.876318 |
self.client.post(self.client.get_url("/kv/lease/revoke"),
json={"ID": self.id})
return True | def revoke(self) | LeaseRevoke revokes a lease.
All keys attached to the lease will expire and be deleted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return: | 13.674857 | 12.924673 | 1.058043 |
result = self.client.post(self.client.get_url("/kv/lease/timetolive"),
json={"ID": self.id})
return int(result['TTL']) | def ttl(self) | LeaseTimeToLive retrieves lease information.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return: | 11.19453 | 10.869854 | 1.029869 |
result = self.client.post(self.client.get_url("/kv/lease/timetolive"),
json={"ID": self.id,
"keys": True})
keys = result['keys'] if 'keys' in result else []
return [_decode(key) for key in keys] | def keys(self) | Get the keys associated with this lease.
:return: | 8.650529 | 7.738934 | 1.117793 |
'''
Wraps a coroutine function with pre-defined arguments (including keyword
arguments). It is an asynchronous version of :func:`functools.partial`.
'''
@functools.wraps(coro)
async def wrapped(*cargs, **ckwargs):
return await coro(*args, *cargs, **kwargs, **ckwargs)
return wrappe... | def apartial(coro, *args, **kwargs) | Wraps a coroutine function with pre-defined arguments (including keyword
arguments). It is an asynchronous version of :func:`functools.partial`. | 3.556463 | 1.947788 | 1.825898 |
'''
A simple LRU cache just like :func:`functools.lru_cache`, but it works for
coroutines. This is not as heavily optimized as :func:`functools.lru_cache`
which uses an internal C implementation, as it targets async operations
that take a long time.
It follows the same API that the standard fu... | def lru_cache(maxsize: int = 128,
typed: bool = False,
expire_after: float = None) | A simple LRU cache just like :func:`functools.lru_cache`, but it works for
coroutines. This is not as heavily optimized as :func:`functools.lru_cache`
which uses an internal C implementation, as it targets async operations
that take a long time.
It follows the same API that the standard functools prov... | 4.310692 | 2.000153 | 2.155181 |
if self.services:
return self.services
url = 'http://api.embed.ly/1/services/python'
http = httplib2.Http(timeout=self.timeout)
headers = {'User-Agent': self.user_agent,
'Connection': 'close'}
resp, content = http.request(url, headers=he... | def get_services(self) | get_services makes call to services end point of api.embed.ly to fetch
the list of supported providers and their regexes | 3.08041 | 2.551434 | 1.207325 |
if not url_or_urls:
raise ValueError('%s requires a url or a list of urls given: %s' %
(method.title(), url_or_urls))
# a flag we can use instead of calling isinstance() all the time
multi = isinstance(url_or_urls, list)
# throw an erro... | def _get(self, version, method, url_or_urls, **kwargs) | _get makes the actual call to api.embed.ly | 3.002172 | 2.907776 | 1.032463 |
if sys.version_info[0] == 2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__st... | def python_2_unicode_compatible(klass) | A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
From django.utils.encoding.py in 1.4.2+, minus the dependency on Six.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class... | 1.6706 | 1.951885 | 0.855891 |
if not isinstance(data, bytes_types):
data = six.b(str(data))
return base64.b64encode(data).decode("utf-8") | def _encode(data) | Encode the given data using base-64
:param data:
:return: base-64 encoded string | 2.858327 | 3.538002 | 0.807893 |
if not isinstance(data, bytes_types):
data = six.b(str(data))
return base64.b64decode(data.decode("utf-8")) | def _decode(data) | Decode the base-64 encoded string
:param data:
:return: decoded data | 3.588523 | 4.328669 | 0.829013 |
if not isinstance(data, bytes_types):
if isinstance(data, six.string_types):
data = data.encode('utf-8')
else:
data = six.b(str(data))
s = bytearray(data)
s[-1] = s[-1] + 1
return bytes(s) | def _increment_last_byte(data) | Get the last byte in the array and increment it
:param bytes_string:
:return: | 2.330417 | 2.527368 | 0.922073 |
self.metadata_path = os.path.join(self.path, 'metadata.rb')
if not os.path.isfile(self.metadata_path):
raise ValueError("Cookbook needs metadata.rb, %s"
% self.metadata_path)
if not self._metadata:
self._metadata = MetadataRb(open(se... | def metadata(self) | Return dict representation of this cookbook's metadata.rb . | 4.103614 | 2.953385 | 1.389461 |
self.berks_path = os.path.join(self.path, 'Berksfile')
if not self._berksfile:
if not os.path.isfile(self.berks_path):
raise ValueError("No Berksfile found at %s"
% self.berks_path)
self._berksfile = Berksfile(open(self.be... | def berksfile(self) | Return this cookbook's Berksfile instance. | 2.419759 | 2.128513 | 1.136831 |
cookbooks = set()
# put these in order
groups = [cookbooks]
for key, val in dictionary.items():
if key == 'depends':
cookbooks.update({cls.depends_statement(cbn, meta)
for cbn, meta in val.items()})
body = '... | def from_dict(cls, dictionary) | Create a MetadataRb instance from a dict. | 6.973288 | 6.625556 | 1.052483 |
line = "depends '%s'" % cookbook_name
if metadata:
if not isinstance(metadata, dict):
raise TypeError("Stencil dependency options for %s "
"should be a dict of options, not %s."
% (cookbook_name, metadat... | def depends_statement(cookbook_name, metadata=None) | Return a valid Ruby 'depends' statement for the metadata.rb file. | 4.47704 | 4.245955 | 1.054425 |
data = utils.ruby_lines(self.readlines())
data = [tuple(j.strip() for j in line.split(None, 1))
for line in data]
depends = {}
for line in data:
if not len(line) == 2:
continue
key, value = line
if key == 'depen... | def parse(self) | Parse the metadata.rb into a dict. | 4.005622 | 3.559533 | 1.125322 |
if not isinstance(other, MetadataRb):
raise TypeError("MetadataRb to merge should be a 'MetadataRb' "
"instance, not %s.", type(other))
current = self.to_dict()
new = other.to_dict()
# compare and gather cookbook dependencies
meta... | def merge(self, other) | Add requirements from 'other' metadata.rb into this one. | 6.517047 | 5.559229 | 1.172293 |
self.flush()
self.seek(0)
data = utils.ruby_lines(self.readlines())
data = [tuple(j.strip() for j in line.split(None, 1))
for line in data]
datamap = {}
for line in data:
if len(line) == 1:
datamap[line[0]] = True
... | def parse(self) | Parse this Berksfile into a dict. | 3.630278 | 3.476735 | 1.044163 |
cookbooks = set()
sources = set()
other = set()
# put these in order
groups = [sources, cookbooks, other]
for key, val in dictionary.items():
if key == 'cookbook':
cookbooks.update({cls.cookbook_statement(cbn, meta)
... | def from_dict(cls, dictionary) | Create a Berksfile instance from a dict. | 4.775735 | 4.523757 | 1.055701 |
line = "cookbook '%s'" % cookbook_name
if metadata:
if not isinstance(metadata, dict):
raise TypeError("Berksfile dependency hash for %s "
"should be a dict of options, not %s."
% (cookbook_name, metadat... | def cookbook_statement(cookbook_name, metadata=None) | Return a valid Ruby 'cookbook' statement for the Berksfile. | 5.124716 | 4.357797 | 1.175988 |
if not isinstance(other, Berksfile):
raise TypeError("Berksfile to merge should be a 'Berksfile' "
"instance, not %s.", type(other))
current = self.to_dict()
new = other.to_dict()
# compare and gather cookbook dependencies
berks_w... | def merge(self, other) | Add requirements from 'other' Berksfile into this one. | 4.98307 | 4.157173 | 1.198668 |
if not self._manifest:
with open(self.manifest_path) as man:
self._manifest = json.load(man)
return self._manifest | def manifest(self) | The manifest definition of the stencilset as a dict. | 3.309986 | 2.673995 | 1.237843 |
if not self._stencils:
self._stencils = self.manifest['stencils']
return self._stencils | def stencils(self) | List of stencils. | 5.280153 | 4.528904 | 1.165879 |
if stencil_name not in self.manifest.get('stencils', {}):
raise ValueError("Stencil '%s' not declared in StencilSet "
"manifest." % stencil_name)
stencil = copy.deepcopy(self.manifest)
allstencils = stencil.pop('stencils')
stencil.pop('de... | def get_stencil(self, stencil_name, **options) | Return a Stencil instance given a stencil name. | 4.732579 | 4.780478 | 0.98998 |
if 'stencil' not in stencil_definition:
selected_stencil_name = stencil_set.manifest.get('default_stencil')
else:
selected_stencil_name = stencil_definition.get('stencil')
if not selected_stencil_name:
raise ValueError("No stencil name, within stencil set %s, specified."
... | def _determine_selected_stencil(stencil_set, stencil_definition) | Determine appropriate stencil name for stencil definition.
Given a fastfood.json stencil definition with a stencil set, figure out
what the name of the stencil within the set should be, or use the default | 3.483584 | 3.410715 | 1.021365 |
template_map = {
'cookbook': {"name": cookbook_name},
'options': stencil['options']
}
# Cookbooks may not yet have metadata, so we pass an empty dict if so
try:
template_map['cookbook'] = cookbook.metadata.to_dict().copy()
except ValueError:
# ValueError may be ... | def _build_template_map(cookbook, cookbook_name, stencil) | Build a map of variables for this generated cookbook and stencil.
Get template variables from stencil option values, adding the default ones
like cookbook and cookbook year. | 7.626632 | 7.402226 | 1.030316 |
for source_path, target_path in files.items():
needdir = os.path.dirname(target_path)
assert needdir, "Target should have valid parent dir"
try:
os.makedirs(needdir)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if os... | def _render_binaries(files, written_files) | Write binary contents from filetable into files.
Using filetable for the input files, and the list of files, render
all the templates into actual files on disk, forcing to overwrite the file
as appropriate, and using the given open mode for the file. | 2.759535 | 2.807319 | 0.982979 |
for tpl_path, content in filetable:
target_path = files[tpl_path]
needdir = os.path.dirname(target_path)
assert needdir, "Target should have valid parent dir"
try:
os.makedirs(needdir)
except OSError as err:
if err.errno != errno.EEXIST:
... | def _render_templates(files, filetable, written_files, force, open_mode='w') | Write template contents from filetable into files.
Using filetable for the rendered templates, and the list of files, render
all the templates into actual files on disk, forcing to overwrite the file
as appropriate, and using the given open mode for the file. | 2.57045 | 2.618838 | 0.981523 |
with open(build_config) as cfg:
cfg = json.load(cfg)
cookbook_name = cfg['name']
template_pack = pack.TemplatePack(templatepack_path)
written_files = []
cookbook = create_new_cookbook(cookbook_name, cookbooks_home)
for stencil_definition in cfg['stencils']:
selected_sten... | def build_cookbook(build_config, templatepack_path,
cookbooks_home, force=False) | Build a cookbook from a fastfood.json file.
Can build on an existing cookbook, otherwise this will
create a new cookbook for you based on your templatepack. | 3.914783 | 3.993865 | 0.980199 |
# force can be passed on the command line or forced in a stencil's options
force = force_argument or stencil['options'].get('force', False)
stencil['files'] = stencil.get('files') or {}
files = {
# files.keys() are template paths, files.values() are target paths
# {path to template... | def process_stencil(cookbook, cookbook_name, template_pack,
force_argument, stencil_set, stencil, written_files) | Process the stencil requested, writing any missing files as needed.
The stencil named 'stencilset_name' should be one of
templatepack's stencils. | 2.880308 | 2.981595 | 0.966029 |
cookbooks_home = utils.normalize_path(cookbooks_home)
if not os.path.exists(cookbooks_home):
raise ValueError("Target cookbook dir %s does not exist."
% os.path.relpath(cookbooks_home))
target_dir = os.path.join(cookbooks_home, cookbook_name)
LOG.debug("Creating d... | def create_new_cookbook(cookbook_name, cookbooks_home) | Create a new cookbook.
:param cookbook_name: Name of the new cookbook.
:param cookbooks_home: Target dir for new cookbook. | 2.267454 | 2.41542 | 0.938741 |
if isinstance(text, basestring):
text = text.splitlines()
elif not isinstance(text, list):
raise TypeError("text should be a list or a string, not %s"
% type(text))
return [l.strip() for l in text if l.strip() and not
l.strip().startswith('#')] | def ruby_lines(text) | Tidy up lines from a file, honor # comments.
Does not honor ruby block comments (yet). | 2.498342 | 2.519576 | 0.991572 |
if not isinstance(update, dict):
update = dict(update)
if not levels > 0:
original.update(update)
else:
for key, val in update.items():
if isinstance(original.get(key), dict):
# might need a force=True to override this
if not isinstanc... | def deepupdate(original, update, levels=5) | Update, like dict.update, but deeper.
Update 'original' from dict/iterable 'update'.
I.e., it recurses on dicts 'levels' times if necessary.
A standard dict.update is levels=0 | 2.81135 | 2.921798 | 0.962199 |
self.seek(0)
original_content_lines = self.readlines()
new_content_lines = copy.copy(original_content_lines)
# ignore blanks and sort statements to be written
statements = sorted([stmnt for stmnt in statements if stmnt])
# find all the insert points for each sta... | def write_statements(self, statements) | Insert the statements into the file neatly.
Ex:
statements = ["good 'dog'", "good 'cat'", "bad 'rat'", "fat 'emu'"]
# stream.txt ... animals = FileWrapper(open('stream.txt'))
good 'cow'
nice 'man'
bad 'news'
animals.write_statements(statements)
# st... | 3.258304 | 3.357568 | 0.970436 |
written_files, cookbook = food.build_cookbook(
args.config_file, args.template_pack,
args.cookbooks, args.force)
if len(written_files) > 0:
print("%s: %s files written" % (cookbook,
len(written_files)))
else:
print("%s up to date"... | def _fastfood_build(args) | Run on `fastfood build`. | 5.097299 | 5.431796 | 0.938419 |
template_pack = pack.TemplatePack(args.template_pack)
if args.stencil_set:
stencil_set = template_pack.load_stencil_set(args.stencil_set)
print("Available Stencils for %s:" % args.stencil_set)
for stencil in stencil_set.stencils:
print(" %s" % stencil)
else:
... | def _fastfood_list(args) | Run on `fastfood list`. | 3.279087 | 3.254805 | 1.00746 |
template_pack = pack.TemplatePack(args.template_pack)
if args.stencil_set:
stencil_set = template_pack.load_stencil_set(args.stencil_set)
print("Stencil Set %s:" % args.stencil_set)
print(' Stencils:')
for stencil in stencil_set.stencils:
print(" %s" % stenci... | def _fastfood_show(args) | Run on `fastfood show`. | 3.503194 | 3.527938 | 0.992986 |
pypi_url = 'http://pypi.python.org/pypi/fastfood/json'
headers = {
'Accept': 'application/json',
}
request = urllib.Request(pypi_url, headers=headers)
response = urllib.urlopen(request).read().decode('utf_8')
data = json.loads(response)
return data | def _release_info() | Check latest fastfood release info from PyPI. | 3.020329 | 2.247468 | 1.343881 |
env = "%s_%s" % (NAMESPACE.upper(), option_name.upper())
return os.environ.get(env, default) | def getenv(option_name, default=None) | Return the option from the environment in the FASTFOOD namespace. | 4.191707 | 3.6351 | 1.15312 |
if isinstance(err, basestring):
string = err
else:
try:
string = err.__name__
except AttributeError:
string = err.__class__.__name__
split = _SPLITCASE_RE.findall(string)
if not split:
split.append(string)
if len(split) > 1 and split[0] ==... | def get_friendly_title(err) | Turn class, instance, or name (str) into an eyeball-friendly title.
E.g. FastfoodStencilSetNotListed --> 'Stencil Set Not Listed' | 3.850955 | 3.206362 | 1.201036 |
if key not in self.manifest:
raise ValueError("Manifest %s requires '%s'."
% (self.manifest_path, key))
if cls:
if not isinstance(self.manifest[key], cls):
raise TypeError("Manifest value '%s' should be %s, not %s"
... | def _validate(self, key, cls=None) | Verify the manifest schema. | 2.899071 | 2.497071 | 1.160988 |
if not self._stencil_sets:
self._stencil_sets = self.manifest['stencil_sets']
return self._stencil_sets | def stencil_sets(self) | List of stencil sets. | 4.445365 | 3.959002 | 1.12285 |
if stencilset_name not in self._stencil_sets:
if stencilset_name not in self.manifest['stencil_sets'].keys():
raise exc.FastfoodStencilSetNotListed(
"Stencil set '%s' not listed in %s under stencil_sets."
% (stencilset_name, self.manif... | def load_stencil_set(self, stencilset_name) | Return the Stencil Set from this template pack. | 3.167393 | 3.082641 | 1.027493 |
if (re.match(NODE_ATTR_RE, option) is None and
re.match(CHEF_CONST_RE, option) is None):
return "'%s'" % option
else:
return option | def qstring(option) | Custom quoting method for jinja. | 5.889948 | 6.005469 | 0.980764 |
for path in files:
if not os.path.isfile(path):
raise ValueError("Template file %s not found"
% os.path.relpath(path))
else:
try:
with codecs.open(path, encoding='utf-8') as f:
text = f.read()
... | def render_templates_generator(*files, **template_map) | Render jinja templates according to template_map.
Yields (path, result) | 2.567409 | 2.570557 | 0.998775 |
_logger.info('Generating code to {!r}.'.format(outfolder))
for task in self.tasks:
for element in task.filtered_elements(model):
task.run(element, outfolder) | def generate(self, model, outfolder) | Generate artifacts for given model.
Attributes:
model:
Model for which to generate code.
outfolder:
Folder where code files are created. | 7.412284 | 7.428324 | 0.997841 |
filepath = self.relative_path_for_element(element)
if outfolder and not os.path.isabs(filepath):
filepath = os.path.join(outfolder, filepath)
_logger.debug('{!r} --> {!r}'.format(element, filepath))
self.ensure_folder(filepath)
self.generate_file(element, f... | def run(self, element, outfolder) | Apply this task to model element. | 3.595189 | 3.684459 | 0.975771 |
context = dict(element=element, **kwargs)
if self.global_context:
context.update(**self.global_context)
return context | def create_template_context(self, element, **kwargs) | Code generation context, specific to template and current element. | 3.274436 | 3.100159 | 1.056215 |
if value is None:
return None
if isinstance(value, bson.ObjectId):
return value
try:
return bson.ObjectId(value)
except (ValueError, AttributeError):
self.fail('invalid_object_id') | def _validated(self, value) | Format the value or raise a :exc:`ValidationError` if an error occurs. | 2.872836 | 2.542462 | 1.129943 |
return jinja2.Environment(
loader=jinja2.FileSystemLoader(self.templates_path),
**kwargs
) | def create_environment(self, **kwargs) | Return a new Jinja environment.
Derived classes may override method to pass additional parameters or to change the template
loader type. | 3.996797 | 2.978086 | 1.342069 |
a = np.asarray(a)
return as_strided(a, shape=(a.size - 1, 2), strides=a.strides * 2) | def pairs(a) | Return array of pairs of adjacent elements in a.
>>> pairs([1, 2, 3, 4])
array([[1, 2],
[2, 3],
[3, 4]]) | 3.352942 | 4.056202 | 0.826621 |
return (
-len(transcript.protein_sequence),
-len(transcript.sequence),
transcript.name
) | def transcript_sort_key(transcript) | Key function used to sort transcripts. Taking the negative of
protein sequence length and nucleotide sequence length so that
the transcripts with longest sequences come first in the list. This couldn't
be accomplished with `reverse=True` since we're also sorting by
transcript name (which places TP53-001... | 5.607195 | 4.091023 | 1.37061 |
assert len(transcripts) > 0
sorted_list = sorted(transcripts, key=transcript_sort_key)
return sorted_list[0] | def best_transcript(transcripts) | Given a set of coding transcripts, choose the one with the longest
protein sequence and in cases of ties use the following tie-breaking
criteria:
- transcript sequence (including UTRs)
- transcript name (so TP53-001 should come before TP53-202) | 3.492038 | 3.764099 | 0.927722 |
mhc_model = mhc_binding_predictor_from_args(args)
variants = variant_collection_from_args(args)
gene_expression_dict = rna_gene_expression_dict_from_args(args)
transcript_expression_dict = rna_transcript_expression_dict_from_args(args)
predictor = TopiaryPredictor(
mhc_model=mhc_model,... | def predict_epitopes_from_args(args) | Returns an epitope collection from the given commandline arguments.
Parameters
----------
args : argparse.Namespace
Parsed commandline arguments for Topiary | 2.759933 | 2.687252 | 1.027047 |
while True:
# Choose a random word
word = choice(dictionary)
# Stop looping as soon as we have a valid candidate
if len(word) >= min_word_length and len(word) <= max_word_length:
break
return word | def get_random_word(dictionary, min_word_length=3, max_word_length=8) | Returns a random word from the dictionary | 3.289255 | 3.314239 | 0.992462 |
# Set the position of the integer
int_position = set_int_position(number_of_elements)
# Load dictionary
dictionary = load_dictionary()
password = ''
for i in range(number_of_elements):
# Add word or integer
if i == int_position:
password += str(get_random_int(... | def pw(min_word_length=3, max_word_length=8, max_int_value=1000, number_of_elements=4, no_special_characters=False) | Generate a password | 2.771808 | 2.724021 | 1.017543 |
# Options
global args
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--min_word_length", type=int,
help="Minimum length for each word", default=3)
parser.add_argument("-x", "--max_word_length", type=int,
help="Maximum length for ea... | def main() | Main method | 2.226207 | 2.217498 | 1.003928 |
protein_subsequences = {}
protein_subsequence_start_offsets = {}
for effect in effects:
protein_sequence = effect.mutant_protein_sequence
# some effects will lack a mutant protein sequence since
# they are either silent or unpredictable
if protein_sequence:
m... | def protein_subsequences_around_mutations(effects, padding_around_mutation) | From each effect get a mutant protein sequence and pull out a subsequence
around the mutation (based on the given padding). Returns a dictionary
of subsequences and a dictionary of subsequence start offsets. | 2.880166 | 2.708587 | 1.063346 |
min_required_padding = max(epitope_lengths) - 1
if not given_padding:
return min_required_padding
else:
require_integer(given_padding, "Padding around mutation")
if given_padding < min_required_padding:
raise ValueError(
"Padding around mutation %d ca... | def check_padding_around_mutation(given_padding, epitope_lengths) | If user doesn't provide any padding around the mutation we need
to at least include enough of the surrounding non-mutated
esidues to construct candidate epitopes of the specified lengths. | 2.532947 | 2.545879 | 0.99492 |
if peptide_start_in_protein > mutation_end_in_protein:
raise ValueError("Peptide starts after mutation")
elif peptide_start_in_protein + peptide_length < mutation_start_in_protein:
raise ValueError("Peptide ends before mutation")
# need a half-open start/end interval
peptide_mutati... | def peptide_mutation_interval(
peptide_start_in_protein,
peptide_length,
mutation_start_in_protein,
mutation_end_in_protein) | Half-open interval of mutated residues in the peptide, determined
from the mutation interval in the original protein sequence.
Parameters
----------
peptide_start_in_protein : int
Position of the first peptide residue within the protein
(starting from 0)
peptide_length : int
m... | 1.99647 | 2.071119 | 0.963957 |
tags = indicator.get('tags')
if tags is not None:
tags = [Tag.from_dict(tag) for tag in tags]
return Indicator(value=indicator.get('value'),
type=indicator.get('indicatorType'),
priority_level=indicator.get('priorityLevel')... | def from_dict(cls, indicator) | Create an indicator object from a dictionary.
:param indicator: The dictionary.
:return: The indicator object. | 2.405007 | 2.461456 | 0.977067 |
if remove_nones:
return super().to_dict(remove_nones=True)
tags = None
if self.tags is not None:
tags = [tag.to_dict(remove_nones=remove_nones) for tag in self.tags]
return {
'value': self.value,
'indicatorType': self.type,
... | def to_dict(self, remove_nones=False) | Creates a dictionary representation of the indicator.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the indicator. | 2.404394 | 2.405416 | 0.999575 |
result = []
track = []
count = 0
for o in df['alerts']:
count += 1
if 'closedState' in o:
if o['closedState'] != 'False Positive':
if 'distinguishers' in o:
try:
if 'virus' in o['distinguishers']:
... | def filter_false_positive(df, process_time) | method that takes in FireEye (FE) alerts and filters FE-tests and False Positives
:param process_time:
:param df:
:return: | 2.852245 | 2.719512 | 1.048808 |
result = []
track = []
for o in df:
if 'METHODOLOGY - WEB APP ATTACK' in o['message']:
track.append(o)
else:
result.append(o)
trackfile = open('tracking_webAppAttack_' + process_time + '.txt', 'w')
numskip = 1
for item in track:
trackfile.writ... | def filter_webapp_attack(df, process_time) | A function that filters out the BASH SHELLSHOCK alert data obtained from FireEye
:param df: a DataFrame object
:param process_time:
:return: | 6.131927 | 6.25168 | 0.980845 |
processed_line = open(file_name, 'r').read()
char_pos = processed_line.find("}")
new_line = "{" + processed_line[char_pos + 2:]
return new_line | def process_alert(file_name) | A function that removes the alerts property from the FireEye alert and transform the data into a JSON ready format
:param file_name:
:return: | 4.545495 | 4.70241 | 0.966631 |
n_before = len(collection)
filtered = [x for x in collection if filter_fn(x)]
n_after = len(filtered)
if not collection_name:
collection_name = collection.__class__.__name__
logging.info(
"%s filtering removed %d/%d entries of %s",
filter_name,
(n_before - n_afte... | def apply_filter(
filter_fn,
collection,
result_fn=None,
filter_name="",
collection_name="") | Apply filter to effect collection and print number of dropped elements
Parameters
---------- | 2.600933 | 3.101136 | 0.838703 |
return apply_filter(
filter_fn=lambda effect: isinstance(effect, NonsilentCodingMutation),
collection=effects,
result_fn=effects.clone_with_new_elements,
filter_name="Silent mutation") | def filter_silent_and_noncoding_effects(effects) | Keep only variant effects which result in modified proteins.
Parameters
----------
effects : varcode.EffectCollection | 9.133492 | 10.855456 | 0.841373 |
if gene_expression_dict:
variants = apply_filter(
lambda variant: any(
gene_expression_dict.get(gene_id, 0.0) >=
gene_expression_threshold
for gene_id in variant.gene_ids
),
variants,
result_fn=variants.clon... | def apply_variant_expression_filters(
variants,
gene_expression_dict,
gene_expression_threshold,
transcript_expression_dict,
transcript_expression_threshold) | Filter a collection of variants by gene and transcript expression thresholds
Parameters
----------
variants : varcode.VariantCollection
gene_expression_dict : dict
gene_expression_threshold : float
transcript_expression_dict : dict
transcript_expression_threshold : float | 2.059672 | 2.216195 | 0.929373 |
if gene_expression_dict:
effects = apply_filter(
lambda effect: (
gene_expression_dict.get(effect.gene_id, 0.0) >=
gene_expression_threshold),
effects,
result_fn=effects.clone_with_new_elements,
filter_name="Effect gene exp... | def apply_effect_expression_filters(
effects,
gene_expression_dict,
gene_expression_threshold,
transcript_expression_dict,
transcript_expression_threshold) | Filter collection of varcode effects by given gene
and transcript expression thresholds.
Parameters
----------
effects : varcode.EffectCollection
gene_expression_dict : dict
gene_expression_threshold : float
transcript_expression_dict : dict
transcript_expression_threshold : float | 2.34107 | 2.508649 | 0.933199 |
if enclave_ids is None:
enclave_ids = self.enclave_ids
if tags is not None:
tags = [tag.to_dict() for tag in tags]
body = {
"enclaveIds": enclave_ids,
"content": [indicator.to_dict() for indicator in indicators],
"tags": tag... | def submit_indicators(self, indicators, enclave_ids=None, tags=None) | Submit indicators directly. The indicator field ``value`` is required; all other metadata fields are optional:
``firstSeen``, ``lastSeen``, ``sightings``, ``notes``, and ``source``. The submission must specify enclaves for
the indicators to be submitted to, and can optionally specify tags to assign to ... | 2.248817 | 2.366922 | 0.950102 |
indicators_page_generator = self._get_indicators_page_generator(
from_time=from_time,
to_time=to_time,
enclave_ids=enclave_ids,
included_tag_ids=included_tag_ids,
excluded_tag_ids=excluded_tag_ids,
page_number=start_page,
... | def get_indicators(self, from_time=None, to_time=None, enclave_ids=None,
included_tag_ids=None, excluded_tag_ids=None,
start_page=0, page_size=None) | Creates a generator from the |get_indicators_page| method that returns each successive indicator as an
|Indicator| object containing values for the 'value' and 'type' attributes only; all
other |Indicator| object attributes will contain Null values.
:param int from_time: start of time window in... | 1.966515 | 2.331088 | 0.843604 |
get_page = functools.partial(
self.get_indicators_page,
from_time=from_time,
to_time=to_time,
page_number=page_number,
page_size=page_size,
enclave_ids=enclave_ids,
included_tag_ids=included_tag_ids,
exclud... | def _get_indicators_page_generator(self, from_time=None, to_time=None, page_number=0, page_size=None,
enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None) | Creates a generator from the |get_indicators_page| method that returns each successive page.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago)
:param int to_time: end of time window in milliseconds since epoch (defaults to current time)
:param int p... | 1.729429 | 1.971409 | 0.877255 |
params = {
'from': from_time,
'to': to_time,
'pageSize': page_size,
'pageNumber': page_number,
'enclaveIds': enclave_ids,
'tagIds': included_tag_ids,
'excludedTagIds': excluded_tag_ids
}
resp = self._c... | def get_indicators_page(self, from_time=None, to_time=None, page_number=None, page_size=None,
enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None) | Get a page of indicators matching the provided filters.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago)
:param int to_time: end of time window in milliseconds since epoch (defaults to current time)
:param int page_number: the page number
:... | 2.14188 | 2.212252 | 0.96819 |
return Page.get_generator(page_generator=self._search_indicators_page_generator(search_term, enclave_ids,
from_time, to_time,
... | def search_indicators(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
indicator_types=None,
tags=None,
excluded_tags=None) | Uses the |search_indicators_page| method to create a generator that returns each successive indicator.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used... | 3.612436 | 3.503022 | 1.031234 |
get_page = functools.partial(self.search_indicators_page, search_term, enclave_ids,
from_time, to_time, indicator_types, tags, excluded_tags)
return Page.get_page_generator(get_page, start_page, page_size) | def _search_indicators_page_generator(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
indicator_types=None,
... | Creates a generator from the |search_indicators_page| method that returns each successive page.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to res... | 2.480026 | 2.901039 | 0.854875 |
body = {
'searchTerm': search_term
}
params = {
'enclaveIds': enclave_ids,
'from': from_time,
'to': to_time,
'entityTypes': indicator_types,
'tags': tags,
'excludedTags': excluded_tags,
'pa... | def search_indicators_page(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
indicator_types=None,
tags=None,
ex... | Search for indicators containing a search term.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict to indicators found in reports in specific... | 2.189547 | 2.285865 | 0.957864 |
return Page.get_generator(page_generator=self._get_related_indicators_page_generator(indicators, enclave_ids)) | def get_related_indicators(self, indicators=None, enclave_ids=None) | Uses the |get_related_indicators_page| method to create a generator that returns each successive report.
:param list(string) indicators: list of indicator values to search for
:param list(string) enclave_ids: list of GUIDs of enclaves to search in
:return: The generator. | 7.75116 | 7.680879 | 1.00915 |
result = self.get_indicators_metadata([Indicator(value=value)])
if len(result) > 0:
indicator = result[0]
return {
'indicator': indicator,
'tags': indicator.tags,
'enclaveIds': indicator.enclave_ids
}
e... | def get_indicator_metadata(self, value) | Provide metadata associated with a single indicators, including value, indicatorType, noteCount,
sightings, lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the
request has READ access to.
:param value: an indicator value to query.
:return... | 3.973871 | 2.130977 | 1.864812 |
data = [{
'value': i.value,
'indicatorType': i.type
} for i in indicators]
resp = self._client.post("indicators/metadata", data=json.dumps(data))
return [Indicator.from_dict(x) for x in resp.json()] | def get_indicators_metadata(self, indicators) | Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings,
lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has
READ access to.
:param indicators: a list of |Indicator| objects to quer... | 3.813091 | 3.834469 | 0.994425 |
# if the indicators parameter is a string, make it a singleton
if isinstance(indicators, string_types):
indicators = [indicators]
params = {
'enclaveIds': enclave_ids,
'indicatorValues': indicators
}
resp = self._client.get("indicato... | def get_indicator_details(self, indicators, enclave_ids=None) | NOTE: This method uses an API endpoint that is intended for internal use only, and is not officially supported.
Provide a list of indicator values and obtain details for all of them, including indicator_type, priority_level,
correlation_count, and whether they have been whitelisted. Note that the valu... | 3.289853 | 3.203262 | 1.027032 |
resp = self._client.post("whitelist", json=terms)
return [Indicator.from_dict(indicator) for indicator in resp.json()] | def add_terms_to_whitelist(self, terms) | Add a list of terms to the user's company's whitelist.
:param terms: The list of terms to whitelist.
:return: The list of extracted |Indicator| objects that were whitelisted. | 7.421949 | 5.188188 | 1.430548 |
params = indicator.to_dict()
self._client.delete("whitelist", params=params) | def delete_indicator_from_whitelist(self, indicator) | Delete an indicator from the user's company's whitelist.
:param indicator: An |Indicator| object, representing the indicator to delete. | 9.672304 | 12.364738 | 0.782249 |
params = {
'type': indicator_type,
'daysBack': days_back
}
resp = self._client.get("indicators/community-trending", params=params)
body = resp.json()
# parse items in response as indicators
return [Indicator.from_dict(indicator) for ind... | def get_community_trends(self, indicator_type=None, days_back=None) | Find indicators that are trending in the community.
:param indicator_type: A type of indicator to filter by. If ``None``, will get all types of indicators except
for MALWARE and CVEs (this convention is for parity with the corresponding view on the Dashboard).
:param days_back: The number ... | 4.427186 | 4.329218 | 1.022629 |
params = {
'pageNumber': page_number,
'pageSize': page_size
}
resp = self._client.get("whitelist", params=params)
return Page.from_dict(resp.json(), content_type=Indicator) | def get_whitelist_page(self, page_number=None, page_size=None) | Gets a paginated list of indicators that the user's company has whitelisted.
:param int page_number: the page number to get.
:param int page_size: the size of the page to be returned.
:return: A |Page| of |Indicator| objects. | 5.110573 | 3.873211 | 1.319467 |
params = {
'indicators': indicators,
'enclaveIds': enclave_ids,
'pageNumber': page_number,
'pageSize': page_size
}
resp = self._client.get("indicators/related", params=params)
return Page.from_dict(resp.json(), content_type=Indi... | def get_related_indicators_page(self, indicators=None, enclave_ids=None, page_size=None, page_number=None) | Finds all reports that contain any of the given indicators and returns correlated indicators from those reports.
:param indicators: list of indicator values to search for
:param enclave_ids: list of IDs of enclaves to search in
:param page_size: number of results per page
:param page_nu... | 3.136571 | 3.036819 | 1.032848 |
get_page = functools.partial(self.get_indicators_for_report_page, report_id=report_id)
return Page.get_page_generator(get_page, start_page, page_size) | def _get_indicators_for_report_page_generator(self, report_id, start_page=0, page_size=None) | Creates a generator from the |get_indicators_for_report_page| method that returns each successive page.
:param str report_id: The ID of the report to get indicators for.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator. | 3.029717 | 3.644781 | 0.831248 |
get_page = functools.partial(self.get_related_indicators_page, indicators, enclave_ids)
return Page.get_page_generator(get_page, start_page, page_size) | def _get_related_indicators_page_generator(self, indicators=None, enclave_ids=None, start_page=0, page_size=None) | Creates a generator from the |get_related_indicators_page| method that returns each
successive page.
:param indicators: list of indicator values to search for
:param enclave_ids: list of IDs of enclaves to search in
:param start_page: The page to start on.
:param page_size: The ... | 3.077937 | 4.015599 | 0.766495 |
return Page.get_page_generator(self.get_whitelist_page, start_page, page_size) | def _get_whitelist_page_generator(self, start_page=0, page_size=None) | Creates a generator from the |get_whitelist_page| method that returns each successive page.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator. | 5.132278 | 5.455901 | 0.940684 |
if colorlist is None:
colorlist = [get_atom_color(t) for t in self.topology['atom_types']]
if highlight is not None:
if isinstance(highlight, int):
colorlist[highlight] = 0xff0000
if isinstance(highlight, (list, np.ndarray)):
f... | def points(self, size=1.0, highlight=None, colorlist=None, opacity=1.0) | Display the system as points.
:param float size: the size of the points. | 3.035589 | 3.179901 | 0.954617 |
'''Display atomic labels for the system'''
if coordinates is None:
coordinates=self.coordinates
l=len(coordinates)
if text is None:
if len(self.topology.get('atom_types'))==l:
text=[self.topology['atom_types'][i]+str(i+1) for i in range(l)]
... | def labels(self, text=None, coordinates=None, colorlist=None, sizes=None, fonts=None, opacity=1.0) | Display atomic labels for the system | 3.51101 | 3.251498 | 1.079813 |
'''Remove all atomic labels from the system'''
for rep_id in self.representations.keys():
if self.representations[rep_id]['rep_type']=='text' and rep_id not in self._axes_reps:
self.remove_representation(rep_id) | def remove_labels(self) | Remove all atomic labels from the system | 7.52049 | 6.016767 | 1.249922 |
'''Toggle axes [x,y,z] on and off for the current representation
Parameters: dictionary of parameters to control axes:
position/p: origin of axes
length/l: length of axis
offset/o: offset to place axis labels
axis_colors/ac: axis colors
... | def toggle_axes(self, parameters = None) | Toggle axes [x,y,z] on and off for the current representation
Parameters: dictionary of parameters to control axes:
position/p: origin of axes
length/l: length of axis
offset/o: offset to place axis labels
axis_colors/ac: axis colors
te... | 2.712207 | 2.21505 | 1.224445 |
'''Display the system bonds as lines.
'''
if "bonds" not in self.topology:
return
bond_start, bond_end = zip(*self.topology['bonds'])
bond_start = np.array(bond_start)
bond_end = np.array(bond_end)
color_array = np.array([get_atom_color(t) for t in ... | def lines(self) | Display the system bonds as lines. | 2.89746 | 2.587281 | 1.119886 |
'''Display atoms as points of size *pointsize* and bonds as lines.'''
self.points(pointsize, opacity=opacity)
self.lines() | def wireframe(self, pointsize=0.2, opacity=1.0) | Display atoms as points of size *pointsize* and bonds as lines. | 11.850725 | 4.762286 | 2.488453 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.