text:
package org.apache.xmlbeans.impl.schema;

import org.apache.xmlbeans.*;
import org.apache.xmlbeans.impl.common.QNameHelper;
import org.apache.xmlbeans.impl.common.ResolverUtil;
import org.apache.xmlbeans.impl.util.HexBin;
import org.apache.xmlbeans.impl.values.XmlStringImpl;
import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException;
import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
import org.xml.sax.EntityResolver;

import javax.xml.namespace.QName;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Consumer;

/**
 * This class represents the state of the SchemaTypeSystemCompiler as it's
 * going.
 */
public class StscState {
    private final static XmlValueRef XMLSTR_PRESERVE = buildString("preserve");
    private final static XmlValueRef XMLSTR_REPLACE = buildString("preserve");
    private final static XmlValueRef XMLSTR_COLLAPSE = buildString("preserve");

    static final SchemaType[] EMPTY_ST_ARRAY = new SchemaType[0];

    private static final XmlValueRef[] FACETS_NONE = new XmlValueRef[12];
    private static final boolean[] FIXED_FACETS_NONE = new boolean[12];
    private static final boolean[] FIXED_FACETS_WS = new boolean[12];

    private static final XmlValueRef[] FACETS_WS_COLLAPSE = {
        null, null, null, null, null, null, null, null, null,
        build_wsstring(SchemaType.WS_COLLAPSE), null, null
    };

    final static XmlValueRef[] FACETS_UNION = FACETS_NONE;
    final static boolean[] FIXED_FACETS_UNION = FIXED_FACETS_NONE;
    final static XmlValueRef[] FACETS_LIST = FACETS_WS_COLLAPSE;
    final static boolean[] FIXED_FACETS_LIST = FIXED_FACETS_WS;

    private static final ThreadLocal<StscStack> tl_stscStack = new ThreadLocal<>();

    private final static String PROJECT_URL_PREFIX = "project://local";

    private String _givenStsName;
    private Collection<XmlError> _errorListener;
    private SchemaTypeSystemImpl _target;
    private BindingConfig _config;
    private Map<QName, QName> _compatMap;
    private boolean _doingDownloads;
    private byte[] _digest = null;
    private boolean _noDigest = false;

    // EXPERIMENTAL: recovery from compilation errors and partial type systems
    private boolean _allowPartial = false;
    private int _recoveredErrors = 0;

    private SchemaTypeLoader _importingLoader;

    private final Map<String, SchemaContainer> _containers = new LinkedHashMap<>();
    private SchemaDependencies _dependencies;

    private final Map<SchemaTypeImpl, SchemaTypeImpl> _redefinedGlobalTypes = new LinkedHashMap<>();
    private final Map<SchemaModelGroupImpl, SchemaModelGroupImpl> _redefinedModelGroups = new LinkedHashMap<>();
    private final Map<SchemaAttributeGroupImpl, SchemaAttributeGroupImpl> _redefinedAttributeGroups = new LinkedHashMap<>();

    private final Map<QName, SchemaType> _globalTypes = new LinkedHashMap<>();
    private final Map<QName, SchemaGlobalElement> _globalElements = new LinkedHashMap<>();
    private final Map<QName, SchemaGlobalAttribute> _globalAttributes = new LinkedHashMap<>();
    private final Map<QName, SchemaModelGroup> _modelGroups = new LinkedHashMap<>();
    private final Map<QName, SchemaAttributeGroup> _attributeGroups = new LinkedHashMap<>();
    private final Map<QName, SchemaType> _documentTypes = new LinkedHashMap<>();
    private final Map<QName, SchemaType> _attributeTypes = new LinkedHashMap<>();
    private final Map<String, SchemaType> _typesByClassname = new LinkedHashMap<>();
    private final Map<String, SchemaComponent> _misspelledNames = new HashMap<>();
    private final Set<SchemaComponent> _processingGroups = new LinkedHashSet<>();
    private final Map<QName, SchemaIdentityConstraint> _idConstraints = new LinkedHashMap<>();
    private final Set<String> _namespaces = new HashSet<>();
    private final List<SchemaAnnotation> _annotations = new ArrayList<>();
    private boolean _noUpa;
    private boolean _noPvr;
    private boolean _noAnn;
    private boolean _mdefAll;
    private final Set<String> _mdefNamespaces = buildDefaultMdefNamespaces();
    private EntityResolver _entityResolver;
    private File _schemasDir;

    private final Map<String, String> _sourceForUri = new HashMap<>();
    private URI _baseURI = URI.create(PROJECT_URL_PREFIX + "/");
    private final SchemaTypeLoader _s4sloader = XmlBeans.typeLoaderForClassLoader(SchemaDocument.class.getClassLoader());

    private static Set<String> buildDefaultMdefNamespaces() {
        // namespaces which are known to appear in WSDLs redundantly
        return new HashSet<>(
            Collections.singletonList("http://www.openuri.org/2002/04/soap/conversation/"));
    }

    /**
     * Only constructed via StscState.start().
     */
    private StscState() {
    }

    /**
     * Initializer for incremental compilation
     */
    public void initFromTypeSystem(SchemaTypeSystemImpl system, Set<String> newNamespaces) {
//         setGivenTypeSystemName(system.getName().substring(14));

        SchemaContainer[] containers = system.containers();
        for (SchemaContainer container : containers) {
            if (!newNamespaces.contains(container.getNamespace())) {
                // Copy data from the given container
                addContainer(container);
            }
        }
    }

    /* CONTAINERS ================================================================*/

    void addNewContainer(String namespace) {
        if (_containers.containsKey(namespace)) {
            return;
        }

        SchemaContainer container = new SchemaContainer(namespace);
        container.setTypeSystem(sts());
        addNamespace(namespace);
        _containers.put(namespace, container);
    }

    private void addContainer(SchemaContainer container) {
        _containers.put(container.getNamespace(), container);

        // container.redefinedModelGroups() / .redefinedAttributeGroups() / .redefinedGlobalTypes() are always empty
        // no need to copy them over to _redefinedModelGroups / _redefinedAttributeGroups / _redefinedGlobalTypes

        container.globalElements().forEach(g -> _globalElements.put(g.getName(), g));
        container.globalAttributes().forEach(g -> _globalAttributes.put(g.getName(), g));
        container.modelGroups().forEach(g -> _modelGroups.put(g.getName(), g));
        container.attributeGroups().forEach(g -> _attributeGroups.put(g.getName(), g));

        container.globalTypes().forEach(mapTypes(_globalTypes, false));
        container.documentTypes().forEach(mapTypes(_documentTypes, true));
        container.attributeTypes().forEach(mapTypes(_attributeTypes, true));

        container.identityConstraints().forEach(g -> _idConstraints.put(g.getName(), g));

        _annotations.addAll(container.annotations());
        _namespaces.add(container.getNamespace());
        container.unsetImmutable();
    }

    private Consumer<SchemaType> mapTypes(Map<QName, SchemaType> map, boolean useProperties) {
        return (t) -> {
            QName name = useProperties ? t.getProperties()[0].getName() : t.getName();
            map.put(name, t);
            if (t.getFullJavaName() != null) {
                addClassname(t.getFullJavaName(), t);
            }
        };
    }

    SchemaContainer getContainer(String namespace) {
        return _containers.get(namespace);
    }

    Map<String, SchemaContainer> getContainerMap() {
        return Collections.unmodifiableMap(_containers);
    }

    /* DEPENDENCIES ================================================================*/

    void registerDependency(String sourceNs, String targetNs) {
        _dependencies.registerDependency(sourceNs, targetNs);
    }

    void registerContribution(String ns, String fileUrl) {
        _dependencies.registerContribution(ns, fileUrl);
    }

    SchemaDependencies getDependencies() {
        return _dependencies;
    }

    void setDependencies(SchemaDependencies deps) {
        _dependencies = deps;
    }

    boolean isFileProcessed(String url) {
        return _dependencies.isFileRepresented(url);
    }

    /**
     * Initializer for schematypepath
     */
    public void setImportingTypeLoader(SchemaTypeLoader loader) {
        _importingLoader = loader;
    }

    /**
     * Initializer for error handling.
     */
    public void setErrorListener(Collection<XmlError> errorListener) {
        _errorListener = errorListener;
    }

    /**
     * Passes an error on to the current error listener.
     * KHK: remove this
     */
    public void error(String message, int code, XmlObject loc) {
        addError(_errorListener, message, code, loc);
    }

    /**
     * Passes an error on to the current error listener.
     */
    public void error(String code, Object[] args, XmlObject loc) {
        addError(_errorListener, code, args, loc);
    }

    /**
     * Passes a recovered error on to the current error listener.
     */
    public void recover(String code, Object[] args, XmlObject loc) {
        addError(_errorListener, code, args, loc);
        _recoveredErrors++;
    }

    /**
     * Passes an error on to the current error listener.
     */
    public void warning(String message, int code, XmlObject loc) {
        addWarning(_errorListener, message, code, loc);
    }

    /**
     * Passes an error on to the current error listener.
     */
    public void warning(String code, Object[] args, XmlObject loc) {
        // it's OK for XMLSchema.xsd itself to have reserved type names
        if (XmlErrorCodes.RESERVED_TYPE_NAME.equals(code) &&
            loc.documentProperties().getSourceName() != null &&
            loc.documentProperties().getSourceName().indexOf("XMLSchema.xsd") > 0) {
            return;
        }

        addWarning(_errorListener, code, args, loc);
    }

    /**
     * Passes a warning on to the current error listener.
     */
    public void info(String message) {
        addInfo(_errorListener, message);
    }

    /**
     * Passes a warning on to the current error listener.
     */
    public void info(String code, Object[] args) {
        addInfo(_errorListener, code, args);
    }

    // KHK: remove this
    public static void addError(Collection<XmlError> errorListener, String message, int code, XmlObject location) {
        XmlError err =
            XmlError.forObject(
                message,
                XmlError.SEVERITY_ERROR,
                location);
        errorListener.add(err);
    }

    public static void addError(Collection<XmlError> errorListener, String code, Object[] args, XmlObject location) {
        XmlError err =
            XmlError.forObject(
                code,
                args,
                XmlError.SEVERITY_ERROR,
                location);
        errorListener.add(err);
    }

    public static void addError(Collection<XmlError> errorListener, String code, Object[] args, File location) {
        XmlError err =
            XmlError.forLocation(
                code,
                args,
                XmlError.SEVERITY_ERROR,
                location.toURI().toString(), 0, 0, 0);
        errorListener.add(err);
    }

    public static void addError(Collection<XmlError> errorListener, String code, Object[] args, URL location) {
        XmlError err =
            XmlError.forLocation(
                code,
                args,
                XmlError.SEVERITY_ERROR,
                location.toString(), 0, 0, 0);
        errorListener.add(err);
    }

    // KHK: remove this
    public static void addWarning(Collection<XmlError> errorListener, String message, int code, XmlObject location) {
        XmlError err =
            XmlError.forObject(
                message,
                XmlError.SEVERITY_WARNING,
                location);
        errorListener.add(err);
    }

    public static void addWarning(Collection<XmlError> errorListener, String code, Object[] args, XmlObject location) {
        XmlError err =
            XmlError.forObject(
                code,
                args,
                XmlError.SEVERITY_WARNING,
                location);
        errorListener.add(err);
    }

    public static void addInfo(Collection<XmlError> errorListener, String message) {
        XmlError err = XmlError.forMessage(message, XmlError.SEVERITY_INFO);
        errorListener.add(err);
    }

    public static void addInfo(Collection<XmlError> errorListener, String code, Object[] args) {
        XmlError err = XmlError.forMessage(code, args, XmlError.SEVERITY_INFO);
        errorListener.add(err);
    }

    public void setGivenTypeSystemName(String name) {
        _givenStsName = name;
    }

    /**
     * Initializer for references to the SchemaTypeLoader
     */
    public void setTargetSchemaTypeSystem(SchemaTypeSystemImpl target) {
        _target = target;
    }

    /**
     * Accumulates a schema digest...
     */
    public void addSchemaDigest(byte[] digest) {
        if (_noDigest) {
            return;
        }

        if (digest == null) {
            _noDigest = true;
            _digest = null;
            return;
        }

        if (_digest == null) {
            _digest = new byte[128 / 8]; // 128 bits.
        }
        int len = _digest.length;
        if (digest.length < len) {
            len = digest.length;
        }
        for (int i = 0; i < len; i++) {
            _digest[i] ^= digest[i];
        }
    }

    /**
     * The SchemaTypeSystem which we're building types on behalf of.
     */
    public SchemaTypeSystemImpl sts() {
        if (_target != null) {
            return _target;
        }

        String name = _givenStsName;
        if (name == null && _digest != null) {
            name = "s" + new String(HexBin.encode(_digest), StandardCharsets.ISO_8859_1);
        }

        _target = new SchemaTypeSystemImpl(name);
        return _target;
    }

    /**
     * True if the given URI is a local file
     */
    public boolean shouldDownloadURI(String uriString) {
        if (_doingDownloads) {
            return true;
        }

        if (uriString == null) {
            return false;
        }

        try {
            URI uri = new URI(uriString);
            if (uri.getScheme().equalsIgnoreCase("jar") ||
                uri.getScheme().equalsIgnoreCase("zip")) {
                // It may be local or not, depending on the embedded URI
                String s = uri.getSchemeSpecificPart();
                int i = s.lastIndexOf('!');
                return shouldDownloadURI(i > 0 ? s.substring(0, i) : s);
            }
            return uri.getScheme().equalsIgnoreCase("file");
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * Initializer for compatMap.
     */
    public void setOptions(XmlOptions options) {
        if (options == null) {
            return; // defaults are all false.
        }

        _allowPartial = options.isCompilePartialTypesystem();

        _compatMap = options.getCompileSubstituteNames();
        _noUpa = options.isCompileNoUpaRule() ||
                 !"true".equals(SystemProperties.getProperty("xmlbean.uniqueparticleattribution", "true"));
        _noPvr = options.isCompileNoPvrRule() ||
                 !"true".equals(SystemProperties.getProperty("xmlbean.particlerestriction", "true"));
        _noAnn = options.isCompileNoAnnotations() ||
                 !"true".equals(SystemProperties.getProperty("xmlbean.schemaannotations", "true"));
        _doingDownloads = options.isCompileDownloadUrls() ||
                          "true".equals(SystemProperties.getProperty("xmlbean.downloadurls", "false"));
        _entityResolver = options.getEntityResolver();

        if (_entityResolver == null) {
            _entityResolver = ResolverUtil.getGlobalEntityResolver();
        }

        if (_entityResolver != null) {
            _doingDownloads = true;
        }

        Set<String> mdef = options.getCompileMdefNamespaces();
        if (mdef != null) {
            _mdefNamespaces.addAll(mdef);

            String local = "##local";
            String any = "##any";

            if (_mdefNamespaces.contains(local)) {
                _mdefNamespaces.remove(local);
                _mdefNamespaces.add("");
            }
            if (_mdefNamespaces.contains(any)) {
                _mdefNamespaces.remove(any);
                _mdefAll = true;
            }
        }
    }

    /**
     * May return null if there is no custom entity resolver.
     */
    public EntityResolver getEntityResolver() {
        return _entityResolver;
    }

    /**
     * True if no unique particle attribution option is set
     */
    public boolean noUpa() {
        return _noUpa;
    }

    /**
     * True if no particle valid (restriction) option is set
     */
    public boolean noPvr() {
        return _noPvr;
    }

    /**
     * True if annotations should be skipped
     */
    public boolean noAnn() {
        return _noAnn;
    }

    /**
     * True if a partial SchemaTypeSystem should be produced
     */
    // EXPERIMENTAL
    public boolean allowPartial() {
        return _allowPartial;
    }

    /**
     * Get count of recovered errors. Not for public.
     */
    // EXPERIMENTAL
    public int getRecovered() {
        return _recoveredErrors;
    }

    /**
     * Intercepts XML names and translates them
     * through the compat map, if any.
     * <p>
     * Also looks for a default namespace for global definitions.
     */
    private QName compatName(QName name, String chameleonNamespace) {
        // first check for a chameleonNamespace namespace
        if (name.getNamespaceURI().length() == 0 && chameleonNamespace != null && chameleonNamespace.length() > 0) {
            name = new QName(chameleonNamespace, name.getLocalPart());
        }

        if (_compatMap == null) {
            return name;
        }

        QName subst = _compatMap.get(name);
        if (subst == null) {
            return name;
        }
        return subst;
    }

    /**
     * Initializer for the schema config object.
     */
    public void setBindingConfig(BindingConfig config)
        throws IllegalArgumentException {
        _config = config;
    }

    public BindingConfig getBindingConfig()
        throws IllegalArgumentException {
        return _config;
    }

    /**
     * Looks up package override for a namespace URI
     */
    public String getPackageOverride(String namespace) {
        if (_config == null) {
            return null;
        }
        return _config.lookupPackageForNamespace(namespace);
    }

    /**
     * Looks up package override for a namespace URI
     */
    public String getJavaPrefix(String namespace) {
        if (_config == null) {
            return null;
        }
        return _config.lookupPrefixForNamespace(namespace);
    }

    /**
     * Looks up package override for a namespace URI
     */
    public String getJavaSuffix(String namespace) {
        if (_config == null) {
            return null;
        }
        return _config.lookupSuffixForNamespace(namespace);
    }

    /**
     * Looks up configured java name for the given qname.
     */
    public String getJavaname(QName qname, int kind) {
        if (_config == null) {
            return null;
        }
        return _config.lookupJavanameForQName(qname, kind);
    }

    /* SPELLINGS ======================================================*/

    private static String crunchName(QName name) {
        // lowercase, and drop namespace.
        return name.getLocalPart().toLowerCase(Locale.ROOT);
    }

    void addSpelling(QName name, SchemaComponent comp) {
        _misspelledNames.put(crunchName(name), comp);
    }

    SchemaComponent findSpelling(QName name) {
        return _misspelledNames.get(crunchName(name));
    }

    /* NAMESPACES ======================================================*/

    void addNamespace(String targetNamespace) {
        _namespaces.add(targetNamespace);
    }

    String[] getNamespaces() {
        return _namespaces.toArray(new String[0]);
    }

    boolean linkerDefinesNamespace(String namespace) {
        return _importingLoader.isNamespaceDefined(namespace);
    }

    /* TYPES ==========================================================*/

    SchemaTypeImpl findGlobalType(QName name, String chameleonNamespace, String sourceNamespace) {
        name = compatName(name, chameleonNamespace);
        SchemaTypeImpl result = (SchemaTypeImpl) _globalTypes.get(name);
        boolean foundOnLoader = false;
        if (result == null) {
            result = (SchemaTypeImpl) _importingLoader.findType(name);
            foundOnLoader = result != null;
        }
        if (!foundOnLoader && sourceNamespace != null) {
            registerDependency(sourceNamespace, name.getNamespaceURI());
        }
        return result;
    }

    SchemaTypeImpl findRedefinedGlobalType(QName name, String chameleonNamespace, SchemaTypeImpl redefinedBy) {
        QName redefinedName = redefinedBy.getName();
        name = compatName(name, chameleonNamespace);
        if (name.equals(redefinedName)) {
            return _redefinedGlobalTypes.get(redefinedBy);
            // BUGBUG: should also link against _importingLoader.findRedefinedType
        }
        SchemaTypeImpl result = (SchemaTypeImpl) _globalTypes.get(name);
        if (result == null) {
            result = (SchemaTypeImpl) _importingLoader.findType(name);
        }
        // no dependency is needed here, necause it's intra-namespace
        return result;
    }

    void addGlobalType(SchemaTypeImpl type, SchemaTypeImpl redefined) {
        if (type != null) {
            QName name = type.getName();
            SchemaContainer container = getContainer(name.getNamespaceURI());
            assert container != null && container == type.getContainer();

            if (redefined != null) {
                if (_redefinedGlobalTypes.containsKey(redefined)) {
                    if (!ignoreMdef(name)) {
                        if (_mdefAll) {
                            warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"global type", QNameHelper.pretty(name), _redefinedGlobalTypes.get(redefined).getSourceName()},
                                type.getParseObject());
                        } else {
                            error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"global type", QNameHelper.pretty(name), _redefinedGlobalTypes.get(redefined).getSourceName()},
                                type.getParseObject());
                        }
                    }
                } else {
                    _redefinedGlobalTypes.put(redefined, type);
                    container.addRedefinedType(type.getRef());
                }
            } else {
                if (_globalTypes.containsKey(name)) {
                    if (!ignoreMdef(name)) {
                        if (_mdefAll) {
                            warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"global type", QNameHelper.pretty(name), _globalTypes.get(name).getSourceName()},
                                type.getParseObject());
                        } else {
                            error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"global type", QNameHelper.pretty(name), _globalTypes.get(name).getSourceName()},
                                type.getParseObject());
                        }
                    }
                } else {
                    _globalTypes.put(name, type);
                    container.addGlobalType(type.getRef());
                    addSpelling(name, type);
                }
            }
        }
    }

    private boolean ignoreMdef(QName name) {
        return _mdefNamespaces.contains(name.getNamespaceURI());
    }

    SchemaType[] globalTypes() {
        return _globalTypes.values().toArray(new SchemaType[0]);
    }

    SchemaType[] redefinedGlobalTypes() {
        return _redefinedGlobalTypes.values().toArray(new SchemaType[0]);
    }

    /* DOCUMENT TYPES =================================================*/

    SchemaTypeImpl findDocumentType(QName name, String chameleonNamespace, String sourceNamespace) {
        name = compatName(name, chameleonNamespace);
        SchemaTypeImpl result = (SchemaTypeImpl) _documentTypes.get(name);
        boolean foundOnLoader = false;
        if (result == null) {
            result = (SchemaTypeImpl) _importingLoader.findDocumentType(name);
            foundOnLoader = result != null;
        }
        if (!foundOnLoader && sourceNamespace != null) {
            registerDependency(sourceNamespace, name.getNamespaceURI());
        }
        return result;
    }

    void addDocumentType(SchemaTypeImpl type, QName name) {
        if (_documentTypes.containsKey(name)) {
            if (!ignoreMdef(name)) {
                if (_mdefAll) {
                    warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                        new Object[]{"global element", QNameHelper.pretty(name), _documentTypes.get(name).getSourceName()},
                        type.getParseObject());
                } else {
                    error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                        new Object[]{"global element", QNameHelper.pretty(name), _documentTypes.get(name).getSourceName()},
                        type.getParseObject());
                }
            }
        } else {
            _documentTypes.put(name, type);
            SchemaContainer container = getContainer(name.getNamespaceURI());
            assert container != null && container == type.getContainer();
            container.addDocumentType(type.getRef());
        }
    }

    SchemaType[] documentTypes() {
        return _documentTypes.values().toArray(new SchemaType[0]);
    }

    /* ATTRIBUTE TYPES =================================================*/

    SchemaTypeImpl findAttributeType(QName name, String chameleonNamespace, String sourceNamespace) {
        name = compatName(name, chameleonNamespace);
        SchemaTypeImpl result = (SchemaTypeImpl) _attributeTypes.get(name);
        boolean foundOnLoader = false;
        if (result == null) {
            result = (SchemaTypeImpl) _importingLoader.findAttributeType(name);
            foundOnLoader = result != null;
        }
        if (!foundOnLoader && sourceNamespace != null) {
            registerDependency(sourceNamespace, name.getNamespaceURI());
        }
        return result;
    }

    void addAttributeType(SchemaTypeImpl type, QName name) {
        if (_attributeTypes.containsKey(name)) {
            if (!ignoreMdef(name)) {
                if (_mdefAll) {
                    warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                        new Object[]{"global attribute", QNameHelper.pretty(name), _attributeTypes.get(name).getSourceName()},
                        type.getParseObject());
                } else {
                    error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                        new Object[]{"global attribute", QNameHelper.pretty(name), _attributeTypes.get(name).getSourceName()},
                        type.getParseObject());
                }
            }
        } else {
            _attributeTypes.put(name, type);
            SchemaContainer container = getContainer(name.getNamespaceURI());
            assert container != null && container == type.getContainer();
            container.addAttributeType(type.getRef());
        }
    }

    SchemaType[] attributeTypes() {
        return _attributeTypes.values().toArray(new SchemaType[0]);
    }

    /* ATTRIBUTES =====================================================*/

    SchemaGlobalAttributeImpl findGlobalAttribute(QName name, String chameleonNamespace, String sourceNamespace) {
        name = compatName(name, chameleonNamespace);
        SchemaGlobalAttributeImpl result = (SchemaGlobalAttributeImpl) _globalAttributes.get(name);
        boolean foundOnLoader = false;
        if (result == null) {
            result = (SchemaGlobalAttributeImpl) _importingLoader.findAttribute(name);
            foundOnLoader = result != null;
        }
        if (!foundOnLoader && sourceNamespace != null) {
            registerDependency(sourceNamespace, name.getNamespaceURI());
        }
        return result;
    }

    void addGlobalAttribute(SchemaGlobalAttributeImpl attribute) {
        if (attribute != null) {
            QName name = attribute.getName();
            _globalAttributes.put(name, attribute);
            addSpelling(name, attribute);
            SchemaContainer container = getContainer(name.getNamespaceURI());
            assert container != null && container == attribute.getContainer();
            container.addGlobalAttribute(attribute.getRef());
        }
    }

    SchemaGlobalAttribute[] globalAttributes() {
        return _globalAttributes.values().toArray(new SchemaGlobalAttribute[0]);
    }

    /* ELEMENTS =======================================================*/

    SchemaGlobalElementImpl findGlobalElement(QName name, String chameleonNamespace, String sourceNamespace) {
        name = compatName(name, chameleonNamespace);
        SchemaGlobalElementImpl result = (SchemaGlobalElementImpl) _globalElements.get(name);
        boolean foundOnLoader = false;
        if (result == null) {
            result = (SchemaGlobalElementImpl) _importingLoader.findElement(name);
            foundOnLoader = result != null;
        }
        if (!foundOnLoader && sourceNamespace != null) {
            registerDependency(sourceNamespace, name.getNamespaceURI());
        }
        return result;
    }

    void addGlobalElement(SchemaGlobalElementImpl element) {
        if (element != null) {
            QName name = element.getName();
            _globalElements.put(name, element);
            SchemaContainer container = getContainer(name.getNamespaceURI());
            assert container != null && container == element.getContainer();
            container.addGlobalElement(element.getRef());
            addSpelling(name, element);
        }
    }

    SchemaGlobalElement[] globalElements() {
        return _globalElements.values().toArray(new SchemaGlobalElement[0]);
    }

    /* ATTRIBUTE GROUPS ===============================================*/

    SchemaAttributeGroupImpl findAttributeGroup(QName name, String chameleonNamespace, String sourceNamespace) {
        name = compatName(name, chameleonNamespace);
        SchemaAttributeGroupImpl result = (SchemaAttributeGroupImpl) _attributeGroups.get(name);
        boolean foundOnLoader = false;
        if (result == null) {
            result = (SchemaAttributeGroupImpl) _importingLoader.findAttributeGroup(name);
            foundOnLoader = result != null;
        }
        if (!foundOnLoader && sourceNamespace != null) {
            registerDependency(sourceNamespace, name.getNamespaceURI());
        }
        return result;
    }

    SchemaAttributeGroupImpl findRedefinedAttributeGroup(QName name, String chameleonNamespace, SchemaAttributeGroupImpl redefinedBy) {
        QName redefinitionFor = redefinedBy.getName();
        name = compatName(name, chameleonNamespace);
        if (name.equals(redefinitionFor)) {
            return _redefinedAttributeGroups.get(redefinedBy);
            // BUGBUG: should also link against _importingLoader.findRedefinedAttributeGroup
        }
        SchemaAttributeGroupImpl result = (SchemaAttributeGroupImpl) _attributeGroups.get(name);
        if (result == null) {
            result = (SchemaAttributeGroupImpl) _importingLoader.findAttributeGroup(name);
        }
        return result;
    }

    void addAttributeGroup(SchemaAttributeGroupImpl attributeGroup, SchemaAttributeGroupImpl redefined) {
        if (attributeGroup != null) {
            QName name = attributeGroup.getName();
            SchemaContainer container = getContainer(name.getNamespaceURI());
            assert container != null && container == attributeGroup.getContainer();
            if (redefined != null) {
                if (_redefinedAttributeGroups.containsKey(redefined)) {
                    if (!ignoreMdef(name)) {
                        if (_mdefAll) {
                            warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"attribute group", QNameHelper.pretty(name), _redefinedAttributeGroups.get(redefined).getSourceName()},
                                attributeGroup.getParseObject());
                        } else {
                            error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"attribute group", QNameHelper.pretty(name), _redefinedAttributeGroups.get(redefined).getSourceName()},
                                attributeGroup.getParseObject());
                        }
                    }
                } else {
                    _redefinedAttributeGroups.put(redefined, attributeGroup);
                    container.addRedefinedAttributeGroup(attributeGroup.getRef());
                }
            } else {
                if (_attributeGroups.containsKey(name)) {
                    if (!ignoreMdef(name)) {
                        if (_mdefAll) {
                            warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"attribute group", QNameHelper.pretty(name), _attributeGroups.get(name).getSourceName()},
                                attributeGroup.getParseObject());
                        } else {
                            error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"attribute group", QNameHelper.pretty(name), _attributeGroups.get(name).getSourceName()},
                                attributeGroup.getParseObject());
                        }
                    }
                } else {
                    _attributeGroups.put(attributeGroup.getName(), attributeGroup);
                    addSpelling(attributeGroup.getName(), attributeGroup);
                    container.addAttributeGroup(attributeGroup.getRef());
                }
            }
        }
    }

    SchemaAttributeGroup[] attributeGroups() {
        return _attributeGroups.values().toArray(new SchemaAttributeGroup[0]);
    }

    SchemaAttributeGroup[] redefinedAttributeGroups() {
        return _redefinedAttributeGroups.values().toArray(new SchemaAttributeGroup[0]);
    }

    /* MODEL GROUPS ===================================================*/

    SchemaModelGroupImpl findModelGroup(QName name, String chameleonNamespace, String sourceNamespace) {
        name = compatName(name, chameleonNamespace);
        SchemaModelGroupImpl result = (SchemaModelGroupImpl) _modelGroups.get(name);
        boolean foundOnLoader = false;
        if (result == null) {
            result = (SchemaModelGroupImpl) _importingLoader.findModelGroup(name);
            foundOnLoader = result != null;
        }
        if (!foundOnLoader && sourceNamespace != null) {
            registerDependency(sourceNamespace, name.getNamespaceURI());
        }
        return result;
    }

    SchemaModelGroupImpl findRedefinedModelGroup(QName name, String chameleonNamespace, SchemaModelGroupImpl redefinedBy) {
        QName redefinitionFor = redefinedBy.getName();
        name = compatName(name, chameleonNamespace);
        if (name.equals(redefinitionFor)) {
            return _redefinedModelGroups.get(redefinedBy);
            // BUGBUG: should also link against _importingLoader.findRedefinedModelGroup
        }
        SchemaModelGroupImpl result = (SchemaModelGroupImpl) _modelGroups.get(name);
        if (result == null) {
            result = (SchemaModelGroupImpl) _importingLoader.findModelGroup(name);
        }
        return result;
    }

    void addModelGroup(SchemaModelGroupImpl modelGroup, SchemaModelGroupImpl redefined) {
        if (modelGroup != null) {
            QName name = modelGroup.getName();
            SchemaContainer container = getContainer(name.getNamespaceURI());
            assert container != null && container == modelGroup.getContainer();
            if (redefined != null) {
                if (_redefinedModelGroups.containsKey(redefined)) {
                    if (!ignoreMdef(name)) {
                        if (_mdefAll) {
                            warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"model group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedModelGroups.get(redefined)).getSourceName()},
                                modelGroup.getParseObject());
                        } else {
                            error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"model group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedModelGroups.get(redefined)).getSourceName()},
                                modelGroup.getParseObject());
                        }
                    }
                } else {
                    _redefinedModelGroups.put(redefined, modelGroup);
                    container.addRedefinedModelGroup(modelGroup.getRef());
                }
            } else {
                if (_modelGroups.containsKey(name)) {
                    if (!ignoreMdef(name)) {
                        if (_mdefAll) {
                            warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"model group", QNameHelper.pretty(name), _modelGroups.get(name).getSourceName()},
                                modelGroup.getParseObject());
                        } else {
                            error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                                new Object[]{"model group", QNameHelper.pretty(name), _modelGroups.get(name).getSourceName()},
                                modelGroup.getParseObject());
                        }
                    }
                } else {
                    _modelGroups.put(modelGroup.getName(), modelGroup);
                    addSpelling(modelGroup.getName(), modelGroup);
                    container.addModelGroup(modelGroup.getRef());
                }
            }
        }
    }

    SchemaModelGroup[] modelGroups() {
        return _modelGroups.values().toArray(new SchemaModelGroup[0]);
    }

    SchemaModelGroup[] redefinedModelGroups() {
        return _redefinedModelGroups.values().toArray(new SchemaModelGroup[0]);
    }

    /* IDENTITY CONSTRAINTS ===========================================*/

    SchemaIdentityConstraintImpl findIdConstraint(QName name, String chameleonNamespace, String sourceNamespace) {
        name = compatName(name, chameleonNamespace);
        if (sourceNamespace != null) {
            registerDependency(sourceNamespace, name.getNamespaceURI());
        }
        return (SchemaIdentityConstraintImpl) _idConstraints.get(name);
    }

    void addIdConstraint(SchemaIdentityConstraintImpl idc) {
        if (idc != null) {
            QName name = idc.getName();
            SchemaContainer container = getContainer(name.getNamespaceURI());
            assert container != null && container == idc.getContainer();
            if (_idConstraints.containsKey(name)) {
                if (!ignoreMdef(name)) {
                    warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
                        new Object[]{"identity constraint", QNameHelper.pretty(name), _idConstraints.get(name).getSourceName()},
                        idc.getParseObject());
                }
            } else {
                _idConstraints.put(name, idc);
                addSpelling(idc.getName(), idc);
                container.addIdentityConstraint(idc.getRef());
            }
        }
    }

    SchemaIdentityConstraintImpl[] idConstraints() {
        return _idConstraints.values().toArray(new SchemaIdentityConstraintImpl[0]);
    }

    /* ANNOTATIONS ===========================================*/

    void addAnnotation(SchemaAnnotationImpl ann, String targetNamespace) {
        if (ann != null) {
            SchemaContainer container = getContainer(targetNamespace);
            assert container != null && container == ann.getContainer();
            _annotations.add(ann);
            container.addAnnotation(ann);
        }
    }

    List<SchemaAnnotation> annotations() {
        return _annotations;
    }

    /* RECURSION AVOIDANCE ============================================*/
    boolean isProcessing(SchemaComponent obj) {
        return _processingGroups.contains(obj);
    }

    void startProcessing(SchemaComponent obj) {
        assert (!_processingGroups.contains(obj));
        _processingGroups.add(obj);
    }

    void finishProcessing(SchemaComponent obj) {
        assert (_processingGroups.contains(obj));
        _processingGroups.remove(obj);
    }

    SchemaComponent[] getCurrentProcessing() {
        return _processingGroups.toArray(new SchemaComponent[0]);
    }

    /* JAVAIZATION ====================================================*/

    Map<String, SchemaType> typesByClassname() {
        return Collections.unmodifiableMap(_typesByClassname);
    }

    void addClassname(String classname, SchemaType type) {
        _typesByClassname.put(classname, type);
    }

    /**
     * Stack management if (heaven help us) we ever need to do
     * nested compilation of schema type system.
     */
    private static final class StscStack {
        StscState current;
        List<StscState> stack = new ArrayList<>();

        final StscState push() {
            stack.add(current);
            current = new StscState();
            return current;
        }

        final void pop() {
            current = stack.get(stack.size() - 1);
            stack.remove(stack.size() - 1);
        }
    }

    public static void clearThreadLocals() {
        tl_stscStack.remove();
    }

    public static StscState start() {
        StscStack stscStack = tl_stscStack.get();

        if (stscStack == null) {
            stscStack = new StscStack();
            tl_stscStack.set(stscStack);
        }
        return stscStack.push();
    }

    public static StscState get() {
        return tl_stscStack.get().current;
    }

    public static void end() {
        StscStack stscStack = tl_stscStack.get();
        stscStack.pop();
        if (stscStack.stack.size() == 0) {
            // this is required to release all the references in this classloader
            tl_stscStack.remove();
        }
        // which will enable class unloading and avoid OOM in PermGen
    }

    static XmlValueRef build_wsstring(int wsr) {
        switch (wsr) {
            case SchemaType.WS_PRESERVE:
                return XMLSTR_PRESERVE;
            case SchemaType.WS_REPLACE:
                return XMLSTR_REPLACE;
            case SchemaType.WS_COLLAPSE:
                return XMLSTR_COLLAPSE;
        }
        return null;
    }

    static XmlValueRef buildString(String str) {
        if (str == null) {
            return null;
        }

        try {
            XmlStringImpl i = new XmlStringImpl();
            i.setStringValue(str);
            i.setImmutable();
            return new XmlValueRef(i);
        } catch (XmlValueOutOfRangeException e) {
            return null;
        }
    }

    public void notFoundError(QName itemName, int code, XmlObject loc, boolean recovered) {
        String expected;
        String expectedName = QNameHelper.pretty(itemName);
        String found = null;
        String foundName = null;
        String sourceName = null;

        if (recovered) {
            _recoveredErrors++;
        }

        switch (code) {
            case SchemaType.TYPE:
                expected = "type";
                break;
            case SchemaType.ELEMENT:
                expected = "element";
                break;
            case SchemaType.ATTRIBUTE:
                expected = "attribute";
                break;
            case SchemaType.MODEL_GROUP:
                expected = "model group";
                break;
            case SchemaType.ATTRIBUTE_GROUP:
                expected = "attribute group";
                break;
            case SchemaType.IDENTITY_CONSTRAINT:
                expected = "identity constraint";
                break;
            default:
                assert (false);
                expected = "definition";
                break;
        }

        SchemaComponent foundComponent = findSpelling(itemName);
        QName name;
        if (foundComponent != null) {
            name = foundComponent.getName();
            if (name != null) {
                switch (foundComponent.getComponentType()) {
                    case SchemaComponent.TYPE:
                        found = "type";
                        sourceName = foundComponent.getSourceName();
                        break;
                    case SchemaComponent.ELEMENT:
                        found = "element";
                        sourceName = foundComponent.getSourceName();
                        break;
                    case SchemaComponent.ATTRIBUTE:
                        found = "attribute";
                        sourceName = foundComponent.getSourceName();
                        break;
                    case SchemaComponent.ATTRIBUTE_GROUP:
                        found = "attribute group";
                        break;
                    case SchemaComponent.MODEL_GROUP:
                        found = "model group";
                        break;
                }

                if (sourceName != null) {
                    sourceName = sourceName.substring(sourceName.lastIndexOf('/') + 1);
                }

                if (!name.equals(itemName)) {
                    foundName = QNameHelper.pretty(name);
                }
            }
        }

        if (found == null) {
            // error with no help
            error(XmlErrorCodes.SCHEMA_QNAME_RESOLVE,
                new Object[]{expected, expectedName}, loc);
        } else {
            // error with help
            error(XmlErrorCodes.SCHEMA_QNAME_RESOLVE$HELP,
                new Object[]{
                    expected,
                    expectedName,
                    found,
                    (foundName == null ? 0 : 1),
                    foundName,
                    (sourceName == null ? 0 : 1),
                    sourceName
                },
                loc);
        }
    }

    /**
     * Produces the "sourceName" (to be used within the schema project
     * source file copies) from the URI of the original source.
     * <p>
     * Returns null if none.
     */
    public String sourceNameForUri(String uri) {
        return _sourceForUri.get(uri);
    }

    /**
     * Returns the whole sourceCopyMap, mapping URI's that have
     * been read to "sourceName" local names that have been used
     * to tag the types.
     */
    public Map<String, String> sourceCopyMap() {
        return Collections.unmodifiableMap(_sourceForUri);
    }

    /**
     * The base URI to use for nice filenames when saving sources.
     */
    public void setBaseUri(URI uri) {
        _baseURI = uri;
    }

    public String relativize(String uri) {
        return relativize(uri, false);
    }

    public String computeSavedFilename(String uri) {
        return relativize(uri, true);
    }

    private String relativize(String uri, boolean forSavedFilename) {
        if (uri == null) {
            return null;
        }

        // deal with things that do not look like absolute uris
        if (uri.startsWith("/")) {
            uri = PROJECT_URL_PREFIX + uri.replace('\\', '/');
        } else {
            // looks like a URL?
            int colon = uri.indexOf(':');
            if (colon <= 1 || !uri.substring(0, colon).matches("^\\w+$")) {
                uri = PROJECT_URL_PREFIX + "/" + uri.replace('\\', '/');
            }
        }

        // now relativize against that...
        if (_baseURI != null) {
            try {
                URI relative = _baseURI.relativize(new URI(uri));
                if (!relative.isAbsolute()) {
                    return relative.toString();
                } else {
                    uri = relative.toString();
                }
            } catch (URISyntaxException ignored) {
            }
        }

        if (!forSavedFilename) {
            return uri;
        }

        int lastslash = uri.lastIndexOf('/');
        String dir = QNameHelper.hexsafe(lastslash == -1 ? "" : uri.substring(0, lastslash));

        int question = uri.indexOf('?', lastslash + 1);
        if (question == -1) {
            return dir + "/" + uri.substring(lastslash + 1);
        }

        String query = QNameHelper.hexsafe(uri.substring(question));

        // if encoded query part is longer than 64 characters, just drop it
        if (query.startsWith(QNameHelper.URI_SHA1_PREFIX)) {
            return dir + "/" + uri.substring(lastslash + 1, question);
        } else {
            return dir + "/" + uri.substring(lastslash + 1, question) + query;
        }
    }

    /**
     * Notes another URI that has been consumed during compilation
     * (this is the URI that is in the document .NAME property)
     */
    public void addSourceUri(String uri, String nameToUse) {
        if (uri == null) {
            return;
        }

        if (nameToUse == null) {
            nameToUse = computeSavedFilename(uri);
        }

        _sourceForUri.put(uri, nameToUse);
    }

    /**
     * Returns the error listener being filled in during this compilation
     */
    public Collection<XmlError> getErrorListener() {
        return _errorListener;
    }

    /**
     * Returns the schema type loader to use for processing s4s
     */
    public SchemaTypeLoader getS4SLoader() {
        return _s4sloader;
    }

    public File getSchemasDir() {
        return _schemasDir;
    }

    public void setSchemasDir(File _schemasDir) {
        this._schemasDir = _schemasDir;
    }
}


text:
<div class="text-center" id="vote-<?=$modelId?>-<?=$targetId?>" data-placement="top" data-container="body" data-toggle="popover">
    <span id="vote-up-<?=$modelId?>-<?=$targetId?>" class="glyphicon glyphicon-thumbs-up" onclick="vote(<?=$modelId?>, <?=$targetId?>, 'like'); return false;" style="cursor: pointer;"><?=$likes?>

    <span id="vote-down-<?=$modelId?>-<?=$targetId?>" class="glyphicon glyphicon-thumbs-down" onclick="vote(<?=$modelId?>, <?=$targetId?>, 'dislike'); return false;" style="cursor: pointer;"><?=$dislikes?>
    <div id="vote-response-<?=$modelId?>-<?=$targetId?>">
        <?php if ($showAggregateRating) { ?>
            <?=Yii::t('vote', 'Aggregate rating')?>: <?=$rating?>
        <?php } ?>

    <meta itemprop="interactionCount" content="UserLikes:<?=$likes?>"/>
    <meta itemprop="interactionCount" content="UserDislikes:<?=$dislikes?>"/>
    <meta itemprop="ratingValue" content="<?=$rating?>"/>
    <meta itemprop="ratingCount" content="<?=$likes+$dislikes?>"/>
    <meta itemprop="bestRating" content="10"/>
    <meta itemprop="worstRating" content="0"/>

redpajama_set_name: RedPajamaGithub


text:
using System.Web.Mvc;

namespace BrockAllen.MembershipReboot.Mvc.App_Start
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new MyErrorFilter());
        }
    }

    public class MyErrorFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;
            var vr = new ViewResult
            {
                ViewName = "Error"
            };
            vr.ViewData.Model = filterContext.Exception;
            filterContext.Result = vr;
        }
    }
}


text:
A dirty command line script for setting your user status in confluence.

# Developing

After cloning the repository run npm link in the project directory to make it available in the shell.


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

namespace Treehopper.PS
{
    [Cmdlet(VerbsCommon.Set, "Treehopper")]
    public class SetTreehopper : PSCmdlet
    {
        [Parameter(ParameterSetName = "Led")]
        public bool Led { get; set; }

        [Parameter(ParameterSetName = "Mode")]
        public string Mode { get; set; }

        [Parameter(ParameterSetName = "Value")]
        public bool Value { get; set; }

        [Parameter(ParameterSetName = "Mode")]
        [Parameter(ParameterSetName = "Value")]
        public int[] Pin { get; set; }

        [Parameter(Mandatory = true, ValueFromPipeline = true)]
        public TreehopperUsb[] Board { get; set; }
        protected override void ProcessRecord()
        {
            foreach(var board in Board)
            {

                board.ConnectAsync().Wait();
                switch(ParameterSetName)
                {
                    case "Led":
                        board.Led = Led;
                        break;

                    case "Value":
                        foreach (int pin in Pin)
                        {
                            board.Pins[pin].DigitalValue = Value;
                        }
                        break;

                    case "Mode":
                        foreach (int pin in Pin)
                        {
                            switch(Mode.ToLower())
                            {
                                case "analoginput":
                                case "analogin":
                                case "analog":
                                    board.Pins[pin].Mode = PinMode.AnalogInput;
                                    break;

                                case "digitalinput":
                                case "digitalin":
                                case "in":
                                    board.Pins[pin].Mode = PinMode.DigitalInput;
                                    break;

                                case "digitalout":
                                case "digitaloutput":
                                case "pushpulloutput":
                                case "digitalpushpull":
                                case "out":
                                    board.Pins[pin].Mode = PinMode.PushPullOutput;
                                    break;

                                case "opendrain":
                                case "digitalopendrain":
                                case "opendrainoutput":
                                    board.Pins[pin].Mode = PinMode.OpenDrainOutput;
                                    break;
                            }

                        }
                        break;
                }
            }
        }
    }
}


text:
// luma.gl, MIT license
import {TextureFormat} from '@luma.gl/api';

/** Ensure a texture format is WebGPU compatible */
export function getWebGPUTextureFormat(format: TextureFormat): GPUTextureFormat {
  if (format.includes('webgl')) {
    throw new Error('webgl-only format');
  }
  return format as GPUTextureFormat;
}


text:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using MS.Internal.PresentationCore;
#if PRESENTATION_CORE
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
#else
using SR=System.Windows.SR;
using SRID=System.Windows.SRID;
#endif

namespace System.Windows.Media
{
    /// <summary>
    ///     TileMode - Enum which descibes the drawing of the ends of a line.
    /// </summary>
    public enum TileMode
    {
        /// <summary>
        ///     None - Do not tile only the base tile is drawn, the remaining area is left as
        ///     transparent
        /// </summary>
        None = 0,

        /// <summary>
        ///     Tile - The basic tile mode  the base tile is drawn and the remaining area is filled
        ///     by repeating the base tile such that the right edge of one tile butts the left edge
        ///     of the next, and similarly for bottom and top
        /// </summary>
        Tile = 4,

        /// <summary>
        ///     FlipX - The same as tile, but alternate columns of tiles are flipped horizontally.
        ///     The base tile is drawn untransformed.
        /// </summary>
        FlipX = 1,

        /// <summary>
        ///     FlipY - The same as tile, but alternate rows of tiles are flipped vertically.  The
        ///     base tile is drawn untransformed.
        /// </summary>
        FlipY = 2,

        /// <summary>
        ///     FlipXY - The combination of FlipX and FlipY.  The base tile is drawn untransformed.
        /// </summary>
        FlipXY = 3,
    }
}


text:
namespace Cedar.EventStore
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using FluentAssertions;
    using Xunit;

    public abstract partial class EventStoreAcceptanceTests
    {
        [Theory]
        [MemberData("GetReadStreamTheories")]
        public async Task Can_read_streams_forwards_and_backwards(ReadStreamTheory theory)
        {
            using(var fixture = GetFixture())
            {
                using(var eventStore = await fixture.GetEventStore())
                {
                    await eventStore.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamEvents(1, 2, 3));
                    await eventStore.AppendToStream("stream-2", ExpectedVersion.NoStream, CreateNewStreamEvents(4, 5, 6));

                    var streamEventsPage =
                        await eventStore.ReadStream(theory.StreamId, theory.Start, theory.PageSize, theory.Direction);

                    var expectedStreamEventsPage = theory.ExpectedStreamEventsPage;
                    var expectedEvents = theory.ExpectedStreamEventsPage.Events;

                    streamEventsPage.FromStreamVersion.Should().Be(expectedStreamEventsPage.FromStreamVersion);
                    streamEventsPage.LastStreamVersion.Should().Be(expectedStreamEventsPage.LastStreamVersion);
                    streamEventsPage.NextStreamVersion.Should().Be(expectedStreamEventsPage.NextStreamVersion);
                    streamEventsPage.ReadDirection.Should().Be(expectedStreamEventsPage.ReadDirection);
                    streamEventsPage.IsEndOfStream.Should().Be(expectedStreamEventsPage.IsEndOfStream);
                    streamEventsPage.Status.Should().Be(expectedStreamEventsPage.Status);
                    streamEventsPage.StreamId.Should().Be(expectedStreamEventsPage.StreamId);
                    streamEventsPage.Events.Count.Should().Be(expectedStreamEventsPage.Events.Count);

                    streamEventsPage.Events.ShouldAllBeEquivalentTo(
                        expectedEvents,
                        options =>
                        {
                            options.Excluding(streamEvent => streamEvent.Checkpoint);
                            options.Excluding(streamEvent => streamEvent.Created);
                            return options;
                        });
                }
            }
        }

        public static IEnumerable<object[]> GetReadStreamTheories()
        {
            var theories = new[]
            {
                new ReadStreamTheory("stream-1", StreamPosition.Start, ReadDirection.Forward, 2,
                    new StreamEventsPage("stream-1", PageReadStatus.Success, 0, 2, 2, ReadDirection.Forward, false,
                          ExpectedStreamEvent("stream-1", 1, 0, SystemClock.GetUtcNow().UtcDateTime),
                          ExpectedStreamEvent("stream-1", 2, 1, SystemClock.GetUtcNow().UtcDateTime))),

                new ReadStreamTheory("not-exist", 1, ReadDirection.Forward, 2,
                    new StreamEventsPage("not-exist", PageReadStatus.StreamNotFound, 1, -1, -1, ReadDirection.Forward, true)),

                new ReadStreamTheory("stream-2", 1, ReadDirection.Forward, 2,
                    new StreamEventsPage("stream-2", PageReadStatus.Success, 1, 3, 2, ReadDirection.Forward, true,
                          ExpectedStreamEvent("stream-2", 5, 1, SystemClock.GetUtcNow().UtcDateTime),
                          ExpectedStreamEvent("stream-2", 6, 2, SystemClock.GetUtcNow().UtcDateTime))),

                new ReadStreamTheory("stream-1", StreamPosition.End, ReadDirection.Backward, 2,
                    new StreamEventsPage("stream-1", PageReadStatus.Success, -1, 0, 2, ReadDirection.Backward, false,
                          ExpectedStreamEvent("stream-1", 3, 2, SystemClock.GetUtcNow().UtcDateTime),
                          ExpectedStreamEvent("stream-1", 2, 1, SystemClock.GetUtcNow().UtcDateTime))),

                 new ReadStreamTheory("stream-1", StreamPosition.End, ReadDirection.Backward, 4,
                    new StreamEventsPage("stream-1", PageReadStatus.Success, -1, -1, 2, ReadDirection.Backward, true,
                          ExpectedStreamEvent("stream-1", 3, 2, SystemClock.GetUtcNow().UtcDateTime),
                          ExpectedStreamEvent("stream-1", 2, 1, SystemClock.GetUtcNow().UtcDateTime),
                          ExpectedStreamEvent("stream-1", 1, 0, SystemClock.GetUtcNow().UtcDateTime)))
            };

            return theories.Select(t => new object[] { t });
        }

        public class ReadStreamTheory
        {
            public readonly string StreamId;
            public readonly int Start;
            public readonly ReadDirection Direction;
            public readonly int PageSize;
            public readonly StreamEventsPage ExpectedStreamEventsPage;

            public ReadStreamTheory(
                string streamId,
                int start,
                ReadDirection direction,
                int pageSize,
                StreamEventsPage expectedStreamEventsPage)
            {
                StreamId = streamId;
                Start = start;
                Direction = direction;
                PageSize = pageSize;
                ExpectedStreamEventsPage = expectedStreamEventsPage;
            }
        }
    }
}


text:
package io.teknek.datalayer;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

import io.teknek.daemon.TeknekDaemon;
import io.teknek.daemon.WorkerStatus;
import io.teknek.driver.TestDriverFactory;
import io.teknek.plan.Bundle;
import io.teknek.plan.FeedDesc;
import io.teknek.plan.OperatorDesc;
import io.teknek.plan.Plan;
import io.teknek.zookeeper.EmbeddedZooKeeperServer;

public class TestWorkerDao extends EmbeddedZooKeeperServer {

  @Test
  public void persistAndReadBack() throws IOException, InterruptedException, WorkerDaoException {
    final TeknekDaemon td = createDaemonWiredToThisZk();
    String group = "io.teknek";
    String name = "abc";
    OperatorDesc d = TestDriverFactory.buildGroovyOperatorDesc();
    td.getWorkerDao().createZookeeperBase();
    td.getWorkerDao().saveOperatorDesc(td.getReestablishingKeeper().getZooKeeper(), d, group, name);
    OperatorDesc d1 = td.getWorkerDao().loadSavedOperatorDesc(td.getReestablishingKeeper().getZooKeeper(), group, name);
    Assert.assertEquals(d1.getTheClass(), d.getTheClass());
    Assert.assertEquals(d1.getSpec(), d.getSpec());
    Assert.assertEquals(d1.getScript(), d.getScript());
    td.stop();
  }

  @Test
  public void readBundleFromUrl() throws MalformedURLException, WorkerDaoException{
    File f = new File("src/test/resources/bundle_io.teknek_itests1.0.0.json");
    Bundle b = WorkerDao.getBundleFromUrl(f.toURL());
    Assert.assertEquals("itests", b.getBundleName() );
    Assert.assertEquals("groovy_identity", b.getOperatorList().get(0).getName());
  }

  @Test
  public void readBundleAndAdd() throws IOException, InterruptedException, WorkerDaoException{
    final TeknekDaemon td = createDaemonWiredToThisZk();
    File f = new File("src/test/resources/bundle_io.teknek_itests1.0.0.json");
    Bundle b = WorkerDao.getBundleFromUrl(f.toURL());
    td.getWorkerDao().saveBundle(td.getReestablishingKeeper().getZooKeeper(), b);
    OperatorDesc oDesc = td.getWorkerDao().loadSavedOperatorDesc(td.getReestablishingKeeper().getZooKeeper(), b.getPackageName(), "groovy_identity");
    Assert.assertEquals("groovy_identity", oDesc.getTheClass());
    FeedDesc fDesc = td.getWorkerDao().loadSavedFeedDesc(b.getPackageName(), "GTry");
    Assert.assertEquals("GTry", fDesc.getTheClass());
    td.stop();
  }

  @Ignore
  public void persistStatus() throws WorkerDaoException, IOException, InterruptedException {
    final TeknekDaemon td = createUnitiDaemonWiredToThisZk();
    WorkerStatus ws = new WorkerStatus("1","2","3");
    Plan p = new Plan().withName("persist");
    td.getWorkerDao().createZookeeperBase();
    td.getWorkerDao().createOrUpdatePlan(p);
    td.getWorkerDao().registerWorkerStatus(td.getReestablishingKeeper().getZooKeeper(), p , ws);
    List<WorkerStatus> statuses = td.getWorkerDao()
            .findAllWorkerStatusForPlan(p, td.getWorkerDao().findWorkersWorkingOnPlan(p));
    Assert.assertEquals(1, statuses.size());
    Assert.assertEquals(ws.getTeknekDaemonId(), statuses.get(0).getTeknekDaemonId());
    Assert.assertEquals(ws.getFeedPartitionId(), statuses.get(0).getFeedPartitionId());
    Assert.assertEquals(ws.getWorkerUuid(), statuses.get(0).getWorkerUuid());
    td.getWorkerDao().deletePlan(p);
    td.stop();
  }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="UTF-8">
  <title>My awesome Game</title>
  <link rel="stylesheet" href="assets/base.css">
  <script src="cordova.js"></script>
</head>
<body>
  <script src="build/bundle.js"></script>
</body>
</html>


text:
@implementation XPGroupClause

+ (instancetype)groupClauseWithVariableName:(NSString *)varName expression:(XPExpression *)expr {
    XPGroupClause *gc = [[[XPGroupClause alloc] init] autorelease];
    gc.variableName = varName;
    gc.expression = expr;
    return gc;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"group by $%@ := %@", _variableName, _expression];
}

- (void)dealloc {
    self.variableName = nil;
    self.expression = nil;
    [super dealloc];
}

@end


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

<title>DoubleAdder (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="java.util.concurrent.atomic.DoubleAdder class">
<meta name="keywords" content="add()">
<meta name="keywords" content="sum()">
<meta name="keywords" content="reset()">
<meta name="keywords" content="sumThenReset()">
<meta name="keywords" content="toString()">
<meta name="keywords" content="doubleValue()">
<meta name="keywords" content="longValue()">
<meta name="keywords" content="intValue()">
<meta name="keywords" content="floatValue()">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

compact1, compact2, compact3

java.util.concurrent.atomic

Class DoubleAdder

java.lang.Object

java.lang.Number

java.util.concurrent.atomic.DoubleAdder

All Implemented Interfaces:

Serializable

public class DoubleAdder
extends Number
implements Serializable

One or more variables that together maintain an initially zero
 double sum.  When updates (method add(double)) are
 contended across threads, the set of variables may grow dynamically
 to reduce contention.  Method sum() (or, equivalently doubleValue()) returns the current total combined across the
 variables maintaining the sum. The order of accumulation within or
 across threads is not guaranteed. Thus, this class may not be
 applicable if numerical stability is required, especially when
 combining values of substantially different orders of magnitude.

This class is usually preferable to alternatives when multiple
 threads update a common value that is used for purposes such as
 summary statistics that are frequently updated but less frequently
 read.

This class extends Number, but does not define
 methods such as equals, hashCode and compareTo because instances are expected to be mutated, and so are
 not useful as collection keys.

Since:

1.8

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

DoubleAdder()

Creates a new adder with initial sum of zero.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
add(double x)

Adds the given value.

double
doubleValue()

Equivalent to sum().

float
floatValue()

Returns the sum() as a float
 after a narrowing primitive conversion.

int
intValue()

Returns the sum() as an int after a
 narrowing primitive conversion.

long
longValue()

Returns the sum() as a long after a
 narrowing primitive conversion.

void
reset()

Resets variables maintaining the sum to zero.

double
sum()

Returns the current sum.

double
sumThenReset()

Equivalent in effect to sum() followed by reset().

String
toString()

Returns the String representation of the sum().

Methods inherited from class java.lang.Number

byteValue, shortValue

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

DoubleAdder

public DoubleAdder()

Creates a new adder with initial sum of zero.

Method Detail

add

public void add(double x)

Adds the given value.

Parameters:

x - the value to add

sum

public double sum()

Returns the current sum.  The returned value is NOT an
 atomic snapshot; invocation in the absence of concurrent
 updates returns an accurate result, but concurrent updates that
 occur while the sum is being calculated might not be
 incorporated.  Also, because floating-point arithmetic is not
 strictly associative, the returned result need not be identical
 to the value that would be obtained in a sequential series of
 updates to a single variable.

Returns:

the sum

reset

public void reset()

Resets variables maintaining the sum to zero.  This method may
 be a useful alternative to creating a new adder, but is only
 effective if there are no concurrent updates.  Because this
 method is intrinsically racy, it should only be used when it is
 known that no threads are concurrently updating.

sumThenReset

public double sumThenReset()

Equivalent in effect to sum() followed by reset(). This method may apply for example during quiescent
 points between multithreaded computations.  If there are
 updates concurrent with this method, the returned value is
 not guaranteed to be the final value occurring before
 the reset.

Returns:

the sum

toString

public String toString()

Returns the String representation of the sum().

Overrides:

toString in class Object

Returns:

the String representation of the sum()

doubleValue

public double doubleValue()

Equivalent to sum().

Specified by:

doubleValue in class Number

Returns:

the sum

longValue

public long longValue()

Returns the sum() as a long after a
 narrowing primitive conversion.

Specified by:

longValue in class Number

Returns:

the numeric value represented by this object after conversion
          to type long.

intValue

public int intValue()

Returns the sum() as an int after a
 narrowing primitive conversion.

Specified by:

intValue in class Number

Returns:

the numeric value represented by this object after conversion
          to type int.

floatValue

public float floatValue()

Returns the sum() as a float
 after a narrowing primitive conversion.

Specified by:

floatValue in class Number

Returns:

the numeric value represented by this object after conversion
          to type float.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using Telligent.Evolution.Extensibility.Api;

namespace ContentMetadata.Api
{
	public interface IContentMetadataApi : IApi
	{
		IReadOnlyList<ContentMetadata> List(Guid contentId);

		IReadOnlyList<ContentMetadata> List(string key, string value);

		ContentMetadata Get(Guid contentId, string key);

		ContentMetadata Get(Guid contentTypeId, string key, string value);

		/// <summary>
		/// Deletes all metadata associated with the IContent.
		/// </summary>
		/// <param name="contentId">The contentId to delete metadata for.</param>
		void Delete(Guid contentId);

		/// <summary>
		/// Deletes an item of metadata associated with an IContent with the relevant key.
		/// </summary>
		/// <param name="contentId">The IContent Id the metadata belongs to.</param>
		/// <param name="key">The key of the metadata to delete.</param>
		void Delete(Guid contentId, string key);

		ContentMetadata Set(Guid contentId, Guid contentTypeId, string key, string value);
	}
}


text:
const webpack = require('webpack');
const path = require('path');
const buildPath = path.resolve(__dirname, 'src/www');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const config = {
  //Entry point to the project
  entry: [
    'webpack/hot/dev-server',
    'webpack/hot/only-dev-server',
    path.join(__dirname, '/src/app/app.jsx')
  ],
  //Webpack config options on how to obtain modules
  resolve: {
    //When requiring, you don't need to add these extensions
    extensions: ['', '.js', '.jsx', '.md', '.txt'],
    //Modules will be searched for in these directories
    modulesDirectories: [
      // We need /docs/node_modules to be resolved before /node_modules
      path.resolve(__dirname, 'node_modules'),
      'node_modules',
      path.resolve(__dirname, '../src')
    ]
  },

  //Configuration for dev server
  //devServer: {
  //  contentBase: 'src/www',
  //  devtool: 'eval',
  //  hot: true,
  // inline: true,
  //  port: 3000,
  //},

  devServer: {
    proxy:       [{
      // proxy all requests not containing ".hot-update.js"
      // regex is still crappy because JS doesn't have negative lookbehind
      path:   /\/api(.*)/,
      // koa running on 3001 with koa-send and isomorphic react
      target:  'http://example:8080'
    }],
    contentBase: 'src/www',
    hot: true,
    port: 3000,
    host: '0.0.0.0',
    historyApiFallback: true
  },

  devtool: 'eval',
  //Output file config
  output: {
    path: buildPath,    //Path of output file
    filename: 'app.js'  //Name of output file
  },
  plugins: [
    //Used to include index.html in build folder
    new HtmlWebpackPlugin({
      inject: false,
      template: path.join(__dirname, '/src/www/index.html')
    }),
    //Allows for sync with browser while developing (like BorwserSync)
    new webpack.HotModuleReplacementPlugin(),
    //Allows error warninggs but does not stop compiling. Will remove when eslint is added
    new webpack.NoErrorsPlugin(),
    new ExtractTextPlugin(path.resolve(__dirname,'/style.css') , {
      allChunks: true
    })
  ],
  externals: {
    fs: 'js' // To remove once https://github.com/benjamn/recast/pull/238 is released
  },
  module: {
    //eslint loader
    preLoaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'eslint-loader',
        include: [path.resolve(__dirname, '../src')],
        exclude: [
          path.resolve(__dirname, '../src/svg-icons'),
          path.resolve(__dirname, '../src/utils/modernizr.custom.js')
        ]
      }
    ],
    //Allow loading of non-es
    loaders: [
      {
        test: /\.jsx$/,
        loaders: [
          'react-hot',
          'babel-loader'
        ],
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.txt$/,
        loader: 'raw-loader',
        include: path.resolve(__dirname, 'src/app/components/raw-code')
      },
      {
        test: /\.md$/,
        loader: 'raw-loader',
        include: path.resolve(__dirname, 'src/app/components')
      },
      {
        test: /\.css$/,
        loaders: [
          "style-loader",
          "css-loader",
          "autoprefixer-loader?browsers=last 2 versions"
        ]
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader?browsers=last 2 versions!sass-loader?indentedSyntax=sass&includePaths[]=" + path.resolve(__dirname, "/src/www/assets/stylesheets"))
      }
    ]
  },
  eslint: {
    configFile: '../.eslintrc'
  }
};

module.exports = config;


text:
'use strict';

var appFrame   = require('../../bellows/pages/appFrame.js');
var body     = require('../../bellows/pages/pageBody.js');
afterEach(function() {
  //browser.ignoreSyncronization = true;
  expect(appFrame.errorMessage.isPresent()).toBe(false);
  expect(body.phpError.isPresent()).toBe(false);
  //browser.ignoreSyncronization = false;
});


text:
package org.lwjgl.opengles;

/**
 * Native bindings to the EXT_texture_filter_anisotropic extension.
 *
 *
Texture mapping using OpenGL's existing mipmap texture filtering modes assumes that the projection of the pixel filter footprint into texture space is
 * a square (ie, isotropic). In practice however, the footprint may be long and narrow (ie, anisotropic). Consequently, mipmap filtering severely blurs
 * images on surfaces angled obliquely away from the viewer.

 *
 *
Several approaches exist for improving texture sampling by accounting for the anisotropic nature of the pixel filter footprint into texture space. This
 * extension provides a general mechanism for supporting anisotropic texturing filtering schemes without specifying a particular formulation of
 * anisotropic filtering.

 *
 *
The extension permits the OpenGL application to specify on a per-texture object basis the maximum degree of anisotropy to account for in texture
 * filtering.

 *
 *
Increasing a texture object's maximum degree of anisotropy may improve texture filtering but may also significantly reduce the implementation's texture
 * filtering rate. Implementations are free to clamp the specified degree of anisotropy to the implementation's maximum supported degree of anisotropy.

 *
 *
A texture's maximum degree of anisotropy is specified independent from the texture's minification and magnification filter (as opposed to being
 * supported as an entirely new filtering mode). Implementations are free to use the specified minification and magnification filter to select a
 * particular anisotropic texture filtering scheme. For example, a NEAREST filter with a maximum degree of anisotropy of two could be treated as a 2-tap
 * filter that accounts for the direction of anisotropy. Implementations are also permitted to ignore the minification or magnification filter and
 * implement the highest quality of anisotropic filtering possible.

 *
 *
Applications seeking the highest quality anisotropic filtering available are advised to request a LINEAR_MIPMAP_LINEAR minification filter, a LINEAR
 * magnification filter, and a large maximum degree of anisotropy.

 */
public final class EXTTextureFilterAnisotropic {

    /** Accepted by the {@code pname} parameters of GetTexParameterfv, GetTexParameteriv, TexParameterf, TexParameterfv, TexParameteri, and TexParameteriv. */
    public static final int GL_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE;

    /** Accepted by the {@code pname} parameters of GetBooleanv, GetDoublev, GetFloatv, and GetIntegerv. */
    public static final int GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF;

    private EXTTextureFilterAnisotropic() {}

}


text:
module Taggings::Validation
  extend ActiveSupport::Concern

  included do
    validates :tag, presence: :true
    validates :tag_id, uniqueness: { scope: [:taggable_id, :taggable_type] }
  end
end


text:
  Le Porge est
      une commune géographiquement positionnée dans le département de Gironde en Aquitaine. On dénombrait 2 199 habitants en 2008.

À Le Porge, la valorisation moyenne à l'achat d'un appartement se situe à 2 479 € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 2 575 € du m². À la location le prix moyen se situe à 10,96 € du m² par mois.

Le nombre de logements, à Le Porge, était réparti en 2011 en 36 appartements et 2 135 maisons soit
 un marché plutôt équilibré.

À Le Porge le salaire moyen mensuel par individu est situé à approximativement 1 977 €  net. C'est inférieur à la moyenne du pays.

La ville offre de multiples  équipements sportifs, elle propose entre autres deux terrains de tennis, un terrain de golf, un terrain de sport et une boucle de randonnée.

À proximité de Le Porge sont positionnées géographiquement les villes de
Lège-Cap-Ferret située à 9 km, 7 193 habitants,
Saumos à 9 km, 470 habitants,
Le Temple à 8 km, 510 habitants,
Lacanau localisée à 11 km, 4 105 habitants,
Villeneuve à 18 km, 373 habitants,
Lanton localisée à 19 km, 5 866 habitants,
 entre autres. De plus, Le Porge est située à seulement 28 km de La Teste-de-Buch.


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

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
    <uses-permission android:name="com.rockets12.lunchcast.permission.C2D_MESSAGE"/>

    <permission
        android:name="com.rockets12.lunchcast.permission.C2D_MESSAGE"
        android:protectionLevel="signature"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/lc_icon"
        android:label="@string/app_name"
        android:supportsRtl="false"
        android:theme="@style/AppTheme">
        <activity
            android:name=".LunchCastActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

</manifest>


text:
package org.nnsoft.guice.junice;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.junit.runner.RunWith;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.nnsoft.guice.junice.annotation.GuiceModules;
import org.nnsoft.guice.junice.annotation.GuiceProvidedModules;
import org.nnsoft.guice.junice.annotation.Mock;
import org.nnsoft.guice.junice.annotation.MockFramework;
import org.nnsoft.guice.junice.annotation.MockType;
import org.nnsoft.guice.junice.handler.GuiceInjectableClassHandler;
import org.nnsoft.guice.junice.handler.GuiceModuleHandler;
import org.nnsoft.guice.junice.handler.GuiceProvidedModuleHandler;
import org.nnsoft.guice.junice.handler.MockFrameworkHandler;
import org.nnsoft.guice.junice.handler.MockHandler;
import org.nnsoft.guice.junice.mock.MockEngine;
import org.nnsoft.guice.junice.mock.guice.MockTypeListener;
import org.nnsoft.guice.junice.reflection.ClassVisitor;
import org.nnsoft.guice.junice.reflection.HandleException;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.matcher.Matchers;
import com.google.inject.util.Modules;

/**
 *

 * It's a {@link BlockJUnit4ClassRunner} runner.
 *

 *

 * This class creates a Google Guice {@link Injector} configured by {@link GuiceModules} annotation (only fr modules
 * with default constructor) and {@link GuiceProvidedModules} annotation and {@link Mock}.
 *

 *

 * Example #1:

 *
 *

 *
 * @RunWith(JUniceRunner.class)
 * @GuiceModules(modules=SimpleModule.class)
 * public class AcmeTestCase {
 *
 *     @GuiceProvidedModules
 *     static public Module getProperties() {
 *         ...
 *         return Modules.combine(new ComplexModule(loadProperies()), ...  );
 *     }
 *
 *

 *
 *

 *

 * Example #2:

 *
 *

 *
 * @RunWith(JUniceRunner.class)
 * public class AcmeTestCase extends com.google.inject.AbstractModule {
 *
 *     public void configure() {
 *         //Configure your proper modules
 *         ...
 *         bind(Service.class).annotatedWith(TestAnnotation.class).to(ServiceTestImpl.class);
 *         ...
 *     }
 *
 *     @Mock
 *     private AnotherService serviceMock;
 *
 *     @Inject
 *     private Service serviceTest;
 *
 *     @org.junit.Test
 *     public void test() {
 *         assertNotNull(serviceMock);
 *         assertNotNull(serviceTest);
 *     }
 *

 *
 *

 *
 * @see GuiceMockModule
 */
public class JUniceRunner
    extends BlockJUnit4ClassRunner
{

    final private static Logger logger = Logger.getLogger( JUniceRunner.class.getName() );

    private Injector injector;

    final private List<Module> allModules;

    final private Map<Field, Object> mocked = new HashMap<Field, Object>( 1 );

    private MockType mockFramework = MockType.EASY_MOCK;

    /**
     * JUniceRunner constructor to create the core JUnice class.
     *
     * @see RunWith
     * @param klass The test case class to run.
     * @throws org.junit.runners.model.InitializationError if any error occurs.
     */
    public JUniceRunner( Class<?> klass )
        throws InitializationError
    {
        super( klass );

        try
        {
            if ( logger.isLoggable( Level.FINER ) )
            {
                logger.finer( "Inizializing JUniceRunner for class: " + klass.getSimpleName() );
            }

            this.allModules = inizializeInjector( klass );

            if ( logger.isLoggable( Level.FINER ) )
            {
                logger.finer( "done..." );
            }
        }
        catch ( Exception e )
        {
            final List<Throwable> throwables = new ArrayList<Throwable>( 1 );
            throwables.add( e );
            throw new InitializationError( throwables );
        }
    }

    /**
     * {@inheritDoc}
     */
    public void run( final RunNotifier notifier )
    {
        if ( logger.isLoggable( Level.FINER ) )
        {
            logger.finer( " ### Run test case: " + getTestClass().getJavaClass() + " ### " );
            logger.finer( " #### Creating injector ####" );
        }

        this.injector = createInjector( allModules );
        super.run( notifier );
        this.flush();

        if ( logger.isLoggable( Level.FINER ) )
        {
            logger.finer( " ### End test case: " + getTestClass().getJavaClass().getName() + " ### " );
        }
    }

    /**
     * {@inheritDoc}
     */
    private void flush()
    {
        this.injector = null;
        this.allModules.clear();
        this.mocked.clear();
    }

    @Override
    protected void runChild( FrameworkMethod method, RunNotifier notifier )
    {
        if ( logger.isLoggable( Level.FINER ) )
        {
            logger.finer( " +++ invoke test method: " + method.getName() + " +++ " );
        }

        super.runChild( method, notifier );
        resetAllResetAfterMocks();

        if ( logger.isLoggable( Level.FINER ) )
        {
            logger.finer( " --- end test method: " + method.getName() + " --- " );
        }

    }

    // create test class via Google-Guice to inject all not-static dependencies.
    protected Object createTest()
        throws Exception
    {
        if ( logger.isLoggable( Level.FINER ) )
        {
            logger.finer( " Create and inject test class: " + getTestClass().getJavaClass() );
        }
        return this.injector.getInstance( getTestClass().getJavaClass() );
    }

    protected Injector createInjector( List<Module> modules )
    {

        return Guice.createInjector( modules );
    }

    /**
     *

     * Initialize the main Injector.
     *

     *

     * This methot collects modules from {@link GuiceModules}, {@link GuiceProvidedModules}, {@link Mock}, creates a
     * Google-Guice Injector and than inject static members into callings class.
     *

     *
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws HandleException
     */
    protected <T> List<Module> inizializeInjector( Class<T> clazz )
        throws HandleException, InstantiationException, IllegalAccessException
    {
        final List<Module> modules = new ArrayList<Module>();
        Module m = visitClass( clazz );
        if ( m != null )
        {
            modules.add( m );
        }
        return modules;
    }

    private void resetAllResetAfterMocks()
    {
        for ( Entry<Field, Object> entry : mocked.entrySet() )
        {
            final Mock mockAnnotation = entry.getKey().getAnnotation( Mock.class );
            if ( mockAnnotation.resetAfter() )
            {
                MockEngine mockEngine = MockEngineFactory.getMockEngine( mockFramework );
                mockEngine.resetMock( entry.getValue() );
            }
        }
    }

    /**
     * @throws HandleException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    private <T> Module visitClass( final Class<T> clazz )
        throws HandleException, InstantiationException, IllegalAccessException
    {
        try
        {
            if ( logger.isLoggable( Level.FINER ) )
            {
                logger.finer( "  Start introspecting class: " + clazz.getName() );
            }
            final List<Module> allModules = new ArrayList<Module>( 1 );

            // Setup the handlers
            final GuiceProvidedModuleHandler guiceProvidedModuleHandler = new GuiceProvidedModuleHandler();
            final GuiceModuleHandler guiceModuleHandler = new GuiceModuleHandler();
            final GuiceInjectableClassHandler<Inject> guiceInjectableClassHandler = new GuiceInjectableClassHandler<Inject>();
            final GuiceInjectableClassHandler<javax.inject.Inject> jsr330InjectableClassHandler = new GuiceInjectableClassHandler<javax.inject.Inject>();

            final MockHandler mockHandler = new MockHandler();
            final MockFrameworkHandler mockFrameworkHandler = new MockFrameworkHandler();

            // Visit class and super-classes
            new ClassVisitor()
            .registerHandler( GuiceProvidedModules.class, guiceProvidedModuleHandler )
            .registerHandler( GuiceModules.class, guiceModuleHandler )
            .registerHandler( Mock.class, mockHandler )
            .registerHandler( MockFramework.class, mockFrameworkHandler )
            .registerHandler( Inject.class, guiceInjectableClassHandler )
            .registerHandler( javax.inject.Inject.class, jsr330InjectableClassHandler )
            .visit( clazz );

            // Retrieve mock framework
            if ( mockFrameworkHandler.getMockType() != null )
            {
                this.mockFramework = mockFrameworkHandler.getMockType();
            }

            // retrieve the modules founded
            allModules.addAll( guiceProvidedModuleHandler.getModules() );
            allModules.addAll( guiceModuleHandler.getModules() );
            MockEngine engine = MockEngineFactory.getMockEngine( this.mockFramework );
            this.mocked.putAll( mockHandler.getMockedObject( engine ) );
            if ( !this.mocked.isEmpty() )
            {
                // Replace all real module binding with Mocked moduled.
                Module m = Modules.override( allModules ).with( new GuiceMockModule( this.mocked ) );
                allModules.clear();
                allModules.add( m );
            }

            // Add only clasess that have got the Inject annotation
             final Class<?>[] guiceInjectableClasses = guiceInjectableClassHandler.getClasses();
             final Class<?>[] jsr330InjectableClasses = jsr330InjectableClassHandler.getClasses();

            final AbstractModule statcInjector = new AbstractModule()
            {
                @Override
                protected void configure()
                {
                    // inject all STATIC dependencies
                    if ( guiceInjectableClasses.length != 0 )
                    {
                        requestStaticInjection( guiceInjectableClasses );
                    }

                    if ( jsr330InjectableClasses.length != 0 )
                    {
                        requestStaticInjection( jsr330InjectableClasses );
                    }

                }
            };
            if ( guiceInjectableClasses.length != 0 || jsr330InjectableClasses.length != 0 )
            {
                allModules.add( statcInjector );
            }

            // Check if the class is itself a Google Module.
            if ( Module.class.isAssignableFrom( getTestClass().getJavaClass() ) )
            {
                if ( logger.isLoggable( Level.FINER ) )
                {
                    logger.finer( "   creating module from test class " + getTestClass().getJavaClass() );
                }
                final Module classModule = (Module) getTestClass().getJavaClass().newInstance();
                allModules.add( classModule );
            }

            // create MockTypeListenerModule
            if ( this.mocked.size() != 0 )
            {
                final AbstractModule mockTypeListenerModule = new AbstractModule()
                {
                    @Override
                    protected void configure()
                    {
                        bindListener( Matchers.any(), new MockTypeListener( mocked ) );
                    }
                };

                // BEGIN patch for issue: google-guice: #452
                for ( Entry<Field, Object> entry : mocked.entrySet() )
                {
                    final Field field = entry.getKey();
                    final Object mock = entry.getValue();
                    if ( Modifier.isStatic( field.getModifiers() ) )
                    {
                        if ( logger.isLoggable( Level.FINER ) )
                        {
                            logger.finer( "   inject static mock field: " + field.getName() );
                        }

                        field.setAccessible( true );
                        field.set( field.getDeclaringClass(), mock );
                    }
                }
                // END patch for issue: google-guice: #452

                allModules.add( mockTypeListenerModule );
            }

            if ( allModules.size() != 0 )
            {
                if ( logger.isLoggable( Level.FINER ) )
                {
                    StringBuilder builder = new StringBuilder();
                    builder.append( " Collected modules: " );
                    builder.append( "\n" );
                    for ( Module module : allModules )
                    {
                        builder.append( "    " + module );
                        builder.append( "\n" );
                    }
                    logger.finer( builder.toString() );
                }
                return Modules.combine( allModules );
            }
            return null;
        }
        finally
        {
            if ( logger.isLoggable( Level.FINER ) )
            {
                logger.finer( " ...done" );
            }
        }
    }

}