def initial_positions(walls):

    width = max(walls)[0] + 1
    height = max(walls)[1] + 1

    left_start = (1, height - 2)
    left = []
    right_start = (width - 2, 1)
    right = []

    dist = 0
    while len(left) < 2:

        for x_dist in range(dist + 1):
            y_dist = dist - x_dist
            pos = (left_start[0] + x_dist, left_start[1] - y_dist)

            if not (0 <= pos[0] < width) and not (0 <= pos[1] < height):
                raise ValueError("Not enough free initial positions.")

            if not (0 <= pos[0] < width) or not (0 <= pos[1] < height):
                continue

            if pos not in walls:
                left.append(pos)

            if len(left) == 2:
                break

        dist += 1

    dist = 0
    while len(right) < 2:

        for x_dist in range(dist + 1):
            y_dist = dist - x_dist
            pos = (right_start[0] - x_dist, right_start[1] + y_dist)

            if not (0 <= pos[0] < width) and not (0 <= pos[1] < height):
                raise ValueError("Not enough free initial positions.")

            if not (0 <= pos[0] < width) or not (0 <= pos[1] < height):
                continue

            if pos not in walls:
                right.append(pos)

            if len(right) == 2:
                break

        dist += 1

    left.reverse()
    right.reverse()
    return [left[0], right[0], left[1], right[1]]

Input: [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 3), (4, 0), (4, 1), (4, 3), (5, 0), (5, 3), (6, 0), (6, 3), (7, 0), (7, 1), (7, 2), (7, 3)]

Output: [(1, 1), (6, 2), (1, 2), (6, 1)]


def deep_extend(*args):

        def clone_obj(item):
            if isinstance(item, dict):
                return dict(**item)
            if isinstance(item, (list, tuple)):
                return list(item)
            return None

        def iterator(item, i, iterable):
            obj = clone_obj(item)
            if obj is None:
                iterable[i] = item
            else:
                if isinstance(obj, dict):
                    iterable[i] = deep_extend({}, obj)
                elif isinstance(obj, (list, tuple)):
                    FuncFlow.each(obj, iterator)
                    iterable[i] = obj
                else:
                    raise TypeError("deep_copy cannot handle this type: {}".format(type(obj)))

        args = list(args)
        dest = args.pop(0)

        for source in args:
            if source:
                for k, v in source.items():
                    obj = clone_obj(v)
                    if obj is None:
                        dest[k] = v
                    else:
                        FuncFlow.each(obj, iterator)
                        dest[k] = obj
        return dest


def get_nested(d, path, delimiter="/"):

    def item_by_tag(d, tags):

        t = tags[-1]
        if len(tags) == 1:
            return d[t]
        return item_by_tag(d[t], tags[:-1])

    tags = path.split(delimiter)
    tags.reverse()

    return item_by_tag(d, tags)

Input: {'nested': {'data': 'should be unchanged', 'event': None}}, 'nested', '/'

Output: {'data': 'should be unchanged', 'event': None}


def extend(*args):
        args = list(args)
        dest = args.pop(0)
        for source in args:
            if source:
                dest.update(source)
        return dest


def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

Input: REPR FAILED, ('My Way',)

Output: {'name': 'My Way'}


def digit_version(version_str: str, length: int = 4):

    assert 'parrots' not in version_str
    version = parse(version_str)
    assert version.release, f'failed to parse version {version_str}'
    release = list(version.release)
    release = release[:length]
    if len(release) < length:
        release = release + [0] * (length - len(release))
    if version.is_prerelease:
        mapping = {'a': -3, 'b': -2, 'rc': -1}
        val = -4

        if version.pre:
            if version.pre[0] not in mapping:
                warnings.warn(f'unknown prerelease version {version.pre[0]}, '
                              'version checking may go wrong')
            else:
                val = mapping[version.pre[0]]
            release.extend([val, version.pre[-1]])
        else:
            release.extend([val, 0])

    elif version.is_postrelease:
        release.extend([1, version.post])
    else:
        release.extend([0, 0])
    return tuple(release)

Input: '2.2.2+cu121', 4

Output: (2, 2, 2, 0, 0, 0)


def __ne__(self, other: object) -> bool:
        return not self == other

Input: {'Properties': {'callcorrect': False}}

Output: {'Properties': {'callcorrect': False}}


def get_or_add_parameter(self, parameter: Parameter) -> Parameter:
        if parameter.title in self.parameters:
            return self.parameters[parameter.title]
        else:
            self.add_parameter(parameter)
        return parameter

Input: {'Value': 'myvalue'}

Output: {'Value': 'myvalue'}


def notification_event(events):

    valid_events = ["All", "InProgress", "Success", "TimedOut", "Cancelled", "Failed"]
    for event in events:
        if event not in valid_events:
            raise ValueError(
                'NotificationEvents must be at least one of: "%s"'
                % (", ".join(valid_events))
            )
    return events

Input: ['All', 'InProgress', 'Success', 'TimedOut', 'Cancelled', 'Failed']

Output: ['All', 'InProgress', 'Success', 'TimedOut', 'Cancelled', 'Failed']


def get_air_quality(city):

    if not city or not city.strip():
        return
    print('获取 {} 的空气质量...'.format(city))
    try:

        url = 'http://api.waqi.info/feed/{city}/?token={token}'.format(city=city, token=AQICN_TOKEN)
        resp = requests.get(url)
        if resp.status_code == 200:

            content_dict = resp.json()
            if content_dict.get('status') == 'ok':
                data_dict = content_dict['data']
                aqi = data_dict['aqi']
                air_status = '严重污染'
                for key in sorted(AIR_STATUS_DICT):
                    if key >= aqi:
                        air_status = AIR_STATUS_DICT[key]
                        break
                aqi_info = '{city} PM2.5：{aqi} {air_status}'.format(city=city, aqi=aqi, air_status=air_status)

                return aqi_info
            else:
                print('获取空气质量失败:{}'.format(content_dict['data']))
                return None
        print('获取空气质量失败。')
    except Exception as exception:
        print(str(exception))
    return None

Input: '桂林'

Output: '桂林 PM2.5：50 优'


def _LiteralEval(value):

  root = ast.parse(value, mode='eval')
  if isinstance(root.body, ast.BinOp):
    raise ValueError(value)

  for node in ast.walk(root):
    for field, child in ast.iter_fields(node):
      if isinstance(child, list):
        for index, subchild in enumerate(child):
          if isinstance(subchild, ast.Name):
            child[index] = _Replacement(subchild)

      elif isinstance(child, ast.Name):
        replacement = _Replacement(child)
        node.__setattr__(field, replacement)

  return ast.literal_eval(root)

Input: '[one, 2, "3"]'

Output: ['one', 2, '3']


def SeparateFlagArgs(args: list):

  if len(args) > 0 and (args[-1] == '-h' or args[-1] == '--help') and '--' not in args:
    args.pop()
    args.append('--')
    args.append('-h')

  if '--' in args:
    separator_index = len(args) - 1 - args[::-1].index('--')
    flag_args = args[separator_index + 1:]
    args = args[:separator_index]
    return args, flag_args

  return args, []

Input: ['a', 'b', '--']

Output: (['a', 'b'], [])


def prepare_docstring_help(N):

    args = []
    if hasattr(N, '__annotations__'):
        for attr_name, cls in N.__annotations__.items():

            filtered = filter_params(N)
            parsed = parse_source_for_params(filtered)
            attr = attr_map(parsed).get(attr_name)
            if attr is None:
                continue

            args.append(argument_help(attr_name, attr))

    return '\n'.join(args)

Output: '    --bar (int):  (Default is 0)'


def filter_params(N):

    filtered_source = []
    for line in inspect.getsourcelines(N.__class__)[0][1:]:

        if line.strip().startswith('def '):
            break
        filtered_source.append(line)
    return filtered_source

Output: ['            bar: int = 0\n']


def _ParseFn(args):

    kwargs, remaining_kwargs, remaining_args = _ParseKeywordArgs(
        args, all_args, fn_spec.varkw)

    parsed_args, kwargs, remaining_args, capacity = _ParseArgs(
        fn_spec.args, fn_spec.defaults, num_required_args, kwargs,
        remaining_args, metadata)

    if fn_spec.varargs or fn_spec.varkw:

      capacity = True

    extra_kw = set(kwargs) - set(fn_spec.kwonlyargs)
    if fn_spec.varkw is None and extra_kw:
      raise FireError('Unexpected kwargs present:', extra_kw)

    missing_kwonly = set(required_kwonly) - set(kwargs)
    if missing_kwonly:
      raise FireError('Missing required flags:', missing_kwonly)

    if fn_spec.varargs is not None:
      varargs, remaining_args = remaining_args, []
    else:
      varargs = []

    for index, value in enumerate(varargs):
      varargs[index] = _ParseValue(value, None, None, metadata)

    varargs = parsed_args + varargs
    remaining_args += remaining_kwargs

    consumed_args = args[:len(args) - len(remaining_args)]
    return (varargs, kwargs), consumed_args, remaining_args, capacity

Input: ['x'], [], {args=[], varargs=None, varkw='cli_args', defaults=(), kwonlyargs=[], kwonlydefaults={}, annotations={}}, {'ACCEPTS_POSITIONAL_ARGS': False}, 0, set()

Output: (([], {}), [], ['x'], True)


def config_dict(configuration_tuple):
    config_dict = {}

    config_file = configuration_tuple._asdict().get('CFG')
    if config_file is None:
        config_file = configfile.get_config_path(configuration_tuple)

    if config_file is not None:
        config_dict = utils.filter_fields(configfile.read_config(config_file), configuration_tuple)
        config_dict = utils.type_correct_with(config_dict, configuration_tuple)

    return config_dict

Output: {'bar': 42}


def read_config(_filepath='test.cfg') -> dict:
    filepath = Path(_filepath)
    if not filepath.exists():
        return {}

    file_config = configparser.ConfigParser()
    file_config.read(filepath)
    if 'Default' in file_config:
        return dict(file_config['Default'])
    else:
        print('warning: config file found at {}, but it was missing section named [Default]'.format(str(filepath)))
        return {}

Input: PosixPath('/local/rcs/XXX/code/pytrace-collector/logs/pypibugs/tried/d3rp+clima/d3rp+clima/tests/test_configfile.py')

Output: PosixPath('/local/rcs/XXX/code/pytrace-collector/logs/pypibugs/tried/d3rp+clima/d3rp+clima/foo.cfg')


def filter_fields(d: dict, nt):

    res = {}
    for k, v in d.items():
        if k in nt._fields:
            res.update({k: v})

    return res

Input: {'bar': '42'}, {}

Output: {'bar': '42'}


def type_correct_with(cdict, cfg_tuple):

    res = {}
    for k, v in cdict.items():
        typename = getattr(cfg_tuple, k)
        res.update({k: type(typename)(v)})
    return res

Input: {'bar': '42'}, {}

Output: {'bar': 42}


def safe_abs_path(res):
    "Gives an abs path, which safely returns a full (not 8.3) windows path"
    res = Path(res).resolve()
    return str(res)


def is_image_file(file_name):

    file_name = str(file_name)
    return any(file_name.endswith(ext) for ext in IMAGE_EXTENSIONS)

Input: PosixPath('/tmp/tmpcr1f5en7/.gitignore')

Output: False


def mock_get_commit_message(diffs, context):
                self.assertNotIn("one", diffs)
                self.assertNotIn("ONE", diffs)
                return "commit message"

Input: 'diff --git a/file.txt b/file.txt\nindex 5626abf..f719efd 100644\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-one\n+two', None, []

Output: 'commit message'


def do_replace(fname, content, before_text, after_text, fence=None):
    before_text = strip_quoted_wrapping(before_text, fname, fence)
    after_text = strip_quoted_wrapping(after_text, fname, fence)
    fname = Path(fname)

    if not fname.exists() and not before_text.strip():
        fname.touch()
        content = ""

    if content is None:
        return

    if not before_text.strip():

        new_content = content + after_text
    else:
        new_content = replace_most_similar_chunk(content, before_text, after_text)

    return new_content

Input: '/tmp/tmp7g7a2csg/file.txt', 'two\n', 'two\n', 'three\n', ('```', '```')

Output: 'three\n'


def strip_quoted_wrapping(res, fname=None, fence=DEFAULT_FENCE):

    if not res:
        return res

    res = res.splitlines()

    if fname and res[0].strip().endswith(Path(fname).name):
        res = res[1:]

    if res[0].startswith(fence[0]) and res[-1].startswith(fence[1]):
        res = res[1:-1]

    res = "\n".join(res)
    if res and res[-1] != "\n":
        res += "\n"

    return res

Input: 'two\n', '/tmp/tmp7g7a2csg/file.txt', ('```', '```')

Output: 'two\n'


def replace_most_similar_chunk(whole, part, replace):

    whole, whole_lines = prep(whole)
    part, part_lines = prep(part)
    replace, replace_lines = prep(replace)

    res = perfect_or_whitespace(whole_lines, part_lines, replace_lines)
    if res:
        return res

    if len(part_lines) > 2 and not part_lines[0].strip():
        skip_blank_line_part_lines = part_lines[1:]
        res = perfect_or_whitespace(whole_lines, skip_blank_line_part_lines, replace_lines)
        if res:
            return res

    try:
        res = try_dotdotdots(whole, part, replace)
        if res:
            return res
    except ValueError:
        pass

    return

    res = replace_closest_edit_distance(whole_lines, part, part_lines, replace_lines)
    if res:
        return res

Input: 'two\n', 'two\n', 'three\n'

Output: 'three\n'


def perfect_or_whitespace(whole_lines, part_lines, replace_lines):

    res = perfect_replace(whole_lines, part_lines, replace_lines)
    if res:
        return res

    res = replace_part_with_missing_leading_whitespace(whole_lines, part_lines, replace_lines)
    if res:
        return res

Input: ['two\n'], ['two\n'], ['three\n']

Output: 'three\n'


def perfect_replace(whole_lines, part_lines, replace_lines):
    part_tup = tuple(part_lines)
    part_len = len(part_lines)

    for i in range(len(whole_lines) - part_len + 1):
        whole_tup = tuple(whole_lines[i : i + part_len])
        if part_tup == whole_tup:
            res = whole_lines[:i] + replace_lines + whole_lines[i + part_len :]
            return "".join(res)

Input: ['two\n'], ['two\n'], ['three\n']

Output: 'three\n'


def parse_quoted_filenames(args):
    filenames = re.findall(r"\"(.+?)\"|(\S+)", args)
    filenames = [name for sublist in filenames for name in sublist if name]
    return filenames

Input: 'foo.txt bar.txt'

Output: ['foo.txt', 'bar.txt']


def replace_part_with_missing_leading_whitespace(whole_lines, part_lines, replace_lines):

    leading = [len(p) - len(p.lstrip()) for p in part_lines if p.strip()] + [
        len(p) - len(p.lstrip()) for p in replace_lines if p.strip()
    ]

    if leading and min(leading):
        num_leading = min(leading)
        part_lines = [p[num_leading:] if p.strip() else p for p in part_lines]
        replace_lines = [p[num_leading:] if p.strip() else p for p in replace_lines]

    num_part_lines = len(part_lines)

    for i in range(len(whole_lines) - num_part_lines + 1):
        add_leading = match_but_for_leading_whitespace(
            whole_lines[i : i + num_part_lines], part_lines
        )

        if add_leading is None:
            continue

        replace_lines = [add_leading + rline if rline.strip() else rline for rline in replace_lines]
        whole_lines = whole_lines[:i] + replace_lines + whole_lines[i + num_part_lines :]
        return "".join(whole_lines)

    return None

Input: ['    line1\n', '    line2\n', '    line3\n'], [' line1\n', ' line2\n'], [' new_line1\n', '     new_line2\n']

Output: '    new_line1\n        new_line2\n    line3\n'


def match_but_for_leading_whitespace(whole_lines, part_lines):
    num = len(whole_lines)

    if not all(whole_lines[i].lstrip() == part_lines[i].lstrip() for i in range(num)):
        return

    add = set(
        whole_lines[i][: len(whole_lines[i]) - len(part_lines[i])]
        for i in range(num)
        if whole_lines[i].strip()
    )

    if len(add) != 1:
        return

    return add.pop()

Input: ['    line1\n', '    line2\n'], ['line1\n', 'line2\n']


def find_diffs(content):

    if not content.endswith("\n"):
        content = content + "\n"

    lines = content.splitlines(keepends=True)
    line_num = 0
    edits = []
    while line_num < len(lines):
        while line_num < len(lines):
            line = lines[line_num]
            if line.startswith("```diff"):
                line_num, these_edits = process_fenced_block(lines, line_num + 1)
                edits += these_edits
                break
            line_num += 1

    return edits

Input: '\nSome text...\n\n```diff\n--- /dev/null\n+++ file.txt\n@@ ... @@\n-Original\n+Modified\n```\n'

Output: [('file.txt', ['-Original\n', '+Modified\n'])]


def process_fenced_block(lines, start_line_num):
    for line_num in range(start_line_num, len(lines)):
        line = lines[line_num]
        if line.startswith("```"):
            break

    block = lines[start_line_num:line_num]
    block.append("@@ @@")

    if block[0].startswith("--- ") and block[1].startswith("+++ "):

        fname = block[1][4:].strip()
        block = block[2:]
    else:
        fname = None

    edits = []

    keeper = False
    hunk = []
    op = " "
    for line in block:
        hunk.append(line)
        if len(line) < 2:
            continue

        if line.startswith("+++ ") and hunk[-2].startswith("--- "):
            if hunk[-3] == "\n":
                hunk = hunk[:-3]
            else:
                hunk = hunk[:-2]

            edits.append((fname, hunk))
            hunk = []
            keeper = False

            fname = line[4:].strip()
            continue

        op = line[0]
        if op in "-+":
            keeper = True
            continue
        if op != "@":
            continue
        if not keeper:
            hunk = []
            continue

        hunk = hunk[:-1]
        edits.append((fname, hunk))
        hunk = []
        keeper = False

    return line_num + 1, edits

Input: ['\n', 'Some text...\n', '\n', '```diff\n', '--- /dev/null\n', '+++ file.txt\n', '@@ ... @@\n', '-Original\n', '+Modified\n', '```\n'], 4

Output: (10, [('file.txt', ['-Original\n', '+Modified\n'])])


def _addpoints(sol, distances, prec):

    res = []

    posfound = False

    pleft = []
    for n, m in enumerate(sol):
        if np.ndim(m) == 0:
            pleft.append(n)

    for i in pleft:
        ires, state = _addpoint(sol, i, distances, prec)

        if state == 0:
            posfound = True
            for j in ires:
                res.append(dcopy(j))

        elif state == 2:
            return [], 2

    if posfound:
        return res, 0

    return res, 1

Input: [array([0., 0.]), array([3., 0.]), 0, 0], array([[ 0.,  3.,  4.,  1.],       [ 3.,  0.,  2.,  3.],       [ 4.,  2.,  0., -1.],       [ 1.,  3., -1.,  0.]]), 0.1

Output: ([[array([0., 0.]), array([3., 0.]), array([3.5       , 1.93649167]), 0], [array([0., 0.]), array([3., 0.]), array([ 3.5       , -1.93649167]), 0], [array([0., 0.]), array([3., 0.]), 0, array([0.16666667, 0.9860133 ])], [array([0., 0.]), array([3., 0.]), 0, array([ 0.16666667, -0.9860133 ])]], 0)


def _addpoint(sol, i, distances, prec):

    res = []

    if np.ndim(sol[i]) != 0:
        return [sol], 0

    solpnts = []
    for n, m in enumerate(sol):
        if np.ndim(m) != 0:
            solpnts.append(n)

    pntscount = len(solpnts)

    for n in range(pntscount - 1):
        for m in range(n + 1, pntscount):
            tmppnt, state = _pntcoord(
                sol, i, solpnts[n], solpnts[m], distances, prec
            )

            if state == 0:
                for pnt in tmppnt:
                    res.append(dcopy(sol))
                    res[-1][i] = pnt

            if state != 1:
                return res, state

    return res, state

Input: [array([0., 0.]), array([3., 0.]), 0, 0], 2, array([[ 0.,  3.,  4.,  1.],       [ 3.,  0.,  2.,  3.],       [ 4.,  2.,  0., -1.],       [ 1.,  3., -1.,  0.]]), 0.1

Output: ([[array([0., 0.]), array([3., 0.]), array([3.5       , 1.93649167]), 0], [array([0., 0.]), array([3., 0.]), array([ 3.5       , -1.93649167]), 0]], 0)


def _pntcoord(sol, i, n, m, distances, prec):

    tmppnt = []

    state = 1

    pntscount = len(sol)

    if distances[i, n] < -0.5 or distances[i, m] < -0.5:
        return tmppnt, state

    if distances[i, n] + distances[i, m] < _dist(sol[n], sol[m]):
        state = 2
        return tmppnt, state

    g = _affinef(*_invtranmat(*_tranmat(sol[n], sol[m])))

    x = _xvalue(distances[i, n], distances[i, m], _dist(sol[n], sol[m]))
    y1, y2 = _yvalue(distances[i, n], distances[i, m], _dist(sol[n], sol[m]))

    pos1 = g(np.array([x, y1]))
    pos2 = g(np.array([x, y2]))

    valid1 = True
    valid2 = True

    for k in range(pntscount):
        if np.ndim(sol[k]) != 0 and distances[i, k] > -0.5:
            valid1 &= abs(_dist(sol[k], pos1) - distances[i, k]) < prec
            valid2 &= abs(_dist(sol[k], pos2) - distances[i, k]) < prec

    if valid1 or valid2:
        state = 0
        same = abs(y1 - y2) < prec / 4.0
        if valid1:
            tmppnt.append(dcopy(pos1))
        if valid2 and not same:
            tmppnt.append(dcopy(pos2))

    else:
        state = 2

    return tmppnt, state

Input: [array([0., 0.]), array([3., 0.]), 0, 0], 2, 0, 1, array([[ 0.,  3.,  4.,  1.],       [ 3.,  0.,  2.,  3.],       [ 4.,  2.,  0., -1.],       [ 1.,  3., -1.,  0.]]), 0.1

Output: ([array([3.5       , 1.93649167]), array([ 3.5       , -1.93649167])], 0)


Input: array([0., 0.]), array([3., 0.])

Output: (array([[ 1.,  0.],       [-0.,  1.]]), array([-0., -0.]))


def _yvalue(b, a, c):

    if a + b <= c or a + c <= b or b + c <= a:
        return 0.0, -0.0

    res = 2 * ((a * b) ** 2 + (a * c) ** 2 + (b * c) ** 2)
    res -= a ** 4 + b ** 4 + c ** 4

    res = max(res, 0.0)
    res = np.sqrt(res)
    res /= 2 * c
    return res, -res

Input: 4.0, 2.0, 3.0

Output: (1.9364916731037083, -1.9364916731037083)


def _solequal(sol1, sol2, prec):

    res = True

    for sol_1, sol_2 in zip(sol1, sol2):
        if np.ndim(sol_1) != 0 and np.ndim(sol_2) != 0:
            res &= _dist(sol_1, sol_2) < prec
        elif np.ndim(sol_1) != 0 and np.ndim(sol_2) == 0:
            return False
        elif np.ndim(sol_1) == 0 and np.ndim(sol_2) != 0:
            return False

    return res

Input: [array([0., 0.]), array([3., 0.]), array([3.5       , 1.93649167]), array([ 0.16666667, -0.9860133 ])], [array([0., 0.]), array([3., 0.]), array([3.5       , 1.93649167]), array([0.16666667, 0.9860133 ])], 0.1

Output: False


def _process_namespace(name, namespaces, ns_sep=':', attr_prefix='@'):
    if not namespaces:
        return name
    try:
        ns, name = name.rsplit(ns_sep, 1)
    except ValueError:
        pass
    else:
        ns_res = namespaces.get(ns.strip(attr_prefix))
        name = '{}{}{}{}'.format(
            attr_prefix if ns.startswith(attr_prefix) else '',
            ns_res, ns_sep, name) if ns_res else name
    return name

Input: 'http://defaultns.com/:root', {'http://defaultns.com/': '', 'http://a.com/': 'a', 'http://b.com/': 'b'}, ':', '@'

Output: 'root'


def check_data(a, b):
    if not isinstance(a, np.ndarray):
        a = np.array(a)

    if not isinstance(b, np.ndarray):
        b = np.array(b)

    if type(a) != type(b):
        raise ValueError("Type mismatch: %s and %s" % (type(a), type(b)))

    if a.size != b.size:
        raise ValueError("Arrays must be equal in length.")
    return a, b

Input: [1, 2, 3], [3, 2, 1]

Output: (array([1, 2, 3]), array([3, 2, 1]))


def logloss(actual, predicted):
    predicted = np.clip(predicted, EPS, 1 - EPS)
    loss = -np.sum(actual * np.log(predicted))
    return loss / float(actual.shape[0])

Input: array([1]), array([1])

Output: 9.992007221626415e-16


def clasifier(optimizer):
    X, y = make_classification(
        n_samples=1000, n_features=100, n_informative=75, random_state=1111, n_classes=2, class_sep=2.5
    )
    y = one_hot(y)

    X -= np.mean(X, axis=0)
    X /= np.std(X, axis=0)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=1111)

    model = NeuralNet(
        layers=[
            Dense(128, Parameters(init="uniform")),
            Activation("relu"),
            Dropout(0.5),
            Dense(64, Parameters(init="normal")),
            Activation("relu"),
            Dense(2),
            Activation("softmax"),
        ],
        loss="categorical_crossentropy",
        optimizer=optimizer,
        metric="accuracy",
        batch_size=64,
        max_epochs=10,
    )
    model.fit(X_train, y_train)
    predictions = model.predict(X_test)
    return roc_auc_score(y_test[:, 0], predictions[:, 0])

Input: {rho=0.95, eps=1e-08, lr=1.0}

Output: 0.92549786628734


def str2datetime(string):

    if string == "0000-00-00T24:60:60Z":
        return None

    ms = string[20:-1]
    ms += "000000"[:6 - len(ms)]
    return datetime.datetime(
        int(string[:4]),
        int(string[5:7]),
        int(string[8:10]),
        int(string[11:13]),
        int(string[14:16]),
        int(string[17:19]),
        int(ms))

Output: datetime.datetime(1970, 1, 1, 0, 0)


def flatten(d, parent_key="", sep="/") -> Dict[str, Any]:

    items: List[Tuple[str, List[str]]] = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, MutableMapping):
            items.extend(flatten(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

Input: {'aprtoapy': [], 'il': []}, 'crypto/tools', '/'

Output: {'crypto/tools/aprtoapy': [], 'crypto/tools/il': []}


def load_json_dict(filename, *args):

    data = {}
    if os.path.exists(filename):
        lock.acquire()
        with open(filename, "r") as f:
            try:
                data = _json.load(f)
                if not isinstance(data, dict):
                    data = {}
            except:
                data = {}
        lock.release()
        if args:
            return {key: data[key] for key in args if key in data}
    return data

Input: '/home/XXX/.plotly/.config', ()

Output: {'plotly_domain': 'https://plot.ly', 'plotly_streaming_domain': 'stream.plot.ly', 'plotly_api_domain': 'https://api.plot.ly', 'plotly_ssl_verification': True, 'plotly_proxy_authorization': False, 'world_readable': True, 'sharing': 'public', 'auto_open': True}


def export_data(self) -> typing.Dict[str, dict]:

        nested_ip_objects = dict()

        if self.__children_ip_object and None in self.__children_ip_object:
            children_per_version = dict()
            for child in self.__children_ip_object[None]:
                version_set = children_per_version.setdefault(
                    child.version, set()
                )
                version_set.add(child)

            for version in children_per_version:
                version_nest = nested_ip_objects.setdefault(version, dict())
                for child in children_per_version[version]:
                    version_nest[child] = self.__gather_nested_children(child)

        return dict({
            "description": dict(self.__description),
            "nested_ip_objects": nested_ip_objects,
        })

Input: AddressSpace(_AddressSpace__strict=True, _AddressSpace__description={}, _AddressSpace__networks={}, _AddressSpace__addresses={}, _AddressSpace__parent_supernet={}, _AddressSpace__children_ip_object={None: set()}), {}, {None: set()}, {}, {}, {}, True

Output: {'description': {}, 'nested_ip_objects': {}}


def get_idx(ndim, axis=None, axis_idx=None):
    s = [midx] * ndim
    if axis is not None:
        if hasattr(axis, "__iter__"):
            for ax, axidx in zip(axis, axis_idx):
                s[ax] = axidx
        else:
            s[axis] = axis_idx
    return tuple(s)

Input: 1, 0, slice(None, -2, None)

Output: (slice(None, -2, None),)


def det_hess(u):

    ndim = np.ndim(u)
    inshape = np.asarray(u.shape)
    outshape = list(inshape - 2)

    hess_unarranged = np.zeros([ndim, ndim] + outshape)
    for i in range(ndim):
        for j in range(i,ndim):
            grad2_val = grad2(u, (i,j))
            hess_unarranged[i,j] = grad2_val
            hess_unarranged[j,i] = grad2_val

    perm_idx = list(range(2,ndim+2)) + list(range(2))
    hess = np.transpose(hess_unarranged, perm_idx)

    return np.linalg.det(hess)

Input: array([  0.,   1.,   4.,   9.,  16.,  25.,  36.,  49.,  64.,  81., 100.,       121., 144., 169., 196., 225., 256., 289., 324., 361., 400., 441.,       484., 529., 576., 625., 676., 729., 784., 841., 900., 961.])

Output: array([2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,       2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.])


def _get_default_expanded_coordinate(shape, ndim):
    x_coords = []
    for i in range(ndim):
        idx = [None] * ndim
        idx[i] = slice(None, None, None)
        x_coords.append(np.arange(shape[i])[tuple(idx)])
    return x_coords

Input: array([92]), 1

Output: [array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,       51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,       68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,       85, 86, 87, 88, 89, 90, 91])]


def _pad_conserve_grads(phi):

    ndim = np.ndim(phi)
    pw = [1, 1]
    pp = np.pad(phi, [tuple(pw)]*ndim, mode="constant")
    for dim in range(ndim):

        idx_pad0_l = _get_idx(ndim, dim, slice(pw[0], pw[0]+1, None))
        idx_pad0_r = _get_idx(ndim, dim, slice(pw[0]+1, pw[0]+2, None))
        idx_pad0 = _get_idx(ndim, dim, slice(pw[0], pw[0]+1, None))
        idx_pad0_fill = _get_idx(ndim, dim, slice(None, pw[0], None))
        idx_pad1_l = _get_idx(ndim, dim, slice(-pw[1]-2, -pw[1]-1, None))
        idx_pad1_r = _get_idx(ndim, dim, slice(-pw[1]-1, -pw[1], None))
        idx_pad1 = _get_idx(ndim, dim, slice(-pw[1]-1, -pw[1], None))
        idx_pad1_fill = _get_idx(ndim, dim, slice(-pw[1], None, None))

        grad0 = pp[idx_pad0_r] - pp[idx_pad0_l]
        grad1 = pp[idx_pad1_r] - pp[idx_pad1_l]
        pad_arange0 = np.arange(-pw[0],0)
        pad_arange1 = np.arange(1,pw[0]+1)
        pad0 = pad_arange0 * grad0 + pp[idx_pad0]
        pad1 = pad_arange1 * grad1 + pp[idx_pad1]
        pp[idx_pad0_fill] = pad0
        pp[idx_pad1_fill] = pad1

    return pp

Input: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

Output: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])


def _get_idx(ndim, dim, s, defidx=None):
    defidx = slice(None, None, None) if defidx is None else defidx
    idx = [defidx] * ndim
    idx[dim] = s
    return tuple(idx)

Input: 1, 0, slice(1, 2, None), None

Output: (slice(1, 2, None),)


def _makeComplementTable(complementData):

        table = list(range(256))
        for _from, to in complementData.items():
            table[ord(_from[0].lower())] = ord(to[0].lower())
            table[ord(_from[0].upper())] = ord(to[0].upper())
        return ''.join(map(chr, table))

Input: {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'M': 'K', 'R': 'Y', 'W': 'W', 'S': 'S', 'Y': 'R', 'K': 'M', 'V': 'B', 'H': 'D', 'D': 'H', 'B': 'V', 'X': 'X', 'N': 'N'}


def find_extension(codec):

    if codec in extensions_dict:

        return codec

    for ext, infos in extensions_dict.items():
        if codec in infos.get("codec", []):
            return ext
    raise ValueError(
        "The audio_codec you chose is unknown by MoviePy. "
        "You should report this. In the meantime, you can "
        "specify a temp_audiofile with the right extension "
        "in write_videofile."
    )


def version_compare(v1, v2):

    arr1 = v1.split(".")
    arr2 = v2.split(".")
    n = len(arr1)
    m = len(arr2)

    arr1 = [int(i) for i in arr1]
    arr2 = [int(i) for i in arr2]

    if n > m:
        for i in range(m, n):
            arr2.append(0)
    elif m > n:
        for i in range(n, m):
            arr1.append(0)

    for i in range(len(arr1)):
        if arr1[i] > arr2[i]:
            return 1
        elif arr2[i] > arr1[i]:
            return -1
    return 0

Input: '3.8.18', '3.8.27'

Output: -1


def parse_access_method(access_method: str):
    num_workers = 0
    scheduler = "threaded"
    download = access_method.startswith("download")
    local = access_method.startswith("local")
    if download or local:
        split = access_method.split(":")
        if len(split) == 1:
            split.extend(("threaded", "0"))
        elif len(split) == 2:
            split.append("threaded" if split[1].isnumeric() else "0")
        elif len(split) >= 3:
            num_integers = sum(1 for i in split if i.isnumeric())
            if num_integers != 1 or len(split) > 3:
                raise ValueError(
                    "Invalid access_method format. Expected format is one of the following: {download, download:scheduler, download:num_workers, download:scheduler:num_workers, download:num_workers:scheduler}"
                )

        access_method = "download" if download else "local"
        num_worker_index = 1 if split[1].isnumeric() else 2
        scheduler_index = 3 - num_worker_index
        num_workers = int(split[num_worker_index])
        scheduler = split[scheduler_index]
    return access_method, num_workers, scheduler

Input: 'download'

Output: ('download', 0, 'threaded')


def write_shape_info(shape_info, buffer, offset) -> int:

    if shape_info.ndim == 1:
        offset += 8
    else:
        buffer[offset : offset + 8] = struct.pack("<ii", *shape_info.shape)
        offset += 8

        buffer[offset : offset + shape_info.nbytes] = shape_info.tobytes()
        offset += shape_info.nbytes
    return offset

Output: 23


def _get_new_player_rack_list(self, num_players):
        player_rack_list = []

        for _ in range(num_players):
            this_rack = []
            for _ in range(config.PLAYER_RACK_SIZE):
                this_tile = self._draw_random_tile()
                this_rack.append(this_tile)

            player_rack_list.append(this_rack)

        return player_rack_list

Input: REPR FAILED, 4, [*, *, A, A, A, A, A, A, A, A, A, B, B, C, C, D, D, D, D, E, E, E, E, E, E, E, E, E, E, E, E, F, F, G, G, G, H, H, I, I, I, I, I, I, I, I, I, J, K, L, L, L, L, M, M, N, N, N, N, N, N, O, O, O, O, O, O, O, O, P, P, Q, R, R, R, R, R, R, S, S, S, S, T, T, T, T, T, T, U, U, U, U, V, V, W, W, X, Y, Y, Z]

Output: [[U, A, E, F, K, H, V], [U, N, E, I, N, C, I], [B, H, T, Q, O, D, T], [A, R, B, O, O, N, I]]


def _draw_random_tile(self):
        random_index = random.randrange(0, len(self.tile_bag))
        selected_tile = self.tile_bag.pop(random_index)

        return selected_tile

Input: REPR FAILED, [*, *, A, A, A, A, A, A, A, A, A, B, B, C, C, D, D, D, D, E, E, E, E, E, E, E, E, E, E, E, E, F, F, G, G, G, H, H, I, I, I, I, I, I, I, I, I, J, K, L, L, L, L, M, M, N, N, N, N, N, N, O, O, O, O, O, O, O, O, P, P, Q, R, R, R, R, R, R, S, S, S, S, T, T, T, T, T, T, U, U, U, U, V, V, W, W, X, Y, Y, Z]

Output: U


def move_is_sublist(letter_list_1, letter_list_2):
    letter_counter_1 = collections.Counter(letter_list_1)
    letter_counter_2 = collections.Counter(letter_list_2)
    for letter, cardinality in letter_counter_1.items():
        if cardinality > letter_counter_2[letter]:

            return False

    return True

Input: [1, 2, 3], [1, 2, 3, 4]

Output: True


def get_word_letter_location_set(word, start_location, is_vertical_move):
    letter_location_set = set()
    next_location_func = get_next_location_function(
        use_positive_seek=True,
        use_vertical_words=is_vertical_move
    )

    current_location = start_location
    word_iterator = iter(word)
    for character in word_iterator:
        if character == '(':
            character = next(word_iterator, None)
            while character != ')':
                current_location = next_location_func(current_location)
                character = next(word_iterator, None)

            character = next(word_iterator, None)

        if character:
            letter_location_set.add((character, current_location))
            current_location = next_location_func(current_location)

    return letter_location_set

Input: 'BAKER', ('h', 8), False

Output: {('K', ('j', 8)), ('B', ('h', 8)), ('A', ('i', 8)), ('E', ('k', 8)), ('R', ('l', 8))}


def move_is_legal(board, move_number, letter_location_set, player_rack=None):
    letter_list = [letter for letter, _ in letter_location_set]
    location_set = set(location for _, location in letter_location_set)

    return_bool = (
        move_is_rack_size_or_less(location_set) and
        move_does_not_misalign_tiles(location_set) and
        move_is_not_out_of_bounds(location_set) and
        all_move_tiles_connected(board, location_set) and
        move_does_not_stack_tiles(letter_list, location_set) and
        move_does_not_cover_tiles(board, location_set) and
        move_touches_tile(move_number, board, location_set)
    )

    if player_rack:
        player_rack_letter_list = [tile.letter for tile in player_rack]
        return_bool = return_bool and move_is_sublist(letter_list,
                                                      player_rack_letter_list)

    return return_bool

Input: abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______★_______9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, 0, {('K', ('j', 8)), ('B', ('h', 8)), ('A', ('i', 8)), ('E', ('k', 8)), ('R', ('l', 8))}, [Q, E, O, S, G, H, E, B, A, K, E, R]

Output: True


def move_is_not_out_of_bounds(location_set):
    for location in location_set:
        if location_is_out_of_bounds(location):

            return False

    return True

Input: {('j', 8), ('l', 8), ('h', 8), ('i', 8), ('k', 8)}

Output: True


def all_move_tiles_connected(board, location_set):
    column_list = [column for column, _ in location_set]
    row_list = [row for _, row in location_set]
    move_is_vertical = (len(set(column_list)) == 1)

    if move_is_vertical:
        this_column = column_list[0]
        for this_row in range(min(row_list), max(row_list) + 1):
            this_tile = board[(this_column, this_row)]
            if not (this_tile or (this_column, this_row) in location_set):

                return False
    else:
        column_range = range(
            config.LETTER_CODE_DICT[min(column_list)],
            config.LETTER_CODE_DICT[max(column_list)] + 1
        )

        this_row = row_list[0]
        for this_column_num in column_range:
            this_column = chr(this_column_num)
            this_tile = board[(this_column, this_row)]
            if not (this_tile or (this_column, this_row) in location_set):

                return False

    return True

Input: abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______★_______9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, {('j', 8), ('l', 8), ('h', 8), ('i', 8), ('k', 8)}

Output: True


def move_does_not_cover_tiles(board, location_set):
    for location in location_set:
        if board[location]:

            return False

    return True

Input: abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______★_______9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, {('j', 8), ('l', 8), ('h', 8), ('i', 8), ('k', 8)}

Output: True


def move_touches_tile(move_number, board, location_set):
    if move_number == 0:
        if board.start_square_location in location_set:
            return True
    else:
        for this_location in location_set:
            if location_touches_tile(board, this_location):
                return True

    return False

Input: 1,   abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______SCRAB___9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, {('i', 13), ('i', 10), ('i', 9), ('i', 12), ('i', 11)}

Output: True


def get_rack_tile_index(player_rack, move_letter):
    for i, rack_tile in enumerate(player_rack):
        if rack_tile.letter == move_letter:
            return i

    return None

Input: [Q, E, O, S, G, H, E, B, A, K, E, R], 'K'

Output: 9


def get_word_location_set(board, initial_location, use_vertical_words):
    word_location_set = set()

    for use_positive_seek in [True, False]:
        current_location = initial_location
        current_tile = board[current_location]
        next_location_func = get_next_location_function(use_positive_seek,
                                                        use_vertical_words)

        while current_tile:
            word_location_set.add(current_location)
            current_location = next_location_func(current_location)
            if location_is_out_of_bounds(current_location):
                current_tile = None
            else:
                current_tile = board[current_location]

    if len(word_location_set) > 1:
        return frozenset(word_location_set)
    else:
        return frozenset()

Input: abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______BAKER___9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, ('j', 8), True

Output: frozenset()


def get_word_set_total_score(board, word_set, num_move_locations):
    total_score = 0
    word_score = 0

    for word_location_set in word_set:
        word_score = 0
        word_multiplier = 1

        for location in word_location_set:
            square = board.board_square_dict[location]
            word_multiplier *= square.word_multiplier
            word_score += square.tile.point_value * square.letter_multiplier

        word_score *= word_multiplier
        total_score += word_score

    if num_move_locations == config.PLAYER_RACK_SIZE:
        total_score += config.BINGO_SCORE

    return total_score

Input: abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______BAKER___9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, {frozenset(), frozenset({('h', 8), ('j', 8), ('l', 8), ('i', 8), ('k', 8)})}, 5

Output: 24


def location_touches_tile(board, location):
    adjacent_location_set = get_adjacent_location_set(location)
    for adjacent_location in adjacent_location_set:
        if board[adjacent_location]:
            return True

    return False

Input: abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______SCRAB___9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, ('i', 13)

Output: False


def rolling_mean_by_h(x, h, w, name):

    df = pd.DataFrame({'x': x, 'h': h})
    df2 = (
        df.groupby('h').agg(['sum', 'count']).reset_index().sort_values('h')
    )
    xs = df2['x']['sum'].values
    ns = df2['x']['count'].values
    hs = df2.h.values

    trailing_i = len(df2) - 1
    x_sum = 0
    n_sum = 0

    res_x = np.empty(len(df2))

    for i in range(len(df2) - 1, -1, -1):
        x_sum += xs[i]
        n_sum += ns[i]
        while n_sum >= w:

            excess_n = n_sum - w
            excess_x = excess_n * xs[i] / ns[i]
            res_x[trailing_i] = (x_sum - excess_x)/ w
            x_sum -= xs[trailing_i]
            n_sum -= ns[trailing_i]
            trailing_i -= 1

    res_h = hs[(trailing_i + 1):]
    res_x = res_x[(trailing_i + 1):]

    return pd.DataFrame({'horizon': res_h, name: res_x})

Input: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), 1, 'x'

Output: horizon    x0        0  0.01        1  1.02        2  2.03        3  3.04        4  4.05        5  5.06        6  6.07        7  7.08        8  8.09        9  9.0


def rolling_median_by_h(x, h, w, name):

    df = pd.DataFrame({'x': x, 'h': h})
    grouped = df.groupby('h')
    df2 = grouped.size().reset_index().sort_values('h')
    hs = df2['h']

    res_h = []
    res_x = []

    i = len(hs) - 1
    while i >= 0:
        h_i = hs[i]
        xs = grouped.get_group(h_i).x.tolist()

        next_idx_to_add = np.array(h == h_i).argmax() - 1
        while (len(xs) < w) and (next_idx_to_add >= 0):

            xs.append(x[next_idx_to_add])
            next_idx_to_add -= 1
        if len(xs) < w:

            break
        res_h.append(hs[i])
        res_x.append(np.median(xs))
        i -= 1
    res_h.reverse()
    res_x.reverse()
    return pd.DataFrame({'horizon': res_h, name: res_x})

Input: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), 1, 'x'

Output: horizon    x0        0  0.01        1  1.02        2  2.03        3  3.04        4  4.05        5  5.06        6  6.07        7  7.08        8  8.09        9  9.0


def create_request_parameters(parent, request_model, params=None, index=None):

    if params is None:
        params = {}

    for param in request_model.params:
        source = param.source
        target = param.target

        if source == 'identifier':

            value = getattr(parent, xform_name(param.name))
        elif source == 'data':

            value = get_data_member(parent, param.path)
        elif source in ['string', 'integer', 'boolean']:

            value = param.value
        elif source == 'input':

            continue
        else:
            raise NotImplementedError(f'Unsupported source type: {source}')

        build_param_structure(params, target, value, index)

    return params

Input: dynamodb.Table(name='MyTable'), {_definition=OrderedDict([('operation', 'Scan'), ('params', [OrderedDict([('target', 'TableName'), ('source', 'identifier'), ('name', 'Name')])])]), operation='Scan'}, None, None

Output: {'TableName': 'MyTable'}


def suggest_type(full_text, text_before_cursor):

    word_before_cursor = last_word(text_before_cursor,
            include='many_punctuations')

    identifier = None

    try:

        if word_before_cursor:
            if word_before_cursor.endswith(
                    '(') or word_before_cursor.startswith('\\'):
                parsed = sqlparse.parse(text_before_cursor)
            else:
                parsed = sqlparse.parse(
                    text_before_cursor[:-len(word_before_cursor)])

                p = sqlparse.parse(word_before_cursor)[0]

                if p.tokens and isinstance(p.tokens[0], Identifier):
                    identifier = p.tokens[0]
        else:
            parsed = sqlparse.parse(text_before_cursor)
    except (TypeError, AttributeError):
        return [{'type': 'keyword'}]

    if len(parsed) > 1:

        current_pos = len(text_before_cursor)
        stmt_start, stmt_end = 0, 0

        for statement in parsed:
            stmt_len = len(str(statement))
            stmt_start, stmt_end = stmt_end, stmt_end + stmt_len

            if stmt_end >= current_pos:
                text_before_cursor = full_text[stmt_start:current_pos]
                full_text = full_text[stmt_start:]
                break

    elif parsed:

        statement = parsed[0]
    else:

        statement = None

    if statement:

        tok1 = statement.token_first()
        if tok1 and (tok1.value == 'source' or tok1.value.startswith('\\')):
            return suggest_special(text_before_cursor)

    last_token = statement and statement.token_prev(len(statement.tokens))[1] or ''

    return suggest_based_on_last_token(last_token, text_before_cursor,
                                       full_text, identifier)

Input: 'SELECT  FROM tabl', 'SELECT '

Output: [{'type': 'column', 'tables': [(None, 'tabl', None)]}, {'type': 'function', 'schema': []}, {'type': 'alias', 'aliases': ['tabl']}, {'type': 'keyword'}]


def parse_special_command(sql):
    command, _, arg = sql.partition(' ')
    verbose = '+' in command
    command = command.strip().replace('+', '')
    return (command, verbose, arg.strip())

Output: ('\\.', False, '')


def strip_matching_quotes(s):

    if (isinstance(s, basestring) and len(s) >= 2 and
            s[0] == s[-1] and s[0] in ('"', "'")):
        s = s[1:-1]
    return s

Input: '"May the force be with you."'

Output: 'May the force be with you.'


def format_uptime(uptime_in_seconds):

    m, s = divmod(int(uptime_in_seconds), 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)

    uptime_values = []

    for value, unit in ((d, 'days'), (h, 'hours'), (m, 'min'), (s, 'sec')):
        if value == 0 and not uptime_values:

            continue
        elif value == 1 and unit.endswith('s'):

            unit = unit[:-1]
        uptime_values.append('{0} {1}'.format(value, unit))

    uptime = ' '.join(uptime_values)
    return uptime

Output: '59 sec'


def _grid(string: str, attr: Mapping[str, str]) -> Grid:
    method = None
    try:
        if attr["source"] in ("grid", "grid_l"):
            method = "linear"
        elif attr["source"] in ("grid_s", "grid_c"):
            method = "spline"
        elif attr["source"] in ("grid_q", "grid_n"):
            method = "nearest"
    except KeyError:
        if re.fullmatch(r"\S[\S ]*\.nc", string):
            method = "linear"
    if method:
        return Grid(
            file=string, x=attr.get("x", "lon"), y=attr.get("y", "lat"), method=method
        )

    raise TextParseError(f"'{string}' does not represent a grid")

Input: 'abc.nc', {}

Output: Grid(file='abc.nc', x='lon', y='lat', method='linear')


def _time(string: str) -> datetime:
    formats = [
        "%Y-%m-%dT%H:%M:%S",
        "%Y-%m-%dT%H:%M",
        "%Y-%m-%dT%H",
        "%Y-%m-%dT",
        "%Y-%m-%d",
    ]
    for format_ in formats:
        try:
            return datetime.strptime(string, format_)
        except ValueError:
            pass

    raise ValueError(f"time data '{string}' does not match format '%Y-%m-%dT%H:%M:%S'")

Output: datetime.datetime(2016, 3, 1, 21, 0, 11)


def contains_nan(stack: MutableSequence[NumberOrArray]) -> bool:
    for item in stack:
        try:
            if math.isnan(item):
                return True
        except TypeError:
            pass
    return False

Output: False


def contains_array(stack: MutableSequence[NumberOrArray]) -> bool:
    for item in stack:
        if isinstance(item, np.ndarray):
            return True
    return False

Output: False


def _get_x(stack: MutableSequence[NumberOrArray]) -> NumberOrArray:
    if not stack:
        raise StackUnderflowError(
            "attempted to get element from the 'stack' but the stack is empty"
        )
    return stack.pop()


def _simulate(self) -> Tuple[int, int]:

        inputs = 0
        outputs = 0
        for token_ in self._tokens:
            outputs -= token_.pops
            inputs = max(inputs, -outputs)
            outputs += token_.puts
        return inputs, outputs + inputs

Input: Expression([Literal(1)]), Literal(1)

Output: (0, 1)


def contains_sublist(list_: List[Any], sublist: List[Any]) -> bool:

    if not sublist:
        return False
    for i in range(len(list_)):
        if list_[i] == sublist[0] and list_[i : i + len(sublist)] == sublist:
            return True
    return False

Input: [1, 2, 3, 4], [1, 2]

Output: True


def delete_sublist(list_: List[Any], sublist: List[Any]) -> List[Any]:

    if not sublist:
        return list_[:]
    for i in range(len(list_)):
        if list_[i] == sublist[0] and list_[i : i + len(sublist)] == sublist:
            return list_[:i] + list_[i + len(sublist) :]
    return list_[:]

Input: [1, 2, 3, 4], [1, 2]

Output: [3, 4]


def bounded_product(sequence, n=None, seed=None):

    p = list(itertools.product(*sequence))
    if seed is not None:
        random.seed(seed)
    random.shuffle(p)
    return p if n is None else p[:n]

Input: ([{'type': 'adam', 'params': {'lr': 0.0006}}, {'type': 'onebitadam', 'params': {'lr': 0.0006}}, {'type': 'cpu_adam', 'params': {'lr': 0.0006}}, {'type': 'cpu_torch_adam', 'params': {'lr': 0.0006}}, {'type': 'sm3', 'params': {'lr': 0.0006}}, {'type': 'lion', 'params': {'lr': 0.0006}}, {'type': 'madgrad_wd', 'params': {'lr': 0.0006}}],), 50, None

Output: [({'type': 'cpu_adam', 'params': {'lr': 0.0006}},), ({'type': 'sm3', 'params': {'lr': 0.0006}},), ({'type': 'onebitadam', 'params': {'lr': 0.0006}},), ({'type': 'lion', 'params': {'lr': 0.0006}},), ({'type': 'adam', 'params': {'lr': 0.0006}},), ({'type': 'madgrad_wd', 'params': {'lr': 0.0006}},), ({'type': 'cpu_torch_adam', 'params': {'lr': 0.0006}},)]


def expand_attention_types(attention_config, num_layers):

    if all([isinstance(i, str) for i in attention_config]):
        return attention_config
    newlist = []
    for item in attention_config:

        if item[1] == "all":
            assert num_layers % len(item[0]) == 0, (
                f"Number of layers ({num_layers}) is not divisible by the length "
                f"of pattern: {item[0]}"
            )
            return item[0] * (num_layers // len(item[0]))
        for _ in range(item[1]):
            newlist.extend(item[0])
    return newlist

Input: [[['global'], 2]], 2

Output: ['global', 'global']


def get_args(input_args=None):
    parser = argparse.ArgumentParser()
    group = parser.add_argument_group(title="input data")
    group.add_argument(
        "--input",
        type=str,
        required=True,
        help="Path to input jsonl files or lmd archive(s) - if using multiple archives, put them in a comma separated "
        "list",
    )
    group.add_argument(
        "--jsonl-keys",
        nargs="+",
        default=["text"],
        help="space separate listed of keys to extract from jsonl. Defa",
    )
    group.add_argument(
        "--num-docs",
        default=None,
        help="Optional: Number of documents in the input data (if known) for an accurate progress bar.",
        type=int,
    )
    group = parser.add_argument_group(title="tokenizer")
    group.add_argument(
        "--tokenizer-type",
        type=str,
        required=True,
        choices=[
            "HFGPT2Tokenizer",
            "HFTokenizer",
            "GPT2BPETokenizer",
            "CharLevelTokenizer",
            "TiktokenTokenizer",
            "SPMTokenizer",
        ],
        help="What type of tokenizer to use.",
    )
    group.add_argument(
        "--vocab-file", type=str, default=None, help="Path to the vocab file"
    )
    group.add_argument(
        "--merge-file",
        type=str,
        default=None,
        help="Path to the BPE merge file (if necessary).",
    )
    group.add_argument(
        "--append-eod",
        action="store_true",
        help="Append an <eod> token to the end of a document.",
    )
    group.add_argument("--ftfy", action="store_true", help="Use ftfy to clean text")
    group = parser.add_argument_group(title="output data")
    group.add_argument(
        "--output-prefix",
        type=str,
        required=True,
        help="Path to binary output file without suffix",
    )
    group.add_argument(
        "--dataset-impl",
        type=str,
        default="mmap",
        choices=["lazy", "cached", "mmap"],
        help="Dataset implementation to use. Default: mmap",
    )

    group = parser.add_argument_group(title="runtime")
    group.add_argument(
        "--workers", type=int, default=1, help="Number of worker processes to launch"
    )
    group.add_argument(
        "--log-interval",
        type=int,
        default=100,
        help="Interval between progress updates",
    )
    args = parser.parse_args(input_args)
    args.keep_empty = False

    args.rank = 0
    args.make_vocab_size_divisible_by = 128
    args.model_parallel_size = 1

    return args

Input: ['--input', './tests/data/enwik8_first100.txt', '--output-prefix', './tests/data/enwik8_first100', '--vocab', 'gpt2', '--tokenizer-type', 'HFGPT2Tokenizer', '--merge-file', './data/gpt2-merges.txt', '--append-eod']

Output: Namespace(input='./tests/data/enwik8_first100.txt', jsonl_keys=['text'], num_docs=None, tokenizer_type='HFGPT2Tokenizer', vocab_file='gpt2', merge_file='./data/gpt2-merges.txt', append_eod=True, ftfy=False, output_prefix='./tests/data/enwik8_first100', dataset_impl='mmap', workers=1, log_interval=100, keep_empty=False, rank=0, make_vocab_size_divisible_by=128, model_parallel_size=1)


def gen_search_gzh_url(keyword, page=1):

        assert isinstance(page, int) and page > 0

        qs_dict = OrderedDict()
        qs_dict['type'] = _search_type_gzh
        qs_dict['page'] = page
        qs_dict['ie'] = 'utf8'
        qs_dict['query'] = keyword

        return 'http://weixin.sogou.com/weixin?{}'.format(urlencode(qs_dict))

Input: '高考', 1


def __handle_content_url(content_url):
        content_url = replace_html(content_url)
        return ('http://mp.weixin.qq.com{}'.format(
            content_url) if 'http://mp.weixin.qq.com' not in content_url else content_url) if content_url else ''


def glob_absolute_paths(file: Union[str, Path]) -> List[Path]:
            path = Path(file)
            if not path.is_absolute():
                path = base / path
            return sorted(path.parent.glob(path.name), key=lambda p: p.stem)

Input: 'aggrid.js', PosixPath('/local/rcs/XXX/code/pytrace-collector/logs/self_collected/tried/zauberzeug+nicegui/zauberzeug+nicegui/nicegui/elements')

Output: [PosixPath('/local/rcs/XXX/code/pytrace-collector/logs/self_collected/tried/zauberzeug+nicegui/zauberzeug+nicegui/nicegui/elements/aggrid.js')]


def compute_key(path: Path) -> str:

    nicegui_base = Path(__file__).parent
    is_file = path.is_file()
    try:
        path = path.relative_to(nicegui_base)
    except ValueError:
        pass
    if is_file:
        return f'{hash_file_path(path.parent)}/{path.name}'
    return f'{hash_file_path(path)}'

Input: PosixPath('/local/rcs/XXX/code/pytrace-collector/logs/self_collected/tried/zauberzeug+nicegui/zauberzeug+nicegui/nicegui/elements/aggrid.js')


def _class_is_prefixed_with_native(class_name: str) -> bool:

    for prefix in native_prefixes:

        if class_name.startswith(prefix):
            return True

    return False

Input: 'FooBar'

Output: False


def sizeof_fmt(num: float, suffix: str = 'B') -> str:

    for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
        if abs(num) < 1024.0:
            return '%3.1f %s%s' % (num, unit, suffix)
        num /= 1024.0
    return '%.1f %s%s' % (num, 'Yi', suffix)

Input: 249.0, 'B'

Output: '249.0 B'


def aes(text, key):
    pad = 16 - len(text) % 16
    text = text + bytearray([pad] * pad)
    encryptor = AES.new(key, 2, b"0102030405060708")
    ciphertext = encryptor.encrypt(text)
    return base64.b64encode(ciphertext)

Input: b'{"ids": [347230, 496619464, 405998841, 28012031], "br": 320000, "csrf_token": ""}', b'0CoJUm6Qyw8W8jud'


def rsa(text, pubkey, modulus):
    text = text[::-1]
    rs = pow(int(binascii.hexlify(text), 16), int(pubkey, 16), int(modulus, 16))
    return format(rs, "x").zfill(256)


def _get_nested(data, key):

    if not data or not isinstance(data, dict):
        return None
    if '.' not in key:
        return data.get(key)
    if key in data:
        return data[key]

    parts = key.split('.')
    for i in range(len(parts))[::-1]:
        prefix = ".".join(parts[:i])
        if prefix in data:
            return _get_nested(data[prefix], ".".join(parts[i:]))

    return None

Input: {'server': {'address': '0.0.0.0'}, 'cache': {'type': 'redis'}}, 'cache.type'

Output: 'redis'


def layer_template(layer_name: str, idx: int) -> Tuple[str, int]:
    split = layer_name.split(".")
    number = int(split[idx])
    split[idx] = "{}"
    from_name = ".".join(split)
    return from_name, number

Input: 'model.layers.0.self_attn.q_proj.weight', 2

Output: ('model.layers.{}.self_attn.q_proj.weight', 0)


def rowcol_to_a1(row, col):

    row = int(row)
    col = int(col)

    if row < 1 or col < 1:
        raise IncorrectCellLabel("({}, {})".format(row, col))

    div = col
    column_label = ""

    while div:
        (div, mod) = divmod(div, 26)
        if mod == 0:
            mod = 26
            div -= 1
        column_label = chr(mod + MAGIC_NUMBER) + column_label

    label = "{}{}".format(column_label, row)

    return label

Input: 4, 4

Output: 'D4'


def a1_to_rowcol(label):

    m = CELL_ADDR_RE.match(label)
    if m:
        column_label = m.group(1).upper()
        row = int(m.group(2))

        col = 0
        for i, c in enumerate(reversed(column_label)):
            col += (ord(c) - MAGIC_NUMBER) * (26**i)
    else:
        raise IncorrectCellLabel(label)

    return (row, col)

Output: (1, 2)


def fill_gaps(L, rows=None, cols=None, padding_value=""):

    try:
        max_cols = max(len(row) for row in L) if cols is None else cols
        max_rows = len(L) if rows is None else rows

        pad_rows = max_rows - len(L)

        if pad_rows:
            L = L + ([[]] * pad_rows)

        return [rightpad(row, max_cols, padding_value=padding_value) for row in L]
    except ValueError:
        return []

Input: [['', 'Dummy']], None, None, ''

Output: [['', 'Dummy']]


def _a1_to_rowcol_unbounded(label):

    m = A1_ADDR_ROW_COL_RE.match(label)
    if m:
        column_label, row = m.groups()

        if column_label:
            col = 0
            for i, c in enumerate(reversed(column_label.upper())):
                col += (ord(c) - MAGIC_NUMBER) * (26**i)
        else:
            col = inf

        if row:
            row = int(row)
        else:
            row = inf
    else:
        raise IncorrectCellLabel(label)

    return (row, col)

Output: (1, 1)


def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):

    assert isinstance(commands, list)
    process = None
    for command in commands:
        try:
            dispcmd = str([command] + args)

            process = subprocess.Popen(
                [command] + args,
                cwd=cwd,
                env=env,
                stdout=subprocess.PIPE,
                stderr=(subprocess.PIPE if hide_stderr else None),
            )
            break
        except OSError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = process.communicate()[0].strip().decode()
    if process.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, process.returncode
    return stdout, process.returncode

Input: ['git'], ['rev-parse', '--git-dir'], '/local/rcs/XXX/code/pytrace-collector/logs/self_collected/tried/danielgatis+rembg/danielgatis+rembg', False, True, None

Output: ('.git', 0)


def render_pep440_feature(pieces):

    if pieces["closest-tag"] and pieces["develop"]:
        rendered = pieces["closest-tag"]
        distance_to_develop = pieces["distance-to-develop"]
        distance_to_merge = pieces["distance-to-master"]
        distance_merge_to_tag = (pieces["distance"] - distance_to_merge)
        distance_dev_to_merge = (distance_to_merge - distance_to_develop)
        if (distance_merge_to_tag > 0):
            rendered += ".%d" % distance_merge_to_tag
        rendered += ".post.dev%d" % distance_dev_to_merge
        rendered += plus_or_dot(pieces)
        rendered += "g%s" % pieces["short"]
        rendered += ".%s" % pieces["branch"]
        rendered += ".%d" % distance_to_develop
    else:

        rendered = "0.post.dev%d" % (pieces["distance"] - 1)
        rendered += plus_or_dot(pieces)
        rendered += "g%s" % pieces["short"]
    if pieces["dirty"]:
        rendered += ".dirty"
    return rendered

Input: {'long': 'e60d005d389cb31b6e99f937e35adbe3fccb7aaf', 'short': 'e60d005', 'error': None, 'dirty': False, 'closest-tag': '0.8', 'distance': 3, 'branch': 'HEAD', 'distance-to-master': 0, 'develop': None, 'distance-to-develop': None, 'date': '2018-05-05T22:17:58-0700', 'authors': ['Padraic Shafer']}

Output: '0.post.dev2+ge60d005'


def forward(ctx, a, b):
        new_tensor = Tensor(a.data + b.data)
        return new_tensor

Input: {}, {data=array([[1., 2., 3., 4.],       [5., 6., 7., 8.]]), grad=None, grad_fn=None, is_leaf=True, require_grad=True}

Output: {data=array([[-3.4401897, -2.4401897, -1.4401897, -0.4401897],       [-3.4401897, -2.4401897, -1.4401897, -0.4401897]]), grad=None, grad_fn=None, is_leaf=True, require_grad=False}


def backward(ctx, grad_output):
        b_grad = grad_output * 1
        a_grad = grad_output * 1
        return a_grad, b_grad

Input: {store=(array([[9.11881966e-04, 2.47875218e-03, 6.73794700e-03, 1.83156389e-02],       [4.97870684e-02, 1.35335283e-01, 3.67879441e-01, 1.00000000e+00]]), array([[0.02844422],       [1.55300179]]))}, array([[1., 1., 1., 1.],       [1., 1., 1., 1.]])

Output: array([[ 0.87176559,  0.65142273,  0.05246873, -1.57565704],       [ 0.87176559,  0.65142273,  0.05246873, -1.57565704]])


def compute_loc(idx, shape):
    loc = [0] * len(shape)
    for i in range(len(shape)):
        prod = int(np.prod(shape[i + 1:]))
        loc[i] = idx // prod
        idx = idx % prod
    return tuple(loc)

Input: 0, (2, 4)

Output: (0, 0)


def create_mock_page_scrapers(number_mock_scrapers):
    mock_scrapers = []
    for _ in range(0, number_mock_scrapers):
        mock_scrapers.append(mock.create_autospec(PageScraper))
    return mock_scrapers

Output: [<MagicMock spec='PageScraper' id='140669237222752'>]


def encode_number(n):
    b128_digits = []
    while n:
        b128_digits.insert(0, (n & 0x7f) | 0x80)
        n = n >> 7
    if not b128_digits:
        b128_digits.append(0)
    b128_digits[-1] &= 0x7f
    return b''.join([int.to_bytes(d, 1, 'big') for d in b128_digits])


def getLimit(self, symbol, limit):
        pass

Input: [{'symbol': 'BTC/USDT', 'id': '0', 'i': 0}, {'symbol': 'BTC/USDT', 'id': '1', 'i': 1}, {'symbol': 'BTC/USDT', 'id': '2', 'i': 2}, {'symbol': 'BTC/USDT', 'id': '3', 'i': 3}, {'symbol': 'BTC/USDT', 'id': '4', 'i': 4}], 'BTC/USDT', None, {'symbol': 'BTC/USDT', 'id': '0', 'i': 0}, {'symbol': 'BTC/USDT', 'id': '1', 'i': 1}, {'symbol': 'BTC/USDT', 'id': '2', 'i': 2}, {'symbol': 'BTC/USDT', 'id': '3', 'i': 3}, {'symbol': 'BTC/USDT', 'id': '4', 'i': 4}

Output: 5


def key_exists(dictionary, key):
        if hasattr(dictionary, '__getitem__') and not isinstance(dictionary, str):
            if isinstance(dictionary, list) and type(key) is not int:
                return False
            try:
                value = dictionary[key]
                return value is not None and value != ''
            except LookupError:
                return False
        return False

Input: (None, {'taker': [[0.0, 0.0005], [250.0, 0.00045], [2500.0, 0.0004], [7500.0, 0.0003], [22500.0, 0.00025], [50000.0, 0.00024], [100000.0, 0.00024], [200000.0, 0.00024], [400000.0, 0.00024], [750000.0, 0.00024]], 'maker': [[0.0, 0.0001], [250.0, 8e-05], [2500.0, 5e-05], [7500.0, 3e-06], [22500.0, 0.0], [50000.0, -5e-05], [100000.0, -6e-05], [200000.0, -7e-05], [400000.0, -8e-05], [750000.0, -9e-05]]})

Output: {'taker': [[0.0, 0.0005], [250.0, 0.00045], [2500.0, 0.0004], [7500.0, 0.0003], [22500.0, 0.00025], [50000.0, 0.00024], [100000.0, 0.00024], [200000.0, 0.00024], [400000.0, 0.00024], [750000.0, 0.00024]], 'maker': [[0.0, 0.0001], [250.0, 8e-05], [2500.0, 5e-05], [7500.0, 3e-06], [22500.0, 0.0], [50000.0, -5e-05], [100000.0, -6e-05], [200000.0, -7e-05], [400000.0, -8e-05], [750000.0, -9e-05]]}


def safe_value(dictionary, key, default_value=None):
        return dictionary[key] if Exchange.key_exists(dictionary, key) else default_value

Input: (None, {'TRC20': 'TRX'})

Output: {'TRC20': 'TRX'}


def extend(*args):
        if args is not None:
            result = None
            if type(args[0]) is collections.OrderedDict:
                result = collections.OrderedDict()
            else:
                result = {}
            for arg in args:
                result.update(arg)
            return result
        return {}

Input: ({'refillRate': 0.02, 'delay': 0.001, 'capacity': 1.0, 'defaultCost': 1.0}, {})

Output: {'refillRate': 0.02, 'delay': 0.001, 'capacity': 1.0, 'defaultCost': 1.0}


def sort_by(array, key, descending=False, default=0):
        return sorted(array, key=lambda k: k[key] if k[key] is not None else default, reverse=descending)

Input: (None, {'id': 'foobar', 'symbol': 'FOO/BAR', 'base': 'FOO', 'quote': 'BAR', 'taker': 0.0025, 'maker': 0.001, 'precision': {'price': 8, 'amount': 8}})

Output: {'id': 'foobar', 'symbol': 'FOO/BAR', 'base': 'FOO', 'quote': 'BAR', 'taker': 0.0025, 'maker': 0.001, 'precision': {'price': 8, 'amount': 8}}


def leftmost_bit(x):
            assert x > 0
            result = 1
            while result <= x:
                result = 2 * result
            return result // 2


def inverse_mod(a, m):

    if a < 0 or m <= a:
        a = a % m

    c, d = a, m
    uc, vc, ud, vd = 1, 0, 0, 1
    while c != 0:
        q, c, d = divmod(d, c) + (c,)
        uc, vc, ud, vd = ud - q * uc, vd - q * vc, uc, vc

    assert d == 1
    if ud > 0:
        return ud
    else:
        return ud + m

Input: 65341020041517633956166170261014086368942546761318486551877808671514674964848, 115792089237316195423570985008687907853269984665640564039457584007908834671663


def generate_k(order, secexp, hash_func, data, retry_gen=0, extra_entropy=b''):

    qlen = bit_length(order)
    holen = hash_func().digest_size
    rolen = (qlen + 7) / 8
    bx = number_to_string(secexp, order) + bits2octets(data, order) + \
        extra_entropy

    v = b'\x01' * holen

    k = b'\x00' * holen

    k = hmac.new(k, v + b'\x00' + bx, hash_func).digest()

    v = hmac.new(k, v, hash_func).digest()

    k = hmac.new(k, v + b'\x01' + bx, hash_func).digest()

    v = hmac.new(k, v, hash_func).digest()

    while True:

        t = b''

        while len(t) < rolen:
            v = hmac.new(k, v, hash_func).digest()
            t += v

        secret = bits2int(t, qlen)

        if secret >= 1 and secret < order:
            if retry_gen <= 0:
                return secret
            else:
                retry_gen -= 1

        k = hmac.new(k, v + b'\x00', hash_func).digest()
        v = hmac.new(k, v, hash_func).digest()

Input: 115792089237316195423570985008687907852837564279074904382605163141518161494337, 11806252235961651298089590628336806290921645495320214372650577192963691649562, <built-in function openssl_sha256>, b'\xa7?\xcf3\x96@\x92\x92\x07(\x1f\xb8\xe08\x88H\x06\xe2\xeb\x08@\xf2$V\x94\xdb\xba\x1d\\\xc8\x9ee', 0, b''


def bit_length(num):

    s = bin(num)
    s = s.lstrip('-0b')
    return len(s)


def bits2octets(data, order):
    z1 = bits2int(data, bit_length(order))
    z2 = z1 - order

    if z2 < 0:
        z2 = z1

    return number_to_string_crop(z2, order)

Input: b'\xa7?\xcf3\x96@\x92\x92\x07(\x1f\xb8\xe08\x88H\x06\xe2\xeb\x08@\xf2$V\x94\xdb\xba\x1d\\\xc8\x9ee', 115792089237316195423570985008687907852837564279074904382605163141518161494337

Output: b'\xa7?\xcf3\x96@\x92\x92\x07(\x1f\xb8\xe08\x88H\x06\xe2\xeb\x08@\xf2$V\x94\xdb\xba\x1d\\\xc8\x9ee'


def __str__(self):
        self.reduce()
        sign = '-' if self.integer < 0 else ''
        integer_array = list(str(abs(self.integer)).rjust(self.decimals, '0'))
        index = len(integer_array) - self.decimals
        if index == 0:
            item = '0.'
        elif self.decimals < 0:
            item = '0' * (-self.decimals)
        elif self.decimals == 0:
            item = ''
        else:
            item = '.'
        integer_array.insert(index, item)
        return sign + ''.join(integer_array)

Input: Precise(1393.938), 10, 3, 1393938

Output: '1393.938'


def string_abs(string):
        if string is None:
            return None
        return str(Precise(string).abs())

Input: Precise(0.001434784043479695), 10, 18, 1434784043479695

Output: '0.001434784043479695'


def string_add(string1, string2):
        if string1 is None and string2 is None:
            return None
        if string1 is None:
            return string2
        elif string2 is None:
            return string1
        return str(Precise(string1).add(Precise(string2)))

Input: Precise(1393.938), 10, 3, 1393938

Output: '1393.938'


def string_sub(string1, string2):
        if string1 is None or string2 is None:
            return None
        return str(Precise(string1).sub(Precise(string2)))

Input: Precise(69696900000.00000002), 10, 8, 6969690000000000002

Output: '69696900000.00000002'


def string_div(string1, string2, precision=18):
        if string1 is None or string2 is None:
            return None
        string2_precise = Precise(string2)
        if string2_precise.integer == 0:
            return None
        return str(Precise(string1).div(string2_precise, precision))

Input: Precise(69696899999.99999998), 10, 8, 6969689999999999998

Output: '69696899999.99999998'


def reduce(self):
        string = str(self.integer)
        start = len(string) - 1
        if start == 0:
            if string == "0":
                self.decimals = 0
            return self
        for i in range(start, -1, -1):
            if string[i] != '0':
                break
        difference = start - i
        if difference == 0:
            return self
        self.decimals -= difference
        self.integer = int(string[:i + 1])

Input: Precise(30), 10, -1, 3

Output: '30'


def string_min(string1, string2):
        if string1 is None or string2 is None:
            return None
        return str(Precise(string1).min(Precise(string2)))

Input: Precise(5.534), 10, 3, 5534

Output: Precise(5.534)


def div(self, other, precision=18):
        distance = precision - self.decimals + other.decimals
        if distance == 0:
            numerator = self.integer
        elif distance < 0:
            exponent = self.base ** -distance
            numerator = self.integer // exponent
        else:
            exponent = self.base ** distance
            numerator = self.integer * exponent
        result, mod = divmod(numerator, other.integer)

        result = result + 1 if result < 0 and mod else result
        return Precise(result, precision)

Input: Precise(0.00000002), Precise(69696900000), 1, 10, 8, 2

Output: Precise(0)


def string_neg(string):
        if string is None:
            return None
        return str(Precise(string).neg())

Input: Precise(213), 10, 0, 213

Output: '213'


def string_mod(string1, string2):
        if string1 is None or string2 is None:
            return None
        return str(Precise(string1).mod(Precise(string2)))

Input: Precise(-213), 10, 0, -213

Output: '-213'


def string_max(string1, string2):
        if string1 is None or string2 is None:
            return None
        return str(Precise(string1).max(Precise(string2)))

Input: Precise(0), 10, 0, 0

Output: '0'


def string_gt(string1, string2):
        if string1 is None or string2 is None:
            return None
        return Precise(string1).gt(Precise(string2))

Input: Precise(0), 10, 0, 0

Output: '0'


def _retryable_test_not_exception_message_delay(thing):
    return thing.go()

Input: {counter=0, count=3}

Output: True


def _retryable_test_with_unless_exception_type_name(thing):
    return thing.go()

Input: {counter=0, count=5}

Output: True


def _retryable_test_with_unless_exception_type_no_input(thing):
    return thing.go()

Input: {counter=0, count=5}

Output: True


def _retryable_test_with_unless_exception_type_name_attempt_limit(thing):
    return thing.go()

Input: {counter=0, count=2}

Output: True


def _import_plugins(plugin_names):
    plugins = []
    for name, path in plugin_names.items():
        log.debug("Importing plugin %s: %s", name, path)
        if '.' not in path:
            plugins.append(__import__(path))
        else:
            package, module = path.rsplit('.', 1)
            module = __import__(path, fromlist=[module])
            plugins.append(module)
    return plugins

Input: {'__builtin__': 'awscli.handlers'}

Output: [<module 'awscli.handlers' from '/local/rcs/XXX/code/pytrace-collector/logs/self_collected/tried/aws+aws-cli/aws+aws-cli/awscli/handlers.py'>]


def dict_to_ini_section(ini_dict, section_header):
    section_str = f'[{section_header}]\n'
    for key, value in ini_dict.items():
        if isinstance(value, dict):
            section_str += f"{key} =\n"
            for new_key, new_value in value.items():
                section_str += f"  {new_key}={new_value}\n"
        else:
            section_str += f"{key}={value}\n"
    return section_str + "\n"

Input: {'aws_access_key_id': '123', 'aws_secret_access_key': '456', 'region': 'fake-region-10', 'endpoint_url': 'https://global.endpoint.aws'}, 'profile service_global_only'

Output: '[profile service_global_only]\naws_access_key_id=123\naws_secret_access_key=456\nregion=fake-region-10\nendpoint_url=https://global.endpoint.aws\n\n'


def load_translation(self) -> "I18N":

        try:
            dir_path = os.path.dirname(os.path.realpath(__file__))
            prompts_path = os.path.join(
                dir_path, f"../translations/{self.language}.json"
            )

            with open(prompts_path, "r") as f:
                self._translations = json.load(f)
        except FileNotFoundError:
            raise ValidationError(
                f"Trasnlation file for language '{self.language}' not found."
            )
        except json.JSONDecodeError:
            raise ValidationError(f"Error decoding JSON from the prompts file.")
        return self

Input: I18N(language='en'), {'language': 'en'}, None, set(), {}, 'en'

Output: I18N(language='en')


def _to_str(size, suffixes, base):

    try:
        size = int(size)
    except ValueError:
        raise TypeError("filesize requires a numeric value, not {!r}".format(size))
    if size == 1:
        return "1 byte"
    elif size < base:
        return "{:,} bytes".format(size)

    for i, suffix in enumerate(suffixes, 2):
        unit = base ** i
        if size < unit:
            break
    return "{:,.1f} {}".format((base * size / unit), suffix)

Input: 1024, ('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'), 1024

Output: '1.0 KiB'


def decode_linux(line, match):
    perms, links, uid, gid, size, mtime, name = match.groups()
    is_link = perms.startswith("l")
    is_dir = perms.startswith("d") or is_link
    if is_link:
        name, _, _link_name = name.partition("->")
        name = name.strip()
        _link_name = _link_name.strip()
    permissions = Permissions.parse(perms[1:])

    mtime_epoch = _parse_time(mtime)

    name = unicodedata.normalize("NFC", name)

    raw_info = {
        "basic": {"name": name, "is_dir": is_dir},
        "details": {
            "size": int(size),
            "type": int(ResourceType.directory if is_dir else ResourceType.file),
        },
        "access": {"permissions": permissions.dump()},
        "ftp": {"ls": line},
    }
    access = raw_info["access"]
    details = raw_info["details"]
    if mtime_epoch is not None:
        details["modified"] = mtime_epoch

    access["user"] = uid
    access["group"] = gid

    return raw_info

Input: 'lrwxrwxrwx    1 0        0              19 Jan 18  2006 debian -> ./pub/mirror/debian', <re.Match object; span=(0, 85), match='lrwxrwxrwx    1 0        0              19 Jan 18>

Output: {'basic': {'name': 'debian', 'is_dir': True}, 'details': {'size': 19, 'type': 1, 'modified': 1137542400.0}, 'access': {'permissions': ['g_r', 'g_w', 'g_x', 'o_r', 'o_w', 'o_x', 'u_r', 'u_w', 'u_x'], 'user': '0', 'group': '0'}, 'ftp': {'ls': 'lrwxrwxrwx    1 0        0              19 Jan 18  2006 debian -> ./pub/mirror/debian'}}


def _parse_time(t):
    t = " ".join(token.strip() for token in t.lower().split(" "))
    try:
        try:
            _t = time.strptime(t, "%b %d %Y")
        except ValueError:
            _t = time.strptime(t, "%b %d %H:%M")
    except ValueError:

        return None

    year = _t.tm_year if _t.tm_year != 1900 else time.localtime().tm_year
    month = _t.tm_mon
    day = _t.tm_mday
    hour = _t.tm_hour
    minutes = _t.tm_min
    dt = datetime.datetime(year, month, day, hour, minutes, tzinfo=UTC)

    epoch_time = (dt - epoch_dt).total_seconds()
    return epoch_time

Input: 'Jan 18  2006'

Output: 1137542400.0


def _is_ascii(s):
    if isinstance(s, str):
        for c in s:
            if ord(c) > 255:
                return False
        return True
    return _supports_unicode(s)

Input: ' 123456789#'

Output: True


def make_context(headers):

    headers = {k.lower(): v for k, v in headers.items()}

    if not all(h in headers for h in (
            TRACE_ID_HEADER.lower(), SPAN_ID_HEADER.lower())):
        return None

    context = TraceContext(
        trace_id=headers.get(TRACE_ID_HEADER.lower()),
        parent_id=headers.get(PARENT_ID_HEADER.lower(), None),
        span_id=headers.get(SPAN_ID_HEADER.lower()),
        sampled=parse_sampled(headers),
        shared=False,
        debug=parse_debug(headers),
    )
    return context

Input: {'X-B3-Flags': '0', 'X-B3-ParentSpanId': None, 'X-B3-Sampled': '1', 'X-B3-SpanId': '41baf1be2fb9bfc5', 'X-B3-TraceId': '6f9a20b5092fa5e144fd15cc31141cd4'}

Output: TraceContext(trace_id='6f9a20b5092fa5e144fd15cc31141cd4', parent_id=None, span_id='41baf1be2fb9bfc5', sampled=True, debug=False, shared=False)


def _prep_ordered_arg(desired_length, arguments=None):

    arguments = listify(arguments) if arguments is not None else [None]
    if len(arguments) != desired_length and len(arguments) != 1:
        raise ValueError("Argument length must be either 1 or the same length as "
                         "the number of transitions.")
    if len(arguments) == 1:
        return arguments * desired_length
    return arguments

Input: 3, None

Output: [None, None, None]


def quat_from_axis_angle(axis, angle):
        axis_ = np.array(axis, dtype=np.float64)
        half_angle = angle * 0.5
        ret = np.empty(4)
        ret[0] = math.cos(half_angle)
        ret[1:4] = math.sin(half_angle) * axis_
        return ret

Input: [1.0, 0.0, 0.0], 6.1086523819801535

Output: array([-0.9961947 ,  0.08715574,  0.        ,  0.        ])


def remove_component(x, *, indices):

    ma = np.ma.array(x, mask=False)
    ma.mask[indices] = True
    shape = x.shape[:-1] + (x.shape[-1] - 1,)
    return ma.compressed().reshape(shape)

Input: array([-0.9961947 ,  0.08715574,  0.        ,  0.        ], dtype=float32), (0,)

Output: array([0.08715574, 0.        , 0.        ], dtype=float32)


def base64url_decode(input: Union[bytes, str]) -> bytes:
    input_bytes = force_bytes(input)

    rem = len(input_bytes) % 4

    if rem > 0:
        input_bytes += b"=" * (4 - rem)

    return base64.urlsafe_b64decode(input_bytes)

Output: b'\x84\x9bW!\x9d\xaeH\xdedm\x07\xdb\xb53Vn\x97f\x86E|\x14\x91\xbe:v\xdc\xealBq\x88'


def to_base64url_uint(val: int) -> bytes:
    if val < 0:
        raise ValueError("Must be a positive integer")

    int_bytes = bytes_from_int(val)

    if len(int_bytes) == 0:
        int_bytes = b"\x00"

    return base64url_encode(int_bytes)

Output: b'AA'


def bytes_from_int(val: int) -> bytes:
    remaining = val
    byte_length = 0

    while remaining != 0:
        remaining >>= 8
        byte_length += 1

    return val.to_bytes(byte_length, "big", signed=False)

Output: b''


def exists(self, func):

        for element in self:
            if func(element):
                return True
        return False

Input: ['aaa', 'BBB', 'ccc'], <method 'islower' of 'str' objects>, ['aaa', 'BBB', 'ccc'], Lineage: sequence

Output: True


def for_all(self, func):

        for element in self:
            if not func(element):
                return False
        return True

Input: ['aaa', 'bbb', 'ccc'], <method 'islower' of 'str' objects>, ['aaa', 'bbb', 'ccc'], Lineage: sequence

Output: True


def to_list(self):

        self.cache()
        return self._base_sequence

Input: [['1', '2', '3', '4'], ['a', 'b', 'c', 'd']], True, [['1', '2', '3', '4'], ['a', 'b', 'c', 'd']], Lineage: sequence -> cache

Output: [['1', '2', '3', '4'], ['a', 'b', 'c', 'd']]


def sqlite3(conn, sql, parameters=None, *args, **kwargs):

    if parameters is None:
        parameters = ()

    if isinstance(conn, (sqlite3api.Connection, sqlite3api.Cursor)):
        return seq(conn.execute(sql, parameters))
    elif isinstance(conn, str):
        with sqlite3api.connect(conn, *args, **kwargs) as input_conn:
            return seq(input_conn.execute(sql, parameters))
    else:
        raise ValueError('conn must be a must be a file path or sqlite3 Connection/Cursor')

Input: 'functional/test/data/test_sqlite3.db', 'SELECT id, name FROM user;', None, (), {}

Output: [(1, 'Tom'), (2, 'Jack'), (3, 'Jane'), (4, 'Stephan')]


def _create_key_val_str(input_dict: Union[Mapping[Any, Any], Any]) -> str:

    def list_to_str(input_list: List[str]) -> str:

        converted_list = []
        for item in sorted(input_list, key=lambda x: str(x)):
            if isinstance(item, dict):
                item = _create_key_val_str(item)
            elif isinstance(item, list):
                item = list_to_str(item)

            converted_list.append(str(item))
        list_str = ", ".join(converted_list)
        return "[" + list_str + "]"

    items_list = []
    for key in sorted(input_dict.keys(), key=lambda x: str(x)):
        val = input_dict[key]
        if isinstance(val, dict):
            val = _create_key_val_str(val)
        elif isinstance(val, list):
            val = list_to_str(input_list=val)

        items_list.append(f"{key}: {val}")

    key_val_str = "{{{}}}".format(", ".join(items_list))
    return key_val_str


def _compare_with_regex(request_headers: Union[Mapping[Any, Any], Any]) -> bool:
        if strict_match and len(request_headers) != len(headers):
            return False

        for k, v in headers.items():
            if request_headers.get(k) is not None:
                if isinstance(v, re.Pattern):
                    if re.match(v, request_headers[k]) is None:
                        return False
                else:
                    if not v == request_headers[k]:
                        return False
            elif strict_match:
                return False

        return True

Input: {'Accept': 'application/json'}, {'Accept': 'application/json'}, False

Output: True


def _clean_unicode(url: str) -> str:

    urllist = list(urlsplit(url))
    netloc = urllist[1]
    if _has_unicode(netloc):
        domains = netloc.split(".")
        for i, d in enumerate(domains):
            if _has_unicode(d):
                d = "xn--" + d.encode("punycode").decode("ascii")
                domains[i] = d
        urllist[1] = ".".join(domains)
        url = urlunsplit(urllist)

    chars = list(url)
    for i, x in enumerate(chars):
        if ord(x) > 128:
            chars[i] = quote(x)

    return "".join(chars)


def class_to_tg(sub_class: str):
    trans = {"Online": "_online", "Offline": "_offline"}

    for upper, lower in trans.items():
        sub_class = sub_class.replace(upper, lower)

    return sub_class.lower()

Input: 'YYeTsOffline'

Output: 'yyets_offline'


def generate_samples_loguniform(low, high, step, base, size=1):

    samples = base ** (random.uniform(low=logb(low, base), high=logb(high, base), size=size))
    if step:
        samples = step * np.floor(samples / step)
    return samples

Input: 5.8884365535558836e-08, 2.6977394324449206e-07, None, 10, 100000

Output: array([8.36400364e-08, 2.64090744e-07, 2.64351674e-07, ...,       6.02217873e-08, 1.13953435e-07, 8.52185827e-08])


def generate_samples_uniform(low, high, step, size=1):

    samples = random.uniform(low=low,
                             high=high,
                             size=size)
    if step:
        samples = step * np.floor(samples / step)
    return samples

Input: 0, 1, None, 10000

Output: array([0.40589487, 0.11308253, 0.31209565, ..., 0.14268188, 0.68390556,       0.14199635])


def validate_uniform(search_space):

    search_space = search_space.copy()

    if type(search_space) != dict:
        raise ValueError

    if "low" not in search_space.keys():
        raise ValueError

    if "high" not in search_space.keys():
        raise ValueError

    if "low" in search_space.keys():
        if type(search_space["low"]) not in (int, float):
            raise ValueError

    if "high" in search_space.keys():
        if type(search_space["high"]) not in (int, float):
            raise ValueError

    if "high" in search_space.keys() and "low" in search_space.keys():
        if search_space["high"] <= search_space["low"]:
            raise ValueError("low <= high")

    if "step" in search_space.keys():
        if type(search_space["step"]) not in (int, float):
            raise ValueError
        if search_space["step"] >= search_space["high"]:
            raise ValueError("Step must be strictly lower than high bound.")

    search_space.setdefault("step", None)

    return search_space

Input: {'low': 0, 'high': 3.141592653589793}

Output: {'low': 0, 'high': 3.141592653589793, 'step': None}


def validate_mixture(search_space):

    search_space = search_space.copy()

    if type(search_space) != dict:
        raise ValueError

    if "parameters" not in search_space.keys():
        raise ValueError

    if type(search_space["parameters"]) != list:
        raise ValueError

    for i, parameter in enumerate(search_space["parameters"]):
        if ("category" not in parameter.keys()) or (parameter["category"] not in ("normal",
                                                                                "uniform",
                                                                                "categorical")):
            raise ValueError

        if "search_space" not in parameter.keys() or type(parameter["search_space"]) != dict:
            raise ValueError

        search_space["parameters"][i]["search_space"] = validate_search_space[
            parameter["category"]](parameter["search_space"])

    if "weights" not in search_space.keys():
        number_of_values = len(search_space["parameters"])
        search_space["probabilities"] = list(np.ones(number_of_values) / number_of_values)

    return search_space

Input: {'parameters': [{'category': 'normal', 'search_space': {'mu': 1.5707963267948966, 'sigma': 3.141592653589793, 'low': 0, 'high': 3.141592653589793, 'step': None}}], 'weights': [1.0]}

Output: {'parameters': [{'category': 'normal', 'search_space': {'mu': 1.5707963267948966, 'sigma': 3.141592653589793, 'low': 0, 'high': 3.141592653589793, 'step': None}}], 'weights': [1.0]}


def validate_normal(search_space):

    search_space = search_space.copy()

    if type(search_space) != dict:
        raise ValueError

    if "mu" not in search_space.keys() or type(search_space["mu"]) not in (int, float):
        print(search_space)
        raise ValueError

    if "sigma" not in search_space.keys() or type(search_space["sigma"]) not in (int, float):
        raise ValueError

    if "step" in search_space.keys():
        if search_space["step"] and type(search_space["step"]) not in (int, float):
            raise ValueError

    if "low" in search_space.keys():
        if type(search_space["low"]) not in (int, float):
            raise ValueError

    if "high" in search_space.keys():
        if type(search_space["high"]) not in (int, float):
            raise ValueError

    if "high" in search_space.keys() and "low" in search_space.keys():
        if search_space["high"] <= search_space["low"]:
            raise ValueError("low <= high")

    search_space.setdefault("low", -np.inf)
    search_space.setdefault("high", -np.inf)

    search_space.setdefault("step", None)

    return search_space

Input: {'mu': 1.5707963267948966, 'sigma': 0.3, 'low': 0, 'high': 3.141592653589793}

Output: {'mu': 1.5707963267948966, 'sigma': 0.3, 'low': 0, 'high': 3.141592653589793, 'step': None}


def validate_categorical(search_space):

    search_space = search_space.copy()

    if type(search_space) != dict:
        raise ValueError
    if "values" not in search_space.keys() or type(search_space['values']) != list:
        raise ValueError
    if "probabilities" in search_space.keys() and (
            type(search_space['probabilities']) != list or
            len(search_space['probabilities']) != len(search_space['values'])):
        raise ValueError

    if "probabilities" in search_space.keys():
        np.random.choice(range(len(search_space["probabilities"])),
                         p=search_space["probabilities"])

    if "probabilities" not in search_space.keys():
        number_of_values = len(search_space["values"])
        search_space["probabilities"] = list(np.ones(number_of_values) / number_of_values)

    return search_space

Input: {'values': [0, 0.6283185307179586, 0.7853981633974483, 1.0471975511965976, 1.5707963267948966, 3.141592653589793]}

Output: {'values': [0, 0.6283185307179586, 0.7853981633974483, 1.0471975511965976, 1.5707963267948966, 3.141592653589793], 'probabilities': [0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666]}


def __missing__(self, b):

        if b in _TILDE_ENCODING_SAFE:
            res = chr(b)
        elif b == _space:
            res = "+"
        else:
            res = "~{:02X}".format(b)
        self[b] = res
        return res

Input: {}, 102

Output: 'f'


def remove_infinites(row):
    to_check = row
    if isinstance(row, dict):
        to_check = row.values()
    if not any((c in _infinities) if isinstance(c, float) else 0 for c in to_check):
        return row
    if isinstance(row, dict):
        return {
            k: (None if (isinstance(v, float) and v in _infinities) else v)
            for k, v in row.items()
        }
    else:
        return [None if (isinstance(c, float) and c in _infinities) else c for c in row]

Input: REPR FAILED

Output: REPR FAILED


def to_css_class(s):

    if css_class_re.match(s):
        return s
    md5_suffix = hashlib.md5(s.encode("utf8")).hexdigest()[:6]

    s = s.lstrip("_").lstrip("-")

    s = "-".join(s.split())

    s = css_invalid_chars_re.sub("", s)

    bits = [b for b in (s, md5_suffix) if b]
    return "-".join(bits)

Input: 'table/with/slashes.csv'

Output: 'tablewithslashescsv-fa7563'


def path_from_row_pks(row, pks, use_rowid, quote=True):

    if use_rowid:
        bits = [row["rowid"]]
    else:
        bits = [
            row[pk]["value"] if isinstance(row[pk], dict) else row[pk] for pk in pks
        ]
    if quote:
        bits = [tilde_encode(str(bit)) for bit in bits]
    else:
        bits = [str(bit) for bit in bits]

    return ",".join(bits)

Input: REPR FAILED, ['id'], False, False

Output: '1'