text:
from kafkatest.directory_layout.kafka_path import TOOLS_JAR_NAME, TOOLS_DEPENDANT_TEST_LIBS_JAR_NAME
from kafkatest.version import DEV_BRANCH, LATEST_0_8_2
from ducktape.cluster.remoteaccount import RemoteCommandError

import importlib
import os
import subprocess
import signal
from kafkatest.services.kafka.util import fix_opts_for_new_jvm

"""This module abstracts the implementation of a verifiable client, allowing
client developers to plug in their own client for all kafkatests that make
use of either the VerifiableConsumer or VerifiableProducer classes.

A verifiable client class must implement exec_cmd() and pids().

This file provides:
 * VerifiableClientMixin class: to be used for creating new verifiable client classes
 * VerifiableClientJava class: the default Java verifiable clients
 * VerifiableClientApp class: uses global configuration to specify
   the command to execute and optional "pids" command, deploy script, etc.
   Config syntax (pass as --global <json_or_jsonfile>):
      {"Verifiable(Producer|Consumer|Client)": {
       "class": "kafkatest.services.verifiable_client.VerifiableClientApp",
       "exec_cmd": "/vagrant/x/myclient --some --standard --args",
       "pids": "pgrep -f ...", // optional
       "deploy": "/vagrant/x/mydeploy.sh", // optional
       "kill_signal": 2 // optional clean_shutdown kill signal (SIGINT in this case)
      }}
 * VerifiableClientDummy class: testing dummy

==============================
Verifiable client requirements
==============================

There are currently two verifiable client specifications:
 * VerifiableConsumer
 * VerifiableProducer

Common requirements for both:
 * One-way communication (client -> tests) through new-line delimited
   JSON objects on stdout (details below).
 * Log/debug to stderr

Common communication for both:
 * `{ "name": "startup_complete" }` - Client succesfully started
 * `{ "name": "shutdown_complete" }` - Client succesfully terminated (after receiving SIGINT/SIGTERM)

==================
VerifiableConsumer
==================

Command line arguments:
 * `--group-id <group-id>`
 * `--topic <topic>`
 * `--broker-list <brokers>`
 * `--session-timeout <n>`
 * `--enable-autocommit`
 * `--max-messages <n>`
 * `--assignment-strategy <s>`
 * `--consumer.config <config-file>` - consumer config properties (typically empty)

Environment variables:
 * `LOG_DIR` - log output directory. Typically not needed if logs are written to stderr.
 * `KAFKA_OPTS` - Security config properties (Java client syntax)
 * `KAFKA_LOG4J_OPTS` - Java log4j options (can be ignored)

Client communication:
 * `{ "name": "offsets_committed",  "success": bool, "error": "<errstr>", "offsets": [ { "topic": "<t>", "partition": <p>, "offset": <o> } ] }` - offset commit results, should be emitted for each committed offset. Emit prior to partitions_revoked.
 * `{ "name": "records_consumed", "partitions": [ { "topic": "<t>", "partition": <p>,  "minOffset": <o>, "maxOffset": <o> } ], "count": <total_consumed> }` - per-partition delta stats from last records_consumed. Emit every 1000 messages, or 1s. Emit prior to partitions_assigned, partitions_revoked and offsets_committed.
 * `{ "name": "partitions_revoked", "partitions": [ { "topic": "<t>", "partition": <p> } ] }` - rebalance: revoked partitions
 * `{ "name": "partitions_assigned", "partitions": [ { "topic": "<t>", "partition": <p> } ] }` - rebalance: assigned partitions

==================
VerifiableProducer
==================

Command line arguments:
 * `--topic <topic>`
 * `--broker-list <brokers>`
 * `--max-messages <n>`
 * `--throughput <msgs/s>`
 * `--producer.config <config-file>` - producer config properties (typically empty)

Environment variables:
 * `LOG_DIR` - log output directory. Typically not needed if logs are written to stderr.
 * `KAFKA_OPTS` - Security config properties (Java client syntax)
 * `KAFKA_LOG4J_OPTS` - Java log4j options (can be ignored)

Client communication:
 * `{ "name": "producer_send_error", "message": "<error msg>", "topic": "<t>", "key": "<msg key>", "value": "<msg value>" }` - emit on produce error.
 * `{ "name": "producer_send_success", "topic": "<t>", "partition": <p>, "offset": <o>, "key": "<msg key>", "value": "<msg value>" }` - emit on produce success.

===========
Development
===========

**Logs:**
During development of kafkatest clients it is generally a good idea to
enable collection of the client's stdout and stderr logs for troubleshooting.
Do this by setting "collect_default" to True for verifiable_consumder_stdout
and .._stderr in verifiable_consumer.py and verifiable_producer.py

**Deployment:**
There's currently no automatic way of deploying 3rd party kafkatest clients
on the VM instance so this needs to be done (at least partially) manually for
now.

One way to do this is logging in to a worker (`vagrant ssh worker1`), downloading
and building the kafkatest client under /vagrant (which maps to the kafka root
directory on the host and is shared with all VM instances).
Also make sure to install any system-level dependencies on each instance.

Then use /vagrant/..../yourkafkatestclient as your run-time path since it will
now be available on all instances.

The VerifiableClientApp automates the per-worker deployment with the optional
"deploy": "/vagrant/../deploy_script.sh" globals configuration property, this
script will be called on the VM just prior to executing the client.
"""

def create_verifiable_client_implementation(context, parent):
    """Factory for generating a verifiable client implementation class instance

    :param parent: parent class instance, either VerifiableConsumer or VerifiableProducer

    This will first check for a fully qualified client implementation class name
    in context.globals as "Verifiable<type>" where <type> is "Producer" or "Consumer",
    followed by "VerifiableClient" (which should implement both).
    The global object layout is: {"class": "<full class name>", "..anything..": ..}.

    If present, construct a new instance, else defaults to VerifiableClientJava
    """

    # Default class
    obj = {"class": "kafkatest.services.verifiable_client.VerifiableClientJava"}

    parent_name = parent.__class__.__name__.rsplit('.', 1)[-1]
    for k in [parent_name, "VerifiableClient"]:
        if k in context.globals:
            obj = context.globals[k]
            break

    if "class" not in obj:
        raise SyntaxError('%s (or VerifiableClient) expected object format: {"class": "full.class.path", ..}' % parent_name)

    clname = obj["class"]
    # Using the fully qualified classname, import the implementation class
    if clname.find('.') == -1:
        raise SyntaxError("%s (or VerifiableClient) must specify full class path (including module)" % parent_name)

    (module_name, clname) = clname.rsplit('.', 1)
    cluster_mod = importlib.import_module(module_name)
    impl_class = getattr(cluster_mod, clname)
    return impl_class(parent, obj)

class VerifiableClientMixin (object):
    """
    Verifiable client mixin class
    """
    @property
    def impl (self):
        """
        :return: Return (and create if necessary) the Verifiable client implementation object.
        """
        # Add _impl attribute to parent Verifiable(Consumer|Producer) object.
        if not hasattr(self, "_impl"):
            setattr(self, "_impl", create_verifiable_client_implementation(self.context, self))
            if hasattr(self.context, "logger") and self.context.logger is not None:
                self.context.logger.debug("Using client implementation %s for %s" % (self._impl.__class__.__name__, self.__class__.__name__))
        return self._impl

    def exec_cmd (self, node):
        """
        :return: command string to execute client.
        Environment variables will be prepended and command line arguments
        appended to this string later by start_cmd().

        This method should also take care of deploying the client on the instance, if necessary.
        """
        raise NotImplementedError()

    def pids (self, node):
        """ :return: list of pids for this client instance on node """
        raise NotImplementedError()

    def kill_signal (self, clean_shutdown=True):
        """ :return: the kill signal to terminate the application. """
        if not clean_shutdown:
            return signal.SIGKILL

        return self.conf.get("kill_signal", signal.SIGTERM)

class VerifiableClientJava (VerifiableClientMixin):
    """
    Verifiable Consumer and Producer using the official Java client.
    """
    def __init__(self, parent, conf=None):
        """
        :param parent: The parent instance, either VerifiableConsumer or VerifiableProducer
        :param conf: Optional conf object (the --globals VerifiableX object)
        """
        super(VerifiableClientJava, self).__init__()
        self.parent = parent
        self.java_class_name = parent.java_class_name()
        self.conf = conf

    def exec_cmd (self, node):
        """ :return: command to execute to start instance
        Translates Verifiable* to the corresponding Java client class name """
        cmd = ""
        if self.java_class_name == 'VerifiableProducer' and node.version <= LATEST_0_8_2:
            # 0.8.2.X releases do not have VerifiableProducer.java, so cheat and add
            # the tools jar from trunk to the classpath
            tools_jar = self.parent.path.jar(TOOLS_JAR_NAME, DEV_BRANCH)
            tools_dependant_libs_jar = self.parent.path.jar(TOOLS_DEPENDANT_TEST_LIBS_JAR_NAME, DEV_BRANCH)
            cmd += "for file in %s; do CLASSPATH=$CLASSPATH:$file; done; " % tools_jar
            cmd += "for file in %s; do CLASSPATH=$CLASSPATH:$file; done; " % tools_dependant_libs_jar
            cmd += "export CLASSPATH; "
        cmd += fix_opts_for_new_jvm(node)
        cmd += self.parent.path.script("kafka-run-class.sh", node) + " org.apache.kafka.tools." + self.java_class_name
        return cmd

    def pids (self, node):
        """ :return: pid(s) for this client intstance on node """
        try:
            cmd = "jps | grep -i " + self.java_class_name + " | awk '{print $1}'"
            pid_arr = [pid for pid in node.account.ssh_capture(cmd, allow_fail=True, callback=int)]
            return pid_arr
        except (RemoteCommandError, ValueError) as e:
            return []

class VerifiableClientDummy (VerifiableClientMixin):
    """
    Dummy class for testing the pluggable framework
    """
    def __init__(self, parent, conf=None):
        """
        :param parent: The parent instance, either VerifiableConsumer or VerifiableProducer
        :param conf: Optional conf object (the --globals VerifiableX object)
        """
        super(VerifiableClientDummy, self).__init__()
        self.parent = parent
        self.conf = conf

    def exec_cmd (self, node):
        """ :return: command to execute to start instance """
        return 'echo -e \'{"name": "shutdown_complete" }\n\' ; echo ARGS:'

    def pids (self, node):
        """ :return: pid(s) for this client intstance on node """
        return []

class VerifiableClientApp (VerifiableClientMixin):
    """
    VerifiableClient using --global settings for exec_cmd, pids and deploy.
    By using this a verifiable client application can be used through simple
    --globals configuration rather than implementing a Python class.
    """

    def __init__(self, parent, conf):
        """
        :param parent: The parent instance, either VerifiableConsumer or VerifiableProducer
        :param conf: Optional conf object (the --globals VerifiableX object)
        """
        super(VerifiableClientApp, self).__init__()
        self.parent = parent
        # "VerifiableConsumer" or "VerifiableProducer"
        self.name = self.parent.__class__.__name__
        self.conf = conf

        if "exec_cmd" not in self.conf:
            raise SyntaxError("%s requires \"exec_cmd\": .. to be set in --globals %s object" % \
                              (self.__class__.__name__, self.name))

    def exec_cmd (self, node):
        """ :return: command to execute to start instance """
        self.deploy(node)
        return self.conf["exec_cmd"]

    def pids (self, node):
        """ :return: pid(s) for this client intstance on node """

        cmd = self.conf.get("pids", "pgrep -f '" + self.conf["exec_cmd"] + "'")
        try:
            pid_arr = [pid for pid in node.account.ssh_capture(cmd, allow_fail=True, callback=int)]
            self.parent.context.logger.info("%s pids are: %s" % (str(node.account), pid_arr))
            return pid_arr
        except (subprocess.CalledProcessError, ValueError) as e:
            return []

    def deploy (self, node):
        """ Call deploy script specified by "deploy" --global key
            This optional script is run on the VM instance just prior to
            executing `exec_cmd` to deploy the kafkatest client.
            The script path must be as seen by the VM instance, e.g. /vagrant/.... """

        if "deploy" not in self.conf:
            return

        script_cmd = self.conf["deploy"]
        self.parent.context.logger.debug("Deploying %s: %s" % (self, script_cmd))
        r = node.account.ssh(script_cmd)


text:
package org.basex.query.func.validate;

import static org.basex.query.QueryError.*;

import java.io.*;
import java.lang.reflect.*;

import org.basex.io.*;
import org.basex.query.*;
import org.basex.query.value.*;
import org.basex.util.*;
import org.xml.sax.*;

/**
 * Validates a document against a RelaxNG document.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Christian Gruen
 */
public class ValidateRngInfo extends ValidateFn {
  @Override
  public Value value(final QueryContext qc) throws QueryException {
    return info(qc);
  }

  @Override
  public Value info(final QueryContext qc) throws QueryException {
    checkCreate(qc);
    return process(new Validation() {
      @Override
      void process(final ErrorHandler handler) throws IOException, SAXException, QueryException {
        final IO in = read(toNodeOrAtomItem(exprs[0], qc), qc, null);

        // schema specified as string
        IO schema = read(toNodeOrAtomItem(exprs[1], qc), qc, null);
        tmp = createTmp(schema);
        if(tmp != null) schema = tmp;

        final boolean compact = exprs.length > 2 && toBoolean(exprs[2], qc);

        try {
          final Class<?>
            pmb = Class.forName("com.thaiopensource.util.PropertyMapBuilder"),
            vd = Class.forName("com.thaiopensource.validate.ValidationDriver"),
            vp = Class.forName("com.thaiopensource.validate.ValidateProperty"),
            pi = Class.forName("com.thaiopensource.util.PropertyId"),
            pm = Class.forName("com.thaiopensource.util.PropertyMap"),
            sr = Class.forName("com.thaiopensource.validate.SchemaReader"),
            csr = Class.forName("com.thaiopensource.validate.rng.CompactSchemaReader");

          final Object ehInstance = vp.getField("ERROR_HANDLER").get(null);
          final Object pmbInstance = pmb.newInstance();
          pi.getMethod("put", pmb, Object.class).invoke(ehInstance, pmbInstance, handler);

          final Object srInstance = compact ? csr.getMethod("getInstance").invoke(null) : null;
          final Object pmInstance = pmb.getMethod("toPropertyMap").invoke(pmbInstance);
          final Object vdInstance = vd.getConstructor(pm, sr).newInstance(pmInstance, srInstance);

          final Method vdLs = vd.getMethod("loadSchema", InputSource.class);
          final Object loaded = vdLs.invoke(vdInstance, schema.inputSource());
          if(Boolean.TRUE.equals(loaded)) {
            final Method vdV = vd.getMethod("validate", InputSource.class);
            vdV.invoke(vdInstance, in.inputSource());
          }
        } catch(final ClassNotFoundException ex) {
          throw BXVA_RELAXNG_X.get(info);
        } catch(final Exception ex) {
          Throwable e = ex;
          while(e.getCause() != null) {
            Util.debug(e);
            e = e.getCause();
          }
          throw BXVA_FAIL_X.get(info, e);
        }
      }
    });
  }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser;

import android.content.pm.ActivityInfo;
import android.support.test.filters.MediumTest;
import android.view.Surface;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.chromium.content_public.browser.ScreenOrientationProvider;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.content_public.common.ScreenOrientationValues;
import org.chromium.content_shell_apk.ContentShellActivityTestRule;
import org.chromium.ui.display.DisplayAndroid;
import org.chromium.ui.display.DisplayAndroid.DisplayAndroidObserver;

import java.util.concurrent.Callable;

/**
 * Tests for ScreenOrientationListener and its implementations.
 *
 * rotation: Surface.ROTATION_*
 * orientation: ActivityInfo.SCREEN_ORIENTATION_*
 * orientation value: ScreenOrientationValues.*
 */
@RunWith(BaseJUnit4ClassRunner.class)
public class ScreenOrientationListenerTest {
    @Rule
    public ContentShellActivityTestRule mActivityTestRule = new ContentShellActivityTestRule();

    private static class OrientationChangeCallbackHelper
            extends CallbackHelper implements DisplayAndroidObserver {
        private int mLastOrientation;

        @Override
        public void onRotationChanged(int rotation) {
            mLastOrientation = rotation;
            notifyCalled();
        }

        @Override
        public void onDIPScaleChanged(float dipScale) {}

        public int getLastRotation() {
            return mLastOrientation;
        }
    }

    private OrientationChangeCallbackHelper mCallbackHelper;
    private DisplayAndroid mDisplayAndroid;
    private int mNaturalOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;

    @Before
    public void setUp() throws Exception {
        mActivityTestRule.launchContentShellWithUrl("about:blank");
        mCallbackHelper = new OrientationChangeCallbackHelper();
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            mDisplayAndroid =
                    mActivityTestRule.getWebContents().getTopLevelNativeWindow().getDisplay();
            mDisplayAndroid.addObserver(mCallbackHelper);
        });

        // Calculate device natural orientation, as mObserver.mOrientation
        // is difference between current and natural orientation in degrees.
        mNaturalOrientation = getNaturalOrientation(mDisplayAndroid);

        // Make sure we start all the tests with the same orientation.
        lockOrientationAndWait(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @After
    public void tearDown() {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            mDisplayAndroid.removeObserver(mCallbackHelper);
            mDisplayAndroid = null;
            mActivityTestRule.getActivity().setRequestedOrientation(
                    ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        });

        mCallbackHelper = null;
    }

    private static int getNaturalOrientation(DisplayAndroid display) {
        int rotation = display.getRotation();
        if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
            if (display.getDisplayHeight() >= display.getDisplayWidth()) {
                return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            }
            return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        } else {
            if (display.getDisplayHeight() < display.getDisplayWidth()) {
                return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            }
            return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        }
    }

    private int orientationToRotation(int orientation) {
        if (mNaturalOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            switch (orientation) {
                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
                    return Surface.ROTATION_0;
                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
                    return Surface.ROTATION_90;
                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
                    return Surface.ROTATION_180;
                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
                    return Surface.ROTATION_270;
                default:
                    Assert.fail("Should not be there!");
                    return Surface.ROTATION_0;
            }
        } else { // mNaturalOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            switch (orientation) {
                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
                    return Surface.ROTATION_270;
                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
                    return Surface.ROTATION_0;
                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
                    return Surface.ROTATION_90;
                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
                    return Surface.ROTATION_180;
                default:
                    Assert.fail("Should not be there!");
                    return Surface.ROTATION_0;
            }
        }
    }

    private int getCurrentRotation() {
        return TestThreadUtils.runOnUiThreadBlockingNoException(new Callable<Integer>() {
            @Override
            public Integer call() {
                return mDisplayAndroid.getRotation();
            }
        });
    }

    // Returns the rotation observed.
    private int lockOrientationAndWait(final int orientation) throws Exception {
        int expectedRotation = orientationToRotation(orientation);
        int currentRotation = getCurrentRotation();
        if (expectedRotation == currentRotation) return expectedRotation;

        int callCount = mCallbackHelper.getCallCount();
        TestThreadUtils.runOnUiThreadBlocking(
                () -> { mActivityTestRule.getActivity().setRequestedOrientation(orientation); });
        mCallbackHelper.waitForCallback(callCount);
        return mCallbackHelper.getLastRotation();
    }

    @Test
    @MediumTest
    @Feature({"ScreenOrientation"})
    @DisabledTest
    public void testOrientationChanges() throws Exception {
        int rotation = lockOrientationAndWait(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        Assert.assertEquals(
                orientationToRotation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE), rotation);

        rotation = lockOrientationAndWait(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Assert.assertEquals(
                orientationToRotation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT), rotation);

        rotation = lockOrientationAndWait(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
        Assert.assertEquals(
                orientationToRotation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE), rotation);

        // Note: REVERSE_PORTRAIT does not work when device orientation is locked by user (eg from
        // the notification shade). Bots on the commit queue are all locked, so don't bother testing
        // REVERSE_PORTRAIT.
    }

    private int orientationValueToRotation(int orientationValue) {
        if (mNaturalOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            switch (orientationValue) {
                case ScreenOrientationValues.PORTRAIT_PRIMARY:
                    return Surface.ROTATION_0;
                case ScreenOrientationValues.LANDSCAPE_PRIMARY:
                    return Surface.ROTATION_90;
                case ScreenOrientationValues.PORTRAIT:
                    return Surface.ROTATION_0;
                case ScreenOrientationValues.LANDSCAPE:
                    return Surface.ROTATION_90;
                case ScreenOrientationValues.LANDSCAPE_SECONDARY:
                    return Surface.ROTATION_270;
                case ScreenOrientationValues.PORTRAIT_SECONDARY:
                    return Surface.ROTATION_180;
                default:
                    Assert.fail("Can't requiest this orientation value " + orientationValue);
                    return 0;
            }
        } else { // mNaturalOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            switch (orientationValue) {
                case ScreenOrientationValues.PORTRAIT_PRIMARY:
                    return Surface.ROTATION_270;
                case ScreenOrientationValues.LANDSCAPE_PRIMARY:
                    return Surface.ROTATION_0;
                case ScreenOrientationValues.PORTRAIT:
                    return Surface.ROTATION_90;
                case ScreenOrientationValues.LANDSCAPE:
                    return Surface.ROTATION_0;
                case ScreenOrientationValues.LANDSCAPE_SECONDARY:
                    return Surface.ROTATION_180;
                case ScreenOrientationValues.PORTRAIT_SECONDARY:
                    return Surface.ROTATION_90;
                default:
                    Assert.fail("Can't requiest this orientation value " + orientationValue);
                    return 0;
            }
        }
    }

    // Returns the rotation observed.
    private int lockOrientationValueAndWait(final int orientationValue) throws Exception {
        int expectedRotation = orientationValueToRotation(orientationValue);
        int currentRotation = getCurrentRotation();
        if (expectedRotation == currentRotation) return expectedRotation;

        int callCount = mCallbackHelper.getCallCount();
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            ScreenOrientationProvider.getInstance().lockOrientation(
                    mActivityTestRule.getWebContents().getTopLevelNativeWindow(),
                    (byte) orientationValue);
        });
        mCallbackHelper.waitForCallback(callCount);
        return mCallbackHelper.getLastRotation();
    }

    @Test
    @MediumTest
    @Feature({"ScreenOrientation"})
    @DisabledTest(message = "crbug.com/807356")
    public void testBasicValues() throws Exception {
        int rotation = lockOrientationValueAndWait(ScreenOrientationValues.LANDSCAPE_PRIMARY);
        Assert.assertEquals(
                orientationValueToRotation(ScreenOrientationValues.LANDSCAPE_PRIMARY), rotation);

        rotation = lockOrientationValueAndWait(ScreenOrientationValues.PORTRAIT_PRIMARY);
        Assert.assertEquals(
                orientationValueToRotation(ScreenOrientationValues.PORTRAIT_PRIMARY), rotation);

        rotation = lockOrientationValueAndWait(ScreenOrientationValues.LANDSCAPE_SECONDARY);
        Assert.assertEquals(
                orientationValueToRotation(ScreenOrientationValues.LANDSCAPE_SECONDARY), rotation);

        // The note in testOrientationChanges about REVERSE_PORTRAIT applies to PORTRAIT_SECONDARY.
    }
}


text:
@interface TGCacheController ()
{
    TGProgressWindow *_progressWindow;
    TGVariantCollectionItem *_cacheItem;
}

@end

@implementation TGCacheController

- (NSArray *)keepMediaVariants
{
    NSArray *values = @[//@(1 * 60 * 60 * 24),
                        @(1 * 60 * 60 * 24 * 7),
                        @(1 * 60 * 60 * 24 * 7 * 4),
                        @(INT_MAX)];

    NSMutableArray *variants = [[NSMutableArray alloc] init];
    for (NSNumber *nValue in values)
    {
        NSString *title = @"";

        if ([nValue intValue] == INT_MAX)
            title = TGLocalized(@"MessageTimer.Forever");
        else
            title = [TGStringUtils stringForMessageTimerSeconds:[nValue intValue]];

        [variants addObject:@{@"title": title, @"value": nValue}];
    }

    return variants;
}

- (NSString *)keepMediaVariantTitleForSeconds:(int)seconds
{
    for (NSDictionary *record in [self keepMediaVariants])
    {
        if ([record[@"value"] intValue] == seconds)
            return record[@"title"];
    }

    return [[NSString alloc] initWithFormat:@"%d seconds", seconds];
}

- (instancetype)init
{
    self = [super init];
    if (self != nil)
    {
        self.title = TGLocalized(@"Cache.Title");

        int keepMediaSeconds = INT_MAX;
        NSNumber *nKeepMediaSeconds = [[NSUserDefaults standardUserDefaults] objectForKey:@"keepMediaSeconds"];
        if (nKeepMediaSeconds != nil)
            keepMediaSeconds = [nKeepMediaSeconds intValue];

        _cacheItem = [[TGVariantCollectionItem alloc] initWithTitle:TGLocalized(@"Cache.KeepMedia") action:@selector(keepMediaPressed)];
        _cacheItem.variant = [self keepMediaVariantTitleForSeconds:keepMediaSeconds];

        _cacheItem.deselectAutomatically = true;

        TGCommentCollectionItem *commentItem = [[TGCommentCollectionItem alloc] initWithFormattedText:TGLocalized(@"Cache.Help")];

        TGCollectionMenuSection *cacheSection = [[TGCollectionMenuSection alloc] initWithItems:@[
            _cacheItem,
            commentItem
        ]];

        UIEdgeInsets topSectionInsets = cacheSection.insets;
        topSectionInsets.top = 32.0f;
        cacheSection.insets = topSectionInsets;
        [self.menuSections addSection:cacheSection];
    }
    return self;
}

- (void)keepMediaPressed
{
    __weak TGCacheController *weakSelf = self;

    NSMutableArray *actions = [[NSMutableArray alloc] init];
    for (NSDictionary *record in [self keepMediaVariants])
    {
        [actions addObject:[[TGActionSheetAction alloc] initWithTitle:record[@"title"] action:[[NSString alloc] initWithFormat:@"%@", record[@"value"]]]];
    }
    [actions addObject:[[TGActionSheetAction alloc] initWithTitle:TGLocalized(@"Common.Cancel") action:@"cancel" type:TGActionSheetActionTypeCancel]];

    [[[TGActionSheet alloc] initWithTitle:nil actions:actions actionBlock:^(__unused id target, NSString *action)
    {
        __strong TGCacheController *strongSelf = weakSelf;
        if (strongSelf != nil)
        {
           if (![action isEqualToString:@"cancel"])
           {
               [strongSelf applyKeepMediaSeconds:[action intValue]];
           }
        }
    } target:self] showInView:self.view];
}

- (void)applyKeepMediaSeconds:(int)value
{
    [[NSUserDefaults standardUserDefaults] setObject:@(value) forKey:@"keepMediaSeconds"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [_cacheItem setVariant:[self keepMediaVariantTitleForSeconds:value]];

    [TGDatabaseInstance() processAndScheduleMediaCleanup];
}

- (void)clearCachePressed
{
    _progressWindow = [[TGProgressWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [_progressWindow show:true];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
    {
        [[TGRemoteImageView sharedCache] clearCache:TGCacheDisk];

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        [[NSFileManager defaultManager] removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:@"files"] error:nil];
        [[NSFileManager defaultManager] removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:@"audio"] error:nil];
        [[NSFileManager defaultManager] removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:@"video"] error:nil];

        TGDispatchOnMainThread(^
        {
            [_progressWindow dismissWithSuccess];
        });
    });
}

@end


text:
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="script-src 'self';">
<script src="../../../http/tests/inspector/inspector-test.js"></script>
<script src="../../../http/tests/inspector/debugger-test.js"></script>
<script src="resources/pause-on-blocked-by-csp.js"></script>
<script src="resources/pause-on-blocked-event-handler.js"></script>
</head>
<body>
<p>
Tests that pause on exception works for inline event handlers blocked by CSP.
</p>
<button id="test" onclick="alert('FAIL!');">Button</button>
</body>
</html>


text:
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.gmf.runtime.common.core.service.AbstractProvider;
import org.eclipse.gmf.runtime.common.core.service.IOperation;
import org.eclipse.gmf.runtime.common.ui.services.icon.GetIconOperation;
import org.eclipse.gmf.runtime.common.ui.services.icon.IIconProvider;
import org.eclipse.swt.graphics.Image;

/**
 * @generated
 */
public class EsbIconProvider extends AbstractProvider implements IIconProvider {

	/**
	 * @generated
	 */
	public Image getIcon(IAdaptable hint, int flags) {
		return EsbElementTypes.getImage(hint);
	}

	/**
	 * @generated
	 */
	public boolean provides(IOperation operation) {
		if (operation instanceof GetIconOperation) {
			return ((GetIconOperation) operation).execute(this) != null;
		}
		return false;
	}
}


text:
(function() {
  "use strict";

  var i18nModule = angular.module( "i18n", [] );

  /**
   * The i18nLocale directive can (and should) be used to tell the i18n service which locale to use.
   * You may just want to combine it with the ngApp directive in your DOM. For example:
   *
   * <html ng-app="yourApp" i18n-locale="de">
   *
   * The "de" part should in practice be filled by the result of the i18n.getLocale() call in your express app.
   */
  i18nModule.directive( "i18nLocale", [ "i18n", "$rootScope", function( i18n, $rootScope ) {
    return {
      restrict : "A",
      link     : function postLink( scope, element, attributes ) {
        // Observe the value provided to us and re-initialize if it changes.
        attributes.$observe( "i18nLocale", function( value ) {
          i18n.init( value );
        } );
        // Also check if a "i18nLocale" model in the scope changes its value to indicate a desired locale change.
        $rootScope.$watch( "i18nLocale", function localeChanged( newLocale, oldLocale ) {
          if( !newLocale || newLocale == oldLocale ) return;
          i18n.init( newLocale );
        } );
      }
    };
  } ] );

  /**
   * The main i18n service which handles retrieval of the translation map sends single translation terms to the backend.
   */
  i18nModule.factory( "i18n", function( $rootScope, $http, $q ) {
    var i18nService = function() {

      // We use this deferred to keep track of if the last locale loading request has completed.
      this._localeLoadedDeferred = $q.defer();
      // If a lot of locale loading is requested, we collect all the promises on this stack so we can later resolve them.
      this._deferredStack = [];

      // A handy boolean that indicates if the currently requested locale was loaded.
      this.loaded = false;

      // Initialize the service with a given locale.
      this.init = function( locale ) {
        if( locale != this.userLanguage ) {
          if( this._localeLoadedDeferred ) {
            this._deferredStack.push( this._localeLoadedDeferred );
          }
          this._localeLoadedDeferred = $q.defer();
          this.loaded = false;
          this.userLanguage = locale;

          var service = this;

          $http( { method : "get", url : "/i18n/" + locale, cache : true } ).success( function( translations ) {
            $rootScope.i18n = translations;
            service.loaded = true;
            service._localeLoadedDeferred.resolve( $rootScope.i18n );

            while( service._deferredStack.length ) {
              service._deferredStack.pop().resolve( $rootScope.i18n );
            }
          } );
        }

        return this._localeLoadedDeferred.promise;
      };

      /**
       * Syntactic sugar. Returns a promise to return the i18n service, once the translation map is loaded.
       * @returns {defer.promise|*|promise}
       */
      this.i18n = function() {
        var serviceDeferred = $q.defer();

        var service = this;
        this.ensureLocaleIsLoaded().then( function() {
          serviceDeferred.resolve( service );
        } );

        return serviceDeferred.promise;
      };

      /**
       * Returns a promise to return the translation map, once it is loaded.
       * @returns {defer.promise|*|promise}
       */
      this.ensureLocaleIsLoaded = function() {
        return this._localeLoadedDeferred.promise;
      };

      /**
       * Translate a given term, using the currently loaded translation map.
       * @param {String} name The string to translate.
       * @returns {String} The translated string or the input, if no translation was available.
       */
      this.__ = function( name ) {
        if( !$rootScope.i18n ) {
          return name;
        }

        var translation = $rootScope.i18n[ name ];
        if( !translation ) {
          translation = name;

          // Temporarily store the original string in the translation table
          // to avoid future lookups causing additional GET requests to the backend.
          $rootScope.i18n[ name ] = translation;

          // Invoke the translation endpoint on the backend to cause the term to be added
          // to the translation table on the backend.
          // Additionally, store the returned, translated term in the translation table.
          // The term is very unlikely to be actually translated now, as it was most
          // likely previously unknown in the users locale, but, hey.
          $http.get( "/i18n/" + this.userLanguage + "/" + encodeURIComponent( name ) ).success( function( translated ) {
            $rootScope.i18n[ name ] = translated;
          } );
        }

        // If an implementation of vsprintf is loaded and we have additional parameters,
        // try to perform the substitution and return the result.
        if( arguments.length > 1 && typeof( vsprintf ) == "function" ) {
          translation = vsprintf( translation, Array.prototype.slice.call( arguments, 1 ) );
        }

        return translation;
      };

      /**
       * Translate a given term and pick the singular or plural version depending on the given count.
       * @param {Number} count The number of items, depending on which the correct translation term will be chosen.
       * @param {String} singular The term that should be used if the count equals 1.
       * @param {String} plural The term that should be used if the count doesn't equal 1.
       * @returns {String} The translated phrase depending on the count.
       */
      this.__n = function( count, singular, plural ) {
        if( !$rootScope.i18n ) {
          return singular;
        }

        var translation = $rootScope.i18n[ singular ];
        if( !translation ) {
          translation = {one : singular, other : plural};

          // Temporarily store the original string in the translation table
          // to avoid future lookups causing additional GET requests to the backend.
          $rootScope.i18n[ singular ] = translation;

          // Invoke the translation endpoint on the backend to cause the term to be added
          // to the translation table on the backend.
          // Additionally, store the returned, translated term in the translation table.
          // The term is very unlikely to be actually translated now, as it was most
          // likely previously unknown in the users locale, but, hey.
          $http.get( "/i18n/" + this.userLanguage + "/" + encodeURIComponent( singular ) + "?plural=" + encodeURIComponent( plural ) + "&count=" + encodeURIComponent( count ) ).success( function( translated ) {
            $rootScope.i18n[ singular ] = translated;
          } );
        }

        translation = (count == 1) ? translation.one : translation.other;

        // If an implementation of vsprintf is loaded, try to perform the substitution and return the result.
        if( typeof( vsprintf ) == "function" ) {
          translation = vsprintf( translation, [count] );
        }

        return translation;
      };
    };

    return new i18nService();
  } );

  /**
   * i18n filter to be used conveniently in templates.
   * When looking to translate just a single phrase, pass the phrase into the filter like so:
   *
   *   {{"My phrase"|i18n}}
   *
   * When you need pluralization support, pass the count into the filter, and provide the two terms as additional arguments:
   *
   *   {{2|i18n:"singular":"plural"}}
   *   {{4|i18n:"%s item":"%s items"}}
   */
  i18nModule.filter( "i18n", [
    "i18n", function( i18n ) {
      /**
       * Check if the given input is a number.
       * @see http://stackoverflow.com/a/1830844/259953
       * @param n The input to check.
       * @returns {boolean} true if the input is a number; false otherwise.
       */
      function isNumber( n ) {
        return !isNaN( parseFloat( n ) ) && isFinite( n );
      }

      return function( input ) {
        // If the input is a number, assume pluralization is requested.
        if( isNumber( input ) ) {
          return i18n.__n.apply( i18n, arguments );
        }
        return i18n.__.apply( i18n, arguments );
      };
    }
  ] );
}());


text:
#ifndef MBED_FATFILEHANDLE_H
#define MBED_FATFILEHANDLE_H

#include "FileHandle.h"
#include "PlatformMutex.h"

using namespace mbed;

class FATFileHandle : public FileHandle {
public:

    FATFileHandle(FIL fh, PlatformMutex * mutex);
    virtual int close();
    virtual ssize_t write(const void* buffer, size_t length);
    virtual ssize_t read(void* buffer, size_t length);
    virtual int isatty();
    virtual off_t lseek(off_t position, int whence);
    virtual int fsync();
    virtual off_t flen();

protected:

    virtual void lock();
    virtual void unlock();

    FIL _fh;
    PlatformMutex * _mutex;

};

#endif


text:
//-----------------------------------------------------------------------
// <copyright file="UpdateRequest.cs" company="Marimer LLC">
//     Copyright (c) Marimer LLC. All rights reserved.
//     Website: https://cslanet.com
// </copyright>
// <summary>Request message for updating</summary>
//-----------------------------------------------------------------------

using System;

namespace Csla.Server.Hosts.DataPortalChannel
{
  /// <summary>
  /// Request message for updating
  /// a business object.
  /// </summary>
  [Serializable]
  public class UpdateRequest : ReadOnlyBase<UpdateRequest>
  {
    /// <summary>
    /// Serialized object data.
    /// </summary>
    public static readonly PropertyInfo<byte[]> ObjectDataProperty = RegisterProperty<byte[]>(c => c.ObjectData);

    /// <summary>
    /// Serialized object data.
    /// </summary>
    public byte[] ObjectData
    {
      get { return GetProperty(ObjectDataProperty); }
      set { LoadProperty(ObjectDataProperty, value); }
    }

    /// <summary>
    /// Serialized data for the principal object.
    /// </summary>
    public static readonly PropertyInfo<byte[]> PrincipalProperty = RegisterProperty<byte[]>(c => c.Principal);

    /// <summary>
    /// Serialized data for the principal object.
    /// </summary>
    public byte[] Principal
    {
      get { return GetProperty(PrincipalProperty); }
      set { LoadProperty(PrincipalProperty, value); }
    }

    /// <summary>
    /// Serialized data for the client context object.
    /// </summary>
    public static readonly PropertyInfo<byte[]> ClientContextProperty = RegisterProperty<byte[]>(c => c.ClientContext);

    /// <summary>
    /// Serialized data for the client context object.
    /// </summary>
    public byte[] ClientContext
    {
      get { return GetProperty(ClientContextProperty); }
      set { LoadProperty(ClientContextProperty, value); }
    }

    /// <summary>
    /// Serialized client culture.
    /// </summary>
    /// <value>The client culture.</value>
    public static readonly PropertyInfo<string> ClientCultureProperty = RegisterProperty<string>(c => c.ClientCulture);

    /// <summary>
    /// Serialized client culture.
    /// </summary>
    /// <value>The client culture.</value>
    public string ClientCulture
    {
      get { return GetProperty(ClientCultureProperty); }
      set { LoadProperty(ClientCultureProperty, value); }
    }

    /// <summary>
    /// Serialized client UI culture.
    /// </summary>
    /// <value>The client UI culture.</value>
    public static readonly PropertyInfo<string> ClientUICultureProperty = RegisterProperty<string>(c => c.ClientUICulture);

    /// <summary>
    /// Serialized client UI culture.
    /// </summary>
    /// <value>The client UI culture.</value>
    public string ClientUICulture
    {
      get { return GetProperty(ClientUICultureProperty); }
      set { LoadProperty(ClientUICultureProperty, value); }
    }
  }
}


text:
```
node index.js
```
or use
```
npm start
```

## Description
Core application that powers shazamjs applications. Edit the admin password in /lib/env.js to change password from blank. Please note anyone can connect to this socket.io server an d the information is transmitted in plain http fashion. This application is not ment to demonstrate security, but show the applications of node on a variety of platforms.

## Client Implementation
### Clients need to handle the following events emitted by the server:
```
socket.on("Refresh!", (currentAppState) => {//Handle the current appState});
```

On "Refresh!" the app state is transmitted to the client to update itself.

```
socket.on("Transform!", (currentAppState) => {//Handle the current appState});
```
On "Transform!" the app state is transmitted to the client to update itself, but it is expected the client does something special to signify the app state is changing state between Billy and Shazam.

### Clients should emit the follow information to the server:

```
socket.emit("Shazam!", {location: "A location string"})
```
Client tells server someone has clicked Shazam a long with the current location of where the event occured.

```
socket.emit("Who am I?")
```
Client requests the server send the current state. The server only broadcasts the state via the Refresh event. The server only broadcasts the Refresh event to the current socket, not globally.

## Server Implementation
The server handles the following events:

```
socket.on("Who am I?", () => { //emit "Refresh Event!"});
```
Emit a Refresh event only to the current socket that emitted the "Who Am I?" event.

```
socket.on("Shazam!", () => { //update the app state then emit "Transform!"});
```

The server increments the proper app state based upon the location string sent.

### Possible Location Strings
"coreApp", "websiteApp", "desktopApp", "hardwareApp", "consoleApp", "mobileApp"


text:
.. include:: ../../Includes.txt

========================================
Feature: #67880 - Added count to listNum
========================================

See :issue:`67880`

Description
===========

A new property `returnCount` is added to the stdWrap property `split`.

When dealing with comma separated values like the content of field:records or similar,
in some cases we need to know, how many items are present inside the csv.

Example:

.. code-block:: typoscript

	# should return 9
	1 = TEXT
	1 {
		value = x,y,z,1,2,3,a,b,c
		split.token = ,
		split.returnCount = 1
	}


text:
"""Tests for the :class:`jicbioimage.core.image.ImageCollection` class."""

import unittest

try:
    from mock import MagicMock, patch
except ImportError:
    from unittest.mock import MagicMock, patch

class ImageCollectionTests(unittest.TestCase):

    def test_len(self):
        from jicbioimage.core.image import ImageCollection
        image_collection = ImageCollection()
        self.assertEqual(len(image_collection), 0)

    def test_has_proxy_image(self):
        from jicbioimage.core.image import ImageCollection
        image_collection = ImageCollection()
        self.assertTrue(callable(image_collection.proxy_image))

    def test_proxy_image(self):
        from jicbioimage.core.image import ImageCollection, ProxyImage
        image_collection = ImageCollection()
        image_collection.append(ProxyImage('test0.tif'))
        image_collection.append(ProxyImage('test1.tif'))

        proxy_image = image_collection.proxy_image()
        self.assertEqual(proxy_image.fpath, 'test0.tif')

        proxy_image = image_collection.proxy_image(index=1)
        self.assertEqual(proxy_image.fpath, 'test1.tif')

    def test_repr_html(self):
        from jicbioimage.core.image import ImageCollection, ProxyImage, Image
        image_collection = ImageCollection()
        image = Image((50,50))
        image.png = MagicMock(return_value=bytearray('image', encoding='utf-8'))
        with patch('jicbioimage.core.image.Image.from_file', return_value=image) as patched_image:
            image_collection.append(ProxyImage('test0.tif'))
            html = image_collection._repr_html_()
            self.assertEqual(html.strip().replace(' ', '').replace('\n', ''),
'''

Index	0

'''.strip().replace(' ', '').replace('\n', ''))

        image.png.assert_called_once_with(width=300)

if __name__ == '__main__':
    unittest.main()


text:
package test.performance;

import main.Hierarchy;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import test.helpers.BasePerformanceTest;
import test.types.PerformanceTests;

public class ContainsPerformance extends BasePerformanceTest {

    @Category(PerformanceTests.class)
    @Test
    public void PerformanceContains_With50000LookUpsInReversedOrderWith50000ElementsWith1Parent()
    {
        Hierarchy<Integer> hierarchy = new Hierarchy<>(-3);

        for (int i = 1; i < 50001; i++)
        {
            hierarchy.add(-3, i);
        }

        long start = System.currentTimeMillis();
        for (int i = 50000; i > 0; i--)
        {
            Assert.assertTrue("Contains method returned wrong value!", hierarchy.contains(i));
        }

        long end = System.currentTimeMillis();
        Assert.assertTrue(end - start < 50);
    }

    @Category(PerformanceTests.class)
    @Test
    public void PerformanceContains_With25000ExistingAnd25000NonexistantElements()
    {
        Hierarchy<Integer> hierarchy = new Hierarchy<>(-1);

        for (int i = 1; i < 50001; i = i + 2)
        {
            hierarchy.add(i - 2, i);
        }

        long start = System.currentTimeMillis();

        for (int i = 1; i < 50001; i = i + 2)
        {
            Assert.assertTrue("Contains method returned wrong value!", hierarchy.contains(i));
            Assert.assertFalse("Contains method returned wrong value!", hierarchy.contains(i + 1));
        }

        long end = System.currentTimeMillis();
        Assert.assertTrue(end - start < 50);
    }
}


text:
<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use common\models\Profiles;
use common\models\RegForm;
use common\models\SignupForm;
use common\models\PasswordResetRequestForm;
use common\models\ResetPasswordForm;
use common\models\SendEmailForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->redirect('@web/tender/index');
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionReg()
    {
        $model = new RegForm();

        if ($model->load(Yii::$app->request->post()) && $model->validate()):

            if ($user = $model->reg()):
                if ($user->status === User::STATUS_ACTIVE):
                    if (Yii::$app->getUser()->login($user)):

                        return $this->redirect('category');
                    endif;
                endif;
            else:
                Yii::$app->session->setFlash('error', 'Возникла ошибка при регистрации.');
                Yii::error('Ошибка при регистрации');
                return $this->refresh();
            endif;
        endif;

        return $this->render(
            'reg',
            [
                'model' => $model,
            ]
        );
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Проверьте почту.');
                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Извините, нельзя сбросить пароль на эту почту.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'Новый пароль сохранен.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }

    public function actionProfiles()
    {
        $model = ($model = Profiles::findOne(Yii::$app->user->id)) ? $model : new Profiles();

        if ($model->load(Yii::$app->request->post()) && $model->validate()):
            if ($model->updateProfiles()):
                Yii::$app->session->setFlash('success', 'Профиль изменен');
            else:
                Yii::$app->session->setFlash('error', 'Профиль не изменен');
                Yii::error('Ошибка записи. Профиль не изменен');
                return $this->refresh();
            endif;
        endif;

        return $this->render(
            'profiles',
            [
                'model' => $model,
            ]
        );
    }

    public function actionSendEmail()
    {
        $model = new SendEmailForm();

        if ($model->load(Yii::$app->request->post())) {
            if ($model->validate()) {

                if ($model->sendEmail()):
                    Yii::$app->getSession()->setFlash('warning', 'Проверьте email.');
                    return $this->goHome();
                else:
                    Yii::$app->getSession()->setFlash('error', 'Нельзя сбросить пароль.');
                endif;

            }
        }

        return $this->render('sendEmail', [
            'model' => $model,
        ]);
    }
}


text:
package commands

import (
	"github.com/jfrog/jfrog-cli-core/v2/utils/coreutils"
	"github.com/jfrog/jfrog-cli-core/v2/utils/plugins"
	"github.com/jfrog/jfrog-cli/utils/cliutils"
	clientutils "github.com/jfrog/jfrog-client-go/utils"
	"github.com/jfrog/jfrog-client-go/utils/errorutils"
	"github.com/jfrog/jfrog-client-go/utils/io/fileutils"
	"github.com/urfave/cli"
	"os"
	"path/filepath"
)

func UninstallCmd(c *cli.Context) error {
	if c.NArg() != 1 {
		return cliutils.WrongNumberOfArgumentsHandler(c)
	}
	err := plugins.CheckPluginsVersionAndConvertIfNeeded()
	if err != nil {
		return err
	}
	return runUninstallCmd(c.Args().Get(0))
}

func runUninstallCmd(requestedPlugin string) error {
	pluginsDir, err := coreutils.GetJfrogPluginsDir()
	if err != nil {
		return err
	}
	requestedPluginDirPath := filepath.Join(pluginsDir, requestedPlugin)
	exists, err := fileutils.IsDirExists(requestedPluginDirPath, false)
	if err != nil {
		return err
	}
	if !exists {
		return generateNoPluginFoundError(requestedPlugin)
	}

	ci, err := clientutils.GetBoolEnvValue(coreutils.CI, false)
	if err != nil {
		return err
	}
	if !ci {
		if !coreutils.AskYesNo("Are you sure you want to uninstall plugin: \""+requestedPlugin+"\"?", false) {
			return nil
		}
	}
	return errorutils.CheckError(os.RemoveAll(requestedPluginDirPath))
}

func generateNoPluginFoundError(pluginName string) error {
	return errorutils.CheckErrorf("plugin '" + pluginName + "' could not be found")
}


text:
class FinalRoom : public Room
{
public:
	FinalRoom(const char* name, const char* description, const char* ready_description, vector<bool>* goals);

	~FinalRoom();

	void Tick();
	void Look() const;

private:
	vector<bool>* goals;
	const char* ready_description;
};