Search is not available for this dataset
text stringlengths 75 104k |
|---|
def s3_keys_from_s3cfg(opt):
'''Retrieve S3 access key settings from s3cmd's config file, if present; otherwise return None.'''
try:
if opt.s3cfg != None:
s3cfg_path = "%s" % opt.s3cfg
else:
s3cfg_path = "%s/.s3cfg" % os.environ["HOME"]
if not os.path.exists(s3cfg_path):
... |
def init_s3_keys(opt):
'''Initialize s3 access keys from environment variable or s3cfg config file.'''
S3Handler.S3_KEYS = S3Handler.s3_keys_from_cmdline(opt) or S3Handler.s3_keys_from_env() \
or S3Handler.s3_keys_from_s3cfg(opt) |
def connect(self):
'''Connect to S3 storage'''
try:
if S3Handler.S3_KEYS:
self.s3 = BotoClient(self.opt, S3Handler.S3_KEYS[0], S3Handler.S3_KEYS[1])
else:
self.s3 = BotoClient(self.opt)
except Exception as e:
raise RetryFailure('Unable to connect to s3: %s' % e) |
def list_buckets(self):
'''List all buckets'''
result = []
for bucket in self.s3.list_buckets().get('Buckets') or []:
result.append({
'name': S3URL.combine('s3', bucket['Name'], ''),
'is_dir': True,
'size': 0,
'last_modified': bucket['CreationDate']
})
... |
def s3walk(self, basedir, show_dir=None):
'''Walk through a S3 directory. This function initiate a walk with a basedir.
It also supports multiple wildcards.
'''
# Provide the default value from command line if no override.
if not show_dir:
show_dir = self.opt.show_dir
# trailing slash ... |
def local_walk(self, basedir):
'''Walk through local directories from root basedir'''
result = []
for root, dirs, files in os.walk(basedir):
for f in files:
result.append(os.path.join(root, f))
return result |
def get_basename(self, path):
'''Unix style basename.
This fuction will return 'bar' for '/foo/bar/' instead of empty string.
It is used to normalize the input trailing slash.
'''
if path[-1] == PATH_SEP:
path = path[0:-1]
return os.path.basename(path) |
def source_expand(self, source):
'''Expand the wildcards for an S3 path. This emulates the shall expansion
for wildcards if the input is local path.
'''
result = []
if not isinstance(source, list):
source = [source]
for src in source:
# XXX Hacky: We need to disable recursive wh... |
def put_single_file(self, pool, source, target):
'''Upload a single file or a directory by adding a task into queue'''
if os.path.isdir(source):
if self.opt.recursive:
for f in (f for f in self.local_walk(source) if not os.path.isdir(f)):
target_url = S3URL(target)
# deal with ... |
def put_files(self, source, target):
'''Upload files to S3.
This function can handle multiple file upload if source is a list.
Also, it works for recursive mode which copy all files and keep the
directory structure under the given source directory.
'''
pool = ThreadPool(ThreadUtil, self... |
def create_bucket(self, source):
'''Use the create_bucket API to create a new bucket'''
s3url = S3URL(source)
message('Creating %s', source)
if not self.opt.dry_run:
resp = self.s3.create_bucket(Bucket=s3url.bucket)
if resp['ResponseMetadata']["HTTPStatusCode"] == 200:
message('Done... |
def update_privilege(self, obj, target):
'''Get privileges from metadata of the source in s3, and apply them to target'''
if 'privilege' in obj['Metadata']:
os.chmod(target, int(obj['Metadata']['privilege'], 8)) |
def print_files(self, source):
'''Print out a series of files'''
sources = self.source_expand(source)
for source in sources:
s3url = S3URL(source)
response = self.s3.get_object(Bucket=s3url.bucket, Key=s3url.path)
message('%s', response['Body'].read()) |
def get_single_file(self, pool, source, target):
'''Download a single file or a directory by adding a task into queue'''
if source[-1] == PATH_SEP:
if self.opt.recursive:
basepath = S3URL(source).path
for f in (f for f in self.s3walk(source) if not f['is_dir']):
pool.download(f['... |
def get_files(self, source, target):
'''Download files.
This function can handle multiple files if source S3 URL has wildcard
characters. It also handles recursive mode by download all files and
keep the directory structure.
'''
pool = ThreadPool(ThreadUtil, self.opt)
source = self.... |
def delete_removed_files(self, source, target):
'''Remove remote files that are not present in the local source.
(Obsolete) It is used for old sync command now.
'''
message("Deleting files found in %s and not in %s", source, target)
if os.path.isdir(source):
unecessary = []
basepath =... |
def cp_single_file(self, pool, source, target, delete_source):
'''Copy a single file or a directory by adding a task into queue'''
if source[-1] == PATH_SEP:
if self.opt.recursive:
basepath = S3URL(source).path
for f in (f for f in self.s3walk(source) if not f['is_dir']):
pool.co... |
def cp_files(self, source, target, delete_source=False):
'''Copy files
This function can handle multiple files if source S3 URL has wildcard
characters. It also handles recursive mode by copying all files and
keep the directory structure.
'''
pool = ThreadPool(ThreadUtil, self.opt)
... |
def del_files(self, source):
'''Delete files on S3'''
src_files = []
for obj in self.s3walk(source):
if not obj['is_dir']: # ignore directories
src_files.append(obj['name'])
pool = ThreadPool(ThreadUtil, self.opt)
pool.batch_delete(src_files)
pool.join() |
def relative_dir_walk(self, dir):
'''Generic version of directory walk. Return file list without base path
for comparison.
'''
result = []
if S3URL.is_valid(dir):
basepath = S3URL(dir).path
for f in (f for f in self.s3walk(dir) if not f['is_dir']):
result.append(os.path.relpa... |
def dsync_files(self, source, target):
'''Sync directory to directory.'''
src_s3_url = S3URL.is_valid(source)
dst_s3_url = S3URL.is_valid(target)
source_list = self.relative_dir_walk(source)
if len(source_list) == 0 or '.' in source_list:
raise Failure('Sync command need to sync directory to ... |
def sync_files(self, source, target):
'''Sync files to S3. Does implement deletions if syncing TO s3.
Currently identical to get/put -r -f --sync-check with exception of deletions.
'''
src_s3_url = S3URL.is_valid(source)
dst_s3_url = S3URL.is_valid(target)
if src_s3_url and not dst_s3_url:
... |
def size(self, source):
'''Get the size component of the given s3url. If it is a
directory, combine the sizes of all the files under
that directory. Subdirectories will not be counted unless
--recursive option is set.
'''
result = []
for src in self.source_expand(source):
size... |
def file_hash(self, filename, block_size=2**20):
'''Calculate MD5 hash code for a local file'''
m = hashlib.md5()
with open(filename, 'rb') as f:
while True:
data = f.read(block_size)
if not data:
break
m.update(data)
return m.hexdigest() |
def get_md5(self):
'''Get or calculate MD5 value of the local file.'''
if self.md5 is None:
self.md5 = self.file_hash(self.filename)
return self.md5 |
def mkdirs(self, target):
'''Ensure all directories are created for a given target file.'''
path = os.path.dirname(target)
if path and path != PATH_SEP and not os.path.isdir(path):
# Multi-threading means there will be intervleaved execution
# between the check and creation of the directory.
... |
def sync_check(self, md5cache, remoteKey):
'''Check MD5 for a local file and a remote file.
Return True if they have the same md5 hash, otherwise False.
'''
if not remoteKey:
return False
if not os.path.exists(md5cache.filename):
return False
localmd5 = md5cache.get_md5()
# c... |
def partial_match(self, path, filter_path):
'''Partially match a path and a filter_path with wildcards.
This function will return True if this path partially match a filter path.
This is used for walking through directories with multiple level wildcard.
'''
if not path or not filter_path:
... |
def s3walk(self, s3url, s3dir, filter_path, result):
'''Thread worker for s3walk.
Recursively walk into all subdirectories if they still match the filter
path partially.
'''
paginator = self.s3.get_paginator('list_objects')
filter_path_level = filter_path.count(PATH_SEP)
for page in ... |
def conditional(self, result, obj):
'''Check all file item with given conditions.'''
fileonly = (self.opt.last_modified_before is not None) or (self.opt.last_modified_after is not None)
if obj['is_dir']:
if not fileonly:
result.append(obj)
return
if (self.opt.last_modified_before i... |
def get_file_splits(self, id, source, target, fsize, splitsize):
'''Get file splits for upload/download/copy operation.'''
pos = 0
part = 1 # S3 part id starts from 1
mpi = ThreadUtil.MultipartItem(id)
splits = []
while pos < fsize:
chunk = min(splitsize, fsize - pos)
assert(chunk >... |
def get_file_privilege(self, source):
'''Get privileges of a local file'''
try:
return str(oct(os.stat(source).st_mode)[-3:])
except Exception as e:
raise Failure('Could not get stat for %s, error_message = %s', source, e) |
def lookup(self, s3url):
'''Get the s3 object with the S3 URL. Return None if not exist.'''
try:
return self.s3.head_object(Bucket=s3url.bucket, Key=s3url.path)
except BotoClient.ClientError as e:
if e.response['ResponseMetadata']['HTTPStatusCode'] == 404:
return None
else:
... |
def read_file_chunk(self, source, pos, chunk):
'''Read local file chunk'''
if chunk==0:
return StringIO()
data = None
with open(source, 'rb') as f:
f.seek(pos)
data = f.read(chunk)
if not data:
raise Failure('Unable to read data from source: %s' % source)
return StringI... |
def upload(self, source, target, mpi=None, pos=0, chunk=0, part=0):
'''Thread worker for upload operation.'''
s3url = S3URL(target)
obj = self.lookup(s3url)
# Initialization: Set up multithreaded uploads.
if not mpi:
fsize = os.path.getsize(source)
md5cache = LocalMD5Cache(source)
... |
def _verify_file_size(self, obj, downloaded_file):
'''Verify the file size of the downloaded file.'''
file_size = os.path.getsize(downloaded_file)
if int(obj['ContentLength']) != file_size:
raise RetryFailure('Downloaded file size inconsistent: %s' % (repr(obj))) |
def write_file_chunk(self, target, pos, chunk, body):
'''Write local file chunk'''
fd = os.open(target, os.O_CREAT | os.O_WRONLY)
try:
os.lseek(fd, pos, os.SEEK_SET)
data = body.read(chunk)
num_bytes_written = os.write(fd, data)
if(num_bytes_written != len(data)):
raise Retry... |
def download(self, source, target, mpi=None, pos=0, chunk=0, part=0):
'''Thread worker for download operation.'''
s3url = S3URL(source)
obj = self.lookup(s3url)
if obj is None:
raise Failure('The obj "%s" does not exists.' % (s3url.path,))
# Initialization: Set up multithreaded downloads.
... |
def copy(self, source, target, mpi=None, pos=0, chunk=0, part=0, delete_source=False):
'''Copy a single file from source to target using boto S3 library.'''
if self.opt.dry_run:
message('%s => %s' % (source, target))
return
source_url = S3URL(source)
target_url = S3URL(target)
if not ... |
def delete(self, source):
'''Thread worker for download operation.'''
s3url = S3URL(source)
message('Delete %s', source)
if not self.opt.dry_run:
self.s3.delete_object(Bucket=s3url.bucket, Key=s3url.path) |
def batch_delete(self, sources):
'''Delete a list of files in batch of batch_delete_size (default=1000).'''
assert(type(sources) == list)
if len(sources) == 0:
return
elif len(sources) == 1:
self.delete(sources[0])
elif len(sources) > self.opt.batch_delete_size:
for i in range(0, ... |
def run(self, args):
'''Main entry to handle commands. Dispatch to individual command handler.'''
if len(args) == 0:
raise InvalidArgument('No command provided')
cmd = args[0]
if cmd + '_handler' in CommandHandler.__dict__:
CommandHandler.__dict__[cmd + '_handler'](self, args)
else:
... |
def validate(self, format, args):
'''Validate input parameters with given format.
This function also checks for wildcards for recursive mode.
'''
fmtMap = {
'cmd': 'Command',
's3': 's3 path',
'local': 'local path'
}
fmts = format.split('|')
if len(fmts) != len(args):
... |
def pretty_print(self, objlist):
'''Pretty print the result of s3walk. Here we calculate the maximum width
of each column and align them.
'''
def normalize_time(timestamp):
'''Normalize the timestamp format for pretty print.'''
if timestamp is None:
return ' ' * 16
return ... |
def ls_handler(self, args):
'''Handler for ls command'''
if len(args) == 1:
self.pretty_print(self.s3handler().list_buckets())
return
self.validate('cmd|s3', args)
self.pretty_print(self.s3handler().s3walk(args[1])) |
def mb_handler(self, args):
'''Handler for mb command'''
if len(args) == 1:
raise InvalidArgument('No s3 bucketname provided')
self.validate('cmd|s3', args)
self.s3handler().create_bucket(args[1]) |
def put_handler(self, args):
'''Handler for put command'''
# Special check for shell expansion
if len(args) < 3:
raise InvalidArgument('Invalid number of parameters')
self.validate('|'.join(['cmd'] + ['local'] * (len(args) - 2) + ['s3']), args)
source = args[1:-1] # shell expansion
targe... |
def get_handler(self, args):
'''Handler for get command'''
# Special case when we don't have target directory.
if len(args) == 2:
args += ['.']
self.validate('cmd|s3|local', args)
source = args[1]
target = args[2]
self.s3handler().get_files(source, target) |
def cat_handler(self, args):
'''Handler for cat command'''
self.validate('cmd|s3', args)
source = args[1]
self.s3handler().print_files(source) |
def dsync_handler(self, args):
'''Handler for dsync command.'''
self.opt.recursive = True
self.opt.sync_check = True
self.opt.force = True
self.validate('cmd|s3,local|s3,local', args)
source = args[1]
target = args[2]
self.s3handler().dsync_files(source, target) |
def sync_handler(self, args):
'''Handler for sync command.
XXX Here we emulate sync command with get/put -r -f --sync-check. So
it doesn't provide delete operation.
'''
self.opt.recursive = True
self.opt.sync_check = True
self.opt.force = True
self.validate('cmd|s3,local|s3,lo... |
def cp_handler(self, args):
'''Handler for cp command'''
self.validate('cmd|s3|s3', args)
source = args[1]
target = args[2]
self.s3handler().cp_files(source, target) |
def mv_handler(self, args):
'''Handler for mv command'''
self.validate('cmd|s3|s3', args)
source = args[1]
target = args[2]
self.s3handler().cp_files(source, target, delete_source=True) |
def del_handler(self, args):
'''Handler for del command'''
self.validate('cmd|s3', args)
source = args[1]
self.s3handler().del_files(source) |
def du_handler(self, args):
'''Handler for size command'''
for src, size in self.s3handler().size(args[1:]):
message('%s\t%s' % (size, src)) |
def _totalsize_handler(self, args):
'''Handler of total_size command'''
total_size = 0
for src, size in self.s3handler().size(args[1:]):
total_size += size
message(str(total_size)) |
def match_date(self, value):
'''Search for date information in the string'''
m = self.REGEX_DATE.search(value)
date = datetime.datetime.utcnow().date()
if m:
date = datetime.date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
value = self.REGEX_DATE.sub('', value)
return (date, value... |
def match_time(self, value):
'''Search for time information in the string'''
m = self.REGEX_TIME.search(value)
time = datetime.datetime.utcnow().time()
if m:
time = datetime.time(int(m.group(1)), int(m.group(2)))
value = self.REGEX_TIME.sub('', value)
return (time, value) |
def match_delta(self, value):
'''Search for timedelta information in the string'''
m = self.REGEX_DELTA.search(value)
delta = datetime.timedelta(days=0)
if m:
d = int(m.group(1))
if m.group(3) == 'ago' or m.group(3) == 'before':
d = -d
if m.group(2) == 'minute':
delta ... |
def check_dict(self, opt, value):
'''Take json as dictionary parameter'''
try:
return json.loads(value)
except:
raise optparse.OptionValueError("Option %s: invalid dict value: %r" % (opt, value)) |
def discover_gateways(self):
"""Discover gateways using multicast"""
_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
_socket.settimeout(5.0)
if self._interface != 'any':
_socket.bind((self._interface, 0))
for gateway in self._gateways_config:
... |
def listen(self):
"""Start listening."""
_LOGGER.info('Creating Multicast Socket')
self._mcastsocket = self._create_mcast_socket()
self._listening = True
thread = Thread(target=self._listen_to_msg, args=())
self._threads.append(thread)
thread.daemon = True
... |
def stop_listen(self):
"""Stop listening."""
self._listening = False
if self._mcastsocket is not None:
_LOGGER.info('Closing multisocket')
self._mcastsocket.close()
self._mcastsocket = None
for thread in self._threads:
thread.join() |
def write_to_hub(self, sid, **kwargs):
"""Send data to gateway to turn on / off device"""
if self.key is None:
_LOGGER.error('Gateway Key is not provided. Can not send commands to the gateway.')
return False
data = {}
for key in kwargs:
data[key] = kwa... |
def get_from_hub(self, sid):
"""Get data from gateway"""
cmd = '{ "cmd":"read","sid":"' + sid + '"}'
resp = self._send_cmd(cmd, "read_ack") if int(self.proto[0:1]) == 1 else self._send_cmd(cmd, "read_rsp")
_LOGGER.debug("read_ack << %s", resp)
return self.push_data(resp) |
def push_data(self, data):
"""Push data broadcasted from gateway to device"""
if not _validate_data(data):
return False
jdata = json.loads(data['data']) if int(self.proto[0:1]) == 1 else _list2map(data['params'])
if jdata is None:
return False
sid = data['... |
def _get_key(self):
"""Get key using token from gateway"""
init_vector = bytes(bytearray.fromhex('17996d093d28ddb3ba695a2e6f58562e'))
encryptor = Cipher(algorithms.AES(self.key.encode()), modes.CBC(init_vector),
backend=default_backend()).encryptor()
ciphertext... |
def train(hparams, *args):
"""Train your awesome model.
:param hparams: The arguments to run the model with.
"""
# Initialize experiments and track all the hyperparameters
exp = Experiment(
name=hparams.test_tube_exp_name,
# Location to save the metrics.
save_dir=hparams.log... |
def train(hparams, *args):
"""Train your awesome model.
:param hparams: The arguments to run the model with.
"""
# Initialize experiments and track all the hyperparameters
exp = Experiment(
name=hparams.test_tube_exp_name,
# Location to save the metrics.
save_dir=hparams.log... |
def exception_handler(job, *exc_info):
"""
Called by RQ when there is a failure in a worker.
NOTE: Make sure that in your RQ worker process, rollbar.init() has been called with
handler='blocking'. The default handler, 'thread', does not work from inside an RQ worker.
"""
# Report data about the... |
def patch_debugtoolbar(settings):
"""
Patches the pyramid_debugtoolbar (if installed) to display a link to the related rollbar item.
"""
try:
from pyramid_debugtoolbar import tbtools
except ImportError:
return
rollbar_web_base = settings.get('rollbar.web_base', DEFAULT_WEB_BASE)... |
def includeme(config):
"""
Pyramid entry point
"""
settings = config.registry.settings
config.add_tween('rollbar.contrib.pyramid.rollbar_tween_factory', over=EXCVIEW)
# run patch_debugtoolbar, unless they disabled it
if asbool(settings.get('rollbar.patch_debugtoolbar', True)):
patc... |
def _ensure_log_handler(self):
"""
If there's no log configuration, set up a default handler.
"""
if log.handlers:
return
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(m... |
def get_request():
"""
Get the current request object. Implementation varies on
library support. Modified below when we know which framework
is being used.
"""
# TODO(cory): add in a generic _get_locals_request() which
# will iterate up through the call stack and look for a variable
# t... |
def init(access_token, environment='production', scrub_fields=None, url_fields=None, **kw):
"""
Saves configuration variables in this module's SETTINGS.
access_token: project access token. Get this from the Rollbar UI:
- click "Settings" in the top nav
- click "Projects"... |
def lambda_function(f):
"""
Decorator for making error handling on AWS Lambda easier
"""
@functools.wraps(f)
def wrapper(event, context):
global _CURRENT_LAMBDA_CONTEXT
_CURRENT_LAMBDA_CONTEXT = context
try:
result = f(event, context)
return wait(lambd... |
def report_exc_info(exc_info=None, request=None, extra_data=None, payload_data=None, level=None, **kw):
"""
Reports an exception to Rollbar, using exc_info (from calling sys.exc_info())
exc_info: optional, should be the result of calling sys.exc_info(). If omitted, sys.exc_info() will be called here.
r... |
def report_message(message, level='error', request=None, extra_data=None, payload_data=None):
"""
Reports an arbitrary string message to Rollbar.
message: the string body of the message
level: level to report at. One of: 'critical', 'error', 'warning', 'info', 'debug'
request: the request object fo... |
def send_payload(payload, access_token):
"""
Sends a payload object, (the result of calling _build_payload() + _serialize_payload()).
Uses the configured handler from SETTINGS['handler']
Available handlers:
- 'blocking': calls _send_payload() (which makes an HTTP request) immediately, blocks on it
... |
def search_items(title, return_fields=None, access_token=None, endpoint=None, **search_fields):
"""
Searches a project for items that match the input criteria.
title: all or part of the item's title to search for.
return_fields: the fields that should be returned for each item.
e.g. ['id', ... |
def _create_agent_log():
"""
Creates .rollbar log file for use with rollbar-agent
"""
log_file = SETTINGS['agent.log_file']
if not log_file.endswith('.rollbar'):
log.error("Provided agent log file does not end with .rollbar, which it must. "
"Using default instead.")
... |
def _report_exc_info(exc_info, request, extra_data, payload_data, level=None):
"""
Called by report_exc_info() wrapper
"""
if not _check_config():
return
filtered_level = _filtered_level(exc_info[1])
if level is None:
level = filtered_level
filtered_exc_info = events.on_ex... |
def _report_message(message, level, request, extra_data, payload_data):
"""
Called by report_message() wrapper
"""
if not _check_config():
return
filtered_message = events.on_message(message,
request=request,
... |
def _build_person_data(request):
"""
Returns a dictionary describing the logged-in user using data from `request.
Try request.rollbar_person first, then 'user', then 'user_id'
"""
if hasattr(request, 'rollbar_person'):
rollbar_person_prop = request.rollbar_person
try:
pe... |
def _add_lambda_context_data(data):
"""
Attempts to add information from the lambda context if it exists
"""
global _CURRENT_LAMBDA_CONTEXT
context = _CURRENT_LAMBDA_CONTEXT
if context is None:
return
try:
lambda_data = {
'lambda': {
'remaining_tim... |
def _add_request_data(data, request):
"""
Attempts to build request data; if successful, sets the 'request' key on `data`.
"""
try:
request_data = _build_request_data(request)
except Exception as e:
log.exception("Exception while building request_data for Rollbar payload: %r", e)
... |
def _check_add_locals(frame, frame_num, total_frames):
"""
Returns True if we should record local variables for the given frame.
"""
# Include the last frames locals
# Include any frame locals that came from a file in the project's root
return any(((frame_num == total_frames - 1),
... |
def _build_request_data(request):
"""
Returns a dictionary containing data from the request.
Can handle webob or werkzeug-based request objects.
"""
# webob (pyramid)
if WebobBaseRequest and isinstance(request, WebobBaseRequest):
return _build_webob_request_data(request)
# django
... |
def _build_server_data():
"""
Returns a dictionary containing information about the server environment.
"""
# server environment
server_data = {
'host': socket.gethostname(),
'pid': os.getpid()
}
# argv does not always exist in embedded python environments
argv = getattr... |
def _build_payload(data):
"""
Returns the full payload as a string.
"""
for k, v in iteritems(data):
data[k] = _transform(v, key=(k,))
payload = {
'access_token': SETTINGS['access_token'],
'data': data
}
return payload |
def main():
rollbar.init('ACCESS_TOKEN', environment='test', handler='twisted')
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000, factory)
reactor.run() |
def compose(chosung, joongsung, jongsung=u''):
"""This function returns a Hangul letter by composing the specified chosung, joongsung, and jongsung.
@param chosung
@param joongsung
@param jongsung the terminal Hangul letter. This is optional if you do not need a jongsung."""
if jongsung is None: jo... |
def decompose(hangul_letter):
"""This function returns letters by decomposing the specified Hangul letter."""
from . import checker
if len(hangul_letter) < 1:
raise NotLetterException('')
elif not checker.is_hangul(hangul_letter):
raise NotHangulException('')
if hangul_letter in C... |
def has_jongsung(letter):
"""Check whether this letter contains Jongsung"""
if len(letter) != 1:
raise Exception('The target string must be one letter.')
if not is_hangul(letter):
raise NotHangulException('The target string must be Hangul')
code = lt.hangul_index(letter)
return code... |
def attach(word, josa=EUN_NEUN):
"""add josa at the end of this word"""
last_letter = word.strip()[-1]
try:
_, _, letter_jong = letter.decompose(last_letter)
except NotHangulException:
letter_jong = letter.get_substituent_of(last_letter)
if letter_jong in ('', josa['except']):
... |
def is_inside_except(node):
"""Returns true if node is inside the name of an except handler."""
current = node
while current and not isinstance(current.parent, astroid.ExceptHandler):
current = current.parent
return current and current is current.parent.name |
def is_inside_lambda(node: astroid.node_classes.NodeNG) -> bool:
"""Return true if given node is inside lambda"""
parent = node.parent
while parent is not None:
if isinstance(parent, astroid.Lambda):
return True
parent = parent.parent
return False |
def get_all_elements(
node: astroid.node_classes.NodeNG
) -> Iterable[astroid.node_classes.NodeNG]:
"""Recursively returns all atoms in nested lists and tuples."""
if isinstance(node, (astroid.Tuple, astroid.List)):
for child in node.elts:
for e in get_all_elements(child):
... |
def clobber_in_except(
node: astroid.node_classes.NodeNG
) -> Tuple[bool, Tuple[str, str]]:
"""Checks if an assignment node in an except handler clobbers an existing
variable.
Returns (True, args for W0623) if assignment clobbers an existing variable,
(False, None) otherwise.
"""
if isinsta... |
def is_super(node: astroid.node_classes.NodeNG) -> bool:
"""return True if the node is referencing the "super" builtin function
"""
if getattr(node, "name", None) == "super" and node.root().name == BUILTINS_NAME:
return True
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.