text:
package org.kie.dmn.validation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.drools.kiesession.rulebase.InternalKnowledgeBase;
import org.drools.modelcompiler.builder.KieBaseBuilder;
import org.kie.api.command.BatchExecutionCommand;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.dmn.api.core.DMNCompiler;
import org.kie.dmn.api.core.DMNCompilerConfiguration;
import org.kie.dmn.api.core.DMNMessage;
import org.kie.dmn.api.core.DMNModel;
import org.kie.dmn.backend.marshalling.v1x.DMNMarshallerFactory;
import org.kie.dmn.backend.marshalling.v1x.XStreamMarshaller;
import org.kie.dmn.backend.marshalling.v1x.XStreamMarshaller.DMN_VERSION;
import org.kie.dmn.core.api.DMNFactory;
import org.kie.dmn.core.api.DMNMessageManager;
import org.kie.dmn.core.assembler.DMNAssemblerService;
import org.kie.dmn.core.assembler.DMNResource;
import org.kie.dmn.core.assembler.DMNResourceDependenciesSorter;
import org.kie.dmn.core.compiler.DMNCompilerConfigurationImpl;
import org.kie.dmn.core.compiler.DMNCompilerImpl;
import org.kie.dmn.core.compiler.DMNProfile;
import org.kie.dmn.core.impl.DMNMessageImpl;
import org.kie.dmn.core.util.DefaultDMNMessagesManager;
import org.kie.dmn.core.util.Msg;
import org.kie.dmn.core.util.MsgUtil;
import org.kie.dmn.feel.util.ClassLoaderUtil;
import org.kie.dmn.model.api.DMNModelInstrumentedBase;
import org.kie.dmn.model.api.DecisionService;
import org.kie.dmn.model.api.Definitions;
import org.kie.dmn.validation.dtanalysis.InternalDMNDTAnalyser;
import org.kie.dmn.validation.dtanalysis.InternalDMNDTAnalyserFactory;
import org.kie.dmn.validation.dtanalysis.model.DTAnalysis;
import org.kie.internal.command.CommandFactory;
import org.kie.internal.utils.ChainedProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import static java.util.stream.Collectors.toList;
import static org.kie.dmn.validation.DMNValidator.Validation.ANALYZE_DECISION_TABLE;
import static org.kie.dmn.validation.DMNValidator.Validation.VALIDATE_COMPILATION;
import static org.kie.dmn.validation.DMNValidator.Validation.VALIDATE_MODEL;
import static org.kie.dmn.validation.DMNValidator.Validation.VALIDATE_SCHEMA;

public class DMNValidatorImpl implements DMNValidator {
    public static final Logger LOG = LoggerFactory.getLogger(DMNValidatorImpl.class);
    static final Schema schemav1_1;
    static {
        try {
            schemav1_1 = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                  .newSchema(new StreamSource(DMNValidatorImpl.class.getResourceAsStream("org/omg/spec/DMN/20151101/dmn.xsd")));
        } catch (SAXException e) {
            throw new RuntimeException("Unable to initialize correctly DMNValidator.", e);
        }
    }
    static final Schema schemav1_2;
    static {
        try {
            schemav1_2 = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                      .newSchema(new Source[]{new StreamSource(DMNValidatorImpl.class.getResourceAsStream("org/omg/spec/DMN/20180521/DC.xsd")),
                                                              new StreamSource(DMNValidatorImpl.class.getResourceAsStream("org/omg/spec/DMN/20180521/DI.xsd")),
                                                              new StreamSource(DMNValidatorImpl.class.getResourceAsStream("org/omg/spec/DMN/20180521/DMNDI12.xsd")),
                                                              new StreamSource(DMNValidatorImpl.class.getResourceAsStream("org/omg/spec/DMN/20180521/DMN12.xsd"))
                                      });
        } catch (SAXException e) {
            throw new RuntimeException("Unable to initialize correctly DMNValidator.", e);
        }
    }
    static final Schema schemav1_3;
    static {
        try {
            schemav1_3 = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                      .newSchema(new Source[]{new StreamSource(DMNValidatorImpl.class.getResourceAsStream("org/omg/spec/DMN/20191111/DC.xsd")),
                                                              new StreamSource(DMNValidatorImpl.class.getResourceAsStream("org/omg/spec/DMN/20191111/DI.xsd")),
                                                              new StreamSource(DMNValidatorImpl.class.getResourceAsStream("org/omg/spec/DMN/20191111/DMNDI13.xsd")),
                                                              new StreamSource(DMNValidatorImpl.class.getResourceAsStream("org/omg/spec/DMN/20191111/DMN13.xsd"))
                                      });
        } catch (SAXException e) {
            throw new RuntimeException("Unable to initialize correctly DMNValidator.", e);
        }
    }

    private Schema overrideSchema = null;

    /**
     * Collect at init time the runtime issues which prevented to build the `kieContainer` correctly.
     */
    private List<DMNMessage> failedInitMsg = new ArrayList<>();

    private final List<DMNProfile> dmnProfiles = new ArrayList<>();
    private final DMNCompilerConfiguration dmnCompilerConfig;

    private final InternalDMNDTAnalyser dmnDTValidator;
    private InternalKnowledgeBase kb11;
    private InternalKnowledgeBase kb12;

    public DMNValidatorImpl(ClassLoader cl, List<DMNProfile> dmnProfiles, Properties p) {
        kb11 = KieBaseBuilder.createKieBaseFromModel(Arrays.asList(org.kie.dmn.validation.bootstrap.ValidationBootstrapModels.V1X_MODEL,
                                                                   org.kie.dmn.validation.bootstrap.ValidationBootstrapModels.V11_MODEL));
        kb12 = KieBaseBuilder.createKieBaseFromModel(Arrays.asList(org.kie.dmn.validation.bootstrap.ValidationBootstrapModels.V1X_MODEL,
                                                                   org.kie.dmn.validation.bootstrap.ValidationBootstrapModels.V12_MODEL));
        ChainedProperties localChainedProperties = new ChainedProperties();
        if (p != null) {
            localChainedProperties.addProperties(p);
        }
        this.dmnProfiles.addAll(DMNAssemblerService.getDefaultDMNProfiles(localChainedProperties));
        this.dmnProfiles.addAll(dmnProfiles);
        final ClassLoader classLoader = cl == null ? ClassLoaderUtil.findDefaultClassLoader() : cl;
        DMNCompilerConfigurationImpl dmnCompilerConfiguration = DMNAssemblerService.compilerConfigWithKModulePrefs(classLoader,
                                                                                localChainedProperties,
                                                                                this.dmnProfiles,
                                                                                (DMNCompilerConfigurationImpl) DMNFactory.newCompilerConfiguration());
        try {
            DMNAssemblerService.applyDecisionLogicCompilerFactory(classLoader, dmnCompilerConfiguration);
        } catch (Exception e) {
            throw new IllegalStateException("Unable to initialize DMNCompiler decisionlogicCompilerFactory based on parameters provided", e);
        }
        this.dmnCompilerConfig = dmnCompilerConfiguration;
        dmnDTValidator = InternalDMNDTAnalyserFactory.newDMNDTAnalyser(this.dmnProfiles);
    }

    @Override
    public void dispose() {
        // since exec model, no more kieContainer to dispose
    }

    public static class ValidatorBuilderImpl implements ValidatorBuilder {

        private final EnumSet<Validation> flags;
        private final DMNValidatorImpl validator;
        private ValidatorImportReaderResolver importResolver;

        public ValidatorBuilderImpl(DMNValidatorImpl dmnValidatorImpl, Validation[] options) {
            this.validator = dmnValidatorImpl;
            this.flags = EnumSet.copyOf(Arrays.asList(options));
        }

        @Override
        public ValidatorBuilder usingImports(ValidatorImportReaderResolver r) {
            this.importResolver = r;
            return this;
        }

        @Override
        public ValidatorBuilder usingSchema(Schema r) {
            validator.setOverrideSchema(r);
            return this;
        }

        @Override
        public List<DMNMessage> theseModels(File... files) {
            DMNMessageManager results = new DefaultDMNMessagesManager();
            try {
                Reader[] readers = new Reader[files.length];
                for (int i = 0; i < files.length; i++) {
                    readers[i] = new FileReader(files[i]);
                }
                results.addAll(theseModels(readers));
            } catch (Throwable t) {
                MsgUtil.reportMessage(LOG,
                                      DMNMessage.Severity.ERROR,
                                      null,
                                      results,
                                      t,
                                      null,
                                      Msg.VALIDATION_RUNTIME_PROBLEM,
                                      t.getMessage());
            }
            return results.getMessages();
        }

        @Override
        public List<DMNMessage> theseModels(Reader... readers) {
            DMNMessageManager results = new DefaultDMNMessagesManager();
            List<Definitions> models = new ArrayList<>();
            for (Reader reader : readers) {
                try {
                    String content = readContent(reader);
                    if (flags.contains(VALIDATE_SCHEMA)) {
                        results.addAll(validator.validateSchema(new StringReader(content)));
                    }
                    Definitions dmndefs = unmarshalDefinitionsFromReader(validator.dmnCompilerConfig, new StringReader(content));
                    models.add(dmndefs);
                } catch (Exception t) {
                    MsgUtil.reportMessage(LOG,
                                          DMNMessage.Severity.ERROR,
                                          null,
                                          results,
                                          t,
                                          null,
                                          Msg.VALIDATION_RUNTIME_PROBLEM,
                                          t.getMessage());
                }
            }
            if (flags.contains(VALIDATE_MODEL) || flags.contains(VALIDATE_COMPILATION) || flags.contains(ANALYZE_DECISION_TABLE)) {
                if (results.hasErrors()) {
                    MsgUtil.reportMessage(LOG,
                                          DMNMessage.Severity.ERROR,
                                          null,
                                          results,
                                          null,
                                          null,
                                          Msg.VALIDATION_STOPPED);
                    return results.getMessages();
                }
                validateDefinitions(internalValidatorSortModels(models), results);
            }
            return results.getMessages();
        }

        @Override
        public List<DMNMessage> theseModels(Definitions... models) {
            DMNMessageManager results = new DefaultDMNMessagesManager();
            if (flags.contains(VALIDATE_SCHEMA)) {
                MsgUtil.reportMessage(LOG,
                                      DMNMessage.Severity.ERROR,
                                      null,
                                      results,
                                      null,
                                      null,
                                      Msg.FAILED_NO_XML_SOURCE);
            }
            if (flags.contains(VALIDATE_MODEL) || flags.contains(VALIDATE_COMPILATION) || flags.contains(ANALYZE_DECISION_TABLE)) {
                if (results.hasErrors()) {
                    MsgUtil.reportMessage(LOG,
                                          DMNMessage.Severity.ERROR,
                                          null,
                                          results,
                                          null,
                                          null,
                                          Msg.VALIDATION_STOPPED);
                    return results.getMessages();
                }
                validateDefinitions(internalValidatorSortModels(Arrays.asList(models)), results);
            }
            return results.getMessages();
        }

        private void validateDefinitions(List<Definitions> definitions, DMNMessageManager results) {
            List<Definitions> otherModel_Definitions = new ArrayList<>();
            List<DMNModel> otherModel_DMNModels = new ArrayList<>();
            for (Definitions dmnModel : definitions) {
                try {
                    if (flags.contains(VALIDATE_MODEL)) {
                        results.addAll(validator.validateModel(dmnModel, otherModel_Definitions));
                        otherModel_Definitions.add(dmnModel);
                    }
                    if (flags.contains(VALIDATE_COMPILATION) || flags.contains(ANALYZE_DECISION_TABLE)) {
                        DMNCompilerImpl compiler = new DMNCompilerImpl(validator.dmnCompilerConfig);
                        Function<String, Reader> relativeResolver = null;
                        if (importResolver != null) {
                            relativeResolver = locationURI -> importResolver.newReader(dmnModel.getNamespace(),
                                                                                dmnModel.getName(),
                                                                                locationURI);
                        }
                        DMNModel model = compiler.compile(dmnModel,
                                                          otherModel_DMNModels,
                                                          null,
                                                          relativeResolver);
                        if (model != null) {
                            results.addAll(model.getMessages());
                            otherModel_DMNModels.add(model);
                            if (flags.contains(ANALYZE_DECISION_TABLE)) {
                                List<DTAnalysis> vs = validator.dmnDTValidator.analyse(model, flags);
                                List<DMNMessage> dtAnalysisResults = vs.stream().flatMap(a -> a.asDMNMessages().stream()).collect(Collectors.toList());
                                results.addAllUnfiltered(dtAnalysisResults);
                            }
                        } else {
                            throw new IllegalStateException("Compiled model is null!");
                        }
                    }
                } catch (Throwable t) {
                    MsgUtil.reportMessage(LOG,
                                          DMNMessage.Severity.ERROR,
                                          null,
                                          results,
                                          t,
                                          null,
                                          Msg.VALIDATION_RUNTIME_PROBLEM,
                                          t.getMessage());
                }
            }
        }

        private List<Definitions> internalValidatorSortModels(List<Definitions> ms) {
            List<DMNResource> dmnResources = ms.stream().map(d -> new DMNResource(new QName(d.getNamespace(), d.getName()), null, d)).collect(Collectors.toList());
            DMNAssemblerService.enrichDMNResourcesWithImportsDependencies(dmnResources, Collections.emptyList());
            List<DMNResource> sortedDmnResources = DMNResourceDependenciesSorter.sort(dmnResources);
            return sortedDmnResources.stream().map(d -> d.getDefinitions()).collect(Collectors.toList());
        }
    }

    public Schema getOverrideSchema() {
        return overrideSchema;
    }

    public void setOverrideSchema(Schema overrideSchema) {
        this.overrideSchema = overrideSchema;
    }

    public ValidatorBuilder validateUsing(Validation... options) {
        return new ValidatorBuilderImpl(this, options);
    }

    @Override
    public List<DMNMessage> validate(Definitions dmnModel) {
        return validate( dmnModel, VALIDATE_MODEL );
    }

    @Override
    public List<DMNMessage> validate(Definitions dmnModel, Validation... options) {
        DMNMessageManager results = new DefaultDMNMessagesManager();
        EnumSet<Validation> flags = EnumSet.copyOf( Arrays.asList( options ) );
        if( flags.contains( VALIDATE_SCHEMA ) ) {
            MsgUtil.reportMessage( LOG,
                                   DMNMessage.Severity.ERROR,
                                   dmnModel,
                                   results,
                                   null,
                                   null,
                                   Msg.FAILED_NO_XML_SOURCE );
        }
        try {
            validateModelCompilation( dmnModel, results, flags );
        } catch ( Throwable t ) {
            MsgUtil.reportMessage(LOG,
                                  DMNMessage.Severity.ERROR,
                                  null,
                                  results,
                                  t,
                                  null,
                                  Msg.VALIDATION_RUNTIME_PROBLEM,
                                  t.getMessage());
        }
        return results.getMessages();
    }

    @Override
    public List<DMNMessage> validate(File xmlFile) {
        return validate( xmlFile, VALIDATE_MODEL );
    }

    @Override
    public List<DMNMessage> validate(File xmlFile, Validation... options) {
        DMNMessageManager results = new DefaultDMNMessagesManager(  );
        EnumSet<Validation> flags = EnumSet.copyOf( Arrays.asList( options ) );
        if( flags.contains( VALIDATE_SCHEMA ) ) {
            results.addAll( validateSchema( xmlFile ) );
        }
        if( flags.contains( VALIDATE_MODEL ) || flags.contains( VALIDATE_COMPILATION ) || flags.contains( ANALYZE_DECISION_TABLE ) ) {
            Definitions dmndefs = null;
            try {
                dmndefs = DMNMarshallerFactory.newMarshallerWithExtensions(dmnCompilerConfig.getRegisteredExtensions()).unmarshal(new FileReader(xmlFile));
                dmndefs.normalize();
                validateModelCompilation( dmndefs, results, flags );
            } catch ( Throwable t ) {
                MsgUtil.reportMessage(LOG,
                                      DMNMessage.Severity.ERROR,
                                      null,
                                      results,
                                      t,
                                      null,
                                      Msg.VALIDATION_RUNTIME_PROBLEM,
                                      t.getMessage());
            }
        }
        return results.getMessages();
    }

    @Override
    public List<DMNMessage> validate(Reader reader) {
        return validate( reader, VALIDATE_MODEL );
    }

    @Override
    public List<DMNMessage> validate(Reader reader, Validation... options) {
        DMNMessageManager results = new DefaultDMNMessagesManager(  );
        EnumSet<Validation> flags = EnumSet.copyOf( Arrays.asList( options ) );
        try {
            String content = readContent( reader );
            if( flags.contains( VALIDATE_SCHEMA ) ) {
                results.addAll( validateSchema( new StringReader( content ) ) );
            }
            if( flags.contains( VALIDATE_MODEL ) || flags.contains( VALIDATE_COMPILATION ) || flags.contains( ANALYZE_DECISION_TABLE ) ) {
                Definitions dmndefs = unmarshalDefinitionsFromReader(dmnCompilerConfig, new StringReader(content));
                validateModelCompilation( dmndefs, results, flags );
            }
        } catch ( Throwable t ) {
            MsgUtil.reportMessage(LOG,
                                  DMNMessage.Severity.ERROR,
                                  null,
                                  results,
                                  t,
                                  null,
                                  Msg.VALIDATION_RUNTIME_PROBLEM,
                                  t.getMessage());
        }
        return results.getMessages();
    }

    private static String readContent(Reader reader)
            throws IOException {
        char[] b = new char[32 * 1024];
        StringBuilder content = new StringBuilder(  );
        int chars = -1;
        while( (chars = reader.read( b ) ) > 0 ) {
            content.append( b, 0, chars );
        }
        return content.toString();
    }

    private static Definitions unmarshalDefinitionsFromReader(DMNCompilerConfiguration config, Reader reader) {
        Definitions dmndefs = DMNMarshallerFactory.newMarshallerWithExtensions(config.getRegisteredExtensions()).unmarshal(reader);
        dmndefs.normalize();
        return dmndefs;
    }

    private void validateModelCompilation(Definitions dmnModel, DMNMessageManager results, EnumSet<Validation> flags) {
        if( flags.contains( VALIDATE_MODEL ) ) {
            results.addAll(validateModel(dmnModel, Collections.emptyList()));
        }
        if( flags.contains( VALIDATE_COMPILATION ) ) {
            results.addAll( validateCompilation( dmnModel ) );
        }
        if (flags.contains( ANALYZE_DECISION_TABLE )) {
            results.addAllUnfiltered(analyseDT(dmnModel, flags));
        }
    }

    private List<DMNMessage> validateSchema(File xmlFile) {
        List<DMNMessage> problems = new ArrayList<>();
        try {
            DMN_VERSION inferDMNVersion = XStreamMarshaller.inferDMNVersion(new FileReader(xmlFile));
            Source s = new StreamSource(xmlFile);
            switch (inferDMNVersion) {
                case DMN_v1_1:
                    return validateSchema(s, schemav1_1);
                case DMN_v1_2:
                    return validateSchema(s, schemav1_2);
                case DMN_v1_3:
                case UNKNOWN:
                default:
                    return validateSchema(s, schemav1_3);
            }
        } catch (Exception e) {
            problems.add(new DMNMessageImpl(DMNMessage.Severity.ERROR, MsgUtil.createMessage(Msg.FAILED_XML_VALIDATION, e.getMessage()), Msg.FAILED_XML_VALIDATION.getType(), null, e));
        }
        return problems;
    }

    private List<DMNMessage> validateSchema(Reader reader) {
        List<DMNMessage> problems = new ArrayList<>();
        try (BufferedReader buffer = new BufferedReader(reader)) {
            String xml = buffer.lines().collect(Collectors.joining("\n"));
            DMN_VERSION inferDMNVersion = XStreamMarshaller.inferDMNVersion(new StringReader(xml));
            Source s = new StreamSource(new StringReader(xml));
            switch (inferDMNVersion) {
                case DMN_v1_1:
                    return validateSchema(s, schemav1_1);
                case DMN_v1_2:
                    return validateSchema(s, schemav1_2);
                case DMN_v1_3:
                case UNKNOWN:
                default:
                    return validateSchema(s, schemav1_3);
            }
        } catch (Exception e) {
            problems.add(new DMNMessageImpl(DMNMessage.Severity.ERROR, MsgUtil.createMessage(Msg.FAILED_XML_VALIDATION, e.getMessage()), Msg.FAILED_XML_VALIDATION.getType(), null, e));
        }
        return problems;
    }

    private List<DMNMessage> validateSchema(Source s, Schema s2) {
        Schema using = overrideSchema != null ? overrideSchema : s2;
        List<DMNMessage> problems = new ArrayList<>();
        try {
            Validator validator = using.newValidator();
            validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
            validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
            validator.validate(s);
        } catch (SAXException | IOException e) {
            problems.add(new DMNMessageImpl(DMNMessage.Severity.ERROR, MsgUtil.createMessage(Msg.FAILED_XML_VALIDATION, e.getMessage()), Msg.FAILED_XML_VALIDATION.getType(), null, e));
        }
        return problems;
    }

    private List<DMNMessage> validateModel(Definitions dmnModel, List<Definitions> otherModel_Definitions) {
        StatelessKieSession kieSession = dmnModel instanceof org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase ? kb11.newStatelessKieSession() : kb12.newStatelessKieSession();
        MessageReporter reporter = new MessageReporter();
        kieSession.setGlobal( "reporter", reporter );

        // exclude dynamicDecisionService for validation
        List<DMNModelInstrumentedBase> dmnModelElements = allChildren(dmnModel)
                       .filter(d -> !(d instanceof DecisionService &&
                               Boolean.parseBoolean(d.getAdditionalAttributes().get(new QName("http://www.trisotech.com/2015/triso/modeling", "dynamicDecisionService")))))
                       .collect(toList());
        BatchExecutionCommand batch = CommandFactory.newBatchExecution(Arrays.asList(CommandFactory.newInsertElements(dmnModelElements, "DEFAULT", false, "DEFAULT"),
                                                                                CommandFactory.newInsertElements(otherModel_Definitions, "DMNImports", false, "DMNImports")));
        kieSession.execute(batch);

        return reporter.getMessages().getMessages();
    }

    private List<DMNMessage> validateCompilation(Definitions dmnModel) {
        if( dmnModel != null ) {
            DMNCompiler compiler = new DMNCompilerImpl(dmnCompilerConfig);
            DMNModel model = compiler.compile( dmnModel );
            if( model != null ) {
                return model.getMessages();
            } else {
                throw new IllegalStateException("Compiled model is null!");
            }
        }
        return Collections.emptyList();
    }

    private List<DMNMessage> analyseDT(Definitions dmnModel, Set<Validation> flags) {
        if (dmnModel != null) {
            DMNCompilerImpl compiler = new DMNCompilerImpl(dmnCompilerConfig);
            DMNModel model = compiler.compile(dmnModel);
            if (model != null) {
                List<DTAnalysis> vs = dmnDTValidator.analyse(model, flags);
                List<DMNMessage> results = vs.stream().flatMap(a -> a.asDMNMessages().stream()).collect(Collectors.toList());
                return results;
            } else {
                throw new IllegalStateException("Compiled model is null!");
            }
        }
        return Collections.emptyList();
    }

    private static Stream<DMNModelInstrumentedBase> allChildren(DMNModelInstrumentedBase root) {
        return Stream.concat( Stream.of(root),
                              root.getChildren().stream().flatMap(DMNValidatorImpl::allChildren) );
    }
}


text:
package org.wikipedia.database;

public class UserOptionContentProvider extends AppContentProvider {
}

redpajama_set_name: RedPajamaGithub


text:
import fixtures
from requests_mock.contrib import fixture as requests_mock_fixture

from cinderclient import client
from cinderclient import exceptions
from cinderclient import shell
from cinderclient.v1 import shell as shell_v1
from cinderclient.tests.v1 import fakes
from cinderclient.tests import utils
from cinderclient.tests.fixture_data import keystone_client

class ShellTest(utils.TestCase):

    FAKE_ENV = {
        'CINDER_USERNAME': 'username',
        'CINDER_PASSWORD': 'password',
        'CINDER_PROJECT_ID': 'project_id',
        'OS_VOLUME_API_VERSION': '1',
        'CINDER_URL': keystone_client.BASE_URL,
    }

    # Patch os.environ to avoid required auth info.
    def setUp(self):
        """Run before each test."""
        super(ShellTest, self).setUp()
        for var in self.FAKE_ENV:
            self.useFixture(fixtures.EnvironmentVariable(var,
                                                         self.FAKE_ENV[var]))

        self.shell = shell.OpenStackCinderShell()

        # HACK(bcwaldon): replace this when we start using stubs
        self.old_get_client_class = client.get_client_class
        client.get_client_class = lambda *_: fakes.FakeClient

        self.requests = self.useFixture(requests_mock_fixture.Fixture())
        self.requests.register_uri(
            'GET', keystone_client.BASE_URL,
            text=keystone_client.keystone_request_callback)

    def tearDown(self):
        # For some method like test_image_meta_bad_action we are
        # testing a SystemExit to be thrown and object self.shell has
        # no time to get instantatiated which is OK in this case, so
        # we make sure the method is there before launching it.
        if hasattr(self.shell, 'cs'):
            self.shell.cs.clear_callstack()

        # HACK(bcwaldon): replace this when we start using stubs
        client.get_client_class = self.old_get_client_class
        super(ShellTest, self).tearDown()

    def run_command(self, cmd):
        self.shell.main(cmd.split())

    def assert_called(self, method, url, body=None, **kwargs):
        return self.shell.cs.assert_called(method, url, body, **kwargs)

    def assert_called_anytime(self, method, url, body=None):
        return self.shell.cs.assert_called_anytime(method, url, body)

    def test_extract_metadata(self):
        # mimic the result of argparse's parse_args() method
        class Arguments:

            def __init__(self, metadata=[]):
                self.metadata = metadata

        inputs = [
            ([], {}),
            (["key=value"], {"key": "value"}),
            (["key"], {"key": None}),
            (["k1=v1", "k2=v2"], {"k1": "v1", "k2": "v2"}),
            (["k1=v1", "k2"], {"k1": "v1", "k2": None}),
            (["k1", "k2=v2"], {"k1": None, "k2": "v2"})
        ]

        for input in inputs:
            args = Arguments(metadata=input[0])
            self.assertEqual(input[1], shell_v1._extract_metadata(args))

    def test_translate_volume_keys(self):
        cs = fakes.FakeClient()
        v = cs.volumes.list()[0]
        setattr(v, 'os-vol-tenant-attr:tenant_id', 'fake_tenant')
        setattr(v, '_info', {'attachments': [{'server_id': 1234}],
                'id': 1234, 'name': 'sample-volume',
                'os-vol-tenant-attr:tenant_id': 'fake_tenant'})
        shell_v1._translate_volume_keys([v])
        self.assertEqual(v.tenant_id, 'fake_tenant')

    def test_list(self):
        self.run_command('list')
        # NOTE(jdg): we default to detail currently
        self.assert_called('GET', '/volumes/detail')

    def test_list_filter_status(self):
        self.run_command('list --status=available')
        self.assert_called('GET', '/volumes/detail?status=available')

    def test_list_filter_display_name(self):
        self.run_command('list --display-name=1234')
        self.assert_called('GET', '/volumes/detail?display_name=1234')

    def test_list_all_tenants(self):
        self.run_command('list --all-tenants=1')
        self.assert_called('GET', '/volumes/detail?all_tenants=1')

    def test_list_availability_zone(self):
        self.run_command('availability-zone-list')
        self.assert_called('GET', '/os-availability-zone')

    def test_show(self):
        self.run_command('show 1234')
        self.assert_called('GET', '/volumes/1234')

    def test_delete(self):
        self.run_command('delete 1234')
        self.assert_called('DELETE', '/volumes/1234')

    def test_delete_by_name(self):
        self.run_command('delete sample-volume')
        self.assert_called_anytime('GET', '/volumes/detail?all_tenants=1')
        self.assert_called('DELETE', '/volumes/1234')

    def test_delete_multiple(self):
        self.run_command('delete 1234 5678')
        self.assert_called_anytime('DELETE', '/volumes/1234')
        self.assert_called('DELETE', '/volumes/5678')

    def test_backup(self):
        self.run_command('backup-create 1234')
        self.assert_called('POST', '/backups')

    def test_restore(self):
        self.run_command('backup-restore 1234')
        self.assert_called('POST', '/backups/1234/restore')

    def test_snapshot_list_filter_volume_id(self):
        self.run_command('snapshot-list --volume-id=1234')
        self.assert_called('GET', '/snapshots/detail?volume_id=1234')

    def test_snapshot_list_filter_status_and_volume_id(self):
        self.run_command('snapshot-list --status=available --volume-id=1234')
        self.assert_called('GET', '/snapshots/detail?'
                           'status=available&volume_id=1234')

    def test_rename(self):
        # basic rename with positional arguments
        self.run_command('rename 1234 new-name')
        expected = {'volume': {'display_name': 'new-name'}}
        self.assert_called('PUT', '/volumes/1234', body=expected)
        # change description only
        self.run_command('rename 1234 --display-description=new-description')
        expected = {'volume': {'display_description': 'new-description'}}
        self.assert_called('PUT', '/volumes/1234', body=expected)
        # rename and change description
        self.run_command('rename 1234 new-name '
                         '--display-description=new-description')
        expected = {'volume': {
            'display_name': 'new-name',
            'display_description': 'new-description',
        }}
        self.assert_called('PUT', '/volumes/1234', body=expected)

        # Call rename with no arguments
        self.assertRaises(SystemExit, self.run_command, 'rename')

    def test_rename_snapshot(self):
        # basic rename with positional arguments
        self.run_command('snapshot-rename 1234 new-name')
        expected = {'snapshot': {'display_name': 'new-name'}}
        self.assert_called('PUT', '/snapshots/1234', body=expected)
        # change description only
        self.run_command('snapshot-rename 1234 '
                         '--display-description=new-description')
        expected = {'snapshot': {'display_description': 'new-description'}}
        self.assert_called('PUT', '/snapshots/1234', body=expected)
        # snapshot-rename and change description
        self.run_command('snapshot-rename 1234 new-name '
                         '--display-description=new-description')
        expected = {'snapshot': {
            'display_name': 'new-name',
            'display_description': 'new-description',
        }}
        self.assert_called('PUT', '/snapshots/1234', body=expected)

        # Call snapshot-rename with no arguments
        self.assertRaises(SystemExit, self.run_command, 'snapshot-rename')

    def test_set_metadata_set(self):
        self.run_command('metadata 1234 set key1=val1 key2=val2')
        self.assert_called('POST', '/volumes/1234/metadata',
                           {'metadata': {'key1': 'val1', 'key2': 'val2'}})

    def test_set_metadata_delete_dict(self):
        self.run_command('metadata 1234 unset key1=val1 key2=val2')
        self.assert_called('DELETE', '/volumes/1234/metadata/key1')
        self.assert_called('DELETE', '/volumes/1234/metadata/key2', pos=-2)

    def test_set_metadata_delete_keys(self):
        self.run_command('metadata 1234 unset key1 key2')
        self.assert_called('DELETE', '/volumes/1234/metadata/key1')
        self.assert_called('DELETE', '/volumes/1234/metadata/key2', pos=-2)

    def test_reset_state(self):
        self.run_command('reset-state 1234')
        expected = {'os-reset_status': {'status': 'available'}}
        self.assert_called('POST', '/volumes/1234/action', body=expected)

    def test_reset_state_with_flag(self):
        self.run_command('reset-state --state error 1234')
        expected = {'os-reset_status': {'status': 'error'}}
        self.assert_called('POST', '/volumes/1234/action', body=expected)

    def test_reset_state_multiple(self):
        self.run_command('reset-state 1234 5678 --state error')
        expected = {'os-reset_status': {'status': 'error'}}
        self.assert_called_anytime('POST', '/volumes/1234/action',
                                   body=expected)
        self.assert_called_anytime('POST', '/volumes/5678/action',
                                   body=expected)

    def test_reset_state_two_with_one_nonexistent(self):
        cmd = 'reset-state 1234 123456789'
        self.assertRaises(exceptions.CommandError, self.run_command, cmd)
        expected = {'os-reset_status': {'status': 'available'}}
        self.assert_called_anytime('POST', '/volumes/1234/action',
                                   body=expected)

    def test_reset_state_one_with_one_nonexistent(self):
        cmd = 'reset-state 123456789'
        self.assertRaises(exceptions.CommandError, self.run_command, cmd)

    def test_snapshot_reset_state(self):
        self.run_command('snapshot-reset-state 1234')
        expected = {'os-reset_status': {'status': 'available'}}
        self.assert_called('POST', '/snapshots/1234/action', body=expected)

    def test_snapshot_reset_state_with_flag(self):
        self.run_command('snapshot-reset-state --state error 1234')
        expected = {'os-reset_status': {'status': 'error'}}
        self.assert_called('POST', '/snapshots/1234/action', body=expected)

    def test_snapshot_reset_state_multiple(self):
        self.run_command('snapshot-reset-state 1234 5678')
        expected = {'os-reset_status': {'status': 'available'}}
        self.assert_called_anytime('POST', '/snapshots/1234/action',
                                   body=expected)
        self.assert_called_anytime('POST', '/snapshots/5678/action',
                                   body=expected)

    def test_encryption_type_list(self):
        """
        Test encryption-type-list shell command.

        Verify a series of GET requests are made:
        - one to get the volume type list information
        - one per volume type to retrieve the encryption type information
        """
        self.run_command('encryption-type-list')
        self.assert_called_anytime('GET', '/types')
        self.assert_called_anytime('GET', '/types/1/encryption')
        self.assert_called_anytime('GET', '/types/2/encryption')

    def test_encryption_type_show(self):
        """
        Test encryption-type-show shell command.

        Verify two GET requests are made per command invocation:
        - one to get the volume type information
        - one to get the encryption type information
        """
        self.run_command('encryption-type-show 1')
        self.assert_called('GET', '/types/1/encryption')
        self.assert_called_anytime('GET', '/types/1')

    def test_encryption_type_create(self):
        """
        Test encryption-type-create shell command.

        Verify GET and POST requests are made per command invocation:
        - one GET request to retrieve the relevant volume type information
        - one POST request to create the new encryption type
        """
        expected = {'encryption': {'cipher': None, 'key_size': None,
                                   'provider': 'TestProvider',
                                   'control_location': 'front-end'}}
        self.run_command('encryption-type-create 2 TestProvider')
        self.assert_called('POST', '/types/2/encryption', body=expected)
        self.assert_called_anytime('GET', '/types/2')

    def test_encryption_type_update(self):
        """
        Test encryption-type-update shell command.

        Verify two GETs/one PUT requests are made per command invocation:
        - one GET request to retrieve the relevant volume type information
        - one GET request to retrieve the relevant encryption type information
        - one PUT request to update the encryption type information
        """
        self.skipTest("Not implemented")

    def test_encryption_type_delete(self):
        """
        Test encryption-type-delete shell command.

        Verify one GET/one DELETE requests are made per command invocation:
        - one GET request to retrieve the relevant volume type information
        - one DELETE request to delete the encryption type information
        """
        self.run_command('encryption-type-delete 1')
        self.assert_called('DELETE', '/types/1/encryption/provider')
        self.assert_called_anytime('GET', '/types/1')

    def test_migrate_volume(self):
        self.run_command('migrate 1234 fakehost --force-host-copy=True')
        expected = {'os-migrate_volume': {'force_host_copy': 'True',
                                          'host': 'fakehost'}}
        self.assert_called('POST', '/volumes/1234/action', body=expected)

    def test_snapshot_metadata_set(self):
        self.run_command('snapshot-metadata 1234 set key1=val1 key2=val2')
        self.assert_called('POST', '/snapshots/1234/metadata',
                           {'metadata': {'key1': 'val1', 'key2': 'val2'}})

    def test_snapshot_metadata_unset_dict(self):
        self.run_command('snapshot-metadata 1234 unset key1=val1 key2=val2')
        self.assert_called_anytime('DELETE', '/snapshots/1234/metadata/key1')
        self.assert_called_anytime('DELETE', '/snapshots/1234/metadata/key2')

    def test_snapshot_metadata_unset_keys(self):
        self.run_command('snapshot-metadata 1234 unset key1 key2')
        self.assert_called_anytime('DELETE', '/snapshots/1234/metadata/key1')
        self.assert_called_anytime('DELETE', '/snapshots/1234/metadata/key2')

    def test_volume_metadata_update_all(self):
        self.run_command('metadata-update-all 1234 key1=val1 key2=val2')
        self.assert_called('PUT', '/volumes/1234/metadata',
                           {'metadata': {'key1': 'val1', 'key2': 'val2'}})

    def test_snapshot_metadata_update_all(self):
        self.run_command('snapshot-metadata-update-all\
                         1234 key1=val1 key2=val2')
        self.assert_called('PUT', '/snapshots/1234/metadata',
                           {'metadata': {'key1': 'val1', 'key2': 'val2'}})

    def test_readonly_mode_update(self):
        self.run_command('readonly-mode-update 1234 True')
        expected = {'os-update_readonly_flag': {'readonly': True}}
        self.assert_called('POST', '/volumes/1234/action', body=expected)

        self.run_command('readonly-mode-update 1234 False')
        expected = {'os-update_readonly_flag': {'readonly': False}}
        self.assert_called('POST', '/volumes/1234/action', body=expected)

    def test_service_disable(self):
        self.run_command('service-disable host cinder-volume')
        self.assert_called('PUT', '/os-services/disable',
                           {"binary": "cinder-volume", "host": "host"})

    def test_services_disable_with_reason(self):
        cmd = 'service-disable host cinder-volume --reason no_reason'
        self.run_command(cmd)
        body = {'host': 'host', 'binary': 'cinder-volume',
                'disabled_reason': 'no_reason'}
        self.assert_called('PUT', '/os-services/disable-log-reason', body)

    def test_service_enable(self):
        self.run_command('service-enable host cinder-volume')
        self.assert_called('PUT', '/os-services/enable',
                           {"binary": "cinder-volume", "host": "host"})

    def test_snapshot_delete(self):
        self.run_command('snapshot-delete 1234')
        self.assert_called('DELETE', '/snapshots/1234')

    def test_quota_delete(self):
        self.run_command('quota-delete 1234')
        self.assert_called('DELETE', '/os-quota-sets/1234')

    def test_snapshot_delete_multiple(self):
        self.run_command('snapshot-delete 1234 5678')
        self.assert_called('DELETE', '/snapshots/5678')


text:
using System.Net.Sockets;
using System.Globalization;

namespace System.Net
{
    /// <devdoc>
    ///    <para>
    ///       Provides an IP address.
    ///    </para>
    /// </devdoc>
    [Serializable]
    public class IPEndPoint : EndPoint
    {
        /// <devdoc>
        ///    <para>
        ///       Specifies the minimum acceptable value for the <see cref='System.Net.IPEndPoint.Port'/>
        ///       property.
        ///    </para>
        /// </devdoc>
        public const int MinPort = 0x00000000;

        /// <devdoc>
        ///    <para>
        ///       Specifies the maximum acceptable value for the <see cref='System.Net.IPEndPoint.Port'/>
        ///       property.
        ///    </para>
        /// </devdoc>
        public const int MaxPort = 0x0000FFFF;

        private IPAddress _address;
        private int _port;

        internal const int AnyPort = MinPort;

        internal static IPEndPoint Any = new IPEndPoint(IPAddress.Any, AnyPort);
        internal static IPEndPoint IPv6Any = new IPEndPoint(IPAddress.IPv6Any, AnyPort);

        public override AddressFamily AddressFamily
        {
            get
            {
                // IPv6 Changes: Always delegate this to the address we are wrapping.
                return _address.AddressFamily;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Creates a new instance of the IPEndPoint class with the specified address and port.
        ///    </para>
        /// </devdoc>
        public IPEndPoint(long address, int port)
        {
            if (!TcpValidationHelpers.ValidatePortNumber(port))
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }
            _port = port;
            _address = new IPAddress(address);
        }

        /// <devdoc>
        ///    <para>
        ///       Creates a new instance of the IPEndPoint class with the specified address and port.
        ///    </para>
        /// </devdoc>
        public IPEndPoint(IPAddress address, int port)
        {
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }
            if (!TcpValidationHelpers.ValidatePortNumber(port))
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }
            _port = port;
            _address = address;
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the IP address.
        ///    </para>
        /// </devdoc>
        public IPAddress Address
        {
            get
            {
                return _address;
            }
            set
            {
                _address = value;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the port.
        ///    </para>
        /// </devdoc>
        public int Port
        {
            get
            {
                return _port;
            }
            set
            {
                if (!TcpValidationHelpers.ValidatePortNumber(value))
                {
                    throw new ArgumentOutOfRangeException(nameof(value));
                }
                _port = value;
            }
        }

        public override string ToString()
        {
            string format = (_address.AddressFamily == AddressFamily.InterNetworkV6) ? "[{0}]:{1}" : "{0}:{1}";
            return String.Format(format, _address.ToString(), Port.ToString(NumberFormatInfo.InvariantInfo));
        }

        public override SocketAddress Serialize()
        {
            // Let SocketAddress do the bulk of the work
            return new SocketAddress(Address, Port);
        }

        public override EndPoint Create(SocketAddress socketAddress)
        {
            // Validate SocketAddress
            if (socketAddress.Family != this.AddressFamily)
            {
                throw new ArgumentException(SR.Format(SR.net_InvalidAddressFamily, socketAddress.Family.ToString(), this.GetType().FullName, this.AddressFamily.ToString()), nameof(socketAddress));
            }
            if (socketAddress.Size < 8)
            {
                throw new ArgumentException(SR.Format(SR.net_InvalidSocketAddressSize, socketAddress.GetType().FullName, this.GetType().FullName), nameof(socketAddress));
            }

            return socketAddress.GetIPEndPoint();
        }

        public override bool Equals(object comparand)
        {
            if (!(comparand is IPEndPoint))
            {
                return false;
            }
            return ((IPEndPoint)comparand)._address.Equals(_address) && ((IPEndPoint)comparand)._port == _port;
        }

        public override int GetHashCode()
        {
            return _address.GetHashCode() ^ _port;
        }

        // For security, we need to be able to take an IPEndPoint and make a copy that's immutable and not derived.
        internal IPEndPoint Snapshot()
        {
            return new IPEndPoint(Address.Snapshot(), Port);
        }
    }
}


text:
interface TwitterAPI_I {
    /*
        https://dev.twitter.com/rest/reference/get/statuses/user_timeline
        endpoint: https://api.twitter.com/1.1/statuses/user_timeline.json

        maxId: the caller needs to substract 1
        https://dev.twitter.com/docs/working-with-timelines
        ... or not:
        "Environments where a Tweet ID cannot be represented as an integer with 64 bits of
        precision (such as JavaScript) should skip this step."
    */
    getUserTimeline : (twittername: string, maxId?: TwitterTweetId) => Promise<TwitterAPITweet[]>

    /*
        https://dev.twitter.com/rest/reference/get/search/tweets
        https://dev.twitter.com/docs/using-search
        endpoint: https://api.twitter.com/1.1/search/tweets.json
    */
    search: (parameters : TwitterAPISearchParams) => Promise<TwitterAPITweet[]>

    /*
        https://dev.twitter.com/rest/reference/get/users/lookup
        endpoint: https://api.twitter.com/1.1/users/lookup.json
    */
    lookupUsersByIds: (user_ids: TwitterUserId[]) => Promise<TwitterAPIUser[]>
    lookupUsersByScreenNames: (screen_names: string[]) => Promise<TwitterAPIUser[]>

    /*
        https://dev.twitter.com/rest/reference/get/friends/ids
        endpoint : https://api.twitter.com/1.1/friends/ids.json
    */
    getFriends: (id: TwitterUserId) => Promise<{ids: TwitterUserId[]}>

    /*
        https://dev.twitter.com/rest/reference/get/help/languages
        endpoint : https://api.twitter.com/1.1/help/languages.jsonavril
    */
    getLanguages: () => Promise<{code: string, name: string}[]>
}

interface TwitterAPIUserTimelineOptions{
    count?: number // between 0 and 200
    include_rts?: number // 0 or 1
    'trim_user'?: string // 't' or nothing
    screen_name?: string
    max_id?: TwitterTweetId
}

interface TwitterAPIUserLookupOptions{
    user_id?: string // 783214,6253282
    screen_name?: string // twitterapi,twitter
    include_entities : boolean
}

interface TwitterAPISearchParams{
    q: {
        text: string // the string shouldn't be encoded
        from: string
        to: string
        '@': string
        since: Date
        until: Date
        filter: string
    }
    since_id: TwitterTweetId
    max_id: TwitterTweetId
    count: number
    result_type: string // 'mixed', 'recent', 'popular'
    lang: string
    geocode: string
}

interface TwitterAPIEntities{
    urls: TwitterAPIURLEntity[]
    user_mentions: TwitterAPIUserMentionEntity[]
    media: TwitterAPIMediaEntity[]
    hashtags: TwitterAPIHashtagEntity[]
}

interface TwitterAPIUserMentionEntity{
    id_str: TwitterUserId
    indices: number[]
    screen_name: string
}

interface TwitterAPIURLEntity{
    url: string
    expanded_url: string
    indices: number[]
}

interface TwitterAPIMediaEntity{
    url: string
}

interface TwitterAPIHashtagEntity{
    text: string
}

interface TwitterTweetId extends String{
    __TwitterTweetId : TwitterTweetId
}

interface TwitterAPITweet{
    // id: number // purposefully commented so TypeScript warns about its use, because it shouldn't be used in JS
    id_str : TwitterTweetId

    created_at : string // Date-parseable string

    entities: TwitterAPIEntities
    user: TwitterAPIReducedUser // the 'trim_user' parameter will always be used
    text: string
    lang: string

    retweeted_status?: TwitterAPITweet
    retweet_count: number
    favorite_count: number

    in_reply_to_user_id_str: TwitterUserId
}

interface TwitterUserId extends String{
    __TwitterUserId: TwitterUserId
}

/*
    Some API calls allow for a 'trim_user' parameter. When used, a reduced version of the user is used
*/
interface TwitterAPIReducedUser{
    // 'id' purposefully omitted
    id_str: TwitterUserId
}

interface TwitterAPIUser extends TwitterAPIReducedUser{
    screen_name: string
    name: string
    profile_image_url_https : string
}


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

class MatrixForUser
{
    static void Main()
    {
        MatrixClass matrix1 = new MatrixClass(2,2);
        matrix1[0, 0] = 1;
        matrix1[0, 1] = -2;
        matrix1[1, 0] = 3;
        matrix1[1, 1] = 3;
        MatrixClass matrix2 = new MatrixClass(2,2);
        matrix2[0, 0] = 4;
        matrix2[0, 1] = 4;
        matrix2[1, 0] = 5;
        matrix2[1, 1] = 5;

        MatrixClass resultSum = matrix1 + matrix2;
        Console.WriteLine("Adding the two matrix:");
        Console.WriteLine(resultSum.ToString());
        MatrixClass resultExtraction = matrix1 - matrix2;
        Console.WriteLine("Extract Matrix2 from Matrix1:");
        Console.WriteLine(resultExtraction.ToString());
        MatrixClass resultMultiplication = matrix1 * matrix2;
        Console.WriteLine("Result of multiplication of Matrix1 and Matrix2:");
        Console.WriteLine(resultMultiplication.ToString());
    }
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsDOMCommandEvent_h__
#define nsDOMCommandEvent_h__

#include "nsIDOMCommandEvent.h"
#include "nsDOMEvent.h"

class nsDOMCommandEvent : public nsDOMEvent,
                          public nsIDOMCommandEvent
{
public:
  nsDOMCommandEvent(nsPresContext* aPresContext,
                    nsCommandEvent* aEvent);
  virtual ~nsDOMCommandEvent();

  NS_DECL_ISUPPORTS_INHERITED

  NS_DECL_NSIDOMCOMMANDEVENT

  // Forward to base class
  NS_FORWARD_TO_NSDOMEVENT
};

#endif // nsDOMCommandEvent_h__


text:
from datetime import date, datetime, time

import pytest
import sqlalchemy as sa

from sqlalchemy_utils import ColorType, EncryptedType, PhoneNumberType
from sqlalchemy_utils.types.encrypted import AesEngine, FernetEngine

cryptography = None
try:
    import cryptography  # noqa
except ImportError:
    pass

@pytest.fixture
def User(Base, encryption_engine, test_key):
    class User(Base):
        __tablename__ = 'user'
        id = sa.Column(sa.Integer, primary_key=True)

        username = sa.Column(EncryptedType(
            sa.Unicode,
            test_key,
            encryption_engine)
        )

        access_token = sa.Column(EncryptedType(
            sa.String,
            test_key,
            encryption_engine)
        )

        is_active = sa.Column(EncryptedType(
            sa.Boolean,
            test_key,
            encryption_engine)
        )

        accounts_num = sa.Column(EncryptedType(
            sa.Integer,
            test_key,
            encryption_engine)
        )

        phone = sa.Column(EncryptedType(
            PhoneNumberType,
            test_key,
            encryption_engine)
        )

        color = sa.Column(EncryptedType(
            ColorType,
            test_key,
            encryption_engine)
        )

        date = sa.Column(EncryptedType(
            sa.Date,
            test_key,
            encryption_engine)
        )

        time = sa.Column(EncryptedType(
            sa.Time,
            test_key,
            encryption_engine)
        )

        datetime = sa.Column(EncryptedType(
            sa.DateTime,
            test_key,
            encryption_engine)
        )

        enum = sa.Column(EncryptedType(
            sa.Enum('One', name='user_enum_t'),
            test_key,
            encryption_engine)
        )

    return User

@pytest.fixture
def test_key():
    return 'secretkey1234'

@pytest.fixture
def user_name():
    return u'someone'

@pytest.fixture
def user_phone():
    return u'(555) 555-5555'

@pytest.fixture
def user_color():
    return u'#fff'

@pytest.fixture
def user_enum():
    return 'One'

@pytest.fixture
def user_date():
    return date(2010, 10, 2)

@pytest.fixture
def user_time():
    return time(10, 12)

@pytest.fixture
def user_datetime():
    return datetime(2010, 10, 2, 10, 12)

@pytest.fixture
def test_token():
    import string
    import random
    token = ''
    characters = string.ascii_letters + string.digits
    for i in range(60):
        token += ''.join(random.choice(characters))
    return token

@pytest.fixture
def active():
    return True

@pytest.fixture
def accounts_num():
    return 2

@pytest.fixture
def user(
    request,
    session,
    User,
    user_name,
    user_phone,
    user_color,
    user_date,
    user_time,
    user_enum,
    user_datetime,
    test_token,
    active,
    accounts_num
):
    # set the values to the user object
    user = User()
    user.username = user_name
    user.phone = user_phone
    user.color = user_color
    user.date = user_date
    user.time = user_time
    user.enum = user_enum
    user.datetime = user_datetime
    user.access_token = test_token
    user.is_active = active
    user.accounts_num = accounts_num
    session.add(user)
    session.commit()

    return session.query(User).get(user.id)

@pytest.mark.skipif('cryptography is None')
class EncryptedTypeTestCase(object):

    @pytest.fixture
    def Team(self, Base, encryption_engine):
        self._team_key = None

        class Team(Base):
            __tablename__ = 'team'
            id = sa.Column(sa.Integer, primary_key=True)
            key = sa.Column(sa.String(50))
            name = sa.Column(EncryptedType(
                sa.Unicode,
                lambda: self._team_key,
                encryption_engine)
            )
        return Team

    @pytest.fixture
    def init_models(self, User, Team):
        pass

    def test_unicode(self, user, user_name):
        assert user.username == user_name

    def test_string(self, user, test_token):
        assert user.access_token == test_token

    def test_boolean(self, user, active):
        assert user.is_active == active

    def test_integer(self, user, accounts_num):
        assert user.accounts_num == accounts_num

    def test_phone_number(self, user, user_phone):
        assert str(user.phone) == user_phone

    def test_color(self, user, user_color):
        assert user.color.hex == user_color

    def test_date(self, user, user_date):
        assert user.date == user_date

    def test_datetime(self, user, user_datetime):
        assert user.datetime == user_datetime

    def test_time(self, user, user_time):
        assert user.time == user_time

    def test_enum(self, user, user_enum):
        assert user.enum == user_enum

    def test_lookup_key(self, session, Team):
        # Add teams
        self._team_key = 'one'
        team = Team(key=self._team_key, name=u'One')
        session.add(team)
        session.commit()
        team_1_id = team.id

        self._team_key = 'two'
        team = Team(key=self._team_key)
        team.name = u'Two'
        session.add(team)
        session.commit()
        team_2_id = team.id

        # Lookup teams
        self._team_key = session.query(Team.key).filter_by(
            id=team_1_id
        ).one()[0]

        team = session.query(Team).get(team_1_id)

        assert team.name == u'One'

        with pytest.raises(Exception):
            session.query(Team).get(team_2_id)

        session.expunge_all()

        self._team_key = session.query(Team.key).filter_by(
            id=team_2_id
        ).one()[0]

        team = session.query(Team).get(team_2_id)

        assert team.name == u'Two'

        with pytest.raises(Exception):
            session.query(Team).get(team_1_id)

        session.expunge_all()

        # Remove teams
        session.query(Team).delete()
        session.commit()

class TestAesEncryptedTypeTestcase(EncryptedTypeTestCase):

    @pytest.fixture
    def encryption_engine(self):
        return AesEngine

    def test_lookup_by_encrypted_string(self, session, User, user, user_name):
        test = session.query(User).filter(
            User.username == user_name
        ).first()

        assert test.username == user.username

class TestFernetEncryptedTypeTestCase(EncryptedTypeTestCase):

    @pytest.fixture
    def encryption_engine(self):
        return FernetEngine


text:
package org.physical_web.cms;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.physical_web.cms.bluetooth.BluetoothManager;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

@RunWith(AndroidJUnit4.class)
public class BluetoothManagerTest {
    private final static String TAG = BluetoothManagerTest.class.getSimpleName();
    BluetoothManager testSubject;

    @Before
    public void setUp() {
        Context context = InstrumentationRegistry.getTargetContext();
        testSubject = new BluetoothManager(context);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNonHTTPS() {
        String nonHTTPSUri = "http://example.com";
        testSubject.shortenIfNeeded(nonHTTPSUri);
    }

    @Test
    public void noNeedToShortenTest() {
        String alreadyShortUri = "https://192.168.1.1";
        String processedUri = testSubject.shortenIfNeeded(alreadyShortUri);
        assertEquals(alreadyShortUri.substring("https://".length()), processedUri);
    }

    @Test
    public void shortenTest() {
        String longUri = "https://example.com/?solonglonglonguri";
        String longUriWithoutPrefix = longUri.substring("https://".length());
        String processedUri = testSubject.shortenIfNeeded(longUri);
        assertTrue(processedUri.length() < longUriWithoutPrefix.length());
        assertTrue(processedUri.length() < 16); // max length of URI per eddystone spec
        assertTrue(processedUri.contains("goo.gl"));
        Log.i(TAG, "shortned URI correctly: " + processedUri);
    }
}


text:
jsqf
=======
javascript implementation of QP framework

##Introduction
QP framework is an event-driven framework to implement active object computing model. Visit [QP Website]: (http://www.state-machine.com) for detail information

##Library
QEvent - define the event object

QTimeEvent - define the time event object

QState - define the state of a HSM (Hierarchical State Machine)

QHsm - define the HSM

QActive - define the active object which implements a HSM

QF - the framework

## examples
dpp.js - implementation of the diner problem of philosophy

TestMachine.js - implementation of the statecharts descrbled in page 88 of the book "Practical UML Statecharts in c/c++"

testdpp.js - app for test dpp

qhsmtst.js - app for test TestMachine


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.github.ecobin.gui_refresh_by_time" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".UpdateService"
            android:enabled="true"
            android:exported="true" >
        </service>
    </application>

</manifest>


text:
package com.unknown.seleniumplugin.domain;

/**
 * Created by mike-sid on 27.08.14.
 */
public interface XPathSelectorSymbolConstants {
    String START_STEP_SYMBOL = "/";
    String ATTRIBUTE_SELECTOR_PART_START_ELEMENT = "[";
    String ATTRIBUTE_SELECTOR_PART_END_ELEMENT = "]";
    String ATTRIBUTE_VALUE_START_END_SYMBOL = "'";
    String EQUAL_SYMBOL = "=";
    String ATTRIBUTE_NAME_START_SYMBOL = "@";
    String OPENING_BRACE_ELEMENT = "(";
    String CLOSING_BRACE_ELEMENT = ")";

}


text:
namespace ptest {
namespace hiera {

class TestPath;
class TestSuiteView;

class OneTestPredicate {
public:
  explicit OneTestPredicate(const std::string& predicate);
  ~OneTestPredicate();
  OneTestPredicate(OneTestPredicate&&);

  bool match(const TestPath& path) const;

private:
  OneTestPredicate(const OneTestPredicate&) =delete;
  OneTestPredicate& operator=(const OneTestPredicate&) =delete;
  OneTestPredicate& operator=(OneTestPredicate&&) =delete;

  std::string m_predicate;
};

} // namespace ptest::hiera
} // namespace ptest


text:
ENV=lbaasv2_mitaka

enabled_var="enable_$ENV"

if [[ ! ${!enabled_var} == 1 ]]
then
    echo "$ENV disabled"
    exit 0
else
    echo "installing $ENV"
fi

DIR=/$ENV

# initialize the environment
cd /
tempest init $ENV
virtualenv $ENV
cp -R /environments${DIR}/. $DIR/
cp $DIR/init-$ENV /init-$ENV
chmod +x /init-$ENV

# Get correct version of the software to test and
# copy to the working directory for the environemnt
mkdir $DIR/build
cd $DIR/build
git clone -b stable/mitaka https://github.com/openstack/neutron-lbaas.git
mv $DIR/build/neutron-lbaas/neutron_lbaas $DIR/
mv $DIR/build/neutron-lbaas/requirements.txt $DIR/neutron_lbaas/requirements.txt
mv $DIR/build/neutron-lbaas/test-requirements.txt $DIR/neutron_lbaas/test-requirements.txt

# get rid of the unused source and branches
rm -rf $DIR/build

# install in the virtualenv for the environment
cd $DIR
/bin/bash -c "cd $DIR \
              && source ./bin/activate \
              && pip install -r ./neutron_lbaas/requirements.txt \
              && pip install -r ./neutron_lbaas/test-requirements.txt \
              && pip install -r ./neutron_lbaas/tests/tempest/requirements.txt \
              && mkdir $DIR/tempest \
              && cp -Rf $DIR/lib/python2.7/site-packages/tempest/* $DIR/tempest/ \
              && pip install --upgrade tempest f5-openstack-agent junitxml"

# patch files
find $DIR/neutron_lbaas/tests/tempest/v2 -exec sed -i 's/127.0/128.0/g' {} \; 2>/dev/null

# clean up container files
find $DIR/tools -type f -exec chmod +x {} \;
chmod +x $DIR/run_tests.sh


text:
cask "rocket-chat" do
  version "3.0.4"
  sha256 "0b8da4a59c08a7d3c8e90b0b8d2d3c2770ebd1885ac2dee5f8d3a62cbe1cc6c5"

  # github.com/RocketChat/Rocket.Chat.Electron/ was verified as official when first introduced to the cask
  url "https://github.com/RocketChat/Rocket.Chat.Electron/releases/download/#{version}/rocketchat-#{version}.dmg"
  appcast "https://github.com/RocketChat/Rocket.Chat.Electron/releases.atom"
  name "Rocket.Chat"
  desc "Official desktop client for Rocket.Chat"
  homepage "https://rocket.chat/"

  auto_updates true

  app "Rocket.Chat.app"

  zap trash: [
    "~/Library/Application Support/Rocket.Chat",
    "~/Library/Caches/chat.rocket",
    "~/Library/Caches/chat.rocket.ShipIt",
    "~/Library/Caches/chat.rocket.electron.helper",
    "~/Library/Preferences/chat.rocket.plist",
    "~/Library/Preferences/chat.rocket.electron.helper.plist",
    "~/Library/Saved Application State/chat.rocket.savedState",
  ]
end


text: """Automatic and manual clustering facilities."""


text:
$(function() {
    var key = 'locahistory_demo';

    $('#append').on('click', function() {
        var entry = $('#entry').val();
        localhistory.append(key, entry);
    });

    $('#load').on('click', function() {
        localhistory.load(key, function(err, entries) {
            if (err) {
                alert(err);
                return;
            }

            var $entries = entries.reverse().map(function(entry) {
                return $('<li>').append(JSON.stringify(entry));
            });

            $('#history').html($entries);
        });
    });

    $('#clear').on('click', function() {
        localhistory.clear(key);
        $('#history').html('');
    });
});


text:
#pragma once
#include <aws/healthlake/HealthLake_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace HealthLake
{
namespace Model
{
  enum class PreloadDataType
  {
    NOT_SET,
    SYNTHEA
  };

namespace PreloadDataTypeMapper
{
AWS_HEALTHLAKE_API PreloadDataType GetPreloadDataTypeForName(const Aws::String& name);

AWS_HEALTHLAKE_API Aws::String GetNameForPreloadDataType(PreloadDataType value);
} // namespace PreloadDataTypeMapper
} // namespace Model
} // namespace HealthLake
} // namespace Aws


text:
package org.hitogo.alert.dialog;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.annotation.StyleRes;

import org.hitogo.alert.core.Alert;
import org.hitogo.alert.core.AlertBuilderImpl;
import org.hitogo.alert.core.AlertImpl;
import org.hitogo.alert.core.AlertParams;
import org.hitogo.alert.core.AlertType;
import org.hitogo.button.core.Button;
import org.hitogo.core.Hitogo;
import org.hitogo.core.HitogoContainer;
import org.hitogo.core.HitogoController;
import org.hitogo.core.HitogoParamsHolder;

/**
 * Builder which includes all basic method to assign specific dialog values to the alert.
 *
 * @see Alert
 * @since 1.0.0
 */
public class DialogAlertBuilderImpl extends AlertBuilderImpl<DialogAlertBuilder, DialogAlert> implements DialogAlertBuilder {

    private Integer dialogThemeResId;
    private boolean isDismissible;

    /**
     * Default constructor for the DialogAlertBuilderImpl.
     *
     * @param targetClass Class object for the requested alert.
     * @param paramClass  Class object for the params object which is used by the alert.
     * @param container   Container which is used as a reference for this alert (context, view,
     *                    controller).
     * @see HitogoContainer
     * @see HitogoController
     * @see AlertType
     * @since 1.0.0
     */
    public DialogAlertBuilderImpl(@NonNull Class<? extends AlertImpl> targetClass,
                                  @NonNull Class<? extends AlertParams> paramClass,
                                  @NonNull HitogoContainer container) {
        super(targetClass, paramClass, container, AlertType.DIALOG);
    }

    @Override
    @NonNull
    public DialogAlertBuilder asDismissible() {
        return asDismissible(true);
    }

    @Override
    @NonNull
    public DialogAlertBuilder asDismissible(boolean isDismissible) {
        this.isDismissible = isDismissible;
        return this;
    }

    @Override
    @NonNull
    public DialogAlertBuilder asDismissible(@Nullable Button closeButton) {
        this.isDismissible = true;

        if (closeButton != null) {
            return super.setCloseButton(closeButton);
        }
        return this;
    }

    @Override
    @NonNull
    public DialogAlertBuilder addButton(@NonNull String... buttonContent) {
        for (String buttonText : buttonContent) {
            Button button = Hitogo.with(getContainer())
                    .asTextButton()
                    .addText(buttonText)
                    .build();
            super.addButton(button);
        }
        return this;
    }

    @Override
    @NonNull
    public DialogAlertBuilder addButton(@StringRes int... buttonContent) {
        for (int textRes : buttonContent) {
            Button button = Hitogo.with(getContainer())
                    .asTextButton()
                    .addText(textRes)
                    .build();
            super.addButton(button);
        }
        return this;
    }

    @Override
    @NonNull
    public DialogAlertBuilder setStyle(@StyleRes int dialogThemeResId) {
        this.dialogThemeResId = dialogThemeResId;
        return this;
    }

    @Override
    protected void onProvideData(HitogoParamsHolder holder) {
        super.onProvideData(holder);

        holder.provideInteger(DialogAlertParamsKeys.DIALOG_THEME_RES_ID, dialogThemeResId);
        holder.provideBoolean(DialogAlertParamsKeys.IS_DISMISSIBLE_KEY, isDismissible);
    }
}


text:
package com.kspichale.rest.sample;

public class Product {

	private final long id;
	private final String name;
	private final String price;

	public Product(long id, String name, String price) {
		this.id = id;
		this.name = name;
		this.price = price;
	}

	public long getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getPrice() {
		return price;
	}
}


text:
package org.s1.table.errors;

/**
 * More than one object found
 */
public class MoreThanOneFoundException extends Exception {

    public MoreThanOneFoundException() {
        super();
    }

    public MoreThanOneFoundException(String message) {
        super(message);
    }

    public MoreThanOneFoundException(String message, Throwable cause) {
        super(message,cause);
    }

    public MoreThanOneFoundException(Throwable cause) {
        super(cause);
    }
}


text:
package org.apache.hc.client5.http.impl.cookie;

import java.time.Instant;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.BitSet;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hc.client5.http.cookie.CommonCookieAttributeHandler;
import org.apache.hc.client5.http.cookie.Cookie;
import org.apache.hc.client5.http.cookie.MalformedCookieException;
import org.apache.hc.client5.http.cookie.SetCookie;
import org.apache.hc.core5.annotation.Contract;
import org.apache.hc.core5.annotation.ThreadingBehavior;
import org.apache.hc.core5.util.Args;
import org.apache.hc.core5.util.TextUtils;
import org.apache.hc.core5.util.Tokenizer;

/**
 * Cookie {@code expires} attribute handler conformant to the more relaxed interpretation
 * of HTTP state management.
 *
 * @since 4.4
 */
@Contract(threading = ThreadingBehavior.STATELESS)
public class LaxExpiresHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler {

    /**
     * Singleton instance.
     *
     * @since 5.2
     */
    public static final LaxExpiresHandler INSTANCE = new LaxExpiresHandler();

    private static final BitSet DELIMS;
    static {
        final BitSet bitSet = new BitSet();
        bitSet.set(0x9);
        for (int b = 0x20; b <= 0x2f; b++) {
            bitSet.set(b);
        }
        for (int b = 0x3b; b <= 0x40; b++) {
            bitSet.set(b);
        }
        for (int b = 0x5b; b <= 0x60; b++) {
            bitSet.set(b);
        }
        for (int b = 0x7b; b <= 0x7e; b++) {
            bitSet.set(b);
        }
        DELIMS = bitSet;
    }
    private static final Map<String, Month> MONTHS;
    static {
        final ConcurrentHashMap<String, Month> map = new ConcurrentHashMap<>(12);
        map.put("jan", Month.JANUARY);
        map.put("feb", Month.FEBRUARY);
        map.put("mar", Month.MARCH);
        map.put("apr", Month.APRIL);
        map.put("may", Month.MAY);
        map.put("jun", Month.JUNE);
        map.put("jul", Month.JULY);
        map.put("aug", Month.AUGUST);
        map.put("sep", Month.SEPTEMBER);
        map.put("oct", Month.OCTOBER);
        map.put("nov", Month.NOVEMBER);
        map.put("dec", Month.DECEMBER);
        MONTHS = map;
    }

    private final static Pattern TIME_PATTERN = Pattern.compile(
            "^([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})([^0-9].*)?$");
    private final static Pattern DAY_OF_MONTH_PATTERN = Pattern.compile(
            "^([0-9]{1,2})([^0-9].*)?$");
    private final static Pattern MONTH_PATTERN = Pattern.compile(
            "^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)(.*)?$", Pattern.CASE_INSENSITIVE);
    private final static Pattern YEAR_PATTERN = Pattern.compile(
            "^([0-9]{2,4})([^0-9].*)?$");

    public LaxExpiresHandler() {
        super();
    }

    @Override
    public void parse(final SetCookie cookie, final String value) throws MalformedCookieException {
        Args.notNull(cookie, "Cookie");
        if (TextUtils.isBlank(value)) {
            return;
        }
        final Tokenizer.Cursor cursor = new Tokenizer.Cursor(0, value.length());
        final StringBuilder content = new StringBuilder();

        int second = 0, minute = 0, hour = 0, day = 0, year = 0;
        Month month = Month.JANUARY;
        boolean foundTime = false, foundDayOfMonth = false, foundMonth = false, foundYear = false;
        try {
            while (!cursor.atEnd()) {
                skipDelims(value, cursor);
                content.setLength(0);
                copyContent(value, cursor, content);

                if (content.length() == 0) {
                    break;
                }
                if (!foundTime) {
                    final Matcher matcher = TIME_PATTERN.matcher(content);
                    if (matcher.matches()) {
                        foundTime = true;
                        hour = Integer.parseInt(matcher.group(1));
                        minute = Integer.parseInt(matcher.group(2));
                        second =Integer.parseInt(matcher.group(3));
                        continue;
                    }
                }
                if (!foundDayOfMonth) {
                    final Matcher matcher = DAY_OF_MONTH_PATTERN.matcher(content);
                    if (matcher.matches()) {
                        foundDayOfMonth = true;
                        day = Integer.parseInt(matcher.group(1));
                        continue;
                    }
                }
                if (!foundMonth) {
                    final Matcher matcher = MONTH_PATTERN.matcher(content);
                    if (matcher.matches()) {
                        foundMonth = true;
                        month = MONTHS.get(matcher.group(1).toLowerCase(Locale.ROOT));
                        continue;
                    }
                }
                if (!foundYear) {
                    final Matcher matcher = YEAR_PATTERN.matcher(content);
                    if (matcher.matches()) {
                        foundYear = true;
                        year = Integer.parseInt(matcher.group(1));
                        continue;
                    }
                }
            }
        } catch (final NumberFormatException ignore) {
            throw new MalformedCookieException("Invalid 'expires' attribute: " + value);
        }
        if (!foundTime || !foundDayOfMonth || !foundMonth || !foundYear) {
            throw new MalformedCookieException("Invalid 'expires' attribute: " + value);
        }
        if (year >= 70 && year <= 99) {
            year = 1900 + year;
        }
        if (year >= 0 && year <= 69) {
            year = 2000 + year;
        }
        if (day < 1 || day > 31 || year < 1601 || hour > 23 || minute > 59 || second > 59) {
            throw new MalformedCookieException("Invalid 'expires' attribute: " + value);
        }

        final Instant expiryDate = ZonedDateTime.of(year, month.getValue(), day, hour, minute, second, 0,
                ZoneId.of("UTC")).toInstant();
        cookie.setExpiryDate(expiryDate);
    }

    private void skipDelims(final CharSequence buf, final Tokenizer.Cursor cursor) {
        int pos = cursor.getPos();
        final int indexFrom = cursor.getPos();
        final int indexTo = cursor.getUpperBound();
        for (int i = indexFrom; i < indexTo; i++) {
            final char current = buf.charAt(i);
            if (DELIMS.get(current)) {
                pos++;
            } else {
                break;
            }
        }
        cursor.updatePos(pos);
    }

    private void copyContent(final CharSequence buf, final Tokenizer.Cursor cursor, final StringBuilder dst) {
        int pos = cursor.getPos();
        final int indexFrom = cursor.getPos();
        final int indexTo = cursor.getUpperBound();
        for (int i = indexFrom; i < indexTo; i++) {
            final char current = buf.charAt(i);
            if (DELIMS.get(current)) {
                break;
            }
            pos++;
            dst.append(current);
        }
        cursor.updatePos(pos);
    }

    @Override
    public String getAttributeName() {
        return Cookie.EXPIRES_ATTR;
    }

}


text:
package org.zstack.network.service.virtualrouter.vyos;

import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.network.service.virtualrouter.VirtualRouterGlobalProperty;
import org.zstack.network.service.virtualrouter.VirtualRouterStruct;
import org.zstack.network.service.virtualrouter.VirtualRouterVmInventory;
import org.zstack.network.service.virtualrouter.eip.VirtualRouterEipBackend;

/**
 * Created by xing5 on 2016/10/31.
 */
public class VyosEipBackend extends VirtualRouterEipBackend {
    @Override
    protected void acquireVirtualRouterVm(VirtualRouterStruct struct, ReturnValueCompletion<VirtualRouterVmInventory> completion) {
        struct.setApplianceVmType(VyosConstants.VYOS_VM_TYPE);
        struct.setProviderType(VyosConstants.VYOS_ROUTER_PROVIDER_TYPE);
        struct.setVirtualRouterOfferingSelector(new VyosOfferingSelector());
        struct.setApplianceVmAgentPort(VirtualRouterGlobalProperty.AGENT_PORT);
        super.acquireVirtualRouterVm(struct, completion);
    }

    @Override
    public String getNetworkServiceProviderType() {
        return VyosConstants.VYOS_ROUTER_PROVIDER_TYPE;
    }
}


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

namespace Stacks.Actors.DI
{
    class DependencyInjectionHelper : IDependencyInjectionHelper
    {
        private readonly ActorSystem actorSystem;

        public DependencyInjectionHelper(ActorSystem actorSystem)
        {
            this.actorSystem = actorSystem;
        }

        private IDependencyResolver GetResolverOrFail()
        {
            var resolver = actorSystem.DependencyResolver;

            if (resolver == null)
                throw new Exception($"Cannot use dependency injection ({nameof(ActorSystem)}.{nameof(ActorSystem.DI)}) before setting " +
                    $"dependency resolver through {nameof(ActorSystem.SetDependencyResolver)} method");

            return resolver;
        }

        public T Resolve<T>()
        {
            return Resolve<T>(null, null);
        }

        public T Resolve<T>(IDictionary<string, object> args)
        {
            return Resolve<T>(null, args);
        }

        public T Resolve<T>(string resolveName, IDictionary<string, object> args = null)
        {
            var resolver = GetResolverOrFail();
            return resolver.Resolve<T>(resolveName, args);
        }

        public void Release<T>(T obj)
        {
            var resolver = GetResolverOrFail();
            resolver.Release(obj);
        }

        public void Register<I, TImpl>()
            where I : class
            where TImpl : Actor, I
        {
            var resolver = GetResolverOrFail();
            resolver.Register<I, TImpl>();
        }

        public void RegisterTransient<I, TImpl>()
            where I : class
            where TImpl : Actor, I
        {
            var resolver = GetResolverOrFail();
            resolver.RegisterTransient<I, TImpl>();
        }
    }
}


text:
from __future__ import division
import numpy as np
from .base import supervised_model, base_adaptor

class one_by_one_model(supervised_model):
    def __init__(self, models):
        self.models = models

    def apply(self, fs):
        result = []
        for ell,model in self.models.items():
            if model.apply(fs):
                result.append(ell)
        return result

class one_by_one(base_adaptor):
    '''
    Implements 1-vs-all multi-label classifier by transforming a base (binary)
    classifier.

    Example
    -------

    features = [....]
    labels = [
        (0,),
        (1,2),
        (0,2),
        (0,3),
        (1,2,3),
        (2,0),
        ...
        ]
    learner = one_by_one(milk.defaultlearner())
    model = learner.train(features, labels)
    '''
    def train(self, features, labels, **kwargs):
        universe = set()
        for ls in labels:
            universe.update(ls)
        models = {}
        for ell in universe:
            contained = np.array([int(ell in ls) for ls in labels])
            models[ell] = self.base.train(features, contained, normalisedlabels=True)
        return one_by_one_model(models)

    def __str__(self):
        return 'one_by_one({})'.format(self.base)


text:
names
=====

Small app for my girlfriend and I to write down and rate name ideas for our future child


text:
package org.apache.heron.integration_test.topology.serialization;

import java.net.MalformedURLException;

import org.apache.heron.api.Config;
import org.apache.heron.integration_test.common.AbstractTestTopology;
import org.apache.heron.integration_test.common.bolt.IncrementBolt;
import org.apache.heron.integration_test.core.TestTopologyBuilder;

/**
 * Topology to test Customized Java Serialization
 */
public final class SerializationTopology extends AbstractTestTopology {

  private SerializationTopology(String[] args) throws MalformedURLException {
    super(args);
  }

  @Override
  protected TestTopologyBuilder buildTopology(TestTopologyBuilder builder) {

    CustomObject[] inputObjects = new CustomObject[]{
        new CustomObject("A", 10),
        new CustomObject("B", 20),
        new CustomObject("C", 30)
    };

    builder.setSpout("custom-spout", new CustomSpout(inputObjects), 1);
    builder.setBolt("check-bolt", new CustomCheckBolt(inputObjects), 1)
        .shuffleGrouping("custom-spout");
    builder.setBolt("count-bolt", new IncrementBolt(), 1)
        .shuffleGrouping("check-bolt");
    return builder;
  }

  @Override
  protected Config buildConfig(Config config) {
    config.setSerializationClassName("org.apache.heron.api.serializer.JavaSerializer");
    return config;
  }

  public static void main(String[] args) throws Exception {
    SerializationTopology topology = new SerializationTopology(args);
    topology.submit();
  }
}


text:
pub enum MathLib {
    /// Use ispc's built-in math functions (the default).
    ISPCDefault,
    /// Use high-performance but lower-accuracy math functions.
    Fast,
    /// Use the Intel(r) SVML math libraries.
    SVML,
    /// Use the system's math library (**may be quite slow**).
    System,
}

impl ToString for MathLib {
    fn to_string(&self) -> String {
        match *self {
            MathLib::ISPCDefault => String::from("--math-lib=default"),
            MathLib::Fast => String::from("--math-lib=fast"),
            MathLib::SVML => String::from("--math-lib=svml"),
            MathLib::System => String::from("--math-lib=system"),
        }
    }
}

/// Select the target CPU architecture
pub enum Architecture {
    Arm,
    Aarch64,
    X86,
    X64
}

impl ToString for Architecture {
    fn to_string(&self) -> String {
        match *self {
            Architecture::Arm => String::from("--arch=arm"),
            Architecture::Aarch64 => String::from("--arch=aarch64"),
            Architecture::X86 => String::from("--arch=x86"),
            Architecture::X64 => String::from("--arch=x86_64"),
        }
    }
}

/// Select 32 or 64 bit addressing to be used by ISPC. Note: 32-bit
/// addressing calculations are done by default, even on 64 bit target
/// architectures.
pub enum Addressing {
    /// Select 32 bit addressing calculations.
    A32,
    /// Select 64 bit addressing calculations.
    A64,
}

impl ToString for Addressing {
    fn to_string(&self) -> String {
        match *self {
            Addressing::A32 => String::from("--addressing=32"),
            Addressing::A64 => String::from("--addressing=64"),
        }
    }
}

/// ISPC target CPU ISA options, if none is set ISPC will
/// target the machine being compile on.
#[derive(Eq, PartialEq)]
pub enum CPU {
    Generic,
    /// Synonym for Atom target
    Bonnell,
    Core2,
    Penryn,
    /// Synonym for corei7 target
    Nehalem,
    /// Synonym for btver2
    Ps4,
    /// Synonym for corei7-avx
    SandyBridge,
    /// Synonym for core-avx-i target
    IvyBridge,
    /// Synonym for core-avx2 target
    Haswell,
    Broadwell,
    Knl,
    Skx,
    Icl,
    /// Synonym for slm target
    Silvermont,
    CoretexA15,
    CoretexA9,
    CoretexA35,
    CoretexA53,
    CoretexA57,
}

impl ToString for CPU {
    fn to_string(&self) -> String {
        match *self {
            CPU::Generic => String::from("--cpu=generic"),
            CPU::Bonnell => String::from("--cpu=bonnell"),
            CPU::Core2 => String::from("--cpu=core2"),
            CPU::Penryn => String::from("--cpu=penryn"),
            CPU::Nehalem => String::from("--cpu=nehalem"),
            CPU::Ps4 => String::from("--cpu=ps4"),
            CPU::SandyBridge => String::from("--cpu=sandybridge"),
            CPU::IvyBridge => String::from("--cpu=ivybridge"),
            CPU::Haswell => String::from("--cpu=haswell"),
            CPU::Broadwell => String::from("--cpu=broadwell"),
            CPU::Knl => String::from("--cpu=knl"),
            CPU::Skx => String::from("--cpu=skx"),
            CPU::Icl => String::from("--cpu=icl"),
            CPU::Silvermont => String::from("--cpu=silvermont"),
            CPU::CoretexA15 => String::from("--cpu=cortex-a15"),
            CPU::CoretexA9 => String::from("--cpu=cortex-a9"),
            CPU::CoretexA35 => String::from("--cpu=cortex-a35"),
            CPU::CoretexA53 => String::from("--cpu=cortex-a53"),
            CPU::CoretexA57 => String::from("--cpu=cortex-a57"),
        }
    }
}

/// ISPC optimization options.
#[derive(Ord, PartialOrd, Eq, PartialEq)]
pub enum OptimizationOpt {
    /// Remove assertion statements from final code.
    DisableAssertions,
    /// Disable 'fused multiply-add' instructions (on targets that support them).
    DisableFMA,
    /// Disable loop unrolling.
    DisableLoopUnroll,
    /// Faster masked vector loads on SSE (may go past end of array).
    FastMaskedVload,
    /// Perform non-IEEE-compliant optimizations of numeric expressions.
    FastMath,
    /// Always issue aligned vector load and store instructions.
    ForceAlignedMemory,
    /// Disable using zmm registers in favor of ymm on avx512skx-i32x16 (ISPC 1.13+)
    DisableZmm,
}

impl ToString for OptimizationOpt {
    fn to_string(&self) -> String {
        match *self {
            OptimizationOpt::DisableAssertions => String::from("--opt=disable-assertions"),
            OptimizationOpt::DisableFMA => String::from("--opt=disable-fma"),
            OptimizationOpt::DisableLoopUnroll => String::from("--opt=disable-loop-unroll"),
            OptimizationOpt::FastMaskedVload => String::from("--opt=fast-masked-vload"),
            OptimizationOpt::FastMath => String::from("--opt=fast-math"),
            OptimizationOpt::ForceAlignedMemory => String::from("--opt=force-aligned-memory"),
            OptimizationOpt::DisableZmm => String::from("--opt=disable-zmm"),
        }
    }
}

/// Target instruction sets and vector widths available to specialize for. The
/// default if none is set will be the host CPU's ISA and vector width.
pub enum TargetISA {
    Host,
    SSE2i32x4,
    SSE2i32x8,
    SSE4i32x4,
    SSE4i32x8,
    SSE4i16x8,
    SSE4i8x16,
    AVX1i32x4,
    AVX1i32x8,
    AVX1i32x16,
    AVX1i64x4,
    AVX2i32x8,
    AVX2i32x16,
    AVX2i64x4,
    AVX512KNLi32x16,
    AVX512SKXi32x16,
    AVX512SKXi32x8,
    Neoni8x16,
    Neoni16x8,
    Neoni32x4,
    Neoni32x8,
}

impl TargetISA {
    pub fn lib_suffix(&self) -> String {
        match *self {
            TargetISA::Host => String::from("host"),
            TargetISA::SSE2i32x4 => String::from("sse2"),
            TargetISA::SSE2i32x8 => String::from("sse2"),
            TargetISA::SSE4i32x4 => String::from("sse4"),
            TargetISA::SSE4i32x8 => String::from("sse4"),
            TargetISA::SSE4i16x8 => String::from("sse4"),
            TargetISA::SSE4i8x16 => String::from("sse4"),
            TargetISA::AVX1i32x4 => String::from("avx"),
            TargetISA::AVX1i32x8 => String::from("avx"),
            TargetISA::AVX1i32x16 => String::from("avx"),
            TargetISA::AVX1i64x4 => String::from("avx"),
            TargetISA::AVX2i32x8 => String::from("avx2"),
            TargetISA::AVX2i32x16 => String::from("avx2"),
            TargetISA::AVX2i64x4 => String::from("avx2"),
            TargetISA::AVX512KNLi32x16 => String::from("avx512knl"),
            TargetISA::AVX512SKXi32x16 => String::from("avx512skx"),
            TargetISA::AVX512SKXi32x8 => String::from("avx512skx"),
            TargetISA::Neoni8x16 => String::from("neon"),
            TargetISA::Neoni16x8 => String::from("neon"),
            TargetISA::Neoni32x4 => String::from("neon"),
            TargetISA::Neoni32x8 => String::from("neon"),
        }
    }
}

impl ToString for TargetISA {
    fn to_string(&self) -> String {
        match *self {
            TargetISA::Host => String::from("host"),
            TargetISA::SSE2i32x4 => String::from("sse2-i32x4"),
            TargetISA::SSE2i32x8 => String::from("sse2-i32x8"),
            TargetISA::SSE4i32x4 => String::from("sse4-i32x4"),
            TargetISA::SSE4i32x8 => String::from("sse4-i32x8"),
            TargetISA::SSE4i16x8 => String::from("sse4-i16x8"),
            TargetISA::SSE4i8x16 => String::from("sse4-i8x16"),
            TargetISA::AVX1i32x4 => String::from("avx1-i32x4"),
            TargetISA::AVX1i32x8 => String::from("avx1-i32x8"),
            TargetISA::AVX1i32x16 => String::from("avx1-i32x16"),
            TargetISA::AVX1i64x4 => String::from("avx1-i64x4"),
            TargetISA::AVX2i32x8 => String::from("avx2-i32x8"),
            TargetISA::AVX2i32x16 => String::from("avx2-i32x16"),
            TargetISA::AVX2i64x4 => String::from("avx2-i64x4"),
            TargetISA::AVX512KNLi32x16 => String::from("avx512knl-i32x16"),
            TargetISA::AVX512SKXi32x16 => String::from("avx512skx-i32x16"),
            TargetISA::AVX512SKXi32x8 => String::from("avx512skx-i32x8"),
            TargetISA::Neoni8x16 => String::from("neon-i8x16"),
            TargetISA::Neoni16x8 => String::from("neon-i16x8"),
            TargetISA::Neoni32x4 => String::from("neon-i32x4"),
            TargetISA::Neoni32x8 => String::from("neon-i32x8"),
        }
    }
}

/// Target instruction sets and vector widths available to specialize for. The
/// default if none is set will be the host CPU's ISA and vector width.
pub enum TargetOS {
    Windows,
    Ps4,
    Linux,
    Macos,
    Android,
}

impl TargetOS {
    pub fn lib_suffix(&self) -> String {
        match *self {
            TargetOS::Windows => String::from("windows"),
            TargetOS::Ps4 => String::from("ps4"),
            TargetOS::Linux => String::from("linux"),
            TargetOS::Macos => String::from("macos"),
            TargetOS::Android => String::from("android"),
        }
    }
}

impl ToString for TargetOS {
    fn to_string(&self) -> String {
        match *self {
            TargetOS::Windows => String::from("--target-os=windows"),
            TargetOS::Ps4 => String::from("--target-os=ps4"),
            TargetOS::Linux => String::from("--target-os=linux"),
            TargetOS::Macos => String::from("--target-os=macos"),
            TargetOS::Android => String::from("--target-os=android"),
        }
    }
}


text:
// Iport third party libraries

/* eslint-disable no-unused-vars */

import react from 'react';
import reactdom from 'react-dom';


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Klare.</title>
		<link rel="shortcut icon" href="img/klare_favicon.png">

		<link href="https://fonts.googleapis.com/css?family=Amiri" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.css">

    <link rel="stylesheet" href="css/main.css">

Work in progress.

For now, you can check my work here:


text:
/* ----------------------------------------------------------------------
   OINK - scripting wrapper on MapReduce-MPI library
   http://www.sandia.gov/~sjplimp/mapreduce.html, Sandia National Laboratories
   Steve Plimpton, sjplimp@sandia.gov

   See the README file in the top-level MR-MPI directory.
------------------------------------------------------------------------- */

#ifdef COMMAND_CLASS

CommandStyle(rmat2,RMAT2)

#else

#ifndef OINK_RMAT2_H
#define OINK_RMAT2_H

#include "command.h"
#include "map_rmat_generate.h"

namespace OINK_NS {

class RMAT2 : public Command {
 public:
  RMAT2(class OINK *);
  void run();
  void params(int, char **);

 private:
  RMAT_struct rmat;
};

}

#endif
#endif


text:
test-addml-validator
====================

Archival Data Description Markup Language (ADDML) open source utility for validating text-files (xml, delimited, fixed length).