code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
rows = (line.split() for line in sacct_stream)
# filter rows that begin with a SLURM job id
relevant_rows = (row for row in rows if row[0].isdigit())
jobs = [convert_job(row) for row in relevant_rows]
return jobs | def parse_sacct(sacct_stream) | Parse out information from sacct status output. | 4.221974 | 4.179748 | 1.010103 |
categories = FAILED_CATEGORIES if failed else NORMAL_CATEGORIES
filtered_jobs = [job for job in sacct_jobs if job['state'] in categories]
return filtered_jobs | def filter_jobs(sacct_jobs, failed=True) | Filter jobs that have a FAILED etc. status. | 3.554856 | 3.701653 | 0.960343 |
ys = segments[:, 1]
closeness = numpy.abs(numpy.subtract.outer(ys, lines)) # each row a y, each collumn a distance to each line
line_of_y = numpy.argmin(closeness, axis=1)
distance = numpy.min(closeness, axis=1)
bad = distance > numpy.mean(distance) + nearline_tolerance * numpy.std(distance)
... | def guess_segments_lines(segments, lines, nearline_tolerance=5.0) | given segments, outputs a array of line numbers, or -1 if it
doesn't belong to any | 3.911607 | 3.770662 | 1.037379 |
x1, y1 = segments[:, 0], segments[:, 1]
x2, y2 = x1 + segments[:, 2], y1 + segments[:, 3]
n = len(segments)
x1so, x2so, y1so, y2so = list(map(numpy.argsort, (x1, x2, y1, y2)))
x1soi, x2soi, y1soi, y2soi = list(map(numpy.argsort, (x1so, x2so, y1so, y2so))) # inverse transformations
# let r... | def contained_segments_matrix(segments) | givens a n*n matrix m, n=len(segments), in which m[i,j] means
segments[i] is contained inside segments[j] | 2.260067 | 2.219582 | 1.01824 |
# sort_f= lambda r: max_line_width*(r[1]/max_line_height)+r[0]
# segments= sorted(segments, key=sort_f)
# segments= segments_to_numpy( segments )
# return segments
mlh, mlw = self.max_line_height, self.max_line_width
s = segments.astype(numpy.uint32) # prevent o... | def _process(self, segments) | sort segments in read order - left to right, up to down | 5.081604 | 4.731227 | 1.074056 |
ys = ys.astype(numpy.float32)
compactness_list, means_list, diffs, deviations = [], [], [], []
start_n = 1
for k in range(start_n, min(len(ys), max_lines)):
compactness, classified_points, means = cv2.kmeans(data=ys, K=k, bestLabels=None, criteria=(
cv2.T... | def _guess_lines(ys, max_lines=50, confidence_minimum=0.0) | guesses and returns text inter-line distance, number of lines, y_position of first line | 3.613542 | 3.599818 | 1.003813 |
# Socket to talk to server
socket = get_context().socket(REQ)
try:
socket.setsockopt(LINGER, timeout * 1000)
if address.find(":") == -1:
socket.connect("tcp://%s:%d" % (address, self.default_port))
else:
socket.connect(... | def _send_to_address(self, address, data, timeout=10) | send data to *address* and *port* without verification of response. | 3.486395 | 3.487103 | 0.999797 |
self._is_running = True
network_fail = False
try:
while self._do_run:
try:
if network_fail is True:
LOGGER.info("Network connection re-established!")
network_fail = False
... | def _run(self) | Broadcasts forever. | 3.334497 | 3.124428 | 1.067235 |
res_type = json['sys']['type']
if ResourceType.Array.value == res_type:
return self.create_array(json)
elif ResourceType.Entry.value == res_type:
return self.create_entry(json)
elif ResourceType.Asset.value == res_type:
return ResourceFactory... | def from_json(self, json) | Create resource out of JSON data.
:param json: JSON dict.
:return: Resource with a type defined by the given JSON data. | 2.553416 | 2.47138 | 1.033194 |
sys = json['sys']
ct = sys['contentType']['sys']['id']
fields = json['fields']
raw_fields = copy.deepcopy(fields)
# Replace links with :class:`.resources.ResourceLink` objects.
for k, v in fields.items():
link = ResourceFactory._extract_link(v)
... | def create_entry(self, json) | Create :class:`.resources.Entry` from JSON.
:param json: JSON dict.
:return: Entry instance. | 3.214179 | 2.820422 | 1.139609 |
result = Asset(json['sys'])
file_dict = json['fields']['file']
result.fields = json['fields']
result.url = file_dict['url']
result.mimeType = file_dict['contentType']
return result | def create_asset(json) | Create :class:`.resources.Asset` from JSON.
:param json: JSON dict.
:return: Asset instance. | 4.88193 | 5.239195 | 0.931809 |
result = ContentType(json['sys'])
for field in json['fields']:
field_id = field['id']
del field['id']
result.fields[field_id] = field
result.name = json['name']
result.display_field = json.get('displayField')
return result | def create_content_type(json) | Create :class:`.resource.ContentType` from JSON.
:param json: JSON dict.
:return: ContentType instance. | 3.776445 | 3.871714 | 0.975393 |
clz = field.field_type
if clz is Boolean:
if not isinstance(value, bool):
return bool(value)
elif clz is Date:
if not isinstance(value, str):
value = str(value)
return parser.parse(value)
elif clz is Number:
... | def convert_value(value, field) | Given a :class:`.fields.Field` and a value, ensure that the value matches the given type, otherwise
attempt to convert it.
:param value: field value.
:param field: :class:`.fields.Field` instance.
:return: Result value. | 3.459926 | 3.166742 | 1.092582 |
for item in json['items']:
key = None
processed = self.from_json(item)
if isinstance(processed, Asset):
key = 'Asset'
elif isinstance(processed, Entry):
key = 'Entry'
if key is not None:
array.... | def process_array_items(self, array, json) | Iterate through all `items` and create a resource for each.
In addition map the resources under the `items_mapped` by the resource id and type.
:param array: Array resource.
:param json: Raw JSON dictionary. | 5.09729 | 4.508392 | 1.130623 |
includes = json.get('includes') or {}
for key in array.items_mapped.keys():
if key in includes:
for resource in includes[key]:
processed = self.from_json(resource)
array.items_mapped[key][processed.sys['id']] = processed | def process_array_includes(self, array, json) | Iterate through all `includes` and create a resource for every item.
In addition map the resources under the `items_mapped` by the resource id and type.
:param array: Array resource.
:param json: Raw JSON dictionary. | 5.71914 | 4.670363 | 1.22456 |
result = Array(json['sys'])
result.total = json['total']
result.skip = json['skip']
result.limit = json['limit']
result.items = []
result.items_mapped = {'Asset': {}, 'Entry': {}}
self.process_array_items(result, json)
self.process_array_includes... | def create_array(self, json) | Create :class:`.resources.Array` from JSON.
:param json: JSON dict.
:return: Array instance. | 4.688697 | 4.776437 | 0.981631 |
@wraps(method)
def apply_clear_and_verify(*args, **kw):
clear_calls()
method(*args, **kw)
verify() # if no exceptions
return apply_clear_and_verify | def with_fakes(method) | Decorator that calls :func:`fudge.clear_calls` before method() and :func:`fudge.verify` afterwards. | 5.790043 | 3.47571 | 1.665859 |
self.clear_actual_calls()
for stack in self.call_stacks:
stack.reset()
for fake, call_order in self.get_expected_call_order().items():
call_order.reset_calls() | def clear_calls(self) | Clears out any calls that were made on previously
registered fake objects and resets all call stacks.
You do not need to use this directly. Use fudge.clear_calls() | 7.321195 | 5.927469 | 1.23513 |
try:
for exp in self.get_expected_calls():
exp.assert_called()
exp.assert_times_called()
for fake, call_order in self.get_expected_call_order().items():
call_order.assert_order_met(finalize=True)
finally:
self.c... | def verify(self) | Ensure all expected calls were called,
raise AssertionError otherwise.
You do not need to use this directly. Use fudge.verify() | 7.608916 | 6.476141 | 1.174915 |
error = None
actual_call_len = len(self._actual_calls)
expected_call_len = len(self._call_order)
if actual_call_len == 0:
error = "Not enough calls were made"
else:
for i,call in enumerate(self._call_order):
if actual_call_len < i... | def assert_order_met(self, finalize=False) | assert that calls have been made in the right order. | 3.530578 | 3.419132 | 1.032595 |
self._callable = ExpectedCall(self, call_name=self._name,
callable=True)
return self | def expects_call(self) | The fake must be called.
.. doctest::
:hide:
>>> import fudge
>>> fudge.clear_expectations()
>>> fudge.clear_calls()
This is useful for when you stub out a function
as opposed to a class. For example::
>>> import fudge
... | 16.267586 | 34.489582 | 0.471667 |
self._callable = Call(self, call_name=self._name, callable=True)
return self | def is_callable(self) | The fake can be called.
This is useful for when you stub out a function
as opposed to a class. For example::
>>> import fudge
>>> remove = Fake('os.remove').is_callable()
>>> remove('some/path') | 14.766088 | 22.308022 | 0.661918 |
exp = self._get_current_call()
exp.call_replacement = call
return self | def calls(self, call) | Redefine a call.
The fake method will execute your function. I.E.::
>>> f = Fake().provides('hello').calls(lambda: 'Why, hello there')
>>> f.hello()
'Why, hello there' | 16.448473 | 26.046892 | 0.631495 |
if call_name in self._declared_calls:
return self.next_call(for_method=call_name)
self._last_declared_call_name = call_name
c = ExpectedCall(self, call_name, call_order=self._expected_call_order)
self._declare_call(call_name, c)
return self | def expects(self, call_name) | Expect a call.
.. doctest::
:hide:
>>> import fudge
>>> fudge.clear_expectations()
>>> fudge.clear_calls()
If the method *call_name* is never called, then raise an error. I.E.::
>>> session = Fake('session').expects('open').expects('close'... | 4.530319 | 4.983026 | 0.90915 |
last_call_name = self._last_declared_call_name
if for_method:
if for_method not in self._declared_calls:
raise FakeDeclarationError(
"next_call(for_method=%r) is not possible; "
"declare expects(%r) or provides(... | def next_call(self, for_method=None) | Start expecting or providing multiple calls.
.. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called`
Up until calling this method, calls are infinite.
For example, before next_call() ... ::
>>> from fudge import Fake
>>> f = Fake().pro... | 4.251662 | 4.049253 | 1.049987 |
if call_name in self._declared_calls:
return self.next_call(for_method=call_name)
self._last_declared_call_name = call_name
c = Call(self, call_name)
self._declare_call(call_name, c)
return self | def provides(self, call_name) | Provide a call.
The call acts as a stub -- no error is raised if it is not called.::
>>> session = Fake('session').provides('open').provides('close')
>>> import fudge
>>> fudge.clear_expectations() # from any previously declared fakes
>>> fudge.clear_calls()
... | 4.520751 | 5.576722 | 0.810647 |
exp = self._get_current_call()
exp.exception_to_raise = exc
return self | def raises(self, exc) | Set last call to raise an exception class or instance.
For example::
>>> import fudge
>>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert"))
>>> db.insert()
Traceback (most recent call last):
...
... | 12.100659 | 13.932117 | 0.868544 |
if self._callable:
raise FakeDeclarationError(
"remember_order() cannot be used for Fake(callable=True) or Fake(expect_call=True)")
self._expected_call_order = ExpectedCallOrder(self)
registry.remember_expected_call_order(self._expected_call_order)
... | def remember_order(self) | Verify that subsequent :func:`fudge.Fake.expects` are called in the right order.
For example::
>>> import fudge
>>> db = fudge.Fake('db').remember_order().expects('insert').expects('update')
>>> db.update()
Traceback (most recent call last):
...
... | 7.167981 | 9.998653 | 0.716895 |
exp = self._get_current_call()
exp.return_val = val
return self | def returns(self, val) | Set the last call to return a value.
Set a static value to return when a method is called. I.E.::
>>> f = Fake().provides('get_number').returns(64)
>>> f.get_number()
64 | 10.362077 | 18.987858 | 0.545721 |
exp = self._get_current_call()
endpoint = kwargs.get('name', exp.call_name)
name = self._endpoint_name(endpoint)
kwargs['name'] = '%s()' % name
fake = self.__class__(*args, **kwargs)
exp.return_val = fake
return fake | def returns_fake(self, *args, **kwargs) | Set the last call to return a new :class:`fudge.Fake`.
Any given arguments are passed to the :class:`fudge.Fake` constructor
Take note that this is different from the cascading nature of
other methods. This will return an instance of the *new* Fake,
not self, so you should be careful ... | 6.210742 | 7.103909 | 0.874271 |
if self._last_declared_call_name:
actual_last_call = self._declared_calls[self._last_declared_call_name]
if isinstance(actual_last_call, CallStack):
raise FakeDeclarationError("Cannot use times_called() in combination with next_call()")
# else: # self._ca... | def times_called(self, n) | Set the number of times an object can be called.
When working with provided calls, you'll only see an
error if the expected call count is exceeded ::
>>> auth = Fake('auth').provides('login').times_called(1)
>>> auth.login()
>>> auth.login()
Traceback (m... | 8.046763 | 7.971763 | 1.009408 |
exp = self._get_current_call()
if args:
exp.expected_args = args
if kwargs:
exp.expected_kwargs = kwargs
return self | def with_args(self, *args, **kwargs) | Set the last call to expect specific argument values.
The app under test must send all declared arguments and keyword arguments
otherwise your test will raise an AssertionError. For example:
.. doctest::
>>> import fudge
>>> counter = fudge.Fake('counter').expects('in... | 4.651921 | 7.465679 | 0.623108 |
exp = self._get_current_call()
if args:
exp.expected_matching_args = args
if kwargs:
exp.expected_matching_kwargs = kwargs
return self | def with_matching_args(self, *args, **kwargs) | Set the last call to expect specific argument values if those arguments exist.
Unlike :func:`fudge.Fake.with_args` use this if you want to only declare
expectations about matching arguments. Any unknown keyword arguments
used by the app under test will be allowed.
For example, you can... | 4.960423 | 6.399094 | 0.775176 |
exp = self._get_current_call()
if args:
exp.unexpected_args = args
if kwargs:
exp.unexpected_kwargs = kwargs
return self | def without_args(self, *args, **kwargs) | Set the last call to expect that certain arguments will not exist.
This is the opposite of :func:`fudge.Fake.with_matching_args`. It will
fail if any of the arguments are passed.
.. doctest::
>>> import fudge
>>> query = fudge.Fake('query').expects_call().without_args... | 5.113286 | 7.273653 | 0.702987 |
exp = self._get_current_call()
exp.expected_arg_count = count
return self | def with_arg_count(self, count) | Set the last call to expect an exact argument count.
I.E.::
>>> auth = Fake('auth').provides('login').with_arg_count(2)
>>> auth.login('joe_user') # forgot password
Traceback (most recent call last):
...
AssertionError: fake:auth.login() was called w... | 8.516273 | 13.411749 | 0.634986 |
exp = self._get_current_call()
exp.expected_kwarg_count = count
return self | def with_kwarg_count(self, count) | Set the last call to expect an exact count of keyword arguments.
I.E.::
>>> auth = Fake('auth').provides('login').with_kwarg_count(2)
>>> auth.login(username='joe') # forgot password=
Traceback (most recent call last):
...
AssertionError: fake:auth.l... | 8.232636 | 11.95855 | 0.688431 |
self.log.debug('starting the ``get`` method')
transientSettings = self.settings[
"database settings"]["transients"]
catalogueSettings = self.settings[
"database settings"]["static catalogues"]
if "pessto marshall" in self.settings[
"datab... | def connect(self) | connect to the various databases, the credientals and settings of which are found in the sherlock settings file
**Return:**
- ``transientsDbConn`` -- the database hosting the transient source data
- ``cataloguesDbConn`` -- connection to the database hosting the contextual catalogues the... | 3.426261 | 3.086701 | 1.110007 |
self.log.debug('starting the ``_setup_tunnel`` method')
# TEST TUNNEL DOES NOT ALREADY EXIST
sshPort = tunnelParameters["port"]
connected = self._checkServer(
"127.0.0.1", sshPort)
if connected:
self.log.debug('ssh tunnel already exists - moving ... | def _setup_tunnel(
self,
tunnelParameters) | *setup a ssh tunnel for a database connection to port through*
**Key Arguments:**
- ``tunnelParameters`` -- the tunnel parameters found associated with the database settings
**Return:**
- ``sshPort`` -- the port the ssh tunnel is connected via
.. todo ::
-... | 3.820345 | 3.71382 | 1.028683 |
self.log.debug('starting the ``_checkServer`` method')
# CREATE A TCP SOCKET
import socket
s = socket.socket()
self.log.debug(
% locals())
try:
s.connect((address, port))
self.log.debug(
% locals())
... | def _checkServer(self, address, port) | Check that the TCP Port we've decided to use for tunnelling is available
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check su... | 4.445422 | 4.709956 | 0.943835 |
def _wrapped_view(request, *args, **kwargs):
if not request.is_secure():
if defaults.ACCOUNTS_USE_HTTPS:
request_url = request.build_absolute_uri(
request.get_full_path())
secure_url = request_url.replace('http://', 'https:... | def secure_required(view_func) | Decorator to switch an url from http to https.
If a view is accessed through http and this decorator is applied
to that view, than it will return a permanent redirect to the
secure (https) version of the same view.
The decorator also must check that ``ACCOUNTS_USE_HTTPS`` is enabled.
If disable... | 2.479951 | 2.442872 | 1.015178 |
return forms.CharField(label=_(u"%(label)s") % {'label': label},
widget=forms.TextInput(attrs=attrs_dict),
max_length=75,
error_messages={'required': _(u"%(error)s") %
{'error': error_r... | def identification_field_factory(label, error_required) | A simple identification field factory which enable you to set the label.
:param label:
String containing the label for this field.
:param error_required:
String containing the error message if the field is left empty. | 3.218684 | 4.497844 | 0.715606 |
try:
user = get_user_model().objects.get(username=self.cleaned_data["username"])
except get_user_model().DoesNotExist:
pass
else:
raise forms.ValidationError(
self.error_messages['duplicate_username'])
if self.c... | def clean_username(self) | Validate that the username is unique and not listed
in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list. | 2.89219 | 2.183834 | 1.324364 |
if get_user_model().objects.filter(
Q(email__iexact=self.cleaned_data['email']) |
Q(email_unconfirmed__iexact=self.cleaned_data['email'])):
raise forms.ValidationError(_(u'This email address is already '
'in use. Please supply a different emai... | def clean_email(self) | Validate that the email address is unique. | 2.461597 | 2.131203 | 1.155027 |
username, email, password = (self.cleaned_data['username'],
self.cleaned_data['email'],
self.cleaned_data['password1'])
user = get_user_model().objects.create_user(username, email, password,
not d... | def save(self) | Creates a new user and account. Returns the newly created user. | 4.140004 | 3.502345 | 1.182066 |
identification = self.cleaned_data.get('identification')
password = self.cleaned_data.get('password')
if identification and password:
self.user_cache = authenticate(identification=identification,
password=password)
if self.user_c... | def clean(self) | Checks for the identification and password.
If the combination can't be found will raise an invalid sign in error. | 2.746515 | 2.512327 | 1.093216 |
if self.cleaned_data['email'].lower() == self.user.email:
raise forms.ValidationError(_(u"You're already known under "
"this email address."))
if get_user_model().objects.filter(
email__iexact=self.cleaned_data['email']... | def clean_email(self) | Validate that the email is not already registered with another user. | 2.605719 | 2.468255 | 1.055693 |
if self.cleaned_data.get('picture'):
picture_data = self.cleaned_data['picture']
if 'error' in picture_data:
raise forms.ValidationError(_(u'Upload a valid image. '
'The file you uploaded was either not an image '
... | def clean_picture(self) | Validates format and file size of uploaded profile picture. | 3.134195 | 3.057826 | 1.024975 |
return {
'type': 'grouping',
'grouping': grouping.element._compiler_dispatch(self, **kwargs)
} | def visit_grouping(self, grouping, asfrom=False, **kwargs) | TODO: | 6.854229 | 5.608897 | 1.222028 |
jsn = {'command': 'advanced/search', 'type': 'select'}
needs_nested_translation = \
select.use_labels and \
not nested_join_translation and \
not self.stack and \
not self.dialect.supports_right_nested_joins
if needs_nested_translation:
... | def visit_select(self, select, asfrom=False, parens=True,
fromhints=None,
compound_index=0,
nested_join_translation=False,
select_wraps_for=None,
**kwargs) | if select._prefixes:
text += self._generate_prefixes(
select, select._prefixes, **kwargs) | 4.642195 | 4.453469 | 1.042377 |
if column.type._has_column_expression and \
populate_result_map:
col_expr = column.type.column_expression(column)
add_to_result_map = lambda keyname, name, objects, type_: \
self._add_to_result_map(
keyname, name,
... | def _label_select_column(self, select, column,
populate_result_map,
asfrom, column_clause_args,
name=None,
within_columns_clause=True) | produce labeled columns present in a select(). | 3.227199 | 3.224846 | 1.00073 |
import argparse
global LOGGER
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--rotated", help="Time rotated log file")
parser.add_argument("-v", "--verbose", help="print debug messages too",
action="store_true")
parser.add_argument("-s", "--server", ... | def run() | Main function | 2.77049 | 2.738391 | 1.011722 |
with Subscribe(services=[""], addr_listener=True) as sub:
for msg in sub.recv(1):
if msg:
if msg.type in ["log.debug", "log.info",
"log.warning", "log.error",
"log.critical"]:
... | def log(self) | Log stuff. | 3.698284 | 3.631631 | 1.018353 |
to_stop = STARTED_TASKS.copy()
if to_stop:
print "Cleaning up..."
for task in to_stop:
try:
task.stop()
except: # pylint: disable=W0702
etype, value, trace = sys.exc_info()
# Disregard no such process exceptions, print out the rest
... | def cleanup() | Stop all started tasks on system exit.
Note: This only handles signals caught by the atexit module by default.
SIGKILL, for instance, will not be caught, so cleanup is not guaranteed in
all cases. | 4.4437 | 3.920202 | 1.133539 |
if self._status is not TaskStatus.IDLE:
raise RuntimeError("Cannot start %s in state %s" %
(self, self._status))
self._status = TaskStatus.STARTED
STARTED_TASKS.add(self)
self._start()
if wait:
self.wait()
... | def start(self, wait=False) | Start a task.
This function depends on the underlying implementation of _start, which
any subclass of ``Task`` should implement.
Args:
wait (bool): Whether or not to wait on the task to finish before
returning from this function. Default `False`.
Raises:
... | 4.376421 | 3.798358 | 1.152188 |
if self._status is not TaskStatus.STARTED:
raise RuntimeError("Cannot wait on %s in state %s" %
(self, self._status))
self._wait()
self.stop()
return self.return_values | def wait(self) | Wait on a task to finish and stop it when it has finished.
Raises:
RuntimeError: If the task hasn't been started or has already been
stopped.
Returns:
The ``return_values`` of the task. | 5.702589 | 4.643154 | 1.228171 |
if self._status is TaskStatus.STOPPED:
return
if self._status is not TaskStatus.STARTED:
raise RuntimeError("Cannot stop %s in state %s" %
(self, self._status))
self._stop()
STARTED_TASKS.remove(self)
self._status ... | def stop(self) | Stop a task immediately.
Raises:
RuntimeError: If the task hasn't been started or has already been
stopped. | 3.626154 | 3.396312 | 1.067674 |
if self._status is not TaskStatus.STOPPED:
raise RuntimeError("Cannot reset %s in state %s" %
(self, self._status))
self._reset()
self.return_values = {}
self._status = TaskStatus.IDLE | def reset(self) | Reset a task.
Allows a task to be started again, clears the ``return_values``.
Raises:
RuntimeError: If the task has not been stopped. | 5.23655 | 3.693359 | 1.417829 |
# pylint: disable=W0212
nonremote = [t for t in self._tasks if not isinstance(t, RemoteTask)]
remote = [t for t in self._tasks if isinstance(t, RemoteTask)]
host_dict = defaultdict(list)
for task in remote:
host_dict[task.host].append(task)
aggregat... | def _aggregate(self) | Helper method to aggregate RemoteTasks into single ssh session. | 3.657763 | 3.243673 | 1.127661 |
extension = filename.split('.')[-1].lower()
salt, hash = generate_sha1(instance.id)
return '%(path)s/%(hash)s.%(extension)s' % {
'path': getattr(defaults,
'ACCOUNTS_PICTURE_PATH','%s/%s' % (
str(instance._meta.app_label),
... | def upload_to_picture(instance, filename) | Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and
saving it under unique hash for the image. This is for privacy
reasons so others can't just browse through the picture directory. | 4.424724 | 4.069197 | 1.08737 |
expiration_days = datetime.timedelta(
days=defaults.ACCOUNTS_ACTIVATION_DAYS)
expiration_date = self.date_joined + expiration_days
if self.activation_key == defaults.ACCOUNTS_ACTIVATED:
return True
if get_datetime_now() >= expiration_date:... | def activation_key_expired(self) | Checks if activation key is expired.
Returns ``True`` when the ``activation_key`` of the user is expired
and ``False`` if the key is still valid.
The key is expired when it's set to the value defined in
``ACCOUNTS_ACTIVATED`` or ``activation_key_created`` is beyond the
amount ... | 3.988193 | 3.051492 | 1.306965 |
context= {'user': self,
'protocol': get_protocol(),
'activation_days': defaults.ACCOUNTS_ACTIVATION_DAYS,
'activation_key': self.activation_key,
'site': Site.objects.get_current()}
subject = ''.join(render_to_string(
... | def send_activation_email(self) | Sends a activation email to the user.
This email is send when the user wants to activate their
newly created user. | 2.655248 | 2.730142 | 0.972568 |
self.email_unconfirmed = email
salt, hash = generate_sha1(self.username)
self.email_confirmation_key = hash
self.email_confirmation_key_created = get_datetime_now()
self.save()
# Send email for activation
self.send_confirmation_email()
... | def change_email(self, email) | Changes the email address for a user.
A user needs to verify this new email address before it becomes
active. By storing the new email address in a temporary field
-- ``temporary_email`` -- we are able to set this email address
after the user has verified it by clicking on the verific... | 4.74605 | 5.635232 | 0.84221 |
context= {'user': self,
'new_email': self.email_unconfirmed,
'protocol': get_protocol(),
'confirmation_key': self.email_confirmation_key,
'site': Site.objects.get_current()}
# Email to the old address
subject_old ... | def send_confirmation_email(self) | Sends an email to confirm the new email address.
This method sends out two emails. One to the new email address that
contains the ``email_confirmation_key`` which is used to verify this
this email address with :func:`User.objects.confirm_email`.
The other email is to the old email addr... | 2.026819 | 1.936457 | 1.046664 |
# First check for a picture and if any return that.
if self.picture:
return self.picture.url
# Use Gravatar if the user wants to.
if defaults.ACCOUNTS_GRAVATAR_PICTURE:
return get_gravatar(self.email,
defaults.ACCOUNTS_GRA... | def get_picture_url(self) | Returns the image containing the picture for the user.
The picture can be a uploaded image or a Gravatar.
Gravatar functionality will only be used when
``ACCOUNTS_GRAVATAR_PICTURE`` is set to ``True``.
:return:
``None`` when Gravatar is not used and no default image is
... | 3.993326 | 3.064492 | 1.303095 |
if self.first_name or self.last_name:
# We will return this as translated string. Maybe there are some
# countries that first display the last name.
name = _(u"%(first_name)s %(last_name)s") % \
{'first_name': self.first_name,
'last_n... | def get_full_name_or_username(self) | Returns the full name of the user, or if none is supplied will return
the username.
Also looks at ``ACCOUNTS_WITHOUT_USERNAMES`` settings to define if it
should return the username or email address when the full name is not
supplied.
:return:
``String`` containing t... | 4.20898 | 3.831116 | 1.09863 |
non_null_params = ['space_id', 'access_token']
for param in non_null_params:
if getattr(config, param) is None:
raise Exception('Configuration for \"{0}\" must not be empty.'.format(param))
for clazz in config.custom_entries:
if not issubclass(cl... | def validate_config(config) | Verify sanity for a :class:`.Config` instance.
This will raise an exception in case conditions are not met, otherwise
will complete silently.
:param config: (:class:`.Config`) Configuration container. | 4.053119 | 3.990186 | 1.015772 |
if issubclass(resource_class, Entry):
params = None
content_type = getattr(resource_class, '__content_type__', None)
if content_type is not None:
params = {'content_type': resource_class.__content_type__}
return RequestArray(self.dispatche... | def fetch(self, resource_class) | Construct a :class:`.Request` for the given resource type.
Provided an :class:`.Entry` subclass, the Content Type ID will be inferred and requested explicitly.
Examples::
client.fetch(Asset)
client.fetch(Entry)
client.fetch(ContentType)
client.fetch(Cus... | 3.578665 | 3.401886 | 1.051965 |
result = None
if array is not None:
container = array.items_mapped.get(link_resource_type)
result = container.get(resource_id)
if result is None:
clz = utils.class_for_type(link_resource_type)
result = self.fetch(clz).where({'sys.id': re... | def resolve(self, link_resource_type, resource_id, array=None) | Resolve a link to a CDA resource.
Provided an `array` argument, attempt to retrieve the resource from the `mapped_items`
section of that array (containing both included and regular resources), in case the
resource cannot be found in the array (or if no `array` was provided) - attempt to fetch
... | 4.413155 | 4.288761 | 1.029005 |
return self.resolve(resource_link.link_type, resource_link.resource_id, array) | def resolve_resource_link(self, resource_link, array=None) | Convenience method for resolving links given a :class:`.resources.ResourceLink` object.
Extract link values and pass to the :func:`.resolve` method of this class.
:param resource_link: (:class:`.ResourceLink`) instance.
:param array: (:class:`.Array`) Optional array resource.
:return: ... | 5.276073 | 5.518713 | 0.956033 |
sys = dct.get('sys')
return self.resolve(sys['linkType'], sys['id'], array) if sys is not None else None | def resolve_dict_link(self, dct, array=None) | Convenience method for resolving links given a dict object.
Extract link values and pass to the :func:`.resolve` method of this class.
:param dct: (dict) Dictionary with the link data.
:param array: (:class:`.Array`) Optional array resource.
:return: :class:`.Resource` subclass, `None`... | 7.588177 | 6.256703 | 1.212808 |
url = '{0}/{1}'.format(self.base_url, request.remote_path)
r = self.httpclient.get(url, params=request.params, headers=self.get_headers())
if 200 <= r.status_code < 300:
return self.resource_factory.from_json(r.json())
else:
if r.status_code in ErrorMappi... | def invoke(self, request) | Invoke the given :class:`.Request` instance using the associated :class:`.Dispatcher`.
:param request: :class:`.Request` instance to invoke.
:return: :class:`.Resource` subclass. | 2.929058 | 2.987588 | 0.980409 |
result = self.invoke()
if self.resolve_links:
result.resolve_links()
return result | def all(self) | Attempt to retrieve all available resources matching this request.
:return: Result instance as returned by the :class:`.Dispatcher`. | 14.258174 | 9.209742 | 1.548162 |
self.params['limit'] = 1
result = self.all()
return result.items[0] if result.total > 0 else None | def first(self) | Attempt to retrieve only the first resource matching this request.
:return: Result instance, or `None` if there are no matching resources. | 6.210867 | 4.843058 | 1.282427 |
self.params = dict(self.params, **params) # params overrides self.params
return self | def where(self, params) | Set a dict of parameters to be passed to the API when invoking this request.
:param params: (dict) query parameters.
:return: this :class:`.RequestArray` instance for convenience. | 7.473688 | 8.516661 | 0.877537 |
print("Demonstrating complex require_condition example")
val = 64
Buzz.require_condition(is_even(val), 'This condition should pass')
val = 81
Buzz.require_condition(is_even(val), 'Value {val} is not even', val=val) | def complex_require_condition() | This function demonstrates a more complex usage of the require_condition
function. It shows argument interpolation and handling a more complex
boolean expression | 6.717742 | 6.712268 | 1.000816 |
request = context['request']
if request.get_full_path in (reverse(url) for url in urls.split()):
return css if css else 'active'
return '' | def active_url(context, urls, css=None) | Highlight menu item based on url tag.
Returns a css class if ``request.path`` is in given ``url``.
:param url:
Django url to be reversed.
:param css:
Css class to be returned for highlighting. Return active if none set. | 4.553372 | 5.649468 | 0.805982 |
request = context['request']
#pattern = "^" + pattern + "$"
if re.search(pattern, request.path):
return css if css else 'active'
return '' | def active_path(context, pattern, css=None) | Highlight menu item based on path.
Returns a css class if ``request.path`` is in given ``pattern``.
:param pattern:
Regex url pattern.
:param css:
Css class to be returned for highlighting. Return active if none set. | 4.269785 | 4.746501 | 0.899565 |
if self.prefix:
item_name = self.prefix + self.seperator + item_name
item_names = item_name.split(self.seperator)
node = self._storage
for item_name in item_names:
node = node[item_name]
return node | def get(self, item_name) | Retrieve the value of an option.
:param str item_name: The name of the option to retrieve.
:return: The value of *item_name* in the configuration. | 2.545821 | 2.948373 | 0.863467 |
if self.has_option(item_name):
return self.get(item_name)
return default_value | def get_if_exists(self, item_name, default_value=None) | Retrieve the value of an option if it exists, otherwise
return *default_value* instead of raising an error:
:param str item_name: The name of the option to retrieve.
:param default_value: The value to return if *item_name* does not exist.
:return: The value of *item_name* in the configuration. | 2.499255 | 2.845845 | 0.878212 |
if self.prefix:
option_name = self.prefix + self.seperator + option_name
item_names = option_name.split(self.seperator)
node = self._storage
for item_name in item_names:
if node is None:
return False
if not item_name in node:
return False
node = node[item_name]
return True | def has_option(self, option_name) | Check that an option exists.
:param str option_name: The name of the option to check.
:return: True of the option exists in the configuration.
:rtype: bool | 2.482863 | 2.521181 | 0.984802 |
if not self.has_option(section_name):
return False
return isinstance(self.get(section_name), dict) | def has_section(self, section_name) | Checks that an option exists and that it contains sub options.
:param str section_name: The name of the section to check.
:return: True if the section exists.
:rtype: dict | 3.207278 | 3.193386 | 1.00435 |
if self.prefix:
item_name = self.prefix + self.seperator + item_name
item_names = item_name.split(self.seperator)
item_last = item_names.pop()
node = self._storage
for item_name in item_names:
if not item_name in node:
node[item_name] = {}
node = node[item_name]
node[item_last] = item_value
... | def set(self, item_name, item_value) | Sets the value of an option in the configuration.
:param str item_name: The name of the option to set.
:param item_value: The value of the option to set. | 2.01234 | 2.214854 | 0.908565 |
vconf = Configuration(verify_file)
missing = {}
for setting, setting_type in vconf.get('settings').items():
if not self.has_option(setting):
missing['missing'] = missing.get('settings', [])
missing['missing'].append(setting)
elif not type(self.get(setting)).__name__ == setting_type:
missing['... | def get_missing(self, verify_file) | Use a verification configuration which has a list of required options
and their respective types. This information is used to identify missing
and incompatible options in the loaded configuration.
:param str verify_file: The file to load for verification data.
:return: A dictionary of missing and incompatible ... | 2.865071 | 2.620115 | 1.093491 |
with open(self.configuration_file, 'w') as file_h:
file_h.write(self._serializer('dumps', self._storage)) | def save(self) | Save the current configuration to disk. | 8.147632 | 7.078584 | 1.151026 |
result = []
for line in lines:
content = line.strip()
replaced = regexer.sub(handler, content)
result.append(line.replace(content, replaced, 1))
return result | def replace_lines(regexer, handler, lines) | Uses replacement handler to perform replacements on lines of text
First we strip off all whitespace
We run the replacement on a clean 'content' string
Finally we replace the original content with the replaced version
This ensures that we retain the correct whitespace from the original line | 2.576845 | 2.195242 | 1.173832 |
handler = ReplacementHandler(**params)
for target, regexer in regexer_for_targets(targets):
with open(target) as fh:
lines = fh.readlines()
lines = replace_lines(regexer, handler, lines)
with open(target, "w") as fh:
fh.writelines(lines)
if handler.missin... | def write_targets(targets, **params) | Writes version info into version file | 5.098001 | 4.927786 | 1.034542 |
for target in targets:
path, file_ext = os.path.splitext(target)
regexer = config.regexers[file_ext]
yield target, regexer | def regexer_for_targets(targets) | Pairs up target files with their correct regex | 4.042927 | 3.868435 | 1.045107 |
updates = {}
for line in lines:
# for consistency we must match the replacer and strip whitespace / newlines
match = regexer.match(line.strip())
if not match:
continue
k_v = match.groupdict()
updates[k_v[Constants.KEY_GROUP]] = k_v[Constants.VALUE_GROUP]
... | def extract_keypairs(lines, regexer) | Given some lines of text, extract key-value pairs from them | 5.486241 | 5.075322 | 1.080964 |
results = {}
for target, regexer in regexer_for_targets(targets):
with open(target) as fh:
results.update(extract_keypairs(fh.readlines(), regexer))
return results | def read_targets(targets) | Reads generic key-value pairs from input files | 7.228474 | 6.79442 | 1.063884 |
triggers = set()
for trigger, pattern in trigger_patterns.items():
matches = glob.glob(pattern)
if matches:
_LOG.debug("trigger: %s bump from %r\n\t%s", trigger, pattern, matches)
triggers.add(trigger)
else:
_LOG.debug("trigger: no match on %r", p... | def detect_file_triggers(trigger_patterns) | The existence of files matching configured globs will trigger a version bump | 3.911397 | 3.613086 | 1.082564 |
triggers = set()
if file_triggers:
triggers = triggers.union(detect_file_triggers(config.trigger_patterns))
if bump:
_LOG.debug("trigger: %s bump requested", bump)
triggers.add(bump)
return triggers | def get_all_triggers(bump, file_triggers) | Aggregated set of significant figures to bump | 5.830081 | 5.937988 | 0.981828 |
updates = {}
lock_key = config._forward_aliases.get(Constants.VERSION_LOCK_FIELD)
# if we are explicitly setting or locking the version, then set the lock field True anyway
if lock:
updates[Constants.VERSION_LOCK_FIELD] = config.VERSION_LOCK_VALUE
elif (
triggers
and loc... | def get_lock_behaviour(triggers, all_data, lock) | Binary state lock protects from version increments if set | 5.548014 | 5.250154 | 1.056733 |
version_string = ".".join(semver)
maybe_dev_version_string = version_string
updates = {}
if release_mode:
# in production, we have something like `1.2.3`, as well as a flag e.g. PRODUCTION=True
updates[Constants.RELEASE_FIELD] = config.RELEASED_VALUE
else:
# in dev mode,... | def get_final_version_string(release_mode, semver, commit_count=0) | Generates update dictionary entries for the version string | 5.658087 | 5.387618 | 1.050202 |
cmd = "git rev-list --count HEAD"
commit_count = str(
int(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip())
)
cmd = "git rev-parse HEAD"
commit = str(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip())
return {Constants.COMMIT_FIELD: commit, Constants.C... | def get_dvcs_info() | Gets current repository info from git | 2.470818 | 2.408602 | 1.025831 |
updates = {}
if config_path:
get_or_create_config(config_path, config)
for k, v in config.regexers.items():
config.regexers[k] = re.compile(v)
# a forward-mapping of the configured aliases
# giving <our config param> : <the configured value>
# if a value occurs multiple t... | def main(
set_to=None,
set_patch_count=None,
release=None,
bump=None,
lock=None,
file_triggers=None,
config_path=None,
**extra_updates
) | Main workflow.
Load config from cli and file
Detect "bump triggers" - things that cause a version increment
Find the current version
Create a new version
Write out new version and any other requested variables
:param set_to: explicitly set semver to this version string
:param set_patch_cou... | 5.069416 | 4.920896 | 1.030181 |
args, others = get_cli()
if args.version:
print(__version__)
exit(0)
log_level = logging.WARNING - 10 * args.verbosity
logging.basicConfig(level=log_level, format="%(module)s %(levelname)8s %(message)s")
command_line_updates = parse_other_args(others)
old, new, updates =... | def main_from_cli() | Main workflow.
Load config from cli and file
Detect "bump triggers" - things that cause a version increment
Find the current version
Create a new version
Write out new version and any other requested variables | 4.134494 | 4.377682 | 0.944448 |
log_analysis = LogAnalysis(context.obj['store'])
try:
new_run = log_analysis(config, sampleinfo=sampleinfo, sacct=sacct)
except MissingFileError as error:
click.echo(click.style(f"Skipping, missing Sacct file: {error.message}", fg='yellow'))
return
except KeyError as error:
... | def log_cmd(context, sampleinfo, sacct, quiet, config) | Log an analysis.
CONFIG: MIP config file for an analysis | 3.757658 | 3.78704 | 0.992242 |
mip_cli = MipCli(context.obj['script'])
mip_config = mip_config or context.obj['mip_config']
email = email or environ_email()
kwargs = dict(config=mip_config, family=family, priority=priority, email=email, dryrun=dryrun, start_with=start_with)
if command:
mip_command = mip_cli.build_com... | def start(context, mip_config, email, priority, dryrun, command, start_with, family) | Start a new analysis. | 3.296602 | 3.318337 | 0.99345 |
existing_tables = context.obj['store'].engine.table_names()
if force or reset:
if existing_tables and not force:
message = f"Delete existing tables? [{', '.join(existing_tables)}]"
click.confirm(click.style(message, fg='yellow'), abort=True)
context.obj['store'].drop... | def init(context, reset, force) | Setup the database. | 2.835028 | 2.732647 | 1.037466 |
root_dir = root_dir or context.obj['root']
config_files = Path(root_dir).glob('*/analysis/*_config.yaml')
for config_file in config_files:
LOG.debug("found analysis config: %s", config_file)
with config_file.open() as stream:
context.invoke(log_cmd, config=stream, quiet=True... | def scan(context, root_dir) | Scan a directory for analyses. | 5.239907 | 5.025146 | 1.042737 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.