text:
package com.gemstone.gemfire.internal.redis.executor.string;

import java.util.List;

import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.internal.redis.ByteArrayWrapper;
import com.gemstone.gemfire.internal.redis.Command;
import com.gemstone.gemfire.internal.redis.Coder;
import com.gemstone.gemfire.internal.redis.ExecutionHandlerContext;
import com.gemstone.gemfire.internal.redis.RedisConstants.ArityDef;

public class AppendExecutor extends StringExecutor {

  private final int VALUE_INDEX = 2;

  @Override
  public void executeCommand(Command command, ExecutionHandlerContext context) {
    List<byte[]> commandElems = command.getProcessedCommand();

    Region<ByteArrayWrapper, ByteArrayWrapper> r = context.getRegionProvider().getStringsRegion();;

    if (commandElems.size() < 3) {
      command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.APPEND));
      return;
    }

    ByteArrayWrapper key = command.getKey();
    checkAndSetDataType(key, context);
    ByteArrayWrapper string = r.get(key);

    byte[] stringByteArray = commandElems.get(VALUE_INDEX);
    if (string == null) {
      r.put(key, new ByteArrayWrapper(stringByteArray));
      command.setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), stringByteArray.length));
    } else {
      byte[] newValue = concatArrays(string.toBytes(), stringByteArray);
      string.setBytes(newValue);
      r.put(key, string);
      command.setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), newValue.length));
    }

  }

  private byte[] concatArrays(byte[] o, byte[] n) {
    int oLen = o.length;
    int nLen = n.length;
    byte[] combined = new byte[oLen+nLen];
    System.arraycopy(o, 0, combined, 0, oLen);
    System.arraycopy(n, 0, combined, oLen, nLen);
    return combined;
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class NoOpCameraControls : ICameraControls
{
    public List<CameraAction> GetActions()
    {
        return new List<CameraAction>();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import css from "styled-jsx/css";

const TOP_OFFSET = "20px";
export const modalCss = css`
  /* completions styles */
  dialog {
    // We don't have a reset, so we need to reset some things on dialog.
    width: initial;
    height: initial;
    margin: initial;
    background: initial;
  }
  .modal--overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.25);
    z-index: 10000;
  }
  .modal--content {
    align-items: stretch;
    background-color: var(--theme-app-bg);
    color: var(--theme-app-fg);
    border-radius: 4px;
    border: var(--theme-app-border) 1px solid;
    box-sizing: border-box;
    display: flex;
    flex-flow: column nowrap;
    justify-content: flex-start;
    left: 400px;
    max-height: calc(100vh - ${TOP_OFFSET} * 2);
    outline: none;
    overflow: auto;
    padding: 20px;
    position: absolute;
    right: 400px;
    top: ${TOP_OFFSET};
    z-index: 10000;
  }
  @media only screen and (max-width: 1500px) {
    .modal--content {
      left: 200px;
      right: 200px;
    }
  }
  @media only screen and (max-width: 1000px) {
    .modal--content {
      left: 100px;
      right: 100px;
    }
  }
  @media only screen and (max-width: 600px) {
    .modal--content {
      left: 40px;
      right: 40px;
    }
  }
  .modal--content--header {
    padding: 0 20px 20px 20px;
    border-bottom: var(--theme-app-border) 1px solid;
  }
  .modal--content--body {
    padding: 20px;
  }
  .modal--content--body--field {
    font-weight: bold;
    margin-right: 5px;
  }
  .modal--content--body--value {
    font-family: monospace;
  }
`;


text:
<!DOCTYPE HTML>
<title>Test for clipping of border-radius</title>
<style>
canvas {
  margin: 18px 19px 21px 25px;
  /* border + padding: 1px 2px 4px 8px */

  /* Horizontal: TL TR BR BL / Vertical: TL TR BR BL */
  /* border-radius: 25px 17px 14px 18px / 12px 15px 18px 17px; */
  border-radius: 17px 15px 12px 10px / 11px 14px 14px 13px;
}
</style>
<canvas id="canvas" height="100" width="200"></canvas>
<script>
var canvas = document.getElementById("canvas");
var cx = canvas.getContext("2d");
cx.fillStyle="lime";
cx.fillRect(0, 0, 200, 100);
</script>


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace WuWen.Infrastructure.Data
{
    public static class ISqlBuilderExtensions
    {
        public static int ExecuteNonQuery(this IAdoProvider col, string connectionString, ISqlBuilder sqlBuilder)
        {
            Tuple<string, IEnumerable<IDataParameter>> tuple = sqlBuilder.Build();
            return col.ExecuteNonQuery(connectionString, tuple.Item1, tuple.Item2.ToArray());
        }
        public static void ExecuteReader(this IAdoProvider col, string connectionString, ISqlBuilder sqlBuilder, Action<IDataReader> readCallback)
        {
            Tuple<string, IEnumerable<IDataParameter>> tuple = sqlBuilder.Build();
            col.ExecuteReader(readCallback, connectionString, tuple.Item1, (tuple.Item2 == null) ? new IDataParameter[0] : tuple.Item2.ToArray());
        }
        public static IEnumerable<TEntity> ExecuteReader<TEntity>(this IAdoProvider col, string connectionString, ISqlBuilder sqlBuilder, Func<IDataReader, TEntity> buildEntity)
        {
            Tuple<string, IEnumerable<IDataParameter>> tuple = sqlBuilder.Build();
            return col.ExecuteReader(buildEntity, connectionString, tuple.Item1, tuple.Item2.ToArray());
        }
        public static T ExecuteScalar<T>(this IAdoProvider col, string connectionString, ISqlBuilder sqlBuilder)
        {
            Tuple<string, IEnumerable<IDataParameter>> tuple = sqlBuilder.Build();
            return col.ExecuteScalar<T>(connectionString, tuple.Item1, tuple.Item2.ToArray());
        }
    }
}


text:
package org.toxos.processassertions.flowable;

import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Task;
import org.flowable.engine.test.Deployment;
import org.junit.Test;
import org.toxos.processassertions.flowable.integration.configuration.AbstractProcessAssertTest;
import org.toxos.processassertions.integration.common.process.MultiInstanceProcessConstant;
import org.toxos.processassertions.integration.common.process.SingleUserTaskProcessConstant;
import org.toxos.processassertions.integration.common.process.TwoUserTasksProcessConstant;

import java.util.List;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.fail;
import static org.toxos.processassertions.api.ProcessAssert.assertProcessInActivity;
import static org.toxos.processassertions.api.internal.Assert.assertThat;

/**
 * Tests for assertions that test a process is in an activity.
 *
 * @author Tiese Barrell
 *
 */
public class ProcessIsInActivityAssertionsTest extends AbstractProcessAssertTest {

    @Test
    @Deployment(resources = BPMN_SINGLE_USER_TASK)
    public void assertProcessInActivitySuccess() throws Exception {
        final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SingleUserTaskProcessConstant.PROCESS_KEY.getValue());
        assertProcessInActivity(processInstance.getProcessInstanceId(), SingleUserTaskProcessConstant.USER_TASK_ACTIVITY_ID.getValue());
    }

    @Test
    @Deployment(resources = BPMN_MULTI_INSTANCE)
    public void assertProcessInActivityForMultipleExecutions() throws Exception {
        final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(MultiInstanceProcessConstant.PROCESS_KEY.getValue());
        assertProcessInActivity(processInstance.getProcessInstanceId(), MultiInstanceProcessConstant.USER_TASK_ACTIVITY_ID.getValue());

        final List<Task> tasks = taskService.createTaskQuery()
                .taskDefinitionKey(MultiInstanceProcessConstant.USER_TASK_ACTIVITY_ID.getValue()).list();
        assertThat(tasks.size(), is(3));

        // End task 1
        taskService.complete(tasks.get(0).getId());
        assertProcessInActivity(processInstance.getProcessInstanceId(), MultiInstanceProcessConstant.USER_TASK_ACTIVITY_ID.getValue());

        // End task 2
        taskService.complete(tasks.get(1).getId());
        assertProcessInActivity(processInstance.getProcessInstanceId(), MultiInstanceProcessConstant.USER_TASK_ACTIVITY_ID.getValue());

        // End task 3
        taskService.complete(tasks.get(2).getId());
        try {
            assertProcessInActivity(processInstance.getProcessInstanceId(), MultiInstanceProcessConstant.USER_TASK_ACTIVITY_ID.getValue());
            fail("Expected AssertionError for final task");
        } catch (AssertionError ae) {
            // no-op, expected for final task
        }
    }

    @Test(expected = AssertionError.class)
    @Deployment(resources = BPMN_SINGLE_USER_TASK)
    public void assertProcessInActivityFailureForOtherActivityId() throws Exception {
        final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SingleUserTaskProcessConstant.PROCESS_KEY.getValue());
        assertProcessInActivity(processInstance.getProcessInstanceId(), TwoUserTasksProcessConstant.USER_TASK_2_ACTIVITY_ID.getValue());
    }

    @Test(expected = AssertionError.class)
    @Deployment(resources = BPMN_SINGLE_USER_TASK)
    public void assertProcessInActivityFailureForOtherProcessInstance() throws Exception {
        final ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey(SingleUserTaskProcessConstant.PROCESS_KEY.getValue());
        // Move on to end process 1
        final Task task = taskService.createTaskQuery().taskDefinitionKey(SingleUserTaskProcessConstant.USER_TASK_ACTIVITY_ID.getValue())
                .singleResult();
        taskService.complete(task.getId());

        // start another instance
        final ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey(SingleUserTaskProcessConstant.PROCESS_KEY.getValue());
        assertProcessInActivity(processInstance2.getProcessInstanceId(), SingleUserTaskProcessConstant.USER_TASK_ACTIVITY_ID.getValue());

        assertProcessInActivity(processInstance1.getProcessInstanceId(), SingleUserTaskProcessConstant.USER_TASK_ACTIVITY_ID.getValue());
    }

    @Test(expected = AssertionError.class)
    @Deployment(resources = BPMN_SINGLE_USER_TASK)
    public void assertProcessInActivityFailureForSuspendedProcessInstance() throws Exception {
        final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SingleUserTaskProcessConstant.PROCESS_KEY.getValue());
        assertProcessInActivity(processInstance.getProcessInstanceId(), SingleUserTaskProcessConstant.USER_TASK_ACTIVITY_ID.getValue());

        // suspend the process instance
        runtimeService.suspendProcessInstanceById(processInstance.getProcessInstanceId());
        assertProcessInActivity(processInstance.getProcessInstanceId(), SingleUserTaskProcessConstant.USER_TASK_ACTIVITY_ID.getValue());
    }

    @Test(expected = AssertionError.class)
    @Deployment(resources = BPMN_SINGLE_USER_TASK)
    public void assertProcessInActivityFailureForEndedProcessInstance() throws Exception {
        final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SingleUserTaskProcessConstant.PROCESS_KEY.getValue());

        // Move on to end process
        final Task task = taskService.createTaskQuery().taskDefinitionKey(SingleUserTaskProcessConstant.USER_TASK_ACTIVITY_ID.getValue())
                .singleResult();
        taskService.complete(task.getId());

        assertProcessInActivity(processInstance.getProcessInstanceId(), SingleUserTaskProcessConstant.USER_TASK_ACTIVITY_ID.getValue());
    }

    @Test(expected = AssertionError.class)
    @Deployment(resources = BPMN_SINGLE_USER_TASK)
    public void assertProcessInActivityFailureForActivityThatNeverExisted() throws Exception {
        final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SingleUserTaskProcessConstant.PROCESS_KEY.getValue());

        // Move on to end process
        final Task task = taskService.createTaskQuery().taskDefinitionKey(SingleUserTaskProcessConstant.USER_TASK_ACTIVITY_ID.getValue())
                .singleResult();
        taskService.complete(task.getId());

        assertProcessInActivity(processInstance.getProcessInstanceId(), TwoUserTasksProcessConstant.USER_TASK_2_ACTIVITY_ID.getValue());
    }

}


text:
//
//  customTextField.m
//  customTextField
//
//  Created by Mittal J. Banker on 12/05/16.
//  Copyright © 2016 digicorp. All rights reserved.
//

#import "customTextField.h"
int maxlength;
@implementation customTextField

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];

    if (self) {
        self.delegate = self;
    }

    return self;
}

- (id)initWithCoder:(NSCoder*)aDecoder
{
    if(self = [super initWithCoder:aDecoder]) {
        // Do something

    }
    return self;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    NSCharacterSet *blockedCharacters = [[NSCharacterSet alphanumericCharacterSet] invertedSet] ;

    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    /* for backspace */
    if([string length]==0){
        return YES;
    }
    if (newLength > maxlength) {
        if([string length] > maxlength){
            textField.text = [string substringToIndex:maxlength];
        }
        return NO;
    }
    if(self.isAlphanumeric){
        return ([string rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);

    }
    return true;
}

- (void)drawRect:(CGRect)rect {
    self.backgroundColor = self.fillColor;
    maxlength = self.maxLength;
}

-(BOOL)isAlphaNumericOnly:(NSString *)input
{
    NSString *alphaNum = @"[a-zA-Z0-9]+";
    NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", alphaNum];

    return [regexTest evaluateWithObject:input];
}
@end


text:
@interface RDMGroup (Custom)

-(NSDictionary*)groupDictionary;

@end


text:
package com.evolveum.midpoint.notifications.impl.notifiers;

import com.evolveum.midpoint.notifications.api.OperationStatus;
import com.evolveum.midpoint.notifications.api.events.ResourceObjectEvent;
import com.evolveum.midpoint.notifications.api.events.Event;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.provisioning.api.ResourceOperationDescription;
import com.evolveum.midpoint.schema.DeltaConvertor;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author mederly
 */
@Component
public class SimpleResourceObjectNotifier extends GeneralNotifier {

    private static final Trace LOGGER = TraceManager.getTrace(SimpleResourceObjectNotifier.class);

    @PostConstruct
    public void init() {
        register(SimpleResourceObjectNotifierType.class);
    }

    private static final List<ItemPath> synchronizationPaths = Arrays.asList(
            new ItemPath(ShadowType.F_SYNCHRONIZATION_SITUATION),
            new ItemPath(ShadowType.F_SYNCHRONIZATION_SITUATION_DESCRIPTION),
            new ItemPath(ShadowType.F_SYNCHRONIZATION_TIMESTAMP),
            new ItemPath(ShadowType.F_FULL_SYNCHRONIZATION_TIMESTAMP));

    @Override
    protected boolean quickCheckApplicability(Event event, GeneralNotifierType generalNotifierType, OperationResult result) {
        if (!(event instanceof ResourceObjectEvent)) {
            LOGGER.trace("SimpleResourceObjectNotifier is not applicable for this kind of event, continuing in the handler chain; event class = " + event.getClass());
            return false;
        } else {
            return true;
        }
    }

    @Override
    protected boolean checkApplicability(Event event, GeneralNotifierType generalNotifierType, OperationResult result) {

        ResourceObjectEvent resourceObjectEvent = (ResourceObjectEvent) event;
        ObjectDelta<ShadowType> delta = resourceObjectEvent.getShadowDelta();
        if (!delta.isModify()) {
            return true;
        }

        boolean otherThanSyncPresent = deltaContainsOtherPathsThan(delta, synchronizationPaths);
        boolean otherThanAuxPresent = deltaContainsOtherPathsThan(delta, auxiliaryPaths);
        boolean watchSync = isWatchSynchronizationAttributes((SimpleResourceObjectNotifierType) generalNotifierType);
        boolean watchAux = isWatchAuxiliaryAttributes(generalNotifierType);
        if ((watchSync || otherThanSyncPresent) && (watchAux || otherThanAuxPresent)) {
            return true;
        }

        LOGGER.trace("No relevant attributes in delta, skipping the notifier (watchSync = " + watchSync + ", otherThanSyncPresent = " + otherThanSyncPresent +
                ", watchAux = " + watchAux + ", otherThanAuxPresent = " + otherThanAuxPresent + ")");
        return false;
    }

    private boolean isWatchSynchronizationAttributes(SimpleResourceObjectNotifierType generalNotifierType) {
        return Boolean.TRUE.equals((generalNotifierType).isWatchSynchronizationAttributes());
    }

    @Override
    protected String getSubject(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) {

        ResourceObjectEvent resourceObjectEvent = (ResourceObjectEvent) event;

        ResourceOperationDescription rod = resourceObjectEvent.getAccountOperationDescription();
        ObjectDelta<ShadowType> delta = (ObjectDelta<ShadowType>) rod.getObjectDelta();

        String objectTypeDescription = resourceObjectEvent.isShadowKind(ShadowKindType.ACCOUNT) ? "Account" : "Resource object";

        if (delta.isAdd()) {
            return objectTypeDescription + " creation notification";
        } else if (delta.isModify()) {
            return objectTypeDescription + " modification notification";
        } else if (delta.isDelete()) {
            return objectTypeDescription + " deletion notification";
        } else {
            return "(unknown resource object operation)";
        }
    }

    @Override
    protected String getBody(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) {

        boolean techInfo = Boolean.TRUE.equals(generalNotifierType.isShowTechnicalInformation());

        StringBuilder body = new StringBuilder();

        ResourceObjectEvent resourceObjectEvent = (ResourceObjectEvent) event;

        UserType owner = (UserType) notificationsUtil.getObjectType(resourceObjectEvent.getRequestee(), result);
        ResourceOperationDescription rod = resourceObjectEvent.getAccountOperationDescription();
        ObjectDelta<ShadowType> delta = (ObjectDelta<ShadowType>) rod.getObjectDelta();

        boolean isAccount = resourceObjectEvent.isShadowKind(ShadowKindType.ACCOUNT);
        String objectTypeDescription = isAccount ? "account" : "resource object";

        body.append("Notification about ").append(objectTypeDescription).append("-related operation\n\n");
        if (isAccount) {
            if (owner != null) {
                body.append("User: " + owner.getFullName() + " (" + owner.getName() + ", oid " + owner.getOid() + ")\n");
            } else {
                body.append("User: unknown\n");
            }
        }
        body.append("Notification created on: " + new Date() + "\n\n");
        body.append("Resource: " + rod.getResource().asObjectable().getName() + " (oid " + rod.getResource().getOid() + ")\n");
        boolean named;
        if (rod.getCurrentShadow() != null && rod.getCurrentShadow().asObjectable().getName() != null) {
            if (isAccount) {
                body.append("Account: " + rod.getCurrentShadow().asObjectable().getName() + "\n");
            } else {
                body.append("Resource object: " + rod.getCurrentShadow().asObjectable().getName() + " (kind: " + rod.getCurrentShadow().asObjectable().getKind() + ")\n");
            }
            named = true;
        } else {
            named = false;
        }
        body.append("\n");

        if (isAccount) {
            body.append((named ? "The" : "An") + " account ");
        } else {
            body.append((named ? "The" : "A") + " resource object ");
        }
        switch (resourceObjectEvent.getOperationStatus()) {
            case SUCCESS: body.append("has been successfully "); break;
            case IN_PROGRESS: body.append("has been ATTEMPTED to be "); break;
            case FAILURE: body.append("FAILED to be "); break;
        }

        if (delta.isAdd()) {
            body.append("created on the resource with attributes:\n");
            body.append(textFormatter.formatAccountAttributes(delta.getObjectToAdd().asObjectable(), null, isWatchAuxiliaryAttributes(generalNotifierType)));
            body.append("\n");
        } else if (delta.isModify()) {
            body.append("modified on the resource. Modified attributes are:\n");
            List<ItemPath> hiddenPaths = new ArrayList<ItemPath>();
            if (!isWatchSynchronizationAttributes((SimpleResourceObjectNotifierType) generalNotifierType)) {
                hiddenPaths.addAll(synchronizationPaths);
            }
            if (!isWatchAuxiliaryAttributes(generalNotifierType)) {
                hiddenPaths.addAll(auxiliaryPaths);
            }

            if (resourceObjectEvent.getOperationStatus() != OperationStatus.IN_PROGRESS) {
                // todo we do not have objectOld + objectNew, only the current status
                // it is used to explain modified containers with identifiers -- however, currently I don't know of use of such containers in shadows, which would be visible in notifications
                body.append(textFormatter.formatObjectModificationDelta(delta, hiddenPaths, isWatchAuxiliaryAttributes(generalNotifierType),
                        resourceObjectEvent.getAccountOperationDescription().getCurrentShadow(), null));
            } else {
                // special case - here the attributes are 'result', 'failedOperationType', 'objectChange', 'attemptNumber'
                // we have to unwrap attributes that are to be modified from the objectChange item
                Collection<PrismPropertyValue<ObjectDeltaType>> changes = null;
                if (delta.getModifications() != null) {
                    for (ItemDelta itemDelta : delta.getModifications()) {
                        if (itemDelta.getPath().equivalent(new ItemPath(ShadowType.F_OBJECT_CHANGE))) {
                            changes = itemDelta.getValuesToAdd() != null && !itemDelta.getValuesToAdd().isEmpty() ?
                                    itemDelta.getValuesToAdd() : itemDelta.getValuesToReplace();
                        }
                    }
                }

                if (changes != null && !changes.isEmpty()) {
                    try {
                        List<ObjectDelta<ShadowType>> deltas = new ArrayList<ObjectDelta<ShadowType>>(changes.size());
                        for (PrismPropertyValue<ObjectDeltaType> change : changes) {
                            deltas.add((ObjectDelta) DeltaConvertor.createObjectDelta(change.getValue(), prismContext));
                        }
                        ObjectDelta<ShadowType> shadowDelta = ObjectDelta.summarize(deltas);
                        body.append(textFormatter.formatObjectModificationDelta(shadowDelta, hiddenPaths, isWatchAuxiliaryAttributes(generalNotifierType),
                                resourceObjectEvent.getAccountOperationDescription().getCurrentShadow(), null));
                    } catch (SchemaException e) {
                        LoggingUtils.logException(LOGGER, "Unable to determine the shadow change; operation = {}", e, resourceObjectEvent.getAccountOperationDescription().debugDump());
                        body.append("(unable to determine the change because of schema exception: ").append(e.getMessage()).append(")\n");
                    }
                } else {
                    body.append("(unable to determine the change)\n");
                }
            }
            body.append("\n");
        } else if (delta.isDelete()) {
            body.append("removed from the resource.\n\n");
        }

        if (resourceObjectEvent.getOperationStatus() == OperationStatus.IN_PROGRESS) {
            body.append("The operation will be retried.\n\n");
        } else if (resourceObjectEvent.getOperationStatus() == OperationStatus.FAILURE) {
            body.append("Error: " + resourceObjectEvent.getAccountOperationDescription().getResult().getMessage() + "\n\n");
        }

        body.append("\n\n");
        notificationsUtil.addRequesterAndChannelInformation(body, event, result);

        if (techInfo) {
            body.append("----------------------------------------\n");
            body.append("Technical information:\n\n");
            body.append(rod.debugDump(2));
        }

        return body.toString();
    }

//    private String getLocalPart(QName name) {
//        if (name == null) {
//            return null;
//        } else {
//            return name.getLocalPart();
//        }
//    }
//
//    private String getResourceName(AccountShadowType account) {
//        String oid = null;
//        if (account.getResource() != null) {
//            if (account.getResource().getName() != null) {
//                return account.getResource().getName().getOrig();
//            }
//            oid = account.getResource().getOid();
//        } else {
//            if (account.getResourceRef() != null) {
//                oid = account.getResourceRef().getOid();
//            }
//        }
//        if (oid == null) {
//            return ("(unknown resource)");
//        }
//        return NotificationsUtil.getResourceNameFromRepo(cacheRepositoryService, oid, new OperationResult("dummy"));
//    }
//
//    private void listAccounts(StringBuilder messageText, List<String> lines) {
//        boolean first = true;
//        for (String line : lines) {
//            if (first) {
//                first = false;
//            } else {
//                messageText.append(",\n");
//            }
//            messageText.append(line);
//        }
//        messageText.append(".\n\n");
//    }

    @Override
    protected Trace getLogger() {
        return LOGGER;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  Game Database
  %%
  Copyright (C) 2016 - 2016 LCManager Group
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.lcmanager.gdb.service.impl.data.mapper.RequirementMapper">
	<resultMap type="Requirement" id="requirement">
		<id property="id" column="requirementId" />
		<result property="osFamily" column="requirementOsFamily" />
		<result property="memory" column="requirementMemory" />
		<result property="storage" column="requirementStorage" />
		<collection property="processorAdder" ofType="Processor" foreignColumn="requirementId">
			<id property="id" column="processorId" />
			<result property="model" column="processorModel" />
			<result property="cores" column="processorCores" />
			<result property="threads" column="processorThreads" />
			<result property="frequency" column="processorFrequency" />
			<result property="instructionSet" column="processorInstructionSet" />
			<association property="brand" javaType="Brand" foreignColumn="processorId">
				<id property="id" column="processorBrandId" />
				<result property="name" column="processorBrandName" />
			</association>
		</collection>
		<collection property="graphicsAdder" ofType="Graphics" foreignColumn="requirementId">
			<id property="id" column="graphicsId" />
			<result property="model" column="graphicsModel" />
			<result property="memory" column="graphicsMemory" />
			<result property="frequency" column="graphicsFrequency" />
			<result property="directXVersion" column="graphicsDirectXVersion" />
			<result property="openGlVersion" column="graphicsOpenGlVersion" />
			<association property="brand" javaType="Brand" foreignColumn="graphicsId">
				<id property="id" column="graphicsBrandId" />
				<result property="name" column="graphicsBrandName" />
			</association>
		</collection>
	</resultMap>

	<!-- Methods from BaseMapper. -->
	<insert id="insert" parameterType="Map" useGeneratedKeys="true" keyProperty="obj.id" keyColumn="id">
		INSERT INTO Requirement (
			osFamily,
			memory,
			storage
		) VALUES (
			#{obj.osFamily},
			#{obj.memory},
			#{obj.storage}
		)
	</insert>
	<update id="update" parameterType="Map">
		UPDATE
			Requirement
		SET
			osFamily = #{obj.osFamily},
			memory = #{obj.memory},
			storage = #{obj.storage}
		WHERE
			id = #{obj.id}
	</update>
	<insert id="save" parameterType="Map">
		INSERT INTO Requirement (
			id,
			osFamily,
			memory,
			storage
		) VALUES (
			#{obj.id},
			#{obj.osFamily},
			#{obj.memory},
			#{obj.storage}
		) ON DUPLICATE KEY UPDATE
			osFamily = #{obj.osFamily},
			memory = #{obj.memory},
			storage = #{obj.storage}
	</insert>
	<delete id="delete" parameterType="Map">
		DELETE
		FROM
			Requirement
		WHERE
			id = #{id}
	</delete>
	<select id="exists" parameterType="Map" resultType="boolean">
		SELECT
			COUNT(*)
		FROM
			Requirement
		WHERE
			id = #{obj.id}
	</select>
	<select id="findById" parameterType="Map" resultMap="requirement">
		SELECT
			*
		FROM
			View_Requirement
		WHERE
			requirementId = #{id}
	</select>
	<select id="find" resultMap="requirement">
		SELECT
			*
		FROM
			View_Requirement
	</select>

	<!-- Methods from RequirementMapper. -->
	<insert id="addProcessor" parameterType="Map">
		INSERT IGNORE INTO Requirement_Processor (
			requirementId,
			processorId
		) VALUES (
			#{id},
			#{processorId}
		)
	</insert>
	<delete id="removeProcessor" parameterType="Map">
		DELETE
		FROM
			Requirement_Processor
		WHERE
			requirementId = #{id}
			AND
			processorId = #{processorId}
	</delete>
	<insert id="addGraphics" parameterType="Map">
		INSERT IGNORE INTO Requirement_Graphics (
			requirementId,
			graphicsId
		) VALUES (
			#{id},
			#{graphicsId}
		)
	</insert>
	<delete id="removeGraphics" parameterType="Map">
		DELETE
		FROM
			Requirement_Graphics
		WHERE
			requirementId = #{id}
			AND
			graphicsId = #{graphicsId}
	</delete>
</mapper>


text:
import '@hotwired/turbo-rails'

import 'jquery'
import 'jquery_ujs'
import 'jquery-ui/widgets/autocomplete'
import 'turbolinks_events'
import 'bootstrap'

import 'codemirror/codemirror'
import 'codemirror/addon/dialog/dialog'
import 'codemirror/addon/edit/closebrackets'
import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/fold/foldcode'
import 'codemirror/addon/fold/foldgutter'
import 'codemirror/addon/fold/indent-fold'
import 'codemirror/addon/search/search'
import 'codemirror/addon/search/searchcursor'
import 'codemirror/addon/selection/active-line'
import 'codemirror/mode/python'
import 'codemirror/mode/ruby'
import 'codemirror/mode/shell'
import 'codemirror/mode/sql'

import 'moment/moment'
import 'moment/es'
import 'daterangepicker'

import 'metis_menu'
import 'jquery-slimscroll'
import 'hyper'

import 'apexcharts'
import 'ajax'
import 'autocomplete'
import 'clipboard'
import 'date_pickers'
import 'dynamic_form'
import 'filters'
import 'console'
import 'data_links'
import 'editor'
import 'helps'
import 'issues_board'
import 'objects'
import 'rules'
import 'servers'
import 'trix_configuration'

import 'trix'
import '@rails/actiontext'

import '@rails/actioncable'
import 'consumer'
import 'channels/execution'


text:
import {ExpressionModel} from "../generic/ExpressionModel";
import {ExpressionEvaluator, ExprObj} from "../helpers/ExpressionEvaluator";
import {Expression} from "../../mappings/v1.0/Expression";
import {EventHub} from "../helpers/EventHub";

export class V1ExpressionModel extends ExpressionModel {
    private value?: string     = "";
    private tokens?: ExprObj[] = [];

    public serialize(): string | Expression {
        if (this.type === "expression" && this.eventHub) {
            this.eventHub.emit("expression.serialize", true);
        }
        return this.value !== "" ? this.value : undefined;
    }

    public deserialize(attr: string): void {
        if (typeof attr === "string") {
            this.value = attr;
            this.tokenizeAndSetType(attr);
        }
    }

    constructor(expression?: string | V1ExpressionModel, loc?: string, eventHub?: EventHub) {
        super(loc, eventHub);

        if (expression instanceof V1ExpressionModel) {
            expression = (<V1ExpressionModel> expression).serialize();
        }

        if (expression) this.deserialize(expression);

        if (this.eventHub) {
            this.eventHub.emit("expression.create", this)
        }
    }

    private tokenizeAndSetType(str: string): ExprObj[] {
        // parse expression
        this.tokens = ExpressionEvaluator.grabExpressions(str || "") || [];

        // if expression is literal, type is string, otherwise it's complex (expression or function)
        this.type = this.tokens.length === 1 && this.tokens[0].type === "literal" || this.tokens.length === 0 ? "string" : "expression";
        return this.tokens;
    }

    public evaluate(context: { inputs?: any, self?: any, runtime?: any } = this.cachedContext) {
        if (this.value !== undefined) {
            return this._evaluate(this.value, context, "v1.0");
        }

        return new Promise((res) => {
            res(undefined)
        });
    }

    public setValue(val: string | Expression, type?: "expression" | "string") {
        this.result = undefined;

        this.tokenizeAndSetType(val);
        this.value = val;

        if (this.eventHub) {
            this.eventHub.emit("expression.change", this);
        }
    }

    public getScript(): string {
        return this.value;
    }

    public toString(): string {
        return this.value || "";
    }

    clone(): V1ExpressionModel {
        return new V1ExpressionModel(this.serialize(), this.loc, this.eventHub);
    }

    cloneStatus(clone: V1ExpressionModel) {
        this.setValue(clone.serialize());
        this.setIssue({...clone.issues});
    }

    cloneValidationCallback(clone: V1ExpressionModel) {
        clone.setValidationCallback(err => this.updateValidity(err));
    }
}


text:
 /**
 * @file	opts.h
 * @author	Emil Nilsson
 * @license	MIT
 * @date	2014
 */

#ifndef SG_OPTS_H
#define SG_OPTS_H

struct sg_opts {
	/** The number of buffers. */
	int num_bufs;

	/** The filename of the file to read from/write to. */
	char * filename;
};

/**
 * Reads options.
 */
extern int read_opts(int argc, char * argv[], struct sg_opts * options);

#endif


text:
Quip API Python Client
=====

The official [Quip API](https://quip.com/api/) Python client library.

```python
client = quip.QuipClient(access_token="...")
user = client.get_authenticated_user()
starred = client.get_folder(user["starred_folder_id"])
print "There are", len(starred["children"]), "items in your starred folder"
```


text:
<?php

namespace Application\Model;

use Zend\Db\TableGateway\TableGateway;

class AdvertisementCategoryTable
{
	protected $tableGateway = null;

	public function __construct(TableGateway $tableGateway)
	{
		$this->tableGateway = $tableGateway;
	}

	public function fetchAll($page=1, $size=25, &$count)
	{
		if($page < 1){
			$page = 1;
		} // if

		$select = new \Zend\Db\Sql\Select();

		$select->from($this->tableGateway->getTable())
		       ->order('name')
			   ->offset(($page - 1) * $size)
			   ->limit($size);

		$results = $this->tableGateway->selectWith($select);

		$count = $this->getCount();

		$list = array();

		foreach($results as $result){
			$list[] = $result;
		} // foreach

		return $list;
	}

	public function fetchAllEnabled()
	{
		$select = new \Zend\Db\Sql\Select();

		$select->from($this->tableGateway->getTable())
		       ->where(array('enabled' => 1))
		       ->order('name');

		$results = $this->tableGateway->selectWith($select);

		$list = array();

		foreach($results as $result){
			$list[] = $result;
		} // foreach

		return $list;
	}

	public function getCount()
	{
		$stmt = $this->tableGateway->getAdapter()->createStatement('SELECT count(id) as count FROM advertisement_categories');

		$results = $stmt->execute();

		$result = $results->current();

		if(!$result || !isset($result['count'])){
			return 0;
		} // if

		return $result['count'];
	}

	public function getAdvertisementCategory($id)
	{
		$id = (int)$id;

		$results = $this->tableGateway->select(array('id' => $id));
		$result = $results->current();

		if(!$result){
			return null;
		} // if

		return $result;
	}

	public function save(AdvertisementCategory $advertisementCategory)
	{
		$id = (int)$advertisementCategory->id();

		$data = array(
			'name' => $advertisementCategory->name(),
			'description' => $advertisementCategory->description(),
			'clickrate' => $advertisementCategory->clickRate(),
			'impressionrate' => $advertisementCategory->impressionRate(),
			'enabled' => $advertisementCategory->enabled() ? 1 : 0
		);

		if($id > 0){
			if(!$this->getAdvertisementCategory($id)){
				throw new \Exception("Could not locate an Advertisement Category with id $id");
			} // if
			else{
				$this->tableGateway->update($data, array('id' => $id));
			} // else
		} // if
		else{
			$this->tableGateway->insert($data);
			$advertisementCategory->id((int)$this->tableGateway->lastInsertValue);
		} // else
	}
}


text:
package org.elasticsearch.action.explain;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.Explanation;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.action.support.single.shard.TransportShardSingleOperationAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.routing.ShardIterator;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.mapper.internal.UidFieldMapper;
import org.elasticsearch.index.query.ParsedQuery;
import org.elasticsearch.index.service.IndexService;
import org.elasticsearch.index.shard.service.IndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.internal.ShardSearchRequest;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

import java.io.IOException;

/**
 * Explain transport action. Computes the explain on the targeted shard.
 */
// TODO: AggregatedDfs. Currently the idf can be different then when executing a normal search with explain.
public class TransportExplainAction extends TransportShardSingleOperationAction<ExplainRequest, ExplainResponse> {

    private final IndicesService indicesService;

    private final ScriptService scriptService;

    @Inject
    public TransportExplainAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
                                  TransportService transportService, IndicesService indicesService,
                                  ScriptService scriptService) {
        super(settings, threadPool, clusterService, transportService);
        this.indicesService = indicesService;
        this.scriptService = scriptService;
    }

    protected String transportAction() {
        return ExplainAction.NAME;
    }

    protected String executor() {
        return ThreadPool.Names.GET; // Or use Names.SEARCH?
    }

    @Override
    protected void resolveRequest(ClusterState state, ExplainRequest request) {
        String concreteIndex = state.metaData().concreteIndex(request.index());
        request.filteringAlias(state.metaData().filteringAliases(concreteIndex, request.index()));
        request.index(state.metaData().concreteIndex(request.index()));
    }

    protected ExplainResponse shardOperation(ExplainRequest request, int shardId) throws ElasticSearchException {
        IndexService indexService = indicesService.indexService(request.index());
        IndexShard indexShard = indexService.shardSafe(shardId);
        Term uidTerm = new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(request.type(), request.id()));
        Engine.GetResult result = indexShard.get(new Engine.Get(false, uidTerm));
        if (!result.exists()) {
            return new ExplainResponse(false);
        }

        SearchContext context = new SearchContext(
                0,
                new ShardSearchRequest().types(new String[]{request.type()})
                        .filteringAliases(request.filteringAlias()),
                null, result.searcher(), indexService, indexShard,
                scriptService
        );
        SearchContext.setCurrent(context);

        try {
            context.parsedQuery(parseQuery(request, indexService));
            context.preProcess();
            int topLevelDocId = result.docIdAndVersion().docId + result.docIdAndVersion().reader.docBase;

            Explanation explanation = context.searcher().explain(context.query(), topLevelDocId);
            if (request.fields() != null) {
                if (request.fields().length == 1 && "_source".equals(request.fields()[0])) {
                    request.fields(null); // Load the _source field
                }
                // Advantage is that we're not opening a second searcher to retrieve the _source. Also
                // because we are working in the same searcher in engineGetResult we can be sure that a
                // doc isn't deleted between the initial get and this call.
                GetResult getResult = indexShard.getService().get(result, request.id(), request.type(), request.fields());
                return new ExplainResponse(true, explanation, getResult);
            } else {
                return new ExplainResponse(true, explanation);
            }
        } catch (IOException e) {
            throw new ElasticSearchException("Could not explain", e);
        } finally {
            context.release();
            SearchContext.removeCurrent();
        }
    }

    private ParsedQuery parseQuery(ExplainRequest request, IndexService indexService) {
        try {
            XContentParser parser = XContentHelper.createParser(request.source());
            for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    String fieldName = parser.currentName();
                    if ("query".equals(fieldName)) {
                        return indexService.queryParserService().parse(parser);
                    } else if ("query_binary".equals(fieldName)) {
                        byte[] querySource = parser.binaryValue();
                        XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource);
                        return indexService.queryParserService().parse(qSourceParser);
                    }
                }
            }
        } catch (Exception e) {
            throw new ElasticSearchException("Couldn't parse query from source.", e);
        }

        throw new ElasticSearchException("No query specified");
    }

    protected ExplainRequest newRequest() {
        return new ExplainRequest();
    }

    protected ExplainResponse newResponse() {
        return new ExplainResponse();
    }

    protected ClusterBlockException checkGlobalBlock(ClusterState state, ExplainRequest request) {
        return state.blocks().globalBlockedException(ClusterBlockLevel.READ);
    }

    protected ClusterBlockException checkRequestBlock(ClusterState state, ExplainRequest request) {
        return state.blocks().indexBlockedException(ClusterBlockLevel.READ, request.index());
    }

    protected ShardIterator shards(ClusterState state, ExplainRequest request) throws ElasticSearchException {
        return clusterService.operationRouting().getShards(
                clusterService.state(), request.index(), request.type(), request.id(), request.routing(), request.preference()
        );
    }
}


text:
<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\Group;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method Group|null find($id, $lockMode = null, $lockVersion = null)
 * @method Group|null findOneBy(array $criteria, array $orderBy = null)
 * @method Group[]    findAll()
 * @method Group[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class GroupRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Group::class);
    }

    public function add(Group $user): void
    {
        $this->_em->persist($user);
    }

    public function remove(Group $user): void
    {
        $this->_em->remove($user);
    }
}


text:
#include "common_tools.h"
#include "opengles.h"

typedef void (APIENTRY *glDrawArraysInstancedANGLEPROC) (jint, jint, jint, jint);
typedef void (APIENTRY *glDrawElementsInstancedANGLEPROC) (jint, jint, jint, uintptr_t, jint);
typedef void (APIENTRY *glVertexAttribDivisorANGLEPROC) (jint, jint);

EXTERN_C_ENTER

JNIEXPORT void JNICALL Java_org_lwjgl_opengles_ANGLEInstancedArrays_glDrawArraysInstancedANGLE(JNIEnv *__env, jclass clazz, jint mode, jint first, jint count, jint primcount) {
    glDrawArraysInstancedANGLEPROC glDrawArraysInstancedANGLE = (glDrawArraysInstancedANGLEPROC)tlsGetFunction(373);
    UNUSED_PARAM(clazz)
    glDrawArraysInstancedANGLE(mode, first, count, primcount);
}

JNIEXPORT void JNICALL Java_org_lwjgl_opengles_ANGLEInstancedArrays_nglDrawElementsInstancedANGLE(JNIEnv *__env, jclass clazz, jint mode, jint count, jint type, jlong indicesAddress, jint primcount) {
    glDrawElementsInstancedANGLEPROC glDrawElementsInstancedANGLE = (glDrawElementsInstancedANGLEPROC)tlsGetFunction(374);
    uintptr_t indices = (uintptr_t)indicesAddress;
    UNUSED_PARAM(clazz)
    glDrawElementsInstancedANGLE(mode, count, type, indices, primcount);
}

JNIEXPORT void JNICALL Java_org_lwjgl_opengles_ANGLEInstancedArrays_glVertexAttribDivisorANGLE(JNIEnv *__env, jclass clazz, jint index, jint divisor) {
    glVertexAttribDivisorANGLEPROC glVertexAttribDivisorANGLE = (glVertexAttribDivisorANGLEPROC)tlsGetFunction(375);
    UNUSED_PARAM(clazz)
    glVertexAttribDivisorANGLE(index, divisor);
}

EXTERN_C_EXIT


text:
package fr.noogotte.pvpheaddrop;

import java.util.Random;

import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;

public class PvPListener implements Listener {

    private PvPHeadDrop plugin;

    public PvPListener(PvPHeadDrop plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onEntityDeath(PlayerDeathEvent event) {
        Player death = (Player) event.getEntity();
        Player killer = death.getKiller();

        if (killer == null) {
            return;
        }

        if (!death.hasPermission("pvphead.drop")
                || !killer.hasPermission("pvphead.receive")) {
            return;
        }

        Random rand = new Random();
        boolean drop = rand.nextDouble() * 100 + 1 < plugin.getRate();

        if(!drop) {
            return;
        }

        ItemStack stack = new ItemStack(Material.SKULL_ITEM, 1, (short) 3);
        SkullMeta meta = (SkullMeta) stack.getItemMeta();
        meta.setOwner(death.getName());
        stack.setItemMeta(meta);
        event.getDrops().add(stack);
    }
}


text:
@implementation JSKeyChain

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (id)kSecClassGenericPassword,(id)kSecClass,
            service, (id)kSecAttrService,
            service, (id)kSecAttrAccount,
            (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
            nil];
}

#pragma mark 写入
+ (void)save:(NSString *)service data:(id)data {
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}

#pragma mark 读取
+ (id)load:(NSString *)service {
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Configure the search setting
    //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
}

#pragma mark 删除
+ (void)delete:(NSString *)service {
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}

@end


text:
Sprite::Sprite(const string& n, const Vector2f& pos, const Vector2f& vel):
  Drawable(n, pos, vel),
  frame( FrameFactory::getInstance().getFrame(n)),
  frameWidth(Gamedata::getInstance().getXmlInt(n+"/width")),
  frameHeight(Gamedata::getInstance().getXmlInt(n+"/height")),
  worldWidth(Gamedata::getInstance().getXmlInt("world/width")),
  worldHeight(Gamedata::getInstance().getXmlInt("world/height"))
{ }
Sprite::Sprite(const string& n, const Vector2f& pos, const Vector2f& vel,const Frame* fm):
  Drawable(n, pos, vel),
  frame(fm),
  frameWidth(Gamedata::getInstance().getXmlInt(n+"/width")),
  frameHeight(Gamedata::getInstance().getXmlInt(n+"/height")),
  worldWidth(Gamedata::getInstance().getXmlInt("world/width")),
  worldHeight(Gamedata::getInstance().getXmlInt("world/height"))
{ }

Sprite::Sprite(const Sprite& s) :
  Drawable(s),
  frame(s.frame),
  frameWidth(s.getFrame()->getWidth()),
  frameHeight(s.getFrame()->getHeight()),
  worldWidth(Gamedata::getInstance().getXmlInt("world/width")),
  worldHeight(Gamedata::getInstance().getXmlInt("world/height"))
{ }

Sprite& Sprite::operator=(const Sprite& rhs) {
  Drawable::operator=( rhs );
  frame = rhs.frame;
  frameWidth = rhs.frameWidth;
  frameHeight = rhs.frameHeight;
  worldWidth = rhs.worldWidth;
  worldHeight = rhs.worldHeight;
  return *this;
}

void Sprite::draw() const {
  Uint32 x = static_cast<Uint32>(X());
  Uint32 y = static_cast<Uint32>(Y());
  frame->draw(x, y);
}

int Sprite::getDistance(const Sprite *obj) const {
  return hypot(X()-obj->X(), Y()-obj->Y());
}

int Sprite::getWorldWidth()const{
return worldWidth;
}

void Sprite::update(Uint32 ticks) {

  Vector2f incr = getVelocity() * static_cast<float>(ticks) * 0.001;
  setPosition(getPosition() + incr);

  if ( Y() < 0) {
    velocityY( abs( velocityY() ) );
  }
  if ( Y() > worldHeight-frameHeight) {
    velocityY( -abs( velocityY() ) );
  }

  if ( X() < 0) {
    velocityX( abs( velocityX() ) );
  }
  if ( X() > worldWidth-frameWidth) {
    velocityX( -abs( velocityX() ) );
  }
}


text:
#ifndef UDP_TESTS_H
#define UDP_TESTS_H

#include "../test_params.h"
#include "mbed_trace.h"

#define TRACE_GROUP "GRNT"

NetworkInterface *get_interface();
void drop_bad_packets(UDPSocket &sock, int orig_timeout);
nsapi_version_t get_ip_version();
bool check_oversized_packets(nsapi_error_t error, int &size);
void fill_tx_buffer_ascii(char *buff, size_t len);

#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED
extern mbed_stats_socket_t udp_stats[MBED_CONF_NSAPI_SOCKET_STATS_MAX_COUNT];
int fetch_stats(void);
#endif

/**
 * Single testcase might take only half of the remaining execution time
 */
int split2half_rmng_udp_test_time(); // [s]

namespace udp_global {
#ifdef MBED_GREENTEA_TEST_UDPSOCKET_TIMEOUT_S
static const int TESTS_TIMEOUT = MBED_GREENTEA_TEST_UDPSOCKET_TIMEOUT_S;
#else
#define MESH 3
#define WISUN 0x2345
#if MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == MESH && MBED_CONF_NSAPI_DEFAULT_MESH_TYPE == WISUN
static const int TESTS_TIMEOUT = (25 * 60);
#else
static const int TESTS_TIMEOUT = (20 * 60);
#endif
#endif

static const int MAX_SEND_SIZE_IPV4 = 536;
static const int MAX_SEND_SIZE_IPV6 = 1220;
}

/*
 * Test cases
 */
void UDPSOCKET_ECHOTEST();
void UDPSOCKET_ECHOTEST_CONNECT_SEND_RECV();
void UDPSOCKET_ECHOTEST_NONBLOCK();
void UDPSOCKET_ECHOTEST_NONBLOCK_CONNECT_SEND_RECV();
void UDPSOCKET_ECHOTEST_BURST();
void UDPSOCKET_ECHOTEST_BURST_NONBLOCK();
void UDPSOCKET_OPEN_CLOSE_REPEAT();
void UDPSOCKET_OPEN_DESTRUCT();
void UDPSOCKET_OPEN_LIMIT();
void UDPSOCKET_OPEN_TWICE();
void UDPSOCKET_BIND_PORT();
void UDPSOCKET_BIND_PORT_FAIL();
void UDPSOCKET_BIND_ADDRESS_PORT();
void UDPSOCKET_BIND_ADDRESS_NULL();
void UDPSOCKET_BIND_ADDRESS_INVALID();
void UDPSOCKET_BIND_ADDRESS();
void UDPSOCKET_BIND_WRONG_TYPE();
void UDPSOCKET_BIND_UNOPENED();
void UDPSOCKET_RECV_TIMEOUT();
void UDPSOCKET_SENDTO_INVALID();
void UDPSOCKET_SENDTO_REPEAT();
void UDPSOCKET_SENDTO_TIMEOUT();

#endif //UDP_TESTS_H


text:
using Castle.ActiveRecord;

namespace NHibernate.Query.Generator.Tests.ActiveRecord
{
	[ActiveRecord]
	[JoinedBase]
	public class GenericClass<T> : ActiveRecordBase<T>
	{
		int id;

		[PrimaryKey]
		public virtual int Id
		{
			get { return id; }
			set { id = value; }
		}
	}

	[ActiveRecord]
	public class DerivedGenericClass : GenericClass<DerivedGenericClass>
	{
		[JoinedKey]
		public override int Id
		{
			get { return base.Id; }
			set { base.Id = value; }
		}

		private string name;

		[Property]
		public virtual string Name
		{
			get { return name; }
			set { name = value; }
		}
	}
}


text:
<?php

namespace Application\View\Helper;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
use Zend\View\Helper\AbstractHelper;

class Locale extends AbstractHelper implements ServiceLocatorAwareInterface
{
    use ServiceLocatorAwareTrait;

    public function __invoke() {
        return $this->view->plugin('translate')->getTranslator()->getLocale();
    }

}


text:
"use strict";

var error = require("./../../error");
var Util = require("./../../util");

var search = module.exports = {
    search: {}
};

(function() {
    /** section: github
     *  search#issues(msg, callback) -> null
     *      - msg (Object): Object that contains the parameters and their values to be sent to the server.
     *      - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
     *
     *  ##### Params on the `msg` object:
     *
     *  - user (String): Required.
     *  - repo (String): Required.
     *  - state (String): Required. open or closed Validation rule: ` ^(open|closed)$ `.
     *  - keyword (String): Required. Search term
     **/
    this.issues = function(msg, block, callback) {
        var self = this;
        this.client.httpSend(msg, block, function(err, res) {
            if (err)
                return self.sendError(err, null, msg, callback);

            var ret;
            try {
                ret = res.data && JSON.parse(res.data);
            }
            catch (ex) {
                if (callback)
                    callback(new error.InternalServerError(ex.message), res);
                return;
            }

            if (!ret)
                ret = {};
            if (!ret.meta)
                ret.meta = {};
            ["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
                if (res.headers[header])
                    ret.meta[header] = res.headers[header];
            });

            if (callback)
                callback(null, ret);
        });
    };

    /** section: github
     *  search#repos(msg, callback) -> null
     *      - msg (Object): Object that contains the parameters and their values to be sent to the server.
     *      - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
     *
     *  ##### Params on the `msg` object:
     *
     *  - keyword (String): Required. Search term
     *  - language (String): Optional. Filter results by language, see https://github.com/languages
     *  - start_page (Number): Optional. Page number to fetch Validation rule: ` ^[0-9]+$ `.
     **/
    this.repos = function(msg, block, callback) {
        var self = this;
        this.client.httpSend(msg, block, function(err, res) {
            if (err)
                return self.sendError(err, null, msg, callback);

            var ret;
            try {
                ret = res.data && JSON.parse(res.data);
            }
            catch (ex) {
                if (callback)
                    callback(new error.InternalServerError(ex.message), res);
                return;
            }

            if (!ret)
                ret = {};
            if (!ret.meta)
                ret.meta = {};
            ["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
                if (res.headers[header])
                    ret.meta[header] = res.headers[header];
            });

            if (callback)
                callback(null, ret);
        });
    };

    /** section: github
     *  search#users(msg, callback) -> null
     *      - msg (Object): Object that contains the parameters and their values to be sent to the server.
     *      - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
     *
     *  ##### Params on the `msg` object:
     *
     *  - keyword (String): Required. Keyword search parameters
     *  - start_page (Number): Optional. Page number to fetch Validation rule: ` ^[0-9]+$ `.
     **/
    this.users = function(msg, block, callback) {
        var self = this;
        this.client.httpSend(msg, block, function(err, res) {
            if (err)
                return self.sendError(err, null, msg, callback);

            var ret;
            try {
                ret = res.data && JSON.parse(res.data);
            }
            catch (ex) {
                if (callback)
                    callback(new error.InternalServerError(ex.message), res);
                return;
            }

            if (!ret)
                ret = {};
            if (!ret.meta)
                ret.meta = {};
            ["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
                if (res.headers[header])
                    ret.meta[header] = res.headers[header];
            });

            if (callback)
                callback(null, ret);
        });
    };

    /** section: github
     *  search#email(msg, callback) -> null
     *      - msg (Object): Object that contains the parameters and their values to be sent to the server.
     *      - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
     *
     *  ##### Params on the `msg` object:
     *
     *  - email (String): Required. Email address
     **/
    this.email = function(msg, block, callback) {
        var self = this;
        this.client.httpSend(msg, block, function(err, res) {
            if (err)
                return self.sendError(err, null, msg, callback);

            var ret;
            try {
                ret = res.data && JSON.parse(res.data);
            }
            catch (ex) {
                if (callback)
                    callback(new error.InternalServerError(ex.message), res);
                return;
            }

            if (!ret)
                ret = {};
            if (!ret.meta)
                ret.meta = {};
            ["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
                if (res.headers[header])
                    ret.meta[header] = res.headers[header];
            });

            if (callback)
                callback(null, ret);
        });
    };

}).call(search.search);


text:
#include <core/dependencies.h>

#ifdef POK_NEEDS_SEMAPHORES
#include <types.h>
#include <errno.h>
#include <core/semaphore.h>
#include <core/lockobj.h>
#include <core/syscall.h>

pok_ret_t pok_sem_create (pok_sem_id_t*                        id,
                          const pok_sem_value_t                current_value,
                          const pok_sem_value_t                max_value,
                          const pok_queueing_discipline_t      discipline)
{
   pok_lockobj_attr_t lockattr;
   lockattr.initial_value     = current_value;
   lockattr.max_value         = max_value;
   lockattr.queueing_policy   = discipline;
   lockattr.kind              = POK_LOCKOBJ_KIND_SEMAPHORE;

   return pok_syscall2 (POK_SYSCALL_LOCKOBJ_CREATE, (uint32_t)id, (uint32_t)&lockattr);
}

#endif


text:
package org.redisson;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

import org.redisson.client.BaseRedisPubSubListener;
import org.redisson.client.RedisPubSubListener;
import org.redisson.client.codec.LongCodec;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.client.protocol.pubsub.PubSubType;
import org.redisson.core.RCountDownLatch;

import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.PlatformDependent;

/**
 * Distributed alternative to the {@link java.util.concurrent.CountDownLatch}
 *
 * It has a advantage over {@link java.util.concurrent.CountDownLatch} --
 * count can be reset via {@link #trySetCount}.
 *
 * @author Nikita Koksharov
 *
 */
public class RedissonCountDownLatch extends RedissonObject implements RCountDownLatch {

    private static final Integer zeroCountMessage = 0;
    private static final Integer newCountMessage = 1;

    private static final ConcurrentMap<String, RedissonCountDownLatchEntry> ENTRIES = PlatformDependent.newConcurrentHashMap();

    private final UUID id;

    protected RedissonCountDownLatch(CommandExecutor commandExecutor, String name, UUID id) {
        super(commandExecutor, name);
        this.id = id;
    }

    private Future<RedissonCountDownLatchEntry> subscribe() {
        synchronized (ENTRIES) {
            RedissonCountDownLatchEntry entry = ENTRIES.get(getEntryName());
            if (entry != null) {
                entry.aquire();
                return entry.getPromise();
            }

            Promise<RedissonCountDownLatchEntry> newPromise = newPromise();
            final RedissonCountDownLatchEntry value = new RedissonCountDownLatchEntry(newPromise);
            value.aquire();

            RedissonCountDownLatchEntry oldValue = ENTRIES.putIfAbsent(getEntryName(), value);
            if (oldValue != null) {
                oldValue.aquire();
                return oldValue.getPromise();
            }

            RedisPubSubListener<Integer> listener = createListener(value);

            commandExecutor.getConnectionManager().subscribe(listener, getChannelName());
            return newPromise;
        }
    }

    private RedisPubSubListener<Integer> createListener(final RedissonCountDownLatchEntry value) {
        RedisPubSubListener<Integer> listener = new BaseRedisPubSubListener<Integer>() {

            @Override
            public void onMessage(String channel, Integer message) {
                if (!getChannelName().equals(channel)) {
                    return;
                }
                if (message.equals(zeroCountMessage)) {
                    value.getLatch().open();
                }
                if (message.equals(newCountMessage)) {
                    value.getLatch().close();
                }
            }

            @Override
            public boolean onStatus(PubSubType type, String channel) {
                if (channel.equals(getChannelName())
                        && type == PubSubType.SUBSCRIBE) {
                    value.getPromise().trySuccess(value);
                    return true;
                }
                return false;
            }

        };
        return listener;
    }

    private void unsubscribe(RedissonCountDownLatchEntry entry) {
        synchronized (ENTRIES) {
            if (entry.release() == 0) {
                // just an assertion
                boolean removed = ENTRIES.remove(getEntryName()) == entry;
                if (removed) {
                    commandExecutor.getConnectionManager().unsubscribe(getChannelName());
                }
            }
        }
    }

    public void await() throws InterruptedException {
        Future<RedissonCountDownLatchEntry> promise = subscribe();
        try {
            promise.await();

            while (getCountInner() > 0) {
                // waiting for open state
                RedissonCountDownLatchEntry entry = ENTRIES.get(getEntryName());
                if (entry != null) {
                    entry.getLatch().await();
                }
            }
        } finally {
            unsubscribe(promise.getNow());
        }
    }

    @Override
    public boolean await(long time, TimeUnit unit) throws InterruptedException {
        Future<RedissonCountDownLatchEntry> promise = subscribe();
        try {
            if (!promise.await(time, unit)) {
                return false;
            }

            time = unit.toMillis(time);
            while (getCountInner() > 0) {
                if (time <= 0) {
                    return false;
                }
                long current = System.currentTimeMillis();
                // waiting for open state
                RedissonCountDownLatchEntry entry = ENTRIES.get(getEntryName());
                if (entry != null) {
                    entry.getLatch().await(time, TimeUnit.MILLISECONDS);
                }

                long elapsed = System.currentTimeMillis() - current;
                time = time - elapsed;
            }

            return true;
        } finally {
            unsubscribe(promise.getNow());
        }
    }

    @Override
    public void countDown() {
        if (getCount() <= 0) {
            return;
        }

        commandExecutor.evalWrite(getName(), RedisCommands.EVAL_BOOLEAN_R1,
                "local v = redis.call('decr', KEYS[1]);" +
                        "if v <= 0 then redis.call('del', KEYS[1]) end;" +
                        "if v == 0 then redis.call('publish', ARGV[2], ARGV[1]) end;" +
                        "return true",
                 Collections.<Object>singletonList(getName()), zeroCountMessage, getChannelName());
    }

    private String getEntryName() {
        return id + getName();
    }

    private String getChannelName() {
        return "redisson_countdownlatch_{" + getName() + "}";
    }

    @Override
    public long getCount() {
        return getCountInner();
    }

    private long getCountInner() {
        Long val = commandExecutor.read(getName(), LongCodec.INSTANCE, RedisCommands.GET, getName());
        if (val == null) {
            return 0;
        }
        return val;
    }

    @Override
    public boolean trySetCount(long count) {
        return commandExecutor.evalWrite(getName(), RedisCommands.EVAL_BOOLEAN_R1,
                "if redis.call('exists', KEYS[1]) == 0 then redis.call('set', KEYS[1], ARGV[2]); redis.call('publish', ARGV[3], ARGV[1]); return true else return false end",
                 Collections.<Object>singletonList(getName()), newCountMessage, count, getChannelName());
    }

    @Override
    public Future<Boolean> deleteAsync() {
        return commandExecutor.evalWriteAsync(getName(), RedisCommands.EVAL_BOOLEAN_R1,
                "if redis.call('del', KEYS[1]) == 1 then redis.call('publish', ARGV[2], ARGV[1]); return true else return false end",
                 Collections.<Object>singletonList(getName()), newCountMessage, getChannelName());
    }

}


text:
#if !defined(BOOST_FUSION_NVIEW_PRIOR_IMPL_SEP_24_2009_0142PM)
#define BOOST_FUSION_NVIEW_PRIOR_IMPL_SEP_24_2009_0142PM

#include <boost/fusion/support/config.hpp>
#include <boost/mpl/prior.hpp>

namespace boost { namespace fusion
{
    struct nview_iterator_tag;

    template <typename Sequence, typename Pos>
    struct nview_iterator;

    namespace extension
    {
        template <typename Tag>
        struct prior_impl;

        template <>
        struct prior_impl<nview_iterator_tag>
        {
            template <typename Iterator>
            struct apply
            {
                typedef typename Iterator::first_type::iterator_type first_type;
                typedef typename Iterator::sequence_type sequence_type;

                typedef nview_iterator<sequence_type,
                    typename mpl::prior<first_type>::type> type;

                BOOST_FUSION_GPU_ENABLED
                static type
                call(Iterator const& i)
                {
                    return type(i.seq);
                }
            };
        };
    }

}}

#endif


text:
<?php
// This file exists to ensure that base classes are preloaded before
// MonoBook.php is compiled, working around a bug in the APC opcode
// cache on PHP 5, where cached code can break if the include order
// changed on a subsequent page view.
// see http://lists.wikimedia.org/pipermail/wikitech-l/2006-January/021311.html

if ( ! defined( 'MEDIAWIKI' ) )
	die( 1 );

require_once( dirname( dirname( __FILE__ ) ) . '/includes/SkinTemplate.php');


text:
package com.connect_group.thymeleaf.testing.hamcrest;

import com.connect_group.thymesheet.query.HtmlElement;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.thymeleaf.dom.Element;

public class HasClass extends TypeSafeMatcher<HtmlElement> {

  private final Set<String> expectedClassNames;

  public HasClass(String className) {
    expectedClassNames = toSet(className);
  }

  @Override
  public boolean matchesSafely(HtmlElement item) {
    Element element = item.getElement();
    String classes = element.getAttributeValue("class");
    Set<String> classNames = toSet(classes);

    return classNames.containsAll(expectedClassNames);
  }

  private Set<String> toSet(String classNames) {
    Set<String> set = new HashSet<String>();

    if (classNames == null || classNames.length() == 0) {
      set = Collections.emptySet();
    } else {
      set = new HashSet<String>();
      String[] names = classNames.split("\\s+");
      for (String name : names) {
        set.add(name);
      }
    }
    return set;
  }

  @Override
  public void describeTo(Description description) {
    if (expectedClassNames.size() > 1) {
      description.appendText("has classes ");
    } else {
      description.appendText("has class ");
    }

    for (String className : expectedClassNames) {
      description.appendText(" ").appendValue(className);
    }

  }

}


text:
layout: page
subheadline:  ""
title: "豆腐"
teaser:  ""
breadcrumb: true
category: MenuCuisine/all
permalink: /MenuCuisine/all/doufu/
---

{% include cuisine-template.html item=site.data.vegetables.doufu %}


text:
package com.linkedin.thirdeye.dashboard.resources.v2.rootcause;

import com.linkedin.thirdeye.dashboard.resources.v2.RootCauseEntityFormatter;
import com.linkedin.thirdeye.dashboard.resources.v2.pojo.RootCauseEntity;
import com.linkedin.thirdeye.rootcause.Entity;
import com.linkedin.thirdeye.rootcause.impl.DimensionEntity;

public class DimensionEntityFormatter extends RootCauseEntityFormatter {
  public static final String TYPE_DIMENSION = "dimension";

  @Override
  public boolean applies(Entity entity) {
    return entity instanceof DimensionEntity;
  }

  @Override
  public RootCauseEntity format(Entity entity) {
    DimensionEntity e = (DimensionEntity) entity;
    String label = String.format("%s=%s", e.getName(), e.getValue());
    return makeRootCauseEntity(entity, TYPE_DIMENSION, label, null);
  }
}


text:
var app;
Ext.onReady(function() {
    app = new gxp.Viewer({
        proxy: "/geoserver/rest/proxy?url=",
        portalConfig: {
            renderTo: document.body,
            layout: "border",
            height: 465,
            // by configuring items here, we don't need to configure portalItems
            // and save a wrapping container
            items: [{
                // a TabPanel with the map and a dummy tab
                id: "centerpanel",
                xtype: "tabpanel",
                region: "center",
                activeTab: 0, // map needs to be visible on initialization
                border: true,
                items: ["mymap"]
            }]
        },

        // configuration of all tool plugins for this application
        tools: [{
            ptype: "gxp_mapproperties",
            outputConfig: {
                title: 'Map properties'
            }
        }],
        // layer sources
        defaultSourceType: "gxp_wmssource",
        sources: {
            suite: {
                url: "http://suite.opengeo.org/geoserver/wms",
                version: "1.1.1"
            }
        },

        // map and layers
        map: {
            id: "mymap", // id needed to reference map in portalConfig above
            title: "Map",
            projection: "EPSG:4326",
            layers: [{
                source: "suite",
                name: "world",
                title: "World",
                queryable: true,
                selected: true
            }],
            items: [{
                xtype: "gx_zoomslider",
                vertical: true,
                height: 100
            }]
        }
    });
});


text:
/*
Theme Name:         Teutonia 10
Theme URI:          http://www.bigdee.de/
Description:        Theme for the for the hamburg football team based on Roots
Version:            1.0.1
Author:             Dirk Müller
Author URI:         http://www.bigdee.de

License:            MIT License
License URI:        http://opensource.org/licenses/MIT
*/


text:
cask "keeper-password-manager" do
  version "15.0.11,202012111254"
  sha256 :no_check

  url "https://keepersecurity.com/desktop_electron/Darwin/KeeperSetup.dmg"
  name "Keeper Password Manager"
  homepage "https://keepersecurity.com/"

  app "Keeper Password Manager.app"
end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Xunit;

namespace System.Linq.Parallel.Tests
{
    public static class SingleSingleOrDefaultTests
    {
        public static IEnumerable<object[]> SingleSpecificData(int[] counts)
        {
            foreach (int count in counts.DefaultIfEmpty(Sources.OuterLoopCount))
            {
                foreach (int position in new[] { 0, count / 2, Math.Max(0, count - 1) }.Distinct())
                {
                    yield return new object[] { count, position };
                }
            }
        }

        //
        // Single and SingleOrDefault
        //
        [Theory]
        [InlineData(1)]
        [InlineData("string")]
        [InlineData((object)null)]
        public static void Single<T>(T element)
        {
            Assert.Equal(element, ParallelEnumerable.Repeat(element, 1).Single());
            Assert.Equal(element, ParallelEnumerable.Repeat(element, 1).Single(x => true));
        }

        [Theory]
        [InlineData(1, 0)]
        [InlineData("string", 0)]
        [InlineData((object)null, 0)]
        [InlineData(1, 1)]
        [InlineData("string", 1)]
        [InlineData((object)null, 1)]
        public static void SingleOrDefault<T>(T element, int count)
        {
            Assert.Equal(count >= 1 ? element : default(T), ParallelEnumerable.Repeat(element, count).SingleOrDefault());
            Assert.Equal(count >= 1 ? element : default(T), ParallelEnumerable.Repeat(element, count).SingleOrDefault(x => true));
        }

        [Fact]
        public static void Single_Empty()
        {
            Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Single());
            Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Single(x => true));
        }

        [Theory]
        [InlineData(1)]
        [InlineData(2)]
        [InlineData(16)]
        public static void Single_NoMatch(int count)
        {
            IntegerRangeSet seen = new IntegerRangeSet(0, count);
            Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, count).Single(x => !seen.Add(x)));
            seen.AssertComplete();
        }

        [Fact]
        [OuterLoop]
        public static void Single_NoMatch_Longrunning()
        {
            Single_NoMatch(Sources.OuterLoopCount);
        }

        [Theory]
        [InlineData(0)]
        [InlineData(1)]
        [InlineData(2)]
        [InlineData(16)]
        public static void SingleOrDefault_NoMatch(int count)
        {
            IntegerRangeSet seen = new IntegerRangeSet(0, count);
            Assert.Equal(default(int), ParallelEnumerable.Range(0, count).SingleOrDefault(x => !seen.Add(x)));
            seen.AssertComplete();
        }

        [Fact]
        [OuterLoop]
        public static void SingleOrDefault_NoMatch_Longrunning()
        {
            SingleOrDefault_NoMatch(Sources.OuterLoopCount);
        }

        [Theory]
        [InlineData(2)]
        [InlineData(16)]
        public static void Single_AllMatch(int count)
        {
            Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, count).Single(x => true));
        }

        [Fact]
        [OuterLoop]
        public static void Single_AllMatch_Longrunning()
        {
            Single_AllMatch(Sources.OuterLoopCount);
        }

        [Theory]
        [InlineData(2)]
        [InlineData(16)]
        public static void SingleOrDefault_AllMatch(int count)
        {
            Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, count).SingleOrDefault(x => true));
        }

        [Fact]
        [OuterLoop]
        public static void SingleOrDefault_AllMatch_Longrunning()
        {
            SingleOrDefault_AllMatch(Sources.OuterLoopCount);
        }

        [Theory]
        [MemberData(nameof(SingleSpecificData), new[] { 1, 2, 16 })]
        public static void Single_OneMatch(int count, int element)
        {
            IntegerRangeSet seen = new IntegerRangeSet(0, count);
            Assert.Equal(element, ParallelEnumerable.Range(0, count).Single(x => seen.Add(x) && x == element));
            seen.AssertComplete();
        }

        [Theory]
        [OuterLoop]
        [MemberData(nameof(SingleSpecificData), new int[] { /* Sources.OuterLoopCount */ })]
        public static void Single_OneMatch_Longrunning(int count, int element)
        {
            Single_OneMatch(count, element);
        }

        [Theory]
        [MemberData(nameof(SingleSpecificData), new[] { 0, 1, 2, 16 })]
        public static void SingleOrDefault_OneMatch(int count, int element)
        {
            IntegerRangeSet seen = new IntegerRangeSet(0, count);
            Assert.Equal(element, ParallelEnumerable.Range(0, count).SingleOrDefault(x => seen.Add(x) && x == element));
            seen.AssertComplete();
        }

        [Theory]
        [OuterLoop]
        [MemberData(nameof(SingleSpecificData), new int[] { /* Sources.OuterLoopCount */ })]
        public static void SingleOrDefault_OneMatch_Longrunning(int count, int element)
        {
            SingleOrDefault_OneMatch(count, element);
        }

        [Fact]
        public static void Single_OperationCanceledException()
        {
            AssertThrows.EventuallyCanceled((source, canceler) => source.Single(x => { canceler(); return false; }));
        }

        [Fact]
        public static void SingleOrDefault_OperationCanceledException()
        {
            AssertThrows.EventuallyCanceled((source, canceler) => source.SingleOrDefault(x => { canceler(); return false; }));
        }

        [Fact]
        public static void Single_AggregateException_Wraps_OperationCanceledException()
        {
            AssertThrows.OtherTokenCanceled((source, canceler) => source.Single(x => { canceler(); return false; }));
            AssertThrows.SameTokenNotCanceled((source, canceler) => source.Single(x => { canceler(); return false; }));
        }

        [Fact]
        public static void SingleOrDefault_AggregateException_Wraps_OperationCanceledException()
        {
            AssertThrows.OtherTokenCanceled((source, canceler) => source.SingleOrDefault(x => { canceler(); return false; }));
            AssertThrows.SameTokenNotCanceled((source, canceler) => source.SingleOrDefault(x => { canceler(); return false; }));
        }

        [Fact]
        public static void Single_OperationCanceledException_PreCanceled()
        {
            AssertThrows.AlreadyCanceled(source => source.Single());
            AssertThrows.AlreadyCanceled(source => source.Single(x => true));
        }

        [Fact]
        public static void SingleOrDefault_OperationCanceledException_PreCanceled()
        {
            AssertThrows.AlreadyCanceled(source => source.SingleOrDefault());
            AssertThrows.AlreadyCanceled(source => source.SingleOrDefault(x => true));
        }

        [Fact]
        public static void Single_AggregateException()
        {
            AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Single(x => { throw new DeliberateTestException(); }));
            AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).SingleOrDefault(x => { throw new DeliberateTestException(); }));
        }

        [Fact]
        public static void Single_ArgumentNullException()
        {
            AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).Single());
            AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SingleOrDefault());

            AssertExtensions.Throws<ArgumentNullException>("predicate", () => ParallelEnumerable.Empty<int>().Single(null));
            AssertExtensions.Throws<ArgumentNullException>("predicate", () => ParallelEnumerable.Empty<int>().SingleOrDefault(null));
        }
    }
}


text:
function sigma = EstimateSigma(signal, protocol, model)
%
% function sigma = EstimateSigma(signal, protocol, model)
%
% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)
%

if model.sigma.perVoxel == 1
    sigma = std(signal(protocol.b0_Indices), 1);
    % if lower than the minimum SNR
    sigmaMin = model.sigma.minSNR*mean(signal(protocol.b0_Indices));
    if sigma < sigmaMin
        sigma = sigmaMin;
    end
else
    if isfield(model.sigma, 'globalSigma')
        sigma = model.sigma.globalSigma;
    elseif isfield(model.sigma, 'globalSNR')
        sigma = model.sigma.globalSNR*mean(signal(protocol.b0_Indices));
    else
        disp('You have chosen not to use per voxel sigma estimate');
        error('You need to specify either sigma.globalSigma or sigma.globalSNR for your model');
    end
end

% apply the scaling parameter that may improve fitting
sigma = sigma/model.sigma.scaling;


text:
using ClosedXML.Excel.Drawings;
using ClosedXML.Utils;
using System;
using System.IO;

namespace ClosedXML.Graphics
{
    /// <summary>
    /// A reader for baseline TIFF.
    /// Specification: https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf
    /// </summary>
    internal class TiffInfoReader : ImageInfoReader
    {
        private delegate bool TryReadU16(Stream s, out ushort value);

        protected override bool CheckHeader(Stream stream)
        {
            if (!stream.TryReadU16BE(out var byteOrder))
                return false;

            var usesLittleEndian = byteOrder == ByteOrder.LittleEndian;
            var usesBigEndian = byteOrder == ByteOrder.BigEndian;
            if (!usesBigEndian && !usesLittleEndian)
                return false;

            TryReadU16 tryReadU16 = usesLittleEndian ? StreamExtensions.TryReadU16LE : StreamExtensions.TryReadU16BE;
            if (!tryReadU16(stream, out var version))
                return false;

            // The value (42) was chosen for its deep philosophical value :)
            return version == 42;
        }

        protected override XLPictureInfo ReadInfo(Stream stream)
        {
            var byteOrder = stream.ReadU16BE();
            var usesLittleEndian = byteOrder == ByteOrder.LittleEndian;
            Func<Stream, uint> readU32 = usesLittleEndian ? StreamExtensions.ReadU32LE : StreamExtensions.ReadU32BE;
            Func<Stream, ushort> readU16 = usesLittleEndian ? StreamExtensions.ReadU16LE : StreamExtensions.ReadU16BE;

            stream.Position += 2; // skip version
            var ifdOffset = readU32(stream);
            stream.Position = ifdOffset;
            var entriesCount = readU16(stream);
            uint width = 0, height = 0, resolutionUnit = 2;
            double xResolution = 0, yResolution = 0;
            for (var i = 0; i < entriesCount; ++i)
            {
                var entryTag = readU16(stream);
                var entryType = readU16(stream);
                stream.Position += 4; // entryCount
                var nextEntryStart = stream.Position + 4;
                switch (entryTag)
                {
                    case Tag.ImageWidth:
                        width = ReadShortOrLone(stream, entryType, readU16, readU32);
                        break;

                    case Tag.ImageLength:
                        height = ReadShortOrLone(stream, entryType, readU16, readU32);
                        break;

                    case Tag.XResolution:
                        xResolution = ReadRational(stream, readU32);
                        break;

                    case Tag.YResolution:
                        yResolution = ReadRational(stream, readU32);
                        break;

                    case Tag.ResolutionUnit:
                        resolutionUnit = readU16(stream);
                        break;
                }
                stream.Position = nextEntryStart;
            }

            if (width == 0 || height == 0)
                throw new ArgumentException("Unable to determine dimensions of a TIFF.");

            var dpiX = ToDpi(xResolution, resolutionUnit);
            var dpiY = ToDpi(yResolution, resolutionUnit);
            return new XLPictureInfo(XLPictureFormat.Tiff, width, height, dpiX, dpiY);
        }

        private static uint ReadShortOrLone(Stream stream, ushort entryType, Func<Stream, ushort> readU16, Func<Stream, uint> readU32)
        {
            if (entryType == FieldType.Long)
                return readU32(stream);

            if (entryType == FieldType.Short)
                return readU16(stream);

            throw new ArgumentException("Expected only SHORT/LONG type.");
        }

        private static double ReadRational(Stream stream, Func<Stream, uint> readU32)
        {
            stream.Position = readU32(stream);
            var numerator = readU32(stream);
            var denominator = readU32(stream);
            return (double)numerator / denominator;
        }

        private static double ToDpi(double resolution, uint resolutionUnit) =>
            resolutionUnit switch
            {
                Unit.Inch => resolution,
                Unit.Cm => resolution * 2.54d,
                _ => 0
            };

        private static class ByteOrder
        {
            /// <summary>
            /// <c>II</c> like Intel in ASCII.
            /// </summary>
            public const ushort LittleEndian = 0x4949;

            /// <summary>
            /// <c>MM</c> like Motorola in ASCII.
            /// </summary>
            public const ushort BigEndian = 0x4D4D;
        }

        private static class Tag
        {
            public const ushort ImageWidth = 0x100;
            public const ushort ImageLength = 0x101;
            public const ushort XResolution = 0x11A;
            public const ushort YResolution = 0x11B;
            public const ushort ResolutionUnit = 0x128;
        }

        private static class FieldType
        {
            public const ushort Short = 3; // 2 bytes, unsigned
            public const ushort Long = 4; // 4 bytes, unsigned
        }

        private static class Unit
        {
            public const int Inch = 2;
            public const int Cm = 3;
        }
    }
}


text:
var union = require('../'),
  test = require('tape'),
  glob = require('glob'),
  fs = require('fs');

var REGEN = false;

test('union', function(t){
  glob.sync(__dirname + '/fixtures/in/*.geojson').forEach(function(input) {
      var fcs = JSON.parse(fs.readFileSync(input));
      var args = [];
      for (var i = 0; i < fcs.length; i++) {
        args[i] = fcs[i].features[0];
      }
      var output = union.apply(this, args);
      if (REGEN) fs.writeFileSync(input.replace('/in/', '/out/'), JSON.stringify(output));
      t.deepEqual(output, JSON.parse(fs.readFileSync(input.replace('/in/', '/out/'))), input);
  });
  t.end();
});


text:
<?php

/**
 * Mock Class used for unit tests
 * @author cdolivet
 *
 */
class prestaMemberUserConnectorMock extends prestaMemberUserConnector implements prestaUserConnectorMockInterface
{
	/**
	 * Add a user
	 *
	 * @author	ylybliamay
	 * @version	1.1 - 19 avr. 2011 - Sylvain Blatrix <sblatrix@prestaconcept.net>
	 * @since	29 oct. 2009 - ylybliamay
	 * @see plugins/prestaForumConnectorPlugin/lib/class/userConnector/prestaUserConnectorMockInterface#addUserTest($nickname, $email, $password, $active)
	 */
	public function addUserTest($nickname, $email, $password, $active = 1)
	{
		$user = new prestaMember();
		call_user_func( array($user, $this->params['setUsernameMethod']), $nickname );
		call_user_func( array($user, $this->params['setEmailMethod']), $email );
		call_user_func( array($user, $this->params['setPasswordlMethod']), $password );
		call_user_func( array($user, $this->params['setIsActiveMethod']), $active );
		$user->save();
		return $user->getIdMember();
	}
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2014 SEBASTIEN DERONNE
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Sébastien Deronne <sebastien.deronne@gmail.com>
 */

#include "vht-wifi-mac-helper.h"
#include "ns3/wifi-mac.h"
#include "ns3/edca-txop-n.h"
#include "ns3/pointer.h"
#include "ns3/boolean.h"
#include "ns3/uinteger.h"

namespace ns3 {

VhtWifiMacHelper::VhtWifiMacHelper ()
{
}

VhtWifiMacHelper::~VhtWifiMacHelper ()
{
}

VhtWifiMacHelper
VhtWifiMacHelper::Default (void)
{
  VhtWifiMacHelper helper;

  helper.SetType ("ns3::StaWifiMac",
                  "QosSupported", BooleanValue (true),
                  "HtSupported", BooleanValue (true), //by default, it also supports HT features
                  "VhtSupported", BooleanValue (true));

  //MPDU aggregation is always supported
  helper.SetMpduAggregatorForAc (AC_VO, "ns3::MpduStandardAggregator");
  helper.SetMpduAggregatorForAc (AC_VI, "ns3::MpduStandardAggregator");
  helper.SetMpduAggregatorForAc (AC_BE, "ns3::MpduStandardAggregator");
  helper.SetMpduAggregatorForAc (AC_BK, "ns3::MpduStandardAggregator");

  return helper;
}

StringValue
VhtWifiMacHelper::DataRateForMcs (int mcs)
{
  std::stringstream sstmp;
  std::string strtmp, dataRate;

  sstmp << mcs;
  sstmp >> strtmp;
  dataRate = "VhtMcs" + strtmp;

  return StringValue (dataRate);
}

} //namespace ns3


text:
using System;
using System.Drawing;

namespace Acr.UserDialogs
{
    public class ToastConfig
    {
        /// <summary>
        /// The default duration for how long the toast should remain on-screen.  Defaults to 2.5 seconds
        /// </summary>
        public static TimeSpan DefaultDuration { get; set; } = TimeSpan.FromSeconds(2.5);

        /// <summary>
        /// The default message text color to use.  If not set, defaults very depending on platform.
        /// </summary>
        public static Color? DefaultMessageTextColor { get; set; }

        /// <summary>
        /// The default text color in the action button.  If not set, defaults very depending on platform.
        /// </summary>
        public static Color? DefaultActionTextColor { get; set; }

        /// <summary>
        /// The default toast background color.  If not set, defaults very depending on platform.
        /// </summary>
        public static Color? DefaultBackgroundColor { get; set; }

        public static ToastPosition? DefaultPosition { get; set; }

        public string Message { get; set; }
        public Color? MessageTextColor { get; set; } = DefaultMessageTextColor;
        public Color? BackgroundColor { get; set; } = DefaultBackgroundColor;
        public ToastPosition? Position { get; set; } = DefaultPosition;
        public TimeSpan Duration { get; set; } = DefaultDuration;
        public ToastAction Action { get; set; }
        public string Icon { get; set; }

        public ToastConfig(string message)
        {
            this.Message = message;
        }

        public ToastConfig SetBackgroundColor(Color color)
        {
            this.BackgroundColor = color;
            return this;
        }

        public ToastConfig SetPosition(ToastPosition position)
        {
            this.Position = position;
            return this;
        }

        public ToastConfig SetDuration(int millis) => this.SetDuration(TimeSpan.FromMilliseconds(millis));

        public ToastConfig SetDuration(TimeSpan? duration = null)
        {
            this.Duration = duration ?? DefaultDuration;
            return this;
        }

        public ToastConfig SetAction(Action<ToastAction> action)
        {
            var cfg = new ToastAction();
            action(cfg);
            return this.SetAction(cfg);
        }

        public ToastConfig SetAction(ToastAction action)
        {
            this.Action = action;
            if (action.TextColor == null)
                action.TextColor = DefaultActionTextColor;

            return this;
        }

        public ToastConfig SetMessageTextColor(Color color)
        {
            this.MessageTextColor = color;
            return this;
        }

        public ToastConfig SetIcon(string icon)
        {
            this.Icon = icon;
            return this;
        }
    }
}


text:
package org.hive2hive.core.network.messages.request;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import net.tomp2p.peers.PeerAddress;

import org.hive2hive.core.network.messages.direct.BaseDirectMessage;
import org.hive2hive.core.network.messages.direct.response.IResponseCallBackHandler;
import org.hive2hive.core.network.messages.direct.response.ResponseMessage;

/**
 * Abstract message type of a <b>direct</b> message that requests a response.
 *
 * @author Christian
 *
 */
public abstract class DirectRequestMessage extends BaseDirectMessage implements IRequestMessage {

	private static final long serialVersionUID = -8363641962924723518L;

	private transient Set<IResponseCallBackHandler> handler = new HashSet<>();

	public DirectRequestMessage(PeerAddress targetPeerAddress) {
		super(targetPeerAddress);
	}

	public final Set<IResponseCallBackHandler> getCallBackHandlers() {
		return handler;
	}

	public final void setCallBackHandler(IResponseCallBackHandler handler) {
		this.handler.add(handler);
	}

	public final void addCallBackHandler(IResponseCallBackHandler handler) {
		this.handler.add(handler);
	}

	public final ResponseMessage createResponse(Serializable content) {
		return new ResponseMessage(messageID, senderAddress, content);
	}

	public void sendDirectResponse(ResponseMessage response) {
		messageManager.sendDirect(response, getSenderPublicKey());
	}
}