text:
using FluentAssertions;
using Moq;
using Newtonsoft.Json.Linq;
using Ploeh.AutoFixture.Xunit2;
using Xunit;
using ZAProxy.Components;
using ZAProxy.Infrastructure;
using ZAProxy.Tests.TestUtils;

namespace ZAProxy.Tests.Components
{
    [Trait("Component", "ForcedUser")]
    public class ForcedUserComponentTests
    {
        [Theory, AutoTestData]
        public void ComponentName(
            [Greedy]ForcedUserComponent sut)
        {
            // ACT
            var result = sut.ComponentName;

            // ASSERT
            result.Should().Be("forcedUser");
        }

        #region Views

        [Theory, AutoTestData]
        public void GetForcedUser(
            [Frozen]Mock<IHttpClient> httpClientMock,
            [Greedy]ForcedUserComponent sut,
            int contextId,
            int userId)
        {
            // ARRANGE
            var json = new JObject(
                new JProperty("forcedUserId", userId));
            httpClientMock.SetupApiCall(sut, CallType.View, "getForcedUser",
                new Parameters
                {
                    { "contextId", contextId }
                })
                .Returns(json.ToString())
                .Verifiable();

            // ACT
            var result = sut.GetForcedUser(contextId);

            // ASSERT
            result.Should().Be(userId);
            httpClientMock.Verify();
        }

        [Theory, AutoTestData]
        public void IsForcedUserModeEnabled(
            [Frozen]Mock<IHttpClient> httpClientMock,
            [Greedy]ForcedUserComponent sut,
            bool enabled)
        {
            // ARRANGE
            var json = new JObject(
                new JProperty("forcedModeEnabled", enabled));
            httpClientMock.SetupApiCall(sut, CallType.View, "isForcedUserModeEnabled")
                .Returns(json.ToString())
                .Verifiable();

            // ACT
            var result = sut.IsForcedUserModeEnabled();

            // ASSERT
            result.Should().Be(enabled);
            httpClientMock.Verify();
        }

        #endregion

        #region Actions

        [Theory, AutoTestData]
        public void SetForcedUser(
            [Frozen]Mock<IHttpClient> httpClientMock,
            [Greedy]ForcedUserComponent sut,
            int contextId,
            int userId)
        {
            // ARRANGE
            httpClientMock.SetupApiCall(sut, CallType.Action, "setForcedUser",
                new Parameters
                {
                    { "contextId", contextId },
                    { "userId", userId }
                })
                .ReturnsOkResult()
                .Verifiable();

            // ACT
            sut.SetForcedUser(contextId, userId);

            // ASSERT
            httpClientMock.Verify();
        }

        [Theory, AutoTestData]
        public void SetForcedUserModeEnabled(
            [Frozen]Mock<IHttpClient> httpClientMock,
            [Greedy]ForcedUserComponent sut,
            bool enabled)
        {
            // ARRANGE
            httpClientMock.SetupApiCall(sut, CallType.Action, "setForcedUserModeEnabled",
                new Parameters
                {
                    { "boolean", enabled }
                })
                .ReturnsOkResult()
                .Verifiable();

            // ACT
            sut.SetForcedUserModeEnabled(enabled);

            // ASSERT
            httpClientMock.Verify();
        }

        #endregion
    }
}


text:
package JFlex;

/**
 * This Exception is used in the macro expander to report cycles or
 * undefined macro usages.
 *
 * @author Gerwin Klein
 * @version JFlex 1.3.5, $Revision: 1.12 $, $Date: 2001/10/08 10:08:02 $
 */
public class MacroException extends RuntimeException {

  /**
   * Creates a new MacroException without message
   */
  public MacroException() {
  }

  /**
   * Creates a new MacroException with the specified message
   *
   * @param message   the error description presented to the user.
   */
  public MacroException(String message) {
    super(message);
  }

}

redpajama_set_name: RedPajamaGithub


text:
package no.haagensoftware.netty.webserver.plugin;

import static org.jboss.netty.handler.codec.http.HttpHeaders.isKeepAlive;
import static org.jboss.netty.handler.codec.http.HttpHeaders.setContentLength;
import static org.jboss.netty.handler.codec.http.HttpMethod.GET;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import org.apache.log4j.Logger;
import no.haagensoftware.netty.webserver.scriptCache.ScriptCache;
import no.haagensoftware.netty.webserver.scriptCache.ScriptHash;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequest;

import no.haagensoftware.netty.webserver.handler.FileServerHandler;

/**
 * This class is responsible for serving cached content. The contents is cached by the
 * CachedIndexHandler class.
 * @author joahaa
 *
 */
public class CachedScriptHandler extends FileServerHandler {
	private static Logger logger = Logger.getLogger(CachedScriptHandler.class.getName());

	public CachedScriptHandler(String path) {
		super(path);
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		HttpRequest request = (HttpRequest) e.getMessage();
        if (request.getMethod() != GET) {
            sendError(ctx, METHOD_NOT_ALLOWED);
            return;
        }

        String uri = request.getUri();
        if (uri.startsWith("/cachedScript")) {
            uri = uri.substring(13);
        }
        logger.info("CachedScriptHandler uri: " + uri);

        String path = sanitizeUri(uri);
        if (path == null) {
            sendError(ctx, FORBIDDEN);
            return;
        }

        //Substring out the root path
        if (path.startsWith(getRootPath())) {
        	path = path.substring(getRootPath().length());
        }

        //Substring ut the .js ending
        if (path.endsWith(".js")) {
        	path = path.substring(0, path.length() - 3);
        }

        logger.info("CachedScriptHandler path: " + path);

        ScriptCache scriptCache = ScriptHash.getScriptCache(path);
        //if there is no cache at the path, return a 404.
        if (scriptCache == null) {
        	sendError(ctx, NOT_FOUND);
        	return;
        }

        //Set up and send the response.
		DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);;
        response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/javascript");
        setContentLength(response, scriptCache.getMinifiedScriptContent().length());

        response.setContent(ChannelBuffers.copiedBuffer(scriptCache.getMinifiedScriptContent(), "utf-8"));
        ChannelFuture writeFuture = e.getChannel().write(response);

        // Decide whether to close the connection or not.
        if (!isKeepAlive(request)) {
            // Close the connection when the whole content is written out.
            writeFuture.addListener(ChannelFutureListener.CLOSE);
        }
	}
}


text:
  Saint-Martin-du-Mont est
      une commune localisée dans le département de l'Ain en Rhône-Alpes. Elle comptait 1 505 habitants en 2008.

Le parc d'habitations, à Saint-Martin-du-Mont, était réparti en 2011 en 43 appartements et 798 maisons soit
 un marché plutôt équilibré.

La commune compte quelques  équipements sportifs, elle dispose, entre autres, de un terrain de tennis, un terrain de sport et une boucle de randonnée.

À Saint-Martin-du-Mont, la valorisation moyenne à la vente d'un appartement s'évalue à 1 347 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 640 € du m². À la location la valeur moyenne se situe à 8,85 € du m² mensuel.

À coté de Saint-Martin-du-Mont sont positionnées géographiquement les communes de
Revonnas à 6 km, 630 habitants,
Varambon située à 6 km, 544 habitants,
Tossiat localisée à 4 km, 1 327 habitants,
Druillat localisée à 4 km, 1 092 habitants,
Certines à 5 km, 1 414 habitants,
Neuville-sur-Ain à 4 km, 1 449 habitants,
 entre autres. De plus, Saint-Martin-du-Mont est située à seulement quatorze km de Bourg-en-Bresse.


text:
package org.keycloak.testsuite.util;

import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
import org.junit.rules.ExternalResource;
import org.keycloak.models.RealmModel;

import javax.mail.internet.MimeMessage;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Stian Thorgersen
 */
public class GreenMailRule extends ExternalResource {

    private GreenMail greenMail;

    @Override
    protected void before() throws Throwable {
        ServerSetup setup = new ServerSetup(3025, "localhost", "smtp");

        greenMail = new GreenMail(setup);
        greenMail.start();
    }

    public void credentials(String username, String password) {
        greenMail.setUser(username, password);
    }

    @Override
    protected void after() {
        if (greenMail != null) {
            // Suppress error from GreenMail on shutdown
            Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    if (!(e.getCause() instanceof SocketException && t.getClass().getName()
                            .equals("com.icegreen.greenmail.smtp.SmtpHandler"))) {
                        System.err.print("Exception in thread \"" + t.getName() + "\" ");
                        e.printStackTrace(System.err);
                    }
                }
            });

            greenMail.stop();
        }
    }

    public void configureRealm(RealmModel realm) {
        Map<String, String> config = new HashMap<>();
        config.put("from", "auto@keycloak.org");
        config.put("host", "localhost");
        config.put("port", "3025");
        realm.setSmtpConfig(config);
    }

    public MimeMessage[] getReceivedMessages() {
        return greenMail.getReceivedMessages();
    }

    /**
     * Returns the very last received message. When no message is available, returns {@code null}.
     * @return see description
     */
    public MimeMessage getLastReceivedMessage() {
        MimeMessage[] receivedMessages = greenMail.getReceivedMessages();
        return (receivedMessages == null || receivedMessages.length == 0)
          ? null
          : receivedMessages[receivedMessages.length - 1];
    }

    /**
     * Use this method if you are sending email in a different thread from the one you're testing from.
     * Block waits for an email to arrive in any mailbox for any user.
     * Implementation Detail: No polling wait implementation
     *
     * @param timeout maximum time in ms to wait for emailCount of messages to arrive before giving up and returning false
     * @param emailCount waits for these many emails to arrive before returning
     * @return
     * @throws InterruptedException
     */
    public boolean waitForIncomingEmail(long timeout, int emailCount) throws InterruptedException {
        return greenMail.waitForIncomingEmail(timeout, emailCount);
    }

    /**
     * Does the same thing as Object.wait(long, int) but with a timeout of 5000ms.
     * @param emailCount waits for these many emails to arrive before returning
     * @return
     * @throws InterruptedException
     */
    public boolean waitForIncomingEmail(int emailCount) throws InterruptedException {
        return greenMail.waitForIncomingEmail(emailCount);
    }
}


text:
global.__jymfony = global.__jymfony || {};

/**
 * @memberOf __jymfony
 */
class Async {
    /**
     * Run an async generator.
     * Using this function you can use a generator to wait a promise
     * to be completed simply yield-ing it.
     * This function always returns a Promise object.
     *
     * @param {Generator|GeneratorFunction|AsyncFunction|Function} generator
     * @param {...*} args
     *
     * @returns {Promise}
     */
    static run(generator, ...args) {
        if (isAsyncFunction(generator)) {
            return generator(...args);
        }

        if (isGeneratorFunction(generator)) {
            return Async.run(generator(...args));
        }

        return new Promise((resolve, reject) => {
            if (isFunction(generator)) {
                generator = generator(...args);
            }

            if (! generator || isScalar(generator) || ! isFunction(generator.next)) {
                return resolve(generator);
            }

            /* eslint indent: "off" */
            const next = ret => {
                if (ret.done) {
                    return resolve(ret.value);
                }

                const val = Async.toPromise(ret.value);
                if (val && isPromise(val)) {
                    return val.then(onFulfilled, onRejected);
                } else if (isScalar(val)) {
                    return resolve(val);
                }

                return onRejected(new TypeError(
                    __jymfony.sprintf('Expected a function, a generator, a promise, an array or an object. "%s" yielded',
                        undefined === ret.value ? 'undefined' : ret.value.toString())
                ));
            },

            onFulfilled = res => {
                let retVal;

                try {
                    retVal = generator.next(res);
                } catch (e) {
                    return reject(e);
                }

                next(retVal);
                return null;
            },

            onRejected = err => {
                let retVal;

                try {
                    retVal = generator.throw(err);
                } catch (e) {
                    return reject(e);
                }

                next(retVal);
            };

            onFulfilled();
        });
    }

    /**
     * @param {Object} obj
     *
     * @returns {Promise}
     */
    static toPromise(obj) {
        if (! obj || isPromise(obj)) {
            return obj;
        }

        if (isGenerator(obj) || isGeneratorFunction(obj)) {
            return Async.run(obj);
        }

        if (isAsyncFunction(obj)) {
            return obj();
        }

        if (isFunction(obj)) {
            return Async.functionToPromise(obj);
        }

        if (isArray(obj)) {
            return Promise.all(obj.map(Async.toPromise));
        }

        if (isObjectLiteral(obj)) {
            return Async.objectToPromise(obj);
        }

        return obj;
    }

    /**
     * @param {Function} fn
     * @returns {Promise}
     */
    static functionToPromise(fn) {
        return new Promise((resolve, reject) => {
            const retVal = fn(function (err, res) {
                if (err) {
                    return reject(err);
                }

                if (2 < arguments.length) {
                    /* eslint prefer-rest-params: "off" */
                    res = [].slice.call(arguments, 1);
                }

                resolve(res);
            });

            if (undefined !== retVal) {
                resolve(retVal);
            }
        });
    }

    /**
     * @param {Object} obj
     *
     * @returns {Promise}
     */
    static objectToPromise(obj) {
        const results = {};
        const promises = [];

        for (const k of Object.keys(obj)) {
            const promise = Async.toPromise(obj[k]);

            results[k] = undefined;
            promises.push(promise.then(res => (results[k] = res)));
        }

        return Promise.all(promises).then(() => results);
    }
}

__jymfony.Async = Async;


text:
#include <pebble.h>

Window* my_window = NULL;

//Time Display
char time_string[] = "00:00";  // Make this longer to show AM/PM
TextLayer* time_outline_layer = NULL;
TextLayer* time_text_layer = NULL;

//Date Display
char date_string[16];
TextLayer* date_outline_layer = NULL;
TextLayer* date_text_layer = NULL;

//Image Display
BitmapLayer* bitmap_layer = NULL;
GBitmap* gbitmap_ptr = NULL;

//Transition animations
Layer* animation_layer = NULL;
PropertyAnimation* prop_animation_slide_left = NULL;
PropertyAnimation* prop_animation_slide_up = NULL;

static const char *const dname[7] =
{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

//Image indexes and count
int max_images = 0; //automatically detected
int image_index = RESOURCE_ID_IMAGE_OFFSET + 1; //Images start after IMAGE_OFFSET

static void do_animation(void){
  static bool animation_selection = false;

  animation_selection = !animation_selection;

  if (animation_selection) {
    animation_schedule((Animation*)prop_animation_slide_up);
  } else {
    animation_schedule((Animation*)prop_animation_slide_left);
  }
}

static void load_image_resource(uint32_t resource_id){
  if (gbitmap_ptr) {
    gbitmap_destroy(gbitmap_ptr);
    gbitmap_ptr = NULL;
  }
  gbitmap_ptr = gbitmap_create_with_resource(resource_id);
  image_index = resource_id;
  //layer_mark_dirty(bitmap_layer_get_layer(bitmap_layer));
}

static void increment_image(void){
  image_index = ( image_index >= max_images + RESOURCE_ID_IMAGE_OFFSET) ?
    (RESOURCE_ID_IMAGE_OFFSET + 1) : (image_index + 1);
  load_image_resource(image_index);
}

void tap_handler(AccelAxisType axis, int32_t direction){
  increment_image();
  do_animation();
}

void tick_handler(struct tm *tick_time, TimeUnits units_changed){
  if (units_changed & DAY_UNIT) {
    time_t current_time = time(NULL);
    struct tm *current_tm = localtime(&current_time);
    //strftime(date_string, sizeof(date_string), "%a %-m/%d", localtime(&current_time));
    snprintf(date_string, sizeof(date_string), "%s %d",
      dname[current_tm->tm_wday], current_tm->tm_mday);
    layer_mark_dirty(text_layer_get_layer(date_outline_layer));
    layer_mark_dirty(text_layer_get_layer(date_text_layer));
  }

  clock_copy_time_string(time_string,sizeof(time_string));
  layer_mark_dirty(text_layer_get_layer(time_outline_layer));
  layer_mark_dirty(text_layer_get_layer(time_text_layer));
}

static void init_animation(GRect bounds) {
  GRect right_image_bounds = (GRect){
    .origin = (GPoint){.x=144,.y=0},
    .size = bounds.size};

  GRect bottom_image_bounds = (GRect){
    .origin = (GPoint){.x=0,.y=168},
    .size = bounds.size};

  // Setup slide left animation
  prop_animation_slide_left = property_animation_create_layer_frame(
    animation_layer, &right_image_bounds, NULL);

  animation_set_duration((Animation*)prop_animation_slide_left, 1500);
  animation_set_curve((Animation*)prop_animation_slide_left,
    AnimationCurveEaseInOut);

  // Setup slide up animation
  prop_animation_slide_up = property_animation_create_layer_frame(
    animation_layer, &bottom_image_bounds, NULL);

  animation_set_duration((Animation*)prop_animation_slide_up, 1500);
  animation_set_curve((Animation*)prop_animation_slide_up,
    AnimationCurveEaseInOut);
}

static void window_load(Window *window) {
  Layer *window_layer = window_get_root_layer(window);
  GRect bounds = layer_get_bounds(window_layer);

  //Add layers from back to front (background first)

  //Initialise animations
  animation_layer = layer_create(bounds);
  layer_add_child(window_layer, animation_layer);
  init_animation(bounds);

  //Create bitmap layer for background image
  bitmap_layer = bitmap_layer_create(bounds);
  //Add bitmap_layer to animation layer
  layer_add_child(animation_layer, bitmap_layer_get_layer(bitmap_layer));

  //Load initial bitmap image
  load_image_resource(image_index);
  bitmap_layer_set_bitmap(bitmap_layer, gbitmap_ptr);

  //Setup the time outline display
  time_outline_layer = text_layer_create(GRect(0, 142, 144, 30));
  text_layer_set_text(time_outline_layer, time_string);
	text_layer_set_font(time_outline_layer, fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_BOXY_OUTLINE_30)));
  text_layer_set_text_alignment(time_outline_layer, GTextAlignmentCenter);
  text_layer_set_background_color(time_outline_layer, GColorClear);
  text_layer_set_text_color(time_outline_layer, GColorBlack);
  clock_copy_time_string(time_string,sizeof(time_string));

  //Add clock text second
  layer_add_child(window_layer, text_layer_get_layer(time_outline_layer));

  //Setup the time display
  time_text_layer = text_layer_create(GRect(0, 142, 144, 30));
  text_layer_set_text(time_text_layer, time_string);
	text_layer_set_font(time_text_layer, fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_BOXY_TEXT_30)));
  text_layer_set_text_alignment(time_text_layer, GTextAlignmentCenter);
  text_layer_set_background_color(time_text_layer, GColorClear);
  text_layer_set_text_color(time_text_layer, GColorWhite);
  clock_copy_time_string(time_string,sizeof(time_string));

  //Add clock text second
  layer_add_child(window_layer, text_layer_get_layer(time_text_layer));

  //Setup the date display
  time_t current_time = time(NULL);
  struct tm *current_tm = localtime(&current_time);
  //strftime(date_string, sizeof(date_string), "%a %_m/%d", localtime(&current_time));
  snprintf(date_string, sizeof(date_string), "%s %d",
    dname[current_tm->tm_wday], current_tm->tm_mday);

  //date outline
  date_outline_layer = text_layer_create(GRect(0, -4, 144, 18));
  text_layer_set_text(date_outline_layer, date_string);
	text_layer_set_font(date_outline_layer, fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_BOXY_OUTLINE_18)));
  text_layer_set_text_alignment(date_outline_layer, GTextAlignmentCenter);
  text_layer_set_background_color(date_outline_layer, GColorClear);
  text_layer_set_text_color(date_outline_layer, GColorBlack);

  layer_add_child(window_layer, text_layer_get_layer(date_outline_layer));

  //date text
  date_text_layer = text_layer_create(GRect(0, -4, 144, 18));
  text_layer_set_text(date_text_layer, date_string);
	text_layer_set_font(date_text_layer, fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_BOXY_TEXT_18)));
  text_layer_set_text_alignment(date_text_layer, GTextAlignmentCenter);
  text_layer_set_background_color(date_text_layer, GColorClear);
  text_layer_set_text_color(date_text_layer, GColorWhite);

  layer_add_child(window_layer, text_layer_get_layer(date_text_layer));

  //Setup tick time handler
  tick_timer_service_subscribe((MINUTE_UNIT), tick_handler);

  //Setup tap service
  accel_tap_service_subscribe(tap_handler);
}

static void window_unload(Window *window) {
}

void handle_init(void) {
  //Discover how many images from base index (offset+1)
  while (resource_get_handle(RESOURCE_ID_IMAGE_OFFSET + 1 + max_images)) {
    max_images++;
  }

  my_window = window_create();
  window_set_fullscreen(my_window, true);
  //Allows compositing new image animation over last image displayed
  window_set_background_color(my_window, GColorClear);
  window_set_window_handlers(my_window, (WindowHandlers) {
    .load = window_load,
    .unload = window_unload,
  });

  window_stack_push(my_window, false/*animated*/);
}

void handle_deinit(void) {
    bitmap_layer_destroy(bitmap_layer);
	  text_layer_destroy(time_outline_layer);
	  text_layer_destroy(time_text_layer);
	  window_destroy(my_window);
}

int main(void) {
	  handle_init();
	  app_event_loop();
	  handle_deinit();
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>RetryCounter xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />

View Javadoc

1
20  package org.apache.hadoop.hbase.util;
21
22  import java.util.concurrent.TimeUnit;
23
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26
27  public class RetryCounter {
28    private static final Log LOG = LogFactory.getLog(RetryCounter.class);
29    private final int maxRetries;
30    private int retriesRemaining;
31    private final int retryIntervalMillis;
32    private final TimeUnit timeUnit;
33
34    public RetryCounter(int maxRetries,
35    int retryIntervalMillis, TimeUnit timeUnit) {
36      this.maxRetries = maxRetries;
37      this.retriesRemaining = maxRetries;
38      this.retryIntervalMillis = retryIntervalMillis;
39      this.timeUnit = timeUnit;
40    }
41
42    public int getMaxRetries() {
43      return maxRetries;
44    }
45
46    /**
47     * Sleep for a exponentially back off time
48     * @throws InterruptedException
49     */
50    public void sleepUntilNextRetry() throws InterruptedException {
51      int attempts = getAttemptTimes();
52      long sleepTime = (long) (retryIntervalMillis * Math.pow(2, attempts));
53      LOG.info("Sleeping " + sleepTime + "ms before retry #" + attempts + "...");
54      timeUnit.sleep(sleepTime);
55    }
56
57    public boolean shouldRetry() {
58      return retriesRemaining > 0;
59    }
60
61    public void useRetry() {
62      retriesRemaining--;
63    }
64
65    public int getAttemptTimes() {
66      return maxRetries-retriesRemaining+1;
67    }
68  }

This page was automatically generated by Maven


text:
#ifndef YAVE_COMPONENTS_ATMOSPHERECOMPONENT_H
#define YAVE_COMPONENTS_ATMOSPHERECOMPONENT_H

#include <yave/assets/AssetPtr.h>

#include <yave/graphics/images/IBLProbe.h>

namespace yave {

class AtmosphereComponent final {
    public:
        float planet_radius = 3.0f;
        float atmosphere_height = 2.0f;

        float density_falloff = 1.0f;
        float scattering_strength = 400.0f;

        math::Vec3 wavelengths = math::Vec3(700.0f, 530.0f, 440.0f);
};

}

#endif // YAVE_COMPONENTS_ATMOSPHERECOMPONENT_H


text:
package common

import (
	"errors"
	"testing"
)

type TestError struct{}

var _ error = &TestError{}

func (*TestError) Error() string {
	return "test error"
}

func TestResolutionErrorUnwrap(t *testing.T) {
	originalError := &TestError{}
	resolutionError := NewError("", originalError)
	if !errors.Is(resolutionError, &TestError{}) {
		t.Errorf("resolution error expected to unwrap successfully")
	}
}

func TestResolutionErrorMessage(t *testing.T) {
	originalError := errors.New("this is just a test message")
	resolutionError := NewError("", originalError)
	if resolutionError.Error() != originalError.Error() {
		t.Errorf("resolution error message expected to equal that of original error")
	}
}


text:
package org.snf4j.core;

import java.net.SocketAddress;

interface IDatagramSessionForwarder {

	void incReadBytes(long bytes, long currentTime, SocketAddress remoteAddress);

	void incWrittenBytes(long bytes, long currentTime, SocketAddress remoteAddress);

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<page xmlns="http://jboss.org/schema/seam/pages"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://jboss.org/schema/seam/pages http://jboss.org/schema/seam/pages-2.3.xsd"
    view-id="/login.xhtml">

    <action execute="#{authenticator.preAuthenticate}" on-postback="false" />
    <rewrite pattern="/login" />

    <navigation from-action="#{identity.login}">
        <rule if="#{identity.loggedIn}">
            <redirect view-id="/home.xhtml" />
        </rule>
    </navigation>

    <navigation from-action="#{authenticator.preAuthenticate}">
        <rule if-outcome="true">
            <redirect view-id="/home.xhtml" />
        </rule>
    </navigation>
</page>


text: for (var i = function() { return 10 in [] } in list) process(x);


text:
<?php

namespace nabu\data\catalog;
use nabu\data\catalog\base\CNabuCatalogTaxonomyBase;

/**
 * @author Rafael Gutierrez <rgutierrez@nabu-3.com>
 * @version 3.0.0 Surface
 * @package \nabu\data\catalog
 */
class CNabuCatalogTaxonomy extends CNabuCatalogTaxonomyBase
{

}


text:
module FreshBooks
  class Gateway < FreshBooks::Base
    define_schema do |s|
      s.string :name
      s.boolean :autobill_capable
    end

    actions :list
  end
end


text:
import "../core/core.module";
import "../entry/entry.module";
import { OverviewService } from "./overview.service";
import { OverviewController } from "./overview.controller";

angular
    .module('xr.overview', ['xr.core', 'xr.entry'])
    .service('OverviewService', OverviewService)
    .controller('OverviewController', OverviewController);


text:
namespace grpc {
class CompletionQueue;
class Channel;
class RpcService;
class ServerCompletionQueue;
class ServerContext;
}  // namespace grpc

namespace google {
namespace cloud {
namespace billing {
namespace v1 {

// Retrieves Google Cloud Console billing accounts and associates them with
// projects.
class CloudBilling final {
 public:
  class StubInterface {
   public:
    virtual ~StubInterface() {}
    // Gets information about a billing account. The current authenticated user
    // must be an [owner of the billing
    // account](https://support.google.com/cloud/answer/4430947).
    virtual ::grpc::Status GetBillingAccount(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetBillingAccountRequest& request, ::google::cloud::billing::v1::BillingAccount* response) = 0;
    std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::BillingAccount>> AsyncGetBillingAccount(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetBillingAccountRequest& request, ::grpc::CompletionQueue* cq) {
      return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::BillingAccount>>(AsyncGetBillingAccountRaw(context, request, cq));
    }
    // Lists the billing accounts that the current authenticated user
    // [owns](https://support.google.com/cloud/answer/4430947).
    virtual ::grpc::Status ListBillingAccounts(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListBillingAccountsRequest& request, ::google::cloud::billing::v1::ListBillingAccountsResponse* response) = 0;
    std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ListBillingAccountsResponse>> AsyncListBillingAccounts(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListBillingAccountsRequest& request, ::grpc::CompletionQueue* cq) {
      return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ListBillingAccountsResponse>>(AsyncListBillingAccountsRaw(context, request, cq));
    }
    // Lists the projects associated with a billing account. The current
    // authenticated user must be an [owner of the billing
    // account](https://support.google.com/cloud/answer/4430947).
    virtual ::grpc::Status ListProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListProjectBillingInfoRequest& request, ::google::cloud::billing::v1::ListProjectBillingInfoResponse* response) = 0;
    std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ListProjectBillingInfoResponse>> AsyncListProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) {
      return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ListProjectBillingInfoResponse>>(AsyncListProjectBillingInfoRaw(context, request, cq));
    }
    // Gets the billing information for a project. The current authenticated user
    // must have [permission to view the
    // project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo
    // ).
    virtual ::grpc::Status GetProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetProjectBillingInfoRequest& request, ::google::cloud::billing::v1::ProjectBillingInfo* response) = 0;
    std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ProjectBillingInfo>> AsyncGetProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) {
      return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ProjectBillingInfo>>(AsyncGetProjectBillingInfoRaw(context, request, cq));
    }
    // Sets or updates the billing account associated with a project. You specify
    // the new billing account by setting the `billing_account_name` in the
    // `ProjectBillingInfo` resource to the resource name of a billing account.
    // Associating a project with an open billing account enables billing on the
    // project and allows charges for resource usage. If the project already had a
    // billing account, this method changes the billing account used for resource
    // usage charges.
    //
    // *Note:* Incurred charges that have not yet been reported in the transaction
    // history of the Google Cloud Console may be billed to the new billing
    // account, even if the charge occurred before the new billing account was
    // assigned to the project.
    //
    // The current authenticated user must have ownership privileges for both the
    // [project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo
    // ) and the [billing
    // account](https://support.google.com/cloud/answer/4430947).
    //
    // You can disable billing on the project by setting the
    // `billing_account_name` field to empty. This action disassociates the
    // current billing account from the project. Any billable activity of your
    // in-use services will stop, and your application could stop functioning as
    // expected. Any unbilled charges to date will be billed to the previously
    // associated account. The current authenticated user must be either an owner
    // of the project or an owner of the billing account for the project.
    //
    // Note that associating a project with a *closed* billing account will have
    // much the same effect as disabling billing on the project: any paid
    // resources used by the project will be shut down. Thus, unless you wish to
    // disable billing, you should always call this method with the name of an
    // *open* billing account.
    virtual ::grpc::Status UpdateProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest& request, ::google::cloud::billing::v1::ProjectBillingInfo* response) = 0;
    std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ProjectBillingInfo>> AsyncUpdateProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) {
      return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ProjectBillingInfo>>(AsyncUpdateProjectBillingInfoRaw(context, request, cq));
    }
  private:
    virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::BillingAccount>* AsyncGetBillingAccountRaw(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetBillingAccountRequest& request, ::grpc::CompletionQueue* cq) = 0;
    virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ListBillingAccountsResponse>* AsyncListBillingAccountsRaw(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListBillingAccountsRequest& request, ::grpc::CompletionQueue* cq) = 0;
    virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ListProjectBillingInfoResponse>* AsyncListProjectBillingInfoRaw(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) = 0;
    virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ProjectBillingInfo>* AsyncGetProjectBillingInfoRaw(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) = 0;
    virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::billing::v1::ProjectBillingInfo>* AsyncUpdateProjectBillingInfoRaw(::grpc::ClientContext* context, const ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) = 0;
  };
  class Stub final : public StubInterface {
   public:
    Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel);
    ::grpc::Status GetBillingAccount(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetBillingAccountRequest& request, ::google::cloud::billing::v1::BillingAccount* response) override;
    std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::BillingAccount>> AsyncGetBillingAccount(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetBillingAccountRequest& request, ::grpc::CompletionQueue* cq) {
      return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::BillingAccount>>(AsyncGetBillingAccountRaw(context, request, cq));
    }
    ::grpc::Status ListBillingAccounts(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListBillingAccountsRequest& request, ::google::cloud::billing::v1::ListBillingAccountsResponse* response) override;
    std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ListBillingAccountsResponse>> AsyncListBillingAccounts(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListBillingAccountsRequest& request, ::grpc::CompletionQueue* cq) {
      return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ListBillingAccountsResponse>>(AsyncListBillingAccountsRaw(context, request, cq));
    }
    ::grpc::Status ListProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListProjectBillingInfoRequest& request, ::google::cloud::billing::v1::ListProjectBillingInfoResponse* response) override;
    std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ListProjectBillingInfoResponse>> AsyncListProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) {
      return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ListProjectBillingInfoResponse>>(AsyncListProjectBillingInfoRaw(context, request, cq));
    }
    ::grpc::Status GetProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetProjectBillingInfoRequest& request, ::google::cloud::billing::v1::ProjectBillingInfo* response) override;
    std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ProjectBillingInfo>> AsyncGetProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) {
      return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ProjectBillingInfo>>(AsyncGetProjectBillingInfoRaw(context, request, cq));
    }
    ::grpc::Status UpdateProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest& request, ::google::cloud::billing::v1::ProjectBillingInfo* response) override;
    std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ProjectBillingInfo>> AsyncUpdateProjectBillingInfo(::grpc::ClientContext* context, const ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) {
      return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ProjectBillingInfo>>(AsyncUpdateProjectBillingInfoRaw(context, request, cq));
    }

   private:
    std::shared_ptr< ::grpc::ChannelInterface> channel_;
    ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::BillingAccount>* AsyncGetBillingAccountRaw(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetBillingAccountRequest& request, ::grpc::CompletionQueue* cq) override;
    ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ListBillingAccountsResponse>* AsyncListBillingAccountsRaw(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListBillingAccountsRequest& request, ::grpc::CompletionQueue* cq) override;
    ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ListProjectBillingInfoResponse>* AsyncListProjectBillingInfoRaw(::grpc::ClientContext* context, const ::google::cloud::billing::v1::ListProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) override;
    ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ProjectBillingInfo>* AsyncGetProjectBillingInfoRaw(::grpc::ClientContext* context, const ::google::cloud::billing::v1::GetProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) override;
    ::grpc::ClientAsyncResponseReader< ::google::cloud::billing::v1::ProjectBillingInfo>* AsyncUpdateProjectBillingInfoRaw(::grpc::ClientContext* context, const ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest& request, ::grpc::CompletionQueue* cq) override;
    const ::grpc::RpcMethod rpcmethod_GetBillingAccount_;
    const ::grpc::RpcMethod rpcmethod_ListBillingAccounts_;
    const ::grpc::RpcMethod rpcmethod_ListProjectBillingInfo_;
    const ::grpc::RpcMethod rpcmethod_GetProjectBillingInfo_;
    const ::grpc::RpcMethod rpcmethod_UpdateProjectBillingInfo_;
  };
  static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions());

  class Service : public ::grpc::Service {
   public:
    Service();
    virtual ~Service();
    // Gets information about a billing account. The current authenticated user
    // must be an [owner of the billing
    // account](https://support.google.com/cloud/answer/4430947).
    virtual ::grpc::Status GetBillingAccount(::grpc::ServerContext* context, const ::google::cloud::billing::v1::GetBillingAccountRequest* request, ::google::cloud::billing::v1::BillingAccount* response);
    // Lists the billing accounts that the current authenticated user
    // [owns](https://support.google.com/cloud/answer/4430947).
    virtual ::grpc::Status ListBillingAccounts(::grpc::ServerContext* context, const ::google::cloud::billing::v1::ListBillingAccountsRequest* request, ::google::cloud::billing::v1::ListBillingAccountsResponse* response);
    // Lists the projects associated with a billing account. The current
    // authenticated user must be an [owner of the billing
    // account](https://support.google.com/cloud/answer/4430947).
    virtual ::grpc::Status ListProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::ListProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ListProjectBillingInfoResponse* response);
    // Gets the billing information for a project. The current authenticated user
    // must have [permission to view the
    // project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo
    // ).
    virtual ::grpc::Status GetProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::GetProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ProjectBillingInfo* response);
    // Sets or updates the billing account associated with a project. You specify
    // the new billing account by setting the `billing_account_name` in the
    // `ProjectBillingInfo` resource to the resource name of a billing account.
    // Associating a project with an open billing account enables billing on the
    // project and allows charges for resource usage. If the project already had a
    // billing account, this method changes the billing account used for resource
    // usage charges.
    //
    // *Note:* Incurred charges that have not yet been reported in the transaction
    // history of the Google Cloud Console may be billed to the new billing
    // account, even if the charge occurred before the new billing account was
    // assigned to the project.
    //
    // The current authenticated user must have ownership privileges for both the
    // [project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo
    // ) and the [billing
    // account](https://support.google.com/cloud/answer/4430947).
    //
    // You can disable billing on the project by setting the
    // `billing_account_name` field to empty. This action disassociates the
    // current billing account from the project. Any billable activity of your
    // in-use services will stop, and your application could stop functioning as
    // expected. Any unbilled charges to date will be billed to the previously
    // associated account. The current authenticated user must be either an owner
    // of the project or an owner of the billing account for the project.
    //
    // Note that associating a project with a *closed* billing account will have
    // much the same effect as disabling billing on the project: any paid
    // resources used by the project will be shut down. Thus, unless you wish to
    // disable billing, you should always call this method with the name of an
    // *open* billing account.
    virtual ::grpc::Status UpdateProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ProjectBillingInfo* response);
  };
  template <class BaseClass>
  class WithAsyncMethod_GetBillingAccount : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithAsyncMethod_GetBillingAccount() {
      ::grpc::Service::MarkMethodAsync(0);
    }
    ~WithAsyncMethod_GetBillingAccount() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable synchronous version of this method
    ::grpc::Status GetBillingAccount(::grpc::ServerContext* context, const ::google::cloud::billing::v1::GetBillingAccountRequest* request, ::google::cloud::billing::v1::BillingAccount* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
    void RequestGetBillingAccount(::grpc::ServerContext* context, ::google::cloud::billing::v1::GetBillingAccountRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::billing::v1::BillingAccount>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
      ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag);
    }
  };
  template <class BaseClass>
  class WithAsyncMethod_ListBillingAccounts : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithAsyncMethod_ListBillingAccounts() {
      ::grpc::Service::MarkMethodAsync(1);
    }
    ~WithAsyncMethod_ListBillingAccounts() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable synchronous version of this method
    ::grpc::Status ListBillingAccounts(::grpc::ServerContext* context, const ::google::cloud::billing::v1::ListBillingAccountsRequest* request, ::google::cloud::billing::v1::ListBillingAccountsResponse* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
    void RequestListBillingAccounts(::grpc::ServerContext* context, ::google::cloud::billing::v1::ListBillingAccountsRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::billing::v1::ListBillingAccountsResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
      ::grpc::Service::RequestAsyncUnary(1, context, request, response, new_call_cq, notification_cq, tag);
    }
  };
  template <class BaseClass>
  class WithAsyncMethod_ListProjectBillingInfo : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithAsyncMethod_ListProjectBillingInfo() {
      ::grpc::Service::MarkMethodAsync(2);
    }
    ~WithAsyncMethod_ListProjectBillingInfo() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable synchronous version of this method
    ::grpc::Status ListProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::ListProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ListProjectBillingInfoResponse* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
    void RequestListProjectBillingInfo(::grpc::ServerContext* context, ::google::cloud::billing::v1::ListProjectBillingInfoRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::billing::v1::ListProjectBillingInfoResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
      ::grpc::Service::RequestAsyncUnary(2, context, request, response, new_call_cq, notification_cq, tag);
    }
  };
  template <class BaseClass>
  class WithAsyncMethod_GetProjectBillingInfo : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithAsyncMethod_GetProjectBillingInfo() {
      ::grpc::Service::MarkMethodAsync(3);
    }
    ~WithAsyncMethod_GetProjectBillingInfo() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable synchronous version of this method
    ::grpc::Status GetProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::GetProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ProjectBillingInfo* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
    void RequestGetProjectBillingInfo(::grpc::ServerContext* context, ::google::cloud::billing::v1::GetProjectBillingInfoRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::billing::v1::ProjectBillingInfo>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
      ::grpc::Service::RequestAsyncUnary(3, context, request, response, new_call_cq, notification_cq, tag);
    }
  };
  template <class BaseClass>
  class WithAsyncMethod_UpdateProjectBillingInfo : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithAsyncMethod_UpdateProjectBillingInfo() {
      ::grpc::Service::MarkMethodAsync(4);
    }
    ~WithAsyncMethod_UpdateProjectBillingInfo() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable synchronous version of this method
    ::grpc::Status UpdateProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ProjectBillingInfo* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
    void RequestUpdateProjectBillingInfo(::grpc::ServerContext* context, ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::billing::v1::ProjectBillingInfo>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
      ::grpc::Service::RequestAsyncUnary(4, context, request, response, new_call_cq, notification_cq, tag);
    }
  };
  typedef WithAsyncMethod_GetBillingAccount<WithAsyncMethod_ListBillingAccounts<WithAsyncMethod_ListProjectBillingInfo<WithAsyncMethod_GetProjectBillingInfo<WithAsyncMethod_UpdateProjectBillingInfo<Service > > > > > AsyncService;
  template <class BaseClass>
  class WithGenericMethod_GetBillingAccount : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithGenericMethod_GetBillingAccount() {
      ::grpc::Service::MarkMethodGeneric(0);
    }
    ~WithGenericMethod_GetBillingAccount() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable synchronous version of this method
    ::grpc::Status GetBillingAccount(::grpc::ServerContext* context, const ::google::cloud::billing::v1::GetBillingAccountRequest* request, ::google::cloud::billing::v1::BillingAccount* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
  };
  template <class BaseClass>
  class WithGenericMethod_ListBillingAccounts : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithGenericMethod_ListBillingAccounts() {
      ::grpc::Service::MarkMethodGeneric(1);
    }
    ~WithGenericMethod_ListBillingAccounts() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable synchronous version of this method
    ::grpc::Status ListBillingAccounts(::grpc::ServerContext* context, const ::google::cloud::billing::v1::ListBillingAccountsRequest* request, ::google::cloud::billing::v1::ListBillingAccountsResponse* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
  };
  template <class BaseClass>
  class WithGenericMethod_ListProjectBillingInfo : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithGenericMethod_ListProjectBillingInfo() {
      ::grpc::Service::MarkMethodGeneric(2);
    }
    ~WithGenericMethod_ListProjectBillingInfo() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable synchronous version of this method
    ::grpc::Status ListProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::ListProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ListProjectBillingInfoResponse* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
  };
  template <class BaseClass>
  class WithGenericMethod_GetProjectBillingInfo : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithGenericMethod_GetProjectBillingInfo() {
      ::grpc::Service::MarkMethodGeneric(3);
    }
    ~WithGenericMethod_GetProjectBillingInfo() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable synchronous version of this method
    ::grpc::Status GetProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::GetProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ProjectBillingInfo* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
  };
  template <class BaseClass>
  class WithGenericMethod_UpdateProjectBillingInfo : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithGenericMethod_UpdateProjectBillingInfo() {
      ::grpc::Service::MarkMethodGeneric(4);
    }
    ~WithGenericMethod_UpdateProjectBillingInfo() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable synchronous version of this method
    ::grpc::Status UpdateProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ProjectBillingInfo* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
  };
  template <class BaseClass>
  class WithStreamedUnaryMethod_GetBillingAccount : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithStreamedUnaryMethod_GetBillingAccount() {
      ::grpc::Service::MarkMethodStreamed(0,
        new ::grpc::StreamedUnaryHandler< ::google::cloud::billing::v1::GetBillingAccountRequest, ::google::cloud::billing::v1::BillingAccount>(std::bind(&WithStreamedUnaryMethod_GetBillingAccount<BaseClass>::StreamedGetBillingAccount, this, std::placeholders::_1, std::placeholders::_2)));
    }
    ~WithStreamedUnaryMethod_GetBillingAccount() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable regular version of this method
    ::grpc::Status GetBillingAccount(::grpc::ServerContext* context, const ::google::cloud::billing::v1::GetBillingAccountRequest* request, ::google::cloud::billing::v1::BillingAccount* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
    // replace default version of method with streamed unary
    virtual ::grpc::Status StreamedGetBillingAccount(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::billing::v1::GetBillingAccountRequest,::google::cloud::billing::v1::BillingAccount>* server_unary_streamer) = 0;
  };
  template <class BaseClass>
  class WithStreamedUnaryMethod_ListBillingAccounts : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithStreamedUnaryMethod_ListBillingAccounts() {
      ::grpc::Service::MarkMethodStreamed(1,
        new ::grpc::StreamedUnaryHandler< ::google::cloud::billing::v1::ListBillingAccountsRequest, ::google::cloud::billing::v1::ListBillingAccountsResponse>(std::bind(&WithStreamedUnaryMethod_ListBillingAccounts<BaseClass>::StreamedListBillingAccounts, this, std::placeholders::_1, std::placeholders::_2)));
    }
    ~WithStreamedUnaryMethod_ListBillingAccounts() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable regular version of this method
    ::grpc::Status ListBillingAccounts(::grpc::ServerContext* context, const ::google::cloud::billing::v1::ListBillingAccountsRequest* request, ::google::cloud::billing::v1::ListBillingAccountsResponse* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
    // replace default version of method with streamed unary
    virtual ::grpc::Status StreamedListBillingAccounts(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::billing::v1::ListBillingAccountsRequest,::google::cloud::billing::v1::ListBillingAccountsResponse>* server_unary_streamer) = 0;
  };
  template <class BaseClass>
  class WithStreamedUnaryMethod_ListProjectBillingInfo : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithStreamedUnaryMethod_ListProjectBillingInfo() {
      ::grpc::Service::MarkMethodStreamed(2,
        new ::grpc::StreamedUnaryHandler< ::google::cloud::billing::v1::ListProjectBillingInfoRequest, ::google::cloud::billing::v1::ListProjectBillingInfoResponse>(std::bind(&WithStreamedUnaryMethod_ListProjectBillingInfo<BaseClass>::StreamedListProjectBillingInfo, this, std::placeholders::_1, std::placeholders::_2)));
    }
    ~WithStreamedUnaryMethod_ListProjectBillingInfo() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable regular version of this method
    ::grpc::Status ListProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::ListProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ListProjectBillingInfoResponse* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
    // replace default version of method with streamed unary
    virtual ::grpc::Status StreamedListProjectBillingInfo(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::billing::v1::ListProjectBillingInfoRequest,::google::cloud::billing::v1::ListProjectBillingInfoResponse>* server_unary_streamer) = 0;
  };
  template <class BaseClass>
  class WithStreamedUnaryMethod_GetProjectBillingInfo : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithStreamedUnaryMethod_GetProjectBillingInfo() {
      ::grpc::Service::MarkMethodStreamed(3,
        new ::grpc::StreamedUnaryHandler< ::google::cloud::billing::v1::GetProjectBillingInfoRequest, ::google::cloud::billing::v1::ProjectBillingInfo>(std::bind(&WithStreamedUnaryMethod_GetProjectBillingInfo<BaseClass>::StreamedGetProjectBillingInfo, this, std::placeholders::_1, std::placeholders::_2)));
    }
    ~WithStreamedUnaryMethod_GetProjectBillingInfo() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable regular version of this method
    ::grpc::Status GetProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::GetProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ProjectBillingInfo* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
    // replace default version of method with streamed unary
    virtual ::grpc::Status StreamedGetProjectBillingInfo(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::billing::v1::GetProjectBillingInfoRequest,::google::cloud::billing::v1::ProjectBillingInfo>* server_unary_streamer) = 0;
  };
  template <class BaseClass>
  class WithStreamedUnaryMethod_UpdateProjectBillingInfo : public BaseClass {
   private:
    void BaseClassMustBeDerivedFromService(const Service *service) {}
   public:
    WithStreamedUnaryMethod_UpdateProjectBillingInfo() {
      ::grpc::Service::MarkMethodStreamed(4,
        new ::grpc::StreamedUnaryHandler< ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest, ::google::cloud::billing::v1::ProjectBillingInfo>(std::bind(&WithStreamedUnaryMethod_UpdateProjectBillingInfo<BaseClass>::StreamedUpdateProjectBillingInfo, this, std::placeholders::_1, std::placeholders::_2)));
    }
    ~WithStreamedUnaryMethod_UpdateProjectBillingInfo() override {
      BaseClassMustBeDerivedFromService(this);
    }
    // disable regular version of this method
    ::grpc::Status UpdateProjectBillingInfo(::grpc::ServerContext* context, const ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest* request, ::google::cloud::billing::v1::ProjectBillingInfo* response) final override {
      abort();
      return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
    }
    // replace default version of method with streamed unary
    virtual ::grpc::Status StreamedUpdateProjectBillingInfo(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::billing::v1::UpdateProjectBillingInfoRequest,::google::cloud::billing::v1::ProjectBillingInfo>* server_unary_streamer) = 0;
  };
  typedef WithStreamedUnaryMethod_GetBillingAccount<WithStreamedUnaryMethod_ListBillingAccounts<WithStreamedUnaryMethod_ListProjectBillingInfo<WithStreamedUnaryMethod_GetProjectBillingInfo<WithStreamedUnaryMethod_UpdateProjectBillingInfo<Service > > > > > StreamedUnaryService;
  typedef Service SplitStreamedService;
  typedef WithStreamedUnaryMethod_GetBillingAccount<WithStreamedUnaryMethod_ListBillingAccounts<WithStreamedUnaryMethod_ListProjectBillingInfo<WithStreamedUnaryMethod_GetProjectBillingInfo<WithStreamedUnaryMethod_UpdateProjectBillingInfo<Service > > > > > StreamedService;
};

}  // namespace v1
}  // namespace billing
}  // namespace cloud
}  // namespace google

#endif  // GRPC_google_2fcloud_2fbilling_2fv1_2fcloud_5fbilling_2eproto__INCLUDED


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.ui;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.ExceptionUtilRt;
import com.intellij.util.ReflectionUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import javax.swing.*;
import java.awt.*;
import java.awt.event.InvocationEvent;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicReference;

/**
 *
Encapsulates EDT-related checks and processing. The general idea is that IntelliJ threading model is tightly bound with EDT
 * (e.g. write access is allowed from EDT only and any task executed from EDT is implicitly granted read access). That makes
 * a huge bottleneck in non-IntelliJ environments like Upsource - every vcs revision there is represented as a separate ide project
 * object, hence, global shared write lock and single EDT become a problem.

 *
 *
That's why it should be possible to change that model in non-IntelliJ environment - that involves either custom read/write locks
 * processing or custom EDT processing as well. This interface covers EDT part.

 */
public abstract class EdtInvocationManager {
  private static final AtomicReference<EdtInvocationManager> ourInstance = new AtomicReference<>();

  private static MethodHandle dispatchEventMethod;

  /**
   * Dispatch all pending invocation events (if any) in the {@link com.intellij.ide.IdeEventQueue}, ignores and removes all other events from the queue.
   * In tests, consider using {@link com.intellij.testFramework.PlatformTestUtil#dispatchAllInvocationEventsInIdeEventQueue()}
   * @see UIUtil#pump()
   */
  @TestOnly
  public static void dispatchAllInvocationEvents() {
    assert getInstance().isEventDispatchThread() : Thread.currentThread() + "; EDT: " + getEventQueueThread();
    EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();

    MethodHandle dispatchEventMethod = EdtInvocationManager.dispatchEventMethod;
    if (dispatchEventMethod == null) {
      try {
        Method method = EventQueue.class.getDeclaredMethod("dispatchEvent", AWTEvent.class);
        method.setAccessible(true);
        dispatchEventMethod = MethodHandles.lookup().unreflect(method);
      }
      catch (NoSuchMethodException | IllegalAccessException e) {
        throw new RuntimeException();
      }

      EdtInvocationManager.dispatchEventMethod = dispatchEventMethod;
    }

    for (int i = 1; ; i++) {
      AWTEvent event = eventQueue.peekEvent();
      if (event == null) break;
      try {
        event = eventQueue.getNextEvent();
        if (event instanceof InvocationEvent) {
          dispatchEventMethod.bindTo(eventQueue).invoke(event);
        }
      }
      catch (Throwable e) {
        ExceptionUtilRt.rethrowUnchecked(e);
        throw new RuntimeException(e);
      }

      if (i % 10000 == 0) {
        //noinspection UseOfSystemOutOrSystemErr
        System.out.println("Suspiciously many (" + i + ") AWT events, last dispatched " + event);
      }
    }
  }

  private static @NotNull Thread getEventQueueThread() {
    EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
    try {
      Method method = ReflectionUtil.getDeclaredMethod(EventQueue.class, "getDispatchThread");
      //noinspection ConstantConditions
      return (Thread)method.invoke(eventQueue);
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Please use Application.invokeLater() with a modality state (or GuiUtils, or TransactionGuard methods), unless you work with Swings internals
   * and 'runnable' deals with Swings components only and doesn't access any PSI, VirtualFiles, project/module model or other project settings. For those, use GuiUtils, application.invoke* or TransactionGuard methods.

   *
   * On AWT thread, invoked runnable immediately, otherwise do {@link SwingUtilities#invokeLater(Runnable)} on it.
   */
  public static void invokeLaterIfNeeded(@NotNull Runnable runnable) {
    EdtInvocationManager edtInvocationManager = getInstance();
    if (edtInvocationManager.isEventDispatchThread()) {
      runnable.run();
    }
    else {
      edtInvocationManager.invokeLater(runnable);
    }
  }

  public abstract boolean isEventDispatchThread();

  public abstract void invokeLater(@NotNull Runnable task);

  public abstract void invokeAndWait(@NotNull Runnable task) throws InvocationTargetException, InterruptedException;

  @NotNull
  public static EdtInvocationManager getInstance() {
    EdtInvocationManager result = ourInstance.get();
    if (result == null) {
      result = new SwingEdtInvocationManager();
      if (!ourInstance.compareAndSet(null, result)) {
        result = ourInstance.get();
      }
    }
    return result;
  }

  public static @Nullable EdtInvocationManager setEdtInvocationManager(@NotNull EdtInvocationManager edtInvocationManager) {
    return ourInstance.getAndSet(edtInvocationManager);
  }

  @ApiStatus.Internal
  public static void restoreEdtInvocationManager(@NotNull EdtInvocationManager current, @Nullable EdtInvocationManager old) {
    ourInstance.compareAndSet(current, old);
  }

  /**
   * Please use Application.invokeAndWait() with a modality state (or GuiUtils, or TransactionGuard methods), unless you work with Swings internals
   * and 'runnable' deals with Swings components only and doesn't access any PSI, VirtualFiles, project/module model or other project settings.

   *
   * Invoke and wait in the event dispatch thread
   * or in the current thread if the current thread
   * is event queue thread.
   * DO NOT INVOKE THIS METHOD FROM UNDER READ ACTION.
   */
  public static void invokeAndWaitIfNeeded(@NotNull Runnable runnable) {
    EdtInvocationManager manager = getInstance();
    if (manager.isEventDispatchThread()) {
      runnable.run();
    }
    else {
      try {
        manager.invokeAndWait(runnable);
      }
      catch (Exception e) {
        Logger.getInstance(EdtInvocationManager.class).error(e);
      }
    }
  }

  /**
   * The default {@link EdtInvocationManager} implementation that uses {@link EventQueue}.
   */
  public static class SwingEdtInvocationManager extends EdtInvocationManager {
    @Override
    public boolean isEventDispatchThread() {
      return EventQueue.isDispatchThread();
    }

    @Override
    public void invokeLater(@NotNull Runnable task) {
      EventQueue.invokeLater(task);
    }

    @Override
    public void invokeAndWait(@NotNull Runnable task) throws InvocationTargetException, InterruptedException {
      EventQueue.invokeAndWait(task);
    }
  }
}


text:
package edu.bupt.thrift.service.impl;

/**
 * @author 孙元成 E-mail:stevesun521@gmail.com
 * @version 创建时间:2012-6-14 下午9:47:45
 * 类说明
 */
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.zookeeper.ZooKeeper;

import edu.bupt.cameras.CameraManager;
import edu.bupt.thrift.service.*;
import edu.bupt.zookeeper.beans.CameraX;
import edu.bupt.zookeeper.conf.impl.GConf;
import edu.bupt.zookeeper.conf.impl.MetricsConf;
import edu.bupt.zookeeper.util.MetricsUtil;

public class ZkTServiceImpl implements ZkTService.Iface {
	private Logger logger = Logger.getLogger(ZkTServiceImpl.class);
	// 此处CameraManager 需要考虑同步问题
	private CameraManager cameraManager = null;
	private ZooKeeper zk = null;
	private GConf gConf = null;
	private MetricsConf mConf = null;

	public ZkTServiceImpl(CameraManager cameraManager, ZooKeeper zk) {
		this.cameraManager = cameraManager;
		this.zk = zk;
		gConf = new GConf(zk);
		mConf = new MetricsConf(zk);
	}

	// 手动添加一个serverip的对应的摄像头ip
	@Override
	public boolean addCamera(String serverip, String camip)
			throws TException {
		logger.info("CALL addCamera");
		boolean ret = false;
			if (gConf.addCamera(serverip, camip)) {
				synchronized (cameraManager) {
					ArrayList<String> camlist = new ArrayList<String>(); // TODO
																			// cameraManager接口需要重构
					camlist.add(camip);
					cameraManager.addCamera(camlist);
					logger.info("CALL SERVER addCamera");
				}
				try {
					double now_metics = MetricsUtil.calcMetrics(cameraManager);
					mConf.updateMetricsByIP(serverip, now_metics);
					logger.info("更新metrics");
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ret = true;
				logger.info("CALL SERVER addCamera over!");
			}
		return ret;
	}

	// 删除服务器serverip管理的一个对应的摄像头ip
	@Override
	public boolean deleteCamera(String serverip, String camip)
			throws TException {
		boolean ret = false;
		logger.info("CALL deleteCamera ...................");
		if (gConf.deleteCamera(serverip, camip)) {
			synchronized (cameraManager) {
				ArrayList<String> camlist = new ArrayList<String>(); // TODO
																		// cameraManager接口需要重构
				camlist.add(camip);
				cameraManager.deleteCamera(camlist);
			}
			logger.info("CALL deleteCamera finishing");
			ret = true;
		} else {
			logger.warn("CALL deteteCamera warning");
		}
		return ret;
	}

	@Override
	public List<String> getAllCamsByServerIP(String serverip) throws TException {
		ArrayList<CameraX> listc = gConf.getCameraXListByServerX(serverip);
		List<String> camips = new ArrayList<String>();
		for (CameraX cameraX : listc) {
			camips.add(cameraX.getCip());
		}
		logger.info("CALL getAllCamsByServerIP");
		return camips;
	}

	@Override
	public boolean deleteServerX(String serverip) throws TException {
		if (gConf.delServerX(gConf.getServerXByIp(serverip)) == true) {
			logger.info("CALL deleteServerX Successful");
			return true;
		}
		return false;
	}

	@Override
	public double getMetrics(String serverip) throws TException {
		Double metrics = mConf.getMetricsByIP(serverip);
		return metrics;
	}

	@Override
	public Map<String, Double> getAllMetrics() throws TException {
		Hashtable<String, Double> metricstable = new Hashtable<String, Double>();
		metricstable = mConf.getMetrisTable();
		return metricstable;
	}

	@Override
	public ServerMetrics getBestMetricsEntry() throws TException {
		String bestserverip = MetricsUtil.getBestServerXIP(mConf
				.getMetrisTable());
		Double metrics = mConf.getMetricsByIP(bestserverip);
		ServerMetrics serverMetrics = new ServerMetrics(bestserverip, metrics);
		return serverMetrics;
	}

	@Override
	public Map<String, Double> getBestMetEntry() throws TException {
		String bestserverip = MetricsUtil.getBestServerXIP(mConf
				.getMetrisTable());
		Double metrics = mConf.getMetricsByIP(bestserverip);
		Hashtable<String, Double> table = new Hashtable<String, Double>();
		table.put(bestserverip, metrics);
		return table;
	}

	// 将一个摄像头从一个节点手动转移到其他节点进行
	@Override
	public boolean transferCam(String fromserver, String toserver, String camip)
			throws TException {
		boolean addret=false,delret=false;
		logger.info("Call transferCam operation start");
		if(addret=addCamera(toserver,camip)){
			logger.info("transferCam add cam operation successfully!");
		}else{
			logger.info("transferCam add cam operation failed!");
		}
		if(delret=deleteCamera(fromserver, camip)){
			logger.info("transferCam delete cam operation successfully!");
		}else{
			logger.info("transferCam delete cam operation failed!");
		}
		logger.info("Call transferCam operation finished");
		return addret&&delret;
	}

}


text:
package com.helloandroid.framework;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;

/**
 * Created by scott on 16/1/15.
 */
public class OttoActivity extends AppCompatActivity {

    Bus bus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = new View(this);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));

        setContentView(view);

        bus = new Bus();
        bus.register(this);

        bus.post(new SomeEvent("SomeEvent"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        bus.unregister(this);
    }

    @Subscribe
    public void handleEvent(SomeEvent someEvent) {
        if (someEvent != null) {
            Handler handler = new Handler();
            handler.postDelayed(() -> Toast.makeText(getApplicationContext(), someEvent.some, Toast.LENGTH_SHORT)
                    .show(), 2000);

        }
    }

    public static class SomeEvent {
        public final String some;

        public SomeEvent(String some) {
            this.some = some;
        }
    }

}


text:
package software.amazon.awssdk.protocol.model;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

public class TestSuite {

    private final List<String> testCases;

    @JsonCreator
    public TestSuite(@JsonProperty("testCases") List<String> testCases) {
        this.testCases = testCases;
    }

    public List<String> getTestCases() {
        return testCases;
    }

}


text:
jest.dontMock('../sticky-stack-item');

import React from 'react';
import TestUtils from 'react-addons-test-utils';

const StickyStackItem = require('../sticky-stack-item').default;

describe('StickyStackItem', () => {
  let register;

  beforeEach(() => {
    register = jest.genMockFunction();

    const FakeContext = React.createClass({
      propTypes: {
        children: React.PropTypes.element,
      },
      childContextTypes: {
        getStyle: React.PropTypes.func,
        register: React.PropTypes.func,
      },
      getChildContext() {
        return {
          getStyle: () => {},
          register,
        };
      },
      render() {
        return <div>{this.props.children}</div>;
      },
    });

    TestUtils.renderIntoDocument(
      <FakeContext>
        <StickyStackItem position={0} />
      </FakeContext>
    );
  });

  it('registers itself to the context', () => {
    expect(register).toBeCalled();
  });
});


text:
import React from 'react';
import { createRendererWithUniDriver, cleanup } from '../../../test/utils/unit';

import Dropzone from '../Dropzone';
import { dropzonePrivateDriverFactory } from './Dropzone.private.uni.driver';

const dropzoneWithStub = (stub = jest.fn()) => (
  <Dropzone onDrop={stub}>
    <Dropzone.Overlay>

    </Dropzone.Overlay>
    <Dropzone.Content>

    </Dropzone.Content>
  </Dropzone>
);

describe(Dropzone.displayName, () => {
  const someFiles = [
    new File(['foo'], 'foo.txt', {
      type: 'text/plain',
    }),
  ];

  const render = createRendererWithUniDriver(dropzonePrivateDriverFactory);

  it('should render', async () => {
    const driver = render(dropzoneWithStub()).driver;

    expect(await driver.exists()).toBe(true);
    expect(await driver.getContentElement().exists()).toBe(true);
    expect(await driver.getOverlayElement().exists()).toBe(false);
  });

  describe('event handling', () => {
    let driver, onDropStub;

    beforeEach(() => {
      onDropStub = jest.fn();

      driver = render(dropzoneWithStub(onDropStub)).driver;
    });

    afterEach(() => {
      cleanup();
    });

    it('should call onDrop when drop event happens and it has files', async () => {
      await driver.dropFiles(someFiles);

      expect(onDropStub).toHaveBeenCalledWith(someFiles);
    });

    it("should not call onDrop when drop event happens and it doesn't has files", async () => {
      await driver.dropFiles([]);

      expect(onDropStub).not.toHaveBeenCalled();
    });

    it('should render the overlay when files are hovered on the dropzone', async () => {
      await driver.hover(someFiles);

      expect(await driver.getOverlayElement().exists()).toBe(true);
    });

    it("should not render the overlay when hover event happens and it doesn't have files", async () => {
      await driver.hover([]);

      expect(await driver.getOverlayElement().exists()).toBe(false);
    });

    it('should unrender the overlay when files are unhovered on the dropzone', async () => {
      await driver.hover(someFiles);
      expect(await driver.getOverlayElement().exists()).toBe(true);

      await driver.unhover();
      expect(await driver.getOverlayElement().exists()).toBe(false);
    });

    it('should unrender the overlay when files are dropped on the dropzone', async () => {
      await driver.hover(someFiles);
      expect(await driver.getOverlayElement().exists()).toBe(true);

      await driver.dropFiles(someFiles);
      expect(await driver.getOverlayElement().exists()).toBe(false);
    });
  });

  describe('children type check', () => {
    let consoleErrorStub;

    beforeEach(() => {
      consoleErrorStub = jest
        .spyOn(console, 'error')
        .mockImplementation((message, ...args) => {
          if (/Failed prop type/gi.test(message)) throw new Error(message);
        });
    });

    afterEach(() => {
      consoleErrorStub.mockRestore();
    });

    it('should throw an error when only Overlay is provided', () => {
      const renderFactory = () =>
        render(
          <Dropzone onDrop={jest.fn()}>
            <Dropzone.Overlay />
          </Dropzone>,
        );

      expect(renderFactory).toThrow('<Dropzone.Content /> must be provided');
    });

    it('should throw an error when only Content is provided', () => {
      const renderFactory = () =>
        render(
          <Dropzone onDrop={jest.fn()}>
            <Dropzone.Content />
          </Dropzone>,
        );

      expect(renderFactory).toThrow('<Dropzone.Overlay /> must be provided');
    });

    it('should throw an error when an element which is not Overlay nor Content is present', () => {
      const renderFactory = () =>
        render(
          <Dropzone onDrop={jest.fn()}>
            <Dropzone.Content />
            <Dropzone.Overlay />

          </Dropzone>,
        );

      expect(renderFactory).toThrow('unknown child
');
    });
  });
});


text:
FAQ
===

**Q: Why don't shell pipe and redirect (| and >) work when I spawn a command?**

A: Remember that Pexpect does NOT interpret shell meta characters such as
redirect, pipe, or wild cards (``>``, ``|``, or ``*``). That's done by a shell not
the command you are spawning. This is a common mistake. If you want to run a
command and pipe it through another command then you must also start a shell.
For example::

    child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
    child.expect(pexpect.EOF)

The second form of spawn (where you pass a list of arguments) is useful in
situations where you wish to spawn a command and pass it its own argument list.
This can make syntax more clear. For example, the following is equivalent to the
previous example::

    shell_cmd = 'ls -l | grep LOG > log_list.txt'
    child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
    child.expect(pexpect.EOF)

**Q: Isn't there already a Python Expect?**

A: Yes, there are several of them. They usually require you to compile C.
I wanted something that was pure Python and preferably a single module
that was simple to install. I also wanted something that was easy to use.
This pure Python expect only became possible with the introduction of
the pty module in the standard Python library. Previously, C extensions
were required.

**Q: The `before` and `after` properties sound weird.**

A: This is how the -B and -A options in grep works, so that made it
easier for me to remember. Whatever makes my life easier is what's best.
Originally I was going to model Pexpect after Expect, but then I found
that I didn't actually like the way Expect did some things. It was more
confusing. The `after` property can be a little confusing at first,
because it will actually include the matched string. The `after` means
after the point of match, not after the matched string.

**Q: Why not just use Expect?**

A: I love it. It's great. I has bailed me out of some real jams, but I
wanted something that would do 90% of what I need from Expect; be 10% of
the size; and allow me to write my code in Python instead of TCL.
Pexpect is not nearly as big as Expect, but Pexpect does everything I
have ever used Expect for.

.. _whynotpipe:

**Q: Why not just use a pipe (popen())?**

A: A pipe works fine for getting the output to non-interactive programs.
If you just want to get the output from ls, uname, or ping then this
works. Pipes do not work very well for interactive programs and pipes
will almost certainly fail for most applications that ask for passwords
such as telnet, ftp, or ssh.

There are two reasons for this.

* First an application may bypass stdout and print directly to its
  controlling TTY. Something like SSH will do this when it asks you for
  a password. This is why you cannot redirect the password prompt because
  it does not go through stdout or stderr.

* The second reason is because most applications are built using the C
  Standard IO Library (anything that uses ``#include <stdio.h>``). One
  of the features of the stdio library is that it buffers all input and
  output. Normally output is line buffered when a program is printing to
  a TTY (your terminal screen). Everytime the program prints a line-feed
  the currently buffered data will get printed to your screen. The
  problem comes when you connect a pipe. The stdio library is smart and
  can tell that it is printing to a pipe instead of a TTY. In that case
  it switches from line buffer mode to block buffered. In this mode the
  currently buffered data is flushed when the buffer is full. This
  causes most interactive programs to deadlock. Block buffering is more
  efficient when writing to disks and pipes. Take the situation where a
  program prints a message ``"Enter your user name:\n"`` and then waits
  for you type type something. In block buffered mode, the stdio library
  will not put the message into the pipe even though a linefeed is
  printed. The result is that you never receive the message, yet the
  child application will sit and wait for you to type a response. Don't
  confuse the stdio lib's buffer with the pipe's buffer. The pipe buffer
  is another area that can cause problems. You could flush the input
  side of a pipe, whereas you have no control over the stdio library buffer.

More information: the Standard IO library has three states for a
``FILE *``. These are: _IOFBF for block buffered; _IOLBF for line buffered;
and _IONBF for unbuffered. The STDIO lib will use block buffering when
talking to a block file descriptor such as a pipe. This is usually not
helpful for interactive programs. Short of recompiling your program to
include fflush() everywhere or recompiling a custom stdio library there
is not much a controlling application can do about this if talking over
a pipe.

The program may have put data in its output that remains unflushed
because the output buffer is not full; then the program will go and
deadlock while waiting for input -- because you never send it any
because you are still waiting for its output (still stuck in the STDIO's
output buffer).

The answer is to use a pseudo-tty. A TTY device will force line
buffering (as opposed to block buffering). Line buffering means that you
will get each line when the child program sends a line feed. This
corresponds to the way most interactive programs operate -- send a line
of output then wait for a line of input.

I put "answer" in quotes because it's ugly solution and because there is
no POSIX standard for pseudo-TTY devices (even though they have a TTY
standard...). What would make more sense to me would be to have some way
to set a mode on a file descriptor so that it will tell the STDIO to be
line-buffered. I have investigated, and I don't think there is a way to
set the buffered state of a child process. The STDIO Library does not
maintain any external state in the kernel or whatnot, so I don't think
there is any way for you to alter it. I'm not quite sure how this
line-buffered/block-buffered state change happens internally in the
STDIO library. I think the STDIO lib looks at the file descriptor and
decides to change behavior based on whether it's a TTY or a block file
(see isatty()).

I hope that this qualifies as helpful. Don't use a pipe to control
another application.

**Q: Can I do screen scraping with this thing?**

A: That depends. If your application just does line-oriented output then
this is easy. If it does screen-oriented output then it may work, but it
could be hard. For example, trying to scrape data from the 'top' command
would be hard. The top command repaints the text window.

I am working on an ANSI / VT100 terminal emulator that will have methods
to get characters from an arbitrary X,Y coordinate of the virtual screen.
It works and you can play with it (see :mod:`pexpect.ANSI`), but I have
no working examples at this time.


text:
define("dijit/form/FilteringSelect",["dojo/_base/declare","dojo/_base/lang","dojo/when","./MappedTextBox","./ComboBoxMixin"],function(_1,_2,_3,_4,_5){
return _1("dijit.form.FilteringSelect",[_4,_5],{required:true,_lastDisplayedValue:"",_isValidSubset:function(){
return this._opened;
},isValid:function(){
return !!this.item||(!this.required&&this.get("displayedValue")=="");
},_refreshState:function(){
if(!this.searchTimer){
this.inherited(arguments);
}
},_callbackSetLabel:function(_6,_7,_8,_9){
if((_7&&_7[this.searchAttr]!==this._lastQuery)||(!_7&&_6.length&&this.store.getIdentity(_6[0])!=this._lastQuery)){
return;
}
if(!_6.length){
this.set("value","",_9||(_9===undefined&&!this.focused),this.textbox.value,null);
}else{
this.set("item",_6[0],_9);
}
},_openResultList:function(_a,_b,_c){
if(_b[this.searchAttr]!==this._lastQuery){
return;
}
this.inherited(arguments);
if(this.item===undefined){
this.validate(true);
}
},_getValueAttr:function(){
return this.valueNode.value;
},_getValueField:function(){
return "value";
},_setValueAttr:function(_d,_e,_f,_10){
if(!this._onChangeActive){
_e=null;
}
if(_10===undefined){
if(_d===null||_d===""){
_d="";
if(!_2.isString(_f)){
this._setDisplayedValueAttr(_f||"",_e);
return;
}
}
var _11=this;
this._lastQuery=_d;
_3(this.store.get(_d),function(_12){
_11._callbackSetLabel(_12?[_12]:[],undefined,undefined,_e);
});
}else{
this.valueNode.value=_d;
this.inherited(arguments);
}
},_setItemAttr:function(_13,_14,_15){
this.inherited(arguments);
this._lastDisplayedValue=this.textbox.value;
},_getDisplayQueryString:function(_16){
return _16.replace(/([\\\*\?])/g,"\\$1");
},_setDisplayedValueAttr:function(_17,_18){
if(_17==null){
_17="";
}
if(!this._created){
if(!("displayedValue" in this.params)){
return;
}
_18=false;
}
if(this.store){
this.closeDropDown();
var _19=_2.clone(this.query);
var qs=this._getDisplayQueryString(_17),q;
if(this.store._oldAPI){
q=qs;
}else{
q=this._patternToRegExp(qs);
q.toString=function(){
return qs;
};
}
this._lastQuery=_19[this.searchAttr]=q;
this.textbox.value=_17;
this._lastDisplayedValue=_17;
this._set("displayedValue",_17);
var _1a=this;
var _1b={queryOptions:{ignoreCase:this.ignoreCase,deep:true}};
_2.mixin(_1b,this.fetchProperties);
this._fetchHandle=this.store.query(_19,_1b);
_3(this._fetchHandle,function(_1c){
_1a._fetchHandle=null;
_1a._callbackSetLabel(_1c||[],_19,_1b,_18);
},function(err){
_1a._fetchHandle=null;
if(!_1a._cancelingQuery){
console.error("dijit.form.FilteringSelect: "+err.toString());
}
});
}
},undo:function(){
this.set("displayedValue",this._lastDisplayedValue);
}});
});