text:
package won.protocol.util;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.jena.datatypes.xsd.XSDDateTime;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.compose.Union;
import org.apache.jena.query.*;
import org.apache.jena.rdf.model.*;
import org.apache.jena.rdf.model.impl.ResourceImpl;
import org.apache.jena.rdf.model.impl.StatementImpl;
import org.apache.jena.sparql.path.Path;
import org.apache.jena.sparql.path.PathParser;
import org.apache.jena.vocabulary.DCTerms;
import org.apache.jena.vocabulary.RDF;
import won.protocol.exception.IllegalAtomContentException;
import won.protocol.exception.IncorrectPropertyCountException;
import won.protocol.model.AtomGraphType;
import won.protocol.model.AtomState;
import won.protocol.vocabulary.WON;
import won.protocol.vocabulary.WONMATCH;

import java.net.URI;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * This class wraps the atom models (atom and sysinfo graphs in an atom
 * dataset). It provides abstraction for the atom structure of is/seeks content
 * nodes that are part of the atom model. It can be used to load and query an
 * existing atom dataset (or models). Furthermore it can be used to create an
 * atom model by adding triples.
 * <p>
 * Created by hfriedrich on 16.03.2017.
 */
public class AtomModelWrapper {
    // holds all the atom data with its different (default and named) models
    protected Dataset atomDataset = null;
    private String sysInfoGraphName = null;
    private Set<String> contentGraphNames = null;

    /**
     * Create a new atom model (incluing sysinfo)
     *
     * @param atomUri atom uri to create the atom models for
     */
    public AtomModelWrapper(URI atomUri) {
        this(atomUri.toString());
    }

    /**
     * Create a new atom model (incluing sysinfo)
     *
     * @param atomUri atom uri to create the atom models for
     */
    public AtomModelWrapper(String atomUri) {
        atomDataset = DatasetFactory.createGeneral();
        Model atomModel = ModelFactory.createDefaultModel();
        DefaultPrefixUtils.setDefaultPrefixes(atomModel);
        atomModel.createResource(atomUri, WON.Atom);
        Model sysInfoModel = ModelFactory.createDefaultModel();
        DefaultPrefixUtils.setDefaultPrefixes(sysInfoModel);
        sysInfoModel.createResource(atomUri, WON.Atom);
        String contentGraphName = atomUri + "#atom";
        this.contentGraphNames = Set.of(contentGraphName);
        atomDataset.addNamedModel(contentGraphName, atomModel);
    }

    /**
     * Load an atom dataset and extract the atom and sysinfo models from it
     *
     * @param ds atom dataset to load
     */
    public AtomModelWrapper(Dataset ds) {
        this(ds, false);
    }

    /**
     * Load an atom dataset and extract the atom and sysinfo models from it
     *
     * @param ds atom dataset to load
     * @param addDefaultGraphs if this is set to true an atomModelGraph and a
     * sysInfoGraph will be added to the dataset
     */
    public AtomModelWrapper(Dataset ds, boolean addDefaultGraphs) {
        atomDataset = ds;
        Resource atomNode = getAtomContentNode();
        atomNode = (atomNode != null) ? atomNode : getAtomNode(AtomGraphType.SYSINFO);
        String atomUri = (atomNode != null) ? atomNode.getURI() : null;
        if (addDefaultGraphs && atomUri != null) {
            if (getAtomModel() == null) {
                Model atomModel = ModelFactory.createDefaultModel();
                atomModel.createResource(atomUri, WON.Atom);
                DefaultPrefixUtils.setDefaultPrefixes(atomModel);
                String contentGraphName = "dummy#atom";
                this.contentGraphNames = Set.of(contentGraphName);
                atomDataset.addNamedModel(contentGraphName, atomModel);
            }
            if (getSysInfoModel() == null) {
                Model sysInfoModel = ModelFactory.createDefaultModel();
                sysInfoModel.createResource(atomUri, WON.Atom);
                DefaultPrefixUtils.setDefaultPrefixes(sysInfoModel);
                this.sysInfoGraphName = "dummy#sysinfo";
                atomDataset.addNamedModel(this.sysInfoGraphName, sysInfoModel);
            }
        }
    }

    /**
     * Load the atom and sysinfo models, if one of these models is null then
     * initialize the other one as default model
     *
     * @param atomModel
     * @param sysInfoModel
     */
    public AtomModelWrapper(Model atomModel, Model sysInfoModel) {
        atomDataset = DatasetFactory.createGeneral();
        String atomUri = null;
        if (sysInfoModel != null) {
            this.sysInfoGraphName = "dummy#sysinfo";
            atomDataset.addNamedModel(this.sysInfoGraphName, sysInfoModel);
            atomUri = getAtomNode(AtomGraphType.SYSINFO).getURI();
        }
        if (atomModel != null) {
            String contentGraphName = "dummy#atom";
            atomDataset.addNamedModel(contentGraphName, atomModel);
            this.contentGraphNames = Set.of(contentGraphName);
            atomUri = getAtomContentNode().getURI();
        }
        if (atomUri != null) {
            if (sysInfoModel == null) {
                sysInfoModel = ModelFactory.createDefaultModel();
                DefaultPrefixUtils.setDefaultPrefixes(sysInfoModel);
                sysInfoModel.createResource(atomUri, WON.Atom);
                this.sysInfoGraphName = "dummy#sysinfo";
                atomDataset.addNamedModel(this.sysInfoGraphName, sysInfoModel);
            }
            if (atomModel == null) {
                atomModel = ModelFactory.createDefaultModel();
                DefaultPrefixUtils.setDefaultPrefixes(atomModel);
                atomModel.createResource(atomUri, WON.Atom);
                String contentGraphName = "dummy#atom";
                this.contentGraphNames = Set.of(contentGraphName);
                atomDataset.addNamedModel(contentGraphName, atomModel);
            }
        }
    }

    /**
     * Indicates if the wrapped data looks like atom data.
     *
     * @return
     */
    public static boolean isAAtom(Dataset ds) {
        if (ds == null || ds.isEmpty()) {
            return false;
        }
        AtomModelWrapper wrapper = new AtomModelWrapper(ds, false);
        return wrapper.getAtomContentNode() != null && wrapper.getAtomNode(AtomGraphType.SYSINFO) != null;
    }

    public Dataset getDataset() {
        return atomDataset;
    }

    public Model getAtomModel() {
        Iterator<String> modelNameIter = atomDataset.listNames();
        if (this.contentGraphNames != null) {
            return this.contentGraphNames.stream()
                            .map(n -> atomDataset.getNamedModel(n))
                            .map(m -> m.getGraph())
                            .reduce((l, r) -> {
                                if (l == null) {
                                    return r;
                                }
                                if (r == null) {
                                    return l;
                                }
                                return new Union(l, r);
                            }).map(g -> ModelFactory.createModelForGraph(g)).get();
        }
        Model defaultModel = atomDataset.getDefaultModel();
        if (defaultModel.listSubjectsWithProperty(RDF.type, WON.Atom).hasNext()
                        && !defaultModel.listSubjectsWithProperty(WON.atomState).hasNext()) {
            return defaultModel;
        }
        while (modelNameIter.hasNext()) {
            String tempModelName = modelNameIter.next();
            Model model = atomDataset.getNamedModel(tempModelName);
            if (tempModelName.equals("dummy#sysinfo")) {
                continue;
            }
            if (model.listSubjectsWithProperty(RDF.type, WON.Atom).hasNext()
                            && !model.listSubjectsWithProperty(WON.atomState).hasNext()) {
                this.contentGraphNames = Set.of(tempModelName);
                return model;
            }
        }
        return null;
    }

    public Model getSysInfoModel() {
        Iterator<String> modelNameIter = atomDataset.listNames();
        if (this.sysInfoGraphName != null && atomDataset.getNamedModel(this.sysInfoGraphName) != null) {
            return atomDataset.getNamedModel(this.sysInfoGraphName);
        }
        Model defaultModel = atomDataset.getDefaultModel();
        if (defaultModel.listSubjectsWithProperty(RDF.type, WON.Atom).hasNext()
                        && defaultModel.listSubjectsWithProperty(WON.atomState).hasNext()) {
            return defaultModel;
        }
        while (modelNameIter.hasNext()) {
            String tempModelName = modelNameIter.next();
            if (tempModelName.equals("dummy#atom")) {
                continue;
            }
            Model model = atomDataset.getNamedModel(tempModelName);
            if (model.listSubjectsWithProperty(RDF.type, WON.Atom).hasNext()
                            && model.listSubjectsWithProperty(WON.atomState).hasNext()) {
                this.sysInfoGraphName = tempModelName;
                return model;
            }
        }
        return null;
    }

    public boolean hasDerivedModel() {
        Optional<RDFNode> derivedGraphName = RdfUtils.findFirstPropertyOfO(getAtomNode(AtomGraphType.SYSINFO),
                        WON.derivedGraph);
        if (derivedGraphName.isPresent() && derivedGraphName.get().isURIResource()) {
            String name = derivedGraphName.get().asResource().getURI();
            return this.atomDataset.containsNamedModel(name);
        }
        return false;
    }

    public Optional<Model> getDerivedModel() {
        Optional<RDFNode> derivedGraphName = RdfUtils.findFirstPropertyOfO(getAtomNode(AtomGraphType.SYSINFO),
                        WON.derivedGraph);
        if (derivedGraphName.isPresent() && derivedGraphName.get().isURIResource()) {
            String name = derivedGraphName.get().asResource().getURI();
            if (this.atomDataset.containsNamedModel(name)) {
                return Optional.of(RdfUtils.cloneModel(this.atomDataset.getNamedModel(name)));
            }
        }
        return Optional.empty();
    }

    /**
     * get the atom or sysinfo model
     *
     * @param graphType type specifies the atom or sysinfo model to return
     * @return atom or sysinfo model
     */
    public Model copyAtomModel(AtomGraphType graphType) {
        if (graphType.equals(AtomGraphType.ATOM)) {
            return RdfUtils.cloneModel(getAtomModel());
        } else {
            return RdfUtils.cloneModel(getSysInfoModel());
        }
    }

    /**
     * get the complete dataset
     *
     * @return copy of atomDataset
     */
    public Dataset copyDataset() {
        return RdfUtils.cloneDataset(atomDataset);
    }

    public Dataset copyDatasetWithoutSysinfo() {
        Dataset ds = copyDataset();
        getSysInfoModel(); // side effect: find graph name of sysinfo graph
        if (this.sysInfoGraphName != null) {
            ds.removeNamedModel(this.sysInfoGraphName);
        }
        return ds;
    }

    /**
     * get the node of the atom of either the atom model or the sysinfo model
     *
     * @param graph type specifies the atom or sysinfo atom node to return
     * @return atom or sysinfo atom node
     */
    protected Resource getAtomNode(AtomGraphType graph) {
        if (graph.equals(AtomGraphType.ATOM)) {
            Model atomModel = getAtomModel();
            if (atomModel != null) {
                ResIterator iter = getAtomModel().listSubjectsWithProperty(RDF.type, WON.Atom);
                Resource ret = null;
                if (iter.hasNext()) {
                    ret = iter.next();
                }
                if (iter.hasNext()) {
                    throw new IllegalAtomContentException("More than one atom resource found");
                }
                return ret;
            }
        } else if (graph.equals(AtomGraphType.SYSINFO) && getSysInfoModel() != null) {
            ResIterator iter = getSysInfoModel().listSubjectsWithProperty(RDF.type, WON.Atom);
            Resource ret = null;
            if (iter.hasNext()) {
                return iter.next();
            }
            if (iter.hasNext()) {
                throw new IllegalAtomContentException(
                                "More than one atom resource found. Remove a triple '[atom] rdf:type won:Atom'!");
            }
            return ret;
        }
        return null;
    }

    /**
     * get the content node of the atom
     *
     * @return
     */
    public Resource getAtomContentNode() {
        return getAtomNode(AtomGraphType.ATOM);
    }

    public String getAtomUri() {
        Resource atom = getAtomContentNode();
        if (atom == null) {
            throw new IllegalAtomContentException("No atom resource found. Add a triple '[atom] rdf:type won:Atom'!");
        }
        return atom.getURI();
    }

    public void addFlag(Resource flag) {
        getAtomContentNode().addProperty(WONMATCH.flag, flag);
    }

    public boolean flag(Resource flag) {
        Resource atomRes = getAtomContentNode();
        return atomRes != null && atomRes.hasProperty(WONMATCH.flag, flag);
    }

    public Calendar getDoNotMatchBefore() {
        Statement prop = getAtomContentNode().getProperty(WONMATCH.doNotMatchBefore);
        if (prop == null) {
            return null;
        }
        RDFNode literal = prop.getObject();
        if (!literal.isLiteral()) {
            return null; // This silently fails with a null, but in our case I think this is preferred to
                         // throwing an exception
        }
        Object data = literal.asLiteral().getValue();
        if (data instanceof XSDDateTime) {
            return ((XSDDateTime) data).asCalendar();
        } else {
            return null;
        }
    }

    public Calendar getDoNotMatchAfter() {
        Statement prop = getAtomContentNode().getProperty(WONMATCH.doNotMatchAfter);
        if (prop == null) {
            return null;
        }
        RDFNode literal = prop.getObject();
        if (!literal.isLiteral()) {
            return null; // This silently fails with a null, but in our case I think this is preferred to
                         // throwing an exception
        }
        Object data = literal.asLiteral().getValue();
        if (data instanceof XSDDateTime) {
            return ((XSDDateTime) data).asCalendar();
        } else {
            return null;
        }
    }

    /**
     * Rename resources in all models, replacing the prefix string by the
     * replacement string.
     *
     * @param prefix
     * @param replacement
     */
    public void renameResourceWithPrefix(String prefix, String replacement) {
        RdfUtils.renameResourceWithPrefix(this.atomDataset, prefix, replacement);
        this.contentGraphNames = this.contentGraphNames.stream()
                        .map(s -> replacePrefix(s, prefix, replacement))
                        .collect(Collectors.toSet());
        this.sysInfoGraphName = replacePrefix(this.sysInfoGraphName, prefix, replacement);
    }

    private String replacePrefix(String toChange, String prefix, String replacement) {
        if (toChange == null) {
            return null;
        }
        if (toChange.startsWith(prefix)) {
            return replacement + toChange.substring(prefix.length());
        }
        return toChange;
    }

    public void setAtomURI(URI newAtomURI) {
        setAtomURI(newAtomURI.toString());
    }

    public void setAtomURI(String newAtomURI) {
        String atomURI = getAtomUri();
        if (atomURI == null) {
            throw new IllegalStateException("Cannot change atom URI: none found.");
        }
        renameResourceWithPrefix(atomURI, newAtomURI);
    }

    public void addMatchingContext(String context) {
        getAtomContentNode().addProperty(WONMATCH.matchingContext, context);
    }

    public boolean matchingContext(String context) {
        return getAtomContentNode().hasProperty(WONMATCH.matchingContext, context);
    }

    /**
     * @deprecated use {@link AtomModelWrapper#setQuery(String)} instead, addQuery
     * would not remove any existing ones and we currently support only one query
     * per atom
     * @param query
     */
    public void addQuery(String query) {
        getAtomContentNode().addProperty(WONMATCH.sparqlQuery, query);
    }

    public void removeQuery() {
        getAtomContentNode().removeAll(WONMATCH.sparqlQuery);
    }

    public Optional<String> getQuery() {
        Statement stmt = getAtomContentNode().getProperty(WONMATCH.sparqlQuery);
        if (stmt == null) {
            return Optional.empty();
        }
        return Optional.of(stmt.getString());
    }

    public void setQuery(String query) {
        removeQuery();
        getAtomContentNode().addProperty(WONMATCH.sparqlQuery, query);
    }

    public boolean sparqlQuery() {
        return getAtomContentNode().hasProperty(WONMATCH.sparqlQuery);
    }

    public Collection<String> getMatchingContexts() {
        Collection<String> matchingContexts = new LinkedList<>();
        NodeIterator iter = getAtomModel().listObjectsOfProperty(getAtomContentNode(), WONMATCH.matchingContext);
        while (iter.hasNext()) {
            matchingContexts.add(iter.next().asLiteral().getString());
        }
        return matchingContexts;
    }

    /**
     * Add a socket. The socketURI must be a fragment URI off the atom URI, i.e.
     * [atomuri]#socketid, or it is just a fragment identifier, which will be
     * interpreted relative to the atomURI, i.e. #socketid {@literal ->}
     * [atomuri]#socketid.
     *
     * @param socketUri uniquely identifies this socket of this atom
     * @param socketTypeUri the type of the socket, e.g. won:ChatSocket
     */
    public void addSocket(String socketUri, String socketTypeUri) {
        if (socketUri.startsWith("#")) {
            socketUri = getAtomUri() + socketUri;
        } else if (!socketUri.startsWith(getAtomUri())) {
            throw new IllegalArgumentException(
                            "The socketURI must start with '[atomURI]#' or '#' but was: " + socketUri);
        }
        Resource socket = getAtomModel().getResource(socketUri);
        Resource socketType = getAtomModel().createResource(socketTypeUri);
        getAtomContentNode().addProperty(WON.socket, socket);
        socket.addProperty(WON.socketDefinition, socketType);
    }

    /**
     * @deprecated Default Socket is not used anymore, will be removed soon
     */
    @Deprecated
    public Optional<String> getDefaultSocket() {
        Statement stmt = getAtomContentNode().getProperty(WON.defaultSocket);
        if (stmt == null) {
            return Optional.empty();
        }
        return Optional.of(stmt.getObject().toString());
    }

    /**
     * @deprecated Default Socket is not used anymore, will be removed soon
     */
    @Deprecated
    public void setDefaultSocket(String socketUri) {
        if (socketUri.startsWith("#")) {
            socketUri = getAtomUri() + socketUri;
        } else if (!socketUri.startsWith(getAtomUri())) {
            throw new IllegalArgumentException(
                            "The socketURI must start with '[atomURI]#' or '#' but was: " + socketUri);
        }
        Resource socket = getAtomModel().getResource(socketUri);
        getAtomContentNode().addProperty(WON.defaultSocket, socket);
    }

    public Collection<String> getSocketUris() {
        Collection<String> socketUris = new LinkedList<>();
        NodeIterator iter = getAtomModel().listObjectsOfProperty(getAtomContentNode(), WON.socket);
        while (iter.hasNext()) {
            socketUris.add(iter.next().asResource().getURI());
        }
        return socketUris;
    }

    public Map<URI, URI> getSocketTypeUriMap() {
        Map<URI, URI> socketTypeUriMap = new HashMap<>();
        Collection<String> socketUris = getSocketUris();
        socketUris.forEach(socketUri -> {
            Optional<URI> socketTypeUri = getSocketTypeUri(socketUri);
            socketTypeUri.ifPresent(uri -> socketTypeUriMap.put(URI.create(socketUri), uri));
        });
        return socketTypeUriMap;
    }

    public Optional<String> getSocketType(String socketUri) {
        Resource socket = getAtomModel().createResource(socketUri);
        if (!getAtomContentNode().hasProperty(WON.socket, socket)) {
            return Optional.empty();
        }
        Statement stmt = socket.getProperty(WON.socketDefinition);
        if (stmt == null) {
            return Optional.empty();
        }
        return Optional.of(stmt.getObject().toString());
    }

    public Optional<URI> getSocketTypeUri(String socketUri) {
        Resource socket = getAtomModel().createResource(socketUri);
        if (!getAtomContentNode().hasProperty(WON.socket, socket)) {
            return Optional.empty();
        }
        Statement stmt = socket.getProperty(WON.socketDefinition);
        if (stmt == null) {
            return Optional.empty();
        }
        return Optional.of(URI.create(stmt.getObject().toString()));
    }

    public Collection<Resource> getGoals() {
        Collection<Resource> goalUris = new LinkedList<>();
        NodeIterator iter = getAtomModel().listObjectsOfProperty(getAtomContentNode(), WON.goal);
        while (iter.hasNext()) {
            goalUris.add(iter.next().asResource());
        }
        return goalUris;
    }

    public Resource getGoal(String uri) {
        return getAtomModel().getResource(uri);
    }

    public Model getShapesGraph(Resource goalNode) {
        if (goalNode != null) {
            NodeIterator nodeIter = getAtomModel().listObjectsOfProperty(goalNode, WON.shapesGraph);
            if (nodeIter.hasNext()) {
                String shapesGraphUri = nodeIter.next().asResource().getURI();
                return atomDataset.getNamedModel(shapesGraphUri);
            }
        }
        return null;
    }

    public String getShapesGraphName(Resource goalNode) {
        if (goalNode != null) {
            NodeIterator nodeIter = getAtomModel().listObjectsOfProperty(goalNode, WON.shapesGraph);
            if (nodeIter.hasNext()) {
                return nodeIter.next().asResource().getURI();
            }
        }
        return null;
    }

    public Model getDataGraph(Resource goalNode) {
        if (goalNode != null) {
            NodeIterator nodeIter = getAtomModel().listObjectsOfProperty(goalNode, WON.dataGraph);
            if (nodeIter.hasNext()) {
                String dataGraphUri = nodeIter.next().asResource().getURI();
                return atomDataset.getNamedModel(dataGraphUri);
            }
        }
        return null;
    }

    public String getDataGraphName(Resource goalNode) {
        if (goalNode != null) {
            NodeIterator nodeIter = getAtomModel().listObjectsOfProperty(goalNode, WON.dataGraph);
            if (nodeIter.hasNext()) {
                return nodeIter.next().asResource().getURI();
            }
        }
        return null;
    }

    public AtomState getAtomState() {
        Model sysInfoModel = getSysInfoModel();
        sysInfoModel.enterCriticalSection(true);
        RDFNode state = RdfUtils.findOnePropertyFromResource(sysInfoModel, getAtomNode(AtomGraphType.SYSINFO),
                        WON.atomState);
        sysInfoModel.leaveCriticalSection();
        if (WON.ATOM_STATE_ACTIVE.equals(state)) {
            return AtomState.ACTIVE;
        } else if (WON.ATOM_STATE_INACTIVE.equals(state)) {
            return AtomState.INACTIVE;
        } else if (WON.ATOM_STATE_DELETED.equals(state)) {
            return AtomState.DELETED;
        }
        throw new IllegalStateException("Unrecognized atom state: " + state);
    }

    public void setAtomState(AtomState state) {
        Resource stateRes = AtomState.ACTIVE.equals(state) ? WON.ATOM_STATE_ACTIVE : WON.ATOM_STATE_INACTIVE;
        Resource atom = getAtomNode(AtomGraphType.SYSINFO);
        atom.removeAll(WON.atomState);
        atom.addProperty(WON.atomState, stateRes);
    }

    public ZonedDateTime getCreationDate() {
        String dateString = RdfUtils.findOnePropertyFromResource(getSysInfoModel(), getAtomNode(AtomGraphType.SYSINFO),
                        DCTerms.created).asLiteral().getString();
        return ZonedDateTime.parse(dateString, DateTimeFormatter.ISO_DATE_TIME);
    }

    public ZonedDateTime getModifiedDate() {
        String dateString = RdfUtils.findOnePropertyFromResource(getSysInfoModel(), getAtomNode(AtomGraphType.SYSINFO),
                        DCTerms.modified).asLiteral().getString();
        return ZonedDateTime.parse(dateString, DateTimeFormatter.ISO_DATE_TIME);
    }

    public String getConnectionContainerUri() {
        return RdfUtils.findOnePropertyFromResource(getSysInfoModel(), getAtomNode(AtomGraphType.SYSINFO),
                        WON.connections).asResource().getURI();
    }

    public void setConnectionContainerUri(String containerUri) {
        Resource container = getSysInfoModel().createResource(containerUri);
        Resource atom = getAtomNode(AtomGraphType.SYSINFO);
        atom.removeAll(WON.connections);
        atom.addProperty(WON.connections, container);
    }

    public String getWonNodeUri() {
        return RdfUtils.findOnePropertyFromResource(getSysInfoModel(), getAtomNode(AtomGraphType.SYSINFO), WON.wonNode)
                        .asResource().getURI();
    }

    public void setWonNodeUri(String nodeUri) {
        Resource node = getSysInfoModel().createResource(nodeUri);
        Resource atom = getAtomNode(AtomGraphType.SYSINFO);
        atom.removeAll(WON.wonNode);
        atom.addProperty(WON.wonNode, node);
    }

    /**
     * create a goal content node below the atom node of the atom model.
     *
     * @param uri uri of the content node, if null then create blank node
     * @return content node created
     */
    public Resource createGoalNode(String uri) {
        Resource contentNode = (uri != null) ? getAtomModel().createResource(uri) : getAtomModel().createResource();
        addGoalPropertyToAtomNode(contentNode);
        return contentNode;
    }

    /**
     * create a goal content node below the atom node of the atom model.
     *
     * @param uri uri of the content node, if null then create blank node
     * @return content node created
     */
    public Resource createSeeksNode(String uri) {
        Resource contentNode = (uri != null) ? getAtomModel().createResource(uri) : getAtomModel().createResource();
        addSeeksPropertyToAtomNode(contentNode);
        return contentNode;
    }

    private void addGoalPropertyToAtomNode(RDFNode contentNode) {
        Resource atomNode = getAtomContentNode();
        atomNode.addProperty(WON.goal, contentNode);
    }

    private void addSeeksPropertyToAtomNode(RDFNode contentNode) {
        Resource atomNode = getAtomContentNode();
        atomNode.addProperty(WONMATCH.seeks, contentNode);
    }

    public Collection<Resource> getGoalNodes() {
        Collection<Resource> contentNodes = new LinkedList<>();
        String queryClause = "{ ?atomNode a won:Atom. ?atomNode won:goal ?contentNode. }";
        String queryString = "prefix won: <https://w3id.org/won/core#> \n"
                        + "prefix match: <https://w3id.org/won/matching#> \n"
                        + "prefix con: <https://w3id.org/won/content#> \n"
                        + "SELECT DISTINCT ?contentNode WHERE { \n"
                        + queryClause + "\n }";
        Query query = QueryFactory.create(queryString);
        try (QueryExecution qexec = QueryExecutionFactory.create(query, getAtomModel())) {
            ResultSet rs = qexec.execSelect();
            while (rs.hasNext()) {
                QuerySolution qs = rs.next();
                if (qs.contains("contentNode")) {
                    contentNodes.add(qs.get("contentNode").asResource());
                }
            }
            return contentNodes;
        }
    }

    /**
     * get all content nodes of a specified type
     *
     * @return content nodes
     */
    public Collection<Resource> getSeeksNodes() {
        Collection<Resource> contentNodes = new LinkedList<>();
        String queryClause = "{ ?atomNode a won:Atom. ?atomNode match:seeks ?contentNode. FILTER NOT EXISTS { ?atomNode match:seeks/match:seeks ?contentNode. } }";
        String queryString = "prefix won: <https://w3id.org/won/core#> \n"
                        + "prefix match: <https://w3id.org/won/matching#> \n"
                        + "prefix con: <https://w3id.org/won/content#> \n"
                        + "SELECT DISTINCT ?contentNode WHERE { \n"
                        + queryClause + "\n }";
        Query query = QueryFactory.create(queryString);
        try (QueryExecution qexec = QueryExecutionFactory.create(query, getAtomModel())) {
            ResultSet rs = qexec.execSelect();
            while (rs.hasNext()) {
                QuerySolution qs = rs.next();
                if (qs.contains("contentNode")) {
                    contentNodes.add(qs.get("contentNode").asResource());
                }
            }
            return contentNodes;
        }
    }

    /**
     * get all seeks, seeks_seeks node including the resource for the atomcontent
     * itself (former is-node)
     *
     * @return content nodes
     */
    public Collection<Resource> getAllContentNodes() {
        Collection<Resource> contentNodes = new LinkedList<>();
        String seeksClause = "{ ?atomNode a won:Atom. ?atomNode match:seeks ?contentNode. FILTER NOT EXISTS { ?atomNode match:seeks/match:seeks ?contentNode. } }";
        String seeksSeeksClause = "{ ?atomNode a won:Atom. ?atomNode match:seeks/match:seeks ?contentNode. }";
        String queryClause = seeksClause + "UNION \n" + seeksSeeksClause;
        String queryString = "prefix won: <https://w3id.org/won/core#> \n"
                        + "prefix match: <https://w3id.org/won/matching#> \n"
                        + "prefix con: <https://w3id.org/won/content#> \n"
                        + "SELECT DISTINCT ?contentNode WHERE { \n"
                        + queryClause + "\n }";
        Query query = QueryFactory.create(queryString);
        try (QueryExecution qexec = QueryExecutionFactory.create(query, getAtomModel())) {
            ResultSet rs = qexec.execSelect();
            while (rs.hasNext()) {
                QuerySolution qs = rs.next();
                if (qs.contains("contentNode")) {
                    contentNodes.add(qs.get("contentNode").asResource());
                }
            }
            contentNodes.add(getAtomContentNode());
            return contentNodes;
        }
    }

    /**
     * get all content nodes of a specified type
     *
     * @return content nodes
     */
    public Collection<Resource> getSeeksSeeksNodes() {
        Collection<Resource> contentNodes = new LinkedList<>();
        String seeksSeeksClause = "{ ?atomNode a won:Atom. ?atomNode match:seeks/match:seeks ?contentNode. }";
        String queryString = "prefix won: <https://w3id.org/won/core#> \n"
                        + "prefix match: <https://w3id.org/won/matching#> \n"
                        + "prefix con: <https://w3id.org/won/content#> \n"
                        + "SELECT DISTINCT ?contentNode WHERE { \n"
                        + seeksSeeksClause + "\n }";
        Query query = QueryFactory.create(queryString);
        try (QueryExecution qexec = QueryExecutionFactory.create(query, getAtomModel())) {
            ResultSet rs = qexec.execSelect();
            while (rs.hasNext()) {
                QuerySolution qs = rs.next();
                if (qs.contains("contentNode")) {
                    contentNodes.add(qs.get("contentNode").asResource());
                }
            }
            return contentNodes;
        }
    }

    public void setContentPropertyStringValue(Property p, String value) {
        Resource node = getAtomContentNode();
        node.removeAll(p);
        node.addLiteral(p, value);
    }

    public void setSeeksPropertyStringValue(Property p, String value) {
        Collection<Resource> nodes = getSeeksNodes();
        for (Resource node : nodes) {
            node.removeAll(p);
            node.addLiteral(p, value);
        }
    }

    /**
     * Adds a property directly into the contentNode of the atom
     *
     * @param p
     * @param value
     */
    public void addPropertyStringValue(Property p, String value) {
        Resource node = getAtomContentNode();
        node.addLiteral(p, value);
    }

    public void addSeeksPropertyStringValue(Property p, String value) {
        Collection<Resource> nodes = getSeeksNodes();
        for (Resource node : nodes) {
            node.addLiteral(p, value);
        }
    }

    public String getContentPropertyStringValue(Resource contentNode, Property p) {
        RDFNode node = RdfUtils.findOnePropertyFromResource(getAtomModel(), contentNode, p);
        if (node != null && node.isLiteral()) {
            return node.asLiteral().getString();
        }
        return null;
    }

    public String getContentPropertyStringValue(Property p) {
        return getContentPropertyObject(p).asLiteral().getString();
    }

    public String getContentPropertyStringValue(String propertyPath) {
        Node node = getContentPropertyObject(propertyPath);
        return node != null ? node.getLiteralLexicalForm() : null;
    }

    public Collection<String> getContentPropertyStringValues(Resource contentNode, Property p, String language) {
        Collection<String> values = new LinkedList<>();
        NodeIterator nodeIterator = getAtomModel().listObjectsOfProperty(contentNode, p);
        while (nodeIterator.hasNext()) {
            Literal literalValue = nodeIterator.next().asLiteral();
            if (language == null || language.equals(literalValue.getLanguage())) {
                values.add(literalValue.getString());
            }
        }
        return values;
    }

    public Collection<RDFNode> getContentPropertyObjects(Resource contentNode, Property p) {
        Collection<RDFNode> values = new LinkedList<>();
        NodeIterator nodeIterator = getAtomModel().listObjectsOfProperty(contentNode, p);
        while (nodeIterator.hasNext()) {
            values.add(nodeIterator.next());
        }
        return values;
    }

    public Collection<String> getAllContentPropertyStringValues(Property p, String language) {
        Collection<String> values = new LinkedList<>();
        Collection<Resource> nodes = getSeeksNodes();
        for (Resource node : nodes) {
            Collection valuesOfContentNode = getContentPropertyStringValues(node, p, language);
            values.addAll(valuesOfContentNode);
        }
        Resource node = getAtomContentNode();
        Collection valuesOfContentNode = getContentPropertyStringValues(node, p, language);
        values.addAll(valuesOfContentNode);
        return values;
    }

    public Collection<String> getContentPropertyStringValues(Property p, String language) {
        Resource node = getAtomContentNode();
        Collection valuesOfContentNode = getContentPropertyStringValues(node, p, language);
        return new LinkedList<>(valuesOfContentNode);
    }

    public Collection<String> getSeeksPropertyStringValues(Property p) {
        return getSeeksPropertyStringValues(p, null);
    }

    public Collection<String> getSeeksPropertyStringValues(Property p, String language) {
        Collection<String> values = new LinkedList<>();
        Collection<Resource> nodes = getSeeksNodes();
        for (Resource node : nodes) {
            Collection valuesOfContentNode = getContentPropertyStringValues(node, p, language);
            values.addAll(valuesOfContentNode);
        }
        return values;
    }

    public Collection<RDFNode> getSeeksPropertyObjects(Property p) {
        Collection<RDFNode> values = new LinkedList<>();
        Collection<Resource> nodes = getSeeksNodes();
        for (Resource node : nodes) {
            Collection valuesOfContentNode = getContentPropertyObjects(node, p);
            values.addAll(valuesOfContentNode);
        }
        return values;
    }

    /**
     * Returns one of the possibly many specified values. The specified preferred
     * languages will be tried first in the specified order.
     *
     * @param contentNode
     * @return the string value or null if nothing is found
     */
    public String getSomeContentPropertyStringValue(Resource contentNode, Property p) {
        return getSomeContentPropertyStringValue(contentNode, p, (String) null);
    }

    /**
     * Returns one of the possibly many specified values. The specified preferred
     * languages will be tried first in the specified order.
     *
     * @param contentNode
     * @param preferredLanguages String array of a non-empty language tag as defined
     * by https://tools.ietf.org/html/bcp47. The language tag must be well-formed
     * according to section 2.2.9 of https://tools.ietf.org/html/bcp47.
     * @return the string value or null if nothing is found
     */
    public String getSomeContentPropertyStringValue(Resource contentNode, Property p, String... preferredLanguages) {
        Collection<String> values;
        if (preferredLanguages != null) {
            for (String preferredLanguage : preferredLanguages) {
                values = getContentPropertyStringValues(contentNode, p, preferredLanguage);
                if (values != null && values.size() > 0) {
                    return values.iterator().next();
                }
            }
        }
        values = getContentPropertyStringValues(contentNode, p, null);
        if (values != null && values.size() > 0) {
            return values.iterator().next();
        }
        return null;
    }

    /**
     * Returns one of the possibly many specified values. The specified preferred
     * languages will be tried first in the specified order.
     *
     * @param preferredLanguages String array of a non-empty language tag as defined
     * by https://tools.ietf.org/html/bcp47. The language tag must be well-formed
     * according to section 2.2.9 of https://tools.ietf.org/html/bcp47.
     * @return the string value or null if nothing is found
     */
    public String getSomeContentPropertyStringValue(Property p, String... preferredLanguages) {
        Resource contentNode = getAtomContentNode();
        if (preferredLanguages != null) {
            for (String preferredLanguage : preferredLanguages) {
                String valueOfContentNode = getSomeContentPropertyStringValue(contentNode, p, preferredLanguage);
                if (valueOfContentNode != null) {
                    return valueOfContentNode;
                }
            }
        }
        String valueOfAtomContentNode = getSomeContentPropertyStringValue(contentNode, p);
        if (valueOfAtomContentNode != null) {
            return valueOfAtomContentNode;
        }
        Collection<Resource> nodes = getSeeksNodes();
        if (preferredLanguages != null) {
            for (String preferredLanguage : preferredLanguages) {
                for (Resource node : nodes) {
                    String valueOfContentNode = getSomeContentPropertyStringValue(node, p, preferredLanguage);
                    if (valueOfContentNode != null) {
                        return valueOfContentNode;
                    }
                }
            }
        }
        for (Resource node : nodes) {
            String valueOfContentNode = getSomeContentPropertyStringValue(node, p);
            if (valueOfContentNode != null) {
                return valueOfContentNode;
            }
        }
        return null;
    }

    /**
     * Returns one of the possibly many specified values. The specified preferred
     * languages will be tried first in the specified order.
     *
     * @param preferredLanguages String array of a non-empty language tag as defined
     * by https://tools.ietf.org/html/bcp47. The language tag must be well-formed
     * according to section 2.2.9 of https://tools.ietf.org/html/bcp47.
     * @return the string value or null if nothing is found
     */
    public String getAtomContentPropertyStringValue(Property p, String... preferredLanguages) {
        Resource node = getAtomContentNode();
        if (preferredLanguages != null) {
            for (String preferredLanguage : preferredLanguages) {
                String valueOfContentNode = getSomeContentPropertyStringValue(node, p, preferredLanguage);
                if (valueOfContentNode != null) {
                    return valueOfContentNode;
                }
            }
        }
        return getSomeContentPropertyStringValue(node, p);
    }

    private RDFNode getContentPropertyObject(Property p) {
        Resource node = getAtomContentNode();
        RDFNode object = null;
        NodeIterator nodeIterator = getAtomModel().listObjectsOfProperty(node, p);
        if (nodeIterator.hasNext()) {
            if (object != null) {
                throw new IncorrectPropertyCountException("expected exactly one occurrence of property " + p.getURI(),
                                1, 2);
            }
            object = nodeIterator.next();
        }
        if (object == null) {
            throw new IncorrectPropertyCountException("expected exactly one occurrence of property " + p.getURI(), 1,
                            0);
        }
        return object;
    }

    public Collection<RDFNode> getContentPropertyObjects(Property p) {
        Resource node = getAtomContentNode();
        Collection valuesOfContentNode = getContentPropertyObjects(node, p);
        return new LinkedList<>(valuesOfContentNode);
    }

    private Node getContentPropertyObject(String propertyPath) {
        Path path = PathParser.parse(propertyPath, DefaultPrefixUtils.getDefaultPrefixes());
        Resource resource = getAtomContentNode();
        Node node = resource.asNode();
        return RdfUtils.getNodeForPropertyPath(getAtomModel(), node, path);
    }

    private boolean isSplittableNode(RDFNode node) {
        return node.isResource() && (node.isAnon() || (node.asResource().getURI().startsWith(getAtomUri())
                        && (!node.asResource().getURI().equals(getAtomUri()))));
    }

    private Resource copyNode(Resource node) {
        if (node.isAnon()) {
            return node.getModel().createResource();
        }
        int i = 0;
        String uri = node.getURI() + RandomStringUtils.randomAlphanumeric(4);
        String newUri = uri + "_" + i;
        while (node.getModel().containsResource(new ResourceImpl(newUri))) {
            i++;
            newUri = uri + "_" + i;
        }
        return node.getModel().getResource(newUri);
    }

    /**
     * Returns a copy of the model in which no node reachable from the atom node has
     * multiple incoming edges (unless the graph contains a circle, see below). This
     * is achieved by making copies of all nodes that have multiple incoming edges,
     * such that each copy and the original get one of the incoming edges. The
     * outgoing edges of the original are replicated in the copies. Nodes that were
     * newly introduced by this algorithm are never split. In that special case that
     * the graph contains a circle, the resulting graph still contains a circle, and
     * possibly one or more nodes with more than one incoming edge.
     *
     * @return
     */
    public Model normalizeAtomModel() {
        Model copy = RdfUtils.cloneModel(getAtomModel());
        Set<RDFNode> blacklist = new HashSet<>();
        RDFNode atomNode = copy.getResource(getAtomUri());
        // System.out.println("model before modification:");
        // RDFDataMgr.write(System.out, copy, Lang.TRIG);
        recursiveCopyWhereMultipleInEdges(atomNode);
        // System.out.println("model after modifcation:");
        // RDFDataMgr.write(System.out, copy, Lang.TRIG);
        return copy;
    }

    private void recursiveCopyWhereMultipleInEdges(RDFNode node) {
        ModelModification modelModification = new ModelModification();
        recursiveCopyWhereMultipleInEdges(node, modelModification, new HashSet<>());
        modelModification.modify(node.getModel());
    }

    /**
     * If the specified node that has multiple incoming edges that have already been
     * visited (in depth-first order, i.e. on the way from the root to this node, if
     * this node is not the root), the node is 'split', i.e. one copy is made per
     * such incoming edge. No copies are made for incoming edges from nodes that are
     * discovered further down the tree. When a copy of the node is made, the
     * subgraph reachable from the node is copied as well. This process is done when
     * coming back from a depth-first recursion, i.e. smaller subgraphs are copied
     * before larger subgraphs.
     *
     * @param node
     * @param modelModification
     * @param visited
     */
    private void recursiveCopyWhereMultipleInEdges(RDFNode node, ModelModification modelModification,
                    Collection<RDFNode> visited) {
        // a non-resource is trivially ok
        if (!node.isResource()) {
            return;
        }
        if (visited.contains(node)) {
            return;
        }
        visited.add(node);
        List<Statement> outgoingEdges = node.getModel().listStatements(node.asResource(), null, (RDFNode) null)
                        .toList();
        for (Statement stmt : outgoingEdges) {
            recursiveCopyWhereMultipleInEdges(stmt.getObject(), modelModification, visited);
        }
        if (outgoingEdges.size() > 0) {
            Set<Resource> reachableFromNode = findReachableResources(node);
            List<Statement> incomingEdges = node.getModel().listStatements(null, null, node).toList();
            incomingEdges = incomingEdges.stream().filter(stmt -> !reachableFromNode.contains(stmt.getSubject()))
                            .collect(Collectors.toList());
            if (incomingEdges.size() > 1 && isSplittableNode(node)) {
                for (Statement stmt : incomingEdges) {
                    RDFNode copy = recursiveCopy(node, modelModification);
                    Statement newEdge = new StatementImpl(stmt.getSubject(), stmt.getPredicate(), copy);
                    modelModification.add(newEdge);
                    modelModification.remove(stmt);
                    // RDFDataMgr.write(System.out,
                    // modelModification.copyAndModify(node.getModel()), Lang.TRIG);
                }
                modelModification.remove(outgoingEdges);
            }
        }
    }

    private boolean isReachableFrom(RDFNode src, RDFNode target) {
        return isReachableFrom(src, target, new HashSet<>());
    }

    private boolean isReachableFrom(RDFNode src, RDFNode target, Collection<RDFNode> visited) {
        if (src.equals(target)) {
            return true;
        }
        if (!src.isResource()) {
            return false;
        }
        if (visited.contains(src)) {
            return false;
        }
        visited.add(src);
        StmtIterator it = src.getModel().listStatements(src.asResource(), null, (RDFNode) null);
        while (it.hasNext()) {
            Statement stmt = it.nextStatement();
            if (isReachableFrom(src, stmt.getObject(), visited)) {
                return true;
            }
        }
        return false;
    }

    private Set<Resource> findReachableResources(RDFNode src) {
        Set<Resource> reachable = new HashSet<>();
        findReachableResources(src, reachable);
        return reachable;
    }

    private void findReachableResources(RDFNode src, Set<Resource> found) {
        if (!src.isResource()) {
            return;
        }
        if (found.contains(src)) {
            return;
        }
        found.add(src.asResource());
        StmtIterator it = src.getModel().listStatements(src.asResource(), null, (RDFNode) null);
        while (it.hasNext()) {
            Statement stmt = it.nextStatement();
            findReachableResources(src, found);
        }
    }

    private RDFNode recursiveCopy(RDFNode node, ModelModification modelModification) {
        return recursiveCopy(node, modelModification, null, null, new HashSet<>());
    }

    private RDFNode recursiveCopy(RDFNode node, ModelModification modelModification, RDFNode toReplace,
                    RDFNode replacement, Collection<RDFNode> visited) {
        if (node.equals(toReplace)) {
            return replacement;
        }
        if (!node.isResource()) {
            return node;
        }
        if (visited.contains(node)) {
            return copyNode(node.asResource());
        }
        visited.add(node);
        RDFNode nodeInCopy;
        if (isSplittableNode(node)) {
            nodeInCopy = copyNode(node.asResource());
            visited.add(nodeInCopy);
        } else {
            return node;
        }
        if (toReplace == null && replacement == null) {
            toReplace = node;
            replacement = nodeInCopy;
        }
        List<Statement> outgoingEdges = node.getModel().listStatements(node.asResource(), null, (RDFNode) null)
                        .toList();
        for (Statement stmt : outgoingEdges) {
            RDFNode newObject = recursiveCopy(stmt.getObject(), modelModification, toReplace, replacement, visited);
            modelModification.add(new StatementImpl(nodeInCopy.asResource(), stmt.getPredicate(), newObject));
            modelModification.remove(stmt);
            // RDFDataMgr.write(System.out,
            // modelModification.copyAndModify(node.getModel()), Lang.TRIG);
        }
        return nodeInCopy;
    }

    private class ModelModification {
        private List<Statement> statementsToAdd;
        private List<Statement> statementsToRemove;

        public ModelModification() {
            this.statementsToAdd = new LinkedList<>();
            this.statementsToRemove = new LinkedList<>();
        }

        public Collection<Statement> getStatementsToAdd() {
            return Collections.unmodifiableCollection(statementsToAdd);
        }

        public Collection<Statement> getStatementsToRemove() {
            return Collections.unmodifiableCollection(statementsToRemove);
        }

        public void add(Statement stmt) {
            this.statementsToAdd.add(stmt);
        }

        public void add(Collection<Statement> statements) {
            this.statementsToAdd.addAll(statements);
        }

        public void remove(Statement stmt) {
            this.statementsToRemove.add(stmt);
        }

        public void remove(Collection<Statement> statements) {
            this.statementsToRemove.addAll(statements);
        }

        public void mergeModificationsFrom(ModelModification other) {
            this.statementsToRemove.addAll(other.statementsToRemove);
            this.statementsToAdd.addAll(other.statementsToAdd);
        }

        public Model copyAndModify(Model model) {
            Model ret = RdfUtils.cloneModel(model);
            modify(ret);
            return ret;
        }

        public void modify(Model model) {
            model.add(this.statementsToAdd);
            model.remove(this.statementsToRemove);
        }
    }
}


text:
@interface CustomProgressView ()
@property (nonatomic, strong)UIView  * progressView;
@end
@implementation CustomProgressView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.layer.cornerRadius = 5;
        self.clipsToBounds = YES;
        self.tintColors = __RGB(0xf94700);
        self.trackgroundColors = __RGB(0xe5e8e8);
        self.backgroundColor = self.trackgroundColors;
        [self setUI];
     }
    return self;
}

- (instancetype)init{
    if (self = [super init]) {
        self.layer.cornerRadius = 5;
        self.clipsToBounds = YES;
        self.tintColors = __RGB(0xf94700);
        self.trackgroundColors = __RGB(0xe5e8e8);
        self.backgroundColor = self.trackgroundColors;
        [self setUI];
    }
    return self;
}

- (void)setUI{
    _progressView = [[UIView alloc]init];
    _progressView.backgroundColor = self.tintColors;
    _progressView.layer.cornerRadius = 5;
    _progressView.clipsToBounds = YES;
    [self addSubview:_progressView];
}

- (void)setProgress:(float)progress{
    _progressView.frame = CGRectMake(0, 0, progress * CGRectGetWidth(self.bounds), self.size.height);
    CAGradientLayer * gradient = [CAGradientLayer layer];
    gradient.frame = _progressView.bounds;
    gradient.colors= @[(id)__RGB(0xff7c01).CGColor,(id)__RGB(0xf94700).CGColor];
    gradient.startPoint = CGPointMake(0, 0);
    gradient.endPoint = CGPointMake(1, 0);
    [_progressView.layer addSublayer:gradient];

}

- (void)setProgress:(float)progress animate:(BOOL)animate{
    _progressView.frame = CGRectZero;
    [UIView animateWithDuration:0.23 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
         _progressView.frame = CGRectMake(0, 0, progress * CGRectGetWidth(self.bounds), self.size.height);
    } completion:nil];
}

- (void)setTintColors:(UIColor *)tintColors {
    _tintColors = tintColors;
     _progressView.backgroundColor = _tintColors;
}

- (void)setTrackgroundColors:(UIColor *)trackgroundColors {
    _trackgroundColors = trackgroundColors;
    self.backgroundColor = _trackgroundColors;
}

@end

redpajama_set_name: RedPajamaGithub


text:
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from past.utils import old_div
import logging
# It is not clear if we need to copy here, given that we are almost
# immdediately going to save to the database. Let us assume that we don't.
# We can add it if it turns out that there are issues with mutability.
import copy
import attrdict as ad
import pytz
import datetime as pydt
import geojson
import arrow

import emission.core.wrapper.location as ecwl
import emission.net.usercache.formatters.common as fc
import attrdict as ad
import emission.storage.decorations.local_date_queries as ecsdlq

def format(entry):
    assert(entry.metadata.key == "background/location" or
            entry.metadata.key == "background/filtered_location")
    if ("mLatitude" in entry.data):
        return format_location_raw(entry)
    else:
        return format_location_simple(entry)

# TODO: Remove the RAW code since we don't really have any clients that
# are sending it. But while it is there, we should still convert ms to sec
# since the old data did have that in place
def format_location_raw(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    metadata.time_zone = "America/Los_Angeles"
    metadata.write_ts = old_div(float(entry.metadata.write_ts), 1000)
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = ad.AttrDict()
    data.latitude = entry.data.mLatitude
    data.longitude = entry.data.mLongitude
    data.loc = geojson.Point((data.longitude, data.latitude))
    data.ts = old_div(float(entry.data.mTime), 1000) # convert the ms from the phone to secs
    fc.expand_data_times(data, metadata)
    data.altitude = entry.data.mAltitude
    data.accuracy = entry.data.mAccuracy
    data.sensed_speed = entry.data.mSpeed
    data.heading = entry.data.mBearing
    formatted_entry.data = data

    return formatted_entry

def format_location_simple(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    if "time_zone" not in metadata:
        metadata.time_zone = "America/Los_Angeles"
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = entry.data
    fc.expand_data_times(data, metadata)
    data.loc = geojson.Point((data.longitude, data.latitude))
    data.heading = entry.data.bearing
    del data.bearing
    formatted_entry.data = data

    return formatted_entry


text:
package com.zfdang.zsmth_android;

import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.zfdang.zsmth_android.listeners.OnBoardFragmentInteractionListener;
import com.zfdang.zsmth_android.models.Board;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * {@link RecyclerView.Adapter} that can display a {@link Board} and makes a call to the
 * specified {@link OnBoardFragmentInteractionListener}.
 */
public class BoardRecyclerViewAdapter extends RecyclerView.Adapter<BoardRecyclerViewAdapter.ViewHolder> implements Filterable {

  private final List<Board> mBoards;
  private final OnBoardFragmentInteractionListener mListener;
  private BoardFilter mFilter = null;

  public BoardRecyclerViewAdapter(List<Board> items, OnBoardFragmentInteractionListener listener) {
    mBoards = items;
    mListener = listener;
  }

  @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.board_item, parent, false);
    return new ViewHolder(view);
  }

  @Override public void onBindViewHolder(final ViewHolder holder, int position) {
    holder.mItem = mBoards.get(position);
    Board board = holder.mItem;

    if (board.isFolder()) {
      holder.mCategoryView.setText("[" + board.getCategoryName() + "]");
      holder.mModeratorView.setVisibility(View.GONE);
      holder.mNameView.setText(board.getFolderName());
    } else if (board.isSection()) {
      holder.mCategoryView.setText("[" + board.getCategoryName() + "]");
      holder.mModeratorView.setVisibility(View.GONE);
      holder.mNameView.setText(board.getSectionName());
    } else if(board.isBoard()){
      holder.mCategoryView.setText("[" + board.getCategoryName() + "]");
      holder.mModeratorView.setVisibility(View.VISIBLE);
      holder.mModeratorView.setText(board.getModerator());
      holder.mNameView.setText(board.getBoardName());
    } else if(board.isInvalid()) {
      holder.mCategoryView.setText("[" + board.getCategoryName() + "]");
      holder.mModeratorView.setVisibility(View.GONE);
      holder.mNameView.setText(board.getBoardName());
    }

    holder.mView.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        if (null != mListener) {
          // Notify the active callbacks interface (the activity, if the
          // fragment is attached to one) that an item has been selected.
          mListener.onBoardFragmentInteraction(holder.mItem);
        }
      }
    });

    holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
      @Override public boolean onLongClick(View v) {
        if (null != mListener) {
          // Notify the active callbacks interface (the activity, if the
          // fragment is attached to one) that an item has been selected.
          mListener.onBoardLongClick(holder.mItem);
        }
        return false;
      }
    });
  }

  @Override public int getItemCount() {
    return mBoards.size();
  }

  @Override public Filter getFilter() {
    if (mFilter == null) {
      mFilter = new BoardFilter(this, mBoards);
    }
    return mFilter;
  }

  // https://stackoverflow.com/questions/29792187/add-a-search-filter-on-recyclerview-with-cards/29792313#29792313
  private static class BoardFilter extends Filter {
    private final BoardRecyclerViewAdapter adapter;
    private final List<Board> originalList;
    private final List<Board> filteredList;

    private BoardFilter(BoardRecyclerViewAdapter adapter, List<Board> originalList) {
      super();
      this.adapter = adapter;
      this.originalList = new LinkedList<>(originalList);
      this.filteredList = new ArrayList<>();
    }

    @Override protected FilterResults performFiltering(CharSequence constraint) {
      filteredList.clear();
      final FilterResults results = new FilterResults();

      if (constraint.length() == 0) {
        filteredList.addAll(originalList);
      } else {
        final String filterPattern = constraint.toString().trim();

        for (final Board board : originalList) {
          // this matching method can be further improved
          String boardLabel = String.format("%s-%s-%s", board.getBoardChsName(), board.getBoardEngName(), board.getCategoryName());
          if (Pattern.compile(Pattern.quote(filterPattern), Pattern.CASE_INSENSITIVE).matcher(boardLabel).find()) {
            filteredList.add(board);
          }
        }
      }
      results.values = filteredList;
      results.count = filteredList.size();
      return results;
    }

    @Override protected void publishResults(CharSequence constraint, FilterResults results) {
      adapter.mBoards.clear();
      adapter.mBoards.addAll((ArrayList<Board>) results.values);
      adapter.notifyDataSetChanged();
    }
  }

  public class ViewHolder extends RecyclerView.ViewHolder {
    public Board mItem;
    public final View mView;
    public final TextView mCategoryView;
    public final TextView mModeratorView;
    public final TextView mNameView;

    public ViewHolder(View view) {
      super(view);
      mView = view;
      mCategoryView = (TextView) view.findViewById(R.id.CategoryName);
      mModeratorView = (TextView) view.findViewById(R.id.ModeratorID);
      mNameView = (TextView) view.findViewById(R.id.BoardName);
    }

    @Override public String toString() {
      return mNameView.getText().toString();
    }
  }
}


text:
.class final Landroid/app/SystemServiceRegistry$35;
.super Landroid/app/SystemServiceRegistry$CachedServiceFetcher;
.source "SystemServiceRegistry.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/app/SystemServiceRegistry;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/app/SystemServiceRegistry$CachedServiceFetcher",
        "<",
        "Landroid/telephony/CarrierConfigManager;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .registers 1

    .prologue
    .line 424
    invoke-direct {p0}, Landroid/app/SystemServiceRegistry$CachedServiceFetcher;-><init>()V

    return-void
.end method

# virtual methods
.method public createService(Landroid/app/ContextImpl;)Landroid/telephony/CarrierConfigManager;
    .registers 3
    .param p1, "ctx"    # Landroid/app/ContextImpl;

    .prologue
    .line 427
    new-instance v0, Landroid/telephony/CarrierConfigManager;

    invoke-direct {v0}, Landroid/telephony/CarrierConfigManager;-><init>()V

    return-object v0
.end method

.method public bridge synthetic createService(Landroid/app/ContextImpl;)Ljava/lang/Object;
    .registers 3
    .param p1, "ctx"    # Landroid/app/ContextImpl;

    .prologue
    .line 426
    invoke-virtual {p0, p1}, Landroid/app/SystemServiceRegistry$35;->createService(Landroid/app/ContextImpl;)Landroid/telephony/CarrierConfigManager;

    move-result-object v0

    return-object v0
.end method


text:
import endpoints

from google.appengine.ext import ndb
from protorpc import remote

from endpoints_proto_datastore.ndb import EndpointsModel
from endpoints_proto_datastore.ndb import EndpointsAliasProperty

WEB_CLIENT_ID = '75603594494-t0bvn5ll6v1lgolb66g5cqqrksvllu4e.apps.googleusercontent.com'

class UserModel(EndpointsModel):
    _message_fields_schema = ('id', 'email')
    email = ndb.StringProperty()
    oauthUser = ndb.UserProperty()

    def IdSet(self, value):
        if not isinstance(value, basestring):
            raise TypeError('ID must be a string.')
        self.UpdateFromKey(ndb.Key(UserModel, value))

    @EndpointsAliasProperty(setter=IdSet, required=True)
    def id(self):
        if self.key is not None:
            return self.key.string_id()

@endpoints.api(name='user', version='v1', description='REST API for User',
               allowed_client_ids=[endpoints.API_EXPLORER_CLIENT_ID, WEB_CLIENT_ID],
               scopes=[endpoints.EMAIL_SCOPE])
class UserV1(remote.Service):
    @staticmethod
    def insert_user(user):
        if user.from_datastore:
            email = user.key.string_id()
            raise endpoints.BadRequestException(
                'UserModel of email %s already exists.' % (email,))

        user.oauthUser = endpoints.get_current_user()
        user.put()
        return user

    @staticmethod
    def check_user(user):
        if not user.from_datastore:
            raise endpoints.NotFoundException('User not found.')
        elif user.oauthUser != endpoints.get_current_user():
            raise endpoints.NotFoundException('oAuth user not allowed')

    @UserModel.method(path='users/{id}', http_method='GET', name='users.get', user_required=True)
    def UserGet(self, user):
        self.check_user(user)
        return user

    @UserModel.method(path='users/{id}', http_method='DELETE', name='users.remove', user_required=True)
    def UserRemove(self, user):
        self.check_user(user)
        user.key.delete()
        return user

    @UserModel.method(path='users', http_method='POST', name='users.insert', user_required=True)
    def UserInsert(self, user):
        return self.insert_user(user)

    @UserModel.method(path='users/{id}', http_method='PUT', name='users.update', user_required=True)
    def UserUpdate(self, user):
        self.check_user(user)
        user.oauthUser = endpoints.get_current_user()
        user.put()
        return user

    @UserModel.query_method(path='users', name='users.list', user_required=True)
    def UserList(self, query):
        return query.filter(UserModel.oauthUser == endpoints.get_current_user())

    @UserModel.method(path='login/{id}', http_method='GET', name='users.login', user_required=True)
    def LoginGet(self, user):
        if not user.from_datastore:
            return self.insert_user(user)
        elif user.oauthUser != endpoints.get_current_user():
            raise endpoints.NotFoundException('oAuth user not allowed')
        return user


text:
package com.vaadin.v7.client.widget.grid.selection;

import java.util.Collection;
import java.util.Collections;

import com.vaadin.client.data.DataSource.RowHandle;
import com.vaadin.v7.client.renderers.Renderer;
import com.vaadin.v7.client.widgets.Grid;

/**
 * No-row selection model.
 *
 * @author Vaadin Ltd
 * @since 7.4
 */
public class SelectionModelNone<T> extends AbstractRowHandleSelectionModel<T>
        implements SelectionModel.None<T> {

    @Override
    public boolean isSelected(T row) {
        return false;
    }

    @Override
    public Renderer<Boolean> getSelectionColumnRenderer() {
        return null;
    }

    @Override
    public void setGrid(Grid<T> grid) {
        // noop
    }

    @Override
    public void reset() {
        // noop
    }

    @Override
    public Collection<T> getSelectedRows() {
        return Collections.emptySet();
    }

    @Override
    protected boolean selectByHandle(RowHandle<T> handle)
            throws UnsupportedOperationException {
        throw new UnsupportedOperationException(
                "This selection model " + "does not support selection");
    }

    @Override
    protected boolean deselectByHandle(RowHandle<T> handle)
            throws UnsupportedOperationException {
        throw new UnsupportedOperationException(
                "This selection model " + "does not support deselection");
    }

}


text:
<polymer-element name="w5-item" extend="li" attributes="text href value">
    <script>
        Polymer('w5-item', {
            text: null,
            href: null,
            value: null,
            ready: function() {
                console.log('w5-item')
            }
        });
    </script>
</polymer-element>


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>ngToDo : Angular 1.4 RC</title>
        <meta charset="utf-8">
        <base href="/">

        <meta name="viewport"
              content="width=device-width,
              minimal-ui,
              initial-scale=1,
              maximum-scale=1,
              user-scalable=0" />

        <link href="Content/font-awesome.min.css" rel="stylesheet" />
        <link href="app.less" rel="stylesheet" />

    </head>

<body data-ng-app="app.toDo" ng-strict-di data-ng-controller="toDoAppController as app">

    <work-spinner data-ng-if="app.$router.navigating"></work-spinner>

    <app-header is-logged-in="app.isLoggedIn()" get-username="app.getUsername()"></app-header>

    <div ng-viewport class="main-content slide">

    </div>

    <app-bar></app-bar>
    <script src="scripts/angular-rc/angular.js"></script>
    <script src="scripts/angular-rc/router.es5.js"></script>
    <script src="scripts/angular-rc/angular-animate.js"></script>
    <script src="scripts/jquery-1.9.0.js"></script>
    <script src="scripts/q.min.js"></script>
    <script src="scripts/breeze.min.js"></script>
    <script src="scripts/breeze.angular.js"></script>

    <script src="app.js"></script>
</body>
</html>


text:
package com.amazonaws.services.applicationdiscovery.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.applicationdiscovery.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ExportInfoMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ExportInfoMarshaller {

    private static final MarshallingInfo<String> EXPORTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("exportId").build();
    private static final MarshallingInfo<String> EXPORTSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("exportStatus").build();
    private static final MarshallingInfo<String> STATUSMESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("statusMessage").build();
    private static final MarshallingInfo<String> CONFIGURATIONSDOWNLOADURL_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("configurationsDownloadUrl").build();
    private static final MarshallingInfo<java.util.Date> EXPORTREQUESTTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("exportRequestTime").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<Boolean> ISTRUNCATED_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("isTruncated").build();
    private static final MarshallingInfo<java.util.Date> REQUESTEDSTARTTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("requestedStartTime").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<java.util.Date> REQUESTEDENDTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("requestedEndTime").timestampFormat("unixTimestamp").build();

    private static final ExportInfoMarshaller instance = new ExportInfoMarshaller();

    public static ExportInfoMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ExportInfo exportInfo, ProtocolMarshaller protocolMarshaller) {

        if (exportInfo == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(exportInfo.getExportId(), EXPORTID_BINDING);
            protocolMarshaller.marshall(exportInfo.getExportStatus(), EXPORTSTATUS_BINDING);
            protocolMarshaller.marshall(exportInfo.getStatusMessage(), STATUSMESSAGE_BINDING);
            protocolMarshaller.marshall(exportInfo.getConfigurationsDownloadUrl(), CONFIGURATIONSDOWNLOADURL_BINDING);
            protocolMarshaller.marshall(exportInfo.getExportRequestTime(), EXPORTREQUESTTIME_BINDING);
            protocolMarshaller.marshall(exportInfo.getIsTruncated(), ISTRUNCATED_BINDING);
            protocolMarshaller.marshall(exportInfo.getRequestedStartTime(), REQUESTEDSTARTTIME_BINDING);
            protocolMarshaller.marshall(exportInfo.getRequestedEndTime(), REQUESTEDENDTIME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
const LessThan = Jymfony.Component.Validator.Constraints.LessThan;
const NumberConstraintTrait = Jymfony.Component.Validator.Constraints.NumberConstraintTrait;

/**
 * @memberOf Jymfony.Component.Validator.Constraints
 */
export default class Negative extends mix(LessThan, NumberConstraintTrait) {
    /**
     * @inheritdoc
     */
    __construct(options = null) {
        options = options || {};
        options.message = options.message || 'This value should be negative.';

        return super.__construct(this._configureNumberConstraintOptions(options));
    }

    /**
     * @inheritdoc
     */
    get validatedBy() {
        return 'Jymfony.Component.Validator.Constraints.LessThanValidator';
    }
}


text:
#include "../init/init.h"
#include "../songs/songs.h"
#include "../load/load.h"
#include "../draw/draw.h"
#include "../check/check.h"

void play(SDL_Surface *screen, int *world, int *level, int *azurites, int* difficulty, bool powersShop[8]);

void launchBonus(int powers[NB_BLOCK_X*NB_BLOCK_Y][4], int *lives, int *speed, int *azurites, int componentsPaddle[6], float balls[16][11]);

void launchBonusShop(bool powersShop[8], int *lives, int *speed, int *azurites, int componentsPaddle[6], float balls[16][11], int resetCounter);

#endif // GAME_H_INCLUDED


text:
const crypto = require('crypto');
const constants = require('constants');
const http = require('http');
const MessageText = require('../Message/Text.js');

var AES = function (host, username, password, connection, api) {
    this._host = host;
    this._username = username;
    this._password = password;
    this._connection = connection;
    this._api = api;
    this._hmac_hash = '';

    this._public_key = '';
    this._iv = crypto.randomBytes(16);
    this._key = crypto.createHash('sha256').update(crypto.randomBytes(16).toString('hex')).digest();
    this._session_key;

    this._salt_bytes = 16;
    this._current_salt = this._get_salt();
    this._salt_usage_count = 0;
    this._max_salt_usage = 20;
    this._max_salt_time = 30*1000;
    this._next_salt_time = (new Date()).getTime() + this._max_salt_time;
};

AES.prototype.__proto__ = require('events').EventEmitter.prototype;

AES.prototype.authorize = function() {
    this._register_enc_response();
    this._get_public_key();
};

AES.prototype._enc_command = function(command) {
    var salt_part = 'salt/'+(this._current_salt);
    if (this._is_new_salt_needed()){
        salt_part = 'nextSalt/'+(this._current_salt)+'/';
        this._current_salt = this._get_salt();
        salt_part += (this._current_salt);
    }
    var enc_part = this._cipher(salt_part + '/' + command, 'base64');

    return 'jdev/sys/enc/'+encodeURIComponent(enc_part);
}

AES.prototype._is_new_salt_needed = function(){
    if (this._salt_usage_count <= 0) {
        this._next_salt_time = (new Date()).getTime() + this._max_salt_time;
    }
    this._salt_usage_count++;
    if (
        (this._salt_usage_count >= this._max_salt_usage)
        || (this._next_salt_time < (new Date()).getTime())
    ){
        this._salt_usage_count = 0;
        return true;
    }
    return false;
}

AES.prototype.prepare_control_command = function(control, command) {
    var prefix = 'jdev/sps/io/';

    if (this._hmac_hash){
        prefix = 'jdev/sps/ios/'+this._hmac_hash+'/';
    }

    return this._enc_command(prefix + control + '/' + command);
};

AES.prototype.prepare_secure_command = function(command) {
    return this._enc_command(command);
}

AES.prototype._get_public_key = function() {
    var that = this;

    http.get('http://'+this._host+'/jdev/sys/getPublicKey', (res) => {
        res.on('data', (chunk) => {
            that._parse_public_key(chunk);
            that._generate_session_key();
        });
        res.resume();
    }).on('error', (e) => {
        that.emit('auth_failed', e.message);
    });
};

AES.prototype._parse_public_key = function(content) {
    var data = JSON.parse(content);
    var key = data.LL.value.replace(/CERTIFICATE/g, 'PUBLIC KEY');
    key = key.replace(/^(-+BEGIN PUBLIC KEY-+)(\w)/, '$1\n$2');
    key = key.replace(/(\w)(-+END PUBLIC KEY-+)$/, '$1\n$2');
    this._public_key = {
        'key': key,
        'padding': constants.RSA_PKCS1_PADDING
    };
};

AES.prototype._generate_session_key = function() {
    this._session_key = crypto.publicEncrypt(this._public_key, new Buffer(this._key.toString('hex')+':'+this._iv.toString('hex')));
    this._register_keyexchange_response();
    this._connection.send('jdev/sys/keyexchange/'+this._session_key.toString('base64'));
};

AES.prototype._register_keyexchange_response = function() {
    var that = this;
    this._api.command_chain.push({
        'control': /^j?dev\/sys\/keyexchange\//,
        'callback': function(loxone_message) {
            var key = new Buffer(that._decipher(loxone_message.value), 'hex').toString('utf8');
            var hmac = crypto.createHmac('sha1', key);
            var hmac_hash = hmac.update(that._username+':'+that._password).digest('hex');
            that._hmac_hash = hmac_hash;
            var enc_data = that._cipher(that._hmac_hash+'/'+that._username, 'base64');
            that._register_authenticateenc_response();
            that._connection.send('authenticateEnc/'+enc_data);
        },
        'onetime': true,
    });
};

AES.prototype._register_authenticateenc_response = function() {
    var that = this;
    this._api.command_chain.push({
        'control': /^authenticateEnc\//,
        'callback': function(loxone_message) {
            if (loxone_message.code === '200'){
                that.emit('authorized');
            }else{
                that.emit('auth_failed', loxone_message);
            }
        },
        'onetime': true,
    });
};

AES.prototype._register_enc_response = function() {
    var that = this;
    this._api.command_chain.push({
        'control': /^jdev\/sys\/enc\//,
        'callback': function(loxone_message) {
            if (loxone_message.code === '200'){
                var dec_message = new MessageText(JSON.stringify(loxone_message.data));
                var dec_control = that._decipher(decodeURIComponent(loxone_message.control.substr(13)));
                dec_control = dec_control.replace(/^salt\/[^\/]*\//, "");
                dec_control = dec_control.replace(/^nextSalt\/[^\/]*\/[^\/]*\//, "");
                dec_control = dec_control.replace(/^jdev\//, "dev/");
                dec_message.control = dec_control;
                that.emit('message_text', dec_message);
            }
        },
    });
};

AES.prototype._decipher = function(enc_data) {
    var decipher = crypto.createDecipheriv('aes-256-cbc', this._key, this._iv);
    decipher.setAutoPadding(false);
    var data = decipher.update(enc_data,'base64','utf-8');
    data += decipher.final('utf-8');
    return data.replace(/\x00.*$/,"");
};

AES.prototype._cipher = function(data, out_enc) {
    var cipher = crypto.createCipheriv('aes-256-cbc', this._key, this._iv);
    var enc_data = cipher.update(data + "\0",'utf-8', out_enc);
    enc_data += cipher.final(out_enc);
    return enc_data;
};

AES.prototype._get_salt = function() {
    return encodeURIComponent(crypto.randomBytes(this._salt_bytes).toString('hex'));
};

module.exports = AES;


text:
		 Truck Data

 All Truck Data listed here will be available for First Weighing selection in the Weighing Scale form.

 Truck Data that are currently tagged to Second Weighing will not be displayed here.

							Truck ID
							Truck Code
							Date Modified


text:
package org.mmtk.utility.options;

import org.mmtk.plan.Plan;

/**
 * Provide an upper bound on nursery size. This option is not intended to
 * be created directly, but via NurserySize.
 */
public final class BoundedNursery extends org.vmutil.options.PagesOption {
  /**
   * Create the option.
   */
  public BoundedNursery() {
    super(Options.set, "Bounded Nursery",
        "Bound the maximum size of the nursery to this value",
        Plan.DEFAULT_MAX_NURSERY);
  }

  /**
   * Nursery can not be empty.
   */
  protected void validate() {
    failIf(value <= 0, "Can not have an empty nursery");
  }
}


text:
package org.apereo.cas;

import org.apereo.cas.qr.authentication.JsonResourceQRAuthenticationDeviceRepositoryTests;
import org.apereo.cas.qr.authentication.QRAuthenticationDeviceRepositoryTests;
import org.apereo.cas.qr.authentication.QRAuthenticationTokenAuthenticationHandlerTests;
import org.apereo.cas.qr.authentication.QRAuthenticationTokenCredentialTests;
import org.apereo.cas.qr.validation.DefaultQRAuthenticationTokenValidatorServiceTests;
import org.apereo.cas.qr.validation.QRAuthenticationTokenValidationResultTests;
import org.apereo.cas.qr.web.QRAuthenticationChannelControllerTests;
import org.apereo.cas.qr.web.QRAuthenticationDeviceRepositoryEndpointTests;
import org.apereo.cas.qr.web.flow.QRAuthenticationGenerateCodeActionTests;
import org.apereo.cas.qr.web.flow.QRAuthenticationValidateTokenActionTests;
import org.apereo.cas.qr.web.flow.QRAuthenticationWebflowConfigurerTests;

import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;

/**
 * This is {@link AllTestsSuite}.
 *
 * @author Misagh Moayyed
 * @since 6.0.0-RC3
 */
@SelectClasses({
    QRAuthenticationTokenCredentialTests.class,
    QRAuthenticationChannelControllerTests.class,
    QRAuthenticationTokenAuthenticationHandlerTests.class,
    QRAuthenticationValidateTokenActionTests.class,
    QRAuthenticationGenerateCodeActionTests.class,
    QRAuthenticationWebflowConfigurerTests.class,
    QRAuthenticationDeviceRepositoryEndpointTests.class,
    QRAuthenticationDeviceRepositoryTests.class,
    DefaultQRAuthenticationTokenValidatorServiceTests.class,
    QRAuthenticationTokenValidationResultTests.class,
    JsonResourceQRAuthenticationDeviceRepositoryTests.class
})
@Suite
public class AllTestsSuite {
}


text:
package MIP::Recipes::Pipeline::Install;

use 5.026;
use Carp;
use charnames qw{ :full :short };
use Cwd;
use English qw{ -no_match_vars };
use File::Spec::Functions qw{ catfile };
use List::Util qw{ any };
use open qw{ :encoding(UTF-8) :std };
use Params::Check qw{ check allow last_error };
use utf8;
use warnings;
use warnings qw{ FATAL utf8 };

## MIPs lib/
use MIP::Constants
  qw{ $COLON $DOT $LOG_NAME $NEWLINE $SINGLE_QUOTE $SPACE set_container_constants };

BEGIN {

    require Exporter;
    use base qw{ Exporter };

    # Functions and variables which can be optionally exported
    our @EXPORT_OK = qw{ pipeline_install };
}

sub pipeline_install {

## Function : Install recipes for mip pipelines
## Returns  :
## Arguments: $active_parameter_href => Active parameters for this download hash {REF}
##          : $quiet                 => Be quiet
##          : $verbose               => Verbosity

    my ($arg_href) = @_;

    ## Flatten argument(s)
    my $active_parameter_href;

    ## Default(s)
    my $quiet;
    my $verbose;

    my $tmpl = {
        active_parameter_href => {
            default     => {},
            defined     => 1,
            required    => 1,
            store       => \$active_parameter_href,
            strict_type => 1,
        },
        quiet => {
            allow       => [ undef, 0, 1 ],
            default     => 0,
            store       => \$quiet,
            strict_type => 1,
        },
        verbose => {
            default     => $arg_href->{active_parameter_href}{verbose},
            store       => \$verbose,
            strict_type => 1,
        },
    };

    check( $tmpl, $arg_href, 1 ) or croak q{Could not parse arguments!};

    use MIP::Active_parameter qw{ set_programs_for_installation };
    use MIP::Recipes::Install::Container qw{ install_containers };
    use MIP::Recipes::Install::Mip_scripts qw{ install_mip_scripts };
    use MIP::Recipes::Install::Post_installation qw{ check_mip_installation };

    ## Retrieve logger object now that log_file has been set
    my $log = Log::Log4perl->get_logger($LOG_NAME);

    $log->info( q{Installing MIP into environment: } . $active_parameter_href->{environment_name} );

    set_container_constants( { active_parameter_href => $active_parameter_href, } );

    ## Process input parameters to get a correct combination of programs that are to be installed
    set_programs_for_installation(
        {
            active_parameter_href => $active_parameter_href,
        }
    );

    ## Cache containers
    install_containers(
        {
            active_parameter_href => $active_parameter_href,
            container_href        => $active_parameter_href->{container},
        }
    );

    ## Copy mip scripts
    install_mip_scripts(
        {
            active_parameter_href => $active_parameter_href,
        }
    );

    ## Check installation
    check_mip_installation(
        {
            active_parameter_href => $active_parameter_href,
        }
    );

    $log->info(q{Finished installing MIP});

    return;
}

1;


text:
title: Sign Up!
permalink: "/signup"
layout: single
---

{% include mailchimp.html %}

You can also follow us at

 ReRoll Games
 @ReRoll_BLR
 @ReRoll


text:
class TransactionLedger < ActiveRecord::Base
  belongs_to :transaction_account
  belongs_to :transactionn, class_name: 'Transaction', foreign_key: :transaction_id
  belongs_to :accountable, :polymorphic => true

  validates :accountable_type,        :presence => true
  validates :accountable_id,          :presence => true
  #validates :transaction_id,          :presence => true## test fails but we need this validation back in
  validates :transaction_account_id,  :presence => true

  validates :debit,   :presence => true
  validates :credit,  :presence => true
  validates :period,  :presence => true

  def revenue
    (transaction_account_id == TransactionAccount::REVENUE_ID) ? (credit - debit) : 0.0
  end

  def cash
    (transaction_account_id == TransactionAccount::CASH_ID) ? (credit - debit) : 0.0
  end

  def accounts_receivable
    (transaction_account_id == TransactionAccount::ACCOUNTS_RECEIVABLE_ID) ? (credit - debit) : 0.0
  end

  def accounts_payable
    (transaction_account_id == TransactionAccount::ACCOUNTS_PAYABLE_ID) ? (credit - debit) : 0.0
  end

  def transaction_account_name
    Rails.cache.fetch("transaction_account_name-#{transaction_account_id}", :expires_in => 12.hours) do
      transaction_account.name
    end
  end

  def self.between(start_time, end_time)
    where("created_at >= ? AND created_at <= ?", start_time, end_time)
  end
end


text:
/** *****************************************************************************
 * Pipeline
 *
 * @author       Isaac Suttell <isaac_suttell@playstation.sony.com>
 * @file         Render Workflow to hepl ensure we consistently produce the
 *               same results across each page and prints
 * @flow
 ***************************************************************************** */

module.exports = () => {
  function AssetFactory(assets) {
    return {
      forPayload() {
        return {
          js: assets.js,
          css: assets.css,
        };
      },
    };
  }

  return AssetFactory;
};


text:
package cz.atlascon.travny.graphql.input;

import com.google.common.collect.Maps;
import cz.atlascon.travny.schemas.Field;
import graphql.schema.DataFetchingFieldSelectionSet;

import java.util.Map;
import java.util.Set;

public class RequestedFields {

    private Map<String, RequestedFields> subFields = Maps.newHashMap();

    public RequestedFields(DataFetchingFieldSelectionSet selectionSet) {
        this(selectionSet.get().keySet());
    }

    private RequestedFields() {
    }

    public RequestedFields(Set<String> fields) {
        for (String fn : fields) {
            processFieldName(fn, this);
        }
    }

    public boolean isRequested(Field field) {
        return isRequested(field.getName());
    }

    public void addField(String f) {
        subFields.put(f, new RequestedFields());
    }

    private void processFieldName(String fieldName, final RequestedFields target) {
        RequestedFields flds = target;
        while (fieldName.indexOf('/') > -1) {
            String prefix = fieldName.substring(0, fieldName.indexOf('/'));
            fieldName = fieldName.substring(prefix.length() + 1);
            flds = flds.subFields.computeIfAbsent(prefix, n -> new RequestedFields());
        }
        flds.addField(fieldName);
    }

    public boolean isRequested(final String fieldName) {
        return subFields.containsKey(fieldName);
    }

    public RequestedFields getSub(final String fieldName) {
        RequestedFields existing = subFields.get(fieldName);
        return existing == null ? new RequestedFields() : existing;
    }

    @Override
    public String toString() {
        return subFields.toString();
    }
}


text:
layout: page-fullwidth
permalink: /about/
title: About Us
---

  Since 1998,
  Software Carpentry has been teaching researchers in science, engineering, medicine, and related disciplines
  the computing skills they need to get more done in less time and with less pain.
  Our volunteer instructors
  have run hundreds of events
  for thousands of scientists in the past two and a half years.
  All of our lesson materials are freely reusable
  under the Creative Commons - Attribution license.

  The Software Carpentry Foundation
  and its sibling organization Data Carpentry
  are members of NumFOCUS,
  a 501(c)3 non-profit incorporated in the United States.

Supporters

      Software Carpentry is made possible by the generous support of
      our partners
      and by the hard work of our volunteers.
      We offer several levels of institutional engagement,
      and individuals can become instructors.

Workshops

      You can host a workshop
      or attend one that someone else is hosting.
      Our code of conduct
      and operations guides
      describe how our workshops are run,
      and our answers other questions.

Conversations

      You can send us email,
      join our mailing lists,
      read our blog,
      follow us on Twitter,
      or browse our repositories on GitHub.

Make Things

      As an open source project,
      we rely on volunteers to
      create our lessons
      and
      build our tools.

Read Things

      Best Practices in Scientific Computing
      and
      Software Carpentry: Lessons Learned
      summarize what we've learned.
      You may also enjoy
      these other readings.

Buy Things

      Want to show your support?
      Our online store
      offers everything from maternity shirts to messenger bags,
      and you can buy our stickers too.

Workshops

Learners

Instructors


text:
  <a href="<?php the_permalink(); ?>" class="<?= do_shortcode('[ct id="ct_Classifica_radio_a43a"]') ?>"><?php the_title(); ?>
    <?php get_template_part('templates/species-content/species-classification-alt1'); ?>

  <article <?php post_class(); ?>>

        <?php get_template_part('templates/species-title'); ?>

        <?php if (do_shortcode('[ct id="ct_Latin_text_9c2a"]')) : ?>
          <?php echo do_shortcode('[ct id="ct_Latin_text_9c2a"]') ?>
        <?php endif; ?>

      <?php get_template_part('templates/species-content'); ?>

      <?php get_template_part('templates/species-meta'); ?>
      <?php wp_link_pages(array('before' => '
' . __('Pages:', 'roots'), 'after' => '
')); ?>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>gameplay: Main Page</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="custom.css" rel="stylesheet" type="text/css" />
<link href="search/search.css" rel="stylesheet" type="text/css"/>

overview
wiki
api reference
forums
download

Here is a list of all documented class members with links to the class documentation for each member:

- v -

v : gameplay::SpriteBatch::SpriteVertex

v1 : gameplay::Theme::UVs

v2 : gameplay::Theme::UVs

VALUE_CHANGED : gameplay::Control::Listener

Vector2() : gameplay::Vector2

Vector3() : gameplay::Vector3

Vector4() : gameplay::Vector4

VEHICLE : gameplay::PhysicsCollisionObject

VEHICLE_WHEEL : gameplay::PhysicsCollisionObject

VertexFormat() : gameplay::VertexFormat

VerticalLayout() : gameplay::VerticalLayout

VIEW_MATRIX : gameplay::RenderState

VIEW_PROJECTION_MATRIX : gameplay::RenderState

visit() : gameplay::Scene

<address class="footer">
Generated on Wed May 18 2022 18:44:29 for gameplay by  1.9.4
</address>


text:
package ru.apetrov. models;

public class Bug extends Item {

}


text:
/**
 * wire/domReady plugin
 * A base wire/domReady module that plugins can use if they need domReady.  Simply
 * add 'wire/domReady' to your plugin module dependencies
 * (e.g. require(['wire/domReady', ...], function(domReady, ...) { ... })) and you're
 * set.
 *
 * wire is part of the cujo.js family of libraries (http://cujojs.com/)
 *
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Returns a function that accepts a callback to be called when the DOM is ready.
 *
 * You can also use your AMD loader's paths config to map wire/domReady to whatever
 * domReady function you might want to use.  See documentation for your AMD loader
 * for specific instructions.  For curl.js and requirejs, it will be something like:
 *
 *  paths: {
 *      'wire/domReady': 'path/to/my/domReady'
 *  }
 */

(function(global) {
define(['require'], function(req) {

	// Try require.ready first
	return (global.require && global.require.ready) || function (cb) {
		// If it's not available, assume a domReady! plugin is available
		req(['domReady!'], function () {
            // Using domReady! as a plugin will automatically wait for domReady
            // so we can just call the callback.
            cb();
		});
	};

});
})(this);


text:
package demo.vo;

public enum ServiceType {
	DATA,EVENT,ACTION,DIRECTIVE
}


text:
package graph

import (
	"github.com/docker/docker/engine"
)

func (s *TagStore) CmdLoad(job *engine.Job) engine.Status {
	return job.Errorf("CmdLoad is not supported on this platform")
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>hackathon fullfreedom</title>

    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,900,700,500,300,100' rel='stylesheet' type='text/css'>

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

Back

                  College JumpStart Scholarship Program

Deadline: October 17, 2015

                $1,000

                  The College JumpStart Scholarship is an annual, merit-based competition -- financial need is not considered -- that is open from 10th to 12th graders, college students and non-traditional students.

The main requirement is that you are committed to going to school and can express your goals for getting a higher education.

Apply


text:
<include file="Public/min-header"/>

              <form action="{:U('Promotion/search_goods',array('tpl'=>'select_goods'))}" id="search-form2" class="navbar-form form-inline" method="post">

                  <select name="cat_id" id="cat_id" class="form-control">
                    <option value="">所有分类</option>
                        <foreach name="categoryList" item="v" key="k" >
                           <option value="{$v['id']}" <if condition="$v[id] eq $cat_id">selected</if>>{$v['name']}</option>
			 			</foreach>
                  </select>

                  <select name="brand_id" id="brand_id" class="form-control">
                    <option value="">所有品牌</option>
                        <foreach name="brandList" item="v" key="k" >
                           <option value="{$v['id']}" <if condition="$v[id] eq $brand_id">selected</if>>{$v['name']}</option>
						</foreach>
                  </select>

                    <select name="intro" class="form-control">
                        <option value="0">全部</option>
                        <option value="is_new">新品</option>
                        <option value="is_recommend">推荐</option>
                    </select>

                  关键词

                    <input type="text" name="keywords" value="{$keywords}" placeholder="搜索词" id="input-order-id" class="form-control">

                <button type="submit" id="button-filter search-order" class="btn btn-primary">查找</button>
              </form>

			                选择
			                商品名称
			                价格
			                库存
			                操作

			                <volist name="goodsList" id="list">

                                    <input type="radio" name="goods_id" data-id="{$list.goods_id}" data-name="{$list.goods_name}" data-count="{$list.store_count}" data-price="{$list.shop_price}" onclick="changeGoods(this)"/>

                                {$list.goods_name}
                                {$list.shop_price}
                                {$list.store_count}
                                删除

			            	</volist>

	            		{$page}

	                    确定