text:
\chapter{Script Files}
\label{overview}

  \section{CisDsc.ps1}
    This file is essentially a wrapper for all the functions in the other files. As long as you have this file, you should be able to fetch the other files and set up DSC.
    \subsection{Install-CisDscPullServer}
      Paramters:
      \begin{itemize}
        \item \verb^ComputerName^: Mandatory, name of the computer you want to install server on;
        \item \verb^PullPort^: Port for pull server, 8080 be default;
        \item \verb^CompliancePort^: Port for compliance server, 8081 by default;
        \item \verb^InstallDest^: Installation location, \verb^C:\^ by default.
      \end{itemize}
      This command copies DSC modules from \verb^\\files^ and installs DSC pull server.
    \subsection{Install-CisDscConfiguration}
      Parameters:
      \begin{itemize}
        \item \verb^ComputerName[]^: Mandatory, names of the servers you want to make compliant;
        \item \verb^PullServerName^: Mandatory, name of the pull server;
        \item \verb^Port^: Pull server port, 8080 by default;
        \item \verb^InputDSC^: The directory that contains Template.ps1, \verb^C:\DSC^ by default;
        \item \verb^Force^: Flag to force DSC configuration.
      \end{itemize}
      This command enforces template configuration on clients. \textbf{It should be run on the pull server specified by }\verb^PullServerName^\textbf{.}
    \subsection{Check-CisDscCompliance}
      Parameters:
      \begin{itemize}
        \item \verb^ComputerName[]^: Mandatory, names of the servers you want to check compliance state on;
        \item \verb^UseDefault^: Whether default setting (i.e. installation location) is applied on pull server, true by default;
        \item \verb^MofFile^: The ``golden image'' MOF file, default not specified;
        \item \verb^OutputPath^: Path for outputting compliance reports,
        \verb^C:\DSC\Reports^ by default.
      \end{itemize}
      This command checks the compliance state on clients, based on the MOF it is given. By defualt it uses the Server 2016 template MOF. It generates an overview report and machine-specific detailed reports.

  \section{Template.ps1}
    This is the Server 2016 template based on the standard build doc. It comprises the following modules.
    \subsection{[File]AdminFiles}
      \verb^C:\AdminFiles^ should be present.
    \subsection{[Script]BrownNetwork}
      There should be a network interface called BrownNetwork. Use Network and Sharing Center to check this.
    \subsection{[Script]DNSServer}
      DNS server addresses should be set to 10.4.21.\{2, 3, 4, 5\}, and 10.1.1.10. Use Network and Sharing Center to check this.
    \subsection{[Registry]DNSSuffix}
      DNS suffixes should be in this order: ad.brown.edu, brown.edu, qad.brown.edu, services.brown.edu. Use Network and Sharing Center to check this.
    \subsection{[Script]WINSServer}
      WINS address should be 10.4.21.5. Use Network and Sharing Center to check this.
    \subsection{[Script]LMHOSTS}
      LMHOSTS should be turned off. Use Network and Sharing Center to check this.
    \subsection{[Registry]IPv6}
      IPv6 should be disabled.
    \subsection{[Service]PrintSpooler}
      Print Spooler should be forbidden from starting up. Use Computer Management - Services to check this.
    \subsection{[Registry]AdminESC}
      IE Enhanced Security should be disabled for administrators. Use Server Manager - Local Server to check this.
    \subsection{[Registry]UserESC}
      IE Enhanced Security should be enabled for users. Use Server Manager - Local Server to check this.
    \subsection{[xUAC]UAC}
      It depends on DSC resource xSystemSecurity. User Account Control should be set to Never Notify. Use Control Panel - User Accounts - Change User Account Control Settings to check this.
    \subsection{[Script]DEP}
      Data Execution Prevention should be set to ``Turn on DEP for essential Windows programs and services only''. Use Control Panel - System and Security - System - Advanced System Settings - Advanced - Performance - Data Execution Prevention to check this.
    \subsection{[Registry]AdjustForBestPerformance}
      Visual Effects should be set to ``Adjust for Best Performance''. Use Control Panel - System and Security - System - Advanced System Settings - Advanced - Performance - Visual Effects to check this.
    \subsection{[xRemoteDesktopAdmin]RemoteDesktop}
      It depends on DSC resource xRemoteDektopAdmin. Remote access should be enabled. Use Control Panel - System and Security - Allow Remote Access to check this.
    \subsection{[Registry]ServerManager}
      Registry key should be set to disable Server Manager at logon.
    \subsection{[Script]ServerManagerTask}
      Server Manager should be disabled from auto startup. Use Task Scheduler - Microsoft - Windows - Server Manager to check this.
    \subsection{[File]BGInfo}
      BGInfo should be present at \verb^C:\AdminFiles\BGInfo32-64^. This module is not fully functional at this stage. See Issues \& TODOs for more information.
    \subsection{[Registry]BGInfoKey}
      Registry key for BGInfo should be set, such that it can start correctly.
    \subsection{[WindowsFeature]SMB1}
      SMB1 should be disabled.
    \subsection{[Registry]KB3125869\_Key1}
      KB3125869 should be installed. For more information about this update, please refer to Microsoft website.
    \subsection{[Registry]KB3125869\_Key2}
      Ditto.
    \subsection{[Script]NetshReceiveSideScaling}
      Receive-Side Scaling should be enabled in netsh. Use \verb^netsh int tcp show global^ to check this.
    \subsection{[Script]DeviceManagerReceiveSideScaling}
      Receive-Side Scaling should be disabled in Device Manager.

  \section{PullServerConfiguration.ps1}
    This is the configuration file for pull server installation. You normally need not change its content. However, if you want to enforce HTTPS, you should modify a few properties.\\
    Under \verb^[xDSCWebService]PSDSCPullServer^, set
    \begin{itemize}
      \item \verb^CertificateThumbPrint = Certificate thumbprint for IIS Server^
      \item \verb^UseSecurityBestPractices = $true^.
    \end{itemize}
    Under \verb^[xDSCWebService]PSDSCComplianceServer^, do the same thing with
    \begin{itemize}
      \item \verb^CertificateThumbPrint = Certificate thumbprint for IIS Server^
      \item \verb^UseSecurityBestPractices = $true^.
    \end{itemize}
    After modification, re-install the pull server.

  \section{LCM\_HttpPull.ps1}
    This is the configuration file for DSC Local Configuration Manager. If a client wants to pull DSC Mof files, it has to know where to find them. This file serves that purpose.\\
    To enforce HTTPS, under \verb^[ConfigurationRepositoryWeb]DSCHTTP^, set
    \begin{itemize}
      \item \verb^ServerURL =^\\
      \verb^"https://$PullServerName.ad.brown.edu:$Port/PSDSCPullServer.svc"^
      \item \verb^CertificateID = Certificate thumbprint for IIS Server^
      \item \verb^AllowUnsecureConnection = $false^.
    \end{itemize}
    And then use \verb^Install-CisDscConfiguration^ to re-install settings for the clients.


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.teamupnext.robot.commands;

import com.teamupnext.robot.RobotMap;

/**
 *
 * @author jousley
 */
public class LowerArm extends CommandBase {

    public LowerArm() {
        // Use requires() here to declare subsystem dependencies
        requires(pickerUpper);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
        setTimeout(RobotMap.ARM_DOWN_TIMEOUT);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        pickerUpper.moveDown();
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return isTimedOut();
    }

    // Called once after isFinished returns true
    protected void end() {
        pickerUpper.zeroSolenoids();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
App::uses('Type', 'Taxonomy.Model');
App::uses('CroogoTestCase', 'Croogo.TestSuite');

class ParamsBehaviorTest extends CroogoTestCase {

	public $fixtures = array(
		'plugin.users.aco',
		'plugin.users.aro',
		'plugin.users.aros_aco',
		'plugin.blocks.block',
		'plugin.comments.comment',
		'plugin.contacts.contact',
		'plugin.translate.i18n',
		'plugin.settings.language',
		'plugin.menus.link',
		'plugin.menus.menu',
		'plugin.contacts.message',
		'plugin.meta.meta',
		'plugin.nodes.node',
		'plugin.taxonomy.model_taxonomy',
		'plugin.blocks.region',
		'plugin.users.role',
		'plugin.settings.setting',
		'plugin.taxonomy.taxonomy',
		'plugin.taxonomy.term',
		'plugin.taxonomy.type',
		'plugin.taxonomy.types_vocabulary',
		'plugin.users.user',
		'plugin.taxonomy.vocabulary',
	);

	public $Type = null;

/**
 * setUp
 *
 * @return void
 */
	public function setUp() {
		parent::setUp();
		$this->Type = ClassRegistry::init('Taxonomy.Type');
	}

/**
 * tearDown
 *
 * @return void
 */
	public function tearDown() {
		parent::tearDown();
		unset($this->Type);
		ClassRegistry::flush();
	}

	public function testSingle() {
		$this->Type->save(array(
			'title' => 'Article',
			'alias' => 'article',
			'description' => 'Article Types',
			'params' => 'param1=value1',
		));
		$type = $this->Type->findByAlias('article');
		$expected = array(
			'param1' => 'value1',
		);
		$this->assertEqual($type['Params'], $expected);
	}

	public function testMultiple() {
		$this->Type->save(array(
			'title' => 'Article',
			'alias' => 'article',
			'description' => 'Article Types',
			'params' => "param1=value1\nparam2=value2",
		));
		$type = $this->Type->findByAlias('article');
		$expected = array(
			'param1' => 'value1',
			'param2' => 'value2',
		);
		$this->assertEqual($type['Params'], $expected);
	}

	public function testMixedLineEndings() {
		$this->Type->save(array(
			'title' => 'Article',
			'alias' => 'article',
			'description' => 'Article Types',
			'params' => "param1=value1\r\nparam2=value2\rparam3=value3\nparam4=value4",
		));
		$type = $this->Type->findByAlias('article');
		$expected = array(
			'param1' => 'value1',
			'param2' => 'value2',
			'param3' => 'value3',
			'param4' => 'value4',
		);
		$this->assertEqual($type['Params'], $expected);
	}

	public function testEmbeddedOptions() {
		$this->Type->save(array(
			'title' => 'Article',
			'alias' => 'article',
			'description' => 'Article Types',
			'params' => "param1=value1\r\n[options:linkAttr escape=true escapeTitle=false foo=a:b;c:d;e:f]",
		));
		$type = $this->Type->findByAlias('article');
		$expected = array(
			'param1' => 'value1',
			'linkAttr' => array(
				'escape' => 'true',
				'escapeTitle' => 'false',
				'foo' => array(
					'a' => 'b',
					'c' => 'd',
					'e' => 'f',
				),
			),
		);
		$this->assertEqual($type['Params'], $expected);
	}

	public function testBoolean() {
		$this->Type->save(array(
			'title' => 'Article',
			'alias' => 'article',
			'description' => 'Article Types',
			'params' => "param1=true\nparam2=false\nparam3=yes\nparam4=no\nparam5=on\nparam6=off",
		));
		$type = $this->Type->findByAlias('article');
		$expected = array(
			'param1' => true,
			'param2' => false,
			'param3' => true,
			'param4' => false,
			'param5' => true,
			'param6' => false,
		);
		$this->assertEqual($type['Params'], $expected);
		$this->assertInternalType('boolean', $type['Params']['param1']);
		$this->assertInternalType('boolean', $type['Params']['param2']);
		$this->assertInternalType('boolean', $type['Params']['param3']);
		$this->assertInternalType('boolean', $type['Params']['param4']);
		$this->assertInternalType('boolean', $type['Params']['param5']);
		$this->assertInternalType('boolean', $type['Params']['param6']);
	}

	public function testNumeric() {
		$this->Type->save(array(
			'title' => 'Article',
			'alias' => 'article',
			'description' => 'Article Types',
			'params' => "param1=22\nparam2=0x16\nparam3=0\nparam4=1",
		));
		$type = $this->Type->findByAlias('article');
		$expected = array(
			'param1' => 22,
			'param2' => 22,
			'param3' => 0,
			'param4' => 1,
		);
		$this->assertEqual($type['Params'], $expected);
		$this->assertInternalType('integer', $type['Params']['param1']);
		$this->assertInternalType('integer', $type['Params']['param2']);
		$this->assertInternalType('integer', $type['Params']['param3']);
		$this->assertInternalType('integer', $type['Params']['param4']);
	}

}


text:
from baseline.pytorch.torchy import vec_log_sum_exp
from baseline.pytorch.seq2seq import Seq2SeqModel
from eight_mile.utils import str2bool, write_yaml, read_yaml, Offsets
from eight_mile.pytorch.layers import *
from eight_mile.optz import create_lr_scheduler
import baseline.pytorch.embeddings
import baseline.embeddings
import random
from eight_mile.progress import create_progress_bar
from torch.utils.data.dataset import IterableDataset, TensorDataset
from baseline.vectorizers import Token1DVectorizer, BPEVectorizer1D, Char2DVectorizer, WordpieceVectorizer1D
import codecs
from collections import Counter
import glob
import json

class TensorDatasetReaderBase:
    """Provide a base-class to do operations that are independent of token representation
    """
    def __init__(self, nctx, vectorizers):
        self.vectorizers = vectorizers
        self.nctx = nctx
        self.num_words = {}

    def build_vocab(self, files):
        vocabs = {k: Counter({'[CLS]': 1}) for k in self.vectorizers.keys()}

        for file in files:
            if file is None:
                continue
            self.num_words[file] = 0
            with codecs.open(file, encoding='utf-8', mode='r') as f:
                sentences = []
                for line in f:
                    split_sentence = line.split() + ['<EOS>']
                    self.num_words[file] += len(split_sentence)
                    sentences += split_sentence
                for k, vectorizer in self.vectorizers.items():
                    vocabs[k].update(vectorizer.count(sentences))
        return vocabs

    def load_features(self, filename, vocabs):

        features = dict()
        with codecs.open(filename, encoding='utf-8', mode='r') as f:
            sentences = []
            for line in f:
                sentences += line.strip().split() + ['<EOS>']
            for k, vectorizer in self.vectorizers.items():
                vec, valid_lengths = vectorizer.run(sentences, vocabs[k])
                features[k] = vec[:valid_lengths]
                shp = list(vectorizer.get_dims())
                shp[0] = valid_lengths
                features['{}_dims'.format(k)] = tuple(shp)
        return features

class TensorWordDatasetReader(TensorDatasetReaderBase):
    """Read each word, and produce a tensor of x and y that are identical
    """
    def __init__(self, nctx, use_subword=None, model_file=None, vocab_file=None, special_tokens=None):
        """Create a reader with a context window that reads words

        :param nctx: The context window length
        :param use_subword: If this is not none, it should be either 'bpe' or 'wordpiece'
        """
        self.use_subword = use_subword

        if self.use_subword == 'bpe':
            vectorizer = BPEVectorizer1D(model_file=model_file, vocab_file=vocab_file)
        elif self.use_subword == 'wordpiece':
            vectorizer = WordpieceVectorizer1D(embed_file=model_file, vocab_file=vocab_file,
                                               special_tokens=special_tokens)
        else:
            vectorizer = Token1DVectorizer(transform_fn=baseline.lowercase)
        super().__init__(nctx, {'x': vectorizer})

    def build_vocab(self, files):
        """Read the vocab file to get the tokens

        :param files:
        :return:
        """
        if self.use_subword is not None:
            super().build_vocab(files)
            return {'x': self.vectorizers['x'].vocab}
        return super().build_vocab(files)

    def load(self, filename, vocabs):
        features = self.load_features(filename, vocabs)
        x_tensor = torch.tensor(features['x'], dtype=torch.long)
        num_sequences_word = (x_tensor.size(0) // self.nctx) * self.nctx
        x_tensor = x_tensor.narrow(0, 0, num_sequences_word).view(-1, self.nctx)
        return TensorDataset(x_tensor, x_tensor)

class TensorCharDatasetReader(TensorDatasetReaderBase):
    """TensorCharDatasetReader reads in a vocab and then a dataset and returns as a `dict` of `string` to `ndarray`
    """
    def __init__(self, nctx, chars_per_word):
        y_vectorizer = Token1DVectorizer(transform_fn=baseline.lowercase)
        x_vectorizer = Char2DVectorizer(mxwlen=chars_per_word)
        super().__init__(nctx, {'x': x_vectorizer, 'y': y_vectorizer})
        self.chars_per_word = chars_per_word

    def load(self, filename, vocabs):
        features = self.load_features(filename, vocabs)
        y_tensor = torch.tensor(features['y'], dtype=torch.long)
        num_sequences_word = (y_tensor.size(0) // self.nctx) * self.nctx
        y_tensor = y_tensor.narrow(0, 0, num_sequences_word).view(-1, self.nctx)

        x_dataset = torch.tensor(features['x'], dtype=torch.long)
        x_tensor = torch.tensor(x_dataset, dtype=torch.long)
        x_tensor = x_tensor.narrow(0, 0, num_sequences_word)
        x_tensor = x_tensor.view(-1, self.nctx, self.chars_per_word)
        return TensorDataset(x_tensor, y_tensor)

def load_data_caching(token_type, reader, dataset, file_key, vocabs, caching, logger):
    cached_file = '{}-{}.cache'.format(dataset[file_key], token_type)
    if caching and os.path.exists(cached_file):
        logger.info("Reloading %s from cached file [%s]", file_key, cached_file)
        loaded = torch.load(cached_file)
    else:
        # if build_vocab() was never run, need to run it to set reader.vectorizer.mxlen correctly
        if reader.vectorizers['x'].mxlen == -1:
            _ = reader.build_vocab([dataset[file_key]])
        loaded = reader.load(dataset[file_key], vocabs)
        logger.info("Caching %s to [%s]", file_key, cached_file)
        torch.save(loaded, cached_file)
    return loaded

class MultiFileLoader(IterableDataset):

    def __init__(
            self, directory, pattern, vocabs, src_vectorizer, tgt_vectorizer, last_turn_only=False,
            distribute=True, shuffle=True, record_keys=[]
    ):
        super().__init__()
        self.record_keys = record_keys
        self.src_vectorizer = src_vectorizer
        self.tgt_vectorizer = tgt_vectorizer
        self.pattern = pattern
        self.directory = directory
        self.vocab = vocabs
        self.samples = 0
        self.rank = 0
        self.world_size = 1
        self.shuffle = shuffle
        self.last_turn_only = last_turn_only
        self.distribute = distribute
        if torch.distributed.is_initialized() and distribute:
            self.rank = torch.distributed.get_rank()
            self.world_size = torch.distributed.get_world_size()

        if os.path.exists(f"{directory}/md.yml"):
            f = read_yaml(f"{directory}/md.yml")
            self.samples = f['num_samples']
        else:
            files = list(glob.glob(f"{directory}/{self.pattern}"))
            pg = create_progress_bar(len(files))
            for file in pg(files):
                with open(file) as rf:
                    for _ in rf:
                        self.samples += 1
            write_yaml({'num_samples': self.samples}, f"{directory}/md.yml")

    def __len__(self):
        return self.samples

    def _get_worker_info(self):
        return torch.utils.data.get_worker_info() if self.distribute else None

    def _init_read_order(self):
        # Each node has the same worker_info, so the unique offsets for each is
        # rank * num_workers + worker_id
        # and the total available workers is world_size * num_workers
        worker_info = self._get_worker_info()
        files = sorted(list(glob.glob(f"{self.directory}/{self.pattern}")))

        if worker_info is None:
            num_workers_per_node = 1
            node_worker_id = 0
        else:
            num_workers_per_node = worker_info.num_workers
            node_worker_id = worker_info.id
        all_workers = (self.world_size * num_workers_per_node)
        offset = self.rank * num_workers_per_node + node_worker_id
        read_file_order = list(range(offset, len(files), all_workers))
        if not read_file_order:
            if offset > 0:
                # This is probably wrong
                logger.warning(f"There are no files to read for worker {node_worker_id}, offset {offset}!" +
                               " This might mean that you are passing an incorrect training or validation directory")
            else:
                # This is definitely wrong
                raise Exception(f"No files of pattern {self.pattern} were found in {self.directory}!")
        return files, read_file_order, node_worker_id

    def __iter__(self):
        files, read_file_order, _ = self._init_read_order()
        # If we have multiple files per worker, possibly shuffle the file read order
        while True:
            if self.shuffle:
                random.shuffle(read_file_order)
            for file_idx in read_file_order:
                file = files[file_idx]
                with open(file) as rf:
                    lines = rf.readlines()
                    if self.shuffle:
                        random.shuffle(lines)
                    for l in lines:
                        response = self.process_line(l)
                        if response:
                            yield response

    def process_line(self, line):
        """Read in a line and turn it into an entry

        The entries will get collated by the data loader

        :param line:
        :return:
        """

class NextTurnPredictionFileLoader(MultiFileLoader):

    KEYS_TO_COLS = {'y': 1, 'x': 0}
    def get_pair_order(self, pair):
        p1 = NextTurnPredictionFileLoader.KEYS_TO_COLS[self.record_keys[0]]
        if len(self.record_keys) == 1:
            return pair[p1], pair[p1]
        p2 = NextTurnPredictionFileLoader.KEYS_TO_COLS[self.record_keys[1]]
        return pair[p1], pair[p2]

    def process_line(self, line):
        pair = line.strip().split('\t')
        # Unfortunately, this occassionally happens, a bunch of blank turns etc.
        if len(pair) != 2 and len(self.record_keys) > 1:
            return None
        q, r = self.get_pair_order(pair)
        if q == '' or r == '':
            return None
        if self.last_turn_only:
            turns = q.split('<EOU>')
            q = turns[-1] if turns[-1].strip() != '' else turns[-2]
            if q.strip() == '':
                return None
            q_vec, q_valid_lengths = self.src_vectorizer.run(q.split(), self.vocab)
        else:

            q = [self.src_vectorizer.vocab.get(x, Offsets.UNK) for x in self.src_vectorizer.iterable(q.split())]
            q_valid_lengths = len(q)
            if q_valid_lengths > self.src_vectorizer.mxlen:
                start = q_valid_lengths - self.src_vectorizer.mxlen
                q_vec = np.array(q[start:], dtype=np.long)
            else:
                q_vec = np.zeros(self.src_vectorizer.mxlen, dtype=np.long)
                q_vec[:q_valid_lengths] = np.array(q)

        r_vec, r_valid_lengths = self.tgt_vectorizer.run(r.split(), self.vocab)
        return q_vec, r_vec

def on_demand_mlm_masking(inputs, labels, mask_value, vocab_size):
    # Replace 15% of tokens
    masked_indices = torch.bernoulli(torch.full(labels.shape, 0.15)).type(torch.bool)
    # Anything not masked is 0 so no loss
    labels[~masked_indices] = 0
    # Of the masked items, mask 80% of them with [MASK]
    indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).type(torch.bool) & masked_indices
    inputs[indices_replaced] = mask_value
    # Replace 10% of them with random words, rest preserved for auto-encoding
    indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).type(
        torch.bool) & masked_indices & ~indices_replaced
    random_words = torch.randint(vocab_size, labels.shape, dtype=torch.long, device=labels.device)
    inputs[indices_random] = random_words[indices_random]
    return inputs, labels, masked_indices

class SequencePredictionFileLoader(MultiFileLoader):

    def process_line(self, line):
        line = line.strip()
        if not line:
            return None

        vec, valid_lengths = self.src_vectorizer.run(line.split(), self.vocab)
        if valid_lengths < 2:
            return None
        return vec, vec

class PreprocessedFileLoader(MultiFileLoader):

    def process_line(self, line):
        obj = json.loads(line)
        if 'y' in obj.keys():
            return np.array(obj['x'], dtype=int), np.array(obj['y'], dtype=int)
        else:
            return np.array(obj['x'], dtype=int), np.array(obj['x'], dtype=int)

class NextSequencePredictionFileLoader(MultiFileLoader):

    def process_line(self, line):
        line = line.strip()
        if not line:
            return None
        vec, valid_lengths = self.src_vectorizer.run(line.split(), self.vocab)
        if valid_lengths < 2:
            return None
        pair_entry_length = self.src_vectorizer.mxlen//2
        end_of_query = min(valid_lengths//2, pair_entry_length)
        # Front half is all tokens up until the half_way marker
        # Create a new query vector
        query = np.zeros(pair_entry_length, dtype=np.int)
        query[:end_of_query] = vec[:end_of_query]
        # Repurpose the existing vector as the response vector
        vec = vec[end_of_query:end_of_query+pair_entry_length]
        return query, vec

class MultiTFRecordLoader(MultiFileLoader):
    """Using module tfrecord to read tfrecord file into PyTorch datasets"""
    try:
        import tfrecord
    except:
        pass
    def __init__(self, directory, vocabs, src_vectorizer, tgt_vectorizer, last_turn_only=True, distribute=True, shuffle=True, record_keys=None):
        super().__init__(directory, "*.tfrecord", vocabs, src_vectorizer, tgt_vectorizer, last_turn_only, distribute, shuffle)
        # create index first
        if not record_keys:
            self.x = 'x'
            self.y = 'y'
        elif len(record_keys) < 2:
            self.x = record_keys[0]
            self.y = record_keys[0]
        else:
            self.x, self.y = record_keys
        files = list(glob.glob(os.path.join(directory, '*.tfrecord')))
        for f in files:
            idx_file = '.'.join(f.split('.')[:-1]) + '.index'
            if not os.path.exists(idx_file):
                self.tfrecord.tools.tfrecord2idx.create_index(f, idx_file)

    def __iter__(self):
        files, read_file_order, node_worker_id = self._init_read_order()
        # If we have multiple files per worker, possibly shuffle the file read order
        while True:
            if self.shuffle:
                random.shuffle(read_file_order)
            for file_idx in read_file_order:
                file = files[file_idx]
                idx_file = '.'.join(file.split('.')[:-1]) + '.index'
                # shard = (worker_id, num_workers), but we already assigned this file to one certain worker,
                # so shard = (0, 1)
                itr = self.tfrecord.reader.tfrecord_loader(file, idx_file, shard=(0, 1))
                if self.shuffle:
                    np.random.seed(node_worker_id)
                    # not sure about the optimal choice of shuffle_queue_size here:
                    itr = self.tfrecord.iterator_utils.shuffle_iterator(itr, queue_size=128)
                for d in itr:
                    yield np.array(d[self.x], dtype=int), np.array(d[self.y], dtype=int)

class MultiFileDatasetReader:
    """Provide a base-class to do operations that are independent of token representation
    """

    def __init__(self, src_nctx=64, tgt_nctx=64, src_begin_tok=[], src_end_tok=['<EOS>'], tgt_begin_tok=['<GO>'],
                 tgt_end_tok=['<EOS>'], model_file=None, vocab_file=None, file_type='txt', reader_type="ntp",
                 record_keys=None, lower=False, extra_tokens=["[CLS]", "[MASK]"], subword_type="bpe"):
        self.src_nctx = src_nctx
        self.tgt_nctx = tgt_nctx
        self.pattern = f'*.{file_type}'
        self.reader_type = reader_type
        if not src_begin_tok and self.reader_type == 'lang':
            src_begin_tok = ['[CLS]']
        self.record_keys = record_keys if record_keys else ['x', 'y']
        transform_fn = None if not lower else baseline.lowercase
        self.subword_type = subword_type
        self.src_vectorizer = self._create_subword_vectorizer(
            model_file=model_file, vocab_file=vocab_file, mxlen=src_nctx,
            emit_begin_tok=src_begin_tok, emit_end_tok=src_end_tok,
            transform_fn=transform_fn, extra_tokens=extra_tokens,
        )
        self.tgt_vectorizer = self._create_subword_vectorizer(
            model_file=model_file, vocab_file=vocab_file, mxlen=tgt_nctx,
            emit_begin_tok=tgt_begin_tok, emit_end_tok=tgt_end_tok,
            transform_fn=transform_fn, extra_tokens=extra_tokens,
        )

    def _create_subword_vectorizer(self, mxlen=None, model_file=None, vocab_file=None, emit_begin_tok=None, emit_end_tok=None, transform_fn=None, extra_tokens=None):
        if self.subword_type == 'bpe':
            return BPEVectorizer1D(model_file=model_file, vocab_file=vocab_file, mxlen=mxlen,
                               emit_begin_tok=emit_begin_tok, emit_end_tok=emit_end_tok,
                               transform_fn=transform_fn, extra_tokens=extra_tokens)
        if self.subword_type == 'wordpiece':
            return WordpieceVectorizer1D(
                vocab_file=vocab_file,
                mxlen=mxlen,
                emit_begin_tok=emit_begin_tok,
                emit_end_tok=emit_end_tok,
                transform_fn=transform_fn)
        else:
            from baseline.vectorizers import SentencePieceVectorizer1D
            return SentencePieceVectorizer1D(
                model_file=model_file,
                mxlen=mxlen,
                emit_begin_tok=emit_begin_tok,
                emit_end_tok=emit_end_tok,
                transform_fn=transform_fn,
                extra_tokens=extra_tokens)

    def build_vocab(self, _=None):
        return {'x': self.src_vectorizer.vocab}

    def load(self, directory, vocabs, distribute=True, shuffle=True):
        reader_type = self.reader_type.lower()
        # For `self.record_keys` in NTP and NSP, these names a
        if reader_type == "ntp":
            return NextTurnPredictionFileLoader(directory, self.pattern, vocabs, self.src_vectorizer, self.tgt_vectorizer, distribute=distribute, shuffle=shuffle, record_keys=self.record_keys)
        elif reader_type == "nsp":
            return NextSequencePredictionFileLoader(directory, self.pattern, vocabs, self.src_vectorizer, self.tgt_vectorizer, distribute=distribute, shuffle=shuffle)
        elif reader_type == "lang":
            print("Using files as an LM")
            return SequencePredictionFileLoader(directory, self.pattern, vocabs, self.src_vectorizer, self.tgt_vectorizer, distribute=distribute, shuffle=shuffle)
        elif reader_type == 'tfrecord':
            print("Reading data in .tfrecord format using the tfrecord module")
            return MultiTFRecordLoader(directory, vocabs, self.src_vectorizer, self.tgt_vectorizer, distribute=distribute, shuffle=shuffle, record_keys=self.record_keys)
        return PreprocessedFileLoader(directory, self.pattern, vocabs, self.src_vectorizer, self.tgt_vectorizer, distribute=distribute, shuffle=shuffle)

def get_lr_decay(sched_type, lr, steps_per_epoch, n_epochs, logger, decay_steps=None, decay_rate=None, alpha=None):
    if sched_type == 'cosine':
        decay_steps = decay_steps if decay_steps else steps_per_epoch * n_epochs
        alpha = alpha if alpha else 0.
        params = {'decay_steps': decay_steps, 'alpha': alpha}
    else:
        decay_steps = decay_steps if decay_steps else steps_per_epoch
        if not decay_rate:
            if sched_type == 'exponential':
                decay_rate = 0.5
            elif sched_type == 'invtime':
                decay_rate = 1.0
        params = {'decay_steps': decay_steps, 'decay_rate': decay_rate}
    lr_decay = create_lr_scheduler(lr_scheduler_type=sched_type, lr=lr, **params)
    logger.info(f"Using {sched_type} decay learning rate with params {params}.")
    return lr_decay


text:
import { connect } from 'react-redux';
import ExploreMap from 'components/Explore/ExploreMap';

import {
  updateMapParams,
  setSwitchStatus,
  getGeoDataInfo,
  setInteractionPosition,
  setInteractionVisibility
} from 'actions/exploremap';
import { updateURL } from 'actions/links';

// Selectors
import filterDatasetsByTab from 'selectors/datasets';
import { getActiveDatasetsSelector, getActiveLayersSelector } from 'selectors/explore-map';

const mapStateToProps = state => ({
  enabledDatasets: getActiveDatasetsSelector(state),
  enabledLayers: getActiveLayersSelector(state),
  data: filterDatasetsByTab(state),
  interactionData: state.exploremap.interactionData,
  layers: state.datasets.layers,
  map: state.exploremap
});

const mapDispatchToProps = dispatch => ({
  onTileError: (id) => {
    dispatch(setSwitchStatus(id, false));
    dispatch(updateURL());
  },
  setMapParams: (params) => {
    dispatch(updateMapParams(params));
    dispatch(updateURL());
  },
  setInteractionData: (datasetId, geo) => {
    dispatch(getGeoDataInfo(datasetId, geo));
  },
  setInteractionPosition: (position) => {
    dispatch(setInteractionPosition(position));
  },
  setInteractionVisibility: (visible) => {
    dispatch(setInteractionVisibility(visible));
  }
});

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


text:
package com.ofbizian.semat.dom.domain;

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

import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.query.QueryDefault;
import org.apache.isis.applib.services.registry.ServiceRegistry2;
import org.apache.isis.applib.services.repository.RepositoryService;
import org.apache.isis.applib.services.wrapper.WrapperFactory;

@DomainService(
        nature = NatureOfService.DOMAIN,
        repositoryFor = State.class
)
public class StateRepository {

    @javax.inject.Inject
    RepositoryService repositoryService;

    @javax.inject.Inject
    ServiceRegistry2 serviceRegistry;

    @javax.inject.Inject
    WrapperFactory wrapperFactory;

    public List<Alpha> createProjectAlphas(Project object) {
        Alpha opportunity = new Alpha(AlphaType.OPPORTUNITY, "Opportunity", Concern.CUSTOMER);
        Alpha stakeholders = new Alpha(AlphaType.STAKEHOLDERS, "Stakeholders", Concern.CUSTOMER);
        Alpha requirements = new Alpha(AlphaType.REQUIREMENTS, "Requirements", Concern.SOLUTION);
        Alpha softwareSystem = new Alpha(AlphaType.SOFTWARE_SYSTEM, "Software System", Concern.SOLUTION);
        Alpha team = new Alpha(AlphaType.TEAM, "Team", Concern.ENDEAVOR);
        Alpha work = new Alpha(AlphaType.WORK, "Work", Concern.ENDEAVOR);
        Alpha wayOfWorking = new Alpha(AlphaType.WAY_OF_WORKING, "Way Of Working", Concern.ENDEAVOR);

        List<Alpha> alphas = new ArrayList<>();
        alphas.add(createAlpha(opportunity));
        alphas.add(createAlpha(stakeholders));
        alphas.add(createAlpha(requirements));
        alphas.add(createAlpha(softwareSystem));
        alphas.add(createAlpha(team));
        alphas.add(createAlpha(work));
        alphas.add(createAlpha(wayOfWorking));

        object.setOpportunity(opportunity);
        object.setStakeholders(stakeholders);
        object.setRequirements(requirements);
        object.setSoftwareSystem(softwareSystem);
        object.setTeam(team);
        object.setWork(work);
        object.setWayOfWorking(wayOfWorking);
        return alphas;
    }

    private Alpha createAlpha(Alpha object) {
        serviceRegistry.injectServicesInto(object);
        object.init();
        repositoryService.persist(object);

        int i = 0;
        List<State> states = wrapperFactory.wrap(this).findStates(object.getAlphaType());
        for (State state : states) {
            final AlphaState alphaState = createAlphaState(object, state, false, i++);
            final SortedSet<Item> items = state.getItems();
            int j = 0;
            for (Item item : items) {
                createChecklist(alphaState, item, false, j++);
            }
        }
        return object;
    }

    public List<Alpha> listAlphas() {
        return repositoryService.allInstances(Alpha.class);
    }

    public State createState(final String name, String description, AlphaType alphaType) {
        State object = new State();
        object.setName(name);
        object.setDescription(description);
        object.setAlphaType(alphaType);
        serviceRegistry.injectServicesInto(object);
        object.init();
        repositoryService.persist(object);
        return object;
    }

    public List<State> listStates() {
        return repositoryService.allInstances(State.class);
    }

    public List<State> findStates(AlphaType alphaType) {
        return repositoryService.allMatches(
                new QueryDefault<>(
                        State.class,
                        "findByAlphaType",
                        "alphaType", alphaType));

    }

    public AlphaState createAlphaState(Alpha alpha, State state, boolean achieved, int sequence) {
        AlphaState object = new AlphaState();
        object.setAlpha(alpha);
        object.setState(state);
        object.setAchieved(achieved);
        object.setSequence(sequence);
        serviceRegistry.injectServicesInto(object);
        object.init();
        repositoryService.persist(object);
        return object;
    }

    public List<AlphaState> listAlphaState() {
        return repositoryService.allInstances(AlphaState.class);
    }

    private Item createItem(String description) {
        Item object = new Item();
        object.setDescription(description);
        serviceRegistry.injectServicesInto(object);
        object.init();
        repositoryService.persist(object);
        return object;
    }

    public List<Item> listItems() {
        return repositoryService.allInstances(Item.class);
    }

    public Checklist createChecklist(AlphaState alphaState, Item item, boolean achieved, int sequence) {
        Checklist object = new Checklist();
        object.setAlphaState(alphaState);
        object.setItem(item);
        object.setAchieved(achieved);
        object.setSequence(sequence);
        serviceRegistry.injectServicesInto(object);
        object.init();
        repositoryService.persist(object);
        return object;
    }

    public List<Checklist> listChecklists() {
        return repositoryService.allInstances(Checklist.class);
    }

    public Item createStateItem(String descriptions, State state) {
        final Item item = createItem(descriptions);
        state.addToItems(item);
        item.setState(state);
        return item;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 65: 94 (1997)

#### Original name
Anungitea brevicatenata R.F. Castañeda, W.B. Kendr. & Guarro, 1997

### Remarks
null


text:
@protocol ResponseDelegate <NSObject>

/// 响应成功
- (void)respSuc:(id)data andRespApi:(id)respApi;
/// 响应失败
- (void)respFail:(NSError *)error andRespApi:(id)respApi;

@end

/// RequestManager 继承自BaseServiceManager
/// @warning 设计此Manager主要目的是,后期不采用AFNetWorking时,可在本类的发送方法sendRequest...中切换其他第三方请求框架即可,而不需要项目中到处修改AFNetWorking请求为其他方式请求,同时担任着控制第三方请求的角色;因此,即使看不惯本类,也不要修改;另外,本类增加了Protocal回调数据方式请求
/// @warning 请不要随便修改
@interface RequestManager : BaseServiceManager

/// ResponseDelegate 数据响应回调协议
@property (nonatomic,assign) id<ResponseDelegate> delegate;

+ (id)initManagerWithDelegate:(id<ResponseDelegate>)delegate;
/// 发送数据请求,参数为继承AbsApi抽象类,且遵守BaseApiDelegate协议 的对象
- (void)sendRequest:(AbsApi<ApiDelegate>*)api;

@end


text:
package gae.waveeditor;

/**
 * Class used to hold the waves for a level, and export them
 *
 * @author John Gilhuly
 */

import engine.events.ConcreteQueue;
import engine.events.ConstantSpacingWave;
import engine.events.GameObjectQueue;
import engine.events.RandomSpanWave;
import engine.events.Wave;
import gae.openingView.UIObject;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;

public class WaveSelectorPane implements UIObject {

    private ScrollPane rootNode;
    private ObservableList<WaveEnemyTable> waves;
    private WaveEditor parent;

    public WaveSelectorPane (WaveEditor parent) {
        this.parent = parent;
        initialize();
    }

    private void initialize () {
        rootNode = new ScrollPane();
        rootNode.setHbarPolicy(ScrollBarPolicy.NEVER);
        rootNode.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);

        waves = FXCollections.observableArrayList();

        ListView<WaveEnemyTable> listView = new ListView<WaveEnemyTable>(waves);
        listView.setPrefSize(200, 250);
        listView.setEditable(true);

        listView.setItems(waves);
        listView.setOnMouseClicked(e -> parent.newWaveSelected(listView.getSelectionModel()
                .getSelectedItem()));

        Button newWaveButton = new Button("New Wave");
        newWaveButton.setOnAction(e -> makeNewWave());

        Button saveButton = new Button("Save Waves");
        saveButton.setOnAction(e -> saveWaves());

        VBox scrollContents = new VBox();
        scrollContents.getChildren().addAll(listView, newWaveButton, saveButton);
        scrollContents.setSpacing(5);

        rootNode.setOnKeyPressed(e -> checkKeyPressed(e, listView));
        rootNode.setContent(scrollContents);
    }

    private void checkKeyPressed (KeyEvent e, ListView<WaveEnemyTable> listView) {
        if (e.getCode() == KeyCode.BACK_SPACE) {
            waves.remove((listView.getSelectionModel().getSelectedItem()));
        }
    }

    private void makeNewWave () {
        waves.add(new WaveEnemyTable(waves.size() + 1));
    }

    /**
     * Saves the waves as the specified type of wave
     */
    private void saveWaves () {
        for (WaveEnemyTable wave : waves) {
            GameObjectQueue wQueue = new ConcreteQueue(wave.getEnemiesAsList());
            Wave newWave;
            if (wave.getPreferencesPane().randomWaveSpacing()) {
                newWave =
                        new RandomSpanWave(wave.getPreferencesPane().getWaveSpacing(), wave
                                .getPreferencesPane().getTotalSpacingTime(), wQueue,
                                           parent.getGameWorld());
            }
            else {
                newWave =
                        new ConstantSpacingWave(wave.getPreferencesPane().getWaveSpacing(), wave
                                .getPreferencesPane().getSpacingTime(), wQueue,
                                                parent.getGameWorld());
            }
            parent.getStoryboard().addEvent(newWave);
        }
    }

    @Override
    public Node getObject () {
        return rootNode;
    }

}


text:
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
        Toggle Navigation

      </button>

      Mean Stack

Login

Register


text:
package org.stagemonitor.core;

import com.codahale.metrics.health.HealthCheckRegistry;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.stagemonitor.configuration.ConfigurationRegistry;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class StagemonitorTest {

	private static ConfigurationRegistry originalConfiguration;
	private final HealthCheckRegistry healthCheckRegistry = Stagemonitor.getHealthCheckRegistry();
	private ConfigurationRegistry configuration = mock(ConfigurationRegistry.class);
	private CorePlugin corePlugin = mock(CorePlugin.class);

	@BeforeClass
	public static void beforeClass() {
		originalConfiguration = Stagemonitor.getConfiguration();
	}

	@AfterClass
	public static void afterClass() {
		Stagemonitor.setConfiguration(originalConfiguration);
		Stagemonitor.reset();
	}

	@Before
	public void before() {
		when(configuration.getConfig(CorePlugin.class)).thenReturn(corePlugin);
		when(corePlugin.isStagemonitorActive()).thenReturn(true);
		Stagemonitor.reset();
		Stagemonitor.setConfiguration(configuration);
//		assertFalse(Stagemonitor.isStarted());
		for (String name : healthCheckRegistry.getNames()) {
			healthCheckRegistry.unregister(name);
		}
	}

	@After
	public void after() {
		Stagemonitor.reset();
		for (String name : healthCheckRegistry.getNames()) {
			healthCheckRegistry.unregister(name);
		}
	}

	@Test
	public void testStartMonitoring() throws Exception {
		when(corePlugin.isStagemonitorActive()).thenReturn(true);
		Stagemonitor.setConfiguration(configuration);
		Stagemonitor.reset();

		final MeasurementSession measurementSession = new MeasurementSession("StagemonitorTest", "testHost", "testInstance");
		Stagemonitor.reset(measurementSession);

		assertTrue(Stagemonitor.isStarted());
		assertTrue(Stagemonitor.getMeasurementSession().isInitialized());
		assertSame(measurementSession, Stagemonitor.getMeasurementSession());
		assertThat(healthCheckRegistry.runHealthCheck("TestPlugin").isHealthy()).isTrue();
		assertThat(healthCheckRegistry.runHealthCheck("TestExceptionPlugin").isHealthy()).isFalse();
	}

	@Test
	public void testStartMonitoringNotActive() throws Exception {
		when(corePlugin.isStagemonitorActive()).thenReturn(false);

		final MeasurementSession measurementSession = new MeasurementSession("StagemonitorTest", "testHost", "testInstance");
		Stagemonitor.reset(measurementSession);

		assertTrue(Stagemonitor.isDisabled());
		assertFalse(Stagemonitor.isStarted());
		assertTrue(Stagemonitor.getMeasurementSession().isInitialized());
		assertThat(healthCheckRegistry.getNames()).doesNotContain("TestPlugin", "TestExceptionPlugin");
	}

	@Test
	public void testDisabledPlugin() throws Exception {
		when(corePlugin.isStagemonitorActive()).thenReturn(true);
		when(corePlugin.getDisabledPlugins()).thenReturn(Collections.singletonList("TestExceptionPlugin"));

		Stagemonitor.reset(new MeasurementSession("StagemonitorTest", "testHost", "testInstance"));

		assertThat(healthCheckRegistry.runHealthCheck("TestPlugin").isHealthy()).isTrue();
		assertThat(healthCheckRegistry.runHealthCheck("TestExceptionPlugin").isHealthy()).isFalse();
		assertThat(healthCheckRegistry.runHealthCheck("TestExceptionPlugin").getMessage()).isEqualTo("disabled via configuration");
	}

	@Test
	public void testNotInitialized() throws Exception {
		when(corePlugin.isStagemonitorActive()).thenReturn(true);

		final MeasurementSession measurementSession = new MeasurementSession(null, "testHost", "testInstance");
		Stagemonitor.reset(measurementSession);

		assertFalse(Stagemonitor.isStarted());
	}

	public static class PluginNoDependency extends StagemonitorPlugin {
		public List<Class<? extends StagemonitorPlugin>> dependsOn() {
			return Collections.emptyList();
		}
	}

	public static class PluginSimpleDependency extends StagemonitorPlugin {
		@Override
		public List<Class<? extends StagemonitorPlugin>> dependsOn() {
			return Collections.singletonList(PluginNoDependency.class);
		}
	}

	public static class PluginSimpleDependency2 extends StagemonitorPlugin {
		@Override
		public List<Class<? extends StagemonitorPlugin>> dependsOn() {
			return Collections.singletonList(PluginNoDependency.class);
		}
	}

	public static class PluginMultipleDependencies extends StagemonitorPlugin {
		@Override
		public List<Class<? extends StagemonitorPlugin>> dependsOn() {
			return Arrays.asList(PluginSimpleDependency.class, PluginSimpleDependency2.class, PluginNoDependency.class);
		}
	}

	public static class PluginCyclicA extends StagemonitorPlugin {
		@Override
		public List<Class<? extends StagemonitorPlugin>> dependsOn() {
			return Collections.singletonList(PluginCyclicB.class);
		}
	}
	public static class PluginCyclicB extends StagemonitorPlugin {
		@Override
		public List<Class<? extends StagemonitorPlugin>> dependsOn() {
			return Collections.singletonList(PluginCyclicA.class);
		}
	}

	@Test
	public void testInitPluginsCyclicDependency() {
		final List<StagemonitorPlugin> plugins = Arrays.asList(new PluginNoDependency(), new PluginCyclicA(), new PluginCyclicB());
		assertThatThrownBy(() -> Stagemonitor.initializePluginsInOrder(Collections.emptyList(), plugins))
				.isInstanceOf(IllegalStateException.class)
				.hasMessageContaining("PluginCyclicA")
				.hasMessageContaining("PluginCyclicB");
	}

	@Test
	public void testInitPlugins_NoDependency() {
		final PluginNoDependency pluginNoDependency = new PluginNoDependency();
		Stagemonitor.initializePluginsInOrder(Collections.emptyList(), Collections.singletonList(pluginNoDependency));
		assertThat(pluginNoDependency.isInitialized()).isTrue();
	}

	@Test
	public void testInitPlugins_SimpleDependency() {
		final PluginNoDependency pluginNoDependency = new PluginNoDependency();
		final PluginSimpleDependency pluginSimpleDependency = new PluginSimpleDependency();
		Stagemonitor.initializePluginsInOrder(Collections.emptyList(), Arrays.asList(pluginNoDependency, pluginSimpleDependency));
		assertThat(pluginNoDependency.isInitialized()).isTrue();
		assertThat(pluginSimpleDependency.isInitialized()).isTrue();
	}

	@Test
	public void testInitPlugins_MultipleDependencies() {
		final List<StagemonitorPlugin> plugins = Arrays.asList(new PluginMultipleDependencies(), new PluginSimpleDependency2(),
				new PluginNoDependency(), new PluginSimpleDependency());
		Stagemonitor.initializePluginsInOrder(Collections.emptyList(), plugins);
		for (StagemonitorPlugin plugin : plugins) {
			assertThat(plugin.isInitialized()).describedAs("{} is not initialized", plugin.getClass().getSimpleName()).isTrue();
		}
	}

}


text:
Aria.tplScriptDefinition({
    $classpath : 'test.aria.widgets.form.multiselect.issue470.MultiSelectTestCaseTplScript',
    $prototype : {
        onchange : function () {
            this.data.changed = true;
        }
    }
});


text:
using Expressive.Expressions;
using System;

namespace Expressive.Functions.Date
{
    internal sealed class MinutesBetweenFunction : FunctionBase
    {
        #region FunctionBase Members

        public override string Name => "MinutesBetween";

        public override object Evaluate(IExpression[] parameters, Context context)
        {
            this.ValidateParameterCount(parameters, 2, 2);

            var startObject = parameters[0].Evaluate(this.Variables);
            var endObject = parameters[1].Evaluate(this.Variables);

            if (startObject is null || endObject is null) { return null; }

            var start = Convert.ToDateTime(startObject, context.CurrentCulture);
            var end = Convert.ToDateTime(endObject, context.CurrentCulture);

            return (end - start).TotalMinutes;
        }

        #endregion
    }
}


text:
@interface ELLLocationReportViewModel : ELLReportSectionViewModel

@end


text:
package com.github.jasonmfehr.combiner.transformer;

import java.util.Map;

import org.apache.maven.project.MavenProject;

public class MockResourceTransformer implements ResourceTransformer {

	public String transform(final String resourceName, final String resourceContents, final Map<String, String> settings, final MavenProject mavenProject) {
		return null;
	}

}


text:
using System;
using System.Runtime.Serialization;
using IronPython.Runtime.Types;

namespace IronPython.Runtime.Exceptions {
    [Serializable]
    sealed class ObjectException : Exception, IPythonException {
        private object _instance;
        private PythonType _type;

        public ObjectException(PythonType type, object instance) {
            _instance = instance;
            _type = type;
        }

        public ObjectException(string msg) : base(msg) { }
        public ObjectException(string message, Exception innerException)
            : base(message, innerException) {
        }
#if FEATURE_SERIALIZATION
        private ObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif

        public object Instance {
            get {
                return _instance;
            }
        }

        public PythonType Type {
            get {
                return _type;
            }
        }

        #region IPythonException Members

        public object ToPythonException() {
            return this;
        }

        #endregion
    }
}


text:
var other = require('./other')
var url = require('url')
console.log(url.parse(window.location.href))
console.log(other())


text:
This set of script will build a minimized kernel and debootstrap Ubuntu for the PC Engines Wrap board.

# Installation
* Clone this repository on your Ubuntu machine.
* Optional: Adapt the build.config file
* Optional: Adapt other config files
* Open a terminal and go to the repo path
* Insert your compact flash card and unmount it if it has been mounted automatically
* Execute "sudo scripts/build /dev/sdX" (sdX should be the real name of your compact flash card)
* Insert the compact flash card into your wrap board and power it up. If you have a serial console attached you should see the boot process and get a login screen.
* You can login as user "wrap" with password "wrap" (if you didn't change it in the config)
* If you don't have a serial console, you should be able to SSH to the board if you connected it to eth0 (that's the one next to the power input). The IP address is retrieved via DHCP.


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

namespace BizTalkComponents.PipelineComponents.ManageMessageNamespace
{
    public class NavigationPath
    {
        public string Path { get; private set; }
        private readonly List<NavigationHistoryItem> _navgiationHistoryItems;

        public NavigationPath(string path, List<NavigationHistoryItem> navgiationHistoryItems )
        {
            Path = path;
            _navgiationHistoryItems = navgiationHistoryItems;
        }

        public bool IsMatch(string path)
        {
            return Path.Equals(path, StringComparison.InvariantCultureIgnoreCase);
        }

        public bool IsChildToMatching(string inPath)
        {
            var nodes = inPath.Split('/');

            if (nodes.Length > _navgiationHistoryItems.Count)
                return false;

            for (int i = 0; i < nodes.Length; i++)
            {
                if (nodes[i] != _navgiationHistoryItems[i].Name())
                    return false;
            }

            return true;
        }
    }
}


text:
layout: page
title: Youth River Financial Executive Retreat
date: 2016-05-24
author: Alice Adams
tags: weekly links, java
status: published
summary: Maecenas maximus vitae leo ut.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/19/2016
  endDate: 10/20/2016
  ctyhocn: ATLNBHX
  groupCode: YRFER
published: true
---
Donec cursus ultrices ante, ac pulvinar tellus pellentesque egestas. Aliquam a neque urna. Nulla dignissim purus nec nulla mattis, molestie mattis lectus faucibus. Mauris facilisis orci venenatis lacinia feugiat. Duis sit amet viverra justo. Ut suscipit sit amet risus sed fermentum. Maecenas finibus, sem a sagittis scelerisque, leo lacus posuere sem, a placerat nulla urna vel nunc. In congue eleifend arcu a iaculis. Donec id felis erat. Aenean luctus in purus ac suscipit. Nunc pharetra pretium sapien ut convallis. Praesent nisi nulla, condimentum eu vehicula ullamcorper, congue eu tortor. Cras malesuada arcu sed sapien vehicula, eget consectetur magna imperdiet. Praesent venenatis sapien eu nisi semper tincidunt. Cras mattis placerat diam a pharetra.

1 Curabitur ornare erat a ipsum malesuada, eget aliquam ipsum interdum.

Nunc dapibus massa ut rutrum egestas. Maecenas porttitor diam nec justo pretium facilisis. Mauris vestibulum enim vitae mi ornare faucibus. Maecenas finibus, ligula eu convallis finibus, sem quam tristique sapien, consequat elementum leo sem bibendum neque. Proin rutrum, erat eu commodo accumsan, lacus nunc dignissim nulla, nec porta purus diam vitae ante. Vestibulum non magna non nisl faucibus ornare in id nunc. Donec non aliquam nibh.


text:
import pyauto_functional  # Must be imported first
import pyauto
import test_utils

import logging
import os

class ProtectorTest(pyauto.PyUITest):
  """TestCase for Protector."""

  _default_search_id_key = 'Default Search Provider ID'

  def setUp(self):
    pyauto.PyUITest.setUp(self)
    # Get the profile path of the first profile.
    profiles = self.GetMultiProfileInfo()
    self.assertTrue(profiles['profiles'])
    self._profile_path = profiles['profiles'][0]['path']
    self.assertTrue(self._profile_path)
    # Set to the keyword of the new default search engine after a successful
    # _GetDefaultSearchEngine call.
    self._new_default_search_keyword = None

  def _GetDefaultSearchEngine(self):
    """Returns the default search engine, if any; None otherwise.

    Returns:
       Dictionary describing the default search engine. See GetSearchEngineInfo
       for an example.
    """
    for search_engine in self.GetSearchEngineInfo():
      if search_engine['is_default']:
        return search_engine
    return None

  def _OpenDatabase(self, db_name):
    """Opens a given SQLite database in the default profile.

    Args:
      db_name: name of database file (relative to the profile directory).

    Returns:
      An sqlite3.Connection instance.

    Raises:
      ImportError if sqlite3 module is not found.
    """
    db_path = os.path.join(self._profile_path, db_name)
    logging.info('Opening DB: %s' % db_path)
    import sqlite3
    db_conn = sqlite3.connect(db_path)
    db_conn.isolation_level = None
    self.assertTrue(db_conn)
    return db_conn

  def _FetchSingleValue(self, conn, query, parameters=None):
    """Executes an SQL query that should select a single row with a single
    column and returns its value.

    Args:
      conn: sqlite3.Connection instance.
      query: SQL query (may contain placeholders).
      parameters: parameters to substitute for query.

    Returns:
      Value of the column fetched.
    """
    cursor = conn.cursor()
    cursor.execute(query, parameters)
    row = cursor.fetchone()
    self.assertTrue(row)
    self.assertEqual(1, len(row))
    return row[0]

  def _UpdateSingleRow(self, conn, query, parameters=None):
    """Executes an SQL query that should update a single row.

    Args:
      conn: sqlite3.Connection instance.
      query: SQL query (may contain placeholders).
      parameters: parameters to substitute for query.
    """
    cursor = conn.cursor()
    cursor.execute(query, parameters)
    self.assertEqual(1, cursor.rowcount)

  def _ChangeDefaultSearchEngine(self):
    """Replaces the default search engine in Web Data database with another one.

    Keywords of the new default search engine is saved to
    self._new_default_search_keyword.
    """
    web_database = self._OpenDatabase('Web Data')
    default_id = int(self._FetchSingleValue(
        web_database,
        'SELECT value FROM meta WHERE key = ?',
        (self._default_search_id_key,)))
    self.assertTrue(default_id)
    new_default_id = int(self._FetchSingleValue(
        web_database,
        'SELECT id FROM keywords WHERE id != ? LIMIT 1',
        (default_id,)))
    self.assertTrue(new_default_id)
    self.assertNotEqual(default_id, new_default_id)
    self._UpdateSingleRow(web_database,
                          'UPDATE meta SET value = ? WHERE key = ?',
                          (new_default_id, self._default_search_id_key))
    self._new_default_search_keyword = self._FetchSingleValue(
        web_database,
        'SELECT keyword FROM keywords WHERE id = ?',
        (new_default_id,))
    logging.info('Update default search ID: %d -> %d (%s)' %
                 (default_id, new_default_id, self._new_default_search_keyword))
    web_database.close()

  def testNoChangeOnCleanProfile(self):
    """Test that no change is reported on a clean profile."""
    self.assertFalse(self.GetProtectorState()['showing_change'])

  def testDetectSearchEngineChangeAndApply(self):
    """Test for detecting and applying a default search engine change."""
    # Get current search engine.
    old_default_search = self._GetDefaultSearchEngine()
    self.assertTrue(old_default_search)
    # Close browser, change the search engine and start it again.
    self.RestartBrowser(clear_profile=False,
                        pre_launch_hook=self._ChangeDefaultSearchEngine)
    # The change must be detected by Protector.
    self.assertTrue(self.GetProtectorState()['showing_change'])
    default_search = self._GetDefaultSearchEngine()
    # Protector must restore the old search engine.
    self.assertEqual(old_default_search, default_search)
    self.ApplyProtectorChange()
    # Now the search engine must have changed to the new one.
    default_search = self._GetDefaultSearchEngine()
    self.assertNotEqual(old_default_search, default_search)
    self.assertEqual(self._new_default_search_keyword,
                     default_search['keyword'])
    # No longer showing the change.
    self.assertFalse(self.GetProtectorState()['showing_change'])

  def testDetectSearchEngineChangeAndDiscard(self):
    """Test for detecting and discarding a default search engine change."""
    # Get current search engine.
    old_default_search = self._GetDefaultSearchEngine()
    self.assertTrue(old_default_search)
    # Close browser, change the search engine and start it again.
    self.RestartBrowser(clear_profile=False,
                        pre_launch_hook=self._ChangeDefaultSearchEngine)
    # The change must be detected by Protector.
    self.assertTrue(self.GetProtectorState()['showing_change'])
    default_search = self._GetDefaultSearchEngine()
    # Protector must restore the old search engine.
    self.assertEqual(old_default_search, default_search)
    self.DiscardProtectorChange()
    # Old search engine remains active.
    default_search = self._GetDefaultSearchEngine()
    self.assertEqual(old_default_search, default_search)
    # No longer showing the change.
    self.assertFalse(self.GetProtectorState()['showing_change'])

  def testSearchEngineChangeDismissedOnEdit(self):
    """Test that default search engine change is dismissed when default search
    engine is changed by user.
    """
    # Get current search engine.
    old_default_search = self._GetDefaultSearchEngine()
    self.assertTrue(old_default_search)
    # Close browser, change the search engine and start it again.
    self.RestartBrowser(clear_profile=False,
                        pre_launch_hook=self._ChangeDefaultSearchEngine)
    # The change must be detected by Protector.
    self.assertTrue(self.GetProtectorState()['showing_change'])
    # Change default search engine.
    self.MakeSearchEngineDefault(self._new_default_search_keyword)
    # Change is successful.
    default_search = self._GetDefaultSearchEngine()
    self.assertEqual(self._new_default_search_keyword,
                     default_search['keyword'])
    # No longer showing the change.
    self.assertFalse(self.GetProtectorState()['showing_change'])

# TODO(ivankr): more hijacking cases (remove the current default search engine,
# add new search engines to the list, invalidate backup, etc).

if __name__ == '__main__':
  pyauto_functional.Main()


text:
This layer provides support for the PureScript language with the following packages:

- [`neoclide/coc.nvim`](https://github.com/neoclide/coc.nvim)

#### Table of Contents
- [Install](#install)
  - [Binaries](#binaries)
  - [Indentation](#indentation)
- [Language Server](#language-server)
- [Key Bindings](#key-bindings)

## Install
Add the `+lang/purescript` layer in your configuration file,

```viml
function! Layers()
  " ...
  Layer '+lang/purescript'
  " ...
endfunction
```

### Binaries
Install the language server with `npm i -g purescript-language-server`.

### Indentation
You can configure the indentation by setting `g:sp_purescript_indentation` in your user-init block (i.e. before loading the plugin). By default it is set to `2`.

## Language Server
This layer sets up the `purescript-language-server` language server for usage with coc.nvim.

## Key Bindings
Key Binding | Description
----------- | ---------------------------
            |


text:
/**
 * @file
 *   This file implements the OpenThread Network Diagnostic API.
 */

#include "openthread-core-config.h"

#include <openthread/netdiag.h>

#include "common/instance.hpp"

using namespace ot;

#if OPENTHREAD_FTD || OPENTHREAD_CONFIG_TMF_NETWORK_DIAG_MTD_ENABLE

otError otThreadGetNextDiagnosticTlv(const otMessage *      aMessage,
                                     otNetworkDiagIterator *aIterator,
                                     otNetworkDiagTlv *     aNetworkDiagTlv)
{
    return NetworkDiagnostic::NetworkDiagnostic::GetNextDiagTlv(*static_cast<const Coap::Message *>(aMessage),
                                                                *aIterator, *aNetworkDiagTlv);
}

void otThreadSetReceiveDiagnosticGetCallback(otInstance *                   aInstance,
                                             otReceiveDiagnosticGetCallback aCallback,
                                             void *                         aCallbackContext)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    instance.Get<NetworkDiagnostic::NetworkDiagnostic>().SetReceiveDiagnosticGetCallback(aCallback, aCallbackContext);
}

otError otThreadSendDiagnosticGet(otInstance *        aInstance,
                                  const otIp6Address *aDestination,
                                  const uint8_t       aTlvTypes[],
                                  uint8_t             aCount)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.Get<NetworkDiagnostic::NetworkDiagnostic>().SendDiagnosticGet(
        *static_cast<const Ip6::Address *>(aDestination), aTlvTypes, aCount);
}

otError otThreadSendDiagnosticReset(otInstance *        aInstance,
                                    const otIp6Address *aDestination,
                                    const uint8_t       aTlvTypes[],
                                    uint8_t             aCount)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.Get<NetworkDiagnostic::NetworkDiagnostic>().SendDiagnosticReset(
        *static_cast<const Ip6::Address *>(aDestination), aTlvTypes, aCount);
}

#endif // OPENTHREAD_FTD || OPENTHREAD_CONFIG_TMF_NETWORK_DIAG_MTD_ENABLE


text:
		<link rel="stylesheet" media="screen" href="{{ config.url_stylesheet }}">
		{% if config.url_favicon %}<link rel="shortcut icon" href="{{ config.url_favicon }}">{% endif %}
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
		{% if config.meta_keywords %}<meta name="keywords" content="{{ config.meta_keywords }}">{% endif %}
		{% if config.default_stylesheet.1 != '' %}<link rel="stylesheet" type="text/css" id="stylesheet" href="{{ config.uri_stylesheets }}{{ config.default_stylesheet.1 }}">{% endif %}
		{% if config.font_awesome %}<link rel="stylesheet" media="screen" href="{{ config.root }}{{ config.font_awesome_css }}">{% endif %}
		<script type="text/javascript">var configRoot="{{ config.root }}";</script>
		{% if not nojavascript %}
			<script type="text/javascript" src="{{ config.url_javascript }}"></script>
			{% if not config.additional_javascript_compile %}
			{% for javascript in config.additional_javascript %}<script type="text/javascript" src="{{ config.additional_javascript_url }}{{ javascript }}"></script>{% endfor %}
			{% endif %}
		{% endif %}
		{% if config.recaptcha %}<style type="text/css">{% raw %}
			#recaptcha_area {
				float: none !important;
				padding: 0 !important;
			}
			#recaptcha_logo, #recaptcha_privacy {
				display: none;
			}
			#recaptcha_table {
				border: none !important;
			}
			#recaptcha_table tr:first-child {
				height: auto;
			}
			.recaptchatable img {
				float: none !important;
			}
			#recaptcha_response_field {
				font-size: 10pt !important;
				border: 1px solid #a9a9a9 !important;
				padding: 1px !important;
			}
			td.recaptcha_image_cell {
				background: transparent !important;
			}
			.recaptchatable, #recaptcha_area tr, #recaptcha_area td, #recaptcha_area th {
				padding: 0 !important;
			}
		{% endraw %}</style>{% endif %}


text:
package com.nilhcem.mowitnow.core.instruction;

/**
 * Instructions to give to the mower.
 *

 * These can be either rotating or moving instructions:
 *

 *
'D' for a right rotation.

 *
'G' for a left rotation.

 *
'A' to move the mower forward.

 *

 *

 */
public enum MowerInstruction {
	RIGHT('D', 90),
	LEFT('G', -90),
	FORWARD('A', 0);

	private char letter;
	private int angle;

	private MowerInstruction(char letter, int angle) {
		this.letter = letter;
		this.angle = angle;
	}

	int getAngle() {
		return angle;
	}

	char getLetter() {
		return letter;
	}

	/**
	 * Returns the instruction for the char passed in parameter.
	 *
	 * @param ch the character of the instruction we are searching for ('D', 'G', 'A').
	 * @return the MowerInstruction object {@code null} if not found.
	 */
	public static MowerInstruction getFromChar(char ch) {
		for (MowerInstruction instruction : MowerInstruction.values()) {
			if (instruction.letter == ch) {
				return instruction;
			}
		}
		return null;
	}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Riconciliazione | React</title>
  <meta name="viewport" content="width=device-width">
  <meta property="og:title" content="Riconciliazione | React">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://facebook.github.io/react/docs/reconciliation-it-IT.html">
  <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
  <meta property="og:description" content="A JavaScript library for building user interfaces">
  <meta property="fb:app_id" content="623268441017527">

  <link rel="shortcut icon" href="/react/favicon.ico">
  <link rel="alternate" type="application/rss+xml" title="React" href="https://127.0.0.1/react/feed.xml">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
  <link rel="stylesheet" href="/react/css/syntax.css">
  <link rel="stylesheet" href="/react/css/codemirror.css">
  <link rel="stylesheet" href="/react/css/react.css">

  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

          React

Docs/文档

Support/支持

Download/下载

Blog/博客

            <input id="algolia-doc-search" type="text" placeholder="Search docs..." />

GitHub

React Native

Quick Start / 快速入门

            Getting Started
 快速开始

            Tutorial
 教程

            Thinking in React
 深入理解React

Community Resources - - - - 社区资源

            Conferences
 会议

            Videos
 视频

            Complementary Tools
 其余工具

            Examples
 范例

Guides / 指南

            Why React?
 为什么使用 React?

            Displaying Data
 数据呈现

                    JSX in Depth
 深入理解JSX

                    JSX Spread Attributes
 JSX的延展属性

                    JSX Gotchas / JSX的陷阱

            Interactivity and Dynamic UIs
 富交互性的动态用户界面

            Multiple Components
 复合组件

            Reusable Components
 可复用组件

            Transferring Props
 传递 Props

            Forms
 表单组件

            Working With the Browser
 浏览器中的工作原理

                    Refs to Components
 关于Refs的更多内容

            Tooling Integration
 整合工具

                    Language Tooling
 语言工具

                    Package Management
 包管理器

                    Server-side Environments
 服务器端环境

            Add-Ons
 插件

                    Animation
 动画

                    Two-Way Binding Helpers
 双向绑定

                    Test Utilities
 测试工具集

                    Cloning Elements
 克隆组件

                    Keyed Fragments
 键控片段

                    Immutability Helpers
 不变性的帮手

                    PureRenderMixin
 PureRenderMixin

                    Performance Tools
 性能分析工具

                    Shallow Compare
 浅的比较

            Advanced Performance
 高阶性能

            Context
 语境上下文

Reference / 参考

            Top-Level API
 顶层 API

            Component API
 组件 API

            Component Specs and Lifecycle
 组件的详细说明和生命周期

            Supported Tags and Attributes
 标签和属性支持

            Event System
 事件系统

            DOM Differences
 与 DOM 的差异

            Special Non-DOM Attributes
 特殊的非 DOM 属性

            Reconciliation
 和解

            Web Components
 Web组件

            React (Virtual) DOM Terminology
 React(虚拟)DOM 术语

Flux

            Flux Overview
  Flux概述

            Flux TodoMVC Tutorial
 Flux的TodoMVC教程

Tips / 技巧

            Introduction
 简介

            Inline Styles
 内部样式

            If-Else in JSX
 JSX 的 If-Else

            Self-Closing Tag
 自闭合标签

            Maximum Number of JSX Root Nodes
 JSF根节点最大数目

            Shorthand for Specifying Pixel Values in style props
 像素PX

            Type of the Children props
 子组件属性的类型

            Value of null for Controlled Input
 input控件的null值

            componentWillReceiveProps Not Triggered After Mounting
 Mounting后componentWillReceiveProps未自动触发

            Props in getInitialState Is an Anti-Pattern
 反模式:在getInitialState中使用Props

            DOM Event Listeners in a Component
 组件中的DOM事件监听

            Load Initial Data via AJAX
 使用AJAX加载初始化数据

            False in JSX
 在JSX中的False

            Communicate Between Components
 组件间的通信

            Expose Component Functions
 暴露组件功能

            this.props.children undefined
 this.props.children未定义

            Use React with Other Libraries
 其它类库

            Dangerously Set innerHTML
 设置innerHTML很危险

Contributing

            Design Principles

    Edit on GitHub

      Riconciliazione

La decisione chiave del design di React è fare in modo che l'API sembri ripetere il rendering dell'intera applicazione per ciascun aggiornamento. Ciò rende la scrittura delle applicazione molto più semplice, ma è anche una sfida incredibile per renderlo trattabile. Questo articolo spiega come siamo riusciti a trasformare, tramite potenti euristiche, un problema O(n3) in uno O(n).

Motivazione #

Generare il minimo numero di operazioni necessarie a trasformare un albero in un altro è un problema complesso e ben noto. Gli algoritmi dello stato dell'arte hanno una complessità dell'ordine di O(n3) dove n è il numero di nodi dell'albero.

Ciò significa che visualizzare 1000 nodi richiederebbe un numero di confronti dell'ordine del miliardo. Ciò è decisamente troppo costoso per il nostro caso d'uso. Per mettere questo numero in prospettiva, le CPU oggi giorno eseguono approssimativamente 3 miliardi di istruzioni al secondo. Quindi anche con l'implementazione più efficiente, non saremmo in grado di calcolare la differenza in meno di un secondo.

Dal momento che un algoritmo ottimo non è trattabile, implementiamo un algoritmo O(n) non ottimale usando euristiche basate su due assunzioni:

Due componenti della stessa classe genereranno alberi simili e due componenti di classi diverse genereranno alberi diversi.

È possibile fornire una chiave unica per gli elementi che sia stabile durante rendering differenti.

In pratica, queste assunzioni sono eccezionalmente veloci per quasi tutti i casi d'uso pratici.

Differenza a coppie #

Per effettuare la differenza di due alberi, dobbiamo prima essere capaci di effettuare la differenza tra due nodi. Esistono tre diversi casi da considerare.

Tipi di Nodo Differenti #

Se il tipo di nodo è differente, React li tratterà come due sottoalberi diversi, getterà via il primo e costruirà e inserirà il secondo.

renderA: <div />
renderB: <span />
=> [removeNode <div />], [insertNode <span />]

La stessa logica è usata per i componenti personalizzati. Se non sono dello stesso tipo, React non proverà neppure a confrontare ciò che visualizzano. Rimuoverà soltanto il primo dal DOM e inserirà il secondo.

renderA: <Header />
renderB: <Content />
=> [removeNode <Header />], [insertNode <Content />]

Possedere questa conoscenza di alto livello è un aspetto molto importante del perché l'algoritmo di differenza di React è sia veloce che preciso. Ciò fornisce una buona euristica per potare rapidamente gran parte dell'albero e concentrarsi su parti che hanno una buona probabilità di essere simili.

È molto improbabile che un elemento <Header> generi un DOM che somigli a quello generato da un elemento <Content>. Anziché perdere tempo provando a confrontare queste due strutture, React semplicemente ricostruisce l'albero da zero.

Come corollario, se c'è un elemento <Header> nella stessa posizione in due rendering consecutivi, ti puoi aspettare di trovare una struttura molto simile che vale la pena di esplorare.

Nodi DOM #

Quando vengono confrontati nodi DOM, guardiamo gli attributi di entrambi e decidiamo quali di essi sono cambiati in un tempo lineare.

renderA: <div id="before" />
renderB: <div id="after" />
=> [replaceAttribute id "after"]

Anziché trattare lo stile come una stringa opaca, viene rappresentato come un oggetto chiave-valore. Ciò ci permette di aggiornare solo le proprietà che sono cambiate.

renderA: <div style={{color: 'red'}} />
renderB: <div style={{fontWeight: 'bold'}} />
=> [removeStyle color], [addStyle font-weight 'bold']

Dopo che gli attributi sono stati aggiornati, effettuiamo un confronto ricorsivo su ciascuno dei nodi figli.

Componenti Personalizzati #

We decided that the two custom components are the same. Since components are stateful, we cannot just use the new component and call it a day. React takes all the attributes from the new component and calls component[Will/Did]ReceiveProps() on the previous one.

The previous component is now operational. Its render() method is called and the diff algorithm restarts with the new result and the previous result.

List-wise diff #

Problematic Case #

In order to do children reconciliation, React adopts a very naive approach. It goes over both lists of children at the same time and generates a mutation whenever there's a difference.

For example if you add an element at the end:

renderA: <div><span>first</span></div>
renderB: <div><span>first</span><span>second</span></div>
=> [insertNode <span>second</span>]

Inserting an element at the beginning is problematic. React is going to see that both nodes are spans and therefore run into a mutation mode.

renderA: <div><span>first</span></div>
renderB: <div><span>second</span><span>first</span></div>
=> [replaceAttribute textContent 'second'], [insertNode <span>first</span>]

There are many algorithms that attempt to find the minimum sets of operations to transform a list of elements. Levenshtein distance can find the minimum using single element insertion, deletion and substitution in O(n2). Even if we were to use Levenshtein, this doesn't find when a node has moved into another position and algorithms to do that have much worse complexity.

Keys #

In order to solve this seemingly intractable issue, an optional attribute has been introduced. You can provide for each child a key that is going to be used to do the matching. If you specify a key, React is now able to find insertion, deletion, substitution and moves in O(n) using a hash table.

renderA: <div><span key="first">first</span></div>
renderB: <div><span key="second">second</span><span key="first">first</span></div>
=> [insertNode <span>second</span>]

In practice, finding a key is not really hard. Most of the time, the element you are going to display already has a unique id. When that's not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. Remember that the key only has to be unique among its siblings, not globally unique.

Trade-offs #

It is important to remember that the reconciliation algorithm is an implementation detail. React could re-render the whole app on every action; the end result would be the same. We are regularly refining the heuristics in order to make common use cases faster.

In the current implementation, you can express the fact that a sub-tree has been moved amongst its siblings, but you cannot tell that it has moved somewhere else. The algorithm will re-render that full sub-tree.

Because we rely on two heuristics, if the assumptions behind them are not met, performance will suffer.

The algorithm will not try to match sub-trees of different components classes. If you see yourself alternating between two components classes with very similar output, you may want to make it the same class. In practice, we haven't found this to be an issue.

If you don't provide stable keys (by using Math.random() for example), all the sub-trees are going to be re-rendered every single time. By giving the users the choice to choose the key, they have the ability to shoot themselves in the foot.

        ← Prev(上一页)

        Next(下一页) →

        A Facebook & Instagram collaboration.

        Acknowledgements

        © 2013–2016 Facebook Inc.

        Documentation licensed under CC BY 4.0.


text:
require 'multi_json'

require 'soulmate/version'
require 'soulmate/helpers'
require 'soulmate/base'
require 'soulmate/matcher'
require 'soulmate/loader'
require 'soulmate/config'

module Soulmate
  extend Config
end


text:
An array of `UserType` can be passed in `AngularTokenOptions` at the root module with`.forRoot()`.
The user type is selected during sign in and persists until sign out.
`.currentUserType()` returns the currently logged in user.

#### Example:
```javascript
this.tokenService.init({
  userTypes: [
    { name: 'ADMIN', path: 'admin' },
    { name: 'USER', path: 'user' }
  ]
});

this.tokenService.signIn({
  login:    'example@example.com',
  password: 'secretPassword',
  userType: 'ADMIN'
})

this.tokenService.currentUserType; // ADMIN
```

## Showing/Hiding Elements based on UserType
When wanting to show or hide certain elements based on the UserRole, the following directive can be used as guideline.

```javascript
import { Directive, Input, OnInit, TemplateRef, ViewContainerRef } from '@angular/core';
import { AngularTokenService } from 'angular-token';

@Directive({
  selector: '[ifInRole]'
})
export class IfInRoleDirective implements OnInit {
  @Input('ifInRole') role: string;

  constructor(private viewContainer: ViewContainerRef,
              private templateRef: TemplateRef<any>,
              private tokenService: AngularTokenService) {
  }

  ngOnInit(): void {
    if (this.role === this.tokenService.currentUserType) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}
```

#### Example:
```html
<a routerLink="link1">Public link 1</a>
<a routerLink="link2">Public link 2</a>
<a *ifInRole="'user'" routerLink="private/link1">Private link 1</a>
<a *ifInRole="'admin'" routerLink="private/link2">Private link 2</a>
```


text:
from phusion/baseimage:0.9.15
maintainer Alexis Morelle <alexis.morelle@gmail.com>

# Prerequisites
RUN apt-get update \
    && apt-get install -y curl openjdk-7-jre\
    && rm -rf /var/lib/apt/lists/*

WORKDIR /home/spatwork

# Download Spatwork
ADD target/spatwork-uberjar.jar /home/spatwork/spatwork-uberjar.jar

# Add Frontend
ADD src/main/webapp/ /home/spatwork/src/main/webapp/

# Run
expose 8081

cmd ["java", "-jar", "spatwork-uberjar.jar"]


text:
Imports System.Runtime.InteropServices
Public Class GetSpikeFacesOfBody

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim objApplication As SolidEdgeFramework.Application = Nothing
        Dim objDoc As SolidEdgePart.PartDocument = Nothing
        Dim objModels As SolidEdgePart.Models = Nothing
        Dim objModel As SolidEdgePart.Model = Nothing
        Dim objType As Type = Nothing

        Dim dSpikeWidth As Double
        Dim NumSpikeFaces As Integer
        Dim SpikeFaces(1) As Object
        Dim WidthOfSpikeFaces(1) As Double
        dSpikeWidth = 0.2

        Try
            ' Create/get the application with specific settings
            objApplication = Marshal.GetActiveObject("SolidEdge.Application")

            If objApplication Is Nothing Then
                ' Get the type from the Solid Edge ProgID
                objType = Type.GetTypeFromProgID("SolidEdge.Application")
                ' Start Solid Edge
                objApplication = Activator.CreateInstance(objType)
                ' Make Solid Edge visible
                objApplication.Visible = True
            End If

            ' Get document
            objDoc = objApplication.ActiveDocument

            ' get the models collection
            objModels = objDoc.Models()
            objModel = objModels.Item(1)

            Call objModel.GetSpikeFacesOfBody(dSpikeWidth, NumSpikeFaces, SpikeFaces, WidthOfSpikeFaces)

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Class


text:
var clipboard = new Clipboard('.btn');

function UiViewModel() {
	self = this;
	self.source = ko.observable("");
	self.terms = ko.observableArray([ko.observable("")]);
	self.url =ko.computed(function() {
		var termsParam = self.terms().map(function(obj) {
			return encodeURIComponent(obj());
		}).join(',');
		var url = self.source();
		return newUrl = window.location.origin +
			"/ical?url=" +
			encodeURI(url) + "&containing=" + termsParam;

	});
	self.addTerm = function() {
		self.terms.push(ko.observable(""));
	};
	self.removeTerm = function(term) {
		return self.terms.remove(function(item) {
			return term == item();
		});
	};
	self.termKeyPress = function(data, event) {
		if (event.keyCode == 13) {
			self.addTerm();
			var termInputs = document.querySelectorAll('input.term');
			termInputs[termInputs.length-1].focus();
		} else {
			return true;
		}

	}
}

ko.applyBindings(new UiViewModel());