text:
import { log, logInfo, logWarning, logError } from "./logging";
import { hasAlreadyRun } from "./misc";
import { startOperations, stopOperations } from "./operation-handling";

export default {
	hasAlreadyRun,

	log,
	logInfo,
	logWarning,
	logError,

	startOperations,
	stopOperations,
};

redpajama_set_name: RedPajamaGithub


text:
from django.utils.translation import ugettext_lazy as _

# Built-in Licenses
class _LicenseBase(object):
    """Base class for built-in licenses."""
    icons = ''  # CSS classes. See zamboni.css for a list.
    some_rights = True
    on_form = True
    creative_commons = True

class LICENSE_COPYRIGHT(_LicenseBase):
    id = 1
    name = _(u'All Rights Reserved')
    icons = 'copyr'
    some_rights = False
    url = None
    builtin = 11

class LICENSE_CC_BY(_LicenseBase):
    id = 2
    name = _(u'Creative Commons Attribution 3.0')
    url = 'http://creativecommons.org/licenses/by/3.0/'
    icons = 'cc-attrib'
    builtin = 12

class LICENSE_CC_BY_NC(_LicenseBase):
    id = 3
    icons = 'cc-attrib cc-noncom'
    name = _(u'Creative Commons Attribution-NonCommercial 3.0')
    url = 'http://creativecommons.org/licenses/by-nc/3.0/'
    builtin = 13

class LICENSE_CC_BY_NC_ND(_LicenseBase):
    id = 4
    icons = 'cc-attrib cc-noncom cc-noderiv'
    name = _(u'Creative Commons Attribution-NonCommercial-NoDerivs 3.0')
    url = 'http://creativecommons.org/licenses/by-nc-nd/3.0/'
    builtin = 14

class LICENSE_CC_BY_NC_SA(_LicenseBase):
    id = 5
    icons = 'cc-attrib cc-noncom cc-share'
    name = _(u'Creative Commons Attribution-NonCommercial-Share Alike 3.0')
    url = 'http://creativecommons.org/licenses/by-nc-sa/3.0/'
    builtin = 15

class LICENSE_CC_BY_ND(_LicenseBase):
    id = 6
    icons = 'cc-attrib cc-noderiv'
    name = _(u'Creative Commons Attribution-NoDerivs 3.0')
    url = 'http://creativecommons.org/licenses/by-nd/3.0/'
    builtin = 16

class LICENSE_CC_BY_SA(_LicenseBase):
    id = 7
    icons = 'cc-attrib cc-share'
    name = _(u'Creative Commons Attribution-ShareAlike 3.0')
    url = 'http://creativecommons.org/licenses/by-sa/3.0/'
    builtin = 17

class LICENSE_COPYRIGHT_AR(_LicenseBase):
    id = 8
    name = _(u'All Rights Reserved')
    icons = 'copyr'
    some_rights = False
    creative_commons = False
    url = None
    builtin = 18

ALL_LICENSES = (
    LICENSE_COPYRIGHT, LICENSE_CC_BY, LICENSE_CC_BY_NC, LICENSE_CC_BY_NC_ND,
    LICENSE_CC_BY_NC_SA, LICENSE_CC_BY_ND, LICENSE_CC_BY_SA,
    LICENSE_COPYRIGHT_AR)
LICENSES_BY_BUILTIN = {l.builtin: l for l in ALL_LICENSES}


text:
<?php

/**
 * Configuration options storage and logic
 *
 * @category   Mage
 * @package    Mage_Core
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Core_Model_Config_Options extends Varien_Object
{
    /**
     * Var directory
     *
     * @var string
     */
    const VAR_DIRECTORY = 'var';
    /**
     * Flag cache for existing or already created directories
     *
     * @var array
     */
    protected $_dirExists = array();

    /**
     * Initialize default values of the options
     */
    protected function _construct()
    {
        $appRoot= Mage::getRoot();
        $root   = dirname($appRoot);

        $this->_data['app_dir']     = $appRoot;
        $this->_data['base_dir']    = $root;
        $this->_data['code_dir']    = $appRoot.DS.'code';
        $this->_data['design_dir']  = $appRoot.DS.'design';
        $this->_data['etc_dir']     = $appRoot.DS.'etc';
        $this->_data['lib_dir']     = $root.DS.'lib';
        $this->_data['locale_dir']  = $appRoot.DS.'locale';
        $this->_data['media_dir']   = $root.DS.'media';
        $this->_data['skin_dir']    = $root.DS.'skin';
        $this->_data['var_dir']     = $this->getVarDir();
        $this->_data['tmp_dir']     = $this->_data['var_dir'].DS.'tmp';
        $this->_data['cache_dir']   = $this->_data['var_dir'].DS.'cache';
        $this->_data['log_dir']     = $this->_data['var_dir'].DS.'log';
        $this->_data['session_dir'] = $this->_data['var_dir'].DS.'session';
        $this->_data['upload_dir']  = $this->_data['media_dir'].DS.'upload';
        $this->_data['export_dir']  = $this->_data['var_dir'].DS.'export';
    }

    public function getDir($type)
    {
        $method = 'get'.ucwords($type).'Dir';
        $dir = $this->$method();
        if (!$dir) {
            throw Mage::exception('Mage_Core', 'Invalid dir type requested: '.$type);
        }
        return $dir;
    }

    public function getAppDir()
    {
        //return $this->getDataSetDefault('app_dir', Mage::getRoot());
        return $this->_data['app_dir'];
    }

    public function getBaseDir()
    {
        //return $this->getDataSetDefault('base_dir', dirname($this->getAppDir()));
        return $this->_data['base_dir'];
    }

    public function getCodeDir()
    {
        //return $this->getDataSetDefault('code_dir', $this->getAppDir().DS.'code');
        return $this->_data['code_dir'];
    }

    public function getDesignDir()
    {
        //return $this->getDataSetDefault('design_dir', $this->getAppDir().DS.'design');
        return $this->_data['design_dir'];
    }

    public function getEtcDir()
    {
        //return $this->getDataSetDefault('etc_dir', $this->getAppDir().DS.'etc');
        return $this->_data['etc_dir'];
    }

    public function getLibDir()
    {
        //return $this->getDataSetDefault('lib_dir', $this->getBaseDir().DS.'lib');
        return $this->_data['lib_dir'];
    }

    public function getLocaleDir()
    {
        //return $this->getDataSetDefault('locale_dir', $this->getAppDir().DS.'locale');
        return $this->_data['locale_dir'];
    }

    public function getMediaDir()
    {
        //return $this->getDataSetDefault('media_dir', $this->getBaseDir().DS.'media');
        return $this->_data['media_dir'];
    }

    public function getSkinDir()
    {
        //return $this->getDataSetDefault('skin_dir', $this->getBaseDir().DS.'skin');
        return $this->_data['skin_dir'];
    }

    public function getSysTmpDir()
    {
        return sys_get_temp_dir();
    }

    public function getVarDir()
    {
        //$dir = $this->getDataSetDefault('var_dir', $this->getBaseDir().DS.'var');
        $dir = isset($this->_data['var_dir']) ? $this->_data['var_dir']
            : $this->_data['base_dir'] . DS . self::VAR_DIRECTORY;
        if (!$this->createDirIfNotExists($dir)) {
            $dir = $this->getSysTmpDir().DS.'magento'.DS.'var';
            if (!$this->createDirIfNotExists($dir)) {
                throw new Mage_Core_Exception('Unable to find writable var_dir');
            }
        }
        return $dir;
    }

    public function getTmpDir()
    {
        //$dir = $this->getDataSetDefault('tmp_dir', $this->getVarDir().DS.'tmp');
        $dir = $this->_data['tmp_dir'];
        if (!$this->createDirIfNotExists($dir)) {
            $dir = $this->getSysTmpDir().DS.'magento'.DS.'tmp';
            if (!$this->createDirIfNotExists($dir)) {
                throw new Mage_Core_Exception('Unable to find writable tmp_dir');
            }
        }
        return $dir;
    }

    public function getCacheDir()
    {
        //$dir = $this->getDataSetDefault('cache_dir', $this->getVarDir().DS.'cache');
        $dir = $this->_data['cache_dir'];
        $this->createDirIfNotExists($dir);
        return $dir;
    }

    public function getLogDir()
    {
        //$dir = $this->getDataSetDefault('log_dir', $this->getVarDir().DS.'log');
        $dir = $this->_data['log_dir'];
        $this->createDirIfNotExists($dir);
        return $dir;
    }

    public function getSessionDir()
    {
        //$dir = $this->getDataSetDefault('session_dir', $this->getVarDir().DS.'session');
        $dir = $this->_data['session_dir'];
        $this->createDirIfNotExists($dir);
        return $dir;
    }

    public function getUploadDir()
    {
        //$dir = $this->getDataSetDefault('upload_dir', $this->getMediaDir().DS.'upload');
        $dir = $this->_data['upload_dir'];
        $this->createDirIfNotExists($dir);
        return $dir;
    }

    public function getExportDir()
    {
        //$dir = $this->getDataSetDefault('export_dir', $this->getVarDir().DS.'export');
        $dir = $this->_data['export_dir'];
        $this->createDirIfNotExists($dir);
        return $dir;
    }

    public function createDirIfNotExists($dir)
    {
        if (!empty($this->_dirExists[$dir])) {
            return true;
        }
        if (file_exists($dir)) {
            if (!is_dir($dir)) {
                return false;
            }
            if (!is_dir_writeable($dir)) {
                return false;
            }
        } else {
            $oldUmask = umask(0);
            if (!@mkdir($dir, 0777, true)) {
                return false;
            }
            umask($oldUmask);
        }
        $this->_dirExists[$dir] = true;
        return true;
    }
}


text:
#import "MDCTextField.h"
#import "MDCTextFieldPositioningDelegate.h"
#import "MDCTextInput.h"
#import "MDCTextInputCharacterCounter.h"
#import "MDCTextInputController.h"
#import "MDCTextInputControllerDefault.h"
#import "MDCTextInputControllerFullWidth.h"
#import "MDCTextInputUnderlineView.h"


text:
package org.fcrepo.http.api;

import static org.fcrepo.kernel.api.RdfLexicon.EXTERNAL_CONTENT;
import static org.slf4j.LoggerFactory.getLogger;

import java.util.List;
import java.util.stream.Collectors;

import org.fcrepo.kernel.api.exception.ExternalMessageBodyException;
import org.slf4j.Logger;

/**
 * Constructs ExternalContentHandler objects from link headers
 *
 * @author bbpennel
 */
public class ExternalContentHandlerFactory {

    private static final Logger LOGGER = getLogger(ExternalContentHandlerFactory.class);

    private ExternalContentPathValidator validator;

    /**
     * Looks for ExternalContent link header and if it finds one it will return a new ExternalContentHandler object
     * based on the found Link header. If multiple external content headers were found or the URI provided in the
     * header is not a valid external content path, then an ExternalMessageBodyException will be thrown.
     *
     * @param links links from the request header
     * @return External Content Handler Object if Link header found, else null
     * @throws ExternalMessageBodyException thrown if more than one external content link was provided, or if the URL
     *         of the header was not a valid external content path.
     */
    public ExternalContentHandler createFromLinks(final List<String> links) throws ExternalMessageBodyException {
        if (links == null) {
            return null;
        }

        final List<String> externalContentLinks = links.stream()
                .filter(x -> x.contains(EXTERNAL_CONTENT.toString()))
                .collect(Collectors.toList());

        if (externalContentLinks.size() > 1) {
            // got a problem, you can only have one ExternalContent links
            throw new ExternalMessageBodyException("More then one External Content Link header in request");
        } else if (externalContentLinks.size() == 1) {
            final String link = externalContentLinks.get(0);
            final String uri = getUriString(link);
            // Validate that the URI is valid according to allowed set of external uris
            try {
                validator.validate(uri);
            } catch (final ExternalMessageBodyException e) {
                LOGGER.warn("Rejected invalid external path {}", uri);
                throw e;
            }

            return new ExternalContentHandler(link);
        }

        return null;
    }

    private static String getUriString(final String link) {
        final String value = link.trim();
        if (value.startsWith("<")) {
            final int gtIndex = value.indexOf('>');
            if (gtIndex != -1) {
                return value.substring(1, gtIndex).trim();
            } else {
                throw new IllegalArgumentException("Missing token > in " + value);
            }
        } else {
            throw new IllegalArgumentException("Missing starting token < in " + value);
        }
    }

    /**
     * Set the external content path validator
     *
     * @param validator validator
     */
    public void setValidator(final ExternalContentPathValidator validator) {
        this.validator = validator;
    }
}


text:
package com.babarehner.android.xminder;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

import com.babarehner.android.xminder.data.ExerciseContract;

/**
 * Created by mike on 6/15/17.
 */

public class StrengthCursorAdapter extends CursorAdapter {

    public StrengthCursorAdapter(Context context, Cursor c) {
        super(context, c, 0 /* flags */);
    }

    /**
     * Creates a new blank list item with not data
     * @param context
     * @param cursor
     * @param parent
     * @return
     */
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.list_item_strength, parent, false);
    }

    /**
     * Binds data to the empty list item created above
     * @param v
     * @param context
     * @param c
     */
    @Override
    public void bindView(View v, Context context, Cursor c) {
        // find the id of the views to modify
        TextView exNameTextView = (TextView) v.findViewById(R.id.exercise_name);
        TextView effortTextView = (TextView) v.findViewById(R.id.effort_text_view);
        TextView durationTextView = (TextView) v.findViewById(R.id.duration_text_view);
        TextView setsTextView = (TextView) v.findViewById(R.id.set_num_text_view);

        int exNameColIndex = c.getColumnIndex(ExerciseContract.ExerciseEntry.C_EX_NAME);
        int exWeightColIndex = c.getColumnIndex(ExerciseContract.ExerciseEntry.C_WEIGHT);
        int exRepsColIndex = c.getColumnIndex(ExerciseContract.ExerciseEntry.C_REPS);
        int exSetsColIndex = c.getColumnIndex(ExerciseContract.ExerciseEntry.C_SETS);

        String exName = c.getString(exNameColIndex);
        String exWeight = c.getString(exWeightColIndex);
        String exReps = c.getString(exRepsColIndex);
        String exSets = c.getString(exSetsColIndex);

        exNameTextView.setText(exName);
        effortTextView.setText(exWeight);
        durationTextView.setText(exReps);
        setsTextView.setText((exSets));

    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="ChildList.cs" company="Marimer LLC">
//     Copyright (c) Marimer LLC. All rights reserved.
//     Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using Csla;
using Csla.Serialization;

namespace Csla.Test.PropertyGetSet
{
  [Serializable]
  public class ChildList : BusinessListBase<ChildList, EditableGetSet>
  {
    public ChildList()
    { }

    public ChildList(bool isChild)
    {
      MarkAsChild();
    }

    public new int EditLevel
    {
      get { return base.EditLevel; }
    }

    internal void Update()
    {
      foreach (var item in this)
        if (item.IsNew)
          item.Insert();
        else
          item.Update();
    }

  }
}


text:
package org.elasticsearch.monitor;

import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.monitor.fs.FsService;
import org.elasticsearch.monitor.jvm.JvmMonitorService;
import org.elasticsearch.monitor.jvm.JvmService;
import org.elasticsearch.monitor.network.NetworkService;
import org.elasticsearch.monitor.os.OsService;
import org.elasticsearch.monitor.process.ProcessService;

/**
 *
 */
public class MonitorService extends AbstractLifecycleComponent<MonitorService> {

    private final JvmMonitorService jvmMonitorService;

    private final OsService osService;

    private final ProcessService processService;

    private final JvmService jvmService;

    private final NetworkService networkService;

    private final FsService fsService;

    @Inject
    public MonitorService(Settings settings, JvmMonitorService jvmMonitorService,
                          OsService osService, ProcessService processService, JvmService jvmService, NetworkService networkService,
                          FsService fsService) {
        super(settings);
        this.jvmMonitorService = jvmMonitorService;
        this.osService = osService;
        this.processService = processService;
        this.jvmService = jvmService;
        this.networkService = networkService;
        this.fsService = fsService;
    }

    public OsService osService() {
        return this.osService;
    }

    public ProcessService processService() {
        return this.processService;
    }

    public JvmService jvmService() {
        return this.jvmService;
    }

    public NetworkService networkService() {
        return this.networkService;
    }

    public FsService fsService() {
        return this.fsService;
    }

    @Override
    protected void doStart() throws ElasticSearchException {
        jvmMonitorService.start();
    }

    @Override
    protected void doStop() throws ElasticSearchException {
        jvmMonitorService.stop();
    }

    @Override
    protected void doClose() throws ElasticSearchException {
        jvmMonitorService.close();
    }
}


text:
Paideia
=======

Paideia aims at making lives easier for all of us by bringing knowldege that we need in day to day lives one step closer to all of us. This is an android app using which one can point their phone at quite literally anything and get information about it. For instance, when you want to know more about the fruit that is sitting beside you or when you just want to "learn" more about the stuff that is around you, Paideia helps you start off. Here is some of the info given by Paideia about random stuff that is around us:

Seriously, the kind of information we get through Paideia by observing normal things around us is amazing!

##What can it do?

1. Detects objects around us.
2. Has inbuilt Text-to-speech system that can read it out. This can greatly help people with who are specially abled.
3. Extracts useful and relevant information from Wikipedia and Wolfram Alpha.
4. Users can set preferences which allows Paideia to customize what they see.

##How does it do?

1. We use a *deep learning* model trained using Tensorflow on Imagenet ILSVRC2012 data to recognize images from live feed.
2. We use API's provided by Wolfram Alpha and Wikipedia in order to extract relevant information to the user.
3. We use a simple learning approach to customize feeds for users based on their usage pattern.
4. Google tts system to read out information to the user.

##Who does it help?
1. Children who want to learn more.
2. Adults who want to learn more.
3. Specially abled people who want to learn more.
4. So basically, everyone who wanna learn more.

##Where can I get it?
Grab the apk from [release page](https://github.com/alseambusher/Paideia/releases).

##Setting up the codebase.
* Setup [Tensorflow](https://www.tensorflow.org/versions/r0.7/get_started/os_setup.html).
* Setup [Bazel](http://bazel.io/docs/install.html).
* Clone the repo in the root folder of tensorflow.
```bash
$ git clone https://github.com/alseambusher/Paideia
```
* Get model
```bash
$ wget https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip -O /tmp/inception5h.zip

$ unzip /tmp/inception5h.zip -d Paideia/assets/
```
* Building code
```bash
$ bazel build //Paideia:paideia
```
* Installation
```bash
$ adb install bazel-bin/Paideia/paideia.apk
```

##Contribiting
Pull requests and suggestions are welcome.


text:
import philosophy
from philosophy.exceptions import *
import sys
import time
import argparse

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def print_bold(msg):
    print(bcolors.BOLD, msg, bcolors.ENDC, sep='')

def print_err(msg):
    print(bcolors.FAIL, bcolors.BOLD, msg, bcolors.ENDC,
          sep='', file=sys.stderr)

def print_log(msg):
    print(bcolors.OKGREEN, msg, bcolors.ENDC, sep='')

def getargs():
    parser = argparse.ArgumentParser(description='Play The Philosophy Game')
    parser.add_argument('start', action='store', type=str,
                        metavar='start', nargs='?',
                        help='the initial Wikipedia pagename to start with')
    parser.add_argument('-e', '--end', action='store', default='Philosophy',
                        type=str, metavar='end', dest='end',
                        help='Wikipedia pagename to terminate at (default: \'Philosophy\')')
    parser.add_argument('-i', '--infinite', action='store_true',
                        help="""don't stop execution until a loop is found or
                                a valid link cannot be found""", dest='infinite')
    parser.add_argument('-t', '--times', action='store', dest='times',
                        default=1, type=int, metavar='times',
                        help="""run the script this many times, selecting a random
                                page every time except the first (default: 1)
                                (anything less than 1 is infinity)""")

    return parser.parse_args()

def process(names, args, times=1):
    raised = False
    start_time = time.time()
    try:
        link_count = -1
        for s in names:
            if s == args.end and not args.infinite:
                print_bold(s)
            else:
                print(s)
            link_count += 1
    except ConnectionError:
        print_err('Network error, please check your connection')
        sys.exit(1)

    except MediaWikiError as e:
        print_err('Error: {}: {}'.format(
            e.errors['code'],
            e.errors['info']))
        raised = True

    except LoopException as e:
        print_log('---\n{}, quitting...'.format(e))
        print_log('Visited {} link(s), got a loop, taking {} seconds'.format(
            link_count,
            round(time.time() - start_time, 4)))
        raised = True

    except InvalidPageNameError as e:
        print_err(e)
        raised = True

    except LinkNotFoundError as e:
        print_err(e)
        print_log('---')
        print_log(('Visited {} link(s), could not find appropriate link'
                   + ' in last link, taking {} seconds').format(
            link_count,
            round(time.time() - start_time, 4)))
        raised = True

    if not raised:
        print_log('---')
        print_log('Took {} hop(s) and {} seconds'.format(
            link_count,
            round(time.time() - start_time, 4)))

    if times == args.times:
        return

    # New line for separation
    print()

    names = philosophy.trace(end=args.end, infinite=args.infinite)
    process(names, args, times=times+1)

def main(args):
    start = args.start
    end = args.end
    infinite = args.infinite

    if start == '':
        start = None
    if args.end == '':
        end = 'Philosophy'

    names = philosophy.trace(page=start, end=end, infinite=infinite)
    process(names, args)

if __name__ == '__main__':
    try:
        args = getargs()
        if not sys.stdout.isatty():
            print_bold = print_log = print_err = print
        main(args)
    except KeyboardInterrupt:
        print_err('Script interrupted')
        sys.exit(1)


text:
package org.onosproject.provider.lldp.impl;

import static org.junit.Assert.*;
import static org.onosproject.net.DeviceId.deviceId;

import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.ChassisId;
import org.onosproject.net.Annotations;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.DefaultDevice;
import org.onosproject.net.DefaultPort;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.provider.ProviderId;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

public class SuppressionRulesTest {

    private static final DeviceId NON_SUPPRESSED_DID = deviceId("of:1111000000000000");
    private static final DeviceId SUPPRESSED_DID = deviceId("of:2222000000000000");
    private static final ProviderId PID = new ProviderId("of", "foo");
    private static final String MFR = "whitebox";
    private static final String HW = "1.1.x";
    private static final String SW1 = "3.8.1";
    private static final String SN = "43311-12345";
    private static final ChassisId CID = new ChassisId();

    private static final PortNumber P1 = PortNumber.portNumber(1);

    private SuppressionRules rules;

    @Before
    public void setUp() throws Exception {
        rules = new SuppressionRules(ImmutableSet.of(Device.Type.ROADM),
                               ImmutableMap.of("no-lldp", SuppressionRules.ANY_VALUE,
                                               "sendLLDP", "false"));
    }

    @Test
    public void testSuppressedDeviceType() {
        Device device = new DefaultDevice(PID,
                                          NON_SUPPRESSED_DID,
                                          Device.Type.ROADM,
                                          MFR, HW, SW1, SN, CID);
        assertTrue(rules.isSuppressed(device));
    }

    @Test
    public void testSuppressedDeviceAnnotation() {
        Annotations annotation = DefaultAnnotations.builder()
                .set("no-lldp", "random")
                .build();

        Device device = new DefaultDevice(PID,
                                          NON_SUPPRESSED_DID,
                                          Device.Type.SWITCH,
                                          MFR, HW, SW1, SN, CID, annotation);
        assertTrue(rules.isSuppressed(device));
    }

    @Test
    public void testSuppressedDeviceAnnotationExact() {
        Annotations annotation = DefaultAnnotations.builder()
                .set("sendLLDP", "false")
                .build();

        Device device = new DefaultDevice(PID,
                                          NON_SUPPRESSED_DID,
                                          Device.Type.SWITCH,
                                          MFR, HW, SW1, SN, CID, annotation);
        assertTrue(rules.isSuppressed(device));
    }

    @Test
    public void testNotSuppressedDevice() {
        Device device = new DefaultDevice(PID,
                                          NON_SUPPRESSED_DID,
                                          Device.Type.SWITCH,
                                          MFR, HW, SW1, SN, CID);
        assertFalse(rules.isSuppressed(device));
    }

    @Test
    public void testSuppressedPortAnnotation() {
        Annotations annotation = DefaultAnnotations.builder()
                .set("no-lldp", "random")
                .build();
        Device device = new DefaultDevice(PID,
                                          NON_SUPPRESSED_DID,
                                          Device.Type.SWITCH,
                                          MFR, HW, SW1, SN, CID);
        Port port = new DefaultPort(device, P1, true, annotation);

        assertTrue(rules.isSuppressed(port));
    }

    @Test
    public void testSuppressedPortAnnotationExact() {
        Annotations annotation = DefaultAnnotations.builder()
                .set("sendLLDP", "false")
                .build();
        Device device = new DefaultDevice(PID,
                                          NON_SUPPRESSED_DID,
                                          Device.Type.SWITCH,
                                          MFR, HW, SW1, SN, CID);
        Port port = new DefaultPort(device, P1, true, annotation);

        assertTrue(rules.isSuppressed(port));
    }

    @Test
    public void testNotSuppressedPort() {
        Device device = new DefaultDevice(PID,
                                          NON_SUPPRESSED_DID,
                                          Device.Type.SWITCH,
                                          MFR, HW, SW1, SN, CID);
        Port port = new DefaultPort(device, P1, true);

        assertFalse(rules.isSuppressed(port));
    }
}


text:
package org.innovateuk.ifs.application.forms.questions.team.controller;

import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.address.resource.AddressResource;
import org.innovateuk.ifs.address.resource.OrganisationAddressType;
import org.innovateuk.ifs.application.forms.questions.team.form.ApplicationTeamAddressForm;
import org.innovateuk.ifs.application.forms.questions.team.viewmodel.ApplicationTeamAddressViewModel;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.service.ApplicationOrganisationAddressRestService;
import org.innovateuk.ifs.application.service.ApplicationRestService;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.user.service.OrganisationRestService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.web.servlet.MvcResult;

import static org.innovateuk.ifs.address.builder.AddressResourceBuilder.newAddressResource;
import static org.innovateuk.ifs.address.resource.Countries.COUNTRIES;
import static org.innovateuk.ifs.application.builder.ApplicationResourceBuilder.newApplicationResource;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.organisation.builder.OrganisationResourceBuilder.newOrganisationResource;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(MockitoJUnitRunner.class)
public class ApplicationTeamAddressControllerTest extends BaseControllerMockMVCTest<ApplicationTeamAddressController> {

    @Override
    protected ApplicationTeamAddressController supplyControllerUnderTest() {
        return new ApplicationTeamAddressController();
    }

    @Mock
    private ApplicationOrganisationAddressRestService applicationOrganisationAddressRestService;

    @Mock
    private ApplicationRestService applicationRestService;

    @Mock
    private OrganisationRestService organisationRestService;

    @Test
    public void getAddress() throws Exception {
        AddressResource address = newAddressResource()
                .withAddressLine1("1 street lane")
                .withAddressLine2("somewhere")
                .withTown("some town")
                .withPostcode("zip")
                .withCountry("Swindonland")
                .build();

        ApplicationResource application = newApplicationResource().build();
        OrganisationResource organisation = newOrganisationResource().build();
        long questionId = 40L;

        when(applicationOrganisationAddressRestService.getAddress(application.getId(), organisation.getId(), OrganisationAddressType.INTERNATIONAL)).thenReturn(restSuccess(address));
        when(applicationRestService.getApplicationById(application.getId())).thenReturn(restSuccess(application));
        when(organisationRestService.getOrganisationById(organisation.getId())).thenReturn(restSuccess(organisation));

        MvcResult result = mockMvc.perform(get("/application/{applicationId}/form/question/{questionId}/team/organisation/{organisationId}/address", application.getId(), questionId, organisation.getId()))
                .andExpect(status().isOk())
                .andExpect(view().name("application/questions/application-team-address"))
                .andReturn();

        ApplicationTeamAddressViewModel actual = (ApplicationTeamAddressViewModel) result.getModelAndView().getModel().get("model");
        assertEquals(application.getId(), actual.getApplicationId());
        assertEquals(organisation.getName(), actual.getOrganisationName());
        assertEquals(questionId, actual.getQuestionId());
        assertEquals(COUNTRIES, actual.getCountries());

        ApplicationTeamAddressForm form = (ApplicationTeamAddressForm) result.getModelAndView().getModel().get("form");
        assertEquals(form.getAddressLine1(), address.getAddressLine1());
        assertEquals(form.getAddressLine2(), address.getAddressLine2());
        assertEquals(form.getTown(), address.getTown());
        assertEquals(form.getZipCode(), address.getPostcode());
        assertEquals(form.getCountry(), address.getCountry());
    }

    @Test
    public void updateAddress_validation() throws Exception {
        AddressResource address = newAddressResource()
                .withAddressLine1("1 street lane")
                .withAddressLine2("somewhere")
                .withTown("some town")
                .withPostcode("zip")
                .withCountry("Swindonland")
                .build();

        ApplicationResource application = newApplicationResource().build();
        OrganisationResource organisation = newOrganisationResource().build();
        long questionId = 40L;

        when(applicationRestService.getApplicationById(application.getId())).thenReturn(restSuccess(application));
        when(organisationRestService.getOrganisationById(organisation.getId())).thenReturn(restSuccess(organisation));

        mockMvc.perform(post("/application/{applicationId}/form/question/{questionId}/team/organisation/{organisationId}/address", application.getId(), questionId, organisation.getId()))
                .andExpect(view().name("application/questions/application-team-address"))
                .andExpect(model().attributeHasFieldErrorCode("form", "addressLine1", "NotBlank"))
                .andExpect(model().attributeHasFieldErrorCode("form", "town", "NotBlank"))
                .andExpect(model().attributeHasFieldErrorCode("form", "country", "NotBlank"));

        verify(applicationOrganisationAddressRestService, never()).updateAddress(anyLong(), anyLong(), any(), any());
    }

    @Test
    public void updateAddress() throws Exception {
        AddressResource address = newAddressResource()
                .withAddressLine1("1 street lane")
                .withAddressLine2("somewhere")
                .withTown("some town")
                .withPostcode("zip")
                .withCountry("Swindonland")
                .build();

        long applicationId = 1L;
        long organisationId = 2L;
        long questionId = 40L;

        when(applicationOrganisationAddressRestService.updateAddress(anyLong(), anyLong(), any(), any())).thenReturn(restSuccess());

        mockMvc.perform(post("/application/{applicationId}/form/question/{questionId}/team/organisation/{organisationId}/address", applicationId, questionId, organisationId)
                .param("addressLine1", address.getAddressLine1())
                .param("addressLine2", address.getAddressLine2())
                .param("town", address.getTown())
                .param("zipCode", address.getPostcode())
                .param("country", address.getCountry()))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl(String.format("/application/%d/form/question/%d/team", applicationId, questionId)));

        verify(applicationOrganisationAddressRestService, never()).updateAddress(anyLong(), anyLong(), any(), eq(address));
    }
}


text:
require 'spec_helper'

describe "gws_share_files", type: :feature, dbscope: :example, js: true do
  let(:site) { gws_site }
  let!(:folder) { create :gws_share_folder }
  let!(:category) { create :gws_share_category }
  let(:index_path) { gws_share_folder_files_path site, folder }
  let(:filepath) { tmpfile { |file| file.write('0123456789') } }
  let(:filesize) { ::File.size(filepath) }

  before { login_gws_user }

  context "when file is under quotas" do
    before do
      folder.share_max_file_size = filesize
      folder.share_max_folder_size = filesize
      folder.save!

      site.share_max_file_size = filesize
      site.share_files_capacity = filesize
      site.save!
    end

    it do
      visit index_path
      click_on I18n.t("ss.links.new")

      within "form#item-form" do
        within "#addon-basic" do
          click_on I18n.t("ss.links.upload")
        end
      end

      wait_for_ajax do
        attach_file "item[in_files][]", filepath
        click_on I18n.t("ss.buttons.attach")
      end

      within "form#item-form" do
        fill_in "item[memo]", with: unique_id
        within "footer.send" do
          click_on I18n.t("ss.links.upload")
        end
      end

      expect(page).to have_css('#notice', text: I18n.t('ss.notice.saved'))

      within "#gws-share-file-folder-list" do
        expect(page).to have_css(".tree-item", text: folder.name)
      end
    end
  end

  context "when file is over quotas" do
    shared_examples "over a quota" do
      it do
        visit index_path
        click_on I18n.t("ss.links.new")

        within "form#item-form" do
          within "#addon-basic" do
            click_on I18n.t("ss.links.upload")
          end
        end

        wait_for_ajax do
          attach_file "item[in_files][]", filepath
          click_on I18n.t("ss.buttons.attach")
        end

        within "form#item-form" do
          fill_in "item[memo]", with: unique_id
          within "footer.send" do
            click_on I18n.t("ss.links.upload")
          end
        end

        expect(page).to have_css("#errorExplanation", text: msg)
      end
    end

    context "over folder's share_max_file_size" do
      let(:msg) do
        I18n.t(
          "mongoid.errors.models.gws/share/file.file_size_exceeds_limit",
          size: filesize.to_s(:human_size), limit: folder.share_max_file_size.to_s(:human_size)
        )
      end

      before do
        folder.share_max_file_size = filesize - 1
        folder.save!
      end

      include_context "over a quota"
    end

    context "over folder's share_max_folder_size" do
      let(:msg) do
        I18n.t(
          "mongoid.errors.models.gws/share/file.file_size_exceeds_folder_limit",
          size: filesize.to_s(:human_size), limit: folder.share_max_folder_size.to_s(:human_size)
        )
      end

      before do
        folder.share_max_folder_size = filesize - 1
        folder.save!
      end

      include_context "over a quota"
    end

    context "over site's share_max_file_size" do
      let(:msg) do
        I18n.t(
          "mongoid.errors.models.gws/share/file.file_size_exceeds_limit",
          size: filesize.to_s(:human_size), limit: site.share_max_file_size.to_s(:human_size)
        )
      end

      before do
        site.share_max_file_size = filesize - 1
        site.save!
      end

      include_context "over a quota"
    end

    context "over site's share_files_capacity" do
      let(:msg) do
        I18n.t(
          "mongoid.errors.models.gws/share/file.file_size_exceeds_capacity",
          size: filesize.to_s(:human_size), limit: site.share_files_capacity.to_s(:human_size)
        )
      end

      before do
        site.share_files_capacity = filesize - 1
        site.save!
      end

      include_context "over a quota"
    end
  end

  context "when file is over quotas on updating" do
    let(:filepath2) { tmpfile { |file| file.write('0123456789' + '0') } }
    let(:filesize2) { ::File.size(filepath2) }
    let(:msg) do
      I18n.t(
        "mongoid.errors.models.gws/share/file.file_size_exceeds_capacity",
        size: filesize2.to_s(:human_size), limit: site.share_files_capacity.to_s(:human_size)
      )
    end

    before do
      folder.share_max_file_size = filesize
      folder.share_max_folder_size = filesize
      folder.save!

      site.share_max_file_size = filesize
      site.share_files_capacity = filesize
      site.save!

      Fs::UploadedFile.create_from_file(filepath, content_type: 'application/octet-stream') do |f|
        create(:gws_share_file, folder: folder, in_file: f)
      end
    end

    it do
      visit index_path
      click_on ::File.basename(filepath)
      click_on I18n.t("ss.links.edit")

      within "form#item-form" do
        attach_file "item[in_file]", filepath2
        click_on I18n.t("ss.buttons.save")
      end

      expect(page).to have_css("#errorExplanation", text: msg)
    end
  end
end


text:
#ifndef __CCDEVICE_H__
#define __CCDEVICE_H__

#include "CCPlatformMacros.h"
#include "ccMacros.h"
#include "CCData.h"

NS_CC_BEGIN

struct FontDefinition;

class CC_DLL Device
{
public:
    enum class TextAlign
    {
        CENTER        = 0x33, ///< Horizontal center and vertical center.
        TOP           = 0x13, ///< Horizontal center and vertical top.
        TOP_RIGHT     = 0x12, ///< Horizontal right and vertical top.
        RIGHT         = 0x32, ///< Horizontal right and vertical center.
        BOTTOM_RIGHT = 0x22, ///< Horizontal right and vertical bottom.
        BOTTOM        = 0x23, ///< Horizontal center and vertical bottom.
        BOTTOM_LEFT  = 0x21, ///< Horizontal left and vertical bottom.
        LEFT          = 0x31, ///< Horizontal left and vertical center.
        TOP_LEFT      = 0x11, ///< Horizontal left and vertical top.
    };
    /**
     *  Gets the DPI of device
     *  @return The DPI of device.
     */
    static int getDPI();

    /**
     * To enable or disable accelerometer.
     */
    static void setAccelerometerEnabled(bool isEnabled);
    /**
     *  Sets the interval of accelerometer.
     */
    static void setAccelerometerInterval(float interval);

    static Data getTextureDataForText(const char * text,const FontDefinition& textDefinition,TextAlign align,int &widht,int &height);

private:
    CC_DISALLOW_IMPLICIT_CONSTRUCTORS(Device);
};

NS_CC_END

#endif /* __CCDEVICE_H__ */


text:
#ifndef __ASM_TRAP_H
#define __ASM_TRAP_H

static inline int in_exception_text(unsigned long ptr)
{
	extern char __exception_text_start[];
	extern char __exception_text_end[];

	return ptr >= (unsigned long)&__exception_text_start &&
	       ptr < (unsigned long)&__exception_text_end;
}

#endif


text:
package uk.org.whoami.authme.gui.screens;

/**
 * @Author Hoezef
 */
import java.util.List;

import org.getspout.spoutapi.event.screen.ButtonClickEvent;
import org.getspout.spoutapi.gui.Button;
import org.getspout.spoutapi.gui.Color;
import org.getspout.spoutapi.gui.GenericLabel;
import org.getspout.spoutapi.gui.GenericPopup;
import org.getspout.spoutapi.gui.GenericTextField;
import org.getspout.spoutapi.gui.Widget;
import org.getspout.spoutapi.gui.WidgetAnchor;
import org.getspout.spoutapi.player.SpoutPlayer;

import uk.org.whoami.authme.AuthMe;
import uk.org.whoami.authme.gui.Clickable;
import uk.org.whoami.authme.gui.CustomButton;
import uk.org.whoami.authme.settings.SpoutCfg;

public class LoginScreen extends GenericPopup implements Clickable{

	private SpoutPlayer splayer;
	private AuthMe plugin = AuthMe.getInstance();
	private SpoutCfg spoutCfg = SpoutCfg.getInstance();

	private CustomButton exitBtn;
	private CustomButton loginBtn;
	private GenericTextField passBox;
	private GenericLabel titleLbl;
	private GenericLabel textLbl;
	private GenericLabel errorLbl;

	String exitTxt = spoutCfg.getString("LoginScreen.exit button"); //"Quit";
	String loginTxt = spoutCfg.getString("LoginScreen.login button"); //"Login";
	String exitMsg = spoutCfg.getString("LoginScreen.exit message"); //"Good Bye";
	String title = spoutCfg.getString("LoginScreen.title"); //"LOGIN"
	List<String> textlines = spoutCfg.getStringList("LoginScreen.text");

	public LoginScreen(SpoutPlayer player) {
		this.splayer = player;

		createScreen();
	}

	private void createScreen() {
		int objects = textlines.size() + 4;
		int part = !(textlines.size() <= 5) ? 195 / objects : 20;
		int h = 3*part/4, w = 8*part;

		titleLbl = new GenericLabel();
		titleLbl
			.setText(title)
			.setTextColor(new Color(1.0F, 0, 0, 1.0F))
			.setAlign(WidgetAnchor.TOP_CENTER)
			.setHeight(h)
			.setWidth(w)
			.setX(maxWidth / 2 )
			.setY(25);
		this.attachWidget(plugin, titleLbl);

		int ystart = 25 + h + part/2;
		for (int x=0; x<textlines.size();x++)
		{
			textLbl = new GenericLabel();
			textLbl
				.setText(textlines.get(x))
				.setAlign(WidgetAnchor.TOP_CENTER)
				.setHeight(h)
				.setWidth(w)
				.setX(maxWidth / 2)
				.setY(ystart + x*part);
			this.attachWidget(plugin, textLbl);
		}

		passBox = new GenericTextField();
		passBox
			.setMaximumCharacters(18)
			.setMaximumLines(1)
			.setHeight(h-2)
			.setWidth(w-2)
			.setY(220-h - 2*part);
		passBox.setPasswordField(true);
		setXToMid(passBox);
		this.attachWidget(plugin, passBox);

		errorLbl = new GenericLabel();
		errorLbl
			.setText("")
			.setTextColor(new Color(1.0F, 0, 0, 1.0F))
			.setHeight(h)
			.setWidth(w)
			.setX(passBox.getX() + passBox.getWidth() + 2)
			.setY(passBox.getY());
		this.attachWidget(plugin, errorLbl);

		loginBtn = new CustomButton(this);
		loginBtn
			.setText(loginTxt)
			.setHeight(h)
			.setWidth(w)
			.setY(220-h-part);
		setXToMid(loginBtn);
		this.attachWidget(plugin, loginBtn);

		exitBtn = new CustomButton(this);
		exitBtn
			.setText(exitTxt)
			.setHeight(h)
			.setWidth(w)
			.setY(220-h);
		setXToMid(exitBtn);
		this.attachWidget(plugin, exitBtn);

	}

	public void handleClick(ButtonClickEvent event) {
		Button b = event.getButton();
		if (b.equals(loginBtn))
		{
			//System.out.println("player: " + event.getPlayer().getName() + ", Password: " + passBox.getText() + ", Management: " + plugin.management + ", Plugin: " + plugin);
			String result = plugin.management.performLogin(event.getPlayer(), passBox.getText());
			if(result == "") event.getPlayer().closeActiveWindow();
			else
			{
				errorLbl.setText(result);
				passBox.setText("");
			}
		}else if(b.equals(exitBtn))
		{
			event.getPlayer().kickPlayer(exitMsg);
		}
	}

	private void setXToMid(Widget w) {
		w.setX( (maxWidth - w.getWidth()) / 2);
	}

}


text:
struct worldSize {
	unsigned voxelsWide;
	unsigned voxelsHigh;
	unsigned voxelsDeep;

	worldSize(unsigned vw, unsigned vh, unsigned vd) : voxelsWide(vw), voxelsHigh(vh), voxelsDeep(vd)
	{
		if (vw % IChunk::Width > 0 || vh % IChunk::Height > 0 || vd % IChunk::Depth > 0)
		{
			throw VoxelEngineException("Width, height and depth must be a multiple of IChunk::Width, IChunk::Height and IChunk::Depth respectively");
		}
	}
};


text:
package org.apache.felix.metatype;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.felix.metatype.internal.Activator;
import org.osgi.service.log.LogService;
import org.osgi.service.metatype.AttributeDefinition;

/**
 * The AD class represents the AD element of the
 * meta type descriptor.
 *
 * @author Felix Project Team
 */
public class AD extends OptionalAttributes
{

    /**
     * The message returned from the {@link #validate(String)} method if the
     * value is not any of the specified {@link #getOptionValues() option values}
     * (value is "%not a valid option").
     */
    public static final String VALIDATE_NOT_A_VALID_OPTION = "%not a valid option";

    /**
     * The message returned from the {@link #validate(String)} method if the
     * value is invalid considering its type (value is "%invalid value").
     */
    public static final String VALIDATE_INVALID_VALUE = "%invalid value";

    /**
     * The message returned from the {@link #validate(String)} method if the
     * value is greater than the specified {@link #getMax() maximum value}
     * (value is "%greater than maximum").
     */
    public static final String VALIDATE_GREATER_THAN_MAXIMUM = "%greater than maximum";

    /**
     * The message returned from the {@link #validate(String)} method if the
     * value is less than the specified {@link #getMin() minimum value}
     * (value is "%less than minimum").
     */
    public static final String VALIDATE_LESS_THAN_MINIMUM = "%less than minimum";

    /**
     * The message returned from the {@link #validate(String)} method if the
     * value is null or cannot be converted to an attribute value and a value
     * is {@link #isRequired() required} (value is "%missing required value").
     */
    public static final String VALIDATE_MISSING = "%missing required value";

    private String id;
    private String name;
    private String description;
    private int type;
    private int cardinality = 0;
    private String[] optionLabels;
    private String[] optionValues;
    private String[] defaultValue;
    private String min;
    private String max;
    private boolean isRequired = true;

    public String getID()
    {
        return id;
    }

    public String getName()
    {
        return name;
    }

    public String getDescription()
    {
        return description;
    }

    public int getType()
    {
        return type;
    }

    public int getCardinality()
    {
        return cardinality;
    }

    public String[] getOptionLabels()
    {
        return optionLabels;
    }

    public String[] getOptionValues()
    {
        return optionValues;
    }

    public String[] getDefaultValue()
    {
        return defaultValue;
    }

    public String getMin()
    {
        return min;
    }

    public String getMax()
    {
        return max;
    }

    public boolean isRequired()
    {
        return isRequired;
    }

    /**
     * Implements validation of the valueString and returns an
     * indication of the validation result.
     *
     * @param valueString The string representation of the value to validate,
     *        can be null.
     *
     * @return null if no validation is performed, <tt>""</tt> if
     *         the value is accepted as valid, or a non-empty string
     *         indicating a validation problem was found.
     *
     * @see ADValidator#validate(AD, String)
     * @see #VALIDATE_GREATER_THAN_MAXIMUM
     * @see #VALIDATE_NOT_A_VALID_OPTION
     * @see #VALIDATE_LESS_THAN_MINIMUM
     * @see #VALIDATE_INVALID_VALUE
     * @see #VALIDATE_MISSING
     */
    public String validate(String valueString)
    {
        return ADValidator.validate(this, valueString);
    }

    //--------- Setters for setting up this instance --------------------------

    /**
     * @param id the id to set
     */
    public void setID(String id)
    {
        this.id = id;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name)
    {
        this.name = name;
    }

    /**
     * @param description the description to set
     */
    public void setDescription(String description)
    {
        this.description = description;
    }

    /**
     * @param typeString the type to set
     */
    public void setType(String typeString)
    {
        this.type = toType(typeString);
    }

    /**
     * @param cardinality the cardinality to set
     */
    public void setCardinality(int cardinality)
    {
        this.cardinality = cardinality;
    }

    /**
     * @param options the options to set
     */
    public void setOptions(Map options)
    {
        if (options.size() == 0) {
            optionLabels = null;
            optionValues = null;
            return;
        }

        optionLabels = new String[options.size()];
        optionValues = new String[options.size()];
        int i = 0;
        for (Iterator oi = options.entrySet().iterator(); oi.hasNext(); i++)
        {
            Map.Entry entry = (Map.Entry) oi.next();
            optionValues[i] = String.valueOf(entry.getKey());
            optionLabels[i] = String.valueOf(entry.getValue());
        }
    }

    /**
     * Sets the default value(s) for this AD.
     *

     * NOTE: this method is depending on the value of {@link #getCardinality()}! Make sure that the
     * cardinality is properly set before calling this method.
     *

     *
     * @param defaultValue the default value to set, as encoded string-value (using comma's as separator), can be null.
     */
    public void setDefaultValue(String defaultValue)
    {
        setDefaultValue(splitList(defaultValue), Math.abs(this.cardinality));
    }

    /**
     * @param min the min to set
     */
    public void setMin(String min)
    {
        this.min = min;
    }

    /**
     * @param max the max to set
     */
    public void setMax(String max)
    {
        this.max = max;
    }

    /**
     * @param isRequired the isRequired to set
     */
    public void setRequired(boolean isRequired)
    {
        this.isRequired = isRequired;
    }

    public static int toType(String typeString)
    {
        if ("String".equals(typeString))
        {
            return AttributeDefinition.STRING;
        }
        else if ("Long".equals(typeString))
        {
            return AttributeDefinition.LONG;
        }
        else if ("Double".equals(typeString))
        {
            return AttributeDefinition.DOUBLE;
        }
        else if ("Float".equals(typeString))
        {
            return AttributeDefinition.FLOAT;
        }
        else if ("Integer".equals(typeString))
        {
            return AttributeDefinition.INTEGER;
        }
        else if ("Byte".equals(typeString))
        {
            return AttributeDefinition.BYTE;
        }
        else if ("Character".equals(typeString) || "Char".equals(typeString))
        {
            return AttributeDefinition.CHARACTER;
        }
        else if ("Boolean".equals(typeString))
        {
            return AttributeDefinition.BOOLEAN;
        }
        else if ("Short".equals(typeString))
        {
            return AttributeDefinition.SHORT;
        }
        else if ("Password".equals(typeString))
        {
            return AttributeDefinition.PASSWORD;
        }

        // finally fall back to string for illegal values
        return AttributeDefinition.STRING;
    }

    public static String[] splitList(String listString)
    {
        if (listString == null)
        {
            return null;
        }
        else if (listString.length() == 0)
        {
            return new String[] { "" };
        }

        List<String> strings = new ArrayList<>();
        StringBuilder sb = new StringBuilder();

        int length = listString.length();
        boolean escaped = false;
        int spaceCount = 0;
        boolean start = true;
        for (int i = 0; i < length; i++)
        {
            char ch = listString.charAt(i);
            final boolean isWhitespace = Character.isWhitespace(ch);
            if (start)
            {
                if (isWhitespace)
                {
                    continue;
                }
                start = false;
            }
            if (ch == '\\')
            {
                if (!escaped)
                {
                    escaped = true;
                    continue;
                }
            }
            else if (ch == ',')
            {
                if (!escaped)
                {
                    // unescaped comma, this is a string delimiter...
                    strings.add(sb.toString());
                    sb.setLength(0);
                    start = true;
                    spaceCount = 0;
                    continue;
                }
            }
            else if (ch == ' ')
            {
                // space is only ignored at beginning and end but not if escaped
                if (!escaped)
                {
                    spaceCount++;
                    continue;
                }
            }
            else if (isWhitespace)
            {
                // Other whitespaces are ignored...
                continue;
            }

            if (spaceCount > 0)
            {
                for (int m = 0; m < spaceCount; m++)
                {
                    sb.append(" ");
                }
                spaceCount = 0;
            }
            sb.append(ch);
            escaped = false;
        }

        // Always add the last string, as it contains everything after the last comma...
        strings.add(sb.toString());

        return strings.toArray(new String[strings.size()]);
    }

    protected Comparable convertToType(final String value)
    {
        if (value != null && value.length() > 0)
        {
            try
            {
                switch (getType())
                {
                    case AttributeDefinition.BOOLEAN:
                        // Boolean is only Comparable starting with Java 5
                        return new ComparableBoolean(value);
                    case AttributeDefinition.CHARACTER:
                        return new Character(value.charAt(0));
                    case AttributeDefinition.BYTE:
                        return Byte.valueOf(value);
                    case AttributeDefinition.SHORT:
                        return Short.valueOf(value);
                    case AttributeDefinition.INTEGER:
                        return Integer.valueOf(value);
                    case AttributeDefinition.LONG:
                        return Long.valueOf(value);
                    case AttributeDefinition.FLOAT:
                        return Float.valueOf(value);
                    case AttributeDefinition.DOUBLE:
                        return Double.valueOf(value);
                    case AttributeDefinition.STRING:
                    case AttributeDefinition.PASSWORD:
                    default:
                        return value;
                }
            }
            catch (NumberFormatException nfe)
            {
                Activator.log(LogService.LOG_INFO, "Cannot convert value '" + value + "'", nfe);
            }
        }

        return null;
    }

    /**
     * @param values the defaultValue to set
     */
    protected void setDefaultValue(String[] values, int cardinality)
    {
        if (values != null)
        {
            int count = 0;
            int max = Math.min(values.length, Math.max(1, cardinality));
            for (int i = 0; count < max && i < values.length; i++)
            {
                if ("".equals(ADValidator.validate(this, values[i])))
                {
                    count++;
                }
                else
                {
                    values[i] = null;
                }
            }
            if (count == 0)
            {
                values = cardinality == 0 ? null : new String[0];
            }
            else if (count != values.length)
            {
                String[] filterValues = new String[count];
                int index = 0;
                for (int i = 0; index < count && i < values.length; i++)
                {
                    if (values[i] != null)
                    {
                        filterValues[index] = values[i];
                        index++;
                    }
                }
                values = filterValues;
            }
        }
        this.defaultValue = values;
    }

    private static class ComparableBoolean implements Comparable
    {
        private boolean value;

        ComparableBoolean(String boolValue)
        {
            value = Boolean.valueOf(boolValue).booleanValue();
        }

        @Override
        public int compareTo(Object obj)
        {
            ComparableBoolean cb = (ComparableBoolean) obj;
            return (cb.value == value ? 0 : (value ? 1 : -1));
        }
    }
}


text:
package org.apache.flink.runtime.rpc;

import org.apache.flink.core.testutils.CustomExtension;
import org.apache.flink.util.Preconditions;

import org.junit.jupiter.api.extension.ExtensionContext;

import javax.annotation.Nullable;

import java.util.concurrent.CompletableFuture;

/** Custom extension that starts a {@link TestingRpcService}. */
public class TestingRpcServiceExtension implements CustomExtension {

    @Nullable private TestingRpcService testingRpcService;

    public TestingRpcServiceExtension() {
        this.testingRpcService = null;
    }

    public TestingRpcService getTestingRpcService() {
        Preconditions.checkNotNull(testingRpcService);
        return testingRpcService;
    }

    @Override
    public void before(ExtensionContext extensionContext) {
        if (testingRpcService != null) {
            terminateRpcService(testingRpcService);
        }

        testingRpcService = new TestingRpcService();
    }

    @Override
    public void after(ExtensionContext extensionContext) {
        if (testingRpcService != null) {
            terminateRpcService(testingRpcService);
            testingRpcService = null;
        }
    }

    private void terminateRpcService(TestingRpcService testingRpcService) {
        CompletableFuture<Void> terminationFuture = testingRpcService.stopService();
        terminationFuture.join();
    }
}


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

<title>org.hibernate.internal.util.collections (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.hibernate.internal.util.collections

Interface Summary

Interface
Description

BoundedConcurrentHashMap.EvictionListener<K,V>

BoundedConcurrentHashMap.EvictionPolicy<K,V>

Class Summary

Class
Description

ArrayHelper

BoundedConcurrentHashMap<K,V>

CollectionHelper

ConcurrentReferenceHashMap<K,V>

EmptyIterator

IdentityMap<K,V>

IdentityMap.IdentityKey<K>

IdentityMap.IdentityMapEntry<K,V>

IdentitySet

JoinedIterable<T>

JoinedIterator<T>

LazyIterator

SingletonIterator

Enum Summary

Enum
Description

BoundedConcurrentHashMap.Eviction

ConcurrentReferenceHashMap.Option

ConcurrentReferenceHashMap.ReferenceType

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
Order #{{orderId}}

You need to send ฿{{Market.modalOrder.total_price}} to the payment address {{Market.modalOrder.address}} and mark this order as paid before the merchant ships.

So far there is ฿{{Market.modalOrder.payment_amount}} in the address

                                    <button type="button" class="btn btn-warning"> Pay in your Wallet</button>
                                    <button data-ng-click="markOrderPaid(orderId)" class="btn btn-info"> Mark as Paid</button>
                                    <button data-ng-click="" class="btn btn-danger"> Cancel Order</button>

Shipping & Payment

                        <form name="releasePaymentForm" novalidate>

This order has been paid for by the buyer. You should verify the funds have been sent and then ship the
                            goods. Once you've done this you can enter your payment address and notify the buyer.

                                Where would you like payment sent to?

                                <input type="text" required class="form-control text" name="bitcoinPaymentAddress" data-ng-model="Market.modalOrder.paymentAddress" placeholder="Enter a Bitcoin address"/>

                                    <button id="send-order-button" data-ng-click="markOrderShipped(orderId)" class="{{releasePaymentForm.bitcoinPaymentAddress.$invalid ? 'disabled' : ''}} btn btn-info"> Request Payment</button>

                        </form>

Once you've received your order and are satisfied please release your payment to the seller.

                        <button id="send-order-button" data-ng-click="markOrderReceived(orderId)" class="btn btn-sm btn-info"> Release Payment to Merchant</button>

Order

Contract Details

Shipping Information

{{Market.modalOrder.item_title}}

            {{Market.modalOrder.item_desc}}

                            Order Date:
                            {{Market.modalOrder.updated*1000 | date:'medium'}}

                            Status:
                            {{Market.modalOrder.state}} Waiting for Shipment

                            Contract Price:
                            ฿{{Market.modalOrder.item_price}}

                            Shipping Price:
                            ฿{{Market.modalOrder.shipping_price}}

                            Payment Address:
                            {{Market.modalOrder.address}}

                            Amount in Payment Address:
                            ฿{{Market.modalOrder.payment_amount}}

                            Note to Merchant:
                            {{Market.modalOrder.note_for_merchant}}
                                {{!Market.modalOrder.note_for_merchant ? 'No message specified' : ''}}

                Buyer:
                {{Market.modalOrder.buyer}}

                Merchant:
                {{Market.modalOrder.merchant}}

                Notary:
                {{Market.modalOrder.notary}}

                Payment Address:
                {{Market.modalOrder.address}}

                Raw Contract:

{{Market.modalOrder.signed_contract_body}}

        <address>
          {{Market.modalOrder.shipping_address.recipient_name}}

          {{Market.modalOrder.shipping_address.street1}}

          {{Market.modalOrder.shipping_address.street2}}

          {{Market.modalOrder.shipping_address.city}}, {{Market.modalOrder.shipping_address.stateRegion}} {{Market.modalOrder.shipping_address.zip}}
        </address>

                    <button class="btn btn-info" data-ng-click="cancel()">Close</button>


text:
package com.github.czyzby.autumn.mvc.config;

import com.badlogic.gdx.assets.AssetLoaderParameters;

/** Contains all messages posted by Autumn MVC components using a
 * {@link com.github.czyzby.autumn.processor.event.MessageDispatcher}.
 *
 * @author MJ */
public class AutumnMessage {
    /** Can be extended to contain all application's messages, but should not be initiated. */
    protected AutumnMessage() {
    }

    /** Posted each time SOME assets scheduled with {@link com.github.czyzby.autumn.mvc.component.asset.AssetService}
     * are loaded. This is not posted if assets where loaded on demand with
     * {@link com.github.czyzby.autumn.mvc.component.asset.AssetService#finishLoading(String, Class)} or
     * {@link com.github.czyzby.autumn.mvc.component.asset.AssetService#finishLoading(String, Class, AssetLoaderParameters)}
     * methods. */
    public static final String ASSETS_LOADED = "AMVC_assetsLoaded";

    /** Posted when all application's {@link com.badlogic.gdx.scenes.scene2d.ui.Skin}s are fully loaded. */
    public static final String SKINS_LOADED = "AMVC_skinsLoaded";

    /** Posted when the game's window is resized. Posted AFTER
     * {@link com.github.czyzby.autumn.mvc.component.ui.InterfaceService} resizes current view (if any is present). */
    public static final String GAME_RESIZED = "AMVC_gameResized";

    /** Posted when the game is paused. Posted AFTER {@link com.github.czyzby.autumn.mvc.component.ui.InterfaceService}
     * pauses current view (if any is present). */
    public static final String GAME_PAUSED = "AMVC_gamePaused";

    /** Posted when the game is resumed. Posted AFTER {@link com.github.czyzby.autumn.mvc.component.ui.InterfaceService}
     * resumes current view (if any is present). */
    public static final String GAME_RESUMED = "AMVC_gameResumed";
}


text:
  Vindrac-Alayrac est
       un village
       situé dans le département de Tarn en Midi-Pyrénées. Elle comptait 152 habitants en 2008.

Le nombre d'habitations, à Vindrac-Alayrac, se décomposait en 2011 en trois appartements et 109 maisons soit
 un marché relativement équilibré.

À coté de Vindrac-Alayrac sont positionnées géographiquement les villes de
Itzac située à 5 km, 127 habitants,
Bournazel à 5 km, 160 habitants,
Mouzieys-Panens localisée à 3 km, 206 habitants,
Alos localisée à 5 km, 124 habitants,
Amarens à 3 km, 68 habitants,
Labarthe-Bleys située à 1 km, 83 habitants,
 entre autres. De plus, Vindrac-Alayrac est située à seulement 24 km de Albi.

Si vous pensez demenager à Vindrac-Alayrac, vous pourrez aisément trouver une maison à vendre.

La ville offre quelques  aménagements, elle propose entre autres une boucle de randonnée.


text:
/*
 */
package org.redkale.test.convert;

import java.util.*;
import org.junit.jupiter.api.*;
import org.redkale.convert.json.*;

/**
 *
 * @author zhangjx
 */
public class MapIgnoreColumnTest {

    private boolean main;

    public static void main(String[] args) throws Throwable {
        MapIgnoreColumnTest test = new MapIgnoreColumnTest();
        test.main = true;
        test.run();
    }

    @Test
    public void run() throws Exception {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("aaa", "123");
        map.put("bbb", List.of(1, 2));
        System.out.println(JsonConvert.root().convertTo(map));
        JsonFactory factory = JsonFactory.create();
        factory.register(Map.class, true, "aaa");
        JsonConvert convert = factory.getConvert();
        String rs = "{\"bbb\":[1,2]}";
        if (!main) Assertions.assertEquals(rs, convert.convertTo(map));
        System.out.println(convert.convertTo(map));
        JsonConvert convert2 = JsonConvert.root().newConvert((k, v) -> {
            if ("bbb".equals(k)) return null;
            return v;
        }, null, null);
        if (!main) Assertions.assertEquals("{\"aaa\":\"123\",\"bbb\":null}", convert2.convertTo(map));
        System.out.println(convert2.convertTo(map));
    }

}


text:
'use strict';

const should = require('should');
const PassStream = require('pass-stream');
const jayson = require('./..');
const utils = jayson.utils;

describe('jayson.utils', function() {

  describe('request', function() {

    it('exists', function() {
      utils.should.have.property('request');
      utils.request.should.be.a.Function;
    });

    it('should throw a TypeError on invalid version', function () {
      should(function() {
        utils.request('method', [1, 2,], null, {version: 9});
      }).throw(TypeError);
    });

    it('should throw a TypeError on an invalid method argument', function() {
      (function() {
        utils.request(null, [1, 2,], null);
      }).should.throw(TypeError);
    });

    it('should throw a TypeError on an invalid params argument', function() {
      (function() {
        utils.request('a_method', true);
      }).should.throw(TypeError);
    });

    it('should omit the params argument when not given', function() {
      const request = utils.request('a_method', null);
      request.should.have.property('method', 'a_method');
      request.should.not.have.property('params');
    });

    it('should set the id to null when making a notification version 1 request', function () {
      const request = utils.request('notification', [], null, {version: 1});
      should(request).have.property('id', null);
    });

    it('should omit the id when making a notification version 2 request', function () {
      const request = utils.request('notification', [], null, {version: 2});
      should(request).not.have.property('id');
    });

    it('should set the id to null when making a notification version 2 request with option notificationIdNull = true', function () {
      const request = utils.request('notification', [], null, {
        version: 2,
        notificationIdNull: true,
      });
      should(request).have.property('id', null);
    });

  });

  describe('response', function() {

    it('exists', function() {
      utils.should.have.property('response');
      utils.response.should.be.a.Function;
    });

    it('should set result to null when no error or result provided', function() {
      const result = utils.response(undefined, undefined, 'something', 2);
      should(result).eql({ jsonrpc: '2.0', id: 'something', result: null });
    });

  });

  describe('parseBody', function() {

    const parseBody = utils.parseBody;

    it('should parse a valid json object', function(done) {
      const stream = new PassStream();
      const obj = {asdf: true, complex: {value: 2, a: 3}};

      parseBody(stream, {}, function(err, result) {
        if(err) return done(err);
        obj.should.eql(result);
        done();
      });

      stream.end(JSON.stringify(obj));
    });

    it('should parse a valid json array', function(done) {
      const stream = new PassStream();
      const arr = [{first: true}, {asdf: true, complex: {value: 2, a: 3}}];

      parseBody(stream, {}, function(err, result) {
        if(err) return done(err);
        arr.should.eql(result);
        done();
      });

      stream.end(JSON.stringify(arr));
    });

    it('should return an error on bad input', function(done) {
      const stream = new PassStream();

      parseBody(stream, {}, function(err, result) {
        should(err).be.instanceof(Error);
        done();
      });

      stream.end("\"");
    });

  });

  describe('JSON.stringify', function(done) {

    it('should not throw with circular JSON reference', function(done) {

      const foo = {};
      const bar = { foo: foo };
      foo.bar = bar;

      const fn = utils.JSON.stringify(bar, {}, function(err, str) {
        should(err).not.exist;
        done();
      });

      should(fn).not.throw();
    });

  });

  describe('Response.isValidResponse', function() {

    const specs = [
      {
        desc: 'a valid 2 response',
        response: {jsonrpc: '2.0', result: null, id: 'something'},
        version: 2,
        expected: true,
      },
      {
        desc: 'a valid 2 response',
        response: {jsonrpc: '2.0', result: null, id: null},
        version: 2,
        expected: true,
      },
      {
        desc: 'a valid 2 error response with data',
        response: {jsonrpc: '2.0', id: 'something', error: {code: 123, message: 'something', data: {}}},
        version: 2,
        expected: true,
      },
      {
        desc: 'a valid 2 error response without data',
        response: {jsonrpc: '2.0', id: 'something', error: {code: 123, message: 'something'}},
        version: 2,
        expected: true,
      },
      {
        desc: 'an invalid 2 response (both error and result properties)',
        response: {jsonrpc: '2.0', id: 'something', error: {code: 123, message: 'something'}, result: null},
        version: 2,
        expected: false,
      },
      {
        desc: 'an invalid 2 response (no result or error)',
        response: {jsonrpc: '2.0', id: 'something'},
        version: 2,
        expected: false,
      },
      {
        desc: 'an invalid 2 error response (no code)',
        response: {jsonrpc: '2.0', id: 'something', error: {message: 'something'}},
        version: 2,
        expected: false,
      },
      {
        desc: 'an invalid 2 error response (no message)',
        response: {jsonrpc: '2.0', id: 'something', error: {code: 123}},
        version: 2,
        expected: false,
      },
      {
        desc: 'an invalid 2 error response (code not number)',
        response: {jsonrpc: '2.0', id: 'something', error: {code: '123', message: 'asdf'}},
        version: 2,
        expected: false,
      },
      {
        desc: 'an invalid 2 error response (code not integer)',
        response: {jsonrpc: '2.0', id: 'something', error: {code: 123.3, message: 'asdf'}},
        version: 2,
        expected: false,
      },
      {
        desc: 'an invalid 2 response (invalid error and contains result property)',
        response: {jsonrpc: '2.0', id: 'something', error: {}, result: {}},
        version: 2,
        expected: false,
      },
      {
        desc: 'an invalid 2 response (no jsonrpc property)',
        response: {id: 'something', result: {}},
        version: 2,
        expected: false,
      },
      {
        desc: 'an invalid 2 response (jsonrpc property not equal to 2.0)',
        response: {jsonrpc: '3.0', id: 'something', result: {}},
        version: 2,
        expected: false,
      },
      {
        desc: 'an invalid 2 response (no id property)',
        response: {jsonrpc: '2.0', result: null},
        version: 2,
        expected: false,
      },
      {
        desc: 'an invalid 2 response (response not plain object)',
        response: null,
        version: 2,
        expected: false,
      },
      {
        desc: 'a valid 1 response',
        response: {id: 'something', result: {}, error: null},
        version: 1,
        expected: true,
      },
      {
        desc: 'a valid 1 error response',
        response: {id: 'something', result: null, error: {}},
        version: 1,
        expected: true,
      },
      {
        desc: 'an invalid 1 response (response not plain object)',
        response: null,
        version: 1,
        expected: false,
      },
      {
        desc: 'an invalid 1 response (non-null result and error)',
        response: {id: 'something', result: {}, error: {}},
        version: 1,
        expected: false,
      },
      {
        desc: 'an invalid 1 response (no result or error)',
        response: {id: 'something'},
        version: 1,
        expected: false,
      },
      {
        desc: 'an invalid 1 response (missing id)',
        response: {result: {}, error: null},
        version: 1,
        expected: false,
      },
      {
        desc: 'an invalid 1 response (missing error null)',
        response: {id: 'something', result: {}},
        version: 1,
        expected: false,
      },
      {
        desc: 'an invalid 1 response (missing result null)',
        response: {id: 'something', error: {}},
        version: 1,
        expected: false,
      },
    ];

    specs.forEach(function(spec) {

      it(`should handle ${spec.desc}`, function() {
        const result = utils.Response.isValidResponse(spec.response, spec.version);
        should(result).equal(spec.expected);
      });

    });

  });

});


text:
class CreateBouquetSalesOrders < ActiveRecord::Migration[5.0]
  def change
    create_table :bouquet_sales_orders do |t|
      t.string :state
      t.date :date
      t.integer :quantity
      t.date :shipment_date
      t.references :product, index: true, foreign_key: true
      t.references :customer, index: true, foreign_key: true

      t.timestamps
    end
  end
end


text:
import * as chai from 'chai';
import * as chaiAsPromised from "chai-as-promised";
import * as temp from 'temp';
import * as fs from 'fs-extra';

import { CompoundPreferenceServer } from '@theia/preferences-api';
import { JsonPrefHelper } from '../node/test/preference-stubs';
import { FileUri } from '@theia/core/lib/node/file-uri';

const expect = chai.expect;
const track = temp.track();
const preferencePath = '.theia/prefs.json';

let compoundPrefServer: CompoundPreferenceServer;
let preferenceFileUri: any;
let helper = new JsonPrefHelper();

before(() => {
    chai.should();
    chai.use(chaiAsPromised);
    chai.config.showDiff = true;
    chai.config.includeStack = true;

    const rootUri = FileUri.create(track.mkdirSync());
    preferenceFileUri = rootUri.resolve(preferencePath);
    fs.mkdirSync(FileUri.fsPath(rootUri.resolve('.theia')));
    fs.writeFileSync(FileUri.fsPath(preferenceFileUri), '');

    const jsonPrefServer = helper.createJsonPrefServer(preferenceFileUri);
    compoundPrefServer = new CompoundPreferenceServer(jsonPrefServer);
});

after(() => {
    compoundPrefServer.dispose();
    track.cleanupSync();
});

describe('compound-preference-server', () => {
    it('register a client', async () => {

        // Register a simple client
        let promise: Promise<boolean> = new Promise<boolean>((done) => {
            compoundPrefServer.setClient({
                onDidChangePreference(event) {
                    for (const change of event.changes) {
                        switch (change.preferenceName) {
                            case "showLineNumbers":
                                expect(change.newValue).to.be.true;
                                done();
                                break;
                        }
                    }
                }
            });
        });

        const fileContent = '{ "showLineNumbers": true }';

        // Modify the content.
        fs.writeFileSync(FileUri.fsPath(preferenceFileUri), fileContent);

        let { content } = await helper.getFS().resolveContent(FileUri.fsPath(preferenceFileUri));
        expect(content).to.be.equal(fileContent);

        helper.getWatcher().fireEvents(
            {
                changes: [{
                    uri: preferenceFileUri.toString(),
                    type: 0
                }]
            }
        );

        return promise;

    });
});


text:
package org.apache.shardingsphere.encrypt.rewrite.token.generator.impl;

import com.google.common.base.Preconditions;
import org.apache.shardingsphere.encrypt.rewrite.token.generator.BaseEncryptSQLTokenGenerator;
import org.apache.shardingsphere.encrypt.rewrite.token.pojo.EncryptAssignmentToken;
import org.apache.shardingsphere.encrypt.rewrite.token.pojo.EncryptLiteralAssignmentToken;
import org.apache.shardingsphere.encrypt.rewrite.token.pojo.EncryptParameterAssignmentToken;
import org.apache.shardingsphere.sql.parser.binder.type.TableAvailable;
import org.apache.shardingsphere.sql.parser.binder.statement.SQLStatementContext;
import org.apache.shardingsphere.sql.parser.binder.statement.dml.InsertStatementContext;
import org.apache.shardingsphere.sql.parser.binder.statement.dml.UpdateStatementContext;
import org.apache.shardingsphere.sql.parser.sql.segment.dml.assignment.AssignmentSegment;
import org.apache.shardingsphere.sql.parser.sql.segment.dml.assignment.SetAssignmentSegment;
import org.apache.shardingsphere.sql.parser.sql.segment.dml.expr.simple.LiteralExpressionSegment;
import org.apache.shardingsphere.sql.parser.sql.segment.dml.expr.simple.ParameterMarkerExpressionSegment;
import org.apache.shardingsphere.sql.parser.sql.statement.SQLStatement;
import org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement;
import org.apache.shardingsphere.sql.parser.sql.statement.dml.UpdateStatement;
import org.apache.shardingsphere.underlying.rewrite.sql.token.generator.CollectionSQLTokenGenerator;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Optional;

/**
 * Assignment generator for encrypt.
 */
public final class EncryptAssignmentTokenGenerator extends BaseEncryptSQLTokenGenerator implements CollectionSQLTokenGenerator {

    @Override
    protected boolean isGenerateSQLTokenForEncrypt(final SQLStatementContext sqlStatementContext) {
        return sqlStatementContext instanceof UpdateStatementContext
                || (sqlStatementContext instanceof InsertStatementContext && (((InsertStatementContext) sqlStatementContext).getSqlStatement()).getSetAssignment().isPresent());
    }

    @Override
    public Collection<EncryptAssignmentToken> generateSQLTokens(final SQLStatementContext sqlStatementContext) {
        Collection<EncryptAssignmentToken> result = new LinkedList<>();
        String tableName = ((TableAvailable) sqlStatementContext).getAllTables().iterator().next().getTableName().getIdentifier().getValue();
        for (AssignmentSegment each : getSetAssignmentSegment(sqlStatementContext.getSqlStatement()).getAssignments()) {
            if (getEncryptRule().findEncryptor(tableName, each.getColumn().getIdentifier().getValue()).isPresent()) {
                generateSQLToken(tableName, each).ifPresent(result::add);
            }
        }
        return result;
    }

    private SetAssignmentSegment getSetAssignmentSegment(final SQLStatement sqlStatement) {
        if (sqlStatement instanceof InsertStatement) {
            Optional<SetAssignmentSegment> result = ((InsertStatement) sqlStatement).getSetAssignment();
            Preconditions.checkState(result.isPresent());
            return result.get();
        }
        return ((UpdateStatement) sqlStatement).getSetAssignment();
    }

    private Optional<EncryptAssignmentToken> generateSQLToken(final String tableName, final AssignmentSegment assignmentSegment) {
        if (assignmentSegment.getValue() instanceof ParameterMarkerExpressionSegment) {
            return Optional.of(generateParameterSQLToken(tableName, assignmentSegment));
        }
        if (assignmentSegment.getValue() instanceof LiteralExpressionSegment) {
            return Optional.of(generateLiteralSQLToken(tableName, assignmentSegment));
        }
        return Optional.empty();
    }

    private EncryptAssignmentToken generateParameterSQLToken(final String tableName, final AssignmentSegment assignmentSegment) {
        EncryptParameterAssignmentToken result = new EncryptParameterAssignmentToken(assignmentSegment.getColumn().getStartIndex(), assignmentSegment.getStopIndex());
        String columnName = assignmentSegment.getColumn().getIdentifier().getValue();
        addCipherColumn(tableName, columnName, result);
        addAssistedQueryColumn(tableName, columnName, result);
        addPlainColumn(tableName, columnName, result);
        return result;
    }

    private void addCipherColumn(final String tableName, final String columnName, final EncryptParameterAssignmentToken token) {
        token.addColumnName(getEncryptRule().getCipherColumn(tableName, columnName));
    }

    private void addAssistedQueryColumn(final String tableName, final String columnName, final EncryptParameterAssignmentToken token) {
        getEncryptRule().findAssistedQueryColumn(tableName, columnName).ifPresent(token::addColumnName);
    }

    private void addPlainColumn(final String tableName, final String columnName, final EncryptParameterAssignmentToken token) {
        getEncryptRule().findPlainColumn(tableName, columnName).ifPresent(token::addColumnName);
    }

    private EncryptAssignmentToken generateLiteralSQLToken(final String tableName, final AssignmentSegment assignmentSegment) {
        EncryptLiteralAssignmentToken result = new EncryptLiteralAssignmentToken(assignmentSegment.getColumn().getStartIndex(), assignmentSegment.getStopIndex());
        addCipherAssignment(tableName, assignmentSegment, result);
        addAssistedQueryAssignment(tableName, assignmentSegment, result);
        addPlainAssignment(tableName, assignmentSegment, result);
        return result;
    }

    private void addCipherAssignment(final String tableName, final AssignmentSegment assignmentSegment, final EncryptLiteralAssignmentToken token) {
        Object originalValue = ((LiteralExpressionSegment) assignmentSegment.getValue()).getLiterals();
        Object cipherValue = getEncryptRule().getEncryptValues(tableName, assignmentSegment.getColumn().getIdentifier().getValue(), Collections.singletonList(originalValue)).iterator().next();
        token.addAssignment(getEncryptRule().getCipherColumn(tableName, assignmentSegment.getColumn().getIdentifier().getValue()), cipherValue);
    }

    private void addAssistedQueryAssignment(final String tableName, final AssignmentSegment assignmentSegment, final EncryptLiteralAssignmentToken token) {
        Object originalValue = ((LiteralExpressionSegment) assignmentSegment.getValue()).getLiterals();
        Optional<String> assistedQueryColumn = getEncryptRule().findAssistedQueryColumn(tableName, assignmentSegment.getColumn().getIdentifier().getValue());
        assistedQueryColumn.ifPresent(s -> {
            Object assistedQueryValue = getEncryptRule().getEncryptAssistedQueryValues(
                    tableName, assignmentSegment.getColumn().getIdentifier().getValue(), Collections.singletonList(originalValue)).iterator().next();
            token.addAssignment(s, assistedQueryValue);
        });
    }

    private void addPlainAssignment(final String tableName, final AssignmentSegment assignmentSegment, final EncryptLiteralAssignmentToken token) {
        Object originalValue = ((LiteralExpressionSegment) assignmentSegment.getValue()).getLiterals();
        getEncryptRule().findPlainColumn(tableName, assignmentSegment.getColumn().getIdentifier().getValue()).ifPresent(plainColumn -> token.addAssignment(plainColumn, originalValue));
    }
}


text:
namespace base {
class TimeDelta;
}

namespace ui {

enum class DomCode;

// Platform-specific interface for controlling input devices.
//
// The object provides methods for the preference page to configure input
// devices w.r.t. the user setting. On ChromeOS, this replaces the inputcontrol
// script that is originally located at /opt/google/chrome/.
class OZONE_EXPORT InputController {
 public:
  typedef base::Callback<void(scoped_ptr<std::string>)>
      GetTouchDeviceStatusReply;
  typedef base::Callback<void(scoped_ptr<std::vector<base::FilePath>>)>
      GetTouchEventLogReply;

  InputController() {}
  virtual ~InputController() {}

  // Functions for checking devices existence.
  virtual bool HasMouse() = 0;
  virtual bool HasTouchpad() = 0;

  // Keyboard settings.
  virtual bool IsCapsLockEnabled() = 0;
  virtual void SetCapsLockEnabled(bool enabled) = 0;
  virtual void SetNumLockEnabled(bool enabled) = 0;
  virtual bool IsAutoRepeatEnabled() = 0;
  virtual void SetAutoRepeatEnabled(bool enabled) = 0;
  virtual void SetAutoRepeatRate(const base::TimeDelta& delay,
                                 const base::TimeDelta& interval) = 0;
  virtual void GetAutoRepeatRate(base::TimeDelta* delay,
                                 base::TimeDelta* interval) = 0;

  // Touchpad settings.
  virtual void SetTouchpadSensitivity(int value) = 0;
  virtual void SetTapToClick(bool enabled) = 0;
  virtual void SetThreeFingerClick(bool enabled) = 0;
  virtual void SetTapDragging(bool enabled) = 0;
  virtual void SetNaturalScroll(bool enabled) = 0;

  // Mouse settings.
  virtual void SetMouseSensitivity(int value) = 0;
  virtual void SetPrimaryButtonRight(bool right) = 0;

  // Touch log collection.
  virtual void GetTouchDeviceStatus(const GetTouchDeviceStatusReply& reply) = 0;
  virtual void GetTouchEventLog(const base::FilePath& out_dir,
                                const GetTouchEventLogReply& reply) = 0;

  // Temporarily enable/disable Tap-to-click. Used to enhance the user
  // experience in some use cases (e.g., typing, watching video).
  virtual void SetTapToClickPaused(bool state) = 0;

  // Disables the internal touchpad.
  virtual void DisableInternalTouchpad() = 0;

  // Enables the internal touchpad.
  virtual void EnableInternalTouchpad() = 0;

  // Disables all keys on the internal keyboard except |excepted_keys|.
  virtual void DisableInternalKeyboardExceptKeys(
      scoped_ptr<std::set<DomCode>> excepted_keys) = 0;

  // Enables all keys on the internal keyboard.
  virtual void EnableInternalKeyboard() = 0;

 private:
  DISALLOW_COPY_AND_ASSIGN(InputController);
};

// Create an input controller that does nothing.
OZONE_EXPORT scoped_ptr<InputController> CreateStubInputController();

}  // namespace ui

#endif  // UI_OZONE_PUBLIC_INPUT_CONTROLLER_H_