code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# two options are possible
if not path.abspath(sys.prefix) == VE_ROOT:
# Option A: we are in the parental process that was called from command line like
# $> ./launch.py start PROCESS_NAME
# in this case sys.prefix points to Global Interpreter
python = get_python()
r... | def go_to_ve() | Rerun this script within the virtualenv with same args
NOTICE: parent process will wait for created subprocess to complete | 13.518991 | 12.46384 | 1.084657 |
try:
import virtualenv
except ImportError:
sys.stdout.write('Installing virtualenv into global interpreter \n')
ret_code = subprocess.call([VE_GLOBAL_SCRIPT, PROJECT_ROOT])
sys.stdout.write('Installation finished with code {0}. Re-run ./launch.py install \n'.format(ret_code)... | def install_virtualenv_p2(root, python_version) | Install virtual environment for Python 2.7+; removing the old one if it exists | 4.359785 | 4.456057 | 0.978395 |
import venv
builder = venv.EnvBuilder(system_site_packages=False, clear=True, symlinks=False, upgrade=False)
builder.create(root)
ret_code = subprocess.call([VE_SCRIPT, PROJECT_ROOT, root, python_version])
sys.exit(ret_code) | def install_virtualenv_p3(root, python_version) | Install virtual environment for Python 3.3+; removing the old one if it exists | 4.071524 | 3.900889 | 1.043743 |
python_version = '.'.join(str(v) for v in sys.version_info[:2])
sys.stdout.write('Installing Python {0} virtualenv into {1} \n'.format(python_version, VE_ROOT))
if sys.version_info < (3, 3):
install_virtualenv_p2(VE_ROOT, python_version)
else:
install_virtualenv_p3(VE_ROOT, python_v... | def install_virtualenv(parser_args) | Installs virtual environment | 2.917112 | 2.938699 | 0.992654 |
from synergy.system import process_helper
from synergy.conf import context
process_names = [parser_args.process_name] if parser_args.process_name else list(context.process_context)
for process_name in process_names:
process_helper.poll_process(process_name)
sys.stdout.write('\n') | def query_configuration(parser_args) | Queries process state | 3.790187 | 3.628642 | 1.044519 |
from synergy.db.manager import db_manager
if parser_args.reset:
db_manager.reset_db()
# initialize DB with the context.process_context entries
parser_args.update = True
if parser_args.update:
db_manager.update_db() | def db_command(parser_args) | Manages Synergy DB state | 6.026522 | 5.198488 | 1.159284 |
import logging
from synergy.supervisor.supervisor_configurator import SupervisorConfigurator, set_box_id
if parser_args.boxid:
set_box_id(logging, parser_args.argument)
return
sc = SupervisorConfigurator()
if parser_args.reset:
sc.reset_db()
elif parser_args.start... | def supervisor_command(parser_args) | Supervisor-related commands | 3.726519 | 3.58374 | 1.039841 |
import psutil
import process_starter
from synergy.system import process_helper
try:
pid = process_helper.get_process_pid(parser_args.process_name)
if pid is not None:
if psutil.pid_exists(pid):
message = 'ERROR: Process {0} is already running with pid {1... | def start_process(parser_args) | Start up specific daemon | 2.90044 | 2.847368 | 1.018639 |
from synergy.system import process_helper
try:
pid = process_helper.get_process_pid(parser_args.process_name)
if pid is None or process_helper.poll_process(parser_args.process_name) is False:
message = 'ERROR: Process {0} is already terminated {1}\n'.format(parser_args.process_... | def stop_process(parser_args) | Stop/Kill specific daemon | 2.561453 | 2.584337 | 0.991145 |
def wrapper(request, *args, **kwargs):
user = None
# get the Basic username and password from the request.
auth_string = request.META.get('HTTP_AUTHORIZATION', None)
if auth_string:
(authmeth, auth) = auth_string.split(" ", 1)
auth = auth.strip().decode... | def httpauth_login_required(func) | Put this decorator before your view to check if the user is logged in
via httpauth and return a JSON 401 error if he/she is not. | 2.278518 | 2.242835 | 1.01591 |
def wrapper(request, *args, **kwargs):
slug = kwargs.get('slug', "")
if not slug:
return kickoutt_404("Not found.", content_type="application/json")
try:
wip = WriteAPIIP.objects.get(slug=slug)
ip = get_client_ip(request)
if ip not in w... | def ip_verification_required(func) | Put this decorator before your view to check if the function is coming from an IP on file | 4.032638 | 3.888104 | 1.037173 |
def wrapper(request, *args, **kwargs):
default_to_open = getattr(settings, 'DEFAULT_TO_OPEN_READ', False)
database_name = kwargs.get('database_name', "")
collection_name = kwargs.get('collection_name', "")
if not default_to_open:
if not database_name or not collecti... | def check_public_ok(func) | Call after login decorator. | 3.054255 | 2.959882 | 1.031884 |
def wrapper(request, *args, **kwargs):
database_name = kwargs.get('database_name', "")
collection_name = kwargs.get('collection_name', "")
if not database_name or not collection_name:
return HttpResponse(unauthorized_json_response(),
content_... | def check_read_httpauth_access(func) | Call after login decorator. | 3.123557 | 3.064224 | 1.019363 |
_ROUTING_PREFIX = 'routing_'
_QUEUE_PREFIX = 'queue_'
_SUFFIX = '_freerun'
if arguments is not None:
assert isinstance(arguments, dict)
process_entry = FreerunProcessEntry(
process_name=process_name,
entry_name=entry_name,
trigger_frequency=trigger_frequency,
... | def freerun_context_entry(process_name,
entry_name,
classname,
token,
trigger_frequency,
is_on=True,
present_on_boxes=None,
description=No... | forms process context entry | 1.960398 | 1.958588 | 1.000924 |
if isinstance(field_values, string_types):
field_values = [field_values]
if len(fields_names) != len(field_values):
raise ValueError('Error: unable to build a primary key query due '
'to mismatch in number of fields {0} vs {1}'
.format(len(... | def build_db_query(fields_names, field_values) | method builds query dictionary by zipping together DB field names with the field values | 2.497656 | 2.423102 | 1.030768 |
query = build_db_query(self.primary_key, key)
collection = self.ds.connection(self.collection_name)
document = collection.find_one(query)
if document is None:
raise LookupError('{0} with key {1} was not found'.format(self.model_klass.__name__, query))
return... | def get_one(self, key) | method finds single record base on the given primary key and returns it to the caller | 3.927421 | 3.769336 | 1.04194 |
collection = self.ds.connection(self.collection_name)
cursor = collection.find(query)
if cursor.count() == 0:
raise LookupError('Collection {0} has no {1} records'
.format(self.collection_name, self.model_klass.__name__))
return [self.m... | def run_query(self, query) | method runs query on a specified collection and return a list of filtered Model records | 3.752777 | 3.247204 | 1.155695 |
assert isinstance(instance, self.model_klass)
if instance.db_id:
query = {'_id': ObjectId(instance.db_id)}
else:
query = build_db_query(self.primary_key, instance.key)
self.ds.update(self.collection_name, query, instance)
return instance.db_id | def update(self, instance) | this is an upsert method: replaces or creates the DB representation of the model instance | 3.997187 | 3.757064 | 1.063913 |
return self.client.get_ports(is_audio=True, is_physical=True, is_input=True) | def audio_inputs(self) | :return: A list of audio input :class:`Ports`. | 10.316854 | 6.544213 | 1.576485 |
return self.client.get_ports(is_audio=True, is_physical=True, is_output=True) | def audio_outputs(self) | :return: A list of audio output :class:`Ports`. | 10.022915 | 6.715847 | 1.492428 |
return self.client.get_ports(is_midi=True, is_physical=True, is_input=True) | def midi_inputs(self) | :return: A list of MIDI input :class:`Ports`. | 9.333429 | 6.535307 | 1.428155 |
return self.client.get_ports(is_midi=True, is_physical=True, is_output=True) | def midi_outputs(self) | :return: A list of MIDI output :class:`Ports`. | 9.334133 | 6.450523 | 1.447035 |
raise NotImplementedError('method cursor_fine must be implemented by {0}'.format(self.__class__.__name__)) | def cursor_fine(self,
table_name,
start_id_obj,
end_id_obj,
iteration,
start_timeperiod,
end_timeperiod) | method returns DB cursor based on precise boundaries | 5.995828 | 5.818176 | 1.030534 |
raise NotImplementedError('method cursor_batch must be implemented by {0}'.format(self.__class__.__name__)) | def cursor_batch(self,
table_name,
start_timeperiod,
end_timeperiod) | method returns batched DB cursor | 6.491557 | 6.008936 | 1.080317 |
assert isinstance(primary_key, dict)
assert isinstance(instance, BaseDocument)
collection = self._db[table_name]
# work with a copy of the document, as the direct type change of the _id field
# is later negated by the `BaseDocument.to_json` method
document = ins... | def update(self, table_name, primary_key, instance) | replaces document identified by the primary_key or creates one if a matching document does not exist | 4.155512 | 3.951987 | 1.051499 |
for param in effect.params:
if param.value != param.default:
self._set_param_value(param) | def _load_params_of(self, effect) | Called only when a effect has created
Param changes calls :meth:`~pluginsmanager.observer.host_observer.host_observer.HostObserver.on_param_value_changed()` | 4.524388 | 3.579245 | 1.264062 |
return ProtocolParser._connect_message(
ProtocolParser._get_out_name_of(connection.output),
ProtocolParser._get_in_name_of(connection.input)
) | def connect(connection) | ``connect <origin_port> <destination_port>``
connect two plugin audio ports
e.g.::
connect system:capture_1 plugin_0:in
:param pluginsmanager.model.connection.Connection connection: Connection with a valid
:class:`.Output` and :class:`.Input` | 8.388553 | 6.560162 | 1.278711 |
return 'disconnect {} {}'.format(
ProtocolParser._get_out_name_of(connection.output),
ProtocolParser._get_in_name_of(connection.input)
) | def disconnect(connection) | ``disconnect <origin_port> <destination_port>``
disconnect two plugin audio ports
e.g.::
disconnect system:capture_1 plugin_0:in
:param pluginsmanager.model.connection.Connection connection: Connection with a valid
:class:`.Output` and :class:`.Input` | 8.349783 | 8.424716 | 0.991106 |
instance = param.effect.instance
return 'param_set {} {} {}'.format(instance, param.symbol, param.value) | def param_set(param) | ``param_set <instance_number> <param_symbol> <param_value>``
set a value to given control
e.g.::
param_set 0 gain 2.50
:param Lv2Param param: Parameter that will be updated your value | 11.255672 | 12.153435 | 0.926131 |
instance = param.effect.instance
return 'param_get {} {}'.format(instance, param.symbol) | def param_get(param) | ``param_get <instance_number> <param_symbol>``
get the value of the request control
e.g.::
param_get 0 gain
:param Lv2Param param: Parameter that will be get your current value | 17.086937 | 19.608843 | 0.871389 |
function = lambda connection: connection.input.effect == self \
or connection.output.effect == self
return tuple([c for c in self.pedalboard.connections if function(c)]) | def connections(self) | :return list[Connection]: Connections that this effects is present (with input or output port) | 9.959146 | 7.108576 | 1.401004 |
if self.pedalboard is None:
raise IndexError('Effect not contains a pedalboard')
return self.pedalboard.effects.index(self) | def index(self) | Returns the first occurrence of the effect in your pedalboard | 10.498359 | 5.118211 | 2.051177 |
from django.contrib.sessions.models import Session
if sender != Session:
instance.full_clean() | def pre_save_full_clean_handler(sender, instance, *args, **kwargs) | Force all models to call full_clean before save | 5.470677 | 4.062857 | 1.34651 |
if self._wrapped is not empty:
raise RuntimeError('Settings already configured.')
holder = UserSettingsHolder(default_settings)
for name, value in options.items():
setattr(holder, name, value)
self._wrapped = holder | def configure(self, default_settings=global_settings, **options) | Called to manually configure the settings. The 'default_settings'
parameter sets where to retrieve any unspecified values from (its
argument must support attribute access (__getattr__)). | 4.956579 | 4.642968 | 1.067545 |
settings_module = os.environ.get(ENVIRONMENT_SETTINGS_VARIABLE, 'settings')
if not settings_module:
raise ImproperlyConfigured(
'Requested settings module points to an empty variable. '
'You must either define the environment variable {0} '
... | def _setup(self) | Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually. | 5.287644 | 4.028189 | 1.312661 |
context_module = os.environ.get(ENVIRONMENT_CONTEXT_VARIABLE, 'context')
if not context_module:
raise ImproperlyConfigured(
'Requested context points to an empty variable. '
'You must either define the environment variable {0} '
'or ca... | def _setup(self) | Load the context module pointed to by the environment variable. This
is used the first time we need the context at all, if the user has not
previously configured the context manually. | 6.511849 | 4.891656 | 1.331216 |
if create_file:
with open(str(path), 'a+') as data_file:
data_file.seek(0)
return json.load(data_file)
else:
with open(str(path)) as data_file:
return json.load(data_file) | def read(path, create_file=False) | Reads the json data in path
:param Path path: Path that json data will be readed
:param create_file: Creates the file if it isn't exists
:return: json data | 2.317923 | 2.37312 | 0.976741 |
try:
loop = asyncio.get_event_loop()
if loop.is_running():
asyncio.run_coroutine_threadsafe(Persistence._save(path, json_data), loop)
else:
loop.run_until_complete(Persistence._save(path, json_data))
except AssertionError:
... | def save(path, json_data) | Saves json_data in path
:param Path path: Path that json_data will be persisted
:param json_data: Data that will be persisted | 2.58386 | 2.600379 | 0.993647 |
if use_subprocess is False:
return foo(*args, **kwrags)
child_pid = os.fork()
if child_pid == 0:
foo(*args, **kwrags)
sys.exit(0)
return os.waitpid(child_pid, 0)[1] == 0 | def run_at_subprocess(self, use_subprocess, foo, *args, **kwrags) | This method for run some function at subprocess.
Very useful when you have a problem with memory leaks. | 2.090483 | 2.030632 | 1.029474 |
build_keys_with_mapreduce(database_name, collection_name)
messages.success(request, _(
"Successfully completed MapReduce operation. "
"Key rebuild for custom report complete."))
return HttpResponseRedirect(reverse("djmongo_show_dbs")) | def build_keys(request, database_name, collection_name) | Perform the map/reduce to refresh the keys form.
The display the custom report screen | 15.402227 | 11.821534 | 1.302896 |
ss = get_object_or_404(CustomPublicReadAPI, datbase_name=database_name,
collection_name=collection_name, slug=slug)
ss.delete()
messages.success(request, _("Custom Public Read API deleted."))
return HttpResponseRedirect(
reverse('djmongo_show_apis',
... | def delete_custom_public_read_api(
request,
database_name,
collection_name,
slug) | Delete CustomPublicReadAPI | 3.590912 | 3.45295 | 1.039955 |
ss = get_object_or_404(CustomHTTPAuthReadAPI, datbase_name=database_name,
collection_name=collection_name, slug=slug)
ss.delete()
messages.success(request, _("Custom HTTPAuth Read API deleted."))
return HttpResponseRedirect(
reverse('djmongo_show_apis',
... | def delete_custom_httpauth_read_api(
request,
database_name,
collection_name,
slug) | Delete CustomHTTPAuthReadAPI | 3.659541 | 3.467777 | 1.055299 |
ss = get_object_or_404(PublicReadAPI, database_name=database_name,
collection_name=collection_name, slug=slug)
ss.delete()
messages.success(request, _("Simple Public Read API deleted."))
return HttpResponseRedirect(
reverse('djmongo_show_apis',
arg... | def delete_simple_public_read_api(
request,
database_name,
collection_name,
slug) | Delete Simple PublicReadAPI | 3.353094 | 3.24416 | 1.033578 |
ss = get_object_or_404(HTTPAuthReadAPI, database_name=database_name,
collection_name=collection_name, slug=slug)
ss.delete()
messages.success(request, _("Simple HTTP Auth Read API deleted."))
return HttpResponseRedirect(
reverse('djmongo_show_apis',
... | def delete_simple_httpauth_read_api(
request,
database_name,
collection_name,
slug) | Delete Simple PublicReadAPI | 3.400052 | 3.436547 | 0.98938 |
if utc_now is None:
utc_now = datetime.utcnow()
def wind_days(start_date):
while True:
if self.day_of_week == EVERY_DAY or start_date.weekday() == int(self.day_of_week):
return start_date.replace(hour=self.time_of_day.hour, minute=sel... | def next_trigger_frequency(self, utc_now=None) | :param utc_now: optional parameter to be used by Unit Tests as a definition of "now"
:return: datetime instance presenting next trigger time of the event | 2.290362 | 2.360415 | 0.970322 |
assert not isinstance(value, string_types)
self.timestamps = []
for timestamp in value:
event = EventTime(timestamp)
self.timestamps.append(event) | def change_interval(self, value) | :param value: list of strings in format 'Day_of_Week-HH:MM' | 7.091753 | 6.057926 | 1.170657 |
if utc_now is None:
utc_now = datetime.utcnow()
if self.is_alive():
smallest_timedelta = timedelta(days=99, hours=0, minutes=0, seconds=0, microseconds=0, milliseconds=0)
for event_time in self.timestamps:
next_trigger = event_time.next_trigg... | def next_run_in(self, utc_now=None) | :param utc_now: optional parameter to be used by Unit Tests as a definition of "now"
:return: timedelta instance presenting amount of time before the trigger is triggered next time
or None if the EventClock instance is not running | 2.962474 | 2.779074 | 1.065993 |
collection = self.ds.connection(COLLECTION_MANAGED_PROCESS)
return collection.delete_many(filter={}) | def clear(self) | removes all documents in this collection | 21.139225 | 16.381636 | 1.290422 |
md5 = hashlib.md5()
file_obj = gzip.open(file_name, 'rb')
for chunk in iter(lambda: file_obj.read(8192), ''):
md5.update(chunk)
file_obj.close()
return md5.hexdigest() | def compute_gzip_md5(file_name) | method traverses compressed file and calculates its MD5 checksum | 1.801787 | 1.773714 | 1.015827 |
for every in family_source:
if every not in family_target:
family_target[every] = family_source[every]
else:
family_target[every] += family_source[every] | def copy_and_sum_families(family_source, family_target) | methods iterates thru source family and copies its entries to target family
in case key already exists in both families - then the values are added | 2.335569 | 2.310169 | 1.010995 |
pid_filename = get_pid_filename(process_name)
try:
with open(pid_filename, mode='w') as pid_file:
pid_file.write(str(os.getpid()))
except Exception as e:
print('Unable to create pid file at: {0}, because of: {1}'.format(pid_filename, e),
file=sys.stderr) | def create_pid_file(process_name) | creates pid file and writes os.pid() in there | 2.237478 | 2.147345 | 1.041974 |
pid_filename = get_pid_filename(process_name)
try:
os.remove(pid_filename)
print('Removed pid file at: {0}'.format(pid_filename), file=sys.stdout)
except Exception as e:
print('Unable to remove pid file at: {0}, because of: {1}'.format(pid_filename, e),
file=sys.st... | def remove_pid_file(process_name) | removes pid file | 2.274373 | 2.207636 | 1.03023 |
"Main entry point"
# Pass off to the router
try:
handler = self.route(
environ['PATH_INFO'].lower(),
environ['REQUEST_METHOD'].lower(),
)
if handler is None:
raise HttpNotFound()
# Handle errors
e... | def handle(self, environ, start_response) | Main entry point | 2.585566 | 2.5109 | 1.029737 |
if not hostname or not isinstance(hostname, basestring):
return "hostname_invalid"
if not isinstance(details, list):
return "host_details_not_list"
if len(details) != 3:
return "host_details_wrong_length"
if details[0] not in self.balancer.act... | def host_errors(self, hostname, details) | Validates the format of a host entry
Returns an error string, or None if it is valid. | 2.820967 | 2.717856 | 1.037938 |
"Replaces the hosts list with the provided input"
# Do some error checking
if not isinstance(body, dict):
raise HttpBadRequest("body_not_a_dict")
for hostname, details in body.items():
error = self.host_errors(hostname, details)
if error:
... | def set_all(self, path, body) | Replaces the hosts list with the provided input | 3.298165 | 2.992161 | 1.102268 |
def func(response):
if response is not None:
status_code = response.status
if status_code == true_code:
return True
if false_code is not None and status_code == false_code:
return False
r... | def boolean(cls, true_code, false_code=None) | Callback to validate a response code.
The returned callback checks whether a given response has a
``status_code`` that is considered good (``true_code``) and
raise an appropriate error if not.
The optional ``false_code`` allows for a non-successful status
code to return False i... | 3.380098 | 3.258237 | 1.037401 |
def func(response):
ret = None
if cls.boolean(status_code)(response):
ret = response.json() or {}
return process(ret)
return func | def json(cls, status_code, process) | Callback to validate and extract a JSON object.
The returned callback checks a given response for the given
status_code using :function:`response_boolean`. On success the
response JSON is parsed and returned.
Args:
status_code(int): The http status code to consider a succe... | 8.157773 | 8.941302 | 0.91237 |
return self.adapter.get(url, callback,
params=params, json=json, headers=headers) | def get(self, url, callback,
params=None, json=None, headers=None) | Get a URL.
Args:
callback(func): The response callback function
Keyword Args:
params(dict): Parameters for the request
json(dict): JSON body for the request
headers(dict): Additional headers for the request
Returns:
The result o... | 3.156493 | 5.572124 | 0.566479 |
return self.adapter.put(url, callback, params=params, json=json) | def put(self, url, callback,
params=None, json=None, headers=None) | Put to a URL.
Args:
url(string): URL for the request
callback(func): The response callback function
Keyword Args:
params(dict): Parameters for the request
json(dict): JSON body for the request
headers(dict): HTTP headers for the request
... | 4.664979 | 8.784528 | 0.531045 |
return self.adapter.patch(url, callback,
params=params, json=json, headers=headers) | def patch(self, url, callback,
params=None, json=None, headers=None) | Patch a URL.
Args:
url(string): URL for the request
callback(func): The response callback function
headers(dict): HTTP headers for the request
Keyword Args:
params(dict): Parameters for the request
json(dict): JSON body for the request
... | 3.077179 | 5.811465 | 0.529501 |
return self.adapter.delete(url, callback, json=json) | def delete(self, url, callback, json=None) | Delete a URL.
Args:
url(string): URL for the request
callback(func): The response callback function
Keyword Args:
json(dict): JSON body for the request
Returns:
The result of the callback handling the resopnse from the
execut... | 5.259564 | 12.443081 | 0.42269 |
return self.adapter.live(self, url, resource_class, resource_args,
params=params) | def live(self, url, resource_class, resource_args, params=None) | Get a live endpoint.
Args:
url(string): URL for the request
resource_class(class): The class to use for entries coming
from the live endpoint.
resource_args(dict): Additional arguments to pass to the
`resource_class` constructor
Ke... | 3.45407 | 5.014584 | 0.688805 |
with self.connection.pipeline() as pipe:
pipe.incr(self.__last_update_key)
[getattr(pipe, function)(*a) for function, a in args]
results = pipe.execute()
if kwargs.get('returns'):
return results[kwargs.get('returns')]
else:
... | def __touch_and_multi(self, *args, **kwargs) | Runs each tuple tuple of (redis_cmd, args) in provided inside of a Redis
MULTI block, plus an increment of the last_updated value, then executes
the MULTI block. If ``returns`` is specified, it returns that index
from the results list. If ``returns`` is None, returns all values. | 5.390471 | 3.399558 | 1.585639 |
persistence = PersistenceDecoder(system_effect)
banks = []
for file in glob(str(self.data_path) + "/*.json"):
bank = persistence.read(Persistence.read(file))
bank._uuid = file.split('/')[-1].split('.json')[0]
banks.append(bank)
return banks | def load(self, system_effect) | Return a list if banks presents in data_path
:param SystemEffect system_effect: SystemEffect used in pedalboards
:return list[Bank]: List with Banks persisted in
:attr:`~pluginsmanager.observer.autosaver.banks_files.BanksFiles.data_path` | 5.688717 | 4.946337 | 1.150087 |
path = self._bank_path(bank)
Persistence.save(path, bank.json) | def save_bank(self, bank) | Save the bank in your file
:param Bank bank: Bank that will be persisted | 12.074253 | 16.193941 | 0.745603 |
path = self._bank_path(bank)
Persistence.delete(path) | def delete_bank(self, bank) | Delete the bank's file
:param Bank bank: Bank that will be removed | 14.065855 | 17.02494 | 0.826191 |
for file in glob(str(self.data_path) + "/*.json"):
Persistence.delete(file) | def delete_all_banks(self) | Delete all banks files.
Util for manual save, because isn't possible know which banks
were removed | 11.711057 | 10.840706 | 1.080285 |
p = pyaudio.PyAudio()
interfaces = []
for i in range(p.get_device_count()):
data = p.get_device_info_by_index(i)
if 'hw' not in data['name']:
interfaces.append(AudioInterface(data))
p.terminate()
return interfaces | def audio_interfaces() | Extracts audio interfaces data
:return list[AudioInterface]: Audio interfaces data | 2.997399 | 2.800497 | 1.07031 |
return {
'input': {
'min': self.data['defaultLowInputLatency'],
'max': self.data['defaultHighInputLatency'],
},
'output': {
'min': self.data['defaultLowOutputLatency'],
'max': self.data['defaultHighOutpu... | def latency(self) | :return dict: Min and Max default latency for input and output channels | 2.885921 | 2.043339 | 1.412355 |
try:
self.logger.warning(self.cli_process.stderr.read())
self.logger.info(self.cli_process.stdout.read())
return_code = self.cli_process.wait(timeout=0.01)
if return_code is None:
# process is already terminated
self.logger... | def _poll_process(self) | between death of a process and its actual termination lies poorly documented requirement -
<purging process' io pipes and reading exit status>.
this can be done either by os.wait() or process.wait()
:return tuple (boolean: alive, int: return_code) | 3.346865 | 3.076772 | 1.087784 |
sa = get_object_or_404(Aggregation, slug=slug)
sa.execute_now = True
sa.save()
messages.success(request, _("Saved aggregation executed."))
return HttpResponseRedirect(
reverse(
'djmongo_browse_saved_aggregations_w_params',
args=(
sa.database_name,... | def run_aggregation_by_slug(request, slug) | Run Aggregation By Slug | 6.71798 | 6.549547 | 1.025717 |
ss = get_object_or_404(Aggregation, slug=slug)
ss.delete()
messages.success(request, _("Saved aggregation deleted."))
return HttpResponseRedirect(
reverse(
'djmongo_browse_saved_aggregations_w_params',
args=(
ss.database_name,
ss.colle... | def delete_saved_aggregation_by_slug(request, slug) | Delete Saved Aggregation By Slug | 4.741174 | 4.751111 | 0.997908 |
query = {'_id': ObjectId(key)}
collection = self.ds.connection(COLLECTION_UNIT_OF_WORK)
document = collection.find_one(query)
if document is None:
msg = 'UOW with ID={0} was not found'.format(key)
self.logger.warning(msg)
raise LookupError(ms... | def get_one(self, key) | method finds unit_of_work record and returns it to the caller | 4.417888 | 3.704911 | 1.192441 |
collection = self.ds.connection(COLLECTION_UNIT_OF_WORK)
query = {unit_of_work.STATE: {'$in': [unit_of_work.STATE_IN_PROGRESS,
unit_of_work.STATE_INVALID,
unit_of_work.STATE_REQUESTED]},
... | def get_reprocessing_candidates(self, since=None) | method queries Unit Of Work whose <start_timeperiod> is younger than <since>
and who could be candidates for re-processing | 3.092561 | 2.831657 | 1.092138 |
query = {unit_of_work.PROCESS_NAME: process_name,
unit_of_work.TIMEPERIOD: timeperiod,
unit_of_work.START_ID: start_id,
unit_of_work.END_ID: end_id}
collection = self.ds.connection(COLLECTION_UNIT_OF_WORK)
document = collection.find_on... | def get_by_params(self, process_name, timeperiod, start_id, end_id) | method finds unit_of_work record and returns it to the caller | 3.108545 | 2.793265 | 1.112872 |
assert isinstance(instance, UnitOfWork)
if instance.db_id:
query = {'_id': ObjectId(instance.db_id)}
else:
query = {unit_of_work.PROCESS_NAME: instance.process_name,
unit_of_work.TIMEPERIOD: instance.timeperiod,
unit_of_w... | def update(self, instance) | method finds unit_of_work record and change its status | 3.118856 | 2.760066 | 1.129993 |
assert isinstance(instance, UnitOfWork)
collection = self.ds.connection(COLLECTION_UNIT_OF_WORK)
try:
return collection.insert_one(instance.document).inserted_id
except MongoDuplicateKeyError as e:
exc = DuplicateKeyError(instance.process_name,
... | def insert(self, instance) | inserts a unit of work into MongoDB.
:raises DuplicateKeyError: if such record already exist | 5.224435 | 4.494104 | 1.162509 |
cursor = self.ds.filter(COLLECTION_UNIT_OF_WORK, query)
return [UnitOfWork.from_json(document) for document in cursor] | def run_query(self, query) | method runs the query and returns a list of filtered UnitOfWork records | 13.449899 | 6.97251 | 1.928989 |
if isinstance(e, DuplicateKeyError):
try:
return self.get_by_params(e.process_name, e.timeperiod, e.start_id, e.end_id)
except LookupError as e:
self.logger.error('Unable to recover from DuplicateKeyError error due to {0}'.format(e), exc_info=True... | def recover_from_duplicatekeyerror(self, e) | method tries to recover from DuplicateKeyError | 4.798052 | 4.527382 | 1.059785 |
@functools.wraps(method)
def _locker(self, *args, **kwargs):
assert hasattr(self, 'lock'), \
'thread_safe decorator applied to method {0}.{1}: missing required field {0}.lock'\
.format(self.__class__.__name__, method.__name__)
try:
self.lock.acquire()
... | def thread_safe(method) | wraps method with lock acquire/release cycle
decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock | 3.122544 | 2.997014 | 1.041885 |
from pymongo.errors import AutoReconnect
@functools.wraps(func)
def _reconnector(*args, **kwargs):
for _ in range(20):
try:
return func(*args, **kwargs)
except AutoReconnect:
time.sleep(0.250)
raise
return _reconnector | def with_reconnect(func) | Handle when AutoReconnect is raised from pymongo. This is the standard error
raised for everything from "host disconnected" to "couldn't connect to host"
and more.
The sleep handles the edge case when the state of a replica set changes, and
the cursor raises AutoReconnect because the master may have ch... | 2.432369 | 2.569886 | 0.946489 |
# the only way to implement nonlocal closure variables in Python 2.X
instances = {}
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance | def singleton(cls) | turns class to singleton
:param cls: class itself
:return: function that either creates new instance of the class or returns existing one | 5.937175 | 5.840531 | 1.016547 |
log_recording = LogRecording(parent_object_id=self.parent_object_id, created_at=datetime.utcnow())
self.log_recording_dao.remove(self.parent_object_id)
self.log_recording_dao.update(log_recording)
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
... | def attach(self) | method clears existing log_recorder entries for given parent_object_id,
creates a new one and attaches this handler to the logger
from this moment every log record will be recorded in the DB | 3.276756 | 2.340947 | 1.399756 |
'''Fire API Call for named method.
'''
api_url = '/'.join((self.api_base_url, api_method))
parameters = dict()
parameters.update(self.default_parameters)
parameters.update(kwargs)
post_params = urlencode(parameters).encode('utf-8')
response = self.opener.o... | def _make_api_call(self, api_method, **kwargs) | Fire API Call for named method. | 3.23174 | 2.454857 | 1.316468 |
"Returns a list of the DROP TABLE SQL, then the CREATE TABLE SQL, for the given module."
return sql_delete(app, style, connection) + sql_all(app, style, connection) | def sql_reset(app, style, connection) | Returns a list of the DROP TABLE SQL, then the CREATE TABLE SQL, for the given module. | 10.318144 | 3.367636 | 3.063913 |
try:
self.logger.info('UowStatusListener {')
mq_request = MqTransmission.from_json(message.body)
uow = self.uow_dao.get_one(mq_request.record_db_id)
if uow.unit_of_work_type != unit_of_work.TYPE_MANAGED:
self.logger.info('Received transmi... | def _mq_callback(self, message) | method processes messages from Synergy Worker and updates corresponding Timetable record,
as well as the job itself
:param message: <MqTransmission> mq message | 3.784272 | 3.601522 | 1.050742 |
log.debug(request.POST)
schema = LipishaInitiateSchema
api_type = request.POST.get('api_type')
if api_type == TYPE_ACKNOWLEDGE:
schema = LipishaAcknowledgeSchema
form = Form(request, schema())
transaction_status_code = STATUS_SUCCESS
transaction_status = 'Processed'
transact... | def process_lipisha_payment(request) | Handle payment received and respond with a dictionary | 2.981517 | 2.959941 | 1.007289 |
if not (self.request.POST.get('api_key') == LIPISHA_API_KEY and
self.request.POST.get('api_signature') == LIPISHA_API_SIGNATURE):
raise HTTPBadRequest
return process_lipisha_payment(self.request) | def lipisha_ipn(self) | Process lipisha IPN - Initiate/Acknowledge | 3.812178 | 3.479071 | 1.095746 |
composite_state = self.dependent_on_composite_state()
if not composite_state.all_finished:
return False
if self.job_record is None:
self.tree.timetable.assign_job_record(self)
children_processed = all([child.job_record.is_finished for child in self.chi... | def is_finalizable(self) | method checks whether:
- all counterpart of this node in dependent_on trees are finished
- all direct children of the node are finished
- the node itself is in active state | 7.148628 | 4.753864 | 1.503751 |
# step 1: request Job record if current one is not set
if self.job_record is None:
self.tree.timetable.assign_job_record(self)
# step 2: define if current node has a younger sibling
next_timeperiod = time_helper.increment_timeperiod(self.time_qualifier, self.timepe... | def validate(self) | method traverse tree and performs following activities:
* requests a job record in STATE_EMBRYO if no job record is currently assigned to the node
* requests nodes for reprocessing, if STATE_PROCESSED node relies on unfinalized nodes
* requests node for skipping if it is daily node and all 24 of... | 5.300702 | 4.641585 | 1.142003 |
event_log = self.job_record.event_log
if len(event_log) > job.MAX_NUMBER_OF_EVENTS:
del event_log[-1]
event_log.insert(0, entry) | def add_log_entry(self, entry) | :db.model.job record holds event log, that can be accessed by MX
this method adds a record and removes oldest one if necessary | 4.321295 | 3.501195 | 1.234234 |
tree_b_hierarchy_entry = tree_b.process_hierarchy.get_by_qualifier(self.time_qualifier)
if not tree_b_hierarchy_entry:
# special case when tree with more levels depends on the tree with smaller amount of levels
# for example ThreeLevel Financial tree depends on TwoLevel... | def find_counterpart_in(self, tree_b) | Finds a TreeNode counterpart for this node in tree_b
:param tree_b: target tree that hosts counterpart to this node
:return: TreeNode from tree_b that has the same timeperiod as self.timeperiod,
or None if no counterpart ware found | 11.87502 | 10.560587 | 1.124466 |
composite_state = NodesCompositeState()
for dependent_on in self.tree.dependent_on:
node_b = self.find_counterpart_in(dependent_on)
if node_b is None:
# special case when counterpart tree has no process with corresponding time_qualifier
... | def dependent_on_composite_state(self) | method iterates over all nodes that provide dependency to the current node,
and compile composite state of them all
:return instance of <NodesCompositeState> | 14.687068 | 13.481014 | 1.089463 |
response_dict = {}
try:
mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
'mongodb://localhost:27017/')
mc = MongoClient(mongodb_client_url,document_class=OrderedDict)
db = mc[str(database_name)]
collection = db[str(collection_name)]
... | def create_mongo_db(database_name, collection_name, initial_document) | Create a new database and collection by inserting one document. | 3.352643 | 3.318636 | 1.010247 |
l = []
mc = client_connector()
if not mc:
# The client couldn't connect
return ()
dbs = mc.database_names()
for d in dbs:
dbc = mc[d]
collections = dbc.collection_names()
collections = remove_values_from_list(collections, "system.indexes")
l.app... | def show_dbs() | return a list of all dbs and related collections.
Return an empty list on error. | 5.037349 | 4.154222 | 1.212585 |
try:
mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
'mongodb://localhost:27017/')
mc = MongoClient(mongodb_client_url,document_class=OrderedDict)
dbs = mc[database_name]
dbc = dbs[collection_name]
dbc.ensure_index(key)
... | def mongodb_ensure_index(database_name, collection_name, key) | Ensure Index | 3.65174 | 3.597274 | 1.015141 |
try:
mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
'mongodb://localhost:27017/')
mc = MongoClient(mongodb_client_url,document_class=OrderedDict)
dbs = mc[database_name]
dbs.drop_collection(collection_name)
# print "success"
... | def mongodb_drop_collection(database_name, collection_name) | Drop Collection | 3.749941 | 3.702136 | 1.012913 |
try:
mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
'mongodb://localhost:27017/')
mc = MongoClient(mongodb_client_url,document_class=OrderedDict)
mc.drop_database(database_name)
# print "success"
return ""
except:
... | def mongodb_drop_database(database_name) | Drop Database | 4.012764 | 3.974037 | 1.009745 |
name = "Write APIs Using IP-based Authentication"
if database_name and collection_name:
wapis = WriteAPIIP.objects.filter(
database_name=database_name,
collection_name=collection_name)
else:
wapis = WriteAPIIP.objects.all()
context = {'name': name, 'wapis': w... | def browse_ip_write_apis(request, database_name=None, collection_name=None) | Deprecated | 2.981868 | 2.890319 | 1.031674 |
name = "Write APIs Using HTTPAuth Authentication"
if database_name and collection_name:
wapis = WriteAPIHTTPAuth.objects.filter(
database_name=database_name,
collection_name=collection_name)
else:
wapis = WriteAPIHTTPAuth.objects.all()
context = {'name': name... | def browse_httpauth_write_apis(
request,
database_name=None,
collection_name=None) | Deprecated | 2.885199 | 2.826895 | 1.020625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.