    def update_headers(self, request_headers: HTTPHeadersDict):
        """
        Update the session headers with the request ones while ignoring
        certain name prefixes.

        """
        headers = self.headers
        for name, value in request_headers.copy().items():

            if value is None:
                continue  # Ignore explicitly unset headers

            if type(value) is not str:
                value = value.decode()

            if name.lower() == 'user-agent' and value.startswith('HTTPie/'):
                continue

            if name.lower() == 'cookie':
                for cookie_name, morsel in SimpleCookie(value).items():
                    self['cookies'][cookie_name] = {'value': morsel.value}
                del request_headers[name]
                continue

            for prefix in SESSION_IGNORED_HEADER_PREFIXES:
                if name.lower().startswith(prefix.lower()):
                    break
            else:
                headers[name] = value

        self['headers'] = dict(headers)


def get_user_list(
    *, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime],


def upload_file(request):
    path = tempfile.mkdtemp()
    file_name = os.path.join(path, "%s.txt" % request.node.name)
    with open(file_name, "w") as f:
        f.write(request.node.name)
    return file_name


    def __init__(
        self,
        *,
        resource_group: str,
        location: str,
        application_name: str,
        owner: str,
        client_id: Optional[str],
        client_secret: Optional[str],
        app_zip: str,
        tools: str,
        instance_specific: str,
        third_party: str,
        arm_template: str,
        workbook_data: str,
        create_registration: bool,
        migrations: List[str],
        export_appinsights: bool,
        log_service_principal: bool,
        multi_tenant_domain: str,
        upgrade: bool,
        subscription_id: Optional[str],
        admins: List[UUID]


    def test_runAllImportStepsFromProfile_unicode_id_creates_reports(self):

        TITLE = 'original title'
        PROFILE_ID = u'snapshot-testing'
        site = self._makeSite(TITLE)
        tool = self._makeOne('setup_tool').__of__(site)

        registry = tool.getImportStepRegistry()
        registry.registerStep(
            'dependable', '1', _underscoreSiteTitle, ('purging', ))
        registry.registerStep(
            'dependent', '1', _uppercaseSiteTitle, ('dependable', ))
        registry.registerStep('purging', '1', _purgeIfRequired)

        tool.runAllImportStepsFromProfile(PROFILE_ID)

        prefix = str('import-all-%s' % PROFILE_ID)
        logged = [x for x in tool.objectIds('File') if x.startswith(prefix)]
        self.assertEqual(len(logged), 1)

        # Check acess restriction on log files
        logged = [x for x in tool.objectIds('File')]
        for file_id in logged:
            file_ob = tool._getOb(file_id)
            rop_info = file_ob.rolesOfPermission(view)
            allowed_roles = sorted([x['name'] for x in rop_info
                                    if x['selected']])
            self.assertEqual(allowed_roles, ['Manager', 'Owner'])
            self.assertFalse(file_ob.acquiredRolesAreUsedBy(view))


    def test_can_read_token_from_headers(self):
        """Tests that Sydent correct extracts an auth token from request headers"""
        self.sydent.run()

        request, _ = make_request(
            self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details"
        )
        request.requestHeaders.addRawHeader(
            b"Authorization", b"Bearer " + self.test_token.encode("ascii")
        )

        token = tokenFromRequest(request)

        self.assertEqual(token, self.test_token)


	def innerfn(fn):
		global whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func
		whitelisted.append(fn)

		allowed_http_methods_for_whitelisted_func[fn] = methods

		if allow_guest:
			guest_methods.append(fn)

			if xss_safe:
				xss_safe_methods.append(fn)

		return fn


    async def actset(self, ctx):
        """
        Configure various settings for the act cog.
        """


    def test_parse_header_connection_close(self):
        data = b"GET /foobar HTTP/1.1\nConnection: close\n\n"
        self.parser.parse_header(data)
        self.assertEqual(self.parser.connection_close, True)


    def make_homeserver(self, reactor, clock):
        hs = self.setup_test_homeserver("server", http_client=None)
        self.handler = hs.get_device_handler()
        self.store = hs.get_datastore()
        return hs


    def traverse(cls, base, request, path_items):
        """See ``zope.app.pagetemplate.engine``."""

        path_items = list(path_items)
        path_items.reverse()

        while path_items:
            name = path_items.pop()
            if ITraversable.providedBy(base):
                base = getattr(base, cls.traverseMethod)(name)
            else:
                base = traversePathElement(base, name, path_items,
                                           request=request)

        return base


  def testInputPreProcessErrorBadFormat(self):
    input_str = 'inputx=file[[v1]v2'
    with self.assertRaises(RuntimeError):
      saved_model_cli.preprocess_inputs_arg_string(input_str)
    input_str = 'inputx:file'
    with self.assertRaises(RuntimeError):
      saved_model_cli.preprocess_inputs_arg_string(input_str)
    input_str = 'inputx:np.zeros((5))'
    with self.assertRaises(RuntimeError):
      saved_model_cli.preprocess_input_exprs_arg_string(input_str)


    def test_reset_entrance_exam_student_attempts_single(self):
        """ Test reset single student attempts for entrance exam. """
        url = reverse('reset_student_attempts_for_entrance_exam',
                      kwargs={'course_id': unicode(self.course.id)})
        response = self.client.get(url, {
            'unique_student_identifier': self.student.email,
        })
        self.assertEqual(response.status_code, 200)
        # make sure problem attempts have been reset.
        changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules)
        for changed_module in changed_modules:
            self.assertEqual(
                json.loads(changed_module.state)['attempts'],
                0
            )


def test_render_quoting(self):
        w = widgets.AdminURLFieldWidget()
        self.assertHTMLEqual(
            conditional_escape(w.render('test', 'http://example.com/<sometag>some text</sometag>')),
            '
Currently:http://example.com/<sometag>some text</sometag>
Change:<input class="vURLField" name="test" type="url" value="http://example.com/<sometag>some text</sometag>" />
'
        )
        self.assertHTMLEqual(
            conditional_escape(w.render('test', 'http://example-äüö.com/<sometag>some text</sometag>')),
            '
Currently:http://example-äüö.com/<sometag>some text</sometag>
Change:<input class="vURLField" name="test" type="url" value="http://example-äüö.com/<sometag>some text</sometag>" />
'
        )


def test_date_parsing(value, result):
    if result == errors.DateError:
        with pytest.raises(errors.DateError):
            parse_date(value)
    else:
        assert parse_date(value) == result


    def _process(tlist):
        def get_next_comment():
            # TODO(andi) Comment types should be unified, see related issue38
            return tlist.token_next_by(i=sql.Comment, t=T.Comment)

        def _get_insert_token(token):
            """Returns either a whitespace or the line breaks from token."""
            # See issue484 why line breaks should be preserved.
            m = re.search(r'((\r\n|\r|\n)+) *$', token.value)
            if m is not None:
                return sql.Token(T.Whitespace.Newline, m.groups()[0])
            else:
                return sql.Token(T.Whitespace, ' ')

        tidx, token = get_next_comment()
        while token:
            pidx, prev_ = tlist.token_prev(tidx, skip_ws=False)
            nidx, next_ = tlist.token_next(tidx, skip_ws=False)
            # Replace by whitespace if prev and next exist and if they're not
            # whitespaces. This doesn't apply if prev or next is a parenthesis.
            if (prev_ is None or next_ is None
                    or prev_.is_whitespace or prev_.match(T.Punctuation, '(')
                    or next_.is_whitespace or next_.match(T.Punctuation, ')')):
                # Insert a whitespace to ensure the following SQL produces
                # a valid SQL (see #425).
                if prev_ is not None and not prev_.match(T.Punctuation, '('):
                    tlist.tokens.insert(tidx, _get_insert_token(token))
                tlist.tokens.remove(token)
            else:
                tlist.tokens[tidx] = _get_insert_token(token)

            tidx, token = get_next_comment()


def table_get_custom_enum(c_id):
    ret = list()
    cc = (calibre_db.session.query(db.Custom_Columns)
              .filter(db.Custom_Columns.id == c_id)
              .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none())
    ret.append({'value': "", 'text': ""})
    for idx, en in enumerate(cc.get_display_dict()['enum_values']):
        ret.append({'value': en, 'text': en})
    return json.dumps(ret)


async def account_register_post(
    request: Request,
    U: str = Form(default=str()),  # Username
    E: str = Form(default=str()),  # Email
    H: str = Form(default=False),  # Hide Email
    BE: str = Form(default=None),  # Backup Email
    R: str = Form(default=""),  # Real Name
    HP: str = Form(default=None),  # Homepage
    I: str = Form(default=None),  # IRC Nick # noqa: E741
    K: str = Form(default=None),  # PGP Key
    L: str = Form(default=aurweb.config.get("options", "default_lang")),
    TZ: str = Form(default=aurweb.config.get("options", "default_timezone")),
    PK: str = Form(default=None),  # SSH PubKey
    CN: bool = Form(default=False),
    UN: bool = Form(default=False),
    ON: bool = Form(default=False),
    captcha: str = Form(default=None),
    captcha_salt: str = Form(...),


        def recovery_parser(xml):
            parser = XMLParser(recover=True)
            return parse(BytesIO(xml), parser)


def find_double_newline(s):
    """Returns the position just after a double newline in the given string."""
    pos1 = s.find(b"\n\r\n")  # One kind of double newline
    if pos1 >= 0:
        pos1 += 3
    pos2 = s.find(b"\n\n")  # Another kind of double newline
    if pos2 >= 0:
        pos2 += 2

    if pos1 >= 0:
        if pos2 >= 0:
            return min(pos1, pos2)
        else:
            return pos1
    else:
        return pos2


    def _ensureSnapshotsFolder(self, subdir=None):
        """ Ensure that the appropriate snapshot folder exists.
        """
        path = ['snapshots', self._snapshot_id]

        if subdir is not None:
            path.extend(subdir.split('/'))

        current = self._tool

        for element in path:

            if element not in current.objectIds():
                # No Unicode IDs!
                current._setObject(str(element), Folder(element))

            current = current._getOb(element)

        return current


def clean_id(id_):
    '''
    Returns if the passed id is clean.
    '''
    if re.search(r'\.\.\{sep}'.format(sep=os.sep), id_):
        return False
    return True


    def _contains_display_name(self, display_name: str) -> bool:
        if not display_name:
            return False

        body = self._event.content.get("body", None)
        if not body or not isinstance(body, str):
            return False

        # Similar to _glob_matches, but do not treat display_name as a glob.
        r = regex_cache.get((display_name, False, True), None)
        if not r:
            r1 = re.escape(display_name)
            r1 = _re_word_boundary(r1)
            r = re.compile(r1, flags=re.IGNORECASE)
            regex_cache[(display_name, False, True)] = r

        return bool(r.search(body))


def set_session_tracks(display_obj):
    """Save igv tracks as a session object. This way it's easy to verify that a user is requesting one of these files from remote_static view endpoint

    Args:
        display_obj(dict): A display object containing case name, list of genes, lucus and tracks
    """
    session_tracks = list(display_obj.get("reference_track", {}).values())
    for key, track_items in display_obj.items():
        if key not in ["tracks", "custom_tracks", "sample_tracks"]:
            continue
        for track_item in track_items:
            session_tracks += list(track_item.values())

    session["igv_tracks"] = session_tracks


    def traverse(cls, base, request, path_items):
        """See ``zope.app.pagetemplate.engine``."""

        path_items = list(path_items)
        path_items.reverse()

        while path_items:
            name = path_items.pop()

            if name == '_':
                warnings.warn('Traversing to the name `_` is deprecated '
                              'and will be removed in Zope 6.',
                              DeprecationWarning)
            elif name.startswith('_'):
                raise NotFound(name)

            if ITraversable.providedBy(base):
                base = getattr(base, cls.traverse_method)(name)
            else:
                base = traversePathElement(base, name, path_items,
                                           request=request)

        return base


    def test_get_ora2_responses_success(self):
        url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)})

        with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task:
            mock_submit_ora2_task.return_value = True
            response = self.client.get(url, {})
        success_status = "The ORA data report is being generated."
        self.assertIn(success_status, response.content)


    def test_parse_header_bad_content_length(self):
        data = b"GET /foobar HTTP/8.4\ncontent-length: abc"
        self.parser.parse_header(data)
        self.assertEqual(self.parser.body_rcv, None)


def profile():
    languages = calibre_db.speaking_language()
    translations = babel.list_translations() + [LC('en')]
    kobo_support = feature_support['kobo'] and config.config_kobo_sync
    if feature_support['oauth'] and config.config_login_type == 2:
        oauth_status = get_oauth_status()
        local_oauth_check = oauth_check
    else:
        oauth_status = None
        local_oauth_check = {}

    if request.method == "POST":
        change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages)
    return render_title_template("user_edit.html",
                                 translations=translations,
                                 profile=1,
                                 languages=languages,
                                 content=current_user,
                                 kobo_support=kobo_support,
                                 title=_(u"%(name)s's profile", name=current_user.name),
                                 page="me",
                                 registered_oauth=local_oauth_check,
                                 oauth_status=oauth_status)


  def testFlushFunction(self):
    logdir = self.get_temp_dir()
    with context.eager_mode():
      writer = summary_ops.create_file_writer_v2(
          logdir, max_queue=999999, flush_millis=999999)
      with writer.as_default():
        get_total = lambda: len(events_from_logdir(logdir))
        # Note: First tf.compat.v1.Event is always file_version.
        self.assertEqual(1, get_total())
        summary_ops.write('tag', 1, step=0)
        summary_ops.write('tag', 1, step=0)
        self.assertEqual(1, get_total())
        summary_ops.flush()
        self.assertEqual(3, get_total())
        # Test "writer" parameter
        summary_ops.write('tag', 1, step=0)
        self.assertEqual(3, get_total())
        summary_ops.flush(writer=writer)
        self.assertEqual(4, get_total())
        summary_ops.write('tag', 1, step=0)
        self.assertEqual(4, get_total())
        summary_ops.flush(writer=writer._resource)  # pylint:disable=protected-access
        self.assertEqual(5, get_total())


    async def on_send_join_request(
        self, origin: str, content: JsonDict, room_id: str


def put_file(path):
    try:
        dest_path = sanitized_join(
            path,
            pathlib.Path(app.config["DATA_ROOT"]),
        )
    except ValueError:
        return flask.Response(
            "Not Found",
            404,
            mimetype="text/plain",
        )

    verification_key = flask.request.args.get("v", "")
    length = int(flask.request.headers.get("Content-Length", 0))
    hmac_input = "{} {}".format(path, length).encode("utf-8")
    key = app.config["SECRET_KEY"]
    mac = hmac.new(key, hmac_input, hashlib.sha256)
    digest = mac.hexdigest()

    if not hmac.compare_digest(digest, verification_key):
        return flask.Response(
            "Invalid verification key",
            403,
            mimetype="text/plain",
        )

    content_type = flask.request.headers.get(
        "Content-Type",
        "application/octet-stream",
    )

    dest_path.parent.mkdir(parents=True, exist_ok=True, mode=0o770)
    data_file, metadata_file = get_paths(dest_path)

    try:
        with write_file(data_file) as fout:
            stream_file(flask.request.stream, fout, length)

            with metadata_file.open("x") as f:
                json.dump(
                    {
                        "headers": {"Content-Type": content_type},
                    },
                    f,
                )
    except EOFError:
        return flask.Response(
            "Bad Request",
            400,
            mimetype="text/plain",
        )
    except OSError as exc:
        if exc.errno == errno.EEXIST:
            return flask.Response(
                "Conflict",
                409,
                mimetype="text/plain",
            )
        raise

    return flask.Response(
        "Created",
        201,
        mimetype="text/plain",
    )


def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None):
	frappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args)


def job_log(request, client_id, project_name, spider_name, job_id):
    """
    get log of jog
    :param request: request object
    :param client_id: client id
    :param project_name: project name
    :param spider_name: spider name
    :param job_id: job id
    :return: log of job
    """
    if request.method == 'GET':
        client = Client.objects.get(id=client_id)
        # get log url
        url = log_url(client.ip, client.port, project_name, spider_name, job_id)
        try:
            # get last 1000 bytes of log
            response = requests.get(url, timeout=5, headers={
                'Range': 'bytes=-1000'
            }, auth=(client.username, client.password) if client.auth else None)
            # Get encoding
            encoding = response.apparent_encoding
            # log not found
            if response.status_code == 404:
                return JsonResponse({'message': 'Log Not Found'}, status=404)
            # bytes to string
            text = response.content.decode(encoding, errors='replace')
            return HttpResponse(text)
        except requests.ConnectionError:
            return JsonResponse({'message': 'Load Log Error'}, status=500)


def feed_publisher(book_id):
    off = request.args.get("offset") or 0
    entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
                                                        db.Books,
                                                        db.Books.publishers.any(db.Publishers.id == book_id),
                                                        [db.Books.timestamp.desc()])
    return render_xml_template('feed.xml', entries=entries, pagination=pagination)


    def request(self, method, request_uri, headers, content):
        """Modify the request headers"""
        keys = _get_end2end_headers(headers)
        keylist = "".join(["%s " % k for k in keys])
        headers_val = "".join([headers[k] for k in keys])
        created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
        cnonce = _cnonce()
        request_digest = "%s:%s:%s:%s:%s" % (
            method,
            request_uri,
            cnonce,
            self.challenge["snonce"],
            headers_val,
        )
        request_digest = (
            hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
        )
        headers["authorization"] = (
            'HMACDigest username="%s", realm="%s", snonce="%s",'
            ' cnonce="%s", uri="%s", created="%s", '
            'response="%s", headers="%s"'
        ) % (
            self.credentials[0],
            self.challenge["realm"],
            self.challenge["snonce"],
            cnonce,
            request_uri,
            created,
            request_digest,
            keylist,
        )


def get_valid_filename(value, replace_whitespace=True, chars=128):
    """
    Returns the given string converted to a string that can be used for a clean
    filename. Limits num characters to 128 max.
    """
    if value[-1:] == u'.':
        value = value[:-1]+u'_'
    value = value.replace("/", "_").replace(":", "_").strip('\0')
    if use_unidecode:
        if config.config_unicode_filename:
            value = (unidecode.unidecode(value))
    else:
        value = value.replace(u'§', u'SS')
        value = value.replace(u'ß', u'ss')
        value = unicodedata.normalize('NFKD', value)
        re_slugify = re.compile(r'[\W\s-]', re.UNICODE)
        value = re_slugify.sub('', value)
    if replace_whitespace:
        #  *+:\"/<>? are replaced by _
        value = re.sub(r'[*+:\\\"/<>?]+', u'_', value, flags=re.U)
        # pipe has to be replaced with comma
        value = re.sub(r'[|]+', u',', value, flags=re.U)
    value = value[:chars].strip()
    if not value:
        raise ValueError("Filename cannot be empty")
    return value


def feed_read_books():
    off = request.args.get("offset") or 0
    result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, True, True)
    return render_xml_template('feed.xml', entries=result, pagination=pagination)


def _decompressContent(response, new_content):
    content = new_content
    try:
        encoding = response.get("content-encoding", None)
        if encoding in ["gzip", "deflate"]:
            if encoding == "gzip":
                content = gzip.GzipFile(fileobj=io.BytesIO(new_content)).read()
            if encoding == "deflate":
                content = zlib.decompress(content, -zlib.MAX_WBITS)
            response["content-length"] = str(len(content))
            # Record the historical presence of the encoding in a way the won't interfere.
            response["-content-encoding"] = response["content-encoding"]
            del response["content-encoding"]
    except (IOError, zlib.error):
        content = ""
        raise FailedToDecompressContent(
            _("Content purported to be compressed with %s but failed to decompress.")
            % response.get("content-encoding"),
            response,
            content,
        )
    return content


    def test_list_course_role_members_staff(self):
        url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
        response = self.client.get(url, {
            'rolename': 'staff',
        })
        self.assertEqual(response.status_code, 200)

        # check response content
        expected = {
            'course_id': self.course.id.to_deprecated_string(),
            'staff': [
                {
                    'username': self.other_staff.username,
                    'email': self.other_staff.email,
                    'first_name': self.other_staff.first_name,
                    'last_name': self.other_staff.last_name,
                }
            ]
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)


    def to_xml(self, data, options=None):
        """
        Given some Python data, produces XML output.
        """
        options = options or {}

        if lxml is None:
            raise ImproperlyConfigured("Usage of the XML aspects requires lxml.")

        return tostring(self.to_etree(data, options), xml_declaration=True, encoding='utf-8')


    def __call__(self, value, system):

        if 'request' in system:
            request = system['request']

            mime, encoding = mimetypes.guess_type(value['filename'])
            request.response_content_type = mime
            if encoding:
                request.response_encoding = encoding

            f = os.path.join(self.repository_root,
                             value['filename'][0].lower(),
                             value['filename'])

            if not os.path.exists(f):
                dir_ = os.path.join(self.repository_root,
                             value['filename'][0].lower())
                if not os.path.exists(dir_):
                    os.makedirs(dir_, 0750)

                resp = requests.get(value['url'])
                with open(f, 'wb') as rf:
                    rf.write(resp.content)
                return resp.content
            else:
                data = ''
                with open(f, 'rb') as rf:
                    data = ''
                    while True:
                        content = rf.read(2<<16)
                        if not content:
                            break
                        data += content
                return data


def parse_soap_enveloped_saml(text, body_class, header_class=None):
    """Parses a SOAP enveloped SAML thing and returns header parts and body

    :param text: The SOAP object as XML
    :return: header parts and body as saml.samlbase instances
    """
    envelope = ElementTree.fromstring(text)
    assert envelope.tag == '{%s}Envelope' % NAMESPACE

    # print(len(envelope))
    body = None
    header = {}
    for part in envelope:
        # print(">",part.tag)
        if part.tag == '{%s}Body' % NAMESPACE:
            for sub in part:
                try:
                    body = saml2.create_class_from_element_tree(body_class, sub)
                except Exception:
                    raise Exception(
                        "Wrong body type (%s) in SOAP envelope" % sub.tag)
        elif part.tag == '{%s}Header' % NAMESPACE:
            if not header_class:
                raise Exception("Header where I didn't expect one")
            # print("--- HEADER ---")
            for sub in part:
                # print(">>",sub.tag)
                for klass in header_class:
                    # print("?{%s}%s" % (klass.c_namespace,klass.c_tag))
                    if sub.tag == "{%s}%s" % (klass.c_namespace, klass.c_tag):
                        header[sub.tag] = \
                            saml2.create_class_from_element_tree(klass, sub)
                        break

    return body, header


    def test_received_preq_completed_n_lt_data(self):
        inst, sock, map = self._makeOneWithMap()
        inst.server = DummyServer()
        preq = DummyParser()
        inst.request = preq
        preq.completed = True
        preq.empty = False
        line = b"GET / HTTP/1.1\n\n"
        preq.retval = len(line)
        inst.received(line + line)
        self.assertEqual(inst.request, None)
        self.assertEqual(len(inst.requests), 2)
        self.assertEqual(len(inst.server.tasks), 1)


def create_class_from_xml_string(target_class, xml_string):
    """Creates an instance of the target class from a string.

    :param target_class: The class which will be instantiated and populated
        with the contents of the XML. This class must have a c_tag and a
        c_namespace class variable.
    :param xml_string: A string which contains valid XML. The root element
        of the XML string should match the tag and namespace of the desired
        class.

    :return: An instance of the target class with members assigned according to
        the contents of the XML - or None if the root XML tag and namespace did
        not match those of the target class.
    """
    if not isinstance(xml_string, six.binary_type):
        xml_string = xml_string.encode('utf-8')
    tree = ElementTree.fromstring(xml_string)
    return create_class_from_element_tree(target_class, tree)


    def test_send_push_single_worker(self):
        """Test that registration works when using a pusher worker.
        """
        http_client_mock = Mock(spec_set=["post_json_get_json"])
        http_client_mock.post_json_get_json.side_effect = lambda *_, **__: defer.succeed(
            {}
        )

        self.make_worker_hs(
            "synapse.app.pusher",
            {"start_pushers": True},
            proxied_http_client=http_client_mock,
        )

        event_id = self._create_pusher_and_send_msg("user")

        # Advance time a bit, so the pusher will register something has happened
        self.pump()

        http_client_mock.post_json_get_json.assert_called_once()
        self.assertEqual(
            http_client_mock.post_json_get_json.call_args[0][0],
            "https://push.example.com/push",
        )
        self.assertEqual(
            event_id,
            http_client_mock.post_json_get_json.call_args[0][1]["notification"][
                "event_id"
            ],
        )


def index():
    """ Index handler """

    send = request.vars.send
    if DEMO_MODE:
        session.authorized = True
        session.last_time = t0
    if not send:
        send = URL('site')
    if session.authorized:
        redirect(send)
    elif failed_login_count() >= allowed_number_of_attempts:
        time.sleep(2 ** allowed_number_of_attempts)
        raise HTTP(403)
    elif request.vars.password:
        if verify_password(request.vars.password[:1024]):
            session.authorized = True
            login_record(True)

            if CHECK_VERSION:
                session.check_version = True
            else:
                session.check_version = False

            session.last_time = t0
            if isinstance(send, list):  # ## why does this happen?
                send = str(send[0])

            redirect(send)
        else:
            times_denied = login_record(False)
            if times_denied >= allowed_number_of_attempts:
                response.flash = \
                    T('admin disabled because too many invalid login attempts')
            elif times_denied == allowed_number_of_attempts - 1:
                response.flash = \
                    T('You have one more login attempt before you are locked out')
            else:
                response.flash = T('invalid password.')
    return dict(send=send)


    def run_tests(self):
        # pytest may be not installed yet
        import pytest
        args = ['--forked', '--fulltrace', '--no-cov', 'tests/']
        if self.test_suite:
            args += ['-k', self.test_suite]
        sys.stderr.write('setup.py:test run pytest {}\n'.format(' '.join(args)))
        errno = pytest.main(args)
        sys.exit(errno)


def edit_all_cc_data(book_id, book, to_save):
    cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()
    return edit_cc_data(book_id, book, to_save, cc)


    def test_filename(self):
        tmpname = mktemp('', 'mmap')
        fp = memmap(tmpname, dtype=self.dtype, mode='w+',
                       shape=self.shape)
        abspath = os.path.abspath(tmpname)
        fp[:] = self.data[:]
        self.assertEqual(abspath, fp.filename)
        b = fp[:1]
        self.assertEqual(abspath, b.filename)
        del b
        del fp
        os.unlink(tmpname)


    def test_mixed(self):
        self.assertEqual(self._callFUT(b"\n\n00\r\n\r\n"), 2)


def join_in(request, topic_id):
    # todo: replace by create_access()?
    # This is for topic creators who left their own topics and want to join again
    topic = get_object_or_404(
        Topic,
        pk=topic_id,
        user=request.user,
        category_id=settings.ST_TOPIC_PRIVATE_CATEGORY_PK)
    form = TopicPrivateJoinForm(
        topic=topic,
        user=request.user,
        data=post_data(request))
    if is_post(request) and form.is_valid():
        topic_private = form.save()
        notify_access(user=form.get_user(), topic_private=topic_private)
        return redirect(request.POST.get('next', topic.get_absolute_url()))
    return render(
        request=request,
        template_name='spirit/topic/private/join.html',
        context={
            'topic': topic,
            'form': form})


    def test_reset_student_attempts_all(self, act):
        """ Test reset all student attempts. """
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'all_students': True,
        })
        self.assertEqual(response.status_code, 200)
        self.assertTrue(act.called)


def main(srcfile, dump_module=False):
    argv0 = sys.argv[0]
    components = argv0.split(os.sep)
    argv0 = os.sep.join(components[-2:])
    auto_gen_msg = common_msg % argv0
    mod = asdl.parse(srcfile)
    if dump_module:
        print('Parsed Module:')
        print(mod)
    if not asdl.check(mod):
        sys.exit(1)
    if INC_DIR:
        p = "%s/%s-ast.h" % (INC_DIR, mod.name)
        f = open(p, "w")
        f.write(auto_gen_msg)
        f.write('#include "asdl.h"\n\n')
        c = ChainOfVisitors(TypeDefVisitor(f),
                            StructVisitor(f),
                            PrototypeVisitor(f),
                            )
        c.visit(mod)
        f.write("PyObject* Ta3AST_mod2obj(mod_ty t);\n")
        f.write("mod_ty Ta3AST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n")
        f.write("int Ta3AST_Check(PyObject* obj);\n")
        f.close()

    if SRC_DIR:
        p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
        f = open(p, "w")
        f.write(auto_gen_msg)
        f.write('#include <stddef.h>\n')
        f.write('\n')
        f.write('#include "Python.h"\n')
        f.write('#include "%s-ast.h"\n' % mod.name)
        f.write('\n')
        f.write("static PyTypeObject AST_type;\n")
        v = ChainOfVisitors(
            PyTypesDeclareVisitor(f),
            PyTypesVisitor(f),
            Obj2ModPrototypeVisitor(f),
            FunctionVisitor(f),
            ObjVisitor(f),
            Obj2ModVisitor(f),
            ASTModuleVisitor(f),
            PartingShots(f),
            )
        v.visit(mod)
        f.close()


def is_valid_hostname(string: str) -> bool:
    """Validate that a given string is a valid hostname or domain name, with an
    optional port number.

    For domain names, this only validates that the form is right (for
    instance, it doesn't check that the TLD is valid). If a port is
    specified, it has to be a valid port number.

    :param string: The string to validate
    :type string: str

    :return: Whether the input is a valid hostname
    :rtype: bool
    """

    host_parts = string.split(":", 1)

    if len(host_parts) == 1:
        return hostname_regex.match(string) is not None
    else:
        host, port = host_parts
        valid_hostname = hostname_regex.match(host) is not None

        try:
            port_num = int(port)
            valid_port = (
                port == str(port_num)  # exclude things like '08090' or ' 8090'
                and 1 <= port_num < 65536)
        except ValueError:
            valid_port = False

        return valid_hostname and valid_port


    def test_request_body_too_large_with_wrong_cl_http11_connclose(self):
        body = "a" * self.toobig
        to_send = "GET / HTTP/1.1\nContent-Length: 5\nConnection: close\n\n"
        to_send += body
        to_send = tobytes(to_send)
        self.connect()
        self.sock.send(to_send)
        fp = self.sock.makefile("rb", 0)
        line, headers, response_body = read_http(fp)
        # server trusts the content-length header (5)
        self.assertline(line, "200", "OK", "HTTP/1.1")
        cl = int(headers["content-length"])
        self.assertEqual(cl, len(response_body))
        # connection has been closed
        self.send_check_error(to_send)
        self.assertRaises(ConnectionClosed, read_http, fp)


def list_course_role_members(request, course_id):
    """
    List instructors and staff.
    Requires instructor access.

    rolename is one of ['instructor', 'staff', 'beta', 'ccx_coach']

    Returns JSON of the form {
        "course_id": "some/course/id",
        "staff": [
            {
                "username": "staff1",
                "email": "staff1@example.org",
                "first_name": "Joe",
                "last_name": "Shmoe",
            }
        ]
    }
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(
        request.user, 'instructor', course_id, depth=None
    )

    rolename = request.GET.get('rolename')

    if rolename not in ROLES:
        return HttpResponseBadRequest()

    def extract_user_info(user):
        """ convert user into dicts for json view """
        return {
            'username': user.username,
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name,
        }

    response_payload = {
        'course_id': course_id.to_deprecated_string(),
        rolename: map(extract_user_info, list_with_level(
            course, rolename
        )),
    }
    return JsonResponse(response_payload)


def _unpack_returndata(buf, contract_sig, skip_contract_check, context):
    return_t = contract_sig.return_type
    if return_t is None:
        return ["pass"], 0, 0

    return_t = calculate_type_for_external_return(return_t)
    # if the abi signature has a different type than
    # the vyper type, we need to wrap and unwrap the type
    # so that the ABI decoding works correctly
    should_unwrap_abi_tuple = return_t != contract_sig.return_type

    abi_return_t = return_t.abi_type

    min_return_size = abi_return_t.min_size()
    max_return_size = abi_return_t.size_bound()
    assert 0 < min_return_size <= max_return_size

    ret_ofst = buf
    ret_len = max_return_size

    # revert when returndatasize is not in bounds
    ret = []
    # runtime: min_return_size <= returndatasize
    # TODO move the -1 optimization to IR optimizer
    if not skip_contract_check:
        ret += [["assert", ["gt", "returndatasize", min_return_size - 1]]]

    # add as the last IRnode a pointer to the return data structure

    # the return type has been wrapped by the calling contract;
    # unwrap it so downstream code isn't confused.
    # basically this expands to buf+32 if the return type has been wrapped
    # in a tuple AND its ABI type is dynamic.
    # in most cases, this simply will evaluate to ret.
    # in the special case where the return type has been wrapped
    # in a tuple AND its ABI type is dynamic, it expands to buf+32.
    buf = IRnode(buf, typ=return_t, encoding=_returndata_encoding(contract_sig), location=MEMORY)

    if should_unwrap_abi_tuple:
        buf = get_element_ptr(buf, 0, array_bounds_check=False)

    ret += [buf]

    return ret, ret_ofst, ret_len


  def testRuntimeError(self,
                       inputs,
                       exception=errors.InvalidArgumentError,
                       message=None):


def toggle_archived(book_id):
    is_archived = change_archived_books(book_id, message="Book {} archivebit toggled".format(book_id))
    if is_archived:
        remove_synced_book(book_id)
    return ""


    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        Assert.state(doesNotContainFileColon(path), "Path must not contain 'file:'");

        String pathToUse = StringUtils.cleanPath(path);

        if (pathToUse.startsWith("/")) {
            pathToUse = pathToUse.substring(1);
        }

        this.path = pathToUse;
        this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
    }


    void doubleQuote() {
        final PathAndQuery res = PathAndQuery.parse("/\"?\"");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/%22");
        assertThat(res.query()).isEqualTo("%22");
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String encoding = request.getHeader("Accept-Encoding");
        boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
        SessionTerminal st = (SessionTerminal) request.getSession(true).getAttribute("terminal");
        if (st == null || st.isClosed()) {
            st = new SessionTerminal(getCommandProcessor(), getThreadIO());
            request.getSession().setAttribute("terminal", st);
        }
        String str = request.getParameter("k");
        String f = request.getParameter("f");
        String dump = st.handle(str, f != null && f.length() > 0);
        if (dump != null) {
            if (supportsGzip) {
                response.setHeader("Content-Encoding", "gzip");
                response.setHeader("Content-Type", "text/html");
                try {
                    GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
                    gzos.write(dump.getBytes());
                    gzos.close();
                } catch (IOException ie) {
                    LOG.info("Exception writing response: ", ie);
                }
            } else {
                response.getOutputStream().write(dump.getBytes());
            }
        }
    }


	public PlayerClock(String title, ISkinParam skinParam, TimingRuler ruler, int period, int pulse, int offset,
			boolean compact) {
		super(title, skinParam, ruler, compact);
		this.displayTitle = title.length() > 0;
		this.period = period;
		this.pulse = pulse;
		this.offset = offset;
		this.suggestedHeight = 30;
	}


    public static void init(final InitialContext applicationContext) {
        synchronized (GeoTools.class) {
            context = applicationContext;
        }
        fireConfigurationChanged();
    }


    public void existingDocumentFromUIDeprecatedCheckEscaping() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Submit from the UI space=X.Y&page=Z
        when(mockRequest.getParameter("space")).thenReturn("X.Y");
        when(mockRequest.getParameter("page")).thenReturn("Z");

        // Run the action
        String result = action.render(context);

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note1: The space parameter was previously considered as space name, not space reference, so it is escaped.
        // Note2: We are creating X\.Y.Z since the deprecated parameters were creating terminal documents by default.
        verify(mockURLFactory).createURL("X\\.Y", "Z", "edit", "template=&parent=Main.WebHome&title=Z", null, "xwiki",
            context);
    }


        for (final ReservedChar reservedChar : ReservedChar.values()) {
            RAW_CHAR_TO_MARKER[reservedChar.rawChar] = reservedChar.marker;
            MARKER_TO_PERCENT_ENCODED_CHAR[reservedChar.marker] = reservedChar.percentEncodedChar;
        }


    public String getStringParameterSQL(String param) {
        return "'" + param + "'";
    }


    static void setAttribute(TransformerFactory transformerFactory, String attributeName) {
        try {
            transformerFactory.setAttribute(attributeName, "");
        } catch (IllegalArgumentException iae) {
            if (Boolean.getBoolean(SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES)) {
                LOGGER.warning("Enabling XXE protection failed. The attribute " + attributeName
                        + " is not supported by the TransformerFactory. The " + SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES
                        + " system property is used so the XML processing continues in the UNSECURE mode"
                        + " with XXE protection disabled!!!");
            } else {
                LOGGER.severe("Enabling XXE protection failed. The attribute " + attributeName
                        + " is not supported by the TransformerFactory. This usually mean an outdated XML processor"
                        + " is present on the classpath (e.g. Xerces, Xalan). If you are not able to resolve the issue by"
                        + " fixing the classpath, the " + SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES
                        + " system property can be used to disable XML External Entity protections."
                        + " We don't recommend disabling the XXE as such the XML processor configuration is unsecure!!!", iae);
                throw iae;
            }
        }
    }


	public static void writeObject(XStream xStream, OutputStream os, Object obj) {
		try(OutputStreamWriter osw = new OutputStreamWriter(os, ENCODING)) {
			String data = xStream.toXML(obj);
			data = "<?xml version=\"1.0\" encoding=\"" + ENCODING + "\"?>\n"
					+ data; // give a decent header with the encoding used
			osw.write(data);
			osw.flush();
		} catch (Exception e) {
			throw new OLATRuntimeException(XStreamHelper.class, "Could not write object to stream.", e);
		}
	}


    public void validateConcreteScmMaterial(ValidationContext validationContext) {
        if (getView() == null || getView().trim().isEmpty()) {
            errors.add(VIEW, "P4 view cannot be empty.");
        }
        if (StringUtils.isBlank(getServerAndPort())) {
            errors.add(SERVER_AND_PORT, "P4 port cannot be empty.");
        }
        validateEncryptedPassword();
    }


	private TextBlock getTitleBlock(IGroup g) {
		final Display label = g.getDisplay();
		if (label == null)
			return TextBlockUtils.empty(0, 0);

		final ISkinParam skinParam = dotData.getSkinParam();
		final FontConfiguration fontConfiguration;
		if (UseStyle.useBetaStyle()) {
			final SName sname = dotData.getUmlDiagramType().getStyleName();
			final StyleSignatureBasic signature;
			final USymbol uSymbol = g.getUSymbol();
			if (uSymbol == USymbols.RECTANGLE)
				signature = StyleSignatureBasic.of(SName.root, SName.element, sname, uSymbol.getSName(), SName.title);
			else
				signature = StyleSignatureBasic.of(SName.root, SName.element, sname, SName.title);

			final Style style = signature //
					.withTOBECHANGED(g.getStereotype()) //
					.with(g.getStereostyles()) //
					.getMergedStyle(skinParam.getCurrentStyleBuilder());

			fontConfiguration = style.getFontConfiguration(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());
		} else
			fontConfiguration = g.getFontConfigurationForTitle(skinParam);
		final HorizontalAlignment alignment = HorizontalAlignment.CENTER;
		return label.create(fontConfiguration, alignment, dotData.getSkinParam());
	}


    public void newDocumentWebHomeButTerminalFromURL() throws Exception
    {
        // new document = xwiki:X.Y.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X", "Y"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(true);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Pass the tocreate=terminal request parameter
        when(mockRequest.getParameter("tocreate")).thenReturn("terminal");

        // Run the action
        String result = action.render(context);

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note: We are creating X.Y instead of X.Y.WebHome because the tocreate parameter says "terminal".
        verify(mockURLFactory).createURL("X", "Y", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki",
            context);
    }


  parse_io(ThreadContext context,
           IRubyObject klazz,
           IRubyObject data,
           IRubyObject enc)
  {
    //int encoding = (int)enc.convertToInteger().getLongValue();
    final Ruby runtime = context.runtime;
    XmlSaxParserContext ctx = newInstance(runtime, (RubyClass) klazz);
    ctx.initialize(runtime);
    ctx.setIOInputSource(context, data, runtime.getNil());
    return ctx;
  }


    public void setUp(@TempDir Path tempDir) throws IOException {
        serverRepo = TempDirUtils.createTempDirectoryIn(tempDir, "testHgServerRepo").toFile();
        clientRepo =  TempDirUtils.createTempDirectoryIn(tempDir, "testHgClientRepo").toFile();
        secondBranchWorkingCopy =  TempDirUtils.createTempDirectoryIn(tempDir, "second").toFile();

        setUpServerRepoFromHgBundle(serverRepo, new File("../common/src/test/resources/data/hgrepo.hgbundle"));
        workingDirectory = new File(clientRepo.getPath());
        hgCommand = new HgCommand(null, workingDirectory, "default", serverRepo.getAbsolutePath(), null);
        hgCommand.clone(outputStreamConsumer, new UrlArgument(serverRepo.getAbsolutePath()));
    }


    public Map<String, String> handleCorsPreflightRequest(String pOrigin, String pRequestHeaders) {
        Map<String,String> ret = new HashMap<String, String>();
        if (pOrigin != null && backendManager.isCorsAccessAllowed(pOrigin)) {
            // CORS is allowed, we set exactly the origin in the header, so there are no problems with authentication
            ret.put("Access-Control-Allow-Origin","null".equals(pOrigin) ? "*" : pOrigin);
            if (pRequestHeaders != null) {
                ret.put("Access-Control-Allow-Headers",pRequestHeaders);
            }
            // Fix for CORS with authentication (#104)
            ret.put("Access-Control-Allow-Credentials","true");
            // Allow for one year. Changes in access.xml are reflected directly in the  cors request itself
            ret.put("Access-Control-Allow-Max-Age","" + 3600 * 24 * 365);
        }
        return ret;
    }


    public void simpleGetWithUnsupportedGetParameterMapCall() throws ServletException, IOException {
        prepareStandardInitialisation();
        StringWriter sw = initRequestResponseMocks(
                new Runnable() {
                    public void run() {
                        expect(request.getHeader("Origin")).andReturn(null);
                        expect(request.getRemoteHost()).andReturn("localhost");
                        expect(request.getRemoteAddr()).andReturn("127.0.0.1");
                        expect(request.getRequestURI()).andReturn("/jolokia/");
                        expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
                        expect(request.getParameterMap()).andThrow(new UnsupportedOperationException(""));
                        Vector params = new Vector();
                        params.add("debug");
                        expect(request.getParameterNames()).andReturn(params.elements());
                        expect(request.getParameterValues("debug")).andReturn(new String[] {"false"});
                    }
                },
                getStandardResponseSetup());
        expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
        replay(request,response);

        servlet.doGet(request,response);
        servlet.destroy();
    }


    public void annotatedSubClassExample() throws Exception {
        assertThat(ConstraintViolations.format(validator.validate(new AnnotatedSubclassExample())))
            .containsExactlyInAnyOrder(
                    FAILED_RESULT,
                    FAILED_RESULT+"subclass"
            );
        assertThat(TestLoggerFactory.getAllLoggingEvents())
            .isEmpty();
    }


  public void setUp() throws Exception {
    super.setUp();
    TestUtil.createTempTable(con, "xmltab","x xml");
  }


    public void translate(ServerUpdateScorePacket packet, GeyserSession session) {
        WorldCache worldCache = session.getWorldCache();
        Scoreboard scoreboard = worldCache.getScoreboard();
        int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond();

        Objective objective = scoreboard.getObjective(packet.getObjective());
        if (objective == null && packet.getAction() != ScoreboardAction.REMOVE) {
            logger.info(LanguageUtils.getLocaleStringLog("geyser.network.translator.score.failed_objective", packet.getObjective()));
            return;
        }

        switch (packet.getAction()) {
            case ADD_OR_UPDATE:
                objective.setScore(packet.getEntry(), packet.getValue());
                break;
            case REMOVE:
                if (objective != null) {
                    objective.removeScore(packet.getEntry());
                } else {
                    for (Objective objective1 : scoreboard.getObjectives().values()) {
                        objective1.removeScore(packet.getEntry());
                    }
                }
                break;
        }

        // ScoreboardUpdater will handle it for us if the packets per second
        // (for score and team packets) is higher then the first threshold
        if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) {
            scoreboard.onUpdate();
        }
    }


	public void reportJobCaches(byte[] cacheInstanceBytes) {
		@SuppressWarnings("unchecked")
		Collection<CacheInstance> cacheInstances = (Collection<CacheInstance>) SerializationUtils
				.deserialize(cacheInstanceBytes);
		jobManager.reportJobCaches(getJobToken(), cacheInstances);
	}


    public void translate(LoginPluginRequestPacket packet, GeyserSession session) {
        // A vanilla client doesn't know any PluginMessage in the Login state, so we don't know any either.
        // Note: Fabric Networking API v1 will not let the client log in without sending this
        session.sendDownstreamPacket(
                new LoginPluginResponsePacket(packet.getMessageId(), null)
        );
    }


    public void translate(RiderJumpPacket packet, GeyserSession session) {
        Entity vehicle = session.getRidingVehicleEntity();
        if (vehicle instanceof AbstractHorseEntity) {
            ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(),  PlayerState.START_HORSE_JUMP, packet.getJumpStrength());
            session.sendDownstreamPacket(playerStatePacket);
        }
    }


    public void initWithcustomAccessRestrictor() throws ServletException {
        prepareStandardInitialisation();
        servlet.destroy();
    }


  public static final void testClosedArray() {
    // Discovered by fuzzer with seed -Dfuzz.seed=df3b4778ce54d00a
    assertSanitized("-1742461140214282", "\ufeff-01742461140214282]");
  }


	public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
			byte[] ciphertext, int ciphertextOffset, int length)
			throws ShortBufferException {
		int space;
		if (ciphertextOffset > ciphertext.length)
			space = 0;
		else
			space = ciphertext.length - ciphertextOffset;
		if (keySpec == null) {
			// The key is not set yet - return the plaintext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
			return length;
		}
		if (space < 16 || length > (space - 16))
			throw new ShortBufferException();
		try {
			setup(ad);
			int result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset);
			cipher.doFinal(ciphertext, ciphertextOffset + result);
		} catch (InvalidKeyException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (InvalidAlgorithmParameterException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (IllegalBlockSizeException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (BadPaddingException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		}
		ghash.update(ciphertext, ciphertextOffset, length);
		ghash.pad(ad != null ? ad.length : 0, length);
		ghash.finish(ciphertext, ciphertextOffset + length, 16);
		for (int index = 0; index < 16; ++index)
			ciphertext[ciphertextOffset + length + index] ^= hashKey[index];
		return length + 16;
	}


    public String getEncoding() {
        return encoding;
    }


    private static File newFile() throws IOException {
        File file = File.createTempFile("netty-", ".tmp");
        file.deleteOnExit();

        final FileOutputStream out = new FileOutputStream(file);
        out.write(data);
        out.close();
        return file;
    }


    public void newDocumentWebHomeTopLevelSpaceButTerminalFromURL() throws Exception
    {
        // new document = xwiki:X.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(true);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Pass the tocreate=terminal request parameter
        when(mockRequest.getParameter("tocreate")).thenReturn("terminal");

        // Run the action
        String result = action.render(context);

        // The tests are below this line!

        // Verify that the create template is rendered, so the UI is displayed for the user to enter the missing values.
        assertEquals("create", result);

        // Note: We can not create the "X" terminal document, since it is already at the top level of the hierarchy and
        // none was able to be deducted from the given information. The user needs to specify more info in order to
        // continue.
        // We should not get this far so no redirect should be done, just the template will be rendered.
        verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),
            any(), any(XWikiContext.class));
    }


    private void renderState(FacesContext context) throws IOException {
        // Get the view state and write it to the response..
        PartialViewContext pvc = context.getPartialViewContext();
        PartialResponseWriter writer = pvc.getPartialResponseWriter();
        String viewStateId = Util.getViewStateId(context);

        writer.startUpdate(viewStateId);
        String state = context.getApplication().getStateManager().getViewState(context);
        writer.write(state);
        writer.endUpdate();

        ClientWindow window = context.getExternalContext().getClientWindow();
        if (null != window) {
            String clientWindowId = Util.getClientWindowId(context);
            writer.startUpdate(clientWindowId);
            writer.write(window.getId());
            writer.endUpdate();
        }
    }


    public void warning(SAXParseException e) {
    }


    public void testGetChunk() throws Exception {
        TestHttpData test = new TestHttpData("test", UTF_8, 0);
        try {
            File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
            tmpFile.deleteOnExit();
            FileOutputStream fos = new FileOutputStream(tmpFile);
            byte[] bytes = new byte[4096];
            PlatformDependent.threadLocalRandom().nextBytes(bytes);
            try {
                fos.write(bytes);
                fos.flush();
            } finally {
                fos.close();
            }
            test.setContent(tmpFile);
            ByteBuf buf1 = test.getChunk(1024);
            assertEquals(buf1.readerIndex(), 0);
            assertEquals(buf1.writerIndex(), 1024);
            ByteBuf buf2 = test.getChunk(1024);
            assertEquals(buf2.readerIndex(), 0);
            assertEquals(buf2.writerIndex(), 1024);
            assertFalse("Arrays should not be equal",
                    Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));
        } finally {
            test.delete();
        }
    }


	public String displayCategoryWithReference(@PathVariable final String friendlyUrl, @PathVariable final String ref, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {

		return this.displayCategory(friendlyUrl,ref,model,request,response,locale);
	}


    public void getWithDefaultValueWorks() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.add("name1", "value1");

        assertThat(headers.get("name1", "defaultvalue")).isEqualTo("value1");
        assertThat(headers.get("noname", "defaultvalue")).isEqualTo("defaultvalue");
    }


	final protected Style getStyle() {
		return getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder());

	}


    public boolean verify(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET))
                .withIssuer(ISSUER)
                .build();
        try {
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            log.warn("verify jwt token failed " + e.getMessage());
            return false;
        }
    }


  public void write(byte[] b, int offset, int length) throws IOException {
    if (b == null) {
      throw new NullPointerException();
    }

    if (offset < 0 || offset + length > b.length) {
      throw new ArrayIndexOutOfBoundsException();
    }

    write(fd, b, offset, length);
  }


		protected Class<?> getClassForNode(Node node) {
			Class<?> type = node.getType();
			if (type.getAnnotation(Editable.class) != null && !ClassUtils.isConcrete(type)) {
				ImplementationRegistry registry = OneDev.getInstance(ImplementationRegistry.class);
				for (Class<?> implementationClass: registry.getImplementations(node.getType())) {
					String implementationTag = new Tag("!" + implementationClass.getSimpleName()).getValue();
					if (implementationTag.equals(node.getTag().getValue()))
						return implementationClass;
				}
			}

			return super.getClassForNode(node);
		}


    private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String oldName = request.getParameter("groupName");
        String newName = request.getParameter("newName");

        if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
            m_groupRepository.renameGroup(oldName, newName);
        }

        return listGroups(request, response);
    }


    public PropertiesRequest getRequestedFields( InputStream in ) {
		final Set<QName> set = new LinkedHashSet<QName>();
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            StreamUtils.readTo( in, bout, false, true );
            byte[] arr = bout.toByteArray();
            if( arr.length > 1 ) {
                ByteArrayInputStream bin = new ByteArrayInputStream( arr );
                XMLReader reader = XMLReaderFactory.createXMLReader();
				reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
                PropFindSaxHandler handler = new PropFindSaxHandler();
                reader.setContentHandler( handler );
                try {
                    reader.parse( new InputSource( bin ) );
                    if( handler.isAllProp() ) {
                        return new PropertiesRequest();
                    } else {
                        set.addAll( handler.getAttributes().keySet() );
                    }
                } catch( IOException e ) {
                    log.warn( "exception parsing request body", e );
                    // ignore
                } catch( SAXException e ) {
                    log.warn( "exception parsing request body", e );
                    // ignore
                }
            }
        } catch( Exception ex ) {
			// There's a report of an exception being thrown here by IT Hit Webdav client
			// Perhaps we can just log the error and return an empty set. Usually this
			// class is wrapped by the MsPropFindRequestFieldParser which will use a default
			// set of properties if this returns an empty set
			log.warn("Exception parsing PROPFIND request fields. Returning empty property set", ex);
            //throw new RuntimeException( ex );
        }
		return PropertiesRequest.toProperties(set);
    }


    void validSaveRequestImageUploadAndConflictCheck() throws Exception
    {
        when(mockDocument.getRCSVersion()).thenReturn(new Version("1.2"));
        when(mockClonedDocument.getRCSVersion()).thenReturn(new Version("1.2"));
        when(mockClonedDocument.getComment()).thenReturn("My Changes");
        when(mockClonedDocument.getLock(this.context)).thenReturn(mock(XWikiLock.class));
        when(mockForm.getTemplate()).thenReturn("");
        when(this.propertiesConf.getProperty("edit.conflictChecking.enabled")).thenReturn(true);
        when(mockRequest.getParameter("previousVersion")).thenReturn("1.1");
        context.put("ajax", true);
        when(mockRequest.getParameter("forceSave")).thenReturn("");
        when(mockRequest.getParameter("isNew")).thenReturn("true");

        when(mockDocument.getDate()).thenReturn(new Date(42));
        when(mockRequest.getParameter("editingVersionDate")).thenReturn("43");
        when(this.documentRevisionProvider.getRevision(mockDocument, "1.1")).thenReturn(mock(XWikiDocument.class));
        when(mockDocument.getContentDiff("1.1", "1.2", context)).thenReturn(Collections.emptyList());
        when(mockDocument.getMetaDataDiff("1.1", "1.2", context)).thenReturn(Collections.emptyList());
        when(mockDocument.getObjectDiff("1.1", "1.2", context)).thenReturn(Collections.emptyList());

        assertFalse(saveAction.save(this.context));
        assertEquals(new Version("1.2"), this.context.get("SaveAction.savedObjectVersion"));

        verify(mockClonedDocument).readFromTemplate("", this.context);
        verify(mockClonedDocument).setAuthor("XWiki.FooBar");
        verify(mockClonedDocument).setMetaDataDirty(true);
        verify(this.xWiki).checkSavingDocument(USER_REFERENCE, mockClonedDocument, "My Changes", false, this.context);
        verify(this.xWiki).saveDocument(mockClonedDocument, "My Changes", false, this.context);
        verify(mockClonedDocument).removeLock(this.context);

    }


    public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)
        throws IOException
    {
        XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
        this.treeDigest = keyParams.getTreeDigest().getAlgorithm();

        XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());

        try
        {
            XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters
                .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))
                .withIndex(xmssPrivateKey.getIndex())
                .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())
                .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())
                .withPublicSeed(xmssPrivateKey.getPublicSeed())
                .withRoot(xmssPrivateKey.getRoot());

            if (xmssPrivateKey.getBdsState() != null)
            {
                keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));
            }

            this.keyParams = keyBuilder.build();
        }
        catch (ClassNotFoundException e)
        {
            throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
        }
    }


    public Document read(File file) throws DocumentException {
        try {
            /*
             * We cannot convert the file to an URL because if the filename
             * contains '#' characters, there will be problems with the URL in
             * the InputSource (because a URL like
             * http://myhost.com/index#anchor is treated the same as
             * http://myhost.com/index) Thanks to Christian Oetterli
             */
            InputSource source = new InputSource(new FileInputStream(file));
            if (this.encoding != null) {
                source.setEncoding(this.encoding);
            }
            String path = file.getAbsolutePath();

            if (path != null) {
                // Code taken from Ant FileUtils
                StringBuffer sb = new StringBuffer("file://");

                // add an extra slash for filesystems with drive-specifiers
                if (!path.startsWith(File.separator)) {
                    sb.append("/");
                }

                path = path.replace('\\', '/');
                sb.append(path);

                source.setSystemId(sb.toString());
            }

            return read(source);
        } catch (FileNotFoundException e) {
            throw new DocumentException(e.getMessage(), e);
        }
    }


    public DefaultArgument(Class<T> type, String name, AnnotationMetadata annotationMetadata, Argument... genericTypes) {
        this.type = type;
        this.name = name;
        this.annotationMetadata = annotationMetadata != null ? annotationMetadata : AnnotationMetadata.EMPTY_METADATA;
        this.typeParameters = initializeTypeParameters(genericTypes);
        this.typeParameterArray = genericTypes;
    }


    public DocumentFactory getDocumentFactory() {
        if (factory == null) {
            factory = DocumentFactory.getInstance();
        }

        return factory;
    }


    public void translate(ServerPluginMessagePacket packet, GeyserSession session) {
        // The only plugin messages it has to listen for are Floodgate plugin messages
        if (session.getRemoteAuthType() != AuthType.FLOODGATE) {
            return;
        }

        String channel = packet.getChannel();

        if (channel.equals("floodgate:form")) {
            byte[] data = packet.getData();

            // receive: first byte is form type, second and third are the id, remaining is the form data
            // respond: first and second byte id, remaining is form response data

            FormType type = FormType.getByOrdinal(data[0]);
            if (type == null) {
                throw new NullPointerException(
                        "Got type " + data[0] + " which isn't a valid form type!");
            }

            String dataString = new String(data, 3, data.length - 3, Charsets.UTF_8);

            Form form = Forms.fromJson(dataString, type);
            form.setResponseHandler(response -> {
                byte[] raw = response.getBytes(StandardCharsets.UTF_8);
                byte[] finalData = new byte[raw.length + 2];

                finalData[0] = data[1];
                finalData[1] = data[2];
                System.arraycopy(raw, 0, finalData, 2, raw.length);

                session.sendDownstreamPacket(new ClientPluginMessagePacket(channel, finalData));
            });
            session.sendForm(form);
        }
    }


    public void translate(ServerEntityPositionRotationPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }
        if (entity == null) return;

        entity.updatePositionAndRotation(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), packet.getYaw(), packet.getPitch(), packet.isOnGround());
    }


    private boolean pull(ConsoleOutputStreamConsumer outputStreamConsumer) {
        CommandLine hg = hg("pull", "-b", branch, "--config", String.format("paths.default=%s", url));
        return execute(hg, outputStreamConsumer) == 0;
    }


    public static void encryptPlayerConnection(GeyserConnector connector, GeyserSession session, LoginPacket loginPacket) {
        JsonNode certData;
        try {
            certData = JSON_MAPPER.readTree(loginPacket.getChainData().toByteArray());
        } catch (IOException ex) {
            throw new RuntimeException("Certificate JSON can not be read.");
        }

        JsonNode certChainData = certData.get("chain");
        if (certChainData.getNodeType() != JsonNodeType.ARRAY) {
            throw new RuntimeException("Certificate data is not valid");
        }

        encryptConnectionWithCert(connector, session, loginPacket.getSkinData().toString(), certChainData);
    }


	public String displayCategoryWithReference(@PathVariable final String friendlyUrl, @PathVariable final String ref, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {

		return this.displayCategory(friendlyUrl,ref,model,request,response,locale);
	}


	public static byte[] transcodeSignatureToConcat(final byte[] derSignature, int outputLength)
		throws JOSEException {

		if (derSignature.length < 8 || derSignature[0] != 48) {
			throw new JOSEException("Invalid  ECDSA signature format");
		}

		int offset;
		if (derSignature[1] > 0) {
			offset = 2;
		} else if (derSignature[1] == (byte) 0x81) {
			offset = 3;
		} else {
			throw new JOSEException("Invalid  ECDSA signature format");
		}

		byte rLength = derSignature[offset + 1];

		int i;
		for (i = rLength; (i > 0) && (derSignature[(offset + 2 + rLength) - i] == 0); i--) {
			// do nothing
		}

		byte sLength = derSignature[offset + 2 + rLength + 1];

		int j;
		for (j = sLength; (j > 0) && (derSignature[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--) {
			// do nothing
		}

		int rawLen = Math.max(i, j);
		rawLen = Math.max(rawLen, outputLength / 2);

		if ((derSignature[offset - 1] & 0xff) != derSignature.length - offset
			|| (derSignature[offset - 1] & 0xff) != 2 + rLength + 2 + sLength
			|| derSignature[offset] != 2
			|| derSignature[offset + 2 + rLength] != 2) {
			throw new JOSEException("Invalid  ECDSA signature format");
		}

		final byte[] concatSignature = new byte[2 * rawLen];

		System.arraycopy(derSignature, (offset + 2 + rLength) - i, concatSignature, rawLen - i, i);
		System.arraycopy(derSignature, (offset + 2 + rLength + 2 + sLength) - j, concatSignature, 2 * rawLen - j, j);

		return concatSignature;
	}


    /*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) throws UnsupportedEncodingException {
        try {
            String plainText = new String(cipher.doFinal(in), "UTF-8");
            if(plainText.endsWith(MAGIC))
                return new Secret(plainText.substring(0,plainText.length()-MAGIC.length()));
            return null;
        } catch (GeneralSecurityException e) {
            return null; // if the key doesn't match with the bytes, it can result in BadPaddingException
        }
    }


    public Optional<CorsOriginConfiguration> convert(Object object, Class<CorsOriginConfiguration> targetType, ConversionContext context) {
        CorsOriginConfiguration configuration = new CorsOriginConfiguration();
        if (object instanceof Map) {
            Map mapConfig = (Map) object;
            ConvertibleValues<Object> convertibleValues = new ConvertibleValuesMap<>(mapConfig);

            convertibleValues
                .get(ALLOWED_ORIGINS, Argument.listOf(String.class))
                .ifPresent(configuration::setAllowedOrigins);

            convertibleValues
                .get(ALLOWED_METHODS, Argument.listOf(HttpMethod.class))
                .ifPresent(configuration::setAllowedMethods);

            convertibleValues
                .get(ALLOWED_HEADERS, Argument.listOf(String.class))
                .ifPresent(configuration::setAllowedHeaders);

            convertibleValues
                .get(EXPOSED_HEADERS, Argument.listOf(String.class))
                .ifPresent(configuration::setExposedHeaders);

            convertibleValues
                .get(ALLOW_CREDENTIALS, Boolean.class)
                .ifPresent(configuration::setAllowCredentials);

            convertibleValues
                .get(MAX_AGE, Long.class)
                .ifPresent(configuration::setMaxAge);
        }
        return Optional.of(configuration);
    }


	public static ResourceEvaluation evaluate(File file, String filename) {
		ResourceEvaluation eval = new ResourceEvaluation();
		try {
			ImsManifestFileFilter visitor = new ImsManifestFileFilter();
			Path fPath = PathUtils.visit(file, filename, visitor);
			if(visitor.isValid()) {
				Path realManifestPath = visitor.getManifestPath();
				Path manifestPath = fPath.resolve(realManifestPath);

				RootSearcher rootSearcher = new RootSearcher();
				Files.walkFileTree(fPath, rootSearcher);
				if(rootSearcher.foundRoot()) {
					manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);
				} else {
					manifestPath = fPath.resolve(IMS_MANIFEST);
				}

				QTI21ContentPackage	cp = new QTI21ContentPackage(manifestPath);
				if(validateImsManifest(cp, new PathResourceLocator(manifestPath.getParent()))) {
					eval.setValid(true);
				} else {
					eval.setValid(false);
				}
			} else {
				eval.setValid(false);
			}
			PathUtils.closeSubsequentFS(fPath);
		} catch (IOException | IllegalArgumentException e) {
			log.error("", e);
			eval.setValid(false);
		}
		return eval;
	}


    public void corsNoTags() {
        InputStream is = getClass().getResourceAsStream("/access-sample1.xml");
        PolicyRestrictor restrictor = new PolicyRestrictor(is);

        assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
        assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
        assertTrue(restrictor.isCorsAccessAllowed("https://www.consol.de"));
    }


    protected XWikiDocument prepareEditedDocument(XWikiContext context) throws XWikiException
    {
        // Determine the edited document (translation).
        XWikiDocument editedDocument = getEditedDocument(context);
        EditForm editForm = (EditForm) context.getForm();

        // Update the edited document based on the template specified on the request.
        editedDocument.readFromTemplate(editForm, context);

        // The default values from the template can be overwritten by additional request parameters.
        updateDocumentTitleAndContentFromRequest(editedDocument, context);
        editedDocument.readObjectsFromForm(editForm, context);

        // Set the current user as creator, author and contentAuthor when the edited document is newly created to avoid
        // using XWikiGuest instead (because those fields were not previously initialized).
        if (editedDocument.isNew()) {
            editedDocument.setCreatorReference(context.getUserReference());
            editedDocument.setAuthorReference(context.getUserReference());
            editedDocument.setContentAuthorReference(context.getUserReference());
        }

        // Expose the edited document on the XWiki context and the Velocity context.
        putDocumentOnContext(editedDocument, context);

        return editedDocument;
    }


	public static HColor noGradient(HColor color) {
		if (color instanceof HColorGradient) {
			return ((HColorGradient) color).getColor1();
		}
		return color;
	}


    public void preflightCheck() {
        String origin = "http://bla.com";
        String headers ="X-Data: Test";
        expect(backend.isCorsAccessAllowed(origin)).andReturn(true);
        replay(backend);

        Map<String,String> ret =  handler.handleCorsPreflightRequest(origin, headers);
        assertEquals(ret.get("Access-Control-Allow-Origin"),origin);
    }


    protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)
    {
        for (int i = 0; i != 5 * bitlength; i++)
        {
            BigInteger p = new BigInteger(bitlength, 1, param.getRandom());

            if (p.mod(e).equals(ONE))
            {
                continue;
            }

            if (p.multiply(p).compareTo(sqrdBound) < 0)
            {
                continue;
            }

            if (!isProbablePrime(p))
            {
                continue;
            }

            if (!e.gcd(p.subtract(ONE)).equals(ONE))
            {
                continue;
            }

            return p;
        }

        throw new IllegalStateException("unable to generate prime number for RSA key");
    }


    public SecretRewriter() throws GeneralSecurityException {
        cipher = Secret.getCipher("AES");
        key = Secret.getLegacyKey();
    }


		private void drawSingleCluster(UGraphic ug, IGroup group, ElkNode elkNode) {
			final Point2D corner = getPosition(elkNode);
			final URectangle rect = new URectangle(elkNode.getWidth(), elkNode.getHeight());

			PackageStyle packageStyle = group.getPackageStyle();
			final ISkinParam skinParam = diagram.getSkinParam();
			if (packageStyle == null)
				packageStyle = skinParam.packageStyle();

			final UmlDiagramType umlDiagramType = diagram.getUmlDiagramType();

			final Style style = Cluster.getDefaultStyleDefinition(umlDiagramType.getStyleName(), group.getUSymbol())
					.getMergedStyle(skinParam.getCurrentStyleBuilder());
			final double shadowing = style.value(PName.Shadowing).asDouble();
			final UStroke stroke = Cluster.getStrokeInternal(group, skinParam, style);

			HColor backColor = getBackColor(umlDiagramType);
			backColor = Cluster.getBackColor(backColor, skinParam, group.getStereotype(), umlDiagramType.getStyleName(),
					group.getUSymbol());

			final double roundCorner = group.getUSymbol() == null ? 0
					: group.getUSymbol().getSkinParameter().getRoundCorner(skinParam, group.getStereotype());

			final TextBlock ztitle = getTitleBlock(group);
			final TextBlock zstereo = TextBlockUtils.empty(0, 0);

			final ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle,
					zstereo, 0, 0, elkNode.getWidth(), elkNode.getHeight(), stroke);

			final HColor borderColor = HColorUtils.BLACK;
			decoration.drawU(ug.apply(new UTranslate(corner)), backColor, borderColor, shadowing, roundCorner,
					skinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null),
					skinParam.getStereotypeAlignment(), 0);

//			// Print a simple rectangle right now
//			ug.apply(HColorUtils.BLACK).apply(new UStroke(1.5)).apply(new UTranslate(corner)).draw(rect);
		}


	private static void addMagic(SName sname) {
		final String cleanName = sname.name().replace("_", "");
		addConvert(cleanName + "BackgroundColor", PName.BackGroundColor, sname);
		addConvert(cleanName + "BorderColor", PName.LineColor, sname);
		addConvert(cleanName + "BorderThickness", PName.LineThickness, sname);
		addConvert(cleanName + "RoundCorner", PName.RoundCorner, sname);
		addConvert(cleanName + "DiagonalCorner", PName.DiagonalCorner, sname);
		addConvert(cleanName + "BorderStyle", PName.LineStyle, sname);
		addConvert(cleanName + "StereotypeFontColor", PName.FontColor, SName.stereotype, sname);
		addConFont(cleanName, sname);
	}


    public DefaultFileSystemResourceLoader() {
        this.baseDirPath = Optional.empty();
    }


    void doubleDots() {
        assertThat(PathAndQuery.parse("/..")).isNull();
        assertThat(PathAndQuery.parse("/../")).isNull();
        assertThat(PathAndQuery.parse("/../foo")).isNull();
        assertThat(PathAndQuery.parse("/foo/..")).isNull();
        assertThat(PathAndQuery.parse("/foo/../")).isNull();
        assertThat(PathAndQuery.parse("/foo/../bar")).isNull();

        // Escaped
        assertThat(PathAndQuery.parse("/.%2e")).isNull();
        assertThat(PathAndQuery.parse("/%2E./")).isNull();
        assertThat(PathAndQuery.parse("/foo/.%2e")).isNull();
        assertThat(PathAndQuery.parse("/foo/%2E./")).isNull();

        // Not the double dots we are looking for.
        final PathAndQuery res = PathAndQuery.parse("/..a");
        assertThat(res).isNotNull();
        assertThat(res.path()).isEqualTo("/..a");
        final PathAndQuery res2 = PathAndQuery.parse("/a..");
        assertThat(res2).isNotNull();
        assertThat(res2.path()).isEqualTo("/a..");
    }


	private Style getStyleState() {
		return StyleSignatureBasic.of(SName.root, SName.element, SName.stateDiagram, SName.state).withTOBECHANGED(group.getStereotype())
				.getMergedStyle(diagram.getSkinParam().getCurrentStyleBuilder());
	}


    public void subClassExample() throws Exception {
        assertThat(ConstraintViolations.format(validator.validate(new SubclassExample())))
            .containsExactlyInAnyOrder(
                    FAILED_RESULT,
                    FAILED_RESULT+"subclass"
            );
        assertThat(TestLoggerFactory.getAllLoggingEvents())
            .isEmpty();
    }


    public static Object deserialize(byte[] data)
        throws IOException, ClassNotFoundException
    {
        ByteArrayInputStream in = new ByteArrayInputStream(data);
        ObjectInputStream is = new ObjectInputStream(in);
        return is.readObject();
    }


    public void encodeDeepBinaryJSONWithNullValue() throws JSONException {
        JSONObject data = new JSONObject("{a: \"b\", c: 4, e: {g: null}, h: null}");
        data.put("h", new byte[9]);

        Packet<JSONObject> packet = new Packet<>(Parser.BINARY_EVENT);
        packet.data = data;
        packet.nsp = "/";
        packet.id = 600;
        Helpers.testBin(packet);
    }


  private String buildRedirectAuthnRequest(AuthnRequestType authnRequest, String relayState, boolean sign,
                                           PrivateKey key, Algorithm algorithm) throws SAMLException {
    try {
      byte[] xml = marshallToBytes(PROTOCOL_OBJECT_FACTORY.createAuthnRequest(authnRequest), AuthnRequestType.class);
      String encodedResult = deflateAndEncode(xml);
      String parameters = "SAMLRequest=" + URLEncoder.encode(encodedResult, "UTF-8");
      if (relayState != null) {
        parameters += "&RelayState=" + URLEncoder.encode(relayState, "UTF-8");
      }

      if (sign && key != null && algorithm != null) {
        Signature signature;
        parameters += "&SigAlg=" + URLEncoder.encode(algorithm.uri, "UTF-8");
        signature = Signature.getInstance(algorithm.name);
        signature.initSign(key);
        signature.update(parameters.getBytes(StandardCharsets.UTF_8));

        String signatureParameter = Base64.getEncoder().encodeToString(signature.sign());
        parameters += "&Signature=" + URLEncoder.encode(signatureParameter, "UTF-8");
      }

      return parameters;
    } catch (Exception e) {
      // Not possible but freak out
      throw new SAMLException(e);
    }
  }


    private JWTClaimsSet fetchOidcProfile(BearerAccessToken accessToken) {
        final var userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(),
            accessToken);
        final var userInfoHttpRequest = userInfoRequest.toHTTPRequest();
        configuration.configureHttpRequest(userInfoHttpRequest);
        try {
            final var httpResponse = userInfoHttpRequest.send();
            logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(),
                httpResponse.getContent());
            final var userInfoResponse = UserInfoResponse.parse(httpResponse);
            if (userInfoResponse instanceof UserInfoErrorResponse) {
                logger.error("Bad User Info response, error={}",
                    ((UserInfoErrorResponse) userInfoResponse).getErrorObject().toJSONObject());
                throw new AuthenticationException();
            } else {
                final var userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
                final JWTClaimsSet userInfoClaimsSet;
                if (userInfoSuccessResponse.getUserInfo() != null) {
                    userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
                } else {
                    userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
                }
                return userInfoClaimsSet;
            }
        } catch (IOException | ParseException | java.text.ParseException | AuthenticationException e) {
            throw new TechnicalException(e);
        }
    }


	public int decryptWithAd(byte[] ad, byte[] ciphertext,
			int ciphertextOffset, byte[] plaintext, int plaintextOffset,
			int length) throws ShortBufferException, BadPaddingException {
		int space;
		if (ciphertextOffset > ciphertext.length)
			space = 0;
		else
			space = ciphertext.length - ciphertextOffset;
		if (length > space)
			throw new ShortBufferException();
		if (plaintextOffset > plaintext.length)
			space = 0;
		else
			space = plaintext.length - plaintextOffset;
		if (!haskey) {
			// The key is not set yet - return the ciphertext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
			return length;
		}
		if (length < 16)
			Noise.throwBadTagException();
		int dataLen = length - 16;
		if (dataLen > space)
			throw new ShortBufferException();
		setup(ad);
		poly.update(ciphertext, ciphertextOffset, dataLen);
		finish(ad, dataLen);
		int temp = 0;
		for (int index = 0; index < 16; ++index)
			temp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
		if ((temp & 0xFF) != 0)
			Noise.throwBadTagException();
		encrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);
		return dataLen;
	}


    public RoutingResultBuilder rawParam(String name, String value) {
        pathParams().put(requireNonNull(name, "name"),
                         ArmeriaHttpUtil.decodePath(requireNonNull(value, "value")));
        return this;
    }


    protected char[] getQuotingTriggerChars()
    {
        return BASH_QUOTING_TRIGGER_CHARS;
    }


  private AuthnRequestParseResult parseRequest(byte[] xmlBytes) throws SAMLException {
    String xml = new String(xmlBytes, StandardCharsets.UTF_8);
    if (logger.isDebugEnabled()) {
      logger.debug("SAMLRequest XML is\n{}", xml);
    }

    AuthnRequestParseResult result = new AuthnRequestParseResult();
    result.document = parseFromBytes(xmlBytes);
    result.authnRequest = unmarshallFromDocument(result.document, AuthnRequestType.class);
    result.request = new AuthenticationRequest();
    result.request.xml = xml;
    result.request.id = result.authnRequest.getID();
    result.request.issuer = result.authnRequest.getIssuer().getValue();
    result.request.issueInstant = result.authnRequest.getIssueInstant().toGregorianCalendar().toZonedDateTime();
    NameIDPolicyType nameIdPolicyType = result.authnRequest.getNameIDPolicy();
    if (nameIdPolicyType == null) {
      result.request.nameIdFormat = NameIDFormat.EmailAddress;
    } else {
      result.request.nameIdFormat = NameIDFormat.fromSAMLFormat(nameIdPolicyType.getFormat());
    }
    result.request.version = result.authnRequest.getVersion();
    return result;
  }


static __u8 *kye_report_fixup(struct hid_device *hdev, __u8 *rdesc,
		unsigned int *rsize)
{
	switch (hdev->product) {
	case USB_DEVICE_ID_KYE_ERGO_525V:
		/* the fixups that need to be done:
		 *   - change led usage page to button for extra buttons
		 *   - report size 8 count 1 must be size 1 count 8 for button
		 *     bitfield
		 *   - change the button usage range to 4-7 for the extra
		 *     buttons
		 */
		if (*rsize >= 74 &&
			rdesc[61] == 0x05 && rdesc[62] == 0x08 &&
			rdesc[63] == 0x19 && rdesc[64] == 0x08 &&
			rdesc[65] == 0x29 && rdesc[66] == 0x0f &&
			rdesc[71] == 0x75 && rdesc[72] == 0x08 &&
			rdesc[73] == 0x95 && rdesc[74] == 0x01) {
			hid_info(hdev,
				 "fixing up Kye/Genius Ergo Mouse "
				 "report descriptor\n");
			rdesc[62] = 0x09;
			rdesc[64] = 0x04;
			rdesc[66] = 0x07;
			rdesc[72] = 0x01;
			rdesc[74] = 0x08;
		}
		break;
	case USB_DEVICE_ID_KYE_EASYPEN_I405X:
		if (*rsize == EASYPEN_I405X_RDESC_ORIG_SIZE) {
			rdesc = easypen_i405x_rdesc_fixed;
			*rsize = sizeof(easypen_i405x_rdesc_fixed);
		}
		break;
	case USB_DEVICE_ID_KYE_MOUSEPEN_I608X:
		if (*rsize == MOUSEPEN_I608X_RDESC_ORIG_SIZE) {
			rdesc = mousepen_i608x_rdesc_fixed;
			*rsize = sizeof(mousepen_i608x_rdesc_fixed);
		}
		break;
	case USB_DEVICE_ID_KYE_EASYPEN_M610X:
		if (*rsize == EASYPEN_M610X_RDESC_ORIG_SIZE) {
			rdesc = easypen_m610x_rdesc_fixed;
			*rsize = sizeof(easypen_m610x_rdesc_fixed);
		}
		break;
	case USB_DEVICE_ID_GENIUS_GILA_GAMING_MOUSE:
		rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104,
					"Genius Gila Gaming Mouse");
		break;
	case USB_DEVICE_ID_GENIUS_GX_IMPERATOR:
		rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 83,
					"Genius Gx Imperator Keyboard");
		break;
	case USB_DEVICE_ID_GENIUS_MANTICORE:
		rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104,
					"Genius Manticore Keyboard");
		break;
	}
	return rdesc;
}


    void requestResetPasswordUnexistingUser()
    {
        when(this.userReference.toString()).thenReturn("user:Foobar");
        when(this.userManager.exists(this.userReference)).thenReturn(false);
        String exceptionMessage = "User [user:Foobar] doesn't exist";
        when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noUser",
            "user:Foobar")).thenReturn(exceptionMessage);
        ResetPasswordException resetPasswordException = assertThrows(ResetPasswordException.class,
            () -> this.resetPasswordManager.requestResetPassword(this.userReference));
        assertEquals(exceptionMessage, resetPasswordException.getMessage());
    }


	public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
			byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException {
		int space;
		if (ciphertextOffset > ciphertext.length)
			space = 0;
		else
			space = ciphertext.length - ciphertextOffset;
		if (!haskey) {
			// The key is not set yet - return the plaintext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
			return length;
		}
		if (space < 16 || length > (space - 16))
			throw new ShortBufferException();
		setup(ad);
		encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
		poly.update(ciphertext, ciphertextOffset, length);
		finish(ad, length);
		System.arraycopy(polyKey, 0, ciphertext, ciphertextOffset + length, 16);
		return length + 16;
	}


    public void existingDocumentNonTerminalFromUIDeprecatedCheckEscaping() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Submit from the UI space=X.Y&tocreate=space
        when(mockRequest.getParameter("space")).thenReturn("X.Y");
        when(mockRequest.getParameter("tocreate")).thenReturn("space");

        // Run the action
        String result = action.render(context);

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note1: The space parameter was previously considered as space name, not space reference, so it is escaped.
        // Note2: We are creating X\.Y.WebHome because the tocreate parameter says "space".
        verify(mockURLFactory).createURL("X\\.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=X.Y", null,
            "xwiki", context);
    }


	public void onTurnEnded(TurnEndedEvent event) {
		super.onTurnEnded(event);

		final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();

		if (out.contains("access denied (java.net.SocketPermission")
				|| out.contains("access denied (\"java.net.SocketPermission\"")) {
			messagedAccessDenied = true;
		}
	}


  private String attributeToString(Object attribute) {
    if (attribute == null) {
      return null;
    }

    if (attribute instanceof Number) {
      return attribute.toString();
    } else if (attribute instanceof String) {
      return (String) attribute;
    } else if (attribute instanceof Element) {
      return ((Element) attribute).getTextContent();
    } else {
      logger.warn("This library currently doesn't handle attributes of type [" + attribute.getClass() + "]");
    }

    return null;
  }


    public AbstractXmlConfigRootTagRecognizer(String expectedRootNode) throws Exception {
        this.expectedRootNode = expectedRootNode;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        saxParser = factory.newSAXParser();
    }


        setImmediate(() => {
            if (!this.pendingPublishRequestCount) {
                return;
            }
            const starving_subscription = this._find_starving_subscription();
            if (starving_subscription) {
                doDebug && debugLog(chalk.bgWhite.red("feeding most late subscription subscriptionId  = "), starving_subscription.id);
                starving_subscription.process_subscription();
            }
        });


	public static Path visit(File file, String filename, FileVisitor<Path> visitor)
	throws IOException, IllegalArgumentException {
		if(!StringHelper.containsNonWhitespace(filename)) {
			filename = file.getName();
		}

		Path fPath = null;
		if(file.isDirectory()) {
			fPath = file.toPath();
		} else if(filename != null && filename.toLowerCase().endsWith(".zip")) {
			try {
				fPath = FileSystems.newFileSystem(file.toPath(), null).getPath("/");
			} catch (ProviderNotFoundException | ServiceConfigurationError e) {
				throw new IOException("Unreadable file with .zip extension: " + file, e);
			}
		} else {
			fPath = file.toPath();
		}
		if(fPath != null) {
		    Files.walkFileTree(fPath, visitor);
		}
		return fPath;
	}