code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if type(key) is int:
key = six.int2byte(key)
key_len = len(key)
return b''.join(
six.int2byte(c ^ six.indexbytes(key, i % key_len))
for i, c in enumerate(six.iterbytes(data))
) | def xor(key, data) | Perform cyclical exclusive or operations on ``data``.
The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If
the key is smaller than the provided ``data``, the ``key`` will be
repeated.
Args:
key(int or bytes): The key to xor ``data`` with.
data(bytes): The data to p... | 3.090917 | 3.106258 | 0.995061 |
if alphabet is None:
alphabet = set(i for i in range(256) if i not in (0, 10, 13))
else:
alphabet = set(six.iterbytes(alphabet))
if iv is None:
iv = b'\0' * len(data)
if len(data) != len(iv):
raise ValueError('length of iv differs from data')
if not min_depth... | def find_xor_mask(data, alphabet=None, max_depth=3, min_depth=0, iv=None) | Produce a series of bytestrings that when XORed together end up being
equal to ``data`` and only contain characters from the giving
``alphabet``. The initial state (or previous state) can be given as
``iv``.
Arguments:
data (bytes): The data to recreate as a series of XOR operations.
al... | 3.777266 | 3.719452 | 1.015544 |
alphabet = dict(
(chr(c), chr((c - s + shift) % (e - s + 1) + s))
for s, e in map(lambda r: (ord(r[0]), ord(r[-1])), shift_ranges)
for c in range(s, e + 1)
)
return ''.join(alphabet.get(c, c) for c in data) | def caesar(shift, data, shift_ranges=('az', 'AZ')) | Apply a caesar cipher to a string.
The caesar cipher is a substition cipher where each letter in the given
alphabet is replaced by a letter some fixed number down the alphabet.
If ``shift`` is ``1``, *A* will become *B*, *B* will become *C*, etc...
You can define the alphabets that will be shift by s... | 2.709153 | 3.537873 | 0.765758 |
v = binascii.hexlify(d).decode('ascii')
if separator:
return separator.join(
v[i:i+2]
for i in range(0, len(v), 2)
)
else:
return v | def enhex(d, separator='') | Convert bytes to their hexadecimal representation, optionally joined by a
given separator.
Args:
d(bytes): The data to convert to hexadecimal representation.
separator(str): The separator to insert between hexadecimal tuples.
Returns:
str: The hexadecimal representation of ``d``.
... | 2.672592 | 3.299739 | 0.80994 |
args.key = args.type(args.key)
return xor(args.key, pwnypack.main.binary_value_or_stdin(args.value)) | def xor_app(parser, cmd, args): # pragma: no cover
parser.add_argument(
'-d', '--dec',
help='interpret the key as a decimal integer',
dest='type',
action='store_const',
const=int
)
parser.add_argument(
'-x', '--hex',
help='interpret the key as a... | Xor a value with a key. | 8.41081 | 6.600141 | 1.274338 |
args.shift_ranges = ['az', 'AZ']
return caesar(args.shift, pwnypack.main.string_value_or_stdin(args.value), args.shift_ranges) | def caesar_app(parser, cmd, args): # pragma: no cover
parser.add_argument('shift', type=int, help='the shift to apply')
parser.add_argument('value', help='the value to caesar crypt, read from stdin if omitted', nargs='?')
parser.add_argument(
'-s', '--shift-range',
dest='shift_ranges'... | Caesar crypt a value with a key. | 8.570973 | 5.987997 | 1.431359 |
def rot13_app(parser, cmd, args): # pragma: no cover
parser.add_argument('value', help='the value to rot13, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
return rot13(pwnypack.main.string_value_or_stdin(args.value)) | rot13 encrypt a value. | null | null | null | |
def enb64_app(parser, cmd, args): # pragma: no cover
parser.add_argument('value', help='the value to base64 encode, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
return enb64(pwnypack.main.binary_value_or_stdin(args.value)) | base64 encode a value. | null | null | null | |
def deb64_app(parser, cmd, args): # pragma: no cover
parser.add_argument('value', help='the value to base64 decode, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
return deb64(pwnypack.main.string_value_or_stdin(args.value)) | base64 decode a value. | null | null | null | |
def enhex_app(parser, cmd, args): # pragma: no cover
parser.add_argument('value', help='the value to hex encode, read from stdin if omitted', nargs='?')
parser.add_argument(
'--separator', '-s',
default='',
help='the separator to place between hex tuples'
)
args = parser.p... | hex encode a value. | null | null | null | |
def dehex_app(parser, cmd, args): # pragma: no cover
parser.add_argument('value', help='the value to base64 decode, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
return dehex(pwnypack.main.string_value_or_stdin(args.value)) | hex decode a value. | null | null | null | |
def enurlform_app(parser, cmd, args): # pragma: no cover
parser.add_argument('values', help='the key=value pairs to URL encode', nargs='+')
args = parser.parse_args(args)
return enurlform(dict(v.split('=', 1) for v in args.values)) | encode a series of key=value pairs into a query string. | null | null | null | |
def deurlform_app(parser, cmd, args): # pragma: no cover
parser.add_argument('value', help='the query string to decode')
args = parser.parse_args(args)
return ' '.join('%s=%s' % (key, value) for key, values in deurlform(args.value).items() for value in values) | decode a query string into its key value pairs. | null | null | null | |
def frequency_app(parser, cmd, args): # pragma: no cover
parser.add_argument('value', help='the value to analyse, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
data = frequency(six.iterbytes(pwnypack.main.binary_value_or_stdin(args.value)))
return '\n'.join(
'0x%0... | perform frequency analysis on a value. | null | null | null | |
if self.state == 'half-open':
self.test_fail_count = min(self.test_fail_count + 1, 16)
self.errors.append(self.clock())
if len(self.errors) > self.maxfail:
time = self.clock() - self.errors.pop(0)
if time < self.time_unit:
if time == 0... | def error(self, err=None) | Update the circuit breaker with an error event. | 4.704003 | 4.28054 | 1.098928 |
if id not in self.circuits:
self.circuits[id] = self.factory(self.clock, self.log.getChild(id),
self.error_types, self.maxfail,
self.reset_timeout,
self.tim... | def context(self, id) | Return a circuit breaker for the given ID. | 5.564136 | 4.1501 | 1.340723 |
group.add_argument(
'--bpython',
action='store_const',
dest='shell',
const='bpython',
help='Use the bpython interpreter'
)
if have_IPython:
group.add_argument(
'--ipython',
action='store_const',
d... | def shell(_parser, cmd, args): # pragma: no cover
parser = argparse.ArgumentParser(
prog=_parser.prog,
description=_parser.description,
)
group = parser.add_mutually_exclusive_group()
group.set_defaults(shell=have_bpython and 'bpython' or (have_IPython and 'ipython' or 'python'))... | Start an interactive python interpreter with pwny imported globally. | 2.134785 | 1.953327 | 1.092897 |
if version is None:
version = default
if isinstance(version, dict):
return version
elif version in PY_INTERNALS:
return PY_INTERNALS[version]
else:
return ValueError('Unsupported python version %r requested.' % version) | def get_py_internals(version=None, default=None) | Given a version specification. It can be any dict which is returned
verbatim, an index into :data:`PY_INTERNALS` or ``None``.
Arguments:
version: The python version to return the internals of.
default: The python version that will be looked up if ``version`` is
None.
Returns:
... | 3.863662 | 3.568033 | 1.082855 |
return sorted(
self.stop_times(),
key=lambda x:int(x.get('stop_sequence'))
) | def stop_sequence(self) | Return the sorted StopTimes for this trip. | 7.682172 | 4.51958 | 1.699753 |
strokes, strokeSegments = _identifyStrokes(points)
return list(zip(strokes, strokeSegments)) | def getGestureAndSegments(points) | Returns a list of tuples. The first item in the tuple is the directional
integer, and the second item is a tuple of integers for the start and end
indexes of the points that make up the stroke. | 7.379014 | 7.261499 | 1.016183 |
if len(gestureList) == 0:
return None
#gestureList = [list(frozenset(tuple(gesture))) for gesture in gestureList] # make a unique list
gestureList = frozenset([tuple(gesture) for gesture in gestureList])
distances = {}
for g in gestureList:
levDist = levenshteinDistance(strokes... | def findClosestMatchingGesture(strokes, gestureList, maxDifference=None) | Returns the gesture(s) in `gestureList` that closest matches the gesture in
`strokes`. The `maxDifference` is how many differences there can be and still
be considered a match. | 3.443885 | 3.518101 | 0.978905 |
singleLetterMapping = {DOWNLEFT: '1', DOWN:'2', DOWNRIGHT:'3',
LEFT:'4', RIGHT:'6',
UPLEFT:'7', UP:'8', UPRIGHT:'9'}
len1 = len([singleLetterMapping[letter] for letter in s1])
len2 = len([singleLetterMapping[letter] for letter in s2])
matrix =... | def levenshteinDistance(s1, s2) | Returns the Levenshtein Distance between two strings, `s1` and `s2` as an
integer.
http://en.wikipedia.org/wiki/Levenshtein_distance
The Levenshtein Distance (aka edit distance) is how many changes (i.e.
insertions, deletions, substitutions) have to be made to convert one
string into another.
... | 1.81183 | 1.927884 | 0.939803 |
x1, y1 = coord1
x2, y2 = coord2
if x1 == x2 and y1 == y2:
return None # two coordinates are the same.
elif x1 == x2 and y1 > y2:
return UP
elif x1 == x2 and y1 < y2:
return DOWN
elif x1 > x2 and y1 == y2:
return LEFT
elif x1 < x2 and y1 == y2:
re... | def _getDirection(coord1, coord2) | Return the direction the line formed by the (x, y)
points in `coord1` and `coord2`. | 1.81776 | 1.797742 | 1.011135 |
xdist = coord1[0] - coord2[0]
ydist = coord1[1] - coord2[1]
return sqrt(xdist*xdist + ydist*ydist) | def _distance(coord1, coord2) | Return the distance between two points, `coord1` and `coord2`. These
parameters are assumed to be (x, y) tuples. | 1.859189 | 1.885246 | 0.986179 |
newfields = {}
for localized_field in model.localized_fields:
# get the descriptor, which contains the form field
default_field_descriptor = getattr(model, localized_field)
# See if we've got overridden fields in a custom form.
if hasattr(form, 'declared... | def make_localised_form(model, form, exclude=None) | This is a factory function that creates a form for a model with internationalised
field. The model should be decorated with the L10N decorater. | 4.19176 | 4.131664 | 1.014545 |
# set the localised fields
for localized_field in self.instance.localized_fields:
setattr(self.instance, localized_field, self.cleaned_data[localized_field])
return super(LocalisedForm, self).save(commit) | def save(self, commit=True) | Override save method to also save the localised fields. | 3.379396 | 2.427955 | 1.391869 |
form_errors = []
try:
super(LocalisedForm, self).validate_unique()
except ValidationError as e:
form_errors += e.messages
# add unique validation for the localized fields.
localized_fields_checks = self._get_localized_field_checks()
bad_f... | def validate_unique(self) | Validates the uniqueness of fields, but also handles the localized_fields. | 4.590236 | 4.236984 | 1.083373 |
localized_fields_checks = []
for localized_field in self.instance.localized_fields:
if self.cleaned_data.get(localized_field) is None:
continue
f = getattr(self.instance.__class__, localized_field, None)
if f and f.unique:
if f... | def _get_localized_field_checks(self) | Get the checks we must perform for the localized fields. | 3.128123 | 2.940583 | 1.063776 |
bad_fields = set()
form_errors = []
for (field_name, local_field_name) in unique_checks:
lookup_kwargs = {}
lookup_value = self.cleaned_data[field_name]
# ModelChoiceField will return an object instance rather than
# a raw pr... | def _perform_unique_localized_field_checks(self, unique_checks) | Do the checks for the localized fields. | 3.717717 | 3.665334 | 1.014291 |
missing_modules = []
for module in MODULES:
try:
__import__(module[1])
except ImportError:
missing_modules.append(module)
return missing_modules | def find_missing_modules() | look for dependency that setuptools cannot check or that are too painful to
install with setuptools | 2.886221 | 2.927232 | 0.98599 |
translation.activate(settings.LANGUAGE_CODE)
if app:
unpack = app.split('.')
if len(unpack) == 2:
models = [get_model(unpack[0], unpack[1])]
elif len(unpack) == 1:
models = get_models(get_app(unpack[0]))
else:
... | def handle(self, locale, app=None, **options) | command execution | 2.732767 | 2.736759 | 0.998541 |
try:
modified = request.session.modified
except AttributeError:
pass
else:
if modified or settings.SESSION_SAVE_EVERY_REQUEST:
if request.session.get_expire_at_browser_close():
max_age = None
exp... | def process_response(self, request, response) | If ``request.session was modified``, or if the configuration is to save
the session every time, save the changes and set a session cookie. | 2.005748 | 1.824743 | 1.099195 |
translation.activate(settings.LANGUAGE_CODE)
if app:
unpack = app.split('.')
if len(unpack) == 2:
models = [get_model(unpack[0], unpack[1])]
elif len(unpack) == 1:
models = get_models(get_app(unpack[0]))
else:
... | def handle(self, source, target, app=None, **options) | command execution | 2.348756 | 2.362658 | 0.994116 |
block_len = block_size // 8
assert len(ciphertext) % block_len == 0 and len(ciphertext) >= 2 * block_len
known_prefix = bytearray(known_prefix)
known_suffix = bytearray(known_suffix)
if alphabet is None:
alphabet = bytearray(range(256))
if block_pool is not None:
map_fun... | def padding_oracle_decrypt(oracle, ciphertext, known_prefix=b'', known_suffix=b'', block_size=128,
alphabet=None, pool=None, block_pool=None, progress=None) | Decrypt ciphertext using an oracle function that returns ``True`` if the
provided ciphertext is correctly PKCS#7 padded after decryption. The
cipher needs to operate in CBC mode.
Args:
oracle(callable): The oracle function. Will be called repeatedly with
a chunk of ciphertext.
c... | 2.891938 | 3.29965 | 0.876438 |
plaintext = bytearray(plaintext)
block_len = block_size // 8
padding_len = block_len - (len(plaintext) % block_len)
plaintext.extend([padding_len] * padding_len)
ciphertext = bytearray()
chunk = bytearray(os.urandom(block_len))
ciphertext[0:0] = chunk
for plain_start in range(l... | def padding_oracle_encrypt(oracle, plaintext, block_size=128, pool=None) | Encrypt plaintext using an oracle function that returns ``True`` if the
provided ciphertext is correctly PKCS#7 padded after decryption. The
cipher needs to operate in CBC mode.
Args:
oracle(callable): The oracle function. Will be called repeatedly with
a chunk of ciphertext.
pl... | 2.709825 | 2.961847 | 0.914911 |
kwargs = {
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='all', collection=collection, multiple=True,
**kwargs) | def all(cls, collection, skip=None, limit=None) | Returns all documents of the collection
:param collection Collection instance
:param skip The number of documents to skip in the query
:param limit The maximal amount of documents to return. The skip is applied before the limit restriction.
:returns Document list | 5.89657 | 6.074309 | 0.970739 |
kwargs = {
'newValue': new_value,
'options': {
'keepNull': keep_null,
'waitForSync': wait_for_sync,
'limit': limit,
}
}
return cls._construct_query(name='update-by-example',
... | def update_by_example(cls, collection, example_data, new_value, keep_null=False, wait_for_sync=None, limit=None) | This will find all documents in the collection that match the specified example object,
and partially update the document body with the new value specified. Note that document meta-attributes
such as _id, _key, _from, _to etc. cannot be replaced.
Note: the limit attribute is not sup... | 3.652832 | 4.433343 | 0.823945 |
kwargs = {
'options': {
'waitForSync': wait_for_sync,
'limit': limit,
}
}
return cls._construct_query(name='remove-by-example',
collection=collection, example=example_data, result=False,
... | def remove_by_example(cls, collection, example_data, wait_for_sync=None, limit=None) | This will find all documents in the collection that match the specified example object.
Note: the limit attribute is not supported on sharded collections. Using it will result in an error.
The options attributes waitForSync and limit can given yet without an ecapsulation into a json object.
... | 4.430525 | 5.241421 | 0.845291 |
kwargs = {
'index': index_id,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='by-example-hash',
collection=collection, example=example_data, multiple=allow_multiple,
... | def get_by_example_hash(cls, collection, index_id, example_data, allow_multiple=False, skip=None, limit=None) | This will find all documents matching a given example, using the specified hash index.
:param collection Collection instance
:param index_id ID of the index which should be used for the query
:param example_data The example document
:param allow_multiple If the query can... | 4.248242 | 4.715721 | 0.900868 |
kwargs = {
'index': index_id,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='by-example-skiplist',
collection=collection, example=example_data, multiple=allow_multiple,
... | def get_by_example_skiplist(cls, collection, index_id, example_data, allow_multiple=True, skip=None, limit=None) | This will find all documents matching a given example, using the specified skiplist index.
:param collection Collection instance
:param index_id ID of the index which should be used for the query
:param example_data The example document
:param allow_multiple If the query... | 3.945624 | 4.476197 | 0.881468 |
kwargs = {
'index': index_id,
'attribute': attribute,
'left': left,
'right': right,
'closed': closed,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='range',
... | def range(cls, collection, attribute, left, right, closed, index_id, skip=None, limit=None) | This will find all documents within a given range. In order to execute a range query, a
skip-list index on the queried attribute must be present.
:param collection Collection instance
:param attribute The attribute path to check
:param left The lower bound
:p... | 2.969144 | 3.348763 | 0.886639 |
kwargs = {
'index': index_id,
'attribute': attribute,
'query': example_text,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='fulltext',
collection=collection, multiple=Tru... | def fulltext(cls, collection, attribute, example_text, index_id, skip=None, limit=None) | This will find all documents from the collection that match the fulltext query specified in query.
In order to use the fulltext operator, a fulltext index must be defined for the collection
and the specified attribute.
:param collection Collection instance
:param attrib... | 3.700211 | 4.268397 | 0.866885 |
kwargs = {
'geo': index_id,
'latitude': latitude,
'longitude': longitude,
'distance': distance,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='near',
collecti... | def near(cls, collection, latitude, longitude, index_id, distance=None, skip=None, limit=None) | The default will find at most 100 documents near the given coordinate.
The returned list is sorted according to the distance, with the nearest document being first in the list.
If there are near documents of equal distance, documents are chosen randomly from this set until
the limit ... | 3.801403 | 3.948004 | 0.962867 |
model = self.get(**kwargs)
is_created = False
if model is None:
is_created = True
model = self._model_class()
for key, value in list(kwargs.items()):
setattr(model, key, value)
return model, is_created | def get_or_create(self, **kwargs) | Looks up an object with the given kwargs, creating one if necessary.
Returns a tuple of (object, created), where created is a boolean
specifying whether an object was created. | 2.744637 | 2.759216 | 0.994716 |
def return_fields(obj):
internal_fields = fields
if internal_fields is None:
internal_fields = {}
for attribute in dir(obj):
try:
attr_val = getattr(obj, attribute)
attr_cls = attr_val.__clas... | def get_all_fields(cls, class_obj=None, fields=None) | TODO: This needs to be properly used | 2.836829 | 2.807627 | 1.010401 |
if brightness is None:
brightness = self.brightness
if color is None:
color = self.color
return [(x / 255) * brightness for x in self._rgb_to_rgbw(color)] | def _get_pwm_values(self, brightness=None, color=None) | Get the pwm values for a specific state of the led.
If a state argument is omitted, current value is used.
:param brightness: The brightness of the state.
:param color: The color of the state.
:return: The pwm values. | 2.863996 | 3.578373 | 0.800363 |
# Get the maximum between R, G, and B
max_value = max(color)
# If the maximum value is 0, immediately return pure black.
if max_value == 0:
return [0] * 4
# Figure out what the color with 100% hue is
multiplier = 255 / max_value
hue_red = co... | def _rgb_to_rgbw(color) | Convert a RGB color to a RGBW color.
:param color: The RGB color.
:return: The RGBW color. | 2.598623 | 2.650694 | 0.980355 |
uri = URI.fromBytes(uri.encode(), defaultPort=5672)
kwargs = {}
host = uri.host.decode()
if "@" in host:
auth, host = uri.netloc.decode().split("@")
username, password = auth.split(":")
kwargs.update({"username": username, "password": password... | def from_uri(cls, reactor, uri) | Return an AMQEndpoint instance configured with the given AMQP uri.
@see: https://www.rabbitmq.com/uri-spec.html | 2.551603 | 2.712066 | 0.940834 |
# XXX Since AMQClient requires these parameters at __init__ time, we
# need to override them in the provided factory.
protocol_factory.set_vhost(self._vhost)
protocol_factory.set_heartbeat(self._heartbeat)
description = "tcp:{}:{}:timeout={}".format(
sel... | def connect(self, protocol_factory) | Connect to the C{protocolFactory} to the AMQP broker specified by the
URI of this endpoint.
@param protocol_factory: An L{AMQFactory} building L{AMQClient} objects.
@return: A L{Deferred} that results in an L{AMQClient} upon successful
connection otherwise a L{Failure} wrapping L{Co... | 5.6151 | 5.607512 | 1.001353 |
yield client.authenticate(
self._username, self._password, mechanism=self._auth_mechanism)
returnValue(client) | def _authenticate(self, client) | Perform AMQP authentication. | 7.314119 | 4.860981 | 1.504659 |
'''Create a BlockText from the captured lines and clear _text.'''
if self._text:
self._blocks.append(BlockText('\n'.join(self._text)))
self._text.clear() | def _reset_plain(self) | Create a BlockText from the captured lines and clear _text. | 11.111258 | 3.291044 | 3.376211 |
if self.cancelled or self.finished:
return
if not self.pwm_stages:
self._finish()
return
if self.duration == 0:
progress = 1
else:
run_time = time.time() - self._start_time
progress = max(0, min(1, run_tim... | def step(self) | Apply the current stage of the transition based on current time. | 3.164602 | 2.938191 | 1.077058 |
self.finished = True
if self._callback:
self._callback(self)
self._finish_event.set() | def _finish(self) | Mark transition as finished and execute callback. | 5.538775 | 3.529036 | 1.569487 |
"Send a syslog message to remote host using UDP or TCP"
data = "<%d>%s" % (level + self.facility*8, message)
if self.protocol == 'UDP':
self.socket.sendto(data.encode('utf-8'), (self.host, self.port))
else:
self.socket.send(data.encode('utf-8')) | def send(self, message, level=Level.NOTICE) | Send a syslog message to remote host using UDP or TCP | 3.937006 | 3.218829 | 1.223117 |
'''Render #for loop with given namespace.
Note: we copy the namespace so the parsed variable is only
available in nested objects within this #for loop.
'''
ns = namespace.copy()
result = []
for item in namespace[self._items]:
ns[self._item] = it... | def render(self, namespace) | Render #for loop with given namespace.
Note: we copy the namespace so the parsed variable is only
available in nested objects within this #for loop. | 7.620978 | 2.682399 | 2.841105 |
'''Return both variable names used in the #for loop in the
current line.'''
m = cls.RE_FOR.match(lines.current)
if m is None:
raise DefineBlockError(
'Incorrect block definition at line {}, {}\nShould be '
'something like: #for @item in @items:... | def _compile(cls, lines) | Return both variable names used in the #for loop in the
current line. | 9.672572 | 4.774477 | 2.025892 |
if self['id'] is None:
return
remote_graph = graph_commons.graphs(self['id'])
# TODO: less forceful, more elegant
self.edges = remote_graph.edges
self.nodes = remote_graph.nodes
self.node_types = remote_graph.node_types
self.edge_types = rem... | def sync(self, graph_commons) | Synchronize local and remote representations. | 2.345684 | 2.288917 | 1.024801 |
self._transitions.append(transition)
if self._thread is None or not self._thread.isAlive():
self._thread = threading.Thread(target=self._transition_loop)
self._thread.setDaemon(True)
self._thread.start() | def execute(self, transition) | Queue a transition for execution.
:param transition: The transition | 2.392241 | 2.686136 | 0.890588 |
while self._transitions:
start = time.time()
for transition in self._transitions:
transition.step()
if transition.finished:
self._transitions.remove(transition)
time_delta = time.time() - start
sleep_ti... | def _transition_loop(self) | Execute all queued transitions step by step. | 2.779166 | 2.367261 | 1.174 |
if cancel_transition:
self._cancel_active_transition()
if is_on is not None:
self._is_on = is_on
if brightness is not None:
self._assert_is_brightness(brightness)
self._brightness = brightness
self._update_pwm() | def set(self, is_on=None, brightness=None, cancel_transition=True) | Set properties of the led simultaneously before updating pwm values.
:param is_on: On-off state of the led.
:param brightness: Brightness of the led.
:param cancel_transition: Cancel active transitions. | 2.813307 | 2.9179 | 0.964155 |
if self._is_on:
values = self._get_pwm_values()
else:
values = [0] * len(self._driver.pins)
self._driver.set_pwm(values) | def _update_pwm(self) | Update the pwm values of the driver regarding the current state. | 4.26093 | 3.172357 | 1.343143 |
self._cancel_active_transition()
dest_state = self._prepare_transition(is_on, **kwargs)
total_steps = self._transition_steps(**dest_state)
state_stages = [self._transition_stage(step, total_steps, **dest_state)
for step in range(total_steps)]
pwm... | def transition(self, duration, is_on=None, **kwargs) | Transition to the specified state of the led.
If another transition is already running, it is aborted.
:param duration: The duration of the transition.
:param is_on: The on-off state to transition to.
:param kwargs: The state to transition to. | 4.210678 | 4.103928 | 1.026012 |
# Update state properties
if transition.state_stages:
state = transition.state_stages[transition.stage_index]
if self.is_on and is_on is False:
# If led was turned off, set brightness to initial value
# so that the brightness is restored w... | def _transition_callback(self, is_on, transition) | Callback that is called when a transition has ended.
:param is_on: The on-off state to transition to.
:param transition: The transition that has ended. | 6.87915 | 7.576892 | 0.907912 |
# Handle transitions with changing on-off-state
dest_state = kwargs.copy()
if is_on is not None:
if is_on and not self.is_on:
if 'brightness' not in kwargs or kwargs['brightness'] is None:
dest_state['brightness'] = self.brightness
... | def _prepare_transition(self, is_on=None, **kwargs) | Perform pre-transition tasks and construct the destination state.
:param is_on: The on-off state to transition to.
:param kwargs: The state to transition to.
:return: The destination state of the transition. | 3.812959 | 4.083505 | 0.933747 |
if brightness is not None:
self._assert_is_brightness(brightness)
return self._driver.steps(self.brightness, brightness)
return 0 | def _transition_steps(self, brightness=None) | Get the maximum number of steps needed for a transition.
:param brightness: The brightness to transition to (0.0-1.0).
:return: The maximum number of steps. | 6.977046 | 7.313926 | 0.95394 |
if brightness is not None:
self._assert_is_brightness(brightness)
brightness = self._interpolate(self.brightness, brightness,
step, total_steps)
return {'brightness': brightness} | def _transition_stage(self, step, total_steps, brightness=None) | Get a transition stage at a specific step.
:param step: The current step.
:param total_steps: The total number of steps.
:param brightness: The brightness to transition to (0.0-1.0).
:return: The stage at the specific step. | 5.1446 | 6.591062 | 0.780542 |
diff = end - start
progress = step / (total_steps - 1)
return start + progress * diff | def _interpolate(start, end, step, total_steps) | Interpolate a value from start to end at a given progress.
:param start: The start value.
:param end: The end value.
:param step: The current step.
:param total_steps: The total number of steps.
:return: The interpolated value at the given progress. | 4.626277 | 4.457786 | 1.037797 |
if cls.class_instance is None:
if hostname is None and auth is None and protocol is None and port is None and database is None:
cls.class_instance = Client(hostname='localhost')
else:
cls.class_instance = Client(hostname=hostname, auth=auth, prot... | def instance(cls, hostname=None, auth=None, protocol=None, port=None, database=None) | This method is called from everywhere in the code which accesses the database.
If one of the parameters is set, these variables are overwritten for all others. | 1.729948 | 1.769621 | 0.977581 |
return Collection(
name=name,
api_resource=self.api.collection(name),
api=self.api,
) | def collection(self, name) | Returns a collection with the given name
:param name Collection name
:returns Collection | 5.918635 | 7.687397 | 0.769914 |
api = Client.instance().api
database_data = {
'name': name,
'active': True,
}
if isinstance(users, list) or isinstance(users, tuple):
database_data['users'] = users
data = api.database.post(data=database_data)
db = Databas... | def create(cls, name, users=None) | Creates database and sets itself as the active database.
:param name Database name
:returns Database | 3.761882 | 3.477702 | 1.081715 |
api = Client.instance().api
data = api.database.get()
database_names = data['result']
databases = []
for name in database_names:
db = Database(name=name, api=api)
databases.append(db)
return databases | def get_all(cls) | Returns an array with all databases
:returns Database list | 4.968804 | 3.965709 | 1.252942 |
client = Client.instance()
new_current_database = None
if client.database != name:
new_current_database = name
# Deletions are only possible from the system database
client.set_database(name=SYSTEM_DATABASE)
api = client.api
api.database(... | def remove(cls, name) | Destroys the database. | 5.313475 | 4.622061 | 1.14959 |
return Collection.create(name=name, database=self.name, type=type) | def create_collection(self, name, type=2) | Shortcut to create a collection
:param name Collection name
:param type Collection type (2 = document / 3 = edge)
:returns Collection | 7.592795 | 12.786579 | 0.59381 |
client = Client.instance()
api = client.api
if client.database != database:
database = client.database
collection_data = {
'name': name,
'type': type,
}
data = api.collection.post(data=collection_data)
collection =... | def create(cls, name, database=SYSTEM_DATABASE, type=2) | Creates collection
:param name Collection name
:param database Database name in which it is created
:param type Collection type (2 = document / 3 = edge)
:returns Collection | 3.987648 | 4.786437 | 0.833114 |
api = Client.instance().api
api.collection(name).delete() | def remove(cls, name) | Destroys collection.
:param name Collection name | 29.339085 | 20.451162 | 1.434593 |
data = {
'waitForSync': self.waitForSync,
'journalSize': self.journalSize,
}
self.resource(self.name).properties.put(data) | def save(self) | Updates only waitForSync and journalSize | 11.396829 | 4.557025 | 2.500936 |
data = self.resource(self.name).properties.get()
self.set_data(**data)
return data | def get(self) | Retrieves all properties again for the collection and
sets the attributes. | 15.093967 | 9.492196 | 1.590145 |
data = self.resource(self.name).figures.get()
return data['figures'] | def get_figures(self) | Returns figures about the collection. | 17.070162 | 10.532085 | 1.620777 |
return Edge.create(
collection=self,
from_doc=from_doc,
to_doc=to_doc,
edge_data=edge_data
) | def create_edge(self, from_doc, to_doc, edge_data={}) | Creates edge document.
:param from_doc Document from which the edge comes
:param to_doc Document to which the edge goes
:param edge_data Extra data for the edge
:returns Document | 2.782557 | 3.576076 | 0.778104 |
document_list = []
document_uri_list = self.api.document.get(collection=self.name)['documents']
for document_uri in document_uri_list:
splitted_uri = document_uri.split('/')
document_key = splitted_uri[-1]
document_id = "%s/%s" % (self.name, document... | def documents(self) | Returns all documents of this collection.
:returns Document list | 2.787877 | 2.633825 | 1.05849 |
api = Client.instance().api
doc = Document(
id='',
key='',
collection=collection.name,
api=api,
)
return doc | def create(cls, collection) | Creates document object without really creating it in the collection.
:param collection Collection instance
:returns Document | 10.62706 | 10.099011 | 1.052287 |
data = self.resource(self.id).get()
self.data = data
return data | def retrieve(self) | Retrieves all data for this document and saves it. | 11.00127 | 7.362937 | 1.494141 |
# TODO: Add option force_insert
if not self.is_loaded and self.id is None or self.id == '':
data = self.resource.post(data=self.data, collection=self.collection)
self.id = data['_id']
self.key = data['_key']
self.revision = data['_rev']
... | def save(self) | If its internal state is loaded than it will only updated the
set properties but otherwise it will create a new document. | 3.869301 | 3.389665 | 1.1415 |
if not self.is_loaded:
self.retrieve()
self.is_loaded = True
if self.has(key=key):
return self.data[key]
else:
return None | def get(self, key) | Returns attribute value.
:param key
:returns value | 4.405188 | 4.346202 | 1.013572 |
for i in range(len(self._pins)):
self._pi.set_PWM_dutycycle(self._pins[i], raw_values[i]) | def _set_pwm(self, raw_values) | Set pwm values on the controlled pins.
:param raw_values: Raw values to set (0-255). | 2.678008 | 2.93777 | 0.911579 |
'''Return the filename from the current line.'''
m = cls.RE_EXTEND.match(lines.current)
if m is None:
raise DefineBlockError('''Incorrect block definition at line {}, {}
Should be something like: #extend path/foo.html:'''.format(
lines.pos, lines.current))
ret... | def _compile(cls, lines) | Return the filename from the current line. | 10.207659 | 7.808933 | 1.307177 |
if len(values) != len(self._pins):
raise ValueError('Number of values has to be identical with '
'the number of pins.')
if not all(0 <= v <= 1 for v in values):
raise ValueError('Values must be between 0 and 1.')
for tries in range(s... | def set_pwm(self, values) | Set pwm values on the controlled pins.
:param values: Values to set (0.0-1.0).
:return: | 3.025697 | 3.058974 | 0.989121 |
return [self._to_single_raw_pwm(values[i])
for i in range(len(self._pins))] | def _to_raw_pwm(self, values) | Convert uniform pwm values to raw, driver-specific values.
:param values: The uniform pwm values (0.0-1.0).
:return: Converted, driver-specific pwm values. | 5.598271 | 9.459597 | 0.591809 |
return [self._to_single_uniform_pwm(values[i])
for i in range(len(self._pins))] | def _to_uniform_pwm(self, values) | Convert raw pwm values to uniform values.
:param values: The raw pwm values.
:return: Converted, uniform pwm values (0.0-1.0). | 5.74897 | 8.605832 | 0.668032 |
if not 0 <= start <= 1:
raise ValueError('Values must be between 0 and 1.')
if not 0 <= end <= 1:
raise ValueError('Values must be between 0 and 1.')
raw_start = self._to_single_raw_pwm(start)
raw_end = self._to_single_raw_pwm(end)
return abs(raw... | def steps(self, start, end) | Get the maximum number of steps the driver needs for a transition.
:param start: The start value as uniform pwm value (0.0-1.0).
:param end: The end value as uniform pwm value (0.0-1.0).
:return: The maximum number of steps. | 2.69351 | 2.615165 | 1.029958 |
for i in range(len(self._pins)):
self._device.set_pwm(self._pins[i], 0, raw_values[i]) | def _set_pwm(self, raw_values) | Set pwm values on the controlled pins.
:param raw_values: Raw values to set (0-4095). | 3.013167 | 3.500454 | 0.860793 |
free = c_longlong()
if node < 0 or node > get_max_node():
raise ValueError(node)
size = libnuma.numa_node_size64(node, byref(free))
return (free.value, size) | def get_node_size(node) | Get size of memory on C{node}.
@param node: node idx
@type node: C{int}
@return: free memory/total memory
@rtype: C{tuple}(C{int}, C{int}) | 5.734698 | 5.170325 | 1.109156 |
result = set()
if node < 0 or node > get_max_node():
raise ValueError(node)
mask = bitmask_t()
mask.maskp = (c_ulong * (NUMA_NUM_NODES/(sizeof(c_ulong)*8)))()
mask.size = NUMA_NUM_NODES
if libnuma.numa_node_to_cpus(node, byref(mask)) < 0:
raise RuntimeError(node)
fo... | def node_to_cpus(node) | Get CPUs available on C{node}.
@return: set of CPU ids
@rtype: C{set} | 3.301609 | 3.405055 | 0.96962 |
result = set()
for i in range(0, get_max_node() + 1):
if __nodemask_isset(mask, i):
result.add(i)
return result | def numa_nodemask_to_set(mask) | Convert NUMA nodemask to Python set. | 4.574431 | 4.112028 | 1.112452 |
result = nodemask_t()
__nodemask_zero(result)
for i in range(0, get_max_node() + 1):
if i in mask:
__nodemask_set(result, i)
return result | def set_to_numa_nodemask(mask) | Conver Python set to NUMA nodemask. | 4.669351 | 4.28351 | 1.090076 |
mask = set_to_numa_nodemask(nodemask)
tmp = bitmask_t()
tmp.maskp = cast(byref(mask), POINTER(c_ulong))
tmp.size = sizeof(nodemask_t) * 8
libnuma.numa_set_interleave_mask(byref(tmp)) | def set_interleave_mask(nodemask) | Sets the memory interleave mask for the current thread to C{nodemask}.
@param nodemask: node mask
@type nodemask: C{set} | 5.526179 | 5.770515 | 0.957658 |
nodemask = nodemask_t()
bitmask = libnuma.numa_get_interleave_mask()
libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))
libnuma.numa_bitmask_free(bitmask)
return numa_nodemask_to_set(nodemask) | def get_interleave_mask() | Get interleave mask for current thread.
@return: node mask
@rtype: C{set} | 4.776483 | 4.401698 | 1.085146 |
mask = set_to_numa_nodemask(nodemask)
bitmask = libnuma.numa_allocate_nodemask()
libnuma.copy_nodemask_to_bitmask(byref(mask), bitmask)
libnuma.numa_bind(bitmask)
libnuma.numa_bitmask_free(bitmask) | def bind(nodemask) | Binds the current thread and its children to the nodes specified in nodemask.
They will only run on the CPUs of the specified nodes and only be able to allocate memory from them.
@param nodemask: node mask
@type nodemask: C{set} | 4.180471 | 4.790062 | 0.872738 |
if node < 0 or node > get_max_node():
raise ValueError(node)
libnuma.numa_set_preferred(node) | def set_preferred(node) | Sets the preferred node for the current thread to node.
The preferred node is the node on which memory is preferably allocated before falling back to other
nodes. The default is to use the node on which the process is currently running (local policy).
@param node: node idx
@type node: C{int} | 6.347509 | 7.556986 | 0.839952 |
mask = set_to_numa_nodemask(nodemask)
tmp = bitmask_t()
tmp.maskp = cast(byref(mask), POINTER(c_ulong))
tmp.size = sizeof(nodemask_t) * 8
libnuma.numa_set_membind(byref(tmp)) | def set_membind(nodemask) | Sets the memory allocation mask.
The thread will only allocate memory from the nodes set in nodemask.
@param nodemask: node mask
@type nodemask: C{set} | 5.790381 | 7.133286 | 0.811741 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.