text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.activiti.engine.delegate.event.ActivitiEntityEvent (Flowable - Engine 5.23.0 API)</title>
<meta name="date" content="2017-03-27">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.activiti.engine.delegate.event.ActivitiEntityEvent

Packages that use ActivitiEntityEvent

Package
Description

org.activiti.engine.delegate.event

org.activiti.engine.delegate.event.impl

Uses of ActivitiEntityEvent in org.activiti.engine.delegate.event

Subinterfaces of ActivitiEntityEvent in org.activiti.engine.delegate.event

Modifier and Type
Interface and Description

interface
ActivitiEntityWithVariablesEvent

An ActivitiEntityEvent related to a single entity.

interface
ActivitiProcessStartedEvent

An ActivitiEvent related to start event being sent when activiti process
 instance is started.

Uses of ActivitiEntityEvent in org.activiti.engine.delegate.event.impl

Classes in org.activiti.engine.delegate.event.impl that implement ActivitiEntityEvent

Modifier and Type
Class and Description

class
ActivitiEntityEventImpl

Base class for all ActivitiEvent implementations, related to entities.

class
ActivitiEntityExceptionEventImpl

Base class for all ActivitiEvent implementations, represents an exception occured, related
 to an entity.

class
ActivitiEntityWithVariablesEventImpl

Base class for all ActivitiEntityEvent implementations, related to entities with variables.

class
ActivitiProcessStartedEventImpl

An ActivitiCancelledEvent implementation.

Methods in org.activiti.engine.delegate.event.impl that return ActivitiEntityEvent

Modifier and Type
Method and Description

static ActivitiEntityEvent
ActivitiEventBuilder.createEntityEvent(ActivitiEventType type,
                 Object entity)

static ActivitiEntityEvent
ActivitiEventBuilder.createEntityEvent(ActivitiEventType type,
                 Object entity,
                 String executionId,
                 String processInstanceId,
                 String processDefinitionId)

static ActivitiEntityEvent
ActivitiEventBuilder.createEntityExceptionEvent(ActivitiEventType type,
                          Object entity,
                          Throwable cause)

static ActivitiEntityEvent
ActivitiEventBuilder.createEntityExceptionEvent(ActivitiEventType type,
                          Object entity,
                          Throwable cause,
                          String executionId,
                          String processInstanceId,
                          String processDefinitionId)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2017 Flowable. All rights reserved.


text:
@implementation CCTwitterLoginManager

- (id)init
{
    self = [super init];
    if (self) {
        _accountStore = [[ACAccountStore alloc] init];
        _apiManager = [[TWAPIManager alloc] init];
    }
    return self;
}

- (void)dealloc
{
    self.delegate = nil;
}

- (void)obtainAccessToAccountsWithBlock:(void (^)(BOOL, NSError *))block
{
    ACAccountType *twitterType = [self.accountStore
                                  accountTypeWithAccountTypeIdentifier:
                                  ACAccountTypeIdentifierTwitter];

    ACAccountStoreRequestAccessCompletionHandler handler =
    ^(BOOL granted, NSError *error) {
        if (granted) {
            self.accounts = [_accountStore accountsWithAccountType:twitterType];
        }

        block(granted, error);
    };

    //  This method changed in iOS6.  If the new version isn't available, fall
    //  back to the original (which means that we're running on iOS5+).
    if ([self.accountStore respondsToSelector:@selector(requestAccessToAccountsWithType:options:completion:)]) {
        [self.accountStore requestAccessToAccountsWithType:twitterType
                                                   options:nil
                                                completion:handler];
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [self.accountStore requestAccessToAccountsWithType:twitterType
                                     withCompletionHandler:handler];
#pragma clang diagnostic pop
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    if (buttonIndex==(actionSheet.numberOfButtons-1)) {
        // Cancel
        if ([_delegate respondsToSelector:@selector(loginManagerCanceledConnectToTwitter:)]) {
            [_delegate loginManagerCanceledConnectToTwitter:self];
        }

    } else {
        ACAccount *account = self.accounts[buttonIndex];

        if ([_delegate respondsToSelector:@selector(loginManager:willConnectTwitterAccount:)]) {
            [_delegate loginManager:self willConnectTwitterAccount:account];
        }

        [self.apiManager
         performReverseAuthForAccount:account
         withHandler:^(NSData *responseData, NSError *error) {
             if (responseData) {
                 NSString *response = [[NSString alloc] initWithData:responseData
                                                            encoding:NSUTF8StringEncoding];

                 dispatch_async(dispatch_get_main_queue(), ^{
                     if ([self.delegate respondsToSelector:@selector(loginManager:connectedTwitterAccount:response:)]) {
                         [self.delegate loginManager:self
                             connectedTwitterAccount:account
                                            response:response];
                     }
                 });
             } else {
                 CCLog(@"Error!\n%@", [error localizedDescription]);
                 if ([self.delegate respondsToSelector:@selector(loginManager:failedToConnectedTwitterAccount:error:)]) {
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [self.delegate loginManager:self failedToConnectedTwitterAccount:account error:error];
                     });
                 }
             }
         }];
    }
}

- (BOOL)performTwitterReverseAuthInView:(UIView *)view;
{
    if ([TWAPIManager isLocalTwitterAccountAvailable]) {
        UIActionSheet *sheet = [[UIActionSheet alloc]
                                initWithTitle:@"Choose an Account"
                                delegate:self
                                cancelButtonTitle:nil
                                destructiveButtonTitle:nil
                                otherButtonTitles:nil];

        for (ACAccount *acct in self.accounts) {
            [sheet addButtonWithTitle:acct.username];
        }

        [sheet addButtonWithTitle:@"Cancel"];
        [sheet setDestructiveButtonIndex:[_accounts count]];
        [sheet showInView:view];
        return YES;
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"No Accounts"
                              message:@"Please configure a Twitter account on your device Settings."
                              delegate:nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        return NO;
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
package com.jmw.konfman.web;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jmock.Mock;
import org.jmock.MockObjectTestCase;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;

import com.jmw.konfman.model.Building;
import com.jmw.konfman.service.BuildingManager;
import com.jmw.konfman.web.BuildingFormController;

public class BuildingFormControllerTest extends MockObjectTestCase {
    private final Log log = LogFactory.getLog(BuildingFormControllerTest.class);
    private BuildingFormController c = new BuildingFormController();
    private MockHttpServletRequest request = null;
    private ModelAndView mv = null;
    private Building building = new Building();
    private Mock mockManager = null;

    protected void setUp() throws Exception {
        super.setUp();
        mockManager = new Mock(BuildingManager.class);

        // manually set properties (dependencies) on buildingFormController
        c.buildingManager = (BuildingManager) mockManager.proxy();
        c.setFormView("buildingForm");

        // set context with messages avoid NPE when controller calls
        // getMessageSourceAccessor().getMessage()
        StaticApplicationContext ctx = new StaticApplicationContext();
        Map<String, String> properties = new HashMap<String, String>();
        properties.put("basename", "messages");
        ctx.registerSingleton("messageSource", ResourceBundleMessageSource.class,
                              new MutablePropertyValues(properties));
        ctx.refresh();
        c.setApplicationContext(ctx);

        // setup building values
        building.setId(1L);
        building.setName("Matt");
        building.setTitle("Raible");
    }

    public void testEdit() throws Exception {
        log.debug("testing edit...");

        // set expected behavior on manager
        mockManager.expects(once()).method("getBuilding")
                   .will(returnValue(new Building()));

        request = new MockHttpServletRequest("GET", "/buildingform.html");
        request.addParameter("id", building.getId().toString());
        mv = c.handleRequest(request, new MockHttpServletResponse());
        assertEquals("buildingForm", mv.getViewName());

        // verify expectations
        mockManager.verify();
    }

    public void testSave() throws Exception {
        // set expected behavior on manager
        // called by formBackingObject()
        mockManager.expects(once()).method("getBuilding")
                   .will(returnValue(building));

        Building savedBuilding = building;
        savedBuilding.setName("Updated Name");
        // called by onSubmit()
        mockManager.expects(once()).method("saveBuilding")
                   .with(eq(savedBuilding));

        request = new MockHttpServletRequest("POST", "/buildingform.html");
        request.addParameter("id", building.getId().toString());
        request.addParameter("name", building.getName());
        request.addParameter("name", "Updated Name");
        mv = c.handleRequest(request, new MockHttpServletResponse());
        Errors errors = (Errors) mv.getModel().get(BindException.MODEL_KEY_PREFIX + "building");
        assertNull(errors);
        assertNotNull(request.getSession().getAttribute("message"));

        // verify expectations
        mockManager.verify();
    }

    public void testRemove() throws Exception {
        // set expected behavior on manager
        // called by formBackingObject()
        mockManager.expects(once()).method("getBuilding")
                   .will(returnValue(building));
        // called by onSubmit()
        mockManager.expects(once()).method("removeBuilding").with(eq("1"));

        request = new MockHttpServletRequest("POST", "/buildingform.html");
        request.addParameter("delete", "");
        request.addParameter("id", building.getId().toString());
        mv = c.handleRequest(request, new MockHttpServletResponse());
        assertNotNull(request.getSession().getAttribute("message"));

        // verify expectations
        mockManager.verify();
    }
}


text:
package com.yoya.net.rpc.impl;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yoya.rdf.router.IRequest;
import com.yoya.rdf.router.IRequestBuilder;
import com.yoya.rdf.router.impl.SimpleRequestBuilder;
import com.yoya.rdf.router.session.ISession;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.AttributeKey;

/**
 * Created by baihw on 16-6-2.
 *
 * json字符串转换为request对象。
 */
final class JsonStringToRequest extends MessageToMessageDecoder<String>{

	// 会话属性存储标志键
	private static final AttributeKey<String> _KEY_SID = AttributeKey.newInstance( "__SESSION_ID__" );

	@SuppressWarnings( "unchecked" )
	@Override
	protected void decode( ChannelHandlerContext ctx, String requestMsg, List<Object> out ) throws Exception{
		JSONObject jsonRoot = null;
		try{
			jsonRoot = JSON.parseObject( requestMsg );
		}catch( Exception e ){
			throw new RuntimeException( "非法的请求数据格式!error:".concat( e.getMessage() ) );
		}
		IRequestBuilder requestBuilder = new SimpleRequestBuilder();
		requestBuilder.setRequestId( jsonRoot.getString( "requestId" ) );
		requestBuilder.setPath( jsonRoot.getString( "path" ) );
		Map<String, String> headers = ( Map<String, String> )jsonRoot.get( "headers" );
		String sid = ctx.attr( _KEY_SID ).get();
		if( null == sid || 0 == ( sid = sid.trim() ).length() ){
			sid = UUID.randomUUID().toString().replace( "-", "" );
			ctx.attr( _KEY_SID ).set( sid );
		}
		requestBuilder.addHeaders( headers );
		requestBuilder.addHeader( ISession.KEY_SESSIONID, sid );
		Map<String, String> parameters = ( Map<String, String> )jsonRoot.get( "parameters" );
		requestBuilder.addParameters( parameters );
		IRequest request = requestBuilder.build();
		out.add( request );
	}

} // end class


text:
package com.luolc.emojirain.utils;

import java.util.Random;

/**
 * Utils for {@link Random}.
 *
 * @author LuoLiangchen
 * @since 2016/12/14
 */

public class Randoms {

    private static Random random = new Random();

    public static void setSeed(long seed) {
        random.setSeed(seed);
    }

    public static float floatStandard() {
        return random.nextFloat();
    }

    public static float floatAround(float mean, float delta) {
        return floatInRange(mean - delta, mean + delta);
    }

    public static float floatInRange(float left, float right) {
        return left + (right - left) * random.nextFloat();
    }

    public static double positiveGaussian() {
        return Math.abs(random.nextGaussian());
    }
}


text:
import org.junit.*;

import play.libs.WS;

import static play.test.Helpers.*;
import static org.fest.assertions.Assertions.*;

public class IntegrationTest {

    @Test
    public void test() {

        running(testServer(3333), new Runnable() {
            public void run() {
                assertThat(WS.url("http://localhost:3333").get().get(1000*60).getStatus()).isEqualTo(OK);
            }
        });
    }

}


text:
"""
Created on Wed Sep  4 11:33:32 2013

@author: xinghualu
"""
import cPickle
import numpy as np
from PyGibbCAMP import PyGibbCAMP

dataDir = 'ProcessedData/'

nodeFile = dataDir + "name.matching.csv"
dataMatrix = dataDir + "data.matrix.normalized.csv"
missDataMatrix = dataDir + "missDataMatrix.csv"
perturbMatrix = dataDir + "perturbation.table.csv"

nParents = 2
for alpha in np.arange(1., .5, -0.1, dtype=np.float):
    for i in range(5):
        pickleFileName = dataMatrix + ".chain" + str(i) + ".nParents" + str(nParents) +  ".alpha-" + str(alpha) + ".pickle"
        model = PyGibbCAMP(nodeFile = nodeFile, dataMatrixFile = dataMatrix, perturbMatrix = perturbMatrix, missingDataMatrix= missDataMatrix)
        model.trainGibbsEM(pickleDumpFile = pickleFileName, nParents = nParents, nChains = 1, alpha= alpha, maxIter = 500)

#cPickle.dump(model, open("final-model-09-06-13-alpha.05.nParent.4.pickle", 'wb'))


text:
aws s3api create-bucket \
   --bucket automatictester.co.uk-lightning-aws-lambda-tf-state \
   --acl private \
   --region eu-west-2 \
   --create-bucket-configuration LocationConstraint=eu-west-2

aws s3api put-public-access-block \
   --bucket automatictester.co.uk-lightning-aws-lambda-tf-state \
   --public-access-block-configuration '{"BlockPublicAcls":true,"IgnorePublicAcls":true,"BlockPublicPolicy":true,"RestrictPublicBuckets":true}'


text:
This npm package exports a single argument comparison function. The
function takes two [Reviewers Edition][reved] strings as inputs and
returns:

[reved]: https://npmjs.com/packages/reviewers-edition-parse

- `-1` if the first argument is an earlier Reviewers Edition than the
  second argument

- `0` if the first argument is equal to the second argument

- `1` if the first argument is a later Reviewers Edition than the
  second argument

This makes the function a suitable argument to `Array.prototype.sort`.

The following demonstration is also the test suite for the parser, using
Node.js' built-in `assert` module.

Here is a list of Reviewers Edition strings in ascending order.

```javascript
var sorted = [
  '1e1d', '1e2d', '1e', '1e2u1d', '1e2u', '1e2u1c1d', '1e2u1c2d',
  '3e', '3e1c', '3e2c', '3e3c', '3e2u', '3e11u',
  '4e1d', '4e2d', '4e', '4e99c1d', '4e100c',
  '5e1c', '5e2c', '5e1u', '5e2u', '5e3u1d',
  '1000e'
]
```

This test ensures that if we shuffle that list and resort it using the
comparison function, it ends up in sorted order again.

```javascript
require('assert').deepStrictEqual(
  require('array-shuffle')(sorted)
  .sort(require('reviewers-edition-compare')),
  sorted
)
```

This package is bundled with other functions for
creating and manipulating Reviewers Editions in
[reved](https://www.npmjs.com/packages/reved).


text:
import { connect } from 'react-redux';
import { addTimelineEvent, hideTimelineEvent } from './actions'
import Timeline from '../Timeline'

const filterEvents = (events) => {
  return events
    .sort((a, b) => { return b.createdAt - a.createdAt })
    .filter((event) => {return !event.hidden})
}

const mapStateToProps = (state) => {
  return {
    events: filterEvents([...state.get('events').values()])
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    hideTimelineEvent: (id) => {
      dispatch(hideTimelineEvent(id))
    },
    addTimelineEvent: () => {
      dispatch(addTimelineEvent({text: 'Hello!'}))
    }
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Timeline);


text:
#include <ctype.h>
#include "shell_ops.h"

void shell_op_cursor_vert_move(const struct shell *shell, s32_t delta)
{
	if (delta != 0) {
		shell_raw_fprintf(shell->fprintf_ctx, "\033[%d%c",
				  delta > 0 ? delta : -delta,
				  delta > 0 ? 'A' : 'B');
	}
}

void shell_op_cursor_horiz_move(const struct shell *shell, s32_t delta)
{
	if (delta != 0) {
		shell_raw_fprintf(shell->fprintf_ctx, "\033[%d%c",
				  delta > 0 ? delta : -delta,
				  delta > 0 ? 'C' : 'D');
	}
}

/* Function returns true if command length is equal to multiplicity of terminal
 * width.
 */
static inline bool full_line_cmd(const struct shell *shell)
{
	return ((shell->ctx->cmd_buff_len + shell_strlen(shell->ctx->prompt))
			% shell->ctx->vt100_ctx.cons.terminal_wid == 0U);
}

/* Function returns true if cursor is at beginning of an empty line. */
bool shell_cursor_in_empty_line(const struct shell *shell)
{
	return ((shell->ctx->cmd_buff_pos + shell_strlen(shell->ctx->prompt))
			% shell->ctx->vt100_ctx.cons.terminal_wid == 0U);
}

void shell_op_cond_next_line(const struct shell *shell)
{
	if (shell_cursor_in_empty_line(shell) || full_line_cmd(shell)) {
		cursor_next_line_move(shell);
	}
}

void shell_op_cursor_position_synchronize(const struct shell *shell)
{
	struct shell_multiline_cons *cons = &shell->ctx->vt100_ctx.cons;
	bool last_line;

	shell_multiline_data_calc(cons, shell->ctx->cmd_buff_pos,
				  shell->ctx->cmd_buff_len);
	last_line = (cons->cur_y == cons->cur_y_end);

	/* In case cursor reaches the bottom line of a terminal, it will
	 * be moved to the next line.
	 */
	if (full_line_cmd(shell)) {
		cursor_next_line_move(shell);
	}

	if (last_line) {
		shell_op_cursor_horiz_move(shell, cons->cur_x -
							       cons->cur_x_end);
	} else {
		shell_op_cursor_vert_move(shell, cons->cur_y_end - cons->cur_y);
		shell_op_cursor_horiz_move(shell, cons->cur_x -
							       cons->cur_x_end);
	}
}

void shell_op_cursor_move(const struct shell *shell, s16_t val)
{
	struct shell_multiline_cons *cons = &shell->ctx->vt100_ctx.cons;
	u16_t new_pos = shell->ctx->cmd_buff_pos + val;
	s32_t row_span;
	s32_t col_span;

	shell_multiline_data_calc(cons, shell->ctx->cmd_buff_pos,
				  shell->ctx->cmd_buff_len);

	/* Calculate the new cursor. */
	row_span = row_span_with_buffer_offsets_get(&shell->ctx->vt100_ctx.cons,
						    shell->ctx->cmd_buff_pos,
						    new_pos);
	col_span = column_span_with_buffer_offsets_get(
						    &shell->ctx->vt100_ctx.cons,
						    shell->ctx->cmd_buff_pos,
						    new_pos);

	shell_op_cursor_vert_move(shell, -row_span);
	shell_op_cursor_horiz_move(shell, col_span);
	shell->ctx->cmd_buff_pos = new_pos;
}

static u16_t shift_calc(const char *str, u16_t pos, u16_t len, s16_t sign)
{
	bool found = false;
	u16_t ret = 0U;
	u16_t idx;

	while (1) {
		idx = pos + ret * sign;
		if (((idx == 0U) && (sign < 0)) ||
		    ((idx == len) && (sign > 0))) {
			break;
		}
		if (isalnum((int)str[idx]) != 0) {
			found = true;
		} else {
			if (found) {
				break;
			}
		}
		ret++;
	}

	return ret;
}

void shell_op_cursor_word_move(const struct shell *shell, s16_t val)
{
	s16_t shift;
	s16_t sign;

	if (val < 0) {
		val = -val;
		sign = -1;
	} else {
		sign = 1;
	}

	while (val--) {
		shift = shift_calc(shell->ctx->cmd_buff,
				   shell->ctx->cmd_buff_pos,
				   shell->ctx->cmd_buff_len, sign);
		shell_op_cursor_move(shell, sign * shift);
	}
}

void shell_op_word_remove(const struct shell *shell)
{
	char *str = &shell->ctx->cmd_buff[shell->ctx->cmd_buff_pos - 1];
	char *str_start = &shell->ctx->cmd_buff[0];
	u16_t chars_to_delete;

	/* Line must not be empty and cursor must not be at 0 to continue. */
	if ((shell->ctx->cmd_buff_len == 0) ||
	    (shell->ctx->cmd_buff_pos == 0)) {
		return;
	}

	/* Start at the current position. */
	chars_to_delete = 0U;

	/* Look back for all spaces then for non-spaces. */
	while ((str >= str_start) && (*str == ' ')) {
		++chars_to_delete;
		--str;
	}

	while ((str >= str_start) && (*str != ' ')) {
		++chars_to_delete;
		--str;
	}

	/* Manage the buffer. */
	memmove(str + 1, str + 1 + chars_to_delete,
		shell->ctx->cmd_buff_len - chars_to_delete);
	shell->ctx->cmd_buff_len -= chars_to_delete;
	shell->ctx->cmd_buff[shell->ctx->cmd_buff_len] = '\0';

	/* Update display. */
	shell_op_cursor_move(shell, -chars_to_delete);
	cursor_save(shell);
	shell_internal_fprintf(shell, SHELL_NORMAL, "%s", str + 1);
	clear_eos(shell);
	cursor_restore(shell);
}

void shell_op_cursor_home_move(const struct shell *shell)
{
	shell_op_cursor_move(shell, -shell->ctx->cmd_buff_pos);
}

void shell_op_cursor_end_move(const struct shell *shell)
{
	shell_op_cursor_move(shell, shell->ctx->cmd_buff_len -
						shell->ctx->cmd_buff_pos);
}

void shell_op_left_arrow(const struct shell *shell)
{
	if (shell->ctx->cmd_buff_pos > 0) {
		shell_op_cursor_move(shell, -1);
	}
}

void shell_op_right_arrow(const struct shell *shell)
{
	if (shell->ctx->cmd_buff_pos < shell->ctx->cmd_buff_len) {
		shell_op_cursor_move(shell, 1);
	}
}

static void reprint_from_cursor(const struct shell *shell, u16_t diff,
				bool data_removed)
{
	/* Clear eos is needed only when newly printed command is shorter than
	 * previously printed command. This can happen when delete or backspace
	 * was called.
	 *
	 * Such condition is useful for Bluetooth devices to save number of
	 * bytes transmitted between terminal and device.
	 */
	if (data_removed) {
		clear_eos(shell);
	}

	shell_internal_fprintf(shell, SHELL_NORMAL, "%s",
		      &shell->ctx->cmd_buff[shell->ctx->cmd_buff_pos]);
	shell->ctx->cmd_buff_pos = shell->ctx->cmd_buff_len;

	if (full_line_cmd(shell)) {
		if (((data_removed) && (diff > 0)) || (!data_removed)) {
			cursor_next_line_move(shell);
		}
	}

	shell_op_cursor_move(shell, -diff);
}

static void data_insert(const struct shell *shell, const char *data, u16_t len)
{
	u16_t after = shell->ctx->cmd_buff_len - shell->ctx->cmd_buff_pos;
	char *curr_pos = &shell->ctx->cmd_buff[shell->ctx->cmd_buff_pos];

	if ((shell->ctx->cmd_buff_len + len) >= CONFIG_SHELL_CMD_BUFF_SIZE) {
		return;
	}

	memmove(curr_pos + len, curr_pos, after);
	memcpy(curr_pos, data, len);
	shell->ctx->cmd_buff_len += len;
	shell->ctx->cmd_buff[shell->ctx->cmd_buff_len] = '\0';

	if (!flag_echo_get(shell)) {
		shell->ctx->cmd_buff_pos += len;
		return;
	}

	reprint_from_cursor(shell, after, false);
}

static void char_replace(const struct shell *shell, char data)
{
	shell->ctx->cmd_buff[shell->ctx->cmd_buff_pos++] = data;

	if (!flag_echo_get(shell)) {
		return;
	}

	shell_raw_fprintf(shell->fprintf_ctx, "%c", data);
	if (shell_cursor_in_empty_line(shell)) {
		cursor_next_line_move(shell);
	}
}

void shell_op_char_insert(const struct shell *shell, char data)
{
	if (shell->ctx->internal.flags.insert_mode &&
		(shell->ctx->cmd_buff_len != shell->ctx->cmd_buff_pos)) {
		char_replace(shell, data);
	} else {
		data_insert(shell, &data, 1);
	}
}

void shell_op_char_backspace(const struct shell *shell)
{
	if ((shell->ctx->cmd_buff_len == 0) ||
	    (shell->ctx->cmd_buff_pos == 0)) {
		return;
	}

	shell_op_cursor_move(shell, -1);
	shell_op_char_delete(shell);
}

void shell_op_char_delete(const struct shell *shell)
{
	u16_t diff = shell->ctx->cmd_buff_len - shell->ctx->cmd_buff_pos;
	char *str = &shell->ctx->cmd_buff[shell->ctx->cmd_buff_pos];

	if (diff == 0U) {
		return;
	}

	memmove(str, str + 1, diff);
	--shell->ctx->cmd_buff_len;
	reprint_from_cursor(shell, --diff, true);
}

void shell_op_delete_from_cursor(const struct shell *shell)
{
	shell->ctx->cmd_buff_len = shell->ctx->cmd_buff_pos;
	shell->ctx->cmd_buff[shell->ctx->cmd_buff_pos] = '\0';

	clear_eos(shell);
}

void shell_op_completion_insert(const struct shell *shell,
				const char *compl,
				u16_t compl_len)
{
	data_insert(shell, compl, compl_len);
}

void shell_cmd_line_erase(const struct shell *shell)
{
	shell_multiline_data_calc(&shell->ctx->vt100_ctx.cons,
				  shell->ctx->cmd_buff_pos,
				  shell->ctx->cmd_buff_len);
	shell_op_cursor_horiz_move(shell,
				   -(shell->ctx->vt100_ctx.cons.cur_x - 1));
	shell_op_cursor_vert_move(shell, shell->ctx->vt100_ctx.cons.cur_y - 1);

	clear_eos(shell);
}

static void print_prompt(const struct shell *shell)
{
	shell_internal_fprintf(shell, SHELL_INFO, "%s", shell->ctx->prompt);
}

void shell_print_cmd(const struct shell *shell)
{
	shell_raw_fprintf(shell->fprintf_ctx, "%s", shell->ctx->cmd_buff);
}

void shell_print_prompt_and_cmd(const struct shell *shell)
{
	print_prompt(shell);

	if (flag_echo_get(shell)) {
		shell_print_cmd(shell);
		shell_op_cursor_position_synchronize(shell);
	}
}

static void shell_pend_on_txdone(const struct shell *shell)
{
	if (IS_ENABLED(CONFIG_MULTITHREADING) &&
	    (shell->ctx->state < SHELL_STATE_PANIC_MODE_ACTIVE)) {
		k_poll(&shell->ctx->events[SHELL_SIGNAL_TXDONE], 1, K_FOREVER);
		k_poll_signal_reset(&shell->ctx->signals[SHELL_SIGNAL_TXDONE]);
	} else {
		/* Blocking wait in case of bare metal. */
		while (!flag_tx_rdy_get(shell)) {
		}
		flag_tx_rdy_set(shell, false);
	}
}

void shell_write(const struct shell *shell, const void *data,
		 size_t length)
{
	__ASSERT_NO_MSG(shell && data);

	size_t offset = 0;
	size_t tmp_cnt;

	while (length) {
		int err = shell->iface->api->write(shell->iface,
				&((const u8_t *) data)[offset], length,
				&tmp_cnt);
		(void)err;
		__ASSERT_NO_MSG(err == 0);
		__ASSERT_NO_MSG(length >= tmp_cnt);
		offset += tmp_cnt;
		length -= tmp_cnt;
		if (tmp_cnt == 0 &&
		    (shell->ctx->state != SHELL_STATE_PANIC_MODE_ACTIVE)) {
			shell_pend_on_txdone(shell);
		}
	}
}

/* Function shall be only used by the fprintf module. */
void shell_print_stream(const void *user_ctx, const char *data,
			size_t data_len)
{
	shell_write((const struct shell *) user_ctx, data, data_len);
}

static void vt100_bgcolor_set(const struct shell *shell,
			      enum shell_vt100_color bgcolor)
{
	if ((bgcolor == SHELL_NORMAL) ||
	    (shell->ctx->vt100_ctx.col.bgcol == bgcolor)) {
		return;
	}

	/* -1 because default value is first in enum */
	u8_t cmd[] = SHELL_VT100_BGCOLOR(bgcolor - 1);

	shell->ctx->vt100_ctx.col.bgcol = bgcolor;
	shell_raw_fprintf(shell->fprintf_ctx, "%s", cmd);

}

void shell_vt100_color_set(const struct shell *shell,
			   enum shell_vt100_color color)
{

	if (shell->ctx->vt100_ctx.col.col == color) {
		return;
	}

	shell->ctx->vt100_ctx.col.col = color;

	if (color != SHELL_NORMAL) {

		u8_t cmd[] = SHELL_VT100_COLOR(color - 1);

		shell_raw_fprintf(shell->fprintf_ctx, "%s", cmd);
	} else {
		static const u8_t cmd[] = SHELL_VT100_MODESOFF;

		shell_raw_fprintf(shell->fprintf_ctx, "%s", cmd);
	}
}

void shell_vt100_colors_restore(const struct shell *shell,
				       const struct shell_vt100_colors *color)
{
	shell_vt100_color_set(shell, color->col);
	vt100_bgcolor_set(shell, color->bgcol);
}

void shell_internal_vfprintf(const struct shell *shell,
			     enum shell_vt100_color color, const char *fmt,
			     va_list args)
{
	if (IS_ENABLED(CONFIG_SHELL_VT100_COLORS) &&
	    shell->ctx->internal.flags.use_colors &&
	    (color != shell->ctx->vt100_ctx.col.col)) {
		struct shell_vt100_colors col;

		shell_vt100_colors_store(shell, &col);
		shell_vt100_color_set(shell, color);

		shell_fprintf_fmt(shell->fprintf_ctx, fmt, args);

		shell_vt100_colors_restore(shell, &col);
	} else {
		shell_fprintf_fmt(shell->fprintf_ctx, fmt, args);
	}
}

void shell_internal_fprintf(const struct shell *shell,
			    enum shell_vt100_color color,
			    const char *fmt, ...)
{
	__ASSERT_NO_MSG(shell);
	__ASSERT(!k_is_in_isr(), "Thread context required.");
	__ASSERT_NO_MSG(shell->ctx);
	__ASSERT_NO_MSG(shell->fprintf_ctx);
	__ASSERT_NO_MSG(fmt);

	va_list args = { 0 };

	va_start(args, fmt);
	shell_internal_vfprintf(shell, color, fmt, args);
	va_end(args);
}


text:
package org.killbill.billing.overdue.listener;

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.killbill.billing.BillingExceptionBase;
import org.killbill.billing.overdue.wrapper.OverdueWrapperFactory;
import org.killbill.billing.callcontext.InternalCallContext;

import com.google.inject.Inject;

public class OverdueDispatcher {

    Logger log = LoggerFactory.getLogger(OverdueDispatcher.class);

    private final OverdueWrapperFactory factory;

    @Inject
    public OverdueDispatcher(final OverdueWrapperFactory factory) {
        this.factory = factory;
    }

    public void processOverdueForAccount(final UUID accountId, final InternalCallContext context) {
        processOverdue(accountId, context);
    }

    public void clearOverdueForAccount(final UUID accountId, final InternalCallContext context) {
        clearOverdue(accountId, context);
    }

    private void processOverdue(final UUID accountId, final InternalCallContext context) {
        try {
            factory.createOverdueWrapperFor(accountId, context).refresh(context);
        } catch (BillingExceptionBase e) {
            log.error(String.format("Error processing Overdue for blockable %s", accountId), e);
        }
    }

    private void clearOverdue(final UUID accountId, final InternalCallContext context) {
        try {
            factory.createOverdueWrapperFor(accountId, context).clear(context);
        } catch (BillingExceptionBase e) {
            log.error(String.format("Error processing Overdue for blockable %s (type %s)", accountId), e);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Cindalnet.ExpertAkinator
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Presenter.PresenterMain().FormControl);
        }
    }
}


text:
package org.codehaus.plexus.util.cli.shell;

import org.codehaus.plexus.util.Os;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jason van Zyl
 * @version $Id$
 */
public class BourneShell
    extends Shell
{

    public BourneShell()
    {
        this(false);
    }

    public BourneShell( boolean isLoginShell )
    {
        setUnconditionalQuoting( true );
        setShellCommand( "/bin/sh" );
        setArgumentQuoteDelimiter( '\'' );
        setExecutableQuoteDelimiter( '\'' );
        setSingleQuotedArgumentEscaped( true );
        setSingleQuotedExecutableEscaped( false );
        setQuotedExecutableEnabled( true );
        setArgumentEscapePattern("'\\%s'");

        if ( isLoginShell )
        {
            addShellArg( "-l" );
        }
    }

    /** {@inheritDoc} */
    public String getExecutable()
    {
        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            return super.getExecutable();
        }

        return quoteOneItem( super.getOriginalExecutable(), true );
    }

    public List<String> getShellArgsList()
    {
        List<String> shellArgs = new ArrayList<String>();
        List<String> existingShellArgs = super.getShellArgsList();

        if ( ( existingShellArgs != null ) && !existingShellArgs.isEmpty() )
        {
            shellArgs.addAll( existingShellArgs );
        }

        shellArgs.add( "-c" );

        return shellArgs;
    }

    public String[] getShellArgs()
    {
        String[] shellArgs = super.getShellArgs();
        if ( shellArgs == null )
        {
            shellArgs = new String[0];
        }

        if ( ( shellArgs.length > 0 ) && !shellArgs[shellArgs.length - 1].equals( "-c" ) )
        {
            String[] newArgs = new String[shellArgs.length + 1];

            System.arraycopy( shellArgs, 0, newArgs, 0, shellArgs.length );
            newArgs[shellArgs.length] = "-c";

            shellArgs = newArgs;
        }

        return shellArgs;
    }

    protected String getExecutionPreamble()
    {
        if ( getWorkingDirectoryAsString() == null )
        {
            return null;
        }

        String dir = getWorkingDirectoryAsString();
        StringBuilder sb = new StringBuilder();
        sb.append( "cd " );

        sb.append( quoteOneItem( dir, false ) );
        sb.append( " && " );

        return sb.toString();
    }

    /**
     *
Unify quotes in a path for the Bourne Shell.

     *
     *

     * BourneShell.quoteOneItem(null)                       = null
     * BourneShell.quoteOneItem("")                         = ''
     * BourneShell.quoteOneItem("/test/quotedpath'abc")     = '/test/quotedpath'"'"'abc'
     * BourneShell.quoteOneItem("/test/quoted path'abc")    = '/test/quoted pat'"'"'habc'
     * BourneShell.quoteOneItem("/test/quotedpath\"abc")    = '/test/quotedpath"abc'
     * BourneShell.quoteOneItem("/test/quoted path\"abc")   = '/test/quoted path"abc'
     * BourneShell.quoteOneItem("/test/quotedpath\"'abc")   = '/test/quotedpath"'"'"'abc'
     * BourneShell.quoteOneItem("/test/quoted path\"'abc")  = '/test/quoted path"'"'"'abc'
     *

     *
     * @param path not null path.
     * @return the path unified correctly for the Bourne shell.
     */
    protected String quoteOneItem( String path, boolean isExecutable )
    {
        if ( path == null )
        {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        sb.append( "'" );
        sb.append( path.replace( "'", "'\"'\"'" ) );
        sb.append( "'" );

        return sb.toString();
    }
}


text:
exports.BattleScripts = {

  randomUbersTeam: function(side) {
		var keys = [];
		var pokemonLeft = 0;
		var pokemon = [];
		for (var i in this.data.FormatsData) {
			if (this.data.FormatsData[i].viableMoves && this.data.FormatsData[i].tier === "Uber") {
				keys.push(i);
			}
		}
		keys = keys.randomize();

		var typeCount = {};
		var typeComboCount = {};

		for (var i=0; i<keys.length && pokemonLeft < 6; i++) {
			var template = this.getTemplate(keys[i]);
			if (!template || !template.name || !template.types) continue;

			// Arceus formes have 1/17 the normal rate each (so Arceus as a whole has a normal rate)
			if (keys[i].substr(0,6) === 'arceus' && Math.random()*17>1) continue;

			// Limit 2 of any type
			var types = template.types;
			var skip = false;
			for (var t=0; t<types.length; t++) {
				if (typeCount[types[t]] > 1 && Math.random()*5>1) {
					skip = true;
					break;
				}
			}
			if (skip) continue;

			var set = this.randomUbersSet(template, i);

			// Limit 1 of any type combination
			var typeCombo = types.join();
			if (set.ability === 'Drought' || set.ability === 'Drizzle') {
				// Drought and Drizzle don't count towards the type combo limit
				typeCombo = set.ability;
			}
			if (typeCombo in typeComboCount) continue;

			// Okay, the set passes, add it to our team
			pokemon.push(set);

			pokemonLeft++;
			// Now that our Pokemon has passed all checks, we can increment the type counter:
			for (var t=0; t<types.length; t++) {
				if (types[t] in typeCount) {
					typeCount[types[t]]++;
				} else {
					typeCount[types[t]] = 1;
				}
			}
			typeComboCount[typeCombo] = 1;
		}
		return pokemon;
	},

	randomUbersSet: function(template, i) {
		if (i === undefined) i = 1;
		template = this.getTemplate(template);
		var name = template.name;

		if (!template.exists || (!template.viableMoves && !template.learnset)) {
			template = this.getTemplate('unown');

			var stack = 'Template incompatible with random battles: '+name;
			var fakeErr = {stack: stack};
			require('../crashlogger.js')(fakeErr, 'The randbat set generator');
		}

		var moveKeys = Object.keys(template.viableMoves || template.learnset).randomize();
		var moves = [];
		var ability = '';
		var item = '';
		var evs = {
			hp: 85,
			atk: 85,
			def: 85,
			spa: 85,
			spd: 85,
			spe: 85
		};
		var ivs = {
			hp: 31,
			atk: 31,
			def: 31,
			spa: 31,
			spd: 31,
			spe: 31
		};
		var hasStab = {};
		hasStab[template.types[0]] = true;
		var hasType = {};
		hasType[template.types[0]] = true;
		if (template.types[1]) {
			hasStab[template.types[1]] = true;
			hasType[template.types[1]] = true;
		}

		var damagingMoves = [];
		var damagingMoveIndex = {};
		var hasMove = {};
		var counter = {};
		var setupType = '';

		var j=0;
		do {
			// Choose next 4 moves from learnset/viable moves and add them to moves list:
			while (moves.length<4 && j<moveKeys.length) {
				var moveid = toId(moveKeys[j]);
				j++;
				if (moveid.substr(0,11) === 'hiddenpower') {
					if (!hasMove['hiddenpower']) {
						hasMove['hiddenpower'] = true;
					} else {
						continue;
					}
				}
				moves.push(moveid);
			}

			damagingMoves = [];
			damagingMoveIndex = {};
			hasMove = {};
			counter = {
				Physical: 0, Special: 0, Status: 0, damage: 0,
				technician: 0, skilllink: 0, contrary: 0, sheerforce: 0, ironfist: 0, adaptability: 0, hustle: 0,
				blaze: 0, overgrow: 0, swarm: 0, torrent: 0,
				recoil: 0, inaccurate: 0,
				physicalsetup: 0, specialsetup: 0, mixedsetup: 0
			};
			// Iterate through all moves we've chosen so far and keep track of what they do:
			for (var k=0; k<moves.length; k++) {
				var move = this.getMove(moves[k]);
				var moveid = move.id;
				// Keep track of all moves we have:
				hasMove[moveid] = true;
				if (move.damage || move.damageCallback) {
					// Moves that do a set amount of damage:
					counter['damage']++;
					damagingMoves.push(move);
					damagingMoveIndex[moveid] = k;
				} else {
					// Are Physical/Special/Status moves:
					counter[move.category]++;
				}
				// Moves that have a low base power:
				if (move.basePower && move.basePower <= 60) {
					counter['technician']++;
				}
				// Moves that hit multiple times:
				if (move.multihit && move.multihit[1] === 5) {
					counter['skilllink']++;
				}
				// Punching moves:
				if (move.isPunchAttack) {
					counter['ironfist']++;
				}
				// Recoil:
				if (move.recoil) {
					counter['recoil']++;
				}
				// Moves which have a base power:
				if (move.basePower || move.basePowerCallback) {
					if (hasType[move.type]) {
						counter['adaptability']++;
						// STAB:
						// Power Gem, Bounce, Aeroblast aren't considered STABs.
						// If they're in the Pokémon's movepool and are STAB, consider the Pokémon not to have that type as a STAB.
						if (moveid === 'aeroblast' || moveid === 'powergem' || moveid === 'bounce') hasStab[move.type] = false;
					}
					if (move.category === 'Physical') counter['hustle']++;
					if (move.type === 'Fire') counter['blaze']++;
					if (move.type === 'Grass') counter['overgrow']++;
					if (move.type === 'Bug') counter['swarm']++;
					if (move.type === 'Water') counter['torrent']++;
					// Make sure not to count Knock Off, Rapid Spin, etc.
					if (move.basePower > 20 || move.multihit || move.basePowerCallback) {
						damagingMoves.push(move);
						damagingMoveIndex[moveid] = k;
					}
				}
				// Moves with secondary effects:
				if (move.secondary) {
					if (move.secondary.chance < 50) {
						counter['sheerforce'] -= 5;
					} else {
						counter['sheerforce']++;
					}
				}
				// Moves with low accuracy:
				if (move.accuracy && move.accuracy !== true && move.accuracy < 90) {
					counter['inaccurate']++;
				}
				// Moves which drop stats:
				var ContraryMove = {
					leafstorm: 1, overheat: 1, closecombat: 1, superpower: 1, vcreate: 1
				};
				if (ContraryMove[moveid]) {
					counter['contrary']++;
				}
				// Moves that boost Attack:
				var PhysicalSetup = {
					swordsdance:1, dragondance:1, coil:1, bulkup:1, curse:1, bellydrum:1, shiftgear:1, honeclaws:1, howl:1
				};
				// Moves which boost Special Attack:
				var SpecialSetup = {
					nastyplot:1, tailglow:1, quiverdance:1, calmmind:1
				};
				// Moves which boost Attack AND Special Attack:
				var MixedSetup = {
					growth:1, workup:1, shellsmash:1
				};

				if (PhysicalSetup[moveid]) {
					counter['physicalsetup']++;
				}
				if (SpecialSetup[moveid]) {
					counter['specialsetup']++;
				}
				if (MixedSetup[moveid]) {
					counter['mixedsetup']++;
				}
			}

			// Choose a setup type:
			if (counter['mixedsetup']) {
				setupType = 'Mixed';
			} else if (counter['specialsetup']) {
				setupType = 'Special';
			} else if (counter['physicalsetup']) {
				setupType = 'Physical';
			}

			// Iterate through the moves again, this time to cull them:
			for (var k=0; k<moves.length; k++) {
				var moveid = moves[k];
				var move = this.getMove(moveid);
				var rejected = false;
				var isSetup = false;

				switch (moveid) {

				// not very useful without their supporting moves
				case 'sleeptalk':
					if (!hasMove['rest']) rejected = true;
					break;
				case 'endure':
					if (!hasMove['flail'] && !hasMove['endeavor'] && !hasMove['reversal']) rejected = true;
					break;
				case 'focuspunch':
					if (hasMove['sleeptalk'] || !hasMove['substitute']) rejected = true;
					break;
				case 'storedpower':
					if (!hasMove['cosmicpower'] && !setupType) rejected = true;
					break;
				case 'batonpass':
					if (!setupType && !hasMove['substitute'] && !hasMove['cosmicpower']) rejected = true;
					break;

				// we only need to set up once
				case 'swordsdance': case 'dragondance': case 'coil': case 'curse': case 'bulkup': case 'bellydrum':
					if (counter.Physical < 2 && !hasMove['batonpass']) rejected = true;
					if (setupType !== 'Physical' || counter['physicalsetup'] > 1) rejected = true;
					isSetup = true;
					break;
				case 'nastyplot': case 'tailglow': case 'quiverdance': case 'calmmind':
					if (counter.Special < 2 && !hasMove['batonpass']) rejected = true;
					if (setupType !== 'Special' || counter['specialsetup'] > 1) rejected = true;
					isSetup = true;
					break;
				case 'shellsmash': case 'growth': case 'workup':
					if (counter.Physical+counter.Special < 2 && !hasMove['batonpass']) rejected = true;
					if (setupType !== 'Mixed' || counter['mixedsetup'] > 1) rejected = true;
					isSetup = true;
					break;

				// bad after setup
				case 'seismictoss': case 'nightshade': case 'superfang':
					if (setupType) rejected = true;
					break;
				case 'knockoff': case 'perishsong': case 'magiccoat': case 'spikes':
					if (setupType) rejected = true;
					break;
				case 'uturn': case 'voltswitch':
					if (setupType || hasMove['agility'] || hasMove['rockpolish'] || hasMove['magnetrise']) rejected = true;
					break;
				case 'relicsong':
					if (setupType) rejected = true;
					break;
				case 'pursuit': case 'protect': case 'haze': case 'stealthrock':
					if (setupType || (hasMove['rest'] && hasMove['sleeptalk'])) rejected = true;
					break;
				case 'trick': case 'switcheroo':
					if (setupType || (hasMove['rest'] && hasMove['sleeptalk']) || hasMove['trickroom'] || hasMove['reflect'] || hasMove['lightscreen'] || hasMove['batonpass']) rejected = true;
					break;
				case 'dragontail': case 'circlethrow':
					if (hasMove['agility'] || hasMove['rockpolish']) rejected = true;
					if (hasMove['whirlwind'] || hasMove['roar'] || hasMove['encore']) rejected = true;
					break;

				// bit redundant to have both
				// Attacks:
				case 'flamethrower': case 'fierydance':
					if (hasMove['lavaplume'] || hasMove['overheat'] || hasMove['fireblast'] || hasMove['blueflare']) rejected = true;
					break;
				case 'overheat':
					if (setupType === 'Special' || hasMove['fireblast']) rejected = true;
					break;
				case 'icebeam':
					if (hasMove['blizzard']) rejected = true;
					break;
				case 'surf':
					if (hasMove['scald'] || hasMove['hydropump']) rejected = true;
					break;
				case 'hydropump':
					if (hasMove['razorshell'] || hasMove['scald']) rejected = true;
					break;
				case 'waterfall':
					if (hasMove['aquatail']) rejected = true;
					break;
				case 'airslash':
					if (hasMove['hurricane']) rejected = true;
					break;
				case 'bravebird': case 'pluck': case 'drillpeck':
					if (hasMove['acrobatics']) rejected = true;
					break;
				case 'solarbeam':
					if ((!hasMove['sunnyday'] && template.species !== 'Ninetales') || hasMove['gigadrain'] || hasMove['leafstorm']) rejected = true;
					break;
				case 'gigadrain':
					if ((!setupType && hasMove['leafstorm']) || hasMove['petaldance']) rejected = true;
					break;
				case 'leafstorm':
					if (setupType && hasMove['gigadrain']) rejected = true;
					break;
				case 'weatherball':
					if (!hasMove['sunnyday']) rejected = true;
					break;
				case 'firepunch':
					if (hasMove['flareblitz']) rejected = true;
					break;
				case 'bugbite':
					if (hasMove['uturn']) rejected = true;
					break;
				case 'crosschop': case 'hijumpkick':
					if (hasMove['closecombat']) rejected = true;
					break;
				case 'drainpunch':
					if (hasMove['closecombat'] || hasMove['hijumpkick'] || hasMove['crosschop']) rejected = true;
					break;
				case 'thunderbolt':
					if (hasMove['discharge'] || hasMove['voltswitch'] || hasMove['thunder']) rejected = true;
					break;
				case 'discharge': case 'thunder':
					if (hasMove['voltswitch']) rejected = true;
					break;
				case 'rockslide': case 'rockblast':
					if (hasMove['stoneedge'] || hasMove['headsmash']) rejected = true;
					break;
				case 'stoneedge':
					if (hasMove['headsmash']) rejected = true;
					break;
				case 'bonemerang': case 'earthpower':
					if (hasMove['earthquake']) rejected = true;
					break;
				case 'dragonclaw':
					if (hasMove['outrage'] || hasMove['dragontail']) rejected = true;
					break;
				case 'ancientpower':
					if (hasMove['paleowave']) rejected = true;
					break;
				case 'dragonpulse':
					if (hasMove['dracometeor']) rejected = true;
					break;
				case 'return':
					if (hasMove['bodyslam'] || hasMove['facade'] || hasMove['doubleedge'] || hasMove['tailslap']) rejected = true;
					break;
				case 'poisonjab':
					if (hasMove['gunkshot']) rejected = true;
					break;
				case 'psychic':
					if (hasMove['psyshock']) rejected = true;
					break;
				case 'fusionbolt':
					if (setupType && hasMove['boltstrike']) rejected = true;
					break;
				case 'boltstrike':
					if (!setupType && hasMove['fusionbolt']) rejected = true;
					break;

				// Status:
				case 'rest':
					if (hasMove['painsplit'] || hasMove['wish'] || hasMove['recover'] || hasMove['moonlight'] || hasMove['synthesis']) rejected = true;
					break;
				case 'softboiled': case 'roost':
					if (hasMove['wish'] || hasMove['recover']) rejected = true;
					break;
				case 'perishsong':
					if (hasMove['roar'] || hasMove['whirlwind'] || hasMove['haze']) rejected = true;
					break;
				case 'roar':
					// Whirlwind outclasses Roar because Soundproof
					if (hasMove['whirlwind'] || hasMove['dragontail'] || hasMove['haze'] || hasMove['circlethrow']) rejected = true;
					break;
				case 'substitute':
					if (hasMove['uturn'] || hasMove['voltswitch'] || hasMove['pursuit']) rejected = true;
					break;
				case 'fakeout':
					if (hasMove['trick'] || hasMove['switcheroo']) rejected = true;
					break;
				case 'encore':
					if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
					if (hasMove['whirlwind'] || hasMove['dragontail'] || hasMove['roar'] || hasMove['circlethrow']) rejected = true;
					break;
				case 'suckerpunch':
					if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
					break;
				case 'cottonguard':
					if (hasMove['reflect']) rejected = true;
					break;
				case 'lightscreen':
					if (hasMove['calmmind']) rejected = true;
					break;
				case 'rockpolish': case 'agility': case 'autotomize':
					if (!setupType && !hasMove['batonpass'] && hasMove['thunderwave']) rejected = true;
					if ((hasMove['stealthrock'] || hasMove['spikes'] || hasMove['toxicspikes']) && !hasMove['batonpass']) rejected = true;
					break;
				case 'thunderwave':
					if (setupType && (hasMove['rockpolish'] || hasMove['agility'])) rejected = true;
					if (hasMove['discharge'] || hasMove['trickroom']) rejected = true;
					if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
					break;
				case 'lavaplume':
					if (hasMove['willowisp']) rejected = true;
					break;
				}

				// These moves can be used even if we aren't setting up to use them:
				var SetupException = {
					overheat:1, dracometeor:1, leafstorm:1,
					voltswitch:1, uturn:1,
					suckerpunch:1, extremespeed:1
				};
				if (move.category === 'Special' && setupType === 'Physical' && !SetupException[move.id]) {
					rejected = true;
				}
				if (move.category === 'Physical' && setupType === 'Special' && !SetupException[move.id]) {
					rejected = true;
				}

				// This move doesn't satisfy our setup requirements:
				if (setupType === 'Physical' && move.category !== 'Physical' && counter['Physical'] < 2) {
					rejected = true;
				}
				if (setupType === 'Special' && move.category !== 'Special' && counter['Special'] < 2) {
					rejected = true;
				}

				// Remove rejected moves from the move list.
				if (rejected && j<moveKeys.length) {
					moves.splice(k,1);
					break;
				}

				// handle HP IVs
				if (move.id === 'hiddenpower') {
					var HPivs = this.getType(move.type).HPivs;
					for (var iv in HPivs) {
						ivs[iv] = HPivs[iv];
					}
				}
			}
			if (j<moveKeys.length && moves.length === 4) {
				// Move post-processing:
				if (damagingMoves.length===0) {
					// Have a 60% chance of rejecting one move at random:
					if (Math.random()*1.66>1) moves.splice(Math.floor(Math.random()*moves.length),1);
				} else if (damagingMoves.length===1) {
					// Night Shade, Seismic Toss, etc. don't count:
					if (!damagingMoves[0].damage) {
						damagingid = damagingMoves[0].id;
						damagingType = damagingMoves[0].type;
						var replace = false;
						if (damagingid === 'suckerpunch' || damagingid === 'counter' || damagingid === 'mirrorcoat') {
							// A player shouldn't be forced to rely upon the opponent attacking them to do damage.
							if (!hasMove['encore'] && Math.random()*2>1) replace = true;
						} else if (damagingid === 'focuspunch') {
							// Focus Punch is a bad idea without a sub:
							if (!hasMove['substitute']) replace = true;
						} else if (damagingid.substr(0,11) === 'hiddenpower' && damagingType === 'Ice') {
							// Mono-HP-Ice is never acceptable.
							replace = true;
						} else {
							// If you have one attack, and it's not STAB, Ice, Fire, or Ground, reject it.
							// Mono-Ice/Ground/Fire is only acceptable if the Pokémon's STABs are one of: Poison, Psychic, Steel, Normal, Grass.
							if (!hasStab[damagingType]) {
								if (damagingType === 'Ice' || damagingType === 'Fire' || damagingType === 'Ground') {
									if (!hasStab['Poison'] && !hasStab['Psychic'] && !hasStab['Steel'] && !hasStab['Normal'] && !hasStab['Grass']) {
										replace = true;
									}
								} else {
									replace = true;
								}
							}
						}
						if (replace) moves.splice(damagingMoveIndex[damagingid],1);
					}
				} else if (damagingMoves.length===2) {
					// If you have two attacks, neither is STAB, and the combo isn't Ice/Electric, Ghost/Fighting, or Dark/Fighting, reject one of them at random.
					var type1 = damagingMoves[0].type, type2 = damagingMoves[1].type;
					var typeCombo = [type1, type2].sort().join('/');
					var rejectCombo = true;
					if (!type1 in hasStab && !type2 in hasStab) {
						if (typeCombo === 'Electric/Ice' || typeCombo === 'Fighting/Ghost' || typeCombo === 'Dark/Fightng') rejectCombo = false;
					} else {
						rejectCombo = false;
					}
					if (rejectCombo) moves.splice(Math.floor(Math.random()*moves.length),1);
				} else {
					// If you have three or more attacks, and none of them are STAB, reject one of them at random.
					var isStab = false;
					for (var l=0; l<damagingMoves.length; l++) {
						if (hasStab[damagingMoves[l].type]) {
							isStab = true;
							break;
						}
					}
					if (!isStab) moves.splice(Math.floor(Math.random()*moves.length),1);
				}
			}
		} while (moves.length<4 && j<moveKeys.length);

		// any moveset modification goes here
		//moves[0] = 'Safeguard';
		{
			var abilities = [template.abilities['0']];
			if (template.abilities['1']) {
				abilities.push(template.abilities['1']);
			}
			if (template.abilities['DW']) {
				abilities.push(template.abilities['DW']);
			}
			abilities.sort(function(a,b){
				return this.getAbility(b).rating - this.getAbility(a).rating;
			}.bind(this));
			var ability0 = this.getAbility(abilities[0]);
			var ability1 = this.getAbility(abilities[1]);
			var ability = ability0.name;
			if (abilities[1]) {

				if (ability0.rating <= ability1.rating) {
					if (Math.random()*2<1) {
						ability = ability1.name;
					}
				} else if (ability0.rating - 0.6 <= ability1.rating) {
					if (Math.random()*3<1) {
						ability = ability1.name;
					}
				}

				var rejectAbility = false;
				if (ability === 'Blaze' && !counter['blaze']) {
					rejectAbility = true;
				}
				if (ability === 'Overgrow' && !counter['overgrow']) {
					rejectAbility = true;
				}
				if (ability === 'Swarm' && !counter['swarm']) {
					rejectAbility = true;
				}
				if (ability === 'Torrent' && !counter['torrent']) {
					rejectAbility = true;
				}
				if (ability === 'Contrary' && !counter['contrary']) {
					rejectAbility = true;
				}
				if (ability === 'Technician' && !counter['technician']) {
					rejectAbility = true;
				}
				if (ability === 'Skill Link' && !counter['skilllink']) {
					rejectAbility = true;
				}
				if (ability === 'Iron Fist' && !counter['ironfist']) {
					rejectAbility = true;
				}
				if (ability === 'Adaptability' && !counter['adaptability']) {
					rejectAbility = true;
				}
				if ((ability === 'Rock Head' || ability === 'Reckless') && !counter['recoil']) {
					rejectAbility = true;
				}
				if ((ability === 'No Guard' || ability === 'Compoundeyes') && !counter['inaccurate']) {
					rejectAbility = true;
				}
				if ((ability === 'Sheer Force' || ability === 'Serene Grace') && !counter['sheerforce']) {
					rejectAbility = true;
				}
				if (ability === 'Hustle' && !counter['hustle']) {
					rejectAbility = true;
				}
				if (ability === 'Simple' && !setupType && !hasMove['flamecharge'] && !hasMove['stockpile']) {
					rejectAbility = true;
				}
				if (ability === 'Prankster' && !counter['Status']) {
					rejectAbility = true;
				}
				if (ability === 'Defiant' && !counter['Physical'] && !hasMove['batonpass']) {
					rejectAbility = true;
				}
				// below 2 checks should be modified, when it becomes possible, to check if the team contains rain or sun
				if (ability === 'Swift Swim' && !hasMove['raindance']) {
					rejectAbility = true;
				}
				if (ability === 'Chlorophyll' && !hasMove['sunnyday']) {
					rejectAbility = true;
				}
				if (ability === 'Moody' && template.id !== 'bidoof') {
					rejectAbility = true;
				}
				if (ability === 'Lightningrod' && template.types.indexOf('Ground') >= 0) {
					rejectAbility = true;
				}

				if (rejectAbility) {
					if (ability === ability1.name) { // or not
						ability = ability0.name;
					} else if (ability1.rating > 0) { // only switch if the alternative doesn't suck
						ability = ability1.name;
					}
				}
				if ((abilities[0] === 'Guts' || abilities[1] === 'Guts' || abilities[2] === 'Guts') && ability !== 'Quick Feet' && hasMove['facade']) {
					ability = 'Guts';
				}
				if ((abilities[0] === 'Swift Swim' || abilities[1] === 'Swift Swim' || abilities[2] === 'Swift Swim') && hasMove['raindance']) {
					ability = 'Swift Swim';
				}
				if ((abilities[0] === 'Chlorophyll' || abilities[1] === 'Chlorophyll' || abilities[2] === 'Chlorophyll') && ability !== 'Solar Power' && hasMove['sunnyday']) {
					ability = 'Chlorophyll';
				}
				if (template.id === 'combee') {
					// it always gets Hustle but its only physical move is Endeavor, which loses accuracy
					ability = 'Honey Gather';
				}
			}

			if (hasMove['gyroball']) {
				ivs.spe = 0;
				//evs.atk += evs.spe;
				evs.spe = 0;
			} else if (hasMove['trickroom']) {
				ivs.spe = 0;
				//evs.hp += evs.spe;
				evs.spe = 0;
			}

			item = 'Leftovers';
			if (template.requiredItem) {
				item = template.requiredItem;

			// First, the extra high-priority items

			} else if (ability === 'Imposter') {
				item = 'Choice Scarf';
			} else if (ability === 'Wonder Guard') {
				item = 'Focus Sash';
			} else if (template.species === 'Unown') {
				item = 'Choice Specs';
			} else if ((template.species === 'Wynaut' || template.species === 'Wobbuffet') && hasMove['destinybond'] && Math.random()*2 > 1) {
				item = 'Custap Berry';
			} else if (hasMove['trick'] && hasMove['gyroball'] && (ability === 'Levitate' || hasType['Flying'])) {
				item = 'Macho Brace';
			} else if (hasMove['trick'] && hasMove['gyroball']) {
				item = 'Iron Ball';
			} else if (hasMove['trick'] || hasMove['switcheroo']) {
				var randomNum = Math.random()*2;
				if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum>1)) {
					item = 'Choice Band';
				} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum>1)) {
					item = 'Choice Specs';
				} else {
					item = 'Choice Scarf';
				}
			} else if (hasMove['rest'] && !hasMove['sleeptalk'] && ability !== 'Natural Cure' && ability !== 'Shed Skin') {
				item = 'Chesto Berry';
			} else if (hasMove['naturalgift']) {
				item = 'Liechi Berry';
			} else if (ability === 'Harvest') {
				item = 'Sitrus Berry';
			} else if (template.species === 'Cubone' || template.species === 'Marowak') {
				item = 'Thick Club';
			} else if (template.species === 'Pikachu') {
				item = 'Light Ball';
			} else if (template.species === 'Clamperl') {
				item = 'DeepSeaTooth';
			} else if (hasMove['reflect'] && hasMove['lightscreen']) {
				item = 'Light Clay';
			} else if (hasMove['acrobatics']) {
				item = 'Flying Gem';
			} else if (hasMove['shellsmash']) {
				item = 'White Herb';
			} else if (hasMove['facade'] || ability === 'Poison Heal' || ability === 'Toxic Boost') {
				item = 'Toxic Orb';
			} else if (hasMove['raindance']) {
				item = 'Damp Rock';
			} else if (hasMove['sunnyday']) {
				item = 'Heat Rock';
			} else if (hasMove['sandstorm']) { // lol
				item = 'Smooth Rock';
			} else if (hasMove['hail']) { // lol
				item = 'Icy Rock';
			} else if (ability === 'Magic Guard' && hasMove['psychoshift']) {
				item = 'Flame Orb';
			} else if (ability === 'Sheer Force' || ability === 'Magic Guard') {
				item = 'Life Orb';
			} else if (ability === 'Unburden' && (counter['Physical'] || counter['Special'])) {
				// Give Unburden mons a random Gem of the type of one of their damaging moves
				var shuffledMoves = moves.randomize();
				for (var m in shuffledMoves) {
					var move = this.getMove(shuffledMoves[m]);
					if (move.basePower || move.basePowerCallback) {
						item = move.type + ' Gem';
						break;
					}
				}
			} else if (ability === 'Guts') {
				if (hasMove['drainpunch']) {
					item = 'Flame Orb';
				} else {
					item = 'Toxic Orb';
				}
				if ((hasMove['return'] || hasMove['hyperfang']) && !hasMove['facade']) {
					// lol no
					for (var j=0; j<moves.length; j++) {
						if (moves[j] === 'Return' || moves[j] === 'HyperFang') {
							moves[j] = 'Facade';
							break;
						}
					}
				}
			} else if (ability === 'Marvel Scale' && hasMove['psychoshift']) {
				item = 'Flame Orb';
			} else if (hasMove['reflect'] || hasMove['lightscreen']) {
				// less priority than if you'd had both
				item = 'Light Clay';
			} else if (counter.Physical >= 4 && !hasMove['fakeout'] && !hasMove['suckerpunch'] && !hasMove['flamecharge'] && !hasMove['rapidspin']) {
				if (Math.random()*3 > 1) {
					item = 'Choice Band';
				} else {
					item = 'Expert Belt';
				}
			} else if (counter.Special >= 4) {
				if (Math.random()*3 > 1) {
					item = 'Choice Specs';
				} else {
					item = 'Expert Belt';
				}
			} else if (this.getEffectiveness('Ground', template) >= 2 && ability !== 'Levitate' && !hasMove['magnetrise']) {
				item = 'Air Balloon';
			} else if ((hasMove['eruption'] || hasMove['waterspout']) && !counter['Status']) {
				item = 'Choice Scarf';
			} else if (hasMove['substitute'] && hasMove['reversal']) {
				var shuffledMoves = moves.randomize();
				for (var m in shuffledMoves) {
					var move = this.getMove(shuffledMoves[m]);
					if (move.basePower || move.basePowerCallback) {
						item = move.type + ' Gem';
						break;
					}
				}
			} else if (hasMove['substitute'] || hasMove['detect'] || hasMove['protect'] || ability === 'Moody') {
				item = 'Leftovers';
			} else if ((hasMove['flail'] || hasMove['reversal']) && !hasMove['endure'] && ability !== 'Sturdy') {
				item = 'Focus Sash';
			} else if (ability === 'Iron Barbs') {
				// only Iron Barbs for now
				item = 'Rocky Helmet';
			} else if ((template.baseStats.hp+75)*(template.baseStats.def+template.baseStats.spd+175) > 60000 || template.species === 'Skarmory' || template.species === 'Forretress') {
				// skarmory and forretress get exceptions for their typing
				item = 'Leftovers';
			} else if (counter.Physical + counter.Special >= 3 && setupType) {
				item = 'Life Orb';
			} else if (counter.Special >= 3 && setupType) {
				item = 'Life Orb';
			} else if (counter.Physical + counter.Special >= 4) {
				item = 'Expert Belt';
			} else if (i===0 && ability !== 'Sturdy' && !counter['recoil']) {
				item = 'Focus Sash';
			} else if (hasMove['outrage']) {
				item = 'Lum Berry';

			// this is the "REALLY can't think of a good item" cutoff
			// why not always Leftovers? Because it's boring. :P

			} else if (hasType['Flying'] || ability === 'Levitate') {
				item = 'Leftovers';
			} else if (this.getEffectiveness('Ground', template) >= 1 && ability !== 'Levitate' && !hasMove['magnetrise']) {
				item = 'Air Balloon';
			} else if (hasType['Poison']) {
				item = 'Black Sludge';
			} else if (counter.Status <= 1) {
				item = 'Life Orb';
			} else {
				item = 'Leftovers';
			}

			if (item === 'Leftovers' && hasType['Poison']) {
				item = 'Black Sludge';
			}
		}

		var level = 100;

		return {
			name: name,
			moves: moves,
			ability: ability,
			evs: evs,
			ivs: ivs,
			item: item,
			level: level,
			shiny: (Math.random()*1024<=1)
		};
	},

};


text:
class SkBitmap;

namespace content {

class PermissionController;
class RenderFrameHostImpl;
class StoragePartitionImpl;

// This class was previously responsible for passing messages between
// BackgroundFetchJobControllers on ServiceWorkerContext's thread and
// BackgroundFetchDelegate on the UI thread. It may no longer be needed now that
// these are the same thread.
//
// Lives on the UI thread.
class CONTENT_EXPORT BackgroundFetchDelegateProxy
    : public BackgroundFetchDelegate::Client {
 public:
  using DispatchClickEventCallback =
      base::RepeatingCallback<void(const std::string& unique_id)>;
  using GetPermissionForOriginCallback =
      base::OnceCallback<void(BackgroundFetchPermission)>;

  class Controller {
   public:
    // Called when the given |request| has started fetching.
    virtual void DidStartRequest(
        const std::string& guid,
        std::unique_ptr<BackgroundFetchResponse> response) = 0;

    // Called when the request with the given |guid| has an update, meaning that
    // a total of |bytes_uploaded| of the request were uploaded, and a total of
    // |bytes_downloaded| are now available for the response.
    virtual void DidUpdateRequest(const std::string& guid,
                                  uint64_t bytes_uploaded,
                                  uint64_t bytes_downloaded) = 0;

    // Called when the request with the given |guid| has been completed.
    virtual void DidCompleteRequest(
        const std::string& guid,
        std::unique_ptr<BackgroundFetchResult> result) = 0;

    // Called when the delegate aborts a Background Fetch registration.
    virtual void AbortFromDelegate(
        blink::mojom::BackgroundFetchFailureReason) = 0;

    // Called by the delegate when the Download Service is requesting the
    // upload data.
    virtual void GetUploadData(
        const std::string& guid,
        BackgroundFetchDelegate::GetUploadDataCallback callback) = 0;

    virtual ~Controller() = default;
  };

  explicit BackgroundFetchDelegateProxy(
      base::WeakPtr<StoragePartitionImpl> storage_partition);

  BackgroundFetchDelegateProxy(const BackgroundFetchDelegateProxy&) = delete;
  BackgroundFetchDelegateProxy& operator=(const BackgroundFetchDelegateProxy&) =
      delete;

  ~BackgroundFetchDelegateProxy() override;

  // Set BackgroundFetchClick event dispatcher callback, which is a method on
  // the background fetch context.
  void SetClickEventDispatcher(DispatchClickEventCallback click_event_callback);

  // Gets size of the icon to display with the Background Fetch UI.
  void GetIconDisplaySize(
      BackgroundFetchDelegate::GetIconDisplaySizeCallback callback);

  // Checks if the provided origin has permission to start a Background Fetch.
  void GetPermissionForOrigin(const url::Origin& origin,
                              RenderProcessHost* rph,
                              RenderFrameHostImpl* rfh,
                              GetPermissionForOriginCallback callback);

  // Creates a new download grouping described by |fetch_description|. Further
  // downloads started by StartRequest will also use
  // |fetch_description->job_unique_id| so that a notification can be updated
  // with the current status. If the download was already started in a previous
  // browser session, then |fetch_description->current_guids| should contain the
  // GUIDs of in progress downloads, while completed downloads are recorded in
  // |fetch_description->completed_requests|.
  // Should only be called from the Controller.
  void CreateDownloadJob(
      base::WeakPtr<Controller> controller,
      std::unique_ptr<BackgroundFetchDescription> fetch_description);

  // Requests that the download manager start fetching |request|.
  // Should only be called from the Controller.
  void StartRequest(const std::string& job_unique_id,
                    const url::Origin& origin,
                    const scoped_refptr<BackgroundFetchRequestInfo>& request);

  // Updates the representation of this registration in the user interface to
  // match the given |title| or |icon|.
  // Called from the Controller.
  void UpdateUI(
      const std::string& job_unique_id,
      const absl::optional<std::string>& title,
      const absl::optional<SkBitmap>& icon,
      blink::mojom::BackgroundFetchRegistrationService::UpdateUICallback
          update_ui_callback);

  // Aborts in progress downloads for the given registration. Called from the
  // Controller after it is aborted. May occur even if all requests already
  // called OnDownloadComplete.
  void Abort(const std::string& job_unique_id);

  // Called when the fetch associated |job_unique_id| is completed.
  void MarkJobComplete(const std::string& job_unique_id);

  // Called when the shutdown flow has been initiated.
  void Shutdown();

 private:
  // BackgroundFetchDelegate::Client implementation:
  void OnJobCancelled(
      const std::string& job_unique_id,
      const std::string& download_guid,
      blink::mojom::BackgroundFetchFailureReason reason_to_abort) override;
  void OnDownloadComplete(
      const std::string& job_unique_id,
      const std::string& guid,
      std::unique_ptr<BackgroundFetchResult> result) override;
  void OnDownloadUpdated(const std::string& job_unique_id,
                         const std::string& guid,
                         uint64_t bytes_uploaded,
                         uint64_t bytes_downloaded) override;
  void OnDownloadStarted(
      const std::string& job_unique_id,
      const std::string& guid,
      std::unique_ptr<BackgroundFetchResponse> response) override;
  void OnUIActivated(const std::string& job_unique_id) override;
  void OnUIUpdated(const std::string& job_unique_id) override;
  void GetUploadData(
      const std::string& job_unique_id,
      const std::string& download_guid,
      BackgroundFetchDelegate::GetUploadDataCallback callback) override;

  void DidGetPermissionFromDownloadRequestLimiter(
      GetPermissionForOriginCallback callback,
      bool has_permission);

  BrowserContext* GetBrowserContext();

  BackgroundFetchDelegate* GetDelegate();

  PermissionController* GetPermissionController();

  // Map from unique job ids to the controller.
  std::map<std::string, base::WeakPtr<Controller>> controller_map_;

  // The callback to run after the UI information has been updated.
  std::map<std::string,
           blink::mojom::BackgroundFetchRegistrationService::UpdateUICallback>
      update_ui_callback_map_;

  DispatchClickEventCallback click_event_dispatcher_callback_;

  base::WeakPtr<StoragePartitionImpl> storage_partition_;

  SEQUENCE_CHECKER(sequence_checker_);

  base::WeakPtrFactory<BackgroundFetchDelegateProxy> weak_ptr_factory_{this};
};

}  // namespace content

#endif  // CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_DELEGATE_PROXY_H_


text:
package org.sitenv.referenceccda.test.other;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.sitenv.referenceccda.test.other.ReferenceValidationLogger.*;
import static org.sitenv.vocabularies.test.other.ValidationLogger.println;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.sitenv.referenceccda.dto.ValidationResultsDto;
import org.sitenv.referenceccda.dto.ValidationResultsMetaData;
import org.sitenv.referenceccda.validators.RefCCDAValidationResult;
import org.sitenv.referenceccda.validators.enums.ValidationResultType;
import org.sitenv.referenceccda.validators.schema.CCDATypes;
import org.sitenv.referenceccda.validators.schema.ReferenceCCDAValidator;
import org.sitenv.referenceccda.validators.schema.ValidationObjectives;
import org.sitenv.vocabularies.test.other.VocabularyValidationTester;
import org.xml.sax.SAXException;

public class ReferenceValidationTester extends VocabularyValidationTester {

	protected String handleServiceErrorTest(ValidationResultsDto results) {
		return handleServiceErrorTest(results, true);
	}

	protected static String handleServiceErrorTest(ValidationResultsDto results, boolean expectException) {
		boolean isServiceError = results.getResultsMetaData().isServiceError()
				&& (results.getResultsMetaData().getServiceErrorMessage() != null && !results
						.getResultsMetaData().getServiceErrorMessage()
						.isEmpty());
		if (isServiceError) {
			println("Service Error Message: "
					+ results.getResultsMetaData().getServiceErrorMessage());
		}
		if (expectException) {
			assertTrue(
					"The results are supposed to contain a service error since the snippet sent is invalid",
					isServiceError);
		} else {
			assertFalse(
					"The results are NOT supposed to contain a service error the XML file sent is valid",
					isServiceError);
		}
		return results.getResultsMetaData().getServiceErrorMessage();
	}

	protected static void handlePackageSwitchAndBackTestChoice(String firstTestCCDATypesType, String ccdaFileAsString) {
		List<RefCCDAValidationResult> results = validateDocumentAndReturnResults(ccdaFileAsString, firstTestCCDATypesType);
		assertTrue("MDHT Errors must be returned", hasMDHTValidationErrors(results));

		if (firstTestCCDATypesType.equals(CCDATypes.NON_SPECIFIC_CCDAR2)
				|| firstTestCCDATypesType.equals(CCDATypes.NON_SPECIFIC_CCDA)) {
			println("check original results to ensure there are NO MU2 results (or that there ARE MU2 Results if MU2 type");
			List<RefCCDAValidationResult> mdhtErrors = getMDHTErrorsFromResults(results);
			printResults(mdhtErrors, false, false, false);
			assertFalse("Since this was not an MU2 validation, Mu2consolPackage results should NOT have been returned",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2));
			println("run a new validation against MU2 and ensure there ARE MU2 results");
			mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults(
					ccdaFileAsString, CCDATypes.TRANSITIONS_OF_CARE_AMBULATORY_SUMMARY));
			printResults(mdhtErrors, false, false, false);
			assertTrue("Since this WAS an MU2 validation, Mu2consolPackage results SHOULD have been returned",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2));
			println("run a final validation against Consol and ensure there are NO MU2 results and that there ARE Consol Results");
			mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults(
					ccdaFileAsString, CCDATypes.NON_SPECIFIC_CCDA));
			printResults(mdhtErrors, false, false, false);
			assertFalse("Since this was a Consol validation (reverted from MU2), Mu2consolPackage results should NOT have been returned",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2));
			assertTrue("ConsolPackage results SHOULD have been returned since the document was tested against Consol and contains errors",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR21_OR_CCDAR11));
		} else if(firstTestCCDATypesType.equals(CCDATypes.TRANSITIONS_OF_CARE_AMBULATORY_SUMMARY)) {
			println("check original results to ensure there ARE MU2 results");
			List<RefCCDAValidationResult> mdhtErrors = getMDHTErrorsFromResults(results);
			printResults(mdhtErrors, false, false, false);
			assertTrue("Since this is an MU2 validation, Mu2consolPackage results SHOULD have been returned",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2));
			println("run a new validation against Consol and ensure there are NO MU2 results)");
			mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults(
					ccdaFileAsString, CCDATypes.NON_SPECIFIC_CCDAR2));
			printResults(mdhtErrors, false, false, false);
			assertFalse("Since this was NOT an MU2 validation, Mu2consolPackage results should NOT have been returned",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2));
			println("run a final validation against MU2 and ensure the MU2 results HAVE RETURNED");
			mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults(
					ccdaFileAsString, CCDATypes.TRANSITIONS_OF_CARE_INPATIENT_SUMMARY));
			printResults(mdhtErrors, false, false, false);
			assertTrue("Since this was an MU2 validation (reverted from Consol), Mu2consolPackage results SHOULD have been returned",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR11_MU2));
			assertTrue("ConsolPackage results SHOULD have been returned as well since MU2 inherits from consol "
					+ "and the doc tested has base level errors",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR21_OR_CCDAR11));
		} else if(firstTestCCDATypesType.equals(ValidationObjectives.Receiver.B8_DS4P_AMB_170_315)) {
			println("check original results to ensure there ARE DS4P results");
			List<RefCCDAValidationResult> mdhtErrors = getMDHTErrorsFromResults(results);
			printResults(mdhtErrors, false, false, false);
			assertTrue("Since this is a DS4P validation, CONTENTPROFILEPackage results SHOULD have been returned",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.DS4P));
			println("run a new validation against Consol and ensure there are NO DS4P results)");
			mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults(
					ccdaFileAsString, CCDATypes.NON_SPECIFIC_CCDAR2));
			printResults(mdhtErrors, false, false, false);
			assertFalse("Since this was NOT a DS4P validation, CONTENTPROFILEPackage results should NOT have been returned",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.DS4P));
			println("run a final validation against DS4P and ensure the DS4P results HAVE RETURNED");
			mdhtErrors = getMDHTErrorsFromResults(validateDocumentAndReturnResults(
					ccdaFileAsString, ValidationObjectives.Receiver.B8_DS4P_INP_170_315));
			printResults(mdhtErrors, false, false, false);
			assertTrue("Since this was a DS4P validation (reverted from Consol), CONTENTPROFILEPackage results SHOULD have been returned",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.DS4P));
			assertFalse("ConsolPackage results should NOT have been returned as well since DS4P does not inherit from consol "
					+ "but instead from CDA",
					mdhtErrorsHaveProvidedPackageResult(mdhtErrors, CCDATypes.CCDAR21_OR_CCDAR11));
		}
	}

	protected static void testDocumentTypeIdentificationAndObjectiveSentMetaDataUsingServiceNonVocab(ValidationResultsMetaData resultsMetaData,
			final String docTypeExpected, final String docTypeSet, final String objectiveExpected, final String objectiveSet) {

		assertTrue("The document type should be '" + docTypeExpected + "' but it is '" + docTypeSet + "' instead",
				docTypeSet.equals(docTypeExpected));
		println("docTypeExpected: " + docTypeExpected);
		println("docTypeSet: " + docTypeSet);

		assertTrue("The given validation objective should be '" + objectiveExpected + "' but it is '" + objectiveSet + "' instead",
				objectiveSet.equals(objectiveExpected));
	}

	protected static boolean hasMDHTValidationErrors(List<RefCCDAValidationResult> results) {
		return !getMDHTErrorsFromResults(results).isEmpty();
	}

	protected static List<RefCCDAValidationResult> getMDHTErrorsFromResults(List<RefCCDAValidationResult> results) {
		List<RefCCDAValidationResult> mdhtErrors = new ArrayList<RefCCDAValidationResult>();
		for (RefCCDAValidationResult result : results) {
			if (result.getType() == ValidationResultType.CCDA_MDHT_CONFORMANCE_ERROR) {
				mdhtErrors.add(result);
			}
		}
		return mdhtErrors;
	}

	protected static List<RefCCDAValidationResult> getSpecificIssuesFromResults(List<RefCCDAValidationResult> results,
			ValidationResultType infoType, ValidationResultType warnType, ValidationResultType errorType) {
		List<RefCCDAValidationResult> mdhtIssues = new ArrayList<RefCCDAValidationResult>();
		for (RefCCDAValidationResult result : results) {
			if (result.getType() == infoType || result.getType() == warnType || result.getType() == errorType) {
				mdhtIssues.add(result);
			}
		}
		return mdhtIssues;
	}

	protected static List<RefCCDAValidationResult> getMDHTIssuesFromResults(List<RefCCDAValidationResult> results) {
		return getSpecificIssuesFromResults(results, ValidationResultType.CCDA_MDHT_CONFORMANCE_INFO,
				ValidationResultType.CCDA_MDHT_CONFORMANCE_WARN, ValidationResultType.CCDA_MDHT_CONFORMANCE_ERROR);
	}

	protected static List<RefCCDAValidationResult> getVocabIssuesFromResults(List<RefCCDAValidationResult> results) {
		return getSpecificIssuesFromResults(results, ValidationResultType.CCDA_VOCAB_CONFORMANCE_INFO,
				ValidationResultType.CCDA_VOCAB_CONFORMANCE_WARN, ValidationResultType.CCDA_VOCAB_CONFORMANCE_ERROR);
	}

	protected static List<RefCCDAValidationResult> getContentIssuesFromResults(List<RefCCDAValidationResult> results) {
		return getSpecificIssuesFromResults(results, ValidationResultType.REF_CCDA_INFO,
				ValidationResultType.REF_CCDA_WARN, ValidationResultType.REF_CCDA_ERROR);
	}

	protected static boolean isIssueInResults(List<RefCCDAValidationResult> results, ValidationResultType typeExpected,
			String messageExpected) {
		boolean isErrorMessageFound = false;
		for (int i = 0; i < results.size(); i++) {
			RefCCDAValidationResult curResult = results.get(i);
//			println("curResult type: " + curResult.getType());
//			println("curResult description: " + curResult.getDescription());
			if (curResult.getType() == typeExpected && curResult.getDescription().contains(messageExpected)) {
				isErrorMessageFound = true;
				break;
			}
//			println("isErrorMessageFound: " + isErrorMessageFound);
		}
		return isErrorMessageFound;
	}

	protected static void failIfIssueIsInResults(List<RefCCDAValidationResult> results, ValidationResultType typeExpected,
			String messageExpected) {
		assertFalse("Did NOT expect to find Issue: '" + messageExpected + "' but instead DID return the issue",
				isIssueInResults(results, typeExpected, messageExpected));
	}

	protected static void passIfIssueIsInResults(List<RefCCDAValidationResult> results, ValidationResultType typeExpected,
			String messageExpected) {
		assertTrue("Expected Issue: '" + messageExpected + "' but instead did NOT return the issue",
				isIssueInResults(results, typeExpected, messageExpected));
	}

	protected static int countSpecifcResults(List<RefCCDAValidationResult> results, ValidationResultType type) {
		int issueTypeCount = 0;
		for(RefCCDAValidationResult result : results) {
			if (result.getType() == type) {
				issueTypeCount++;
			}
		}
		return issueTypeCount;
	}

	private static boolean mdhtErrorsHaveProvidedPackageResult(List<RefCCDAValidationResult> mdhtErrors, String ccdaTypeToCheckFor) {
		boolean hasMu2 = false, hasConsol = false, hasDs4p = false;
		for(RefCCDAValidationResult mdhtError :  mdhtErrors) {
			if(mdhtError.getDescription().contains("Mu2consol")) {
				hasMu2 = true;
			}
			if(mdhtError.getDescription().contains("Consol")) {
				hasConsol = true;
			}
			if(mdhtError.getDescription().contains("CONTENTPROFILE")) {
				hasDs4p = true;
			}
		}
		if(ccdaTypeToCheckFor.equals(CCDATypes.CCDAR11_MU2)) {
			return hasMu2;
		} else if(ccdaTypeToCheckFor.equals(CCDATypes.CCDAR21_OR_CCDAR11)) {
			return hasConsol;
		} else if(ccdaTypeToCheckFor.equals(CCDATypes.DS4P)) {
			return hasDs4p;
		}
		return false;
	}

	protected static String convertCCDAFileToString(URI ccdaFileURL) {
		StringBuilder sb = new StringBuilder();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(ccdaFileURL.getPath()));
			String sCurrentLine = "";
			while ((sCurrentLine = br.readLine()) != null) {
				sb.append(sCurrentLine);
			}
		} catch (Exception e) {
			println(e.toString());
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				if(logResults) e.printStackTrace();
			}
		}
		return sb.toString();
	}

	protected static ArrayList<RefCCDAValidationResult> validateDocumentAndReturnResults(String ccdaFileAsString) {
		return validateDocumentAndReturnResults(ccdaFileAsString, CCDATypes.NON_SPECIFIC_CCDAR2);
	}

	protected static ArrayList<RefCCDAValidationResult> validateDocumentAndReturnResults(String ccdaFileAsString,
			String validationObjective) {
		ReferenceCCDAValidator referenceCCDAValidator = new ReferenceCCDAValidator();
		ArrayList<RefCCDAValidationResult> results = null;
		try {
			results = referenceCCDAValidator.validateFile(validationObjective, "Test",
					ccdaFileAsString);
		} catch (SAXException e) {
			if(logResults) e.printStackTrace();
		} catch (Exception e) {
			if(logResults) e.printStackTrace();
		}
		return results;
	}

	protected boolean mdhtResultsHaveSchemaError(
			List<RefCCDAValidationResult> mdhtResults) {
		for (RefCCDAValidationResult result : mdhtResults) {
			if (result.isSchemaError()) {
				return true;
			}
		}
		return false;
	}

}


text:
using System.Collections.Generic;

namespace DotVVM.Framework.Compilation.Static
{
    internal class CompilationReport
    {
        private const string UnknownError = "An unknown error occurred. This is likely a bug in the compiler.";

        public CompilationReport(string viewPath, int line, int column, string message)
        {
            ViewPath = viewPath;
            Line = line;
            Column = column;
            Message = message;
        }

        public CompilationReport(string viewPath, DotvvmCompilationException exception)
            : this(
                viewPath: viewPath,
                line: exception.LineNumber ?? -1,
                column: exception.ColumnNumber ?? -1,
                message: !string.IsNullOrEmpty(exception.Message)
                    ? exception.Message
                    : exception.InnerException?.ToString() ?? UnknownError)
        {
        }

        public string Message { get; }

        public int Line { get; }

        public int Column { get; }

        public string ViewPath { get; }

        public static bool operator ==(CompilationReport? left, CompilationReport? right)
        {
            if (left is null)
            {
                return right is null;
            }

            return left.Equals(right);
        }

        public static bool operator !=(CompilationReport? left, CompilationReport? right)
        {
            return !(left == right);
        }

        public override bool Equals(object? obj)
        {
            return obj is CompilationReport report
                && Message == report.Message
                && Line == report.Line
                && Column == report.Column
                && ViewPath == report.ViewPath;
        }

        public override int GetHashCode()
        {
            var hashCode = -712964631;
            hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Message);
            hashCode = hashCode * -1521134295 + Line.GetHashCode();
            hashCode = hashCode * -1521134295 + Column.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(ViewPath);
            return hashCode;
        }
    }
}


text:
import Iterable from '../iteration/iterable';
import Iterator from '../iteration/iterator';
import HashTable from '../collections/hash-table';
import assertNotNull from '../utils/assert-not-null';
import $iterator from '../iteration/iterator-factory';

export default function unionIterator(first, second, comparer) {
    assertNotNull(first);
    assertNotNull(second);

    return new Iterable(function () {
        var table = new HashTable(comparer),
            it1 = $iterator(first),
            it2 = $iterator(second),
            next;

        return new Iterator(function () {
            while (!(next = it1.next()).done || !(next = it2.next()).done) {
                if (table.add(next.value)) {
                    return {
                        value: next.value,
                        done: false
                    };
                }
            }

            return {
                done: true
            };
        });
    });
}