Search is not available for this dataset
text stringlengths 75 104k |
|---|
def set_terminal_key(self, encrypted_key):
"""
Change the terminal key. The encrypted_key is a hex string.
encrypted_key is expected to be encrypted under master key
"""
if encrypted_key:
try:
new_key = bytes.fromhex(encrypted_key)
if l... |
def get_encrypted_pin(self, clear_pin, card_number):
"""
Get PIN block in ISO 0 format, encrypted with the terminal key
"""
if not self.terminal_key:
print('Terminal key is not set')
return ''
if self.pinblock_format == '01':
try:
... |
def is_url(string, allowed_schemes=None):
"""
Check if a string is a valid url.
:param string: String to check.
:param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid).
:return: True if url, false otherwise
:rtype: bool
"""
if not... |
def is_credit_card(string, card_type=None):
"""
Checks if a string is a valid credit card number.
If card type is provided then it checks that specific type,
otherwise any known credit card number will be accepted.
:param string: String to check.
:type string: str
:param card_type: Card typ... |
def is_snake_case(string, separator='_'):
"""
Checks if a string is formatted as snake case.
A string is considered snake case when:
* it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \
and optionally numbers ([0-9])
* it does not start/end with an underscore... |
def is_json(string):
"""
Check if a string is a valid json.
:param string: String to check.
:type string: str
:return: True if json, false otherwise
:rtype: bool
"""
if not is_full_string(string):
return False
if bool(JSON_WRAPPER_RE.search(string)):
try:
... |
def is_palindrome(string, strict=True):
"""
Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).
:param string: String to check.
:type string: str
:param strict: True if white spaces matter (default), false otherwise.
:type strict: bool
:return: True if the strin... |
def is_pangram(string):
"""
Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram).
:param string: String to check.
:type string: str
:return: True if the string is a pangram, False otherwise.
"""
return is_full_string(string) and set(SPACES_RE.sub('', string)).issuperset... |
def is_slug(string, sign='-'):
"""
Checks if a given string is a slug.
:param string: String to check.
:type string: str
:param sign: Join sign used by the slug.
:type sign: str
:return: True if slug, false otherwise.
"""
if not is_full_string(string):
return False
rex =... |
def camel_case_to_snake(string, separator='_'):
"""
Convert a camel case string into a snake case one.
(The original string is returned if is not a valid camel case string)
:param string: String to convert.
:type string: str
:param separator: Sign to use as separator.
:type separator: str
... |
def snake_case_to_camel(string, upper_case_first=True, separator='_'):
"""
Convert a snake case string into a camel case one.
(The original string is returned if is not a valid snake case string)
:param string: String to convert.
:type string: str
:param upper_case_first: True to turn the first... |
def shuffle(string):
"""
Return a new string containing shuffled items.
:param string: String to shuffle
:type string: str
:return: Shuffled string
:rtype: str
"""
s = sorted(string) # turn the string into a list of chars
random.shuffle(s) # shuffle the list
return ''.join(s) |
def strip_html(string, keep_tag_content=False):
"""
Remove html code contained into the given string.
:param string: String to manipulate.
:type string: str
:param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).
:type keep_tag_content: bool
... |
def prettify(string):
"""
Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following:
- String cannot start or end with spaces
- String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".")
- Arithmetic operator... |
def slugify(string, sign='-'):
"""
Converts a string into a slug using provided join sign.
(**(This Is A "Test"!)** -> **this-is-a-test**)
:param string: String to convert.
:type string: str
:param sign: Sign used to join string tokens (default to "-").
:type sign: str
:return: Slugifie... |
def setup(app):
"""Initialize Sphinx extension."""
app.setup_extension('nbsphinx')
app.add_source_suffix('.nblink', 'linked_jupyter_notebook')
app.add_source_parser(LinkedNotebookParser)
app.add_config_value('nbsphinx_link_target_root', None, rebuild='env')
return {'version': __version__, 'para... |
def parse(self, inputstring, document):
"""Parse the nblink file.
Adds the linked file as a dependency, read the file, and
pass the content to the nbshpinx.NotebookParser.
"""
link = json.loads(inputstring)
env = document.settings.env
source_dir = os.path.dirname... |
def finalize(self):
"""Output the duplicate scripts detected."""
if self.total_duplicate > 0:
print('{} duplicate scripts found'.format(self.total_duplicate))
for duplicate in self.list_duplicate:
print(duplicate) |
def analyze(self, scratch, **kwargs):
"""Run and return the results from the DuplicateScripts plugin.
Only takes into account scripts with more than 3 blocks.
"""
scripts_set = set()
for script in self.iter_scripts(scratch):
if script[0].type.text == 'define %s':
... |
def _set_content_type(self, system):
""" Set response content type """
request = system.get('request')
if request:
response = request.response
ct = response.content_type
if ct == response.default_content_type:
response.content_type = 'applicati... |
def _render_response(self, value, system):
""" Render a response """
view = system['view']
enc_class = getattr(view, '_json_encoder', None)
if enc_class is None:
enc_class = get_json_encoder()
return json.dumps(value, cls=enc_class) |
def _get_common_kwargs(self, system):
""" Get kwargs common for all methods. """
enc_class = getattr(system['view'], '_json_encoder', None)
if enc_class is None:
enc_class = get_json_encoder()
return {
'request': system['request'],
'encoder': enc_class... |
def _get_create_update_kwargs(self, value, common_kw):
""" Get kwargs common to create, update, replace. """
kw = common_kw.copy()
kw['body'] = value
if '_self' in value:
kw['headers'] = [('Location', value['_self'])]
return kw |
def render_create(self, value, system, common_kw):
""" Render response for view `create` method (collection POST) """
kw = self._get_create_update_kwargs(value, common_kw)
return JHTTPCreated(**kw) |
def render_update(self, value, system, common_kw):
""" Render response for view `update` method (item PATCH) """
kw = self._get_create_update_kwargs(value, common_kw)
return JHTTPOk('Updated', **kw) |
def render_delete_many(self, value, system, common_kw):
""" Render response for view `delete_many` method (collection DELETE)
"""
if isinstance(value, dict):
return JHTTPOk(extra=value)
msg = 'Deleted {} {}(s) objects'.format(
value, system['view'].Model.__name__)... |
def render_update_many(self, value, system, common_kw):
""" Render response for view `update_many` method
(collection PUT/PATCH)
"""
msg = 'Updated {} {}(s) objects'.format(
value, system['view'].Model.__name__)
return JHTTPOk(msg, **common_kw.copy()) |
def _render_response(self, value, system):
""" Handle response rendering.
Calls mixin methods according to request.action value.
"""
super_call = super(DefaultResponseRendererMixin, self)._render_response
try:
method_name = 'render_{}'.format(system['request'].action... |
def remember(self, request, username, **kw):
""" Returns 'WWW-Authenticate' header with a value that should be used
in 'Authorization' header.
"""
if self.credentials_callback:
token = self.credentials_callback(username, request)
api_key = 'ApiKey {}:{}'.format(us... |
def callback(self, username, request):
""" Having :username: return user's identifiers or None. """
credentials = self._get_credentials(request)
if credentials:
username, api_key = credentials
if self.check:
return self.check(username, api_key, request) |
def _get_credentials(self, request):
""" Extract username and api key token from 'Authorization' header """
authorization = request.headers.get('Authorization')
if not authorization:
return None
try:
authmeth, authbytes = authorization.split(' ', 1)
except... |
def _get_event_kwargs(view_obj):
""" Helper function to get event kwargs.
:param view_obj: Instance of View that processes the request.
:returns dict: Containing event kwargs or None if events shouldn't
be fired.
"""
request = view_obj.request
view_method = getattr(view_obj, request.ac... |
def _get_event_cls(view_obj, events_map):
""" Helper function to get event class.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Found event class.
"""
request = view_obj.request
view_... |
def _trigger_events(view_obj, events_map, additional_kw=None):
""" Common logic to trigger before/after events.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Instance if triggered event.
"""
... |
def subscribe_to_events(config, subscriber, events, model=None):
""" Helper function to subscribe to group of events.
:param config: Pyramid contig instance.
:param subscriber: Event subscriber function.
:param events: Sequence of events to subscribe to.
:param model: Model predicate value.
"""... |
def add_field_processors(config, processors, model, field):
""" Add processors for model field.
Under the hood, regular nefertari event subscribed is created which
calls field processors in order passed to this function.
Processors are passed following params:
* **new_value**: New value of of fie... |
def set_field_value(self, field_name, value):
""" Set value of request field named `field_name`.
Use this method to apply changes to object which is affected
by request. Values are set on `view._json_params` dict.
If `field_name` is not affected by request, it is added to
`self... |
def set_field_value(self, field_name, value):
""" Set value of response field named `field_name`.
If response contains single item, its field is set.
If response contains multiple items, all the items in response
are edited.
To edit response meta(e.g. 'count') edit response dire... |
def process_fields_param(fields):
""" Process 'fields' ES param.
* Fields list is split if needed
* '_type' field is added, if not present, so the actual value is
displayed instead of 'None'
"""
if not fields:
return fields
if isinstance(fields, six.string_types):
fields =... |
def _catch_index_error(self, response):
""" Catch and raise index errors which are not critical and thus
not raised by elasticsearch-py.
"""
code, headers, raw_data = response
if not raw_data:
return
data = json.loads(raw_data)
if not data or not data.... |
def setup_mappings(cls, force=False):
""" Setup ES mappings for all existing models.
This method is meant to be run once at application lauch.
ES._mappings_setup flag is set to not run make mapping creation
calls on subsequent runs.
Use `force=True` to make subsequent calls per... |
def process_chunks(self, documents, operation):
""" Apply `operation` to chunks of `documents` of size
`self.chunk_size`.
"""
chunk_size = self.chunk_size
start = end = 0
count = len(documents)
while count:
if count < chunk_size:
chun... |
def index_missing_documents(self, documents, request=None):
""" Index documents that are missing from ES index.
Determines which documents are missing using ES `mget` call which
returns a list of document IDs as `documents`. Then missing
`documents` from that list are indexed.
"... |
def aggregate(self, **params):
""" Perform aggreration
Arguments:
:_aggregations_params: Dict of aggregation params. Root key is an
aggregation name. Required.
:_raise_on_empty: Boolean indicating whether to raise exception
when IndexNotFoundExcep... |
def bulk_index_relations(cls, items, request=None, **kwargs):
""" Index objects related to :items: in bulk.
Related items are first grouped in map
{model_name: {item1, item2, ...}} and then indexed.
:param items: Sequence of DB objects related objects if which
should be ind... |
def get_version(path="src/devpy/__init__.py"):
""" Return the version of by with regex intead of importing it"""
init_content = open(path, "rt").read()
pattern = r"^__version__ = ['\"]([^'\"]*)['\"]"
return re.search(pattern, init_content, re.M).group(1) |
def add_plugin_arguments(self, parser):
"""Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser.
"""
for manager in self.hook_managers.values():
if len(list(manager)) == 0:
... |
def get_enabled_hook_plugins(self, hook, args, **kwargs):
"""Get enabled plugins for specified hook name.
"""
manager = self.hook_managers[hook]
if len(list(manager)) == 0:
return []
return [
plugin for plugin in manager.map(
self._create_... |
def get_driver(self, namespace, parsed_args, **kwargs):
"""Get mutually-exlusive plugin for plugin namespace.
"""
option, dest = self._namespace_to_option(namespace)
dest_prefix = '{0}_'.format(dest)
driver_name = getattr(parsed_args, dest, 'default')
driver_extension = ... |
def get_description(self):
"""
Get transaction description (for logging purposes)
"""
if self.card:
card_description = self.card.get_description()
else:
card_description = 'Cardless'
if card_description:
card_description += ' | '
... |
def set_amount(self, amount):
"""
Set transaction amount
"""
if amount:
try:
self.IsoMessage.FieldData(4, int(amount))
except ValueError:
self.IsoMessage.FieldData(4, 0)
self.rebuild() |
def set_expected_action(self, expected_response_action):
"""
Expected outcome of the transaction ('APPROVED' or 'DECLINED')
"""
if expected_response_action.upper() not in ['APPROVED', 'APPROVE', 'DECLINED', 'DECLINE']:
return False
self.expected_response_action = exp... |
def build_emv_data(self):
"""
TODO:
95 TVR
82 app_int_prof
"""
emv_data = ''
emv_data += self.TLV.build({'82': self._get_app_interchange_profile()})
emv_data += self.TLV.build({'9A': get_date()})
emv_data += self.TLV.build({'95': self.term.g... |
def set_currency(self, currency_id):
"""
Set transaction currency code from given currency id, e.g. set 840 from 'USD'
"""
try:
self.currency = currency_codes[currency_id]
self.IsoMessage.FieldData(49, self.currency)
self.rebuild()
except KeyEr... |
def finalize(self):
"""Output the aggregate block count results."""
for name, count in sorted(self.blocks.items(), key=lambda x: x[1]):
print('{:3} {}'.format(count, name))
print('{:3} total'.format(sum(self.blocks.values()))) |
def analyze(self, scratch, **kwargs):
"""Run and return the results from the BlockCounts plugin."""
file_blocks = Counter()
for script in self.iter_scripts(scratch):
for name, _, _ in self.iter_blocks(script.blocks):
file_blocks[name] += 1
self.blocks.update(f... |
def analyze(self, scratch, **kwargs):
"""Run and return the results form the DeadCode plugin.
The variable_event indicates that the Scratch file contains at least
one instance of a broadcast event based on a variable. When
variable_event is True, dead code scripts reported by this plugi... |
def finalize(self):
"""Output the number of instances that contained dead code."""
if self.total_instances > 1:
print('{} of {} instances contained dead code.'
.format(self.dead_code_instances, self.total_instances)) |
def show_help(name):
"""
Show help and basic usage
"""
print('Usage: python3 {} [OPTIONS]... '.format(name))
print('ISO8583 message client')
print(' -v, --verbose\t\tRun transactions verbosely')
print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default')
print(' -s, --serve... |
def _run_interactive(self):
"""
Run transactions interactively (by asking user which transaction to run)
"""
self.term.connect()
self._show_available_transactions()
while True:
trxn_type = self._user_input('\nEnter transaction to send: ')
... |
def find_top_level_directory(start_directory):
"""Finds the top-level directory of a project given a start directory
inside the project.
Parameters
----------
start_directory : str
The directory in which test discovery will start.
"""
top_level = start_directory
while os.path.i... |
def discover(self, start, top_level_directory=None, pattern='test*.py'):
"""Do test case discovery.
This is the top-level entry-point for test discovery.
If the ``start`` argument is a drectory, then ``haas`` will
discover all tests in the package contained in that directory.
... |
def discover_by_module(self, module_name, top_level_directory=None,
pattern='test*.py'):
"""Find all tests in a package or module, or load a single test case if
a class or test inside a module was specified.
Parameters
----------
module_name : str
... |
def discover_single_case(self, module, case_attributes):
"""Find and load a single TestCase or TestCase method from a module.
Parameters
----------
module : module
The imported Python module containing the TestCase to be
loaded.
case_attributes : list
... |
def discover_by_directory(self, start_directory, top_level_directory=None,
pattern='test*.py'):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
top... |
def discover_by_file(self, start_filepath, top_level_directory=None):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
top_level_directory : str
The path to the top-level ... |
def _set_options_headers(self, methods):
""" Set proper headers.
Sets following headers:
Allow
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Arguments:
:methods: Sequence of HTTP method names that are value for
request... |
def _get_handled_methods(self, actions_map):
""" Get names of HTTP methods that can be used at requested URI.
Arguments:
:actions_map: Map of actions. Must have the same structure as
self._item_actions and self._collection_actions
"""
methods = ('OPTIONS',)
... |
def item_options(self, **kwargs):
""" Handle collection OPTIONS request.
Singular route requests are handled a bit differently because
singular views may handle POST requests despite being registered
as item routes.
"""
actions = self._item_actions.copy()
if self... |
def collection_options(self, **kwargs):
""" Handle collection item OPTIONS request. """
methods = self._get_handled_methods(self._collection_actions)
return self._set_options_headers(methods) |
def wrap(self, func):
""" Wrap :func: to perform aggregation on :func: call.
Should be called with view instance methods.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
try:
return self.aggregate()
except KeyError:
retu... |
def pop_aggregations_params(self):
""" Pop and return aggregation params from query string params.
Aggregation params are expected to be prefixed(nested under) by
any of `self._aggregations_keys`.
"""
from nefertari.view import BaseView
self._query_params = BaseView.conv... |
def get_aggregations_fields(cls, params):
""" Recursively get values under the 'field' key.
Is used to get names of fields on which aggregations should be
performed.
"""
fields = []
for key, val in params.items():
if isinstance(val, dict):
fie... |
def check_aggregations_privacy(self, aggregations_params):
""" Check per-field privacy rules in aggregations.
Privacy is checked by making sure user has access to the fields
used in aggregations.
"""
fields = self.get_aggregations_fields(aggregations_params)
fields_dict ... |
def aggregate(self):
""" Perform aggregation and return response. """
from nefertari.elasticsearch import ES
aggregations_params = self.pop_aggregations_params()
if self.view._auth_enabled:
self.check_aggregations_privacy(aggregations_params)
self.stub_wrappers()
... |
def asdict(self, name, _type=None, _set=False):
"""
Turn this 'a:2,b:blabla,c:True,a:'d' to
{a:[2, 'd'], b:'blabla', c:True}
"""
if _type is None:
_type = lambda t: t
dict_str = self.pop(name, None)
if not dict_str:
return {}
_d... |
def get_random_hex(length):
"""
Return random hex string of a given length
"""
if length <= 0:
return ''
return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length] |
def get_response(_code):
"""
Return xx1x response for xx0x codes (e.g. 0810 for 0800)
"""
if _code:
code = str(_code)
return code[:-2] + str(int(code[-2:-1]) + 1) + code[-1]
else:
return None |
def load_case(self, testcase):
"""Load a TestSuite containing all TestCase instances for all tests in
a TestCase subclass.
Parameters
----------
testcase : type
A subclass of :class:`unittest.TestCase`
"""
tests = [self.load_test(testcase, name)
... |
def load_module(self, module):
"""Create and return a test suite containing all cases loaded from the
provided module.
Parameters
----------
module : module
A module object containing ``TestCases``
"""
cases = self.get_test_cases_from_module(module)
... |
def Field(self, field, Value = None):
'''
Add field to bitmap
'''
if Value == None:
try:
return self.__Bitmap[field]
except KeyError:
return None
elif Value == 1 or Value == 0:
self.__Bitmap[field] = Value
... |
def FieldData(self, field, Value = None):
'''
Add field data
'''
if Value == None:
try:
return self.__FieldData[field]
except KeyError:
return None
else:
if len(str(Value)) > self.__IsoSpec.MaxLength(field):
... |
def authenticated_userid(request):
"""Helper function that can be used in ``db_key`` to support `self`
as a collection key.
"""
user = getattr(request, 'user', None)
key = user.pk_field()
return getattr(user, key) |
def iter_blocks(block_list):
"""A generator for blocks contained in a block list.
Yields tuples containing the block name, the depth that the block was
found at, and finally a handle to the block itself.
"""
# queue the block and the depth of the block
queue = [(block, ... |
def iter_scripts(scratch):
"""A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
"""
for script in scratch.stage.scripts:
if not isinstance(script, kurt.Comment):
yield script
for sprite ... |
def iter_sprite_scripts(scratch):
"""A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
"""
for script in scratch.stage.scripts:
if not isinstance(script, kurt.Comment):
yield ('Stage', script)
... |
def script_start_type(script):
"""Return the type of block the script begins with."""
if script[0].type.text == 'when @greenFlag clicked':
return HairballPlugin.HAT_GREEN_FLAG
elif script[0].type.text == 'when I receive %s':
return HairballPlugin.HAT_WHEN_I_RECEIVE
... |
def get_broadcast_events(cls, script):
"""Return a Counter of event-names that were broadcast.
The Count will contain the key True if any of the broadcast blocks
contain a parameter that is a variable.
"""
events = Counter()
for name, _, block in cls.iter_blocks(script)... |
def tag_reachable_scripts(cls, scratch):
"""Tag each script with attribute reachable.
The reachable attribute will be set false for any script that does not
begin with a hat block. Additionally, any script that begins with a
'when I receive' block whose event-name doesn't appear in a
... |
def description(self):
"""Attribute that returns the plugin description from its docstring."""
lines = []
for line in self.__doc__.split('\n')[2:]:
line = line.strip()
if line:
lines.append(line)
return ' '.join(lines) |
def _process(self, scratch, filename, **kwargs):
"""Internal hook that marks reachable scripts before calling analyze.
Returns data exactly as returned by the analyze method.
"""
self.tag_reachable_scripts(scratch)
return self.analyze(scratch, filename=filename, **kwargs) |
def close(self):
"""
Finalises the compressed version of the spreadsheet. If you aren't using the context manager ('with' statement,
you must call this manually, it is not triggered automatically like on a file object.
:return: Nothing.
"""
self.zipf.writestr("content.xml... |
def writerow(self, cells):
"""
Write a row of cells into the default sheet of the spreadsheet.
:param cells: A list of cells (most basic Python types supported).
:return: Nothing.
"""
if self.default_sheet is None:
self.default_sheet = self.new_sheet()
... |
def new_sheet(self, name=None, cols=None):
"""
Create a new sheet in the spreadsheet and return it so content can be added.
:param name: Optional name for the sheet.
:param cols: Specify the number of columns, needed for compatibility in some cases
:return: Sheet object
"... |
def _format_kwargs(func):
"""Decorator to handle formatting kwargs to the proper names expected by
the associated function. The formats dictionary string keys will be used as
expected function kwargs and the value list of strings will be renamed to
the associated key string."""
formats = {}
form... |
def show_limit(entries, **kwargs):
"""Shows a menu but limits the number of entries shown at a time.
Functionally equivalent to `show_menu()` with the `limit` parameter set."""
limit = kwargs.pop('limit', 5)
if limit <= 0:
return show_menu(entries, **kwargs)
istart = 0 # Index of group start... |
def show_menu(entries, **kwargs):
"""Shows a menu with the given list of `MenuEntry` items.
**Params**:
- header (str) - String to show above menu.
- note (str) - String to show as a note below menu.
- msg (str) - String to show below menu.
- dft (str) - Default value if input is left b... |
def run_func(entry):
"""Runs the function associated with the given MenuEntry."""
if entry.func:
if entry.args and entry.krgs:
return entry.func(*entry.args, **entry.krgs)
if entry.args:
return entry.func(*entry.args)
if entry.krgs:
return entry.func(*... |
def enum_menu(strs, menu=None, *args, **kwargs):
"""Enumerates the given list of strings into returned menu.
**Params**:
- menu (Menu) - Existing menu to append. If not provided, a new menu will
be created.
"""
if not menu:
menu = Menu(*args, **kwargs)
for s in strs:
m... |
def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True):
"""Prompts the user for input and returns the given answer. Optionally
checks if answer is valid.
**Params**:
- msg (str) - Message to prompt the user with.
- fmt (func) - Function used to format... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.