code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return [
start_date + timedelta(n)
for n in range(int((end_date - start_date).days))
] | def dates_in_range(start_date, end_date) | Returns all dates between two dates.
Inclusive of the start date but not the end date.
Args:
start_date (datetime.date)
end_date (datetime.date)
Returns:
(list) of datetime.date objects | 2.887386 | 3.880122 | 0.744148 |
hooks = {}
for entrypoint in pkg_resources.iter_entry_points(ENTRYPOINT):
name = str(entrypoint).split('=')[0].strip()
try:
hook = entrypoint.load()
except Exception as e:
write_message('failed to load entry-point %r (error="%s")' % (name, e), 'yellow')
... | def load_hooks() | Load the exposed hooks.
Returns a dict of hooks where the keys are the name of the hook and the
values are the actual hook functions. | 3.494264 | 3.862394 | 0.904689 |
with open(ui_file_path, 'r') as fin:
content = fin.read()
# replace ``_translate("context", `` by ``_(``
content = re.sub(r'_translate\(".*",\s', '_(', content)
content = content.replace(
' _translate = QtCore.QCoreApplication.translate', '')
with open(ui_file_path, 'w'... | def gettext(ui_file_path) | Let you use gettext instead of the Qt tools for l18n | 4.048523 | 3.962477 | 1.021715 |
for i, line in enumerate(local_file):
try:
data = json.loads(line.decode('utf-8'))
yield data
except ValueError as e:
logging.warning("Skipping line %d due to error: %s", i, e)
continue | def stream_json_file(local_file) | Stream a JSON file (in JSON-per-line format)
Args:
local_file (file-like object) an open file-handle that contains a
JSON string on each line
Yields:
(dict) JSON objects | 2.524217 | 2.908713 | 0.867812 |
exists, dest_path = self._downloader.cache.exists_packed(package=self, pkg_path=self.packed_path,
check_stat=not self._in_cache)
unp_exists, unp_path = self._downloader.cache.exists_unpacked(package=self, pkg_path=self.unpacked_pa... | def download(self, force=False) | Download file containing this package.
:param force: Force download even if it seems file already exists
:return: Full path with filename of downloaded package file. | 3.425819 | 3.483238 | 0.983516 |
self._raw = [x for x in
self._downloader.common_parser.iter_packages_params(depslock_file_path, deps_content=deps_content)]
self.packages = self._downloader.get_dependency_packages({'raw': self._raw},
property... | def find_dependencies(self, depslock_file_path, property_validate=True, deps_content=None) | Find all dependencies by package
:param depslock_file_path:
:param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file,
:param deps_content: HACK for use --dependencies-content and existed dependencies.txt.lock file
we can skip validate... | 8.274385 | 7.288336 | 1.135291 |
if depslock_file_path is None:
self._raw = [self._params]
self._raw[0]['repo'] = None
self._raw[0]['server'] = None
else:
self._raw = [x for x in self._downloader.common_parser.iter_packages_params(depslock_file_path)]
self.packages = self... | def find_usedby(self, depslock_file_path, property_validate=True) | Find all dependencies by package
:param depslock_file_path:
:param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file,
we can skip validate part
:return: | 5.835586 | 5.617627 | 1.038799 |
# Convert parameter name to list
if param_list and isinstance(param_list, str):
param_list = [param_list]
if param_list and isinstance(param_list, (list, tuple)):
result = {k: v for k, v in self._params_found.items() if k in param_list}
result.update(... | def get_params(self, param_list=None, get_path=False, merged=False, raw=False) | Get Package params
:param param_list: name or list of parameters
:param get_path:
:param merged: if version splited, True return version in string
:param raw:
:return: | 2.23238 | 2.218566 | 1.006227 |
not_found = set()
for package_name, package in self.packages.items():
if package is None:
not_found.add(package_name)
else:
if package.packages:
not_found = not_found | package.get_none_packages()
return not_fou... | def get_none_packages(self) | Get packages with None (not founded), recursively | 2.61181 | 2.273036 | 1.149041 |
if self._usedby is None:
return None
_result = {}
params = self.merge_valued(params)
for k, v in self._usedby['AQL'].items():
if isinstance(v, str):
k = k.format(**params)
v = v.format(**params)
_result[k] = v
... | def get_usedby_aql(self, params) | Возвращает запрос AQL (без репозитория), из файла конфигурации
:param params:
:return: | 4.132649 | 4.0463 | 1.02134 |
# HACK for prefer-local
result = []
extra_params = self._rules_vars_extra.get(rule_name, {})[0]
_tmp_params = copy.deepcopy(params)
_fixed_params = {}
# Save params with list type - this type not changed
for key, value in _tmp_params.items():
... | def get_params_with_extra(self, rule_name, params) | Get params with extra, like 'any'
:param rule_name: 'path'
:param params: default params
:return: list of combination params | 3.554541 | 3.351856 | 1.06047 |
_first_pattern_pos = path.find('*')
_path_separator_pos = path.rfind('/', 0, _first_pattern_pos) + 1
_path_fixed = path[:_path_separator_pos]
_path_pattern = path[_path_separator_pos:]
return _path_fixed, _path_pattern | def split_fixed_pattern(path) | Split path into fixed and masked parts
:param path: e.g
https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/*.*.*/vc110/x86/win/boost.*.*.*.tar.gz
:return:
_path_fixed: https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/
... | 3.043098 | 2.481651 | 1.22624 |
_first_pattern_pos = path.find('*')
_path_separator_pos = path.rfind('/', 0, _first_pattern_pos)
_path_fixed = path[:_path_separator_pos]
_path_pattern = path[_path_separator_pos + 1:]
_file_name_pattern_separator_pos = _path_pattern.rfind('/', 0)
_file_name_patt... | def split_fixed_pattern_with_file_name(path) | Split path into fixed, masked parts and filename
:param path: e.g
https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/*.*.*/vc110/x86/win/boost.*.*.*.tar.gz
:return:
_path_fixed: https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/
... | 2.100661 | 1.897962 | 1.106798 |
es_connected = False
while not es_connected:
try:
ES = Elasticsearch(
hosts=[HOSTNAME]
)
es_connected = True
except TransportError as e:
logging.info('Not yet connected: %s, sleeping for 1s', e)
time.sleep(1)
re... | def basic_client() | Returns an Elasticsearch basic client that is responsive
to the environment variable ELASTICSEARCH_ENDPOINT | 4.296695 | 3.963523 | 1.08406 |
client.create(index=index_name, body=index_config) | def create_index(index_name, index_config, client) | Creates an index with a given configuration
Args:
index_name (str): Name of the index you want to create
index_config (dict) configuration for the index
client (Elasticsearch.IndicesClient) the Elasticsearch client | 3.907137 | 5.26662 | 0.741868 |
index_client = index_client or indices_client()
if not index_client.exists_alias(name=alias_name):
return None
return list(index_client.get_alias(name=alias_name).keys())[0] | def get_index_from_alias(alias_name, index_client=None) | Retrieve the base index name from an alias
Args:
alias_name (str) Name of the alias
index_client (Elasticsearch.IndicesClient) an Elasticsearch index
client. Optional, will create one if not given
Returns: (str) Name of index | 2.519472 | 3.37404 | 0.746723 |
logging.info('Performing atomic index alias swap')
if index_client.exists_alias(name=alias_name):
old_index_name = get_index_from_alias(alias_name, index_client)
logging.info('Removing old as well as adding new')
actions = {'actions': [
{'remove': {'index': old_index_nam... | def atomic_swap(alias_name, new_index_name, index_client) | Points an alias to a new index, then delete the old index if needed
Uses client.update_aliases to perform this with zero downtime
Args:
alias_name (str) Name of the alias
new_index_name (str) The new index that the alias should point to
index_client (Elasticsearch.IndicesClient) Elasti... | 2.1794 | 2.084877 | 1.045337 |
client = indices_client()
temporary_name = index_name + '_' + str(uuid.uuid4())
logging.info('creating index with config %s', index_config)
create_index(temporary_name, index_config, client)
try:
yield temporary_name
atomic_swap(index_name, temporary_name, client)
except Exc... | def zero_downtime_index(index_name, index_config) | Context manager to create a new index based on a given alias,
allow the caller to index it, and then point the alias to the new index
Args:
index_name (str) Name of an alias that should point to the new index
index_config (dict) Configuration for the new index
Yields: (name) The full name ... | 3.418114 | 3.711365 | 0.920986 |
with zero_downtime_index(self.alias_name, self.index_config()) as target_index:
self.index_all(target_index) | def replace(self) | Replace index with a new one
zero_downtime_index for safety and rollback | 15.997979 | 8.206053 | 1.949534 |
target_index = get_index_from_alias(self.alias_name)
if not target_index:
self.replace()
else:
self.index_all(target_index) | def append(self) | Index documents onto an existing index | 7.322048 | 5.734016 | 1.276949 |
oks = 0
notoks = 0
for ok, item in streaming_bulk(
self.es_client,
self._iter_documents(index_name)
):
if ok:
oks += 1
else:
notoks += 1
logging.info(
"Import results: %d ok, %d n... | def index_all(self, index_name) | Index all available documents, using streaming_bulk for speed
Args:
index_name (string): The index | 3.737316 | 3.819232 | 0.978552 |
cmd = cmd % (quote(src), quote(dst))
args = shlex.split(cmd)
return [arg for arg in args if arg] | def build_args(cmd, src, dst) | Build arguments list for passing to subprocess.call_check
:param cmd str: Command string to interpolate src and dst filepaths into.
Typically the output of `config.Config.uic_command` or `config.Config.rcc_command`.
:param src str: Source filepath.
:param dst str: Destination filepa... | 3.91063 | 6.092944 | 0.641829 |
def check_decorator(fn):
_output_format_map[name] = fn
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
return check_decorator | def register_output_format(name) | Load output format function to dictionary (decorator with this function name) | 3.564533 | 3.313998 | 1.075599 |
if params['out_format'] not in _output_format_map:
raise CrosspmException(
CROSSPM_ERRORCODE_UNKNOWN_OUT_TYPE,
'Unknown out_format: [{}]'.format(params['out_format']),
)
f = _output_format_map[params['out_format']]
result = f(self... | def write_output(self, params, packages) | Функция вызывает определенную функцию для фиксированного out-format
:param params:
:param packages:
:return: | 3.582568 | 3.415634 | 1.048874 |
self._output_config['type'] = PLAIN
text = ''
tmp_packages = OrderedDict()
columns = self._config.get_columns()
widths = {}
for _pkg in packages.values():
_pkg_name = _pkg.package_name
_params = _pkg.get_params(columns, merged=True, raw=Fa... | def output_format_lock(self, packages, **kwargs) | Text to lock file | 2.811329 | 2.797625 | 1.004898 |
def create_ordered_list(packages_):
list_ = []
for _pkg_name in packages_:
_pkg = packages_[_pkg_name]
if _pkg and _pkg.packages:
list_.extend(create_ordered_list(_pkg.packages))
if _pkg:
... | def output_format_module(self, packages, esc_path=False) | Create out with child first position | 3.221317 | 3.219828 | 1.000462 |
def decorator(func):
for key, value in kwargs.items():
setattr(func, key, value)
return func
return decorator | def smart(**kwargs) | Simple decorator to get custom fields on admin class, using this you will use less line codes
:param short_description: description of custom field
:type str:
:param admin_order_field: field to order on click
:type str:
:param allow_tags: allow html tags
:type bool:
:param boolean: if fi... | 3.202973 | 3.94721 | 0.811452 |
'''
If the value is a float, create a numpy array of the required length, filled with value
If the value is a numpy array, check its length
Otherwise throw a type error
'''
try:
fv = float(value)
return np.full(params.length, fv, np.float)
except TypeError:
if isinsta... | def create_buffer(params, value) | If the value is a float, create a numpy array of the required length, filled with value
If the value is a numpy array, check its length
Otherwise throw a type error | 4.378681 | 2.518805 | 1.738396 |
'''
Update the length of the buffer in seconds
:param time: number of seconds
:return: self
'''
self.length = int(time*self.sample_rate)
return self | def set_time(self, time) | Update the length of the buffer in seconds
:param time: number of seconds
:return: self | 5.823449 | 2.503895 | 2.325756 |
if not isinstance(method, Methods):
method = Methods(method.upper())
if content_type == 'application/json' and isinstance(body, dict):
body = json.dumps(body)
if isinstance(query_params, dict):
query_string = parse.urlencode(query_params)
elif... | def make_request(self, method, service, path, body=None,
query_params: QueryParams=None,
headers: dict=None,
correlation_id: str=None,
content_type: str='application/json',
context: Req... | Make a request to another service. If `context` is provided, then
context and correlation will be pulled from the provided request
object for you. This includes credentials, correlationid,
and service-headers.
:param method: GET/PUT/PATCH, etc.
:param service: name of service
... | 2.948204 | 3.044814 | 0.968271 |
return self.make_request(Methods.GET, service, path, **kwargs) | def get(self, service, path, **kwargs) | Make a get request (this returns a coroutine) | 6.087836 | 4.260941 | 1.428754 |
return self.make_request(Methods.POST, service, path, body=body,
**kwargs) | def put(self, service, path, body, **kwargs) | Make a put request (this returns a coroutine) | 6.454995 | 5.6085 | 1.150931 |
return self.make_request(Methods.PATCH, service, path, body=body,
**kwargs) | def patch(self, service, path, body, **kwargs) | Make a patche requests (this returns a coroutine) | 5.778227 | 4.840158 | 1.19381 |
return self.make_request(Methods.DELETE, service, path, **kwargs) | def delete(self, service, path, **kwargs) | Make a delete requests (this returns a coroutine) | 6.385294 | 4.439631 | 1.438249 |
identifier = request_object.identifier
# Look for the object by its ID and return it
resource = request_object.entity_cls.get(identifier)
return ResponseSuccess(Status.SUCCESS, resource) | def process_request(self, request_object) | Fetch Resource and return Entity | 11.054605 | 8.814874 | 1.254085 |
invalid_req = InvalidRequestObject()
# Extract the pagination parameters from the input
page = int(adict.pop('page', 1))
per_page = int(adict.pop(
'per_page', getattr(active_config, 'PER_PAGE', 10)))
order_by = adict.pop('order_by', ())
# Check for ... | def from_dict(cls, entity_cls, adict) | Initialize a ListRequestObject object from a dictionary. | 4.108998 | 3.804441 | 1.080053 |
resources = (request_object.entity_cls.query
.filter(**request_object.filters)
.offset((request_object.page - 1) * request_object.per_page)
.limit(request_object.per_page)
.order_by(request_object.order_by)
... | def process_request(self, request_object) | Return a list of resources | 3.553686 | 3.218351 | 1.104195 |
resource = request_object.entity_cls.create(**request_object.data)
return ResponseSuccessCreated(resource) | def process_request(self, request_object) | Process Create Resource Request | 15.851606 | 11.016618 | 1.438881 |
# Retrieve the object by its identifier
entity = request_object.entity_cls.get(request_object.identifier)
# Update the object and return the updated data
resource = entity.update(request_object.data)
return ResponseSuccess(Status.SUCCESS, resource) | def process_request(self, request_object) | Process Update Resource Request | 6.525011 | 5.788091 | 1.127316 |
# Delete the object by its identifier
entity = request_object.entity_cls.get(request_object.identifier)
entity.delete()
# FIXME Check for return value of `delete()`
# We have successfully deleted the object.
# Sending a 204 Response code.
return Respon... | def process_request(self, request_object) | Process the Delete Resource Request | 10.389238 | 9.482571 | 1.095614 |
if isinstance(value, str) or value is None:
return value
return str(value) | def _cast_to_type(self, value) | Convert the value to its string representation | 4.519839 | 3.564349 | 1.268068 |
try:
return int(value)
except (ValueError, TypeError):
self.fail('invalid', value=value) | def _cast_to_type(self, value) | Convert the value to an int and raise error on failures | 4.741748 | 3.347436 | 1.416531 |
try:
return float(value)
except (ValueError, TypeError):
self.fail('invalid', value=value) | def _cast_to_type(self, value) | Convert the value to a float and raise error on failures | 4.779361 | 3.44133 | 1.388812 |
if value in (True, False):
return bool(value)
if value in ('t', 'True', '1'):
return True
if value in ('f', 'False', '0'):
return False
self.fail('invalid', value=value) | def _cast_to_type(self, value) | Convert the value to a boolean and raise error on failures | 2.982922 | 2.581792 | 1.155369 |
if not isinstance(value, list):
self.fail('invalid', value=value)
return value | def _cast_to_type(self, value) | Raise error if the value is not a list | 7.249872 | 4.924272 | 1.472273 |
if not isinstance(value, dict):
self.fail('invalid', value=value)
return value | def _cast_to_type(self, value) | Raise error if the value is not a dict | 6.882597 | 4.443905 | 1.548772 |
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
try:
value = date_parser(value)
return value.date()
except ValueError:
self.fail('invalid', value=value) | def _cast_to_type(self, value) | Convert the value to a date and raise error on failures | 2.954544 | 2.301732 | 1.283618 |
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
value = datetime.datetime(value.year, value.month, value.day)
return value
try:
value = date_parser(value)
return value
except V... | def _cast_to_type(self, value) | Convert the value to a datetime and raise error on failures | 2.751702 | 2.211677 | 1.24417 |
async def make_request(self, service: str, method: str, path: str,
body: bytes=None, query: str=None,
headers: dict=None, correlation_id: str=None,
content_type: str=None,
timeout:int = 30,
... | Method for actually making a request
:param service: service to make request too
:param method: HTTP method: GET/PUT/POST etc.
:param path: routing path.
Should support dots `foo.2.bars` or slashes `foo/2/bars`
:param body: request body. Bytes-like object
:param query... | 3,197,212.5 | 186,418.9375 | 17.150685 | |
# If the request object is not valid then return a failure response
if not request_object.is_valid:
return ResponseFailure.build_from_invalid_request(
request_object)
# Try to process the request and handle any errors encountered
try:
re... | def execute(self, request_object) | Generic executor method of all UseCases | 3.809649 | 3.700045 | 1.029622 |
'''
To check execution time of a function
borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d
>>> def logger(details, args, kwargs): #some function that uses the time output
... print(details)
...
>>> @FunctionTimer(on_done=... | def FunctionTimer(on_done=None) | To check execution time of a function
borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d
>>> def logger(details, args, kwargs): #some function that uses the time output
... print(details)
...
>>> @FunctionTimer(on_done= logger)
... | 3.529817 | 1.501392 | 2.35103 |
await self.channel.exchange_declare(
self.exchange,
self.exchange_type,
durable=self.durable,
auto_delete=self.auto_delete,
no_wait=self.no_wait,
) | async def exchange_declare(self) | Override this method to change how a exchange is declared | 2.004329 | 1.858864 | 1.078255 |
await self.channel.queue_declare(
self.queue,
durable=self.durable,
exclusive=self.exclusive,
no_wait=self.no_wait
) | async def queue_declare(self) | Override this method to change how a queue is declared | 2.881109 | 2.493579 | 1.155411 |
dict_obj = {}
for field_name in entity.meta_.attributes:
dict_obj[field_name] = getattr(entity, field_name)
return dict_obj | def from_entity(cls, entity: Entity) -> 'DictModel' | Convert the entity to a dictionary record | 3.509455 | 3.252259 | 1.079082 |
database = {
'data': _databases.setdefault(self.identifier, defaultdict(dict)),
'lock': _locks.setdefault(self.identifier, Lock()),
'counters': _counters
}
return database | def get_connection(self) | Return the dictionary database object | 8.13741 | 6.382321 | 1.274992 |
model_cls = self.get_model(entity_cls)
return DictRepository(self, entity_cls, model_cls) | def get_repository(self, entity_cls) | Return a repository object configured with a live connection | 5.082546 | 4.261728 | 1.192602 |
results = {}
for record_key, record_value in db.items():
match = True
stripped_key, lookup_class = self._extract_lookup(key)
lookup = lookup_class(record_value[stripped_key], value)
if negated:
match &= not eval(lookup.as_express... | def _evaluate_lookup(self, key, value, negated, db) | Extract values from DB that match the given criteria | 3.262789 | 3.152459 | 1.034998 |
assert isinstance(query, str)
conn = self.get_connection()
items = []
for schema_name in conn['data']:
input_db = conn['data'][schema_name]
try:
# Ensures that the string contains double quotes around keys and values
quer... | def raw(self, query: Any, data: Any = None) | Run raw queries on the database
As an example of running ``raw`` queries on a Dict repository, we will run the query
on all possible schemas, and return all results. | 5.904343 | 5.511894 | 1.0712 |
for field_name, field_obj in \
self.entity_cls.meta_.auto_fields:
counter_key = f'{self.schema_name}_{field_name}'
if not (field_name in model_obj and model_obj[field_name] is not None):
# Increment the counter and it should start from 1
... | def _set_auto_fields(self, model_obj) | Set the values of the auto field using counter | 4.546988 | 4.082754 | 1.113706 |
# Update the value of the counters
model_obj = self._set_auto_fields(model_obj)
# Add the entity to the repository
identifier = model_obj[self.entity_cls.meta_.id_field.field_name]
with self.conn['lock']:
self.conn['data'][self.schema_name][identifier] = mod... | def create(self, model_obj) | Write a record to the dict repository | 6.545501 | 6.242948 | 1.048463 |
# Filter the dictionary objects based on the filters
negated = criteria.negated
input_db = None
if criteria.connector == criteria.AND:
# Trim database records over successive iterations
# Whatever is left at the end satisfy all criteria (AND)
... | def _filter(self, criteria: Q, db) | Recursive function to filter items from dictionary | 3.99199 | 3.879033 | 1.02912 |
if criteria.children:
items = list(self._filter(criteria, self.conn['data'][self.schema_name]).values())
else:
items = list(self.conn['data'][self.schema_name].values())
# Sort the filtered results based on the order_by clause
for o_key in order_by:
... | def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()) | Read the repository and return results as per the filer | 3.156359 | 2.955244 | 1.068054 |
identifier = model_obj[self.entity_cls.meta_.id_field.field_name]
with self.conn['lock']:
# Check if object is present
if identifier not in self.conn['data'][self.schema_name]:
raise ObjectNotFoundError(
f'`{self.__class__.__name__}` o... | def update(self, model_obj) | Update the entity record in the dictionary | 4.827067 | 4.59001 | 1.051646 |
items = self._filter(criteria, self.conn['data'][self.schema_name])
update_count = 0
for key in items:
item = items[key]
item.update(*args)
item.update(kwargs)
self.conn['data'][self.schema_name][key] = item
update_count += 1... | def update_all(self, criteria: Q, *args, **kwargs) | Update all objects satisfying the criteria | 3.98474 | 3.784565 | 1.052892 |
if criteria:
# Delete the object from the dictionary and return the deletion count
items = self._filter(criteria, self.conn['data'][self.schema_name])
# Delete all the matching identifiers
with self.conn['lock']:
for identifier in items:
... | def delete_all(self, criteria: Q = None) | Delete the dictionary object by its criteria | 3.870718 | 3.470463 | 1.115332 |
# Ensure that we are dealing with a string, for this repository
assert isinstance(query, str)
input_db = self.conn['data'][self.schema_name]
result = None
try:
# Ensures that the string contains double quotes around keys and values
query = query... | def raw(self, query: Any, data: Any = None) | Run raw query on Repository.
For this stand-in repository, the query string is a json string that contains kwargs
criteria with straigh-forward equality checks. Individual criteria are always ANDed
and the result is always a subset of the full repository.
We will ignore the `data` para... | 6.346788 | 5.686265 | 1.116161 |
if isinstance(self.source, str):
# Replace single and double quotes with escaped single-quote
self.source = self.source.replace("'", "\'").replace('"', "\'")
return "\"{source}\"".format(source=self.source)
return self.source | def process_source(self) | Return source with transformations, if any | 4.644571 | 4.084993 | 1.136984 |
if isinstance(self.target, str):
# Replace single and double quotes with escaped single-quote
self.target = self.target.replace("'", "\'").replace('"', "\'")
return "\"{target}\"".format(target=self.target)
return self.target | def process_target(self) | Return target with transformations, if any | 4.493429 | 4.111019 | 1.093021 |
route = route.replace('.', '?')
route = route.replace('/', '.').strip('.')
topic = f'{method.value.lower()}.{route}'
# need to replace `{id}` and `{id}:some_method` with just `*`
return re.sub(r"\.\{[^\}]*\}[:\w\d_-]*", ".*", topic) | def parse_url_to_topic(method, route) | Transforms a URL to a topic.
`GET /bar/{id}` -> `get.bar.*`
`POST /bar/{id}` -> `post.bar.*`
`GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz`
Possible gotchas
`GET /foo/{id}` -> `get.foo.*`
`GET /foo/{id}:action` -> `get.foo.*`
However, once it hits the service the router will be able to d... | 8.243013 | 7.656845 | 1.076555 |
if futurize:
asyncio.ensure_future(
self.handle_request(channel, body, envelope, properties,
futurize=False))
return
self._counter += 1
headers = properties.headers or {}
query = headers.pop('x-wasp-que... | async def handle_request(self, channel: Channel, body, envelope,
properties, futurize=True) | the 'futurize' param is simply because aioamqp doesnt send another job until
this method returns (completes), so we ensure the future of
ourselves and return immediately so we can handle many requests
at a time. | 3.451112 | 3.390152 | 1.017982 |
return json.dumps({
"wrap": load_json(anything.decode(encoding))
}, ensure_ascii=False) | def wrap(anything: bytes, encoding: str) -> str | Use for example of Transformer.function | 9.551831 | 7.399976 | 1.290792 |
def filter(self, criteria: Q, offset: int = 0, limit: int = 10,
order_by: list = ()) -> ResultSet | Filter objects from the repository. Method must return a `ResultSet`
object | 11,698,855 | 80,292.867188 | 145.702295 | |
# FIXME Refactor this method to make it simpler
@classmethod
def from_dict(cls, adict):
invalid_req = InvalidRequestObject()
values = {}
for item in fields(cls):
value = None
if item.metadata and 'require... | def construct(cls, name: str, declared_fields: typing.List[tuple]) | Utility method packaged along with the factory to be able to construct Request Object
classes on the fly.
Example:
.. code-block:: python
UserShowRequestObject = Factory.create_request_object(
'CreateRequestObject',
[('identifier', int, {'required':... | 2.956414 | 2.932677 | 1.008094 |
formatted_fields = []
for declared_field in declared_fields:
field_name = field_type = field_defn = None
# Case when only (name), or "name", is specified
if isinstance(declared_field, str) or len(declared_field) == 1:
field_name = declared_fi... | def _format_fields(cls, declared_fields: typing.List[tuple]) | Process declared fields and construct a list of tuples
that can be fed into dataclass constructor factory. | 2.376231 | 2.312594 | 1.027517 |
'''
Write a sequence of samples as a WAV file
Currently a 16 bit mono file
'''
writer = wave.open(filename, 'wb');
# Set the WAV file parameters, currently default values
writer.setnchannels(1)
writer.setsampwidth(2)
writer.setframerate(params.sample_rate)
data_out = array.array(... | def save(params, filename, source) | Write a sequence of samples as a WAV file
Currently a 16 bit mono file | 3.722543 | 2.785893 | 1.336212 |
heap = self._heap
v, k = heap[0]
while k not in self or self[k] != v:
heappop(heap)
v, k = heap[0]
return k | def smallest(self) | Return the item with the lowest priority.
Raises IndexError if the object is empty. | 5.616751 | 5.351805 | 1.049506 |
heap = self._heap
v, k = heappop(heap)
while k not in self or self[k] != v:
v, k = heappop(heap)
del self[k]
return k | def pop_smallest(self) | Return the item with the lowest priority and remove it.
Raises IndexError if the object is empty. | 4.606188 | 4.577868 | 1.006186 |
# Initialize the use case and request objects
use_case = usecase_cls()
payload.update({'entity_cls': entity_cls})
request_object = request_object_cls.from_dict(payload)
# Run the use case and return the response
resp = use_case.execute(request_object)
... | def perform(cls, entity_cls, usecase_cls, request_object_cls,
payload: dict, raise_error=False) | This method bundles all essential artifacts and initiates usecase
execution.
:param entity_cls: The entity class to be used for running the usecase
:param usecase_cls: The usecase class that will be executed by
the tasklet.
:param request_object_cls: The request object to be used... | 3.416068 | 3.308405 | 1.032542 |
if self.ignore_content_type:
return self.original_body
if self._body is None and self.original_body is not None:
if isinstance(self.original_body, bytes):
self._body = self.parser.decode(self.original_body)
else:
self._body = s... | def body(self) -> dict | Decoded Body | 2.781668 | 2.62142 | 1.06113 |
if self._raw_body is None and self.original_body is not None:
if isinstance(self.original_body, dict):
self._raw_body = self.parser.encode(self.original_body)
if isinstance(self._raw_body, str):
self._raw_body = self._raw_body.encode()
... | def raw_body(self) -> bytes | Encoded Body | 1.595191 | 1.54694 | 1.031191 |
msg_count = 0
for message in messages: # .message() triggers header validation
message.message()
email.outbox.append(message)
msg_count += 1
return msg_count | def send_messages(self, messages) | Redirect messages to the dummy outbox | 8.03566 | 5.94083 | 1.352616 |
'''
Generate a square wave
:param params: buffer parameters, controls length of signal created
:param frequency: wave frequency (array or value)
:param amplitude: wave amplitude (array or value)
:param offset: offset of wave mean from zero (array or value)
:param ratio: ratio of high to low ... | def square_wave(params, frequency=400, amplitude=1,
offset=0, ratio=0.5) | Generate a square wave
:param params: buffer parameters, controls length of signal created
:param frequency: wave frequency (array or value)
:param amplitude: wave amplitude (array or value)
:param offset: offset of wave mean from zero (array or value)
:param ratio: ratio of high to low time (array ... | 3.580968 | 1.853237 | 1.932278 |
'''
Generate a noise signal
:param params: buffer parameters, controls length of signal created
:param amplitude: wave amplitude (array or value)
:param offset: offset of wave mean from zero (array or value)
:return: array of resulting signal
'''
amplitude = create_buffer(params, amplitu... | def noise(params, amplitude=1, offset=0) | Generate a noise signal
:param params: buffer parameters, controls length of signal created
:param amplitude: wave amplitude (array or value)
:param offset: offset of wave mean from zero (array or value)
:return: array of resulting signal | 5.549418 | 2.1561 | 2.573823 |
'''
Generate a wave from a wavetable
:param params: buffer parameters, controls length of signal created
:param frequency: wave frequency (array or value)
:param amplitude: wave amplitude (array or value)
:param offset: offset of wave mean from zero (array or value)
:param table: table of va... | def table_wave(params, frequency=400, amplitude=1,
offset=0, table=None) | Generate a wave from a wavetable
:param params: buffer parameters, controls length of signal created
:param frequency: wave frequency (array or value)
:param amplitude: wave amplitude (array or value)
:param offset: offset of wave mean from zero (array or value)
:param table: table of values represe... | 4.961043 | 1.856159 | 2.672747 |
'''
Generate a sine wave
Convenience function, table_wave generates a sine wave by default
:param params: buffer parameters, controls length of signal created
:param frequency: wave frequency (array or value)
:param amplitude: wave amplitude (array or value)
:param offset: offset of wave mea... | def sine_wave(params, frequency=400, amplitude=1, offset=0) | Generate a sine wave
Convenience function, table_wave generates a sine wave by default
:param params: buffer parameters, controls length of signal created
:param frequency: wave frequency (array or value)
:param amplitude: wave amplitude (array or value)
:param offset: offset of wave mean from zero ... | 6.901594 | 1.629772 | 4.234699 |
'''
Convert a midi value to a frequency.
Midi value 69 corresponds to A4 (440Hz). Changing the midi value by 1 corresponds to
one semitone
:param params: buffer parameters, controls length of signal created
:param midi: midi value
:return: array of resulting frequency
'''
midi = crea... | def midi2f(params, midi=69) | Convert a midi value to a frequency.
Midi value 69 corresponds to A4 (440Hz). Changing the midi value by 1 corresponds to
one semitone
:param params: buffer parameters, controls length of signal created
:param midi: midi value
:return: array of resulting frequency | 7.379068 | 1.972477 | 3.741016 |
class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)]
return cls.merge_dicts(class_lookups) | def get_lookups(cls) | Fetch all Lookups | 5.02941 | 5.025453 | 1.000787 |
from protean.core.repository import BaseLookup
lookup = self._get_lookup(lookup_name)
# If unable to find Lookup, or if Lookup is the wrong class, raise Error
if lookup is None or (lookup is not None and not issubclass(lookup, BaseLookup)):
raise NotImplementedError... | def get_lookup(self, lookup_name) | Fetch Lookup by name | 6.532434 | 6.139843 | 1.063942 |
merged = {}
for d in reversed(dicts):
merged.update(d)
return merged | def merge_dicts(dicts) | Merge dicts in reverse to preference the order of the original list. e.g.,
merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'. | 4.393561 | 2.861915 | 1.535182 |
if lookup_name is None:
lookup_name = lookup.lookup_name
if 'class_lookups' not in cls.__dict__:
cls.class_lookups = {}
cls.class_lookups[lookup_name] = lookup
cls._clear_cached_lookups()
return lookup | def register_lookup(cls, lookup, lookup_name=None) | Register a Lookup to a class | 2.910801 | 2.770992 | 1.050454 |
if lookup_name is None:
lookup_name = lookup.lookup_name
del cls.class_lookups[lookup_name] | def _unregister_lookup(cls, lookup, lookup_name=None) | Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe. | 3.433531 | 2.686441 | 1.278096 |
path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
args, kwargs = (), {}
if len(self.children) == 1 and not isinstance(self.children[0], Q):
child = self.children[0]
kwargs = {child[0]: child[1]}
else:
args = tuple(self.chi... | def deconstruct(self) | Deconstruct a Q Object | 3.204911 | 3.115612 | 1.028662 |
if val is None:
return None
elif isinstance(val, str):
return import_from_string(val)
elif isinstance(val, (list, tuple)):
return [import_from_string(item) for item in val]
return val | def perform_import(val) | If the given setting is a string import notation,
then perform the necessary import or imports. | 1.999687 | 1.998102 | 1.000793 |
try:
module_path, class_name = val.rsplit('.', 1)
module = import_module(module_path)
return getattr(module, class_name)
except (ImportError, AttributeError) as e:
msg = f"Could not import {val}. {e.__class__.__name__}: {e}"
raise ImportError(msg) | def import_from_string(val) | Attempt to import a class from a string representation. | 1.958984 | 1.887165 | 1.038057 |
for key in data:
setattr(self.local_context, key, data[key]) | def set_context(self, data) | Load Context with data | 5.31944 | 4.715973 | 1.127962 |
self.value = None
self.reference.value = None
instance.__dict__.pop(self.field_name, None)
instance.__dict__.pop(self.reference.field_name, None)
self.reference.delete_cached_value(instance) | def _reset_values(self, instance) | Reset all associated values and clean up dictionary items | 3.718279 | 3.284068 | 1.132217 |
# Checks if ``to_cls`` is a string
# If it is, checks if the entity is imported and available
# If it is, register the class
try:
if isinstance(self._to_cls, str):
self._to_cls = fetch_entity_cls_from_registry(self._to_cls)
except Assertio... | def to_cls(self) | Property to retrieve to_cls as an entity when possible | 6.894089 | 5.823081 | 1.183925 |
if isinstance(self.to_cls, str):
return 'id'
else:
return self.via or self.to_cls.meta_.id_field.attribute_name | def linked_attribute(self) | Choose the Linkage attribute between `via` and designated `id_field` of the target class
This method is initially called from `__set_name__()` -> `get_attribute_name()`
at which point, the `to_cls` has not been initialized properly. We simply default
the linked attribute to 'id' in that case.
... | 8.119457 | 4.808194 | 1.688671 |
return self.via or (utils.inflection.underscore(owner.__name__) + '_id') | def _linked_attribute(self, owner) | Choose the Linkage attribute between `via` and own entity's `id_field`
FIXME Explore converting this method into an attribute, and treating it
uniformly at `association` level. | 18.087675 | 11.56816 | 1.563574 |
return self.to_cls.query.filter(**{key: value}) | def _fetch_objects(self, key, value) | Fetch Multiple linked objects | 16.447653 | 15.800871 | 1.040933 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.