text:
package play;

import java.io.File;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.LineNumberReader;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import play.cache.Cache;
import play.classloading.ApplicationClasses;
import play.classloading.ApplicationClassloader;
import play.exceptions.PlayException;
import play.exceptions.UnexpectedException;
import play.libs.IO;
import play.mvc.Http;
import play.mvc.Router;
import play.plugins.PluginCollection;
import play.templates.TemplateLoader;
import play.utils.OrderSafeProperties;
import play.vfs.VirtualFile;

/**
 * Main framework class
 */
public class Play {

    /**
     * 2 modes
     */
    public enum Mode {

        /**
         * Enable development-specific features, e.g. view the documentation at the URL {@literal "/@documentation"}.
         */
        DEV,
        /**
         * Disable development-specific features.
         */
        PROD;

        public boolean isDev() {
            return this == DEV;
        }

        public boolean isProd() {
            return this == PROD;
        }
    }
    /**
     * Is the application initialized
     */
    public static boolean initialized = false;

    /**
     * Is the application started
     */
    public static boolean started = false;
    /**
     * True when the one and only shutdown hook is enabled
     */
    private static boolean shutdownHookEnabled = false;
    /**
     * The framework ID
     */
    public static String id;
    /**
     * The application mode
     */
    public static Mode mode;
    /**
     * The application root
     */
    public static File applicationPath = null;
    /**
     * tmp dir
     */
    public static File tmpDir = null;
    /**
     * tmp dir is readOnly
     */
    public static boolean readOnlyTmp = false;
    /**
     * The framework root
     */
    public static File frameworkPath = null;
    /**
     * All loaded application classes
     */
    public static ApplicationClasses classes;
    /**
     * The application classLoader
     */
    public static ApplicationClassloader classloader;
    /**
     * All paths to search for files
     */
    public static List<VirtualFile> roots = new ArrayList<VirtualFile>(16);
    /**
     * All paths to search for Java files
     */
    public static List<VirtualFile> javaPath;
    /**
     * All paths to search for templates files
     */
    public static List<VirtualFile> templatesPath;
    /**
     * Main routes file
     */
    public static VirtualFile routes;
    /**
     * Plugin routes files
     */
    public static Map<String, VirtualFile> modulesRoutes;
    /**
     * The main application.conf
     */
    public static VirtualFile conf;
    /**
     * The app configuration (already resolved from the framework id)
     */
    public static Properties configuration;
    /**
     * The last time than the application has started
     */
    public static long startedAt;
    /**
     * The list of supported locales
     */
    public static List<String> langs = new ArrayList<String>(16);
    /**
     * The very secret key
     */
    public static String secretKey;
    /**
     * pluginCollection that holds all loaded plugins and all enabled plugins..
     */
    public static PluginCollection pluginCollection = new PluginCollection();
    /**
     * Readonly list containing currently enabled plugins.
     * This list is updated from pluginCollection when pluginCollection is modified
     * Play plugins
     * Use pluginCollection instead.
     */
    @Deprecated
    public static List<PlayPlugin> plugins = pluginCollection.getEnabledPlugins();
    /**
     * Modules
     */
    public static Map<String, VirtualFile> modules = new HashMap<String, VirtualFile>(16);
    /**
     * Framework version
     */
    public static String version = null;
    /**
     * Context path (when several application are deployed on the same host)
     */
    public static String ctxPath = "";
    static boolean firstStart = true;
    public static boolean usePrecompiled = false;
    public static boolean forceProd = false;
    /**
     * Lazy load the templates on demand
     */
    public static boolean lazyLoadTemplates = false;

    /**
     * This is used as default encoding everywhere related to the web: request, response, WS
     */
    public static String defaultWebEncoding = "utf-8";

    /**
     * This flag indicates if the app is running in a standalone Play server or
     * as a WAR in an applicationServer
     */
    public static boolean standalonePlayServer = true;

    /**
     * Init the framework
     *
     * @param root The application path
     * @param id   The framework id to use
     */
    public static void init(File root, String id) {
        // Simple things
        Play.id = id;
        Play.started = false;
        Play.applicationPath = root;

        // load all play.static of exists
        initStaticStuff();

        guessFrameworkPath();

        // Read the configuration file
        readConfiguration();

        Play.classes = new ApplicationClasses();

        // Configure logs
        Logger.init();
        String logLevel = configuration.getProperty("application.log", "INFO");

        //only override log-level if Logger was not configured manually
        if( !Logger.configuredManually) {
            Logger.setUp(logLevel);
        }
        Logger.recordCaller = Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));

        Logger.info("Starting %s", root.getAbsolutePath());

        if (configuration.getProperty("play.tmp", "tmp").equals("none")) {
            tmpDir = null;
            Logger.debug("No tmp folder will be used (play.tmp is set to none)");
        } else {
            tmpDir = new File(configuration.getProperty("play.tmp", "tmp"));
            if (!tmpDir.isAbsolute()) {
                tmpDir = new File(applicationPath, tmpDir.getPath());
            }

            if (Logger.isTraceEnabled()) {
                Logger.trace("Using %s as tmp dir", Play.tmpDir);
            }

            if (!tmpDir.exists()) {
                try {
                    if (readOnlyTmp) {
                        throw new Exception("ReadOnly tmp");
                    }
                    tmpDir.mkdirs();
                } catch (Throwable e) {
                    tmpDir = null;
                    Logger.warn("No tmp folder will be used (cannot create the tmp dir)");
                }
            }
        }

        // Mode
        mode = Mode.valueOf(configuration.getProperty("application.mode", "DEV").toUpperCase());
        if (usePrecompiled || forceProd) {
            mode = Mode.PROD;
        }

        // Context path
        ctxPath = configuration.getProperty("http.path", ctxPath);

        // Build basic java source path
        VirtualFile appRoot = VirtualFile.open(applicationPath);
        roots.add(appRoot);
        javaPath = new CopyOnWriteArrayList<VirtualFile>();
        javaPath.add(appRoot.child("app"));
        javaPath.add(appRoot.child("conf"));

        // Build basic templates path
        if (appRoot.child("app/views").exists()) {
            templatesPath = new ArrayList<VirtualFile>(2);
            templatesPath.add(appRoot.child("app/views"));
        } else {
            templatesPath = new ArrayList<VirtualFile>(1);
        }

        // Main route file
        routes = appRoot.child("conf/routes");

        // Plugin route files
        modulesRoutes = new HashMap<String, VirtualFile>(16);

        // Load modules
        loadModules();

        // Load the templates from the framework after the one from the modules
        templatesPath.add(VirtualFile.open(new File(frameworkPath, "framework/templates")));

        // Enable a first classloader
        classloader = new ApplicationClassloader();

        // Fix ctxPath
        if ("/".equals(Play.ctxPath)) {
            Play.ctxPath = "";
        }

        // Default cookie domain
        Http.Cookie.defaultDomain = configuration.getProperty("application.defaultCookieDomain", null);
        if (Http.Cookie.defaultDomain!=null) {
            Logger.info("Using default cookie domain: " + Http.Cookie.defaultDomain);
        }

        // Plugins
        pluginCollection.loadPlugins();

        // Done !
        if (mode == Mode.PROD || System.getProperty("precompile") != null) {
            mode = Mode.PROD;
            if (preCompile() && System.getProperty("precompile") == null) {
                start();
            } else {
                return;
            }
        } else {
            Logger.warn("You're running Play! in DEV mode");
        }

        // Plugins
        pluginCollection.onApplicationReady();

        Play.initialized = true;
    }

    public static void guessFrameworkPath() {
        // Guess the framework path
        try {
            URL versionUrl = Play.class.getResource("/play/version");
            // Read the content of the file
            Play.version = new LineNumberReader(new InputStreamReader(versionUrl.openStream())).readLine();

            // This is used only by the embedded server (Mina, Netty, Jetty etc)
            URI uri = new URI(versionUrl.toString().replace(" ", "%20"));
            if (frameworkPath == null || !frameworkPath.exists()) {
                if (uri.getScheme().equals("jar")) {
                    String jarPath = uri.getSchemeSpecificPart().substring(5, uri.getSchemeSpecificPart().lastIndexOf("!"));
                    frameworkPath = new File(jarPath).getParentFile().getParentFile().getAbsoluteFile();
                } else if (uri.getScheme().equals("file")) {
                    frameworkPath = new File(uri).getParentFile().getParentFile().getParentFile().getParentFile();
                } else {
                    throw new UnexpectedException("Cannot find the Play! framework - trying with uri: " + uri + " scheme " + uri.getScheme());
                }
            }
        } catch (Exception e) {
            throw new UnexpectedException("Where is the framework ?", e);
        }
    }

    /**
     * Read application.conf and resolve overriden key using the play id mechanism.
     */
    public static void readConfiguration() {
        configuration = readOneConfigurationFile("application.conf", new HashSet<String>());
        // Plugins
        pluginCollection.onConfigurationRead();
    }

    private static Properties readOneConfigurationFile(String filename, Set<String> seenFileNames) {

        if (seenFileNames.contains(filename)) {
            throw new RuntimeException("Detected recursive @include usage. Have seen the file " + filename + " before");
        }
        seenFileNames.add(filename);

        Properties propsFromFile=null;

        VirtualFile appRoot = VirtualFile.open(applicationPath);
        conf = appRoot.child("conf/" + filename);
        try {
            propsFromFile = IO.readUtf8Properties(conf.inputstream());
        } catch (RuntimeException e) {
            if (e.getCause() instanceof IOException) {
                Logger.fatal("Cannot read "+filename);
                fatalServerErrorOccurred();
            }
        }
        // OK, check for instance specifics configuration
        Properties newConfiguration = new OrderSafeProperties();
        Pattern pattern = Pattern.compile("^%([a-zA-Z0-9_\\-]+)\\.(.*)$");
        for (Object key : propsFromFile.keySet()) {
            Matcher matcher = pattern.matcher(key + "");
            if (!matcher.matches()) {
                newConfiguration.put(key, propsFromFile.get(key).toString().trim());
            }
        }
        for (Object key : propsFromFile.keySet()) {
            Matcher matcher = pattern.matcher(key + "");
            if (matcher.matches()) {
                String instance = matcher.group(1);
                if (instance.equals(id)) {
                    newConfiguration.put(matcher.group(2), propsFromFile.get(key).toString().trim());
                }
            }
        }
        propsFromFile = newConfiguration;
        // Resolve ${..}
        pattern = Pattern.compile("\\$\\{([^}]+)}");
        for (Object key : propsFromFile.keySet()) {
            String value = propsFromFile.getProperty(key.toString());
            Matcher matcher = pattern.matcher(value);
            StringBuffer newValue = new StringBuffer(100);
            while (matcher.find()) {
                String jp = matcher.group(1);
                String r;
                if (jp.equals("application.path")) {
                    r = Play.applicationPath.getAbsolutePath();
                } else if (jp.equals("play.path")) {
                    r = Play.frameworkPath.getAbsolutePath();
                } else {
                    r = System.getProperty(jp);
                    if (r == null) {
                        r = System.getenv(jp);
                    }
                    if (r == null) {
                        Logger.warn("Cannot replace %s in configuration (%s=%s)", jp, key, value);
                        continue;
                    }
                }
                matcher.appendReplacement(newValue, r.replaceAll("\\\\", "\\\\\\\\"));
            }
            matcher.appendTail(newValue);
            propsFromFile.setProperty(key.toString(), newValue.toString());
        }
        // Include
        Map<Object, Object> toInclude = new HashMap<Object, Object>(16);
        for (Object key : propsFromFile.keySet()) {
            if (key.toString().startsWith("@include.")) {
                try {
                    String filenameToInclude = propsFromFile.getProperty(key.toString());
                    toInclude.putAll( readOneConfigurationFile(filenameToInclude, seenFileNames) );
                } catch (Exception ex) {
                    Logger.warn("Missing include: %s", key);
                }
            }
        }
        propsFromFile.putAll(toInclude);

        return propsFromFile;
    }

    /**
     * Start the application.
     * Recall to restart !
     */
    public static synchronized void start() {
        try {

            if (started) {
                stop();
            }

            if( standalonePlayServer) {
                // Can only register shutdown-hook if running as standalone server
                if (!shutdownHookEnabled) {
                    //registers shutdown hook - Now there's a good chance that we can notify
                    //our plugins that we're going down when some calls ctrl+c or just kills our process..
                    shutdownHookEnabled = true;
                    Runtime.getRuntime().addShutdownHook(new Thread() {
                        public void run() {
                            Play.stop();
                        }
                    });
                }
            }

            if (mode == Mode.DEV) {
                // Need a new classloader
                classloader = new ApplicationClassloader();
                // Reload plugins
                pluginCollection.reloadApplicationPlugins();

            }

            // Reload configuration
            readConfiguration();

            // Configure logs
            String logLevel = configuration.getProperty("application.log", "INFO");
            //only override log-level if Logger was not configured manually
            if( !Logger.configuredManually) {
                Logger.setUp(logLevel);
            }
            Logger.recordCaller = Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));

            // Locales
            langs = new ArrayList<String>(Arrays.asList(configuration.getProperty("application.langs", "").split(",")));
            if (langs.size() == 1 && langs.get(0).trim().length() == 0) {
                langs = new ArrayList<String>(16);
            }

            // Clean templates
            TemplateLoader.cleanCompiledCache();

            // SecretKey
            secretKey = configuration.getProperty("application.secret", "").trim();
            if (secretKey.length() == 0) {
                Logger.warn("No secret key defined. Sessions will not be encrypted");
            }

            // Default web encoding
            String _defaultWebEncoding = configuration.getProperty("application.web_encoding");
            if( _defaultWebEncoding != null ) {
                Logger.info("Using custom default web encoding: " + _defaultWebEncoding);
                defaultWebEncoding = _defaultWebEncoding;
                // Must update current response also, since the request/response triggering
                // this configuration-loading in dev-mode have already been
                // set up with the previous encoding
                if( Http.Response.current() != null ) {
                    Http.Response.current().encoding = _defaultWebEncoding;
                }
            }

            // Try to load all classes
            Play.classloader.getAllClasses();

            // Routes
            Router.detectChanges(ctxPath);

            // Cache
            Cache.init();

            // Plugins
            try {
                pluginCollection.onApplicationStart();
            } catch (Exception e) {
                if (Play.mode.isProd()) {
                    Logger.error(e, "Can't start in PROD mode with errors");
                }
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                }
                throw new UnexpectedException(e);
            }

            if (firstStart) {
                Logger.info("Application '%s' is now started !", configuration.getProperty("application.name", ""));
                firstStart = false;
            }

            // We made it
            started = true;
            startedAt = System.currentTimeMillis();

            // Plugins
            pluginCollection.afterApplicationStart();

        } catch (PlayException e) {
            started = false;
            try { Cache.stop(); } catch (Exception ignored) {}
            throw e;
        } catch (Exception e) {
            started = false;
            try { Cache.stop(); } catch (Exception ignored) {}
            throw new UnexpectedException(e);
        }
    }

    /**
     * Stop the application
     */
    public static synchronized void stop() {
        if (started) {
            Logger.trace("Stopping the play application");
            pluginCollection.onApplicationStop();
            started = false;
            Cache.stop();
            Router.lastLoading = 0L;
        }
    }

    /**
     * Force all java source and template compilation.
     *
     * @return success ?
     */
    static boolean preCompile() {
        if (usePrecompiled) {
            if (Play.getFile("precompiled").exists()) {
                classloader.getAllClasses();
                Logger.info("Application is precompiled");
                return true;
            }
            Logger.error("Precompiled classes are missing!!");
            fatalServerErrorOccurred();
            return false;
        }
        try {
            Logger.info("Precompiling ...");
            Thread.currentThread().setContextClassLoader(Play.classloader);
            long start = System.currentTimeMillis();
            classloader.getAllClasses();

            if (Logger.isTraceEnabled()) {
                Logger.trace("%sms to precompile the Java stuff", System.currentTimeMillis() - start);
            }

            if (!lazyLoadTemplates) {
                start = System.currentTimeMillis();
                TemplateLoader.getAllTemplate();

                if (Logger.isTraceEnabled()) {
                    Logger.trace("%sms to precompile the templates", System.currentTimeMillis() - start);
                }
            }
            return true;
        } catch (Throwable e) {
            Logger.error(e, "Cannot start in PROD mode with errors");
            fatalServerErrorOccurred();
            return false;
        }
    }

    /**
     * Detect sources modifications
     */
    public static synchronized void detectChanges() {
        if (mode == Mode.PROD) {
            return;
        }
        try {
            pluginCollection.beforeDetectingChanges();
            if(!pluginCollection.detectClassesChange()) {
                classloader.detectChanges();
            }
            Router.detectChanges(ctxPath);
            if (conf.lastModified() > startedAt) {
                start();
                return;
            }
            pluginCollection.detectChange();
            if (!Play.started) {
                throw new RuntimeException("Not started");
            }
        } catch (PlayException e) {
            throw e;
        } catch (Exception e) {
            // We have to do a clean refresh
            start();
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T plugin(Class<T> clazz) {
        return (T)pluginCollection.getPluginInstance((Class<? extends PlayPlugin>)clazz);
    }

    /**
     * Allow some code to run very early in Play - Use with caution !
     */
    public static void initStaticStuff() {
        // Play! plugings
        Enumeration<URL> urls = null;
        try {
            urls = Play.class.getClassLoader().getResources("play.static");
        } catch (Exception e) {
        }
        while (urls != null && urls.hasMoreElements()) {
            URL url = urls.nextElement();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    try {
                        Class.forName(line);
                    } catch (Exception e) {
                        Logger.warn("! Cannot init static: " + line);
                    }
                }
            } catch (Exception ex) {
                Logger.error(ex, "Cannot load %s", url);
            }
        }
    }

    /**
     * Load all modules.
     * You can even specify the list using the MODULES environement variable.
     */
    public static void loadModules() {
        if (System.getenv("MODULES") != null) {
            // Modules path is prepended with a env property
            if (System.getenv("MODULES") != null && System.getenv("MODULES").trim().length() > 0) {
                for (String m : System.getenv("MODULES").split(System.getProperty("os.name").startsWith("Windows") ? ";" : ":")) {
                    File modulePath = new File(m);
                    if (!modulePath.exists() || !modulePath.isDirectory()) {
                        Logger.error("Module %s will not be loaded because %s does not exist", modulePath.getName(), modulePath.getAbsolutePath());
                    } else {
                        final String modulePathName = modulePath.getName();
                        final String moduleName = modulePathName.contains("-") ?
                                modulePathName.substring(0, modulePathName.lastIndexOf("-")) :
                                modulePathName;
                        addModule(moduleName, modulePath);
                    }
                }
            }
        }
        for (Object key : configuration.keySet()) {
            String pName = key.toString();
            if (pName.startsWith("module.")) {
                Logger.warn("Declaring modules in application.conf is deprecated. Use dependencies.yml instead (%s)", pName);
                String moduleName = pName.substring(7);
                File modulePath = new File(configuration.getProperty(pName));
                if (!modulePath.isAbsolute()) {
                    modulePath = new File(applicationPath, configuration.getProperty(pName));
                }
                if (!modulePath.exists() || !modulePath.isDirectory()) {
                    Logger.error("Module %s will not be loaded because %s does not exist", moduleName, modulePath.getAbsolutePath());
                } else {
                    addModule(moduleName, modulePath);
                }
            }
        }

        // Load modules from modules/ directory
        File localModules = Play.getFile("modules");
        if (localModules.exists() && localModules.isDirectory()) {
            for (File module : localModules.listFiles()) {
                String moduleName = module.getName();
                if (moduleName.contains("-")) {
                    moduleName = moduleName.substring(0, moduleName.indexOf("-"));
                }
                if (module.isDirectory()) {
                    addModule(moduleName, module);
                } else {
                    File modulePath = new File(IO.readContentAsString(module).trim());
                    if (!modulePath.exists() || !modulePath.isDirectory()) {
                        Logger.error("Module %s will not be loaded because %s does not exist", moduleName, modulePath.getAbsolutePath());
                    } else {
                        addModule(moduleName, modulePath);
                    }

                }
            }
        }
        // Auto add special modules
        if (Play.runingInTestMode()) {
            addModule("_testrunner", new File(Play.frameworkPath, "modules/testrunner"));
        }
        if (Play.mode == Mode.DEV) {
            addModule("_docviewer", new File(Play.frameworkPath, "modules/docviewer"));
        }
    }

    /**
     * Add a play application (as plugin)
     *
     * @param path The application path
     */
    public static void addModule(String name, File path) {
        VirtualFile root = VirtualFile.open(path);
        modules.put(name, root);
        if (root.child("app").exists()) {
            javaPath.add(root.child("app"));
        }
        if (root.child("app/views").exists()) {
            templatesPath.add(root.child("app/views"));
        }
        if (root.child("conf/routes").exists()) {
            modulesRoutes.put(name, root.child("conf/routes"));
        }
        roots.add(root);
        if (!name.startsWith("_")) {
            Logger.info("Module %s is available (%s)", name, path.getAbsolutePath());
        }
    }

    /**
     * Search a VirtualFile in all loaded applications and plugins
     *
     * @param path Relative path from the applications root
     * @return The virtualFile or null
     */
    public static VirtualFile getVirtualFile(String path) {
        return VirtualFile.search(roots, path);
    }

    /**
     * Search a File in the current application
     *
     * @param path Relative path from the application root
     * @return The file even if it doesn't exist
     */
    public static File getFile(String path) {
        return new File(applicationPath, path);
    }

    /**
     * Returns true if application is runing in test-mode.
     * Test-mode is resolved from the framework id.
     *
     * Your app is running in test-mode if the framwork id (Play.id)
     * is 'test' or 'test-?.*'
     * @return true if testmode
     */
    public static boolean runingInTestMode(){
        return id.matches("test|test-?.*");
    }

    /**
     * Call this method when there has been a fatal error that Play cannot recover from
     */
    public static void fatalServerErrorOccurred() {
        if (standalonePlayServer) {
            // Just quit the process
            System.exit(-1);
        } else {
            // Cannot quit the process while running inside an applicationServer
            String msg = "A fatal server error occurred";
            Logger.error(msg);
            throw new Error(msg);
        }
    }

}


text:
using System.ComponentModel;
using System.Linq;
using System.Windows.Controls;

namespace UnitsNet.Samples.UnitConverter.Wpf
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            if (DesignerProperties.GetIsInDesignMode(this))
            {

            }
            else
            {
                DataContext = new MainWindowVm();
            }
        }

        private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Scroll to view on selection change - fixes issue where on app startup Length was selected but not scrolled to
            var listbox = (ListBox) sender;
            var firstSelectedItem = listbox.SelectedItems.Cast<object>().FirstOrDefault();
            if (firstSelectedItem == null)
            {
                return;
            }

            listbox.ScrollIntoView(firstSelectedItem);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
class Address < ActiveRecord::Base
  belongs_to :country
  belongs_to :state

  has_many :checkouts, :foreign_key => "bill_address_id"
  has_many :shipments

  validates_presence_of :firstname
  validates_presence_of :lastname
  validates_presence_of :address1
  validates_presence_of :city
  validates_presence_of :state, :if => Proc.new { |address| address.state_name.blank? && Spree::Config[:address_requires_state] }
  validates_presence_of :state_name, :if => Proc.new { |address| address.state.blank? && Spree::Config[:address_requires_state] }
  validates_presence_of :zipcode
  validates_presence_of :country
  validates_presence_of :phone
  validate :state_name_validate, :if => Proc.new { |address| address.state.blank? && Spree::Config[:address_requires_state] }

  # disconnected since there's no code to display error messages yet OR matching client-side validation
  def phone_validate
    return if phone.blank?
    n_digits = phone.scan(/[0-9]/).size
    valid_chars = (phone =~ /^[-+()\/\s\d]+$/)
    if !(n_digits > 5 && valid_chars)
      errors.add(:phone, :invalid)
    end
  end

  def state_name_validate
    country = country_id ? Country.find(country_id) : nil
    return if country.blank? || country.states.empty?
    if state_name.blank? || country.states.name_or_abbr_equals(state_name).empty?
      errors.add(:state, :invalid)
    end
  end

  def self.default
    new :country => Country.find(Spree::Config[:default_country_id])
  end

  # can modify an address if it's not been used in an order (but checkouts controller has finer control)
  def editable?
    new_record? || (shipments.empty? && checkouts.empty?)
  end

  def full_name
    self.firstname + " " + self.lastname
  end

  def state_text
    state.nil? ? state_name : (state.abbr.blank? ? state.name : state.abbr)
  end

  def zone
    (state && state.zone) ||
    (country && country.zone)
  end

  def zones
    Zone.match(self)
  end

  def same_as?(other)
    return false if other.nil?
    attributes.except("id", "updated_at", "created_at") ==  other.attributes.except("id", "updated_at", "created_at")
  end
  alias same_as same_as?

  def to_s
    "#{full_name}: #{address1}"
  end

  def clone
    Address.new(self.attributes.except("id", "updated_at", "created_at"))
  end

  def ==(other_address)
    self_attrs = self.attributes
    other_attrs = other_address.respond_to?(:attributes) ? other_address.attributes : {}

    [self_attrs, other_attrs].each { |attrs| attrs.except!("id", "created_at", "updated_at", "order_id") }

    self_attrs == other_attrs
  end

  def empty?
    attributes.except("id", "created_at", "updated_at", "order_id", "country_id").all? {|k,v| v.nil?}
  end
end


text:
import {WasmSectionBinary} from "../wasm-binary-section";
import {WasmSection} from "../../core/wasm-section";
import {ByteArray} from "../../../../utils/bytearray";
import {WasmSignature} from "../../core/wasm-signature";
import {WasmType} from "../../core/wasm-type";
import {Terminal} from "../../../../utils/terminal";
/**
 * Created by 01 on 2017-06-17.
 */
export class SignatureSection extends WasmSectionBinary {

    signatures: WasmSignature[];

    constructor(payload = new ByteArray()) {
        super(
            WasmSection.Signature,
            payload.length,
            null, null,
            payload
        );
        this.signatures = [];
    }

    read() {
        let signatureCount: int32 = this.payload.readU32LEB();
        for (let i: int32 = 0; i < signatureCount; i++) {
            let signature = new WasmSignature();
            let form = this.payload.readUnsignedByte();
            if (form !== WasmType.func) {
                Terminal.error("Wrong function type");
            }
            let numArguments = this.payload.readU32LEB();
            for (let j: int32 = 0; j < numArguments; j++) {
                let type = this.payload.readU32LEB();
                signature.argumentTypes.push(type);
            }

            let numResults = this.payload.readU8LEB();
            if (numResults > 0) {
                signature.returnType = this.payload.readU32LEB();
            } else {
                signature.returnType = WasmType.VOID;
            }
            this.signatures.push(signature);
        }
    }

    publish(data: ByteArray): void {
        super.publish(data);
    }
}


text:
export function $null<T>(a: null, b: T | null): boolean;
export function $undefined<T>(a: undefined, b: T | undefined): boolean;
export function $general<T>(a: T, b: T): boolean;


text:
from vilya.models.actions.base import Action, ActionScope

# TODO
#            message=trunc_utf8(comment.content, 50, None),
#            proj=proj.name,
#            author=comment.author,
#            date=comment.created,
#            type='commit_comment',
#            ref=comment.ref,
#            url='/%s/commit/%s#%s' % (proj.name, comment.ref, self.uid)
class CommitComment(Action):
    def __init__(self, sender, date, proj_name, commit_ref, content, url):
        super(CommitComment, self).__init__(sender, date)
        self.proj = proj_name
        self.ref = commit_ref
        self.content = CommitComment._truncate(content)
        self.url = url  # TODO , uid?

    @property
    def type(self):
        return 'commit_comment'

    @property
    def scope(self):
        return ActionScope.project

    @property
    def target(self):
        return self.proj

    @property
    def entry_id(self):
        # 显示的时候 [:10]
        return self.ref

    @property
    def entry_title(self):
        return 'Commit comment in ' + self.ref[:10]

migrate_commit_comment = {
    'sender': 'author',
    'content': 'message',
    'target': 'proj',
    'scope': ('', lambda x: 'project'),  # only projects has commit_comment
    'entry_id': 'ref',
    'entry_title': ('ref', lambda x: 'Commit comment in ' + x[:10]),
}


text:
#ifndef DGLANDROIDSELECTDEV_H
#define DGLANDROIDSELECTDEV_H

#include "dglqtgui.h"

#include "ui_dglandroidselectdev.h"

#include "ui_dglconnectandroidadb.h"
#include "dgladbdevice.h"

class DGLConnectAndroidAdbDialog : public QDialog {
    Q_OBJECT

   public:
    DGLConnectAndroidAdbDialog();
    ~DGLConnectAndroidAdbDialog();
    std::string getAddress();

   private:
    Ui::DGLConnectAndroidAdbDialogClass m_ui;
};

class DGLAndroidSelectDevWidget : public QWidget, DGLAdbHandler {
    Q_OBJECT

   public:
    DGLAndroidSelectDevWidget(QWidget* parent);
    DGLADBDevice* getCurrentDevice();

    void setPreselectedDevice(const std::string& serial);

   public
slots:
    void adbKillServer();
    void adbConnect();
    void selectDevice(const QString& serial);

    void gotDevices(std::vector<std::string> devices);

signals:
    void selectDevice(DGLADBDevice*);
    void updateWidget();
    void adbFailed(const std::string&);

   private
slots:

    void reloadDevices();

   private:
    virtual void hideEvent(QHideEvent* event) override;
    virtual void showEvent(QShowEvent* event) override;

    class KillOrConnectHandler: public DGLAdbHandler {
    public:
        KillOrConnectHandler(DGLAndroidSelectDevWidget* p):m_Parent(p) {}
        virtual void done(const std::vector<std::string>& data) override;
        virtual void failed(const std::string& reason) override;
    private:
        DGLAndroidSelectDevWidget* m_Parent;
    } m_KillOrConnectHandler;

    virtual void done(const std::vector<std::string>& data) override;
    virtual void failed(const std::string& reason) override;

    QTimer m_ReloadTimer;

    DGLConnectAndroidAdbDialog m_ConnectDialog;

    std::shared_ptr<DGLADBDevice> m_CurrentDevice;

    Ui::DGLAndroidSelectDev m_ui;

    std::string m_PreselectedDeviceSerial;

};

#endif    // DGLCONNECTDIALOG_H


text:
Programming Style Guide
-----------------------
A quick note: Throughout development my programming style changed somewhat, so you will see code that does not follow the rules below. All new code obeys these rules.

**This is not a primer on writing effective Python. I am also not a World Famous Superstar Master Python Coder.**

* Use tabs for line indents. Spaces can be used AFTER tabs to help improve readability or for stylistic reasons if needed.
* Variable names should be prefixed with an underscore (`_chunk_key`) if they are defined outside of a `for` loop. Variables used to iterate through lists/are created in the for loop's definition should omit the underscore. Arguments should never start with an underscore unless keyword arguments (`kwargs`) are expected to clash with them.

Abusing Lambdas
-------------
Throughout the code you'll see opportunites to filter results of certain functions by passing a function to keyword argument `filter_if`. However, `filter_if` is usually only called with one argument, rendering the majority of possible filters that need extra arguments completely useless. Instead of filtering the results after they are returned, we can pack the variables we need to access later inside the lambda's definition.

	def manage_combat(life, group_id):
		if get_stage(life, group_id) == STAGE_RAIDING:
			prepare_for_raid(life, group_id)
			return False

		for known_group_id in life['known_groups']:
			if group_id == known_group_id:
				continue

			if not get_group_memory(life, known_group_id, 'alignment') == 'hostile':
				announce(life, group_id, 'inform_of_known_group', group_id=known_group_id,
						 filter_if=lambda alife: group_exists(alife, known_group_id))

				_known_group_members = get_group_memory(life, known_group_id, 'members')

In the above example we can see that `known_group_id` is created in the local scope, but can still be referenced and used inside of the lambda when it is called later. Another example, this time showing an entire `life` structure being passed:

	announce(life, group_id, 'combat_ready', ignore_if_said_in_last=1000, filter_if=lambda alife: brain.get_alife_flag(life, alife['id'], 'combat_ready'))

Note that the lambda's argument was renamed to `alife` to prevent conflicts with `life`.


text:
package me.dslztx.assist.algorithm;

import static org.junit.Assert.fail;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KMPTest {
    private static final Logger logger = LoggerFactory.getLogger(KMPTest.class);

    @Test
    public void match() {
        try {
            KMP kmp = new KMP("hello world");

            Assert.assertTrue(kmp.match("ni hao hello world hah "));
            Assert.assertFalse(kmp.match("ni hao helo world hah "));
        } catch (Exception e) {
            logger.error("", e);
            fail();
        }
    }

    @Test
    public void firstMatch() {
        try {
            KMP kmp = new KMP("hello world");

            PatternHit hit = kmp.firstMatch("12345hello world678910");
            Assert.assertTrue(hit.equals(new PatternHit(5, 15, "hello world")));
        } catch (Exception e) {
            logger.error("", e);
            fail();
        }
    }

    @Test
    public void matchAll() {
        try {
            KMP kmp = new KMP("hhh");

            List<PatternHit> hits = kmp.matchAll("12345hhhhworld");

            Assert.assertTrue(hits.get(0).equals(new PatternHit(5, 7, "hhh")));
        } catch (Exception e) {
            logger.error("", e);
            fail();
        }
    }

    @Test
    public void matchAllNonCoincide() {
        try {
            KMP kmp = new KMP("hello world");

            List<PatternHit> hits = kmp.matchAllCoincide("12345hello world678910hello world");

            Assert.assertTrue(hits.get(0).equals(new PatternHit(5, 15, "hello world")));
            Assert.assertTrue(hits.get(1).equals(new PatternHit(22, 32, "hello world")));

            KMP kmp2 = new KMP("hhh");

            List<PatternHit> hits2 = kmp2.matchAllCoincide("12345hhhhworld");

            Assert.assertTrue(hits2.get(0).equals(new PatternHit(5, 7, "hhh")));
            Assert.assertTrue(hits2.get(1).equals(new PatternHit(6, 8, "hhh")));
        } catch (Exception e) {
            logger.error("", e);
            fail();
        }
    }
}


text:
package com.hack23.cia.service.external.riksdagen.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import com.hack23.cia.model.external.riksdagen.votering.impl.BallotContainer;
import com.hack23.cia.model.external.riksdagen.votering.impl.VoteDataDto;

/**
 * The Class RiksdagenDateUtil.
 */
final class RiksdagenDateUtil {

	/** The Constant YYYY_MM_DD. */
	public static final String YYYY_MM_DD = "yyyy-MM-dd";

	/** The Constant CONTAINS_ONE. */
	private static final int CONTAINS_ONE = 1;

	/**
	 * Instantiates a new riksdagen date util.
	 */
	public RiksdagenDateUtil() {
		super();
	}

	/**
	 * Best guess vote date.
	 *
	 * @param ballotContainer
	 *            the ballot container
	 * @return the date
	 * @throws ParseException
	 *             the parse exception
	 */
	private static Date bestGuessVoteDate(final BallotContainer ballotContainer) throws ParseException {
		final com.hack23.cia.model.external.riksdagen.votering.impl.BallotDocumentElement ballotDocumentElement = ballotContainer.getBallotDocumentElement();
		Date result;

		final String createdDate=ballotContainer.getBallotDocumentElement().getCreatedDate();

		if(createdDate!= null && createdDate.length()>= YYYY_MM_DD.length()) {
			result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(createdDate);
		} else {
			final String systemDate = ballotDocumentElement.getSystemDate();

			if(systemDate!= null && systemDate.length()>= YYYY_MM_DD.length()) {
				result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(systemDate);
			} else {
				result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(ballotDocumentElement.getMadePublicDate());
			}
		}
		return result;
	}

	/**
	 * Check same date.
	 *
	 * @param voteList
	 *            the vote list
	 * @return the date
	 * @throws ParseException
	 *             the parse exception
	 */
	private static Date checkSameDate(final List<VoteDataDto> voteList) throws ParseException {
		final Set<String> set = new HashSet<>();
		Date result=null;

		for (final VoteDataDto voteData : voteList) {
			final String voteDate = voteData.getVoteDate();
			if (voteDate !=null && voteDate.length() >= YYYY_MM_DD.length()) {
				set.add(voteData.getVoteDate());
			}
		}

		if (set.size() ==CONTAINS_ONE) {
			final String dateString = set.iterator().next();
			result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(dateString);
		}
		return result;
	}

	/**
	 * Try to find valid vote date.
	 *
	 * @param ballotContainer
	 *            the ballot container
	 * @param voteDataList
	 *            the vote data list
	 * @return the date
	 * @throws ParseException
	 *             the parse exception
	 */
	public static Date tryToFindValidVoteDate(final BallotContainer ballotContainer, final List<VoteDataDto> voteDataList)
					throws ParseException {
		Date ballotDate;
		final Date sameDate = checkSameDate(voteDataList);

		if (sameDate != null) {
			ballotDate = sameDate;
		} else {
			ballotDate = bestGuessVoteDate(ballotContainer);
		}
		return ballotDate;
	}

}


text:
eval $(./scripts/ups_as_envs.py)

NEW_RELIC_CONFIG_FILE=newrelic.ini exec newrelic-admin run-program python application.py runprodserver


text:
/**
 * Item.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis WSDL2Java emitter.
 *
 * This was part of the web services demo files,
 * Keep this just in case we need it later
 */

package org.sakaiproject.tool.assessment.ws;

public class Item  implements java.io.Serializable {
    /**
	 *
	 */
	private static final long serialVersionUID = 4561525116839644989L;
	private java.lang.String itemid;
    private java.lang.String itemtext;
    private java.lang.String url;

    public Item() {
    }

    public java.lang.String getItemid() {
        return itemid;
    }

    public void setItemid(java.lang.String itemid) {
        this.itemid = itemid;
    }

    public java.lang.String getItemtext() {
        return itemtext;
    }

    public void setItemtext(java.lang.String itemtext) {
        this.itemtext = itemtext;
    }

    public java.lang.String getUrl() {
        return url;
    }

    public void setUrl(java.lang.String url) {
        this.url = url;
    }

}


text:
This repository contains a simple AndroidStudio project with a custom built CardView xml layout, and an Activity that shows it.

The sole purpouse of this repository is to give an example of how a CardView is built and how you can show it on screen as part of an activity.

The Image below shows the layout that I have built for the custom Card View:

![alt text][screenshot]
[screenshot]: http://i.imgur.com/vx5QCCu.png "Card View Screenshot"

PS: All images used on this example do not belong to me.

## Libraries used
To develop this example I've made use of these two libraries:

### Card View
To be able to use and manipulate CardViews in your project it is necessary to have the following dependecy added to your build.gradle(Module:app) file:
```
compile 'com.android.support:cardview-v7:24.2.1'
```
PS: As of 10.07.2016,the most recent version of the cardview support library is 24.2.1.

Depending on when you are vewing this example, a new version might already be avaiable. In such case Android Studio will advise you to change the version to the newest one.

PS2: This dependency is already added in this project.

### Caligraphy
I have also made use of the caligraphy library in order to help me use custom fonts: _Roboto-Bold_, _Roboto-Medium_ and _Roboto-Regular_

The Github page of the library is: https://github.com/chrisjenx/Calligraphy

You can easily use it in your project adding this line of code to your build.gradle(Module:app) dependencies:
```
compile 'uk.co.chrisjenx:calligraphy:2.2.0'
```
PS: This dependency is also already added in this project.


text:
/* global QUnit */

import { LineSegments } from '../../../../src/objects/LineSegments';

export default QUnit.module( 'Objects', () => {

	QUnit.module( 'LineSegments', () => {

		// INHERITANCE
		QUnit.todo( "Extending", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		// INSTANCING
		QUnit.todo( "Instancing", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		// PUBLIC STUFF
		QUnit.todo( "isLineSegments", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

	} );

} );


text:
class DkNemidUser < ActiveRecord::Base
  devise :dk_nemid, :authentication_keys => [:identifier]

  attr_accessible :identifier, :user, :cvr, :cpr
  belongs_to :user

end


text:
require 'conject/utilities'
class Class
  def object_peers(*syms)
    if !syms.empty?
      @_conject_object_peers = syms
    end
    @_conject_object_peers || []
  end
end