_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q275000 | S3Pipeline._make_fileobj | test | def _make_fileobj(self):
"""
Build file object from items.
"""
bio = BytesIO()
f = gzip.GzipFile(mode='wb', fileobj=bio) if self.use_gzip else bio
# Build file object using ItemExporter
exporter = JsonLinesItemExporter(f)
exporter.start_exporting()
for item in self.items:
exporter.export_item(item)
exporter.finish_exporting()
if f is not bio:
f.close() # Close the file if GzipFile
# Seek to the top of file to be read later
bio.seek(0)
return bio | python | {
"resource": ""
} |
q275001 | Client.get_account_state | test | def get_account_state(self, address, **kwargs):
""" Returns the account state information associated with a specific address.
:param address: a 34-bit length address (eg. AJBENSwajTzQtwyJFkiJSv7MAaaMc7DsRz)
:type address: str
:return: dictionary containing the account state information
:rtype: dict
"""
return self._call(JSONRPCMethods.GET_ACCOUNT_STATE.value, params=[address, ], **kwargs) | python | {
"resource": ""
} |
q275002 | Client.get_asset_state | test | def get_asset_state(self, asset_id, **kwargs):
""" Returns the asset information associated with a specific asset ID.
:param asset_id:
an asset identifier (the transaction ID of the RegistTransaction when the asset is
registered)
:type asset_id: str
:return: dictionary containing the asset state information
:rtype: dict
"""
return self._call(JSONRPCMethods.GET_ASSET_STATE.value, params=[asset_id, ], **kwargs) | python | {
"resource": ""
} |
q275003 | Client.get_block | test | def get_block(self, block_hash, verbose=True, **kwargs):
""" Returns the block information associated with a specific hash value or block index.
:param block_hash: a block hash value or a block index (block height)
:param verbose:
a boolean indicating whether the detailed block information should be returned in JSON
format (otherwise the block information is returned as an hexadecimal string by the
JSON-RPC endpoint)
:type block_hash: str or int
:type verbose: bool
:return:
dictionary containing the block information (or an hexadecimal string if verbose is set
to False)
:rtype: dict or str
"""
return self._call(
JSONRPCMethods.GET_BLOCK.value, params=[block_hash, int(verbose), ], **kwargs) | python | {
"resource": ""
} |
q275004 | Client.get_block_hash | test | def get_block_hash(self, block_index, **kwargs):
""" Returns the hash value associated with a specific block index.
:param block_index: a block index (block height)
:type block_index: int
:return: hash of the block associated with the considered index
:rtype: str
"""
return self._call(JSONRPCMethods.GET_BLOCK_HASH.value, [block_index, ], **kwargs) | python | {
"resource": ""
} |
q275005 | Client.get_block_sys_fee | test | def get_block_sys_fee(self, block_index, **kwargs):
""" Returns the system fees associated with a specific block index.
:param block_index: a block index (block height)
:type block_index: int
:return: system fees of the block, expressed in NeoGas units
:rtype: str
"""
return self._call(JSONRPCMethods.GET_BLOCK_SYS_FEE.value, [block_index, ], **kwargs) | python | {
"resource": ""
} |
q275006 | Client.get_contract_state | test | def get_contract_state(self, script_hash, **kwargs):
""" Returns the contract information associated with a specific script hash.
:param script_hash: contract script hash
:type script_hash: str
:return: dictionary containing the contract information
:rtype: dict
"""
return self._call(JSONRPCMethods.GET_CONTRACT_STATE.value, [script_hash, ], **kwargs) | python | {
"resource": ""
} |
q275007 | Client.get_raw_transaction | test | def get_raw_transaction(self, tx_hash, verbose=True, **kwargs):
""" Returns detailed information associated with a specific transaction hash.
:param tx_hash: transaction hash
:param verbose:
a boolean indicating whether the detailed transaction information should be returned in
JSON format (otherwise the transaction information is returned as an hexadecimal string
by the JSON-RPC endpoint)
:type tx_hash: str
:type verbose: bool
:return:
dictionary containing the transaction information (or an hexadecimal string if verbose
is set to False)
:rtype: dict or str
"""
return self._call(
JSONRPCMethods.GET_RAW_TRANSACTION.value, params=[tx_hash, int(verbose), ], **kwargs) | python | {
"resource": ""
} |
q275008 | Client.get_storage | test | def get_storage(self, script_hash, key, **kwargs):
""" Returns the value stored in the storage of a contract script hash for a given key.
:param script_hash: contract script hash
:param key: key to look up in the storage
:type script_hash: str
:type key: str
:return: value associated with the storage key
:rtype: bytearray
"""
hexkey = binascii.hexlify(key.encode('utf-8')).decode('utf-8')
hexresult = self._call(
JSONRPCMethods.GET_STORAGE.value, params=[script_hash, hexkey, ], **kwargs)
try:
assert hexresult
result = bytearray(binascii.unhexlify(hexresult.encode('utf-8')))
except AssertionError:
result = hexresult
return result | python | {
"resource": ""
} |
q275009 | Client.get_tx_out | test | def get_tx_out(self, tx_hash, index, **kwargs):
""" Returns the transaction output information corresponding to a hash and index.
:param tx_hash: transaction hash
:param index:
index of the transaction output to be obtained in the transaction (starts from 0)
:type tx_hash: str
:type index: int
:return: dictionary containing the transaction output
:rtype: dict
"""
return self._call(JSONRPCMethods.GET_TX_OUT.value, params=[tx_hash, index, ], **kwargs) | python | {
"resource": ""
} |
q275010 | Client.invoke | test | def invoke(self, script_hash, params, **kwargs):
""" Invokes a contract with given parameters and returns the result.
It should be noted that the name of the function invoked in the contract should be part of
paramaters.
:param script_hash: contract script hash
:param params: list of paramaters to be passed in to the smart contract
:type script_hash: str
:type params: list
:return: result of the invocation
:rtype: dictionary
"""
contract_params = encode_invocation_params(params)
raw_result = self._call(
JSONRPCMethods.INVOKE.value, [script_hash, contract_params, ], **kwargs)
return decode_invocation_result(raw_result) | python | {
"resource": ""
} |
q275011 | Client.invoke_function | test | def invoke_function(self, script_hash, operation, params, **kwargs):
""" Invokes a contract's function with given parameters and returns the result.
:param script_hash: contract script hash
:param operation: name of the operation to invoke
:param params: list of paramaters to be passed in to the smart contract
:type script_hash: str
:type operation: str
:type params: list
:return: result of the invocation
:rtype: dictionary
"""
contract_params = encode_invocation_params(params)
raw_result = self._call(
JSONRPCMethods.INVOKE_FUNCTION.value, [script_hash, operation, contract_params, ],
**kwargs)
return decode_invocation_result(raw_result) | python | {
"resource": ""
} |
q275012 | Client.invoke_script | test | def invoke_script(self, script, **kwargs):
""" Invokes a script on the VM and returns the result.
:param script: script runnable by the VM
:type script: str
:return: result of the invocation
:rtype: dictionary
"""
raw_result = self._call(JSONRPCMethods.INVOKE_SCRIPT.value, [script, ], **kwargs)
return decode_invocation_result(raw_result) | python | {
"resource": ""
} |
q275013 | Client.send_raw_transaction | test | def send_raw_transaction(self, hextx, **kwargs):
""" Broadcasts a transaction over the NEO network and returns the result.
:param hextx: hexadecimal string that has been serialized
:type hextx: str
:return: result of the transaction
:rtype: bool
"""
return self._call(JSONRPCMethods.SEND_RAW_TRANSACTION.value, [hextx, ], **kwargs) | python | {
"resource": ""
} |
q275014 | Client.validate_address | test | def validate_address(self, addr, **kwargs):
""" Validates if the considered string is a valid NEO address.
:param hex: string containing a potential NEO address
:type hex: str
:return: dictionary containing the result of the verification
:rtype: dictionary
"""
return self._call(JSONRPCMethods.VALIDATE_ADDRESS.value, [addr, ], **kwargs) | python | {
"resource": ""
} |
q275015 | Client._call | test | def _call(self, method, params=None, request_id=None):
""" Calls the JSON-RPC endpoint. """
params = params or []
# Determines which 'id' value to use and increment the counter associated with the current
# client instance if applicable.
rid = request_id or self._id_counter
if request_id is None:
self._id_counter += 1
# Prepares the payload and the headers that will be used to forge the request.
payload = {'jsonrpc': '2.0', 'method': method, 'params': params, 'id': rid}
headers = {'Content-Type': 'application/json'}
scheme = 'https' if self.tls else 'http'
url = '{}://{}:{}'.format(scheme, self.host, self.port)
# Calls the JSON-RPC endpoint!
try:
response = self.session.post(url, headers=headers, data=json.dumps(payload))
response.raise_for_status()
except HTTPError:
raise TransportError(
'Got unsuccessful response from server (status code: {})'.format(
response.status_code),
response=response)
# Ensures the response body can be deserialized to JSON.
try:
response_data = response.json()
except ValueError as e:
raise ProtocolError(
'Unable to deserialize response body: {}'.format(e), response=response)
# Properly handles potential errors.
if response_data.get('error'):
code = response_data['error'].get('code', '')
message = response_data['error'].get('message', '')
raise ProtocolError(
'Error[{}] {}'.format(code, message), response=response, data=response_data)
elif 'result' not in response_data:
raise ProtocolError(
'Response is empty (result field is missing)', response=response,
data=response_data)
return response_data['result'] | python | {
"resource": ""
} |
q275016 | is_hash256 | test | def is_hash256(s):
""" Returns True if the considered string is a valid SHA256 hash. """
if not s or not isinstance(s, str):
return False
return re.match('^[0-9A-F]{64}$', s.strip(), re.IGNORECASE) | python | {
"resource": ""
} |
q275017 | is_hash160 | test | def is_hash160(s):
""" Returns True if the considered string is a valid RIPEMD160 hash. """
if not s or not isinstance(s, str):
return False
if not len(s) == 40:
return False
for c in s:
if (c < '0' or c > '9') and (c < 'A' or c > 'F') and (c < 'a' or c > 'f'):
return False
return True | python | {
"resource": ""
} |
q275018 | encode_invocation_params | test | def encode_invocation_params(params):
""" Returns a list of paramaters meant to be passed to JSON-RPC endpoints. """
final_params = []
for p in params:
if isinstance(p, bool):
final_params.append({'type': ContractParameterTypes.BOOLEAN.value, 'value': p})
elif isinstance(p, int):
final_params.append({'type': ContractParameterTypes.INTEGER.value, 'value': p})
elif is_hash256(p):
final_params.append({'type': ContractParameterTypes.HASH256.value, 'value': p})
elif is_hash160(p):
final_params.append({'type': ContractParameterTypes.HASH160.value, 'value': p})
elif isinstance(p, bytearray):
final_params.append({'type': ContractParameterTypes.BYTE_ARRAY.value, 'value': p})
elif isinstance(p, str):
final_params.append({'type': ContractParameterTypes.STRING.value, 'value': p})
elif isinstance(p, list):
innerp = encode_invocation_params(p)
final_params.append({'type': ContractParameterTypes.ARRAY.value, 'value': innerp})
return final_params | python | {
"resource": ""
} |
q275019 | decode_invocation_result | test | def decode_invocation_result(result):
""" Tries to decode the values embedded in an invocation result dictionary. """
if 'stack' not in result:
return result
result = copy.deepcopy(result)
result['stack'] = _decode_invocation_result_stack(result['stack'])
return result | python | {
"resource": ""
} |
q275020 | first_kwonly_arg | test | def first_kwonly_arg(name):
""" Emulates keyword-only arguments under python2. Works with both python2 and python3.
With this decorator you can convert all or some of the default arguments of your function
into kwonly arguments. Use ``KWONLY_REQUIRED`` as the default value of required kwonly args.
:param name: The name of the first default argument to be treated as a keyword-only argument. This default
argument along with all default arguments that follow this one will be treated as keyword only arguments.
You can also pass here the ``FIRST_DEFAULT_ARG`` constant in order to select the first default argument. This
way you turn all default arguments into keyword-only arguments. As a shortcut you can use the
``@kwonly_defaults`` decorator (without any parameters) instead of ``@first_kwonly_arg(FIRST_DEFAULT_ARG)``.
>>> from kwonly_args import first_kwonly_arg, KWONLY_REQUIRED, FIRST_DEFAULT_ARG, kwonly_defaults
>>>
>>> # this decoration converts the ``d1`` and ``d2`` default args into kwonly args
>>> @first_kwonly_arg('d1')
>>> def func(a0, a1, d0='d0', d1='d1', d2='d2', *args, **kwargs):
>>> print(a0, a1, d0, d1, d2, args, kwargs)
>>>
>>> func(0, 1, 2, 3, 4)
0 1 2 d1 d2 (3, 4) {}
>>>
>>> func(0, 1, 2, 3, 4, d2='my_param')
0 1 2 d1 my_param (3, 4) {}
>>>
>>> # d0 is an optional deyword argument, d1 is required
>>> def func(d0='d0', d1=KWONLY_REQUIRED):
>>> print(d0, d1)
>>>
>>> # The ``FIRST_DEFAULT_ARG`` constant automatically selects the first default argument so it
>>> # turns all default arguments into keyword-only ones. Both d0 and d1 are keyword-only arguments.
>>> @first_kwonly_arg(FIRST_DEFAULT_ARG)
>>> def func(a0, a1, d0='d0', d1='d1'):
>>> print(a0, a1, d0, d1)
>>>
>>> # ``@kwonly_defaults`` is a shortcut for the ``@first_kwonly_arg(FIRST_DEFAULT_ARG)``
>>> # in the previous example. This example has the same effect as the previous one.
>>> @kwonly_defaults
>>> def func(a0, a1, d0='d0', d1='d1'):
>>> print(a0, a1, d0, d1)
"""
def decorate(wrapped):
if sys.version_info[0] == 2:
arg_names, varargs, _, defaults = inspect.getargspec(wrapped)
else:
arg_names, varargs, _, defaults = inspect.getfullargspec(wrapped)[:4]
if not defaults:
raise TypeError("You can't use @first_kwonly_arg on a function that doesn't have default arguments!")
first_default_index = len(arg_names) - len(defaults)
if name is FIRST_DEFAULT_ARG:
first_kwonly_index = first_default_index
else:
try:
first_kwonly_index = arg_names.index(name)
except ValueError:
raise ValueError("%s() doesn't have an argument with the specified first_kwonly_arg=%r name" % (
getattr(wrapped, '__name__', '?'), name))
if first_kwonly_index < first_default_index:
raise ValueError("The specified first_kwonly_arg=%r must have a default value!" % (name,))
kwonly_defaults = defaults[-(len(arg_names)-first_kwonly_index):]
kwonly_args = tuple(zip(arg_names[first_kwonly_index:], kwonly_defaults))
required_kwonly_args = frozenset(arg for arg, default in kwonly_args if default is KWONLY_REQUIRED)
def wrapper(*args, **kwargs):
if required_kwonly_args:
missing_kwonly_args = required_kwonly_args.difference(kwargs.keys())
if missing_kwonly_args:
raise TypeError("%s() missing %s keyword-only argument(s): %s" % (
getattr(wrapped, '__name__', '?'), len(missing_kwonly_args),
', '.join(sorted(missing_kwonly_args))))
if len(args) > first_kwonly_index:
if varargs is None:
raise TypeError("%s() takes exactly %s arguments (%s given)" % (
getattr(wrapped, '__name__', '?'), first_kwonly_index, len(args)))
kwonly_args_from_kwargs = tuple(kwargs.pop(arg, default) for arg, default in kwonly_args)
args = args[:first_kwonly_index] + kwonly_args_from_kwargs + args[first_kwonly_index:]
return wrapped(*args, **kwargs)
return update_wrapper(wrapper, wrapped)
return decorate | python | {
"resource": ""
} |
q275021 | snap_tz | test | def snap_tz(dttm, instruction, timezone):
"""This function handles timezone aware datetimes.
Sometimes it is necessary to keep daylight saving time switches in mind.
Args:
instruction (string): a string that encodes 0 to n transformations of a time, i.e. "-1h@h", "@mon+2d+4h", ...
dttm (datetime): a datetime with timezone
timezone: a pytz timezone
Returns:
datetime: The datetime resulting from applying all transformations to the input datetime.
Example:
>>> import pytz
>>> CET = pytz.timezone("Europe/Berlin")
>>> dttm = CET.localize(datetime(2017, 3, 26, 3, 44)
>>> dttm
datetime.datetime(2017, 3, 26, 3, 44, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
>>> snap_tz(dttm, "-2h@h", CET)
datetime.datetime(2017, 3, 26, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
>>> # switch from winter to summer time!
"""
transformations = parse(instruction)
return reduce(lambda dt, transformation: transformation.apply_to_with_tz(dt, timezone), transformations, dttm) | python | {
"resource": ""
} |
q275022 | SnapTransformation.apply_to_with_tz | test | def apply_to_with_tz(self, dttm, timezone):
"""We make sure that after truncating we use the correct timezone,
even if we 'jump' over a daylight saving time switch.
I.e. if we apply "@d" to `Sun Oct 30 04:30:00 CET 2016` (1477798200)
we want to have `Sun Oct 30 00:00:00 CEST 2016` (1477778400)
but not `Sun Oct 30 00:00:00 CET 2016` (1477782000)
"""
result = self.apply_to(dttm)
if self.unit in [DAYS, WEEKS, MONTHS, YEARS]:
naive_dttm = datetime(result.year, result.month, result.day)
result = timezone.localize(naive_dttm)
return result | python | {
"resource": ""
} |
q275023 | Barcode.save | test | def save(self, filename, options=None):
"""Renders the barcode and saves it in `filename`.
:parameters:
filename : String
Filename to save the barcode in (without filename
extension).
options : Dict
The same as in `self.render`.
:returns: The full filename with extension.
:rtype: String
"""
output = self.render(options)
_filename = self.writer.save(filename, output)
return _filename | python | {
"resource": ""
} |
q275024 | Barcode.render | test | def render(self, writer_options=None):
"""Renders the barcode using `self.writer`.
:parameters:
writer_options : Dict
Options for `self.writer`, see writer docs for details.
:returns: Output of the writers render method.
"""
options = Barcode.default_writer_options.copy()
options.update(writer_options or {})
if options['write_text']:
options['text'] = self.get_fullcode()
self.writer.set_options(options)
code = self.build()
raw = Barcode.raw = self.writer.render(code)
return raw | python | {
"resource": ""
} |
q275025 | EuropeanArticleNumber13.calculate_checksum | test | def calculate_checksum(self):
"""Calculates the checksum for EAN13-Code.
:returns: The checksum for `self.ean`.
:rtype: Integer
"""
def sum_(x, y):
return int(x) + int(y)
evensum = reduce(sum_, self.ean[::2])
oddsum = reduce(sum_, self.ean[1::2])
return (10 - ((evensum + oddsum * 3) % 10)) % 10 | python | {
"resource": ""
} |
q275026 | BaseWriter.render | test | def render(self, code):
"""Renders the barcode to whatever the inheriting writer provides,
using the registered callbacks.
:parameters:
code : List
List of strings matching the writer spec
(only contain 0 or 1).
"""
if self._callbacks['initialize'] is not None:
self._callbacks['initialize'](code)
ypos = 1.0
for line in code:
# Left quiet zone is x startposition
xpos = self.quiet_zone
for mod in line:
if mod == '0':
color = self.background
else:
color = self.foreground
self._callbacks['paint_module'](xpos, ypos, self.module_width,
color)
xpos += self.module_width
# Add right quiet zone to every line
self._callbacks['paint_module'](xpos, ypos, self.quiet_zone,
self.background)
ypos += self.module_height
if self.text and self._callbacks['paint_text'] is not None:
ypos += self.text_distance
if self.center_text:
xpos = xpos / 2.0
else:
xpos = self.quiet_zone + 4.0
self._callbacks['paint_text'](xpos, ypos)
return self._callbacks['finish']() | python | {
"resource": ""
} |
q275027 | PerlSession.connect | test | def connect(cls, settings):
""" Call that method in the pyramid configuration phase.
"""
server = serializer('json').loads(settings['kvs.perlsess'])
server.setdefault('key_prefix', 'perlsess::')
server.setdefault('codec', 'storable')
cls.cookie_name = server.pop('cookie_name', 'session_id')
cls.client = KVS(**server) | python | {
"resource": ""
} |
q275028 | main | test | def main(ctx, edit, create):
"""
Simple command line tool to help manage environment variables stored in a S3-like system. Facilitates editing text
files remotely stored, as well as downloading and uploading files.
"""
# configs this module logger to behave properly
# logger messages will go to stderr (check __init__.py/patch.py)
# client output should be generated with click.echo() to go to stdout
try:
click_log.basic_config('s3conf')
logger.debug('Running main entrypoint')
if edit:
if ctx.invoked_subcommand is None:
logger.debug('Using config file %s', config.LOCAL_CONFIG_FILE)
config.ConfigFileResolver(config.LOCAL_CONFIG_FILE).edit(create=create)
return
else:
raise UsageError('Edit should not be called with a subcommand.')
# manually call help in case no relevant settings were defined
if ctx.invoked_subcommand is None:
click.echo(main.get_help(ctx))
except exceptions.FileDoesNotExist as e:
raise UsageError('The file {} does not exist. Try "-c" option if you want to create it.'.format(str(e))) | python | {
"resource": ""
} |
q275029 | download | test | def download(remote_path, local_path):
"""
Download a file or folder from the S3-like service.
If REMOTE_PATH has a trailing slash it is considered to be a folder, e.g.: "s3://my-bucket/my-folder/". In this
case, LOCAL_PATH must be a folder as well. The files and subfolder structure in REMOTE_PATH are copied to
LOCAL_PATH.
If REMOTE_PATH does not have a trailing slash, it is considered to be a file, and LOCAL_PATH should be a file as
well.
"""
storage = STORAGES['s3']()
conf = s3conf.S3Conf(storage=storage)
conf.download(remote_path, local_path) | python | {
"resource": ""
} |
q275030 | upload | test | def upload(remote_path, local_path):
"""
Upload a file or folder to the S3-like service.
If LOCAL_PATH is a folder, the files and subfolder structure in LOCAL_PATH are copied to REMOTE_PATH.
If LOCAL_PATH is a file, the REMOTE_PATH file is created with the same contents.
"""
storage = STORAGES['s3']()
conf = s3conf.S3Conf(storage=storage)
conf.upload(local_path, remote_path) | python | {
"resource": ""
} |
q275031 | downsync | test | def downsync(section, map_files):
"""
For each section defined in the local config file, creates a folder inside the local config folder
named after the section. Downloads the environemnt file defined by the S3CONF variable for this section
to this folder.
"""
try:
settings = config.Settings(section=section)
storage = STORAGES['s3'](settings=settings)
conf = s3conf.S3Conf(storage=storage, settings=settings)
local_root = os.path.join(config.LOCAL_CONFIG_FOLDER, section)
conf.downsync(local_root, map_files=map_files)
except exceptions.EnvfilePathNotDefinedError:
raise exceptions.EnvfilePathNotDefinedUsageError() | python | {
"resource": ""
} |
q275032 | diff | test | def diff(section):
"""
For each section defined in the local config file, look up for a folder inside the local config folder
named after the section. Uploads the environemnt file named as in the S3CONF variable for this section
to the remote S3CONF path.
"""
try:
settings = config.Settings(section=section)
storage = STORAGES['s3'](settings=settings)
conf = s3conf.S3Conf(storage=storage, settings=settings)
local_root = os.path.join(config.LOCAL_CONFIG_FOLDER, section)
click.echo(''.join(conf.diff(local_root)))
except exceptions.EnvfilePathNotDefinedError:
raise exceptions.EnvfilePathNotDefinedUsageError() | python | {
"resource": ""
} |
q275033 | parse_env_var | test | def parse_env_var(value):
"""
Split a env var text like
ENV_VAR_NAME=env_var_value
into a tuple ('ENV_VAR_NAME', 'env_var_value')
"""
k, _, v = value.partition('=')
# Remove any leading and trailing spaces in key, value
k, v = k.strip(), v.strip().encode('unicode-escape').decode('ascii')
if v and v[0] == v[-1] in ['"', "'"]:
v = __escape_decoder(v[1:-1])[0]
return k, v | python | {
"resource": ""
} |
q275034 | basic | test | def basic(username, password):
"""Add basic authentication to the requests of the clients."""
none()
_config.username = username
_config.password = password | python | {
"resource": ""
} |
q275035 | api_key | test | def api_key(api_key):
"""Authenticate via an api key."""
none()
_config.api_key_prefix["Authorization"] = "api-key"
_config.api_key["Authorization"] = "key=" + b64encode(api_key.encode()).decode() | python | {
"resource": ""
} |
q275036 | _get_json_content_from_folder | test | def _get_json_content_from_folder(folder):
"""yield objects from json files in the folder and subfolders."""
for dirpath, dirnames, filenames in os.walk(folder):
for filename in filenames:
if filename.lower().endswith(".json"):
filepath = os.path.join(dirpath, filename)
with open(filepath, "rb") as file:
yield json.loads(file.read().decode("UTF-8")) | python | {
"resource": ""
} |
q275037 | get_schemas | test | def get_schemas():
"""Return a dict of schema names mapping to a Schema.
The schema is of type schul_cloud_resources_api_v1.schema.Schema
"""
schemas = {}
for name in os.listdir(JSON_PATH):
if name not in NO_SCHEMA:
schemas[name] = Schema(name)
return schemas | python | {
"resource": ""
} |
q275038 | Schema.get_schema | test | def get_schema(self):
"""Return the schema."""
path = os.path.join(self._get_schema_folder(), self._name + ".json")
with open(path, "rb") as file:
schema = json.loads(file.read().decode("UTF-8"))
return schema | python | {
"resource": ""
} |
q275039 | Schema.get_resolver | test | def get_resolver(self):
"""Return a jsonschema.RefResolver for the schemas.
All schemas returned be get_schemas() are resolved locally.
"""
store = {}
for schema in get_schemas().values():
store[schema.get_uri()] = schema.get_schema()
schema = self.get_schema()
return jsonschema.RefResolver.from_schema(schema, store=store) | python | {
"resource": ""
} |
q275040 | Schema.validate | test | def validate(self, object):
"""Validate an object against the schema.
This function just passes if the schema matches the object.
If the object does not match the schema, a ValidationException is raised.
This error allows debugging.
"""
resolver=self.get_resolver()
jsonschema.validate(object, self.get_schema(), resolver=resolver) | python | {
"resource": ""
} |
q275041 | Schema.get_valid_examples | test | def get_valid_examples(self):
"""Return a list of valid examples for the given schema."""
path = os.path.join(self._get_schema_folder(), "examples", "valid")
return list(_get_json_content_from_folder(path)) | python | {
"resource": ""
} |
q275042 | Schema.get_invalid_examples | test | def get_invalid_examples(self):
"""Return a list of examples which violate the schema."""
path = os.path.join(self._get_schema_folder(), "examples", "invalid")
return list(_get_json_content_from_folder(path)) | python | {
"resource": ""
} |
q275043 | OneDriveAuth.auth_user_get_url | test | def auth_user_get_url(self, scope=None):
'Build authorization URL for User Agent.'
if not self.client_id: raise AuthMissingError('No client_id specified')
return '{}?{}'.format(self.auth_url_user, urllib.urlencode(dict(
client_id=self.client_id, scope=' '.join(scope or self.auth_scope),
response_type='code', redirect_uri=self.auth_redirect_uri ))) | python | {
"resource": ""
} |
q275044 | OneDriveAuth.auth_user_process_url | test | def auth_user_process_url(self, url):
'Process tokens and errors from redirect_uri.'
url = urlparse.urlparse(url)
url_qs = dict(it.chain.from_iterable(
urlparse.parse_qsl(v) for v in [url.query, url.fragment] ))
if url_qs.get('error'):
raise APIAuthError(
'{} :: {}'.format(url_qs['error'], url_qs.get('error_description')) )
self.auth_code = url_qs['code']
return self.auth_code | python | {
"resource": ""
} |
q275045 | OneDriveAuth.auth_get_token | test | def auth_get_token(self, check_scope=True):
'Refresh or acquire access_token.'
res = self.auth_access_data_raw = self._auth_token_request()
return self._auth_token_process(res, check_scope=check_scope) | python | {
"resource": ""
} |
q275046 | OneDriveAPIWrapper.get_user_id | test | def get_user_id(self):
'Returns "id" of a OneDrive user.'
if self._user_id is None:
self._user_id = self.get_user_data()['id']
return self._user_id | python | {
"resource": ""
} |
q275047 | OneDriveAPIWrapper.listdir | test | def listdir(self, folder_id='me/skydrive', limit=None, offset=None):
'Get OneDrive object representing list of objects in a folder.'
return self(self._api_url_join(folder_id, 'files'), dict(limit=limit, offset=offset)) | python | {
"resource": ""
} |
q275048 | OneDriveAPIWrapper.mkdir | test | def mkdir(self, name=None, folder_id='me/skydrive', metadata=dict()):
'''Create a folder with a specified "name" attribute.
folder_id allows to specify a parent folder.
metadata mapping may contain additional folder properties to pass to an API.'''
metadata = metadata.copy()
if name: metadata['name'] = name
return self(folder_id, data=metadata, method='post', auth_header=True) | python | {
"resource": ""
} |
q275049 | OneDriveAPIWrapper.comment_add | test | def comment_add(self, obj_id, message):
'Add comment message to a specified object.'
return self( self._api_url_join(obj_id, 'comments'),
method='post', data=dict(message=message), auth_header=True ) | python | {
"resource": ""
} |
q275050 | decode_obj | test | def decode_obj(obj, force=False):
'Convert or dump object to unicode.'
if isinstance(obj, unicode): return obj
elif isinstance(obj, bytes):
if force_encoding is not None: return obj.decode(force_encoding)
if chardet:
enc_guess = chardet.detect(obj)
if enc_guess['confidence'] > 0.7:
return obj.decode(enc_guess['encoding'])
return obj.decode('utf-8')
else:
return obj if not force else repr(obj) | python | {
"resource": ""
} |
q275051 | set_drop_target | test | def set_drop_target(obj, root, designer, inspector):
"Recursively create and set the drop target for obj and childs"
if obj._meta.container:
dt = ToolBoxDropTarget(obj, root, designer=designer,
inspector=inspector)
obj.drop_target = dt
for child in obj:
set_drop_target(child, root, designer, inspector) | python | {
"resource": ""
} |
q275052 | ToolBox.start_drag_opperation | test | def start_drag_opperation(self, evt):
"Event handler for drag&drop functionality"
# get the control
ctrl = self.menu_ctrl_map[evt.GetToolId()]
# create our own data format and use it in a custom data object
ldata = wx.CustomDataObject("gui")
ldata.SetData(ctrl._meta.name) # only strings are allowed!
# Also create a Bitmap version of the drawing
bmp = ctrl._image.GetBitmap()
# Now make a data object for the bitmap and also a composite
# data object holding both of the others.
bdata = wx.BitmapDataObject(bmp)
data = wx.DataObjectComposite()
data.Add(ldata)
data.Add(bdata)
# And finally, create the drop source and begin the drag
# and drop opperation
dropSource = wx.DropSource(self)
dropSource.SetData(data)
if DEBUG: print("Begining DragDrop\n")
result = dropSource.DoDragDrop(wx.Drag_AllowMove)
if DEBUG: print("DragDrop completed: %d\n" % result)
if result == wx.DragMove:
if DEBUG: print "dragmove!"
self.Refresh() | python | {
"resource": ""
} |
q275053 | ToolBox.set_default_tlw | test | def set_default_tlw(self, tlw, designer, inspector):
"track default top level window for toolbox menu default action"
self.designer = designer
self.inspector = inspector | python | {
"resource": ""
} |
q275054 | inspect | test | def inspect(obj):
"Open the inspector windows for a given object"
from gui.tools.inspector import InspectorTool
inspector = InspectorTool()
inspector.show(obj)
return inspector | python | {
"resource": ""
} |
q275055 | shell | test | def shell():
"Open a shell"
from gui.tools.debug import Shell
shell = Shell()
shell.show()
return shell | python | {
"resource": ""
} |
q275056 | migrate_font | test | def migrate_font(font):
"Convert PythonCard font description to gui2py style"
if 'faceName' in font:
font['face'] = font.pop('faceName')
if 'family' in font and font['family'] == 'sansSerif':
font['family'] = 'sans serif'
return font | python | {
"resource": ""
} |
q275057 | HtmlBox.load_page | test | def load_page(self, location):
"Loads HTML page from location and then displays it"
if not location:
self.wx_obj.SetPage("")
else:
self.wx_obj.LoadPage(location) | python | {
"resource": ""
} |
q275058 | GetParam | test | def GetParam(tag, param, default=__SENTINEL):
""" Convenience function for accessing tag parameters"""
if tag.HasParam(param):
return tag.GetParam(param)
else:
if default == __SENTINEL:
raise KeyError
else:
return default | python | {
"resource": ""
} |
q275059 | send | test | def send(evt):
"Process an outgoing communication"
# get the text written by the user (input textbox control)
msg = ctrl_input.value
# send the message (replace with socket/queue/etc.)
gui.alert(msg, "Message")
# record the message (update the UI)
log(msg)
ctrl_input.value = ""
ctrl_input.set_focus() | python | {
"resource": ""
} |
q275060 | wellcome_tip | test | def wellcome_tip(wx_obj):
"Show a tip message"
msg = ("Close the main window to exit & save.\n"
"Drag & Drop / Click the controls from the ToolBox to create new ones.\n"
"Left click on the created controls to select them.\n"
"Double click to edit the default property.\n"
"Right click to pop-up the context menu.\n")
# create a super tool tip manager and set some styles
stt = STT.SuperToolTip(msg)
stt.SetHeader("Welcome to gui2py designer!")
stt.SetDrawHeaderLine(True)
stt.ApplyStyle("Office 2007 Blue")
stt.SetDropShadow(True)
stt.SetHeaderBitmap(images.designer.GetBitmap())
stt.SetEndDelay(15000) # hide in 15 s
# create a independent tip window, show/hide manually (avoid binding wx_obj)
tip = CustomToolTipWindow(wx_obj, stt)
tip.CalculateBestSize()
tip.CalculateBestPosition(wx_obj)
tip.DropShadow(stt.GetDropShadow())
if stt.GetUseFade():
show = lambda: tip.StartAlpha(True)
else:
show = lambda: tip.Show()
wx.CallLater(1000, show) # show the tip in 1 s
wx.CallLater(30000, tip.Destroy) | python | {
"resource": ""
} |
q275061 | BasicDesigner.mouse_down | test | def mouse_down(self, evt):
"Get the selected object and store start position"
if DEBUG: print "down!"
if (not evt.ControlDown() and not evt.ShiftDown()) or evt.AltDown():
for obj in self.selection:
# clear marker
if obj.sel_marker:
obj.sel_marker.show(False)
obj.sel_marker.destroy()
obj.sel_marker = None
self.selection = [] # clear previous selection
wx_obj = evt.GetEventObject()
if wx_obj.Parent is None or evt.AltDown():
if not evt.AltDown():
evt.Skip()
# start the rubberband effect (multiple selection using the mouse)
self.current = wx_obj
self.overlay = wx.Overlay()
self.pos = evt.GetPosition()
self.parent.wx_obj.CaptureMouse()
#if self.inspector and hasattr(wx_obj, "obj"):
# self.inspector.inspect(wx_obj.obj) # inspect top level window
#self.dclick = False
else:
# create the selection marker and assign it to the control
obj = wx_obj.obj
self.overlay = None
if DEBUG: print wx_obj
sx, sy = wx_obj.ScreenToClient(wx_obj.GetPositionTuple())
dx, dy = wx_obj.ScreenToClient(wx.GetMousePosition())
self.pos = wx_obj.ScreenToClient(wx.GetMousePosition())
self.start = (sx - dx, sy - dy)
self.current = wx_obj
if DEBUG: print "capture..."
# do not capture on TextCtrl, it will fail (blocking) at least in gtk
# do not capture on wx.Notebook to allow selecting the tabs
if not isinstance(wx_obj, wx.Notebook):
self.parent.wx_obj.CaptureMouse()
self.select(obj, keep_selection=True) | python | {
"resource": ""
} |
q275062 | BasicDesigner.mouse_move | test | def mouse_move(self, evt):
"Move the selected object"
if DEBUG: print "move!"
if self.current and not self.overlay:
wx_obj = self.current
sx, sy = self.start
x, y = wx.GetMousePosition()
# calculate the new position (this will overwrite relative dimensions):
x, y = (x + sx, y + sy)
if evt.ShiftDown(): # snap to grid:
x = x / GRID_SIZE[0] * GRID_SIZE[0]
y = y / GRID_SIZE[1] * GRID_SIZE[1]
# calculate the diff to use in the rest of the selected objects:
ox, oy = wx_obj.obj.pos
dx, dy = (x - ox), (y - oy)
# move all selected objects:
for obj in self.selection:
x, y = obj.pos
x = x + dx
y = y + dy
obj.pos = (wx.Point(x, y))
elif self.overlay:
wx_obj = self.current
pos = evt.GetPosition()
# convert to relative client coordinates of the containter:
if evt.GetEventObject() != wx_obj:
pos = evt.GetEventObject().ClientToScreen(pos) # frame
pos = wx_obj.ScreenToClient(pos) # panel
rect = wx.RectPP(self.pos, pos)
# Draw the rubber-band rectangle using an overlay so it
# will manage keeping the rectangle and the former window
# contents separate.
dc = wx.ClientDC(wx_obj)
odc = wx.DCOverlay(self.overlay, dc)
odc.Clear()
dc.SetPen(wx.Pen("blue", 2))
if 'wxMac' in wx.PlatformInfo:
dc.SetBrush(wx.Brush(wx.Colour(0xC0, 0xC0, 0xC0, 0x80)))
else:
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.DrawRectangleRect(rect)
del odc | python | {
"resource": ""
} |
q275063 | BasicDesigner.do_resize | test | def do_resize(self, evt, wx_obj, (n, w, s, e)):
"Called by SelectionTag"
# calculate the pos (minus the offset, not in a panel like rw!)
pos = wx_obj.ScreenToClient(wx.GetMousePosition())
x, y = pos
if evt.ShiftDown(): # snap to grid:
x = x / GRID_SIZE[0] * GRID_SIZE[0]
y = y / GRID_SIZE[1] * GRID_SIZE[1]
pos = wx.Point(x, y)
if not self.resizing or self.resizing != (wx_obj, (n, w, s, e)):
self.pos = list(pos) # store starting point
self.resizing = (wx_obj, (n, w, s, e)) # track obj and handle
else:
delta = pos - self.pos
if DEBUG: print "RESIZING: n, w, s, e", n, w, s, e
if n or w or s or e:
# resize according the direction (n, w, s, e)
x = wx_obj.Position[0] + e * delta[0]
y = wx_obj.Position[1] + n * delta[1]
if w or e:
if not isinstance(wx_obj, wx.TopLevelWindow):
width = wx_obj.Size[0] + (w - e) * delta[0]
else:
width = wx_obj.ClientSize[0] + (w - e) * delta[0]
else:
width = None
if n or s:
height = wx_obj.Size[1] + (s - n) * delta[1]
else:
height = None
else:
# just move
x = wx_obj.Position[0] + delta[0]
y = wx_obj.Position[1] + delta[1]
width = height = None
new_pos = (x, y)
new_size = (width, height)
if new_size != wx_obj.GetSize() or new_pos != wx_obj.GetPosition():
# reset margins (TODO: avoid resizing recursion)
wx_obj.obj.margin_left = 0
wx_obj.obj.margin_right = 0
wx_obj.obj.margin_top = 0
wx_obj.obj.margin_bottom = 0
wx_obj.obj.pos = new_pos # update gui specs (position)
# update gui specs (size), but do not alter default value
if width is not None and height is not None:
wx_obj.obj.width = width
wx_obj.obj.height = height
elif width is not None:
wx_obj.obj.width = width
elif height is not None:
wx_obj.obj.height = height
# only update on sw for a smooth resize
if w:
self.pos[0] = pos[0] # store new starting point
if s:
self.pos[1] = pos[1] | python | {
"resource": ""
} |
q275064 | BasicDesigner.key_press | test | def key_press(self, event):
"support cursor keys to move components one pixel at a time"
key = event.GetKeyCode()
if key in (wx.WXK_LEFT, wx.WXK_UP, wx.WXK_RIGHT, wx.WXK_DOWN):
for obj in self.selection:
x, y = obj.pos
if event.ShiftDown(): # snap to grid:t
# for now I'm only going to align to grid
# in the direction of the cursor movement
if key == wx.WXK_LEFT:
x = (x - GRID_SIZE[0]) / GRID_SIZE[0] * GRID_SIZE[0]
elif key == wx.WXK_RIGHT:
x = (x + GRID_SIZE[0]) / GRID_SIZE[0] * GRID_SIZE[0]
elif key == wx.WXK_UP:
y = (y - GRID_SIZE[1]) / GRID_SIZE[1] * GRID_SIZE[1]
elif key == wx.WXK_DOWN:
y = (y + GRID_SIZE[1]) / GRID_SIZE[1] * GRID_SIZE[1]
else:
if key == wx.WXK_LEFT:
x = x - 1
elif key == wx.WXK_RIGHT:
x = x + 1
elif key == wx.WXK_UP:
y = y - 1
elif key == wx.WXK_DOWN:
y = y + 1
obj.pos = (x, y)
elif key == wx.WXK_DELETE:
self.delete(event)
elif key == wx.WXK_INSERT:
self.duplicate(event)
else:
if DEBUG: print "KEY:", key | python | {
"resource": ""
} |
q275065 | BasicDesigner.delete | test | def delete(self, event):
"delete all of the selected objects"
# get the selected objects (if any)
for obj in self.selection:
if obj:
if DEBUG: print "deleting", obj.name
obj.destroy()
self.selection = [] # clean selection
self.inspector.load_object() | python | {
"resource": ""
} |
q275066 | BasicDesigner.duplicate | test | def duplicate(self, event):
"create a copy of each selected object"
# duplicate the selected objects (if any)
new_selection = []
for obj in self.selection:
if obj:
if DEBUG: print "duplicating", obj.name
obj.sel_marker.destroy()
obj.sel_marker = None
obj2 = obj.duplicate()
obj2.sel_marker = SelectionMarker(obj2)
obj2.sel_marker.show(True)
new_selection.append(obj2)
self.selection = new_selection # update with new obj's
self.inspector.load_object() | python | {
"resource": ""
} |
q275067 | Facade.refresh | test | def refresh(self):
"Capture the new control superficial image after an update"
self.bmp = self.obj.snapshot()
# change z-order to overlap controls (windows) and show the image:
self.Raise()
self.Show()
self.Refresh() | python | {
"resource": ""
} |
q275068 | CustomToolTipWindow.CalculateBestPosition | test | def CalculateBestPosition(self,widget):
"When dealing with a Top-Level window position it absolute lower-right"
if isinstance(widget, wx.Frame):
screen = wx.ClientDisplayRect()[2:]
left,top = widget.ClientToScreenXY(0,0)
right,bottom = widget.ClientToScreenXY(*widget.GetClientRect()[2:])
size = self.GetSize()
xpos = right
ypos = bottom - size[1]
self.SetPosition((xpos,ypos))
else:
STT.ToolTipWindow.CalculateBestPosition(self, widget) | python | {
"resource": ""
} |
q275069 | wx_ListCtrl.GetPyData | test | def GetPyData(self, item):
"Returns the pyth item data associated with the item"
wx_data = self.GetItemData(item)
py_data = self._py_data_map.get(wx_data)
return py_data | python | {
"resource": ""
} |
q275070 | wx_ListCtrl.SetPyData | test | def SetPyData(self, item, py_data):
"Set the python item data associated wit the wx item"
wx_data = wx.NewId() # create a suitable key
self.SetItemData(item, wx_data) # store it in wx
self._py_data_map[wx_data] = py_data # map it internally
self._wx_data_map[py_data] = wx_data # reverse map
return wx_data | python | {
"resource": ""
} |
q275071 | wx_ListCtrl.FindPyData | test | def FindPyData(self, start, py_data):
"Do a reverse look up for an item containing the requested data"
# first, look at our internal dict:
wx_data = self._wx_data_map[py_data]
# do the real search at the wx control:
if wx.VERSION < (3, 0, 0) or 'classic' in wx.version():
data = self.FindItemData(start, wx_data)
else:
data = self.FindItem(start, wx_data)
return data | python | {
"resource": ""
} |
q275072 | wx_ListCtrl.DeleteItem | test | def DeleteItem(self, item):
"Remove the item from the list and unset the related data"
wx_data = self.GetItemData(item)
py_data = self._py_data_map[wx_data]
del self._py_data_map[wx_data]
del self._wx_data_map[py_data]
wx.ListCtrl.DeleteItem(self, item) | python | {
"resource": ""
} |
q275073 | wx_ListCtrl.DeleteAllItems | test | def DeleteAllItems(self):
"Remove all the item from the list and unset the related data"
self._py_data_map.clear()
self._wx_data_map.clear()
wx.ListCtrl.DeleteAllItems(self) | python | {
"resource": ""
} |
q275074 | ListView.clear_all | test | def clear_all(self):
"Remove all items and column headings"
self.clear()
for ch in reversed(self.columns):
del self[ch.name] | python | {
"resource": ""
} |
q275075 | ItemContainerControl._set_selection | test | def _set_selection(self, index, dummy=False):
"Sets the item at index 'n' to be the selected item."
# only change selection if index is None and not dummy:
if index is None:
self.wx_obj.SetSelection(-1)
# clean up text if control supports it:
if hasattr(self.wx_obj, "SetValue"):
self.wx_obj.SetValue("")
else:
self.wx_obj.SetSelection(index)
# send a programmatically event (not issued by wx)
wx_event = ItemContainerControlSelectEvent(self._commandtype,
index, self.wx_obj)
if hasattr(self, "onchange") and self.onchange:
# TODO: fix (should work but it doesn't):
## wx.PostEvent(self.wx_obj, wx_evt)
# WORKAROUND:
event = FormEvent(name="change", wx_event=wx_event)
self.onchange(event) | python | {
"resource": ""
} |
q275076 | ItemContainerControl._get_string_selection | test | def _get_string_selection(self):
"Returns the label of the selected item or an empty string if none"
if self.multiselect:
return [self.wx_obj.GetString(i) for i in
self.wx_obj.GetSelections()]
else:
return self.wx_obj.GetStringSelection() | python | {
"resource": ""
} |
q275077 | ItemContainerControl.set_data | test | def set_data(self, n, data):
"Associate the given client data with the item at position n."
self.wx_obj.SetClientData(n, data)
# reverse association:
self._items_dict[data] = self.get_string(n) | python | {
"resource": ""
} |
q275078 | ItemContainerControl.append | test | def append(self, a_string, data=None):
"Adds the item to the control, associating the given data if not None."
self.wx_obj.Append(a_string, data)
# reverse association:
self._items_dict[data] = a_string | python | {
"resource": ""
} |
q275079 | represent | test | def represent(obj, prefix, parent="", indent=0, context=False, max_cols=80):
"Construct a string representing the object"
try:
name = getattr(obj, "name", "")
class_name = "%s.%s" % (prefix, obj.__class__.__name__)
padding = len(class_name) + 1 + indent * 4 + (5 if context else 0)
params = []
for (k, spec) in sorted(obj._meta.specs.items(), key=get_sort_key):
if k == "index": # index is really defined by creation order
continue # also, avoid infinite recursion
if k == "parent" and parent != "":
v = parent
else:
v = getattr(obj, k, "")
if (not isinstance(spec, InternalSpec)
and v != spec.default
and (k != 'id' or v > 0)
and isinstance(v,
(basestring, int, long, float, bool, dict, list,
decimal.Decimal,
datetime.datetime, datetime.date, datetime.time,
Font, Color))
and repr(v) != 'None'
):
v = repr(v)
else:
v = None
if v is not None:
params.append("%s=%s" % (k, v))
param_lines = []
line = ""
for param in params:
if len(line + param) + 3 > max_cols - padding:
param_lines.append(line)
line = ""
line += param + ", "
param_lines.append(line)
param_str = ("\n%s" % (" " * padding)).join(param_lines)
return "%s(%s)" % (class_name, param_str)
except:
raise
# uninitialized, use standard representation to not break debuggers
return object.__repr__(obj) | python | {
"resource": ""
} |
q275080 | get | test | def get(obj_name, init=False):
"Find an object already created"
wx_parent = None
# check if new_parent is given as string (useful for designer!)
if isinstance(obj_name, basestring):
# find the object reference in the already created gui2py objects
# TODO: only useful for designer, get a better way
obj_parent = COMPONENTS.get(obj_name)
if not obj_parent:
# try to find window (it can be a plain wx frame/control)
wx_parent = wx.FindWindowByName(obj_name)
if wx_parent:
# store gui object (if any)
obj_parent = getattr(wx_parent, "obj")
else:
# fallback using just object name (backward compatibility)
for obj in COMPONENTS.values():
if obj.name==obj_name:
obj_parent = obj
else:
obj_parent = obj_name # use the provided parent (as is)
return obj_parent or wx_parent | python | {
"resource": ""
} |
q275081 | Component.duplicate | test | def duplicate(self, new_parent=None):
"Create a new object exactly similar to self"
kwargs = {}
for spec_name, spec in self._meta.specs.items():
value = getattr(self, spec_name)
if isinstance(value, Color):
print "COLOR", value, value.default
if value.default:
value = None
if value is not None:
kwargs[spec_name] = value
del kwargs['parent']
new_id = wx.NewId()
kwargs['id'] = new_id
kwargs['name'] = "%s_%s" % (kwargs['name'], new_id)
new_obj = self.__class__(new_parent or self.get_parent(), **kwargs)
# recursively create a copy of each child (in the new parent!)
for child in self:
child.duplicate(new_obj)
return new_obj | python | {
"resource": ""
} |
q275082 | SizerMixin._sizer_add | test | def _sizer_add(self, child):
"called when adding a control to the window"
if self.sizer:
if DEBUG: print "adding to sizer:", child.name
border = None
if not border:
border = child.sizer_border
flags = child._sizer_flags
if child.sizer_align:
flags |= child._sizer_align
if child.sizer_expand:
flags |= wx.EXPAND
if 'grid' in self.sizer:
self._sizer.Add(child.wx_obj, flag=flags, border=border,
pos=(child.sizer_row, child.sizer_col),
span=(child.sizer_rowspan, child.sizer_colspan))
else:
self._sizer.Add(child.wx_obj, 0, flags, border) | python | {
"resource": ""
} |
q275083 | ControlSuper.set_parent | test | def set_parent(self, new_parent, init=False):
"Re-parent a child control with the new wx_obj parent"
Component.set_parent(self, new_parent, init)
# if not called from constructor, we must also reparent in wx:
if not init:
if DEBUG: print "reparenting", ctrl.name
if hasattr(self.wx_obj, "Reparent"):
self.wx_obj.Reparent(self._parent.wx_obj) | python | {
"resource": ""
} |
q275084 | ImageBackgroundMixin.__tile_background | test | def __tile_background(self, dc):
"make several copies of the background bitmap"
sz = self.wx_obj.GetClientSize()
bmp = self._bitmap.get_bits()
w = bmp.GetWidth()
h = bmp.GetHeight()
if isinstance(self, wx.ScrolledWindow):
# adjust for scrolled position
spx, spy = self.wx_obj.GetScrollPixelsPerUnit()
vsx, vsy = self.wx_obj.GetViewStart()
dx, dy = (spx * vsx) % w, (spy * vsy) % h
else:
dx, dy = (w, h)
x = -dx
while x < sz.width:
y = -dy
while y < sz.height:
dc.DrawBitmap(bmp, x, y)
y = y + h
x = x + w | python | {
"resource": ""
} |
q275085 | ImageBackgroundMixin.__on_erase_background | test | def __on_erase_background(self, evt):
"Draw the image as background"
if self._bitmap:
dc = evt.GetDC()
if not dc:
dc = wx.ClientDC(self)
r = self.wx_obj.GetUpdateRegion().GetBox()
dc.SetClippingRegion(r.x, r.y, r.width, r.height)
if self._background_tiling:
self.__tile_background(dc)
else:
dc.DrawBitmapPoint(self._bitmap.get_bits(), (0, 0)) | python | {
"resource": ""
} |
q275086 | Label.__on_paint | test | def __on_paint(self, event):
"Custom draws the label when transparent background is needed"
# use a Device Context that supports anti-aliased drawing
# and semi-transparent colours on all platforms
dc = wx.GCDC(wx.PaintDC(self.wx_obj))
dc.SetFont(self.wx_obj.GetFont())
dc.SetTextForeground(self.wx_obj.GetForegroundColour())
dc.DrawText(self.wx_obj.GetLabel(), 0, 0) | python | {
"resource": ""
} |
q275087 | find_modules | test | def find_modules(rootpath, skip):
"""
Look for every file in the directory tree and return a dict
Hacked from sphinx.autodoc
"""
INITPY = '__init__.py'
rootpath = os.path.normpath(os.path.abspath(rootpath))
if INITPY in os.listdir(rootpath):
root_package = rootpath.split(os.path.sep)[-1]
print "Searching modules in", rootpath
else:
print "No modules in", rootpath
return
def makename(package, module):
"""Join package and module with a dot."""
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
skipall = []
for m in skip.keys():
if skip[m] is None: skipall.append(m)
tree = {}
saved = 0
found = 0
def save(module, submodule):
name = module+ "."+ submodule
for s in skipall:
if name.startswith(s):
print "Skipping "+name
return False
if skip.has_key(module):
if submodule in skip[module]:
print "Skipping "+name
return False
if not tree.has_key(module):
tree[module] = []
tree[module].append(submodule)
return True
for root, subs, files in os.walk(rootpath):
py_files = sorted([f for f in files if os.path.splitext(f)[1] == '.py'])
if INITPY in py_files:
subpackage = root[len(rootpath):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
full = makename(root_package, subpackage)
part = full.rpartition('.')
base_package, submodule = part[0], part[2]
found += 1
if save(base_package, submodule): saved += 1
py_files.remove(INITPY)
for py_file in py_files:
found += 1
module = os.path.splitext(py_file)[0]
if save(full, module): saved += 1
for item in tree.keys():
tree[item].sort()
print "%s contains %i submodules, %i skipped" % \
(root_package, found, found-saved)
return tree | python | {
"resource": ""
} |
q275088 | GridView._get_column_headings | test | def _get_column_headings(self):
"Return a list of children sub-components that are column headings"
# return it in the same order as inserted in the Grid
headers = [ctrl for ctrl in self if isinstance(ctrl, GridColumn)]
return sorted(headers, key=lambda ch: ch.index) | python | {
"resource": ""
} |
q275089 | GridTable.ResetView | test | def ResetView(self, grid):
"Update the grid if rows and columns have been added or deleted"
grid.BeginBatch()
for current, new, delmsg, addmsg in [
(self._rows, self.GetNumberRows(),
gridlib.GRIDTABLE_NOTIFY_ROWS_DELETED,
gridlib.GRIDTABLE_NOTIFY_ROWS_APPENDED),
(self._cols, self.GetNumberCols(),
gridlib.GRIDTABLE_NOTIFY_COLS_DELETED,
gridlib.GRIDTABLE_NOTIFY_COLS_APPENDED),
]:
if new < current:
msg = gridlib.GridTableMessage(self,delmsg,new,current-new)
grid.ProcessTableMessage(msg)
elif new > current:
msg = gridlib.GridTableMessage(self,addmsg,new-current)
grid.ProcessTableMessage(msg)
self.UpdateValues(grid)
grid.EndBatch()
self._rows = self.GetNumberRows()
self._cols = self.GetNumberCols()
# update the column rendering plugins
self._updateColAttrs(grid)
# update the scrollbars and the displayed part of the grid
grid.AdjustScrollbars()
grid.ForceRefresh() | python | {
"resource": ""
} |
q275090 | GridTable.UpdateValues | test | def UpdateValues(self, grid):
"Update all displayed values"
# This sends an event to the grid table to update all of the values
msg = gridlib.GridTableMessage(self,
gridlib.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
grid.ProcessTableMessage(msg) | python | {
"resource": ""
} |
q275091 | GridTable._updateColAttrs | test | def _updateColAttrs(self, grid):
"update the column attributes to add the appropriate renderer"
col = 0
for column in self.columns:
attr = gridlib.GridCellAttr()
if False: # column.readonly
attr.SetReadOnly()
if False: # column.renderer
attr.SetRenderer(renderer)
grid.SetColSize(col, column.width)
grid.SetColAttr(col, attr)
col += 1 | python | {
"resource": ""
} |
q275092 | GridTable.SortColumn | test | def SortColumn(self, col):
"col -> sort the data based on the column indexed by col"
name = self.columns[col].name
_data = []
for row in self.data:
rowname, entry = row
_data.append((entry.get(name, None), row))
_data.sort()
self.data = []
for sortvalue, row in _data:
self.data.append(row) | python | {
"resource": ""
} |
q275093 | GridModel.clear | test | def clear(self):
"Remove all rows and reset internal structures"
## list has no clear ... remove items in reverse order
for i in range(len(self)-1, -1, -1):
del self[i]
self._key = 0
if hasattr(self._grid_view, "wx_obj"):
self._grid_view.wx_obj.ClearGrid() | python | {
"resource": ""
} |
q275094 | ComboCellEditor.Create | test | def Create(self, parent, id, evtHandler):
"Called to create the control, which must derive from wxControl."
self._tc = wx.ComboBox(parent, id, "", (100, 50))
self.SetControl(self._tc)
# pushing a different event handler instead evtHandler:
self._tc.PushEventHandler(wx.EvtHandler())
self._tc.Bind(wx.EVT_COMBOBOX, self.OnChange) | python | {
"resource": ""
} |
q275095 | ComboCellEditor.BeginEdit | test | def BeginEdit(self, row, col, grid):
"Fetch the value from the table and prepare the edit control"
self.startValue = grid.GetTable().GetValue(row, col)
choices = grid.GetTable().columns[col]._choices
self._tc.Clear()
self._tc.AppendItems(choices)
self._tc.SetStringSelection(self.startValue)
self._tc.SetFocus() | python | {
"resource": ""
} |
q275096 | ComboCellEditor.EndEdit | test | def EndEdit(self, row, col, grid, val=None):
"Complete the editing of the current cell. Returns True if changed"
changed = False
val = self._tc.GetStringSelection()
print "val", val, row, col, self.startValue
if val != self.startValue:
changed = True
grid.GetTable().SetValue(row, col, val) # update the table
self.startValue = ''
self._tc.SetStringSelection('')
return changed | python | {
"resource": ""
} |
q275097 | ComboCellEditor.IsAcceptedKey | test | def IsAcceptedKey(self, evt):
"Return True to allow the given key to start editing"
## Oops, there's a bug here, we'll have to do it ourself..
##return self.base_IsAcceptedKey(evt)
return (not (evt.ControlDown() or evt.AltDown()) and
evt.GetKeyCode() != wx.WXK_SHIFT) | python | {
"resource": ""
} |
q275098 | ComboCellEditor.StartingKey | test | def StartingKey(self, evt):
"This will be called to let the editor do something with the first key"
key = evt.GetKeyCode()
ch = None
if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3, wx.WXK_NUMPAD4,
wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]:
ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
elif key < 256 and key >= 0 and chr(key) in string.printable:
ch = chr(key)
if not evt.ShiftDown():
ch = ch.lower()
if ch is not None:
self._tc.SetStringSelection(ch)
else:
evt.Skip() | python | {
"resource": ""
} |
q275099 | TypeHandler | test | def TypeHandler(type_name):
""" A metaclass generator. Returns a metaclass which
will register it's class as the class that handles input type=typeName
"""
def metaclass(name, bases, dict):
klass = type(name, bases, dict)
form.FormTagHandler.register_type(type_name.upper(), klass)
return klass
return metaclass | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.