text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.cfk.xiaov.ui.activity.RegisterByPhoneActivity"
    tools:layout_editor_absoluteY="25dp">

    <include
        layout="@layout/include_toolbar"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="52dp"
        android:orientation="vertical"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical"
                    android:orientation="horizontal"
                    android:paddingLeft="10dp"
                    android:paddingRight="10dp">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="10dp"
                        android:text="@string/nickname"
                        android:textColor="@color/black0"
                        android:textSize="14sp" />

                    <EditText
                        android:id="@+id/etNick"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@null"
                        android:hint="例如:陈晨"
                        android:padding="10dp"
                        android:textColorHint="@color/gray3"
                        android:textSize="14sp" />

                </LinearLayout>

                <View
                    android:id="@+id/vLineNick"
                    style="@style/Line" />
            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/llArea"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="10dp"
                android:text="@string/area"
                android:textColor="@color/black0"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/tvArea"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="中国"
                android:textColor="?attr/colorPrimary"
                android:textSize="14sp" />

        </LinearLayout>

        <View style="@style/Line" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            android:paddingLeft="10dp"
            android:paddingRight="10dp">

            <TextView
                android:id="@+id/tvAreaCode"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp"
                android:padding="10dp"
                android:text="+86"
                android:textColor="@color/black0"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/etPhone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@null"
                android:hint="你的手机号码"
                android:inputType="phone"
                android:padding="10dp"
                android:text=""
                android:textColorHint="@color/gray3"
                android:textSize="14sp" />

        </LinearLayout>

        <View
            android:id="@+id/vLinePhone"
            style="@style/Line" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            android:paddingLeft="10dp"
            android:paddingRight="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp"
                android:padding="10dp"
                android:text="@string/verification_code"
                android:textColor="@color/black0"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/etVerifyCode"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@null"
                android:hint="请输入验证码"
                android:padding="10dp"
                android:text=""
                android:textColorHint="@color/gray3"
                android:textSize="14sp" />

            <Button
                android:id="@+id/btnGetCode"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/selector_register_send_code"
                android:text="获取验证码"
                android:textColor="@color/white"
                android:textSize="14sp" />

        </LinearLayout>

        <View
            android:id="@+id/vLineVertifyCode"
            style="@style/Line" />

        <Button
            android:id="@+id/btnRegister"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="30dp"
            android:background="@drawable/selector_login_btn"
            android:enabled="false"
            android:text="注册"
            android:textColor="@color/selector_login_btn"
            android:textSize="16sp" />
    </LinearLayout>

    <TextView
        android:id="@+id/tvRegisterByNormal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="60dp"
        android:padding="10dp"
        android:text="普通方式注册"
        android:textColor="@color/colorAccent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>


text:
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.pgm.http.jetty;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;

import com.google.common.base.Charsets;
import com.google.common.base.Objects;
import com.google.common.escape.Escaper;
import com.google.common.html.HtmlEscapers;
import com.google.common.io.ByteStreams;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.launcher.GerritLauncher;
import com.google.gerrit.reviewdb.client.AuthType;
import com.google.gerrit.server.config.ConfigUtil;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.util.TimeUtil;
import com.google.gwtexpui.linker.server.UserAgentRule;
import com.google.gwtexpui.server.CacheHeaders;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.google.inject.servlet.GuiceFilter;
import com.google.inject.servlet.GuiceServletContextListener;

import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.ForwardedRequestCustomizer;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.util.RawParseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Singleton
public class JettyServer {
  private static final Logger log = LoggerFactory.getLogger(JettyServer.class);

  static class Lifecycle implements LifecycleListener {
    private final JettyServer server;

    @Inject
    Lifecycle(final JettyServer server) {
      this.server = server;
    }

    @Override
    public void start() {
      try {
        server.httpd.start();
      } catch (Exception e) {
        throw new IllegalStateException("Cannot start HTTP daemon", e);
      }
    }

    @Override
    public void stop() {
      try {
        server.httpd.stop();
        server.httpd.join();
      } catch (Exception e) {
        throw new IllegalStateException("Cannot stop HTTP daemon", e);
      }
    }
  }

  private final SitePaths site;
  private final Server httpd;

  private boolean reverseProxy;

  /** Location on disk where our WAR file was unpacked to. */
  private Resource baseResource;

  @Inject
  JettyServer(@GerritServerConfig final Config cfg, final SitePaths site,
      final JettyEnv env)
      throws MalformedURLException, IOException {
    this.site = site;

    httpd = new Server(threadPool(cfg));
    httpd.setConnectors(listen(httpd, cfg));

    Handler app = makeContext(env, cfg);
    if (cfg.getBoolean("httpd", "requestLog", !reverseProxy)) {
      RequestLogHandler handler = new RequestLogHandler();
      handler.setRequestLog(new HttpLog(site, cfg));
      handler.setHandler(app);
      app = handler;
    }

    httpd.setHandler(app);
    httpd.setStopAtShutdown(false);
  }

  private Connector[] listen(Server server, Config cfg) {
    // OpenID and certain web-based single-sign-on products can cause
    // some very long headers, especially in the Referer header. We
    // need to use a larger default header size to ensure we have
    // the space required.
    //
    final int requestHeaderSize =
        cfg.getInt("httpd", "requestheadersize", 16386);
    final URI[] listenUrls = listenURLs(cfg);
    final boolean reuseAddress = cfg.getBoolean("httpd", "reuseaddress", true);
    final int acceptors = cfg.getInt("httpd", "acceptorThreads", 2);
    final AuthType authType = ConfigUtil.getEnum(cfg, "auth", null, "type", AuthType.OPENID);

    reverseProxy = isReverseProxied(listenUrls);
    final Connector[] connectors = new Connector[listenUrls.length];
    for (int idx = 0; idx < listenUrls.length; idx++) {
      final URI u = listenUrls[idx];
      final int defaultPort;
      final ServerConnector c;
      HttpConfiguration config = defaultConfig(requestHeaderSize);

      if (AuthType.CLIENT_SSL_CERT_LDAP.equals(authType) && ! "https".equals(u.getScheme())) {
        throw new IllegalArgumentException("Protocol '" + u.getScheme()
            + "' " + " not supported in httpd.listenurl '" + u
            + "' when auth.type = '" + AuthType.CLIENT_SSL_CERT_LDAP.name()
            + "'; only 'https' is supported");
      }

      if ("http".equals(u.getScheme())) {
        defaultPort = 80;
        c = newServerConnector(server, acceptors, config);

      } else if ("https".equals(u.getScheme())) {
        SslContextFactory ssl = new SslContextFactory();
        final File keystore = getFile(cfg, "sslkeystore", "etc/keystore");
        String password = cfg.getString("httpd", null, "sslkeypassword");
        if (password == null) {
          password = "gerrit";
        }
        ssl.setKeyStorePath(keystore.getAbsolutePath());
        ssl.setTrustStorePath(keystore.getAbsolutePath());
        ssl.setKeyStorePassword(password);
        ssl.setTrustStorePassword(password);

        if (AuthType.CLIENT_SSL_CERT_LDAP.equals(authType)) {
          ssl.setNeedClientAuth(true);

          File crl = getFile(cfg, "sslcrl", "etc/crl.pem");
          if (crl.exists()) {
            ssl.setCrlPath(crl.getAbsolutePath());
            ssl.setValidatePeerCerts(true);
          }
        }

        defaultPort = 443;

        config.addCustomizer(new SecureRequestCustomizer());
        c = new ServerConnector(server,
            null, null, null, 0, acceptors,
            new SslConnectionFactory(ssl, "http/1.1"),
            new HttpConnectionFactory(config));

      } else if ("proxy-http".equals(u.getScheme())) {
        defaultPort = 8080;
        config.addCustomizer(new ForwardedRequestCustomizer());
        c = newServerConnector(server, acceptors, config);

      } else if ("proxy-https".equals(u.getScheme())) {
        defaultPort = 8080;
        config.addCustomizer(new ForwardedRequestCustomizer());
        config.addCustomizer(new HttpConfiguration.Customizer() {
          @Override
          public void customize(Connector connector,
              HttpConfiguration channelConfig, Request request) {
            request.setScheme(HttpScheme.HTTPS.asString());
            request.setSecure(true);
          }
        });
        c = newServerConnector(server, acceptors, config);

      } else {
        throw new IllegalArgumentException("Protocol '" + u.getScheme() + "' "
            + " not supported in httpd.listenurl '" + u + "';"
            + " only 'http', 'https', 'proxy-http, 'proxy-https'"
            + " are supported");
      }

      try {
        if (u.getHost() == null && (u.getAuthority().equals("*") //
            || u.getAuthority().startsWith("*:"))) {
          // Bind to all local addresses. Port wasn't parsed right by URI
          // due to the illegal host of "*" so replace with a legal name
          // and parse the URI.
          //
          final URI r =
              new URI(u.toString().replace('*', 'A')).parseServerAuthority();
          c.setHost(null);
          c.setPort(0 < r.getPort() ? r.getPort() : defaultPort);
        } else {
          final URI r = u.parseServerAuthority();
          c.setHost(r.getHost());
          c.setPort(0 < r.getPort() ? r.getPort() : defaultPort);
        }
      } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid httpd.listenurl " + u, e);
      }

      c.setReuseAddress(reuseAddress);
      connectors[idx] = c;
    }
    return connectors;
  }

  private static ServerConnector newServerConnector(Server server,
      int acceptors, HttpConfiguration config) {
    return new ServerConnector(server, null, null, null, 0, acceptors,
        new HttpConnectionFactory(config));
  }

  private HttpConfiguration defaultConfig(int requestHeaderSize) {
    HttpConfiguration config = new HttpConfiguration();
    config.setRequestHeaderSize(requestHeaderSize);
    config.setSendServerVersion(false);
    config.setSendDateHeader(true);
    return config;
  }

  static boolean isReverseProxied(final URI[] listenUrls) {
    for (URI u : listenUrls) {
      if ("http".equals(u.getScheme()) || "https".equals(u.getScheme())) {
        return false;
      }
    }
    return true;
  }

  static URI[] listenURLs(final Config cfg) {
    String[] urls = cfg.getStringList("httpd", null, "listenurl");
    if (urls.length == 0) {
      urls = new String[] {"http://*:8080/"};
    }

    final URI[] r = new URI[urls.length];
    for (int i = 0; i < r.length; i++) {
      final String s = urls[i];
      try {
        r[i] = new URI(s);
      } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid httpd.listenurl " + s, e);
      }
    }
    return r;
  }

  private File getFile(final Config cfg, final String name, final String def) {
    String path = cfg.getString("httpd", null, name);
    if (path == null || path.length() == 0) {
      path = def;
    }
    return site.resolve(path);
  }

  private ThreadPool threadPool(Config cfg) {
    int maxThreads = cfg.getInt("httpd", null, "maxthreads", 25);
    int minThreads = cfg.getInt("httpd", null, "minthreads", 5);
    int maxCapacity = cfg.getInt("httpd", null, "maxqueued", 50);
    int idleTimeout = (int)MILLISECONDS.convert(60, SECONDS);
    QueuedThreadPool pool = new QueuedThreadPool(
        maxThreads,
        minThreads,
        idleTimeout,
        new BlockingArrayQueue<Runnable>(
            minThreads, // capacity,
            minThreads, // growBy,
            maxCapacity // maxCapacity
    ));
    pool.setName("HTTP");
    return pool;
  }

  private Handler makeContext(final JettyEnv env, final Config cfg)
      throws MalformedURLException, IOException {
    final Set<String> paths = new HashSet<String>();
    for (URI u : listenURLs(cfg)) {
      String p = u.getPath();
      if (p == null || p.isEmpty()) {
        p = "/";
      }
      while (1 < p.length() && p.endsWith("/")) {
        p = p.substring(0, p.length() - 1);
      }
      paths.add(p);
    }

    final List<ContextHandler> all = new ArrayList<ContextHandler>();
    for (String path : paths) {
      all.add(makeContext(path, env, cfg));
    }

    if (all.size() == 1) {
      // If we only have one context path in our web space, return it
      // without any wrapping so Jetty has less work to do per-request.
      //
      return all.get(0);
    } else {
      // We have more than one path served out of this container so
      // combine them in a handler which supports dispatching to the
      // individual contexts.
      //
      final ContextHandlerCollection r = new ContextHandlerCollection();
      r.setHandlers(all.toArray(new Handler[0]));
      return r;
    }
  }

  private ContextHandler makeContext(final String contextPath,
      final JettyEnv env, final Config cfg) throws MalformedURLException, IOException {
    final ServletContextHandler app = new ServletContextHandler();

    // This enables the use of sessions in Jetty, feature available
    // for Gerrit plug-ins to enable user-level sessions.
    //
    app.setSessionHandler(new SessionHandler());
    app.setErrorHandler(new HiddenErrorHandler());

    // This is the path we are accessed by clients within our domain.
    //
    app.setContextPath(contextPath);

    // Serve static resources directly from our JAR. This way we don't
    // need to unpack them into yet another temporary directory prior to
    // serving to clients.
    //
    app.setBaseResource(getBaseResource(app));

    // HTTP front-end filter to be used as surrogate of Apache HTTP
    // reverse-proxy filtering.
    // It is meant to be used as simpler tiny deployment of custom-made
    // security enforcement (Security tokens, IP-based security filtering, others)
    String filterClassName = cfg.getString("httpd", null, "filterClass");
    if (filterClassName != null) {
      try {
        @SuppressWarnings("unchecked")
        Class<? extends Filter> filterClass =
            (Class<? extends Filter>) Class.forName(filterClassName);
        Filter filter = env.webInjector.getInstance(filterClass);
        app.addFilter(new FilterHolder(filter), "/*",
            EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
      } catch (Throwable e) {
        String errorMessage =
            "Unable to instantiate front-end HTTP Filter " + filterClassName;
        log.error(errorMessage, e);
        throw new IllegalArgumentException(errorMessage, e);
      }
    }

    // Perform the same binding as our web.xml would do, but instead
    // of using the listener to create the injector pass the one we
    // already have built.
    //
    GuiceFilter filter = env.webInjector.getInstance(GuiceFilter.class);
    app.addFilter(new FilterHolder(filter), "/*", EnumSet.of(
        DispatcherType.REQUEST,
        DispatcherType.ASYNC));
    app.addEventListener(new GuiceServletContextListener() {
      @Override
      protected Injector getInjector() {
        return env.webInjector;
      }
    });

    // Jetty requires at least one servlet be bound before it will
    // bother running the filter above. Since the filter has all
    // of our URLs except the static resources, the only servlet
    // we need to bind is the default static resource servlet from
    // the Jetty container.
    //
    final ServletHolder ds = app.addServlet(DefaultServlet.class, "/");
    ds.setInitParameter("dirAllowed", "false");
    ds.setInitParameter("redirectWelcome", "false");
    ds.setInitParameter("useFileMappedBuffer", "false");
    ds.setInitParameter("gzip", "true");

    app.setWelcomeFiles(new String[0]);
    return app;
  }

  private Resource getBaseResource(ServletContextHandler app)
      throws IOException {
    if (baseResource == null) {
      try {
        baseResource = unpackWar(GerritLauncher.getDistributionArchive());
      } catch (FileNotFoundException err) {
        if (GerritLauncher.NOT_ARCHIVED.equals(err.getMessage())) {
          baseResource = useDeveloperBuild(app);
        } else {
          throw err;
        }
      }
    }
    return baseResource;
  }

  private static Resource unpackWar(File srcwar) throws IOException {
    File dstwar = makeWarTempDir();
    unpack(srcwar, dstwar);
    return Resource.newResource(dstwar.toURI());
  }

  private static File makeWarTempDir() throws IOException {
    // Obtain our local temporary directory, but it comes back as a file
    // so we have to switch it to be a directory post creation.
    //
    File dstwar = GerritLauncher.createTempFile("gerrit_", "war");
    if (!dstwar.delete() || !dstwar.mkdir()) {
      throw new IOException("Cannot mkdir " + dstwar.getAbsolutePath());
    }

    // Jetty normally refuses to serve out of a symlinked directory, as
    // a security feature. Try to resolve out any symlinks in the path.
    //
    try {
      return dstwar.getCanonicalFile();
    } catch (IOException e) {
      return dstwar.getAbsoluteFile();
    }
  }

  private static void unpack(File srcwar, File dstwar) throws IOException {
    final ZipFile zf = new ZipFile(srcwar);
    try {
      final Enumeration<? extends ZipEntry> e = zf.entries();
      while (e.hasMoreElements()) {
        final ZipEntry ze = e.nextElement();
        final String name = ze.getName();

        if (ze.isDirectory()) continue;
        if (name.startsWith("WEB-INF/")) continue;
        if (name.startsWith("META-INF/")) continue;
        if (name.startsWith("com/google/gerrit/launcher/")) continue;
        if (name.equals("Main.class")) continue;

        final File rawtmp = new File(dstwar, name);
        mkdir(rawtmp.getParentFile());
        rawtmp.deleteOnExit();

        final FileOutputStream rawout = new FileOutputStream(rawtmp);
        try {
          final InputStream in = zf.getInputStream(ze);
          try {
            final byte[] buf = new byte[4096];
            int n;
            while ((n = in.read(buf, 0, buf.length)) > 0) {
              rawout.write(buf, 0, n);
            }
          } finally {
            in.close();
          }
        } finally {
          rawout.close();
        }
      }
    } finally {
      zf.close();
    }
  }

  private static void mkdir(File dir) throws IOException {
    if (!dir.isDirectory()) {
      mkdir(dir.getParentFile());
      if (!dir.mkdir())
        throw new IOException("Cannot mkdir " + dir.getAbsolutePath());
      dir.deleteOnExit();
    }
  }

  private Resource useDeveloperBuild(ServletContextHandler app)
      throws IOException {
    final File dir = GerritLauncher.getDeveloperBuckOut();
    final File gen = new File(dir, "gen");
    final File root = dir.getParentFile();
    final File dstwar = makeWarTempDir();
    File ui = new File(dstwar, "gerrit_ui");
    File p = new File(ui, "permutations");
    mkdir(ui);
    p.createNewFile();
    p.deleteOnExit();

    app.addFilter(new FilterHolder(new Filter() {
      private final UserAgentRule rule = new UserAgentRule();
      private String lastTarget;
      private long lastTime;

      @Override
      public void doFilter(ServletRequest request, ServletResponse res,
          FilterChain chain) throws IOException, ServletException {
        String pkg = "gerrit-gwtui";
        String target = "ui_" + rule.select((HttpServletRequest) request);
        String rule = "//" + pkg + ":" + target;
        File zip = new File(new File(gen, pkg), target + ".zip");

        synchronized (this) {
          try {
            build(root, gen, rule);
          } catch (BuildFailureException e) {
            displayFailure(rule, e.why, (HttpServletResponse) res);
            return;
          }

          if (!target.equals(lastTarget) || lastTime != zip.lastModified()) {
            lastTarget = target;
            lastTime = zip.lastModified();
            unpack(zip, dstwar);
          }
        }

        chain.doFilter(request, res);
      }

      private void displayFailure(String rule, byte[] why, HttpServletResponse res)
          throws IOException {
        res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        res.setContentType("text/html");
        res.setCharacterEncoding(Charsets.UTF_8.name());
        CacheHeaders.setNotCacheable(res);

        Escaper html = HtmlEscapers.htmlEscaper();
        PrintWriter w = res.getWriter();
        w.write("<html><title>BUILD FAILED</title><body>");
        w.format("<h1>%s FAILED</h1>", html.escape(rule));
        w.write("<pre>");
        w.write(html.escape(RawParseUtils.decode(why)));
        w.write("</pre>");
        w.write("</body></html>");
        w.close();
      }

      @Override
      public void init(FilterConfig config) {
      }

      @Override
      public void destroy() {
      }
    }), "/", EnumSet.of(DispatcherType.REQUEST));
    return Resource.newResource(dstwar.toURI());
  }

  private static void build(File root, File gen, String target)
      throws IOException, BuildFailureException {
    log.info("buck build " + target);
    Properties properties = loadBuckProperties(gen);
    String buck = Objects.firstNonNull(properties.getProperty("buck"), "buck");
    ProcessBuilder proc = new ProcessBuilder(buck, "build", target)
        .directory(root)
        .redirectErrorStream(true);
    if (properties.containsKey("PATH")) {
      proc.environment().put("PATH", properties.getProperty("PATH"));
    }
    long start = TimeUtil.nowMs();
    Process rebuild = proc.start();
    byte[] out;
    InputStream in = rebuild.getInputStream();
    try {
      out = ByteStreams.toByteArray(in);
    } finally {
      rebuild.getOutputStream().close();
      in.close();
    }

    int status;
    try {
      status = rebuild.waitFor();
    } catch (InterruptedException e) {
      throw new InterruptedIOException("interrupted waiting for " + buck);
    }
    if (status != 0) {
      throw new BuildFailureException(out);
    }

    long time = TimeUtil.nowMs() - start;
    log.info(String.format("UPDATED    %s in %.3fs", target, time / 1000.0));
  }

  private static Properties loadBuckProperties(File gen)
      throws FileNotFoundException, IOException {
    Properties properties = new Properties();
    InputStream in = new FileInputStream(
        new File(new File(gen, "tools"), "buck.properties"));
    try {
      properties.load(in);
    } finally {
      in.close();
    }
    return properties;
  }

  @SuppressWarnings("serial")
  private static class BuildFailureException extends Exception {
    final byte[] why;

    BuildFailureException(byte[] why) {
      this.why = why;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Iot.Common
{
    using System;
    using System.Fabric;
    using System.Linq;
    using Microsoft.ServiceFabric.Services.Client;

    /// <summary>
    /// http://fabric/app/service/#/partitionkey/any|primary|secondary/endpoint-name/api-path
    /// </summary>
    public class HttpServiceUriBuilder
    {
        private const short FabricSchemeLength = 8;

        public HttpServiceUriBuilder()
        {
            this.Scheme = "http";
            this.Host = "fabric";
            this.Target = HttpServiceUriTarget.Default;
        }

        public HttpServiceUriBuilder(string uri)
            : this(new Uri(uri, UriKind.Absolute))
        {
        }

        public HttpServiceUriBuilder(Uri uri)
        {
            this.Scheme = uri.Scheme;
            this.Host = uri.Host;
            this.ServiceName = new Uri("fabric:" + uri.AbsolutePath.TrimEnd('/'));

            string path = uri.Fragment.Remove(0, 2);
            string[] segments = path.Split('/');

            long int64PartitionKey;
            this.PartitionKey = Int64.TryParse(segments[0], out int64PartitionKey)
                ? new ServicePartitionKey(int64PartitionKey)
                : String.IsNullOrEmpty(segments[0])
                    ? new ServicePartitionKey()
                    : new ServicePartitionKey(segments[0]);

            HttpServiceUriTarget target;
            if (!Enum.TryParse<HttpServiceUriTarget>(segments[1], true, out target))
            {
                throw new ArgumentException();
            }

            this.Target = target;
            this.EndpointName = segments[2];
            this.ServicePathAndQuery = String.Join("/", segments.Skip(3));
        }

        public string Scheme { get; private set; }

        public string Host { get; private set; }

        public Uri ServiceName { get; private set; }

        public ServicePartitionKey PartitionKey { get; private set; }

        public HttpServiceUriTarget Target { get; private set; }

        public string EndpointName { get; private set; }

        public string ServicePathAndQuery { get; private set; }

        public override string ToString()
        {
            return base.ToString();
        }

        public Uri Build()
        {
            if (this.ServiceName == null)
            {
                throw new UriFormatException("Service name is null.");
            }

            UriBuilder builder = new UriBuilder();
            builder.Scheme = String.IsNullOrEmpty(this.Scheme) ? "http" : this.Scheme;
            builder.Host = String.IsNullOrEmpty(this.Host) ? "fabric" : this.Host;
            builder.Path = this.ServiceName.AbsolutePath.Trim('/') + '/';
            ;
            string partitionKey = this.PartitionKey == null || this.PartitionKey.Kind == ServicePartitionKind.Singleton
                ? String.Empty
                : this.PartitionKey.Value.ToString();

            builder.Fragment = $"/{partitionKey}/{this.Target.ToString()}/{this.EndpointName ?? String.Empty}/{this.ServicePathAndQuery ?? String.Empty}";

            return builder.Uri;
        }

        public HttpServiceUriBuilder SetHost(string host)
        {
            this.Host = host?.ToLowerInvariant();
            return this;
        }

        public HttpServiceUriBuilder SetScheme(string scheme)
        {
            this.Scheme = scheme?.ToLowerInvariant();
            return this;
        }

        /// <summary>
        /// Fully-qualified service name URI: fabric:/name/of/service
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public HttpServiceUriBuilder SetServiceName(Uri serviceName)
        {
            if (serviceName != null)
            {
                if (!serviceName.IsAbsoluteUri)
                {
                    throw new UriFormatException("Service URI must be an absolute URI in the form 'fabric:/name/of/service");
                }

                if (!String.Equals(serviceName.Scheme, "fabric", StringComparison.OrdinalIgnoreCase))
                {
                    throw new UriFormatException("Scheme must be 'fabric'.");
                }
            }

            this.ServiceName = serviceName;

            return this;
        }

        /// <summary>
        /// Fully-qualified service name URI: fabric:/name/of/service
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public HttpServiceUriBuilder SetServiceName(string serviceName)
        {
            return this.SetServiceName(new Uri(serviceName, UriKind.Absolute));
        }

        public HttpServiceUriBuilder SetPartitionKey(string namedPartitionKey)
        {
            this.PartitionKey = new ServicePartitionKey(namedPartitionKey);
            return this;
        }

        public HttpServiceUriBuilder SetPartitionKey(long int64PartitionKey)
        {
            this.PartitionKey = new ServicePartitionKey(int64PartitionKey);
            return this;
        }

        public HttpServiceUriBuilder SetTarget(HttpServiceUriTarget target)
        {
            this.Target = target;
            return this;
        }

        public HttpServiceUriBuilder SetEndpointName(string endpointName)
        {
            this.EndpointName = endpointName;
            return this;
        }

        public HttpServiceUriBuilder SetServicePathAndQuery(string servicePathAndQuery)
        {
            this.ServicePathAndQuery = servicePathAndQuery;
            return this;
        }
    }
}


text:
package at.diamonddogs.data.parser;

/**
 * General parser proxy, clean interface that can be used to (de)serialize data
 *
 * @param <INPUT>
 *            the input type
 * @param <OUTPUT>
 *            the output type
 */
public abstract class ParserProxy<INPUT, OUTPUT> {

	/**
	 * The dataObject to be converted to INPUT
	 */
	protected OUTPUT dataObject;

	/**
	 * The source
	 */
	protected INPUT dataSource;

	/**
	 * Serializes the dataObject into an INPUT object
	 *
	 * @return the INPUT object
	 */
	public abstract INPUT serialize();

	/**
	 * Deserializes an input object into an output object
	 *
	 * @param input
	 *            the input object
	 * @return the output object
	 */
	public abstract OUTPUT deserialize(INPUT input);

	/**
	 * Gets the dataObject
	 *
	 * @return the dataObject
	 */
	public OUTPUT getDataObject() {
		return dataObject;
	}

	/**
	 * Sets the dataObject
	 *
	 * @param dataObject
	 *            the dataObject
	 */
	public void setDataObject(OUTPUT dataObject) {
		this.dataObject = dataObject;
	}
}


text:
package io.joern.scanners.c

import io.joern.suites.CQueryTestSuite

class SignedLeftShiftTests extends CQueryTestSuite(SignedLeftShift) {

  "find signed left shift" in {
    val query   = queryBundle.signedLeftShift()
    val results = findMatchingCalls(query)
    results shouldBe Set("bad1", "bad2", "bad3")
  }

}


text:
/** @babel */

import {
	CompositeDisposable,
	Disposable,
} from "atom";
import commands from "./commands";
import config from "./config";
import helper from "./helper";
import StatusBarManager from "./widgets/StatusBarManager";
import Notifications from "./Notifications";
import {promisify} from "promisificator";

export default {
	config,

	/**
	 * Activate package
	 * @return {void}
	 */
	activate() {
		this.updateConfig();

		this.disposables = new CompositeDisposable();
		this.contextMenuDisposables = {};
		this.confirmationDialogs = {};

		this.statusBarManager = new StatusBarManager();
		this.disposables.add(new Disposable(() => {
			this.statusBarManager.destroy();
			this.statusBarManager = null;
		}));

		for (const command in commands) {
			const cmd = commands[command];

			// observe confirm dialog settings
			if (cmd.confirm) {
				this.disposables.add(atom.config.observe(`git-menu.confirmationDialogs.${command}`, value => {
					this.confirmationDialogs[command] = value;
				}));
			} else {
				this.confirmationDialogs[command] = false;
			}

			// add command
			this.disposables.add(atom.commands.add("atom-workspace", `context-git:${command}`, {
				didDispatch: (event) => {
					Notifications.addError("Deprecated Command", "'context-git:*' commands are deprecated. Please use 'git-menu:*' instead.");
					return this.dispatchCommand(command, cmd)(event);
				},
				hiddenInCommandPalette: true,
			}));
			this.disposables.add(atom.commands.add("atom-workspace", `git-menu:${command}`, this.dispatchCommand(command, cmd)));

			if (cmd.label) {
				// add to context menu
				this.disposables.add(atom.config.observe(`git-menu.contextMenuItems.${command}`, value => {
					if (value) {
						this.contextMenuDisposables[command] = atom.contextMenu.add({
							"atom-workspace, atom-text-editor, .tree-view, .tab-bar": [{
								label: "Git",
								submenu: [{
									label: cmd.label.replace(/&/g, "&&"),
									command: `git-menu:${command}`,
								}],
							}],
						});
						this.disposables.add(this.contextMenuDisposables[command]);
					} else {
						if (this.contextMenuDisposables[command]) {
							this.disposables.remove(this.contextMenuDisposables[command]);
							this.contextMenuDisposables[command].dispose();
							delete this.contextMenuDisposables[command];
						}
					}
				}));
			}

			if (cmd.keymap) {
				// add key binding
				atom.keymaps.add("git-menu", {
					"atom-workspace": {
						[cmd.keymap]: `git-menu:${command}`,
					},
				});
			}
		}
	},

	/**
	 * Deactivate package
	 * @return {void}
	 */
	deactivate() {
		this.disposables.dispose();
	},

	/**
	 * Copy config from context-git to git-menu
	 * @return {void}
	 */
	updateConfig() {
		try {
			const hasGitMenuConfig = "git-menu" in atom.config.settings;
			const hasContextGitConfig = "context-git" in atom.config.settings;
			if (hasGitMenuConfig || !hasContextGitConfig) {
				return;
			}

			const contextGitConfig = atom.config.getAll("context-git");
			contextGitConfig.forEach((cfg) => {
				let {scopeSelector} = cfg;
				if (scopeSelector === "*") {
					scopeSelector = null;
				}
				for (const key in cfg.value) {
					const value = cfg.value[key];
					atom.config.set(`git-menu.${key}`, value, {scopeSelector});
				}
			});
		} catch (ex) {
			// fail silently
		}
	},

	/**
	 * Consume the status bar service
	 * @param  {mixed} statusBar Status bar service
	 * @return {void}
	 */
	statusBarService(statusBar) {
		if (this.statusBarManager) {
			this.statusBarManager.addStatusBar(statusBar);
		}
	},

	/**
	 * Consume the busy signal service
	 * @param  {mixed} busySignal Busy signal service
	 * @return {void}
	 */
	busySignalService(busySignal) {
		if (this.statusBarManager) {
			this.statusBarManager.addBusySignal(busySignal);
		}
	},

	dispatchCommand(command, cmd) {
		return async event => {
			try {
				this.statusBarManager.show(cmd.label, {revealTooltip: false});
				const filePaths = helper.getPaths(event.target);

				// show confirm dialog if applicable
				if (this.confirmationDialogs[command]) {
					const {message} = cmd.confirm;
					let {detail} = cmd.confirm;
					if (typeof detail === "function") {
						detail = await detail(filePaths);
					}

					const [confirmButton, hideDialog] = await promisify(atom.confirm.bind(atom), {rejectOnError: false, alwaysReturnArray: true})({
						type: "warning",
						checkboxLabel: "Never Show This Dialog Again",
						message,
						detail,
						buttons: [
							cmd.label,
							"Cancel",
						],
					});

					if (hideDialog) {
						atom.config.set(`git-menu.confirmationDialogs.${command}`, false);
					}
					if (confirmButton === 1) {
						return;
					}
				}

				try {
					// run command
					const {title, message} = await cmd.command(filePaths, this.statusBarManager);
					if (message) {
						Notifications.addSuccess(title, message);
					}
				} catch (err) {
					if (err) {
						const message = (err.stack ? err.stack : err.toString());
						Notifications.addError(`Git Menu: ${cmd.label}`, message);
					}
				}
			} finally {
				this.statusBarManager.hide();
			}
		};
	},
};


text:
using System;
using System.ComponentModel;

namespace VisualBasic6.Attributes
{
    /// <summary>
    /// Specifies the display name for a property, event,
    /// or public void method which takes no arguments.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
    sealed class LocDisplayNameAttribute : DisplayNameAttribute
    {
        readonly string name;

        /// <summary>
        /// Public constructor.
        /// </summary>
        /// <param name="name">Attribute display name.</param>
        public LocDisplayNameAttribute(string name)
        {
            this.name = name;
        }

        /// <summary>
        /// Gets attribute display name.
        /// </summary>
        public override string DisplayName
        {
            get
            {
                return Resources.GetString(name) ?? name;
            }
        }
    }
}


text: My test code for being able to sign/execute requests against AWS services.


text:
#ifndef DATATRANSFERUTILS_H
#define DATATRANSFERUTILS_H

#include <gutil/macros.h>

class QString;
class QByteArray;

NAMESPACE_GUTIL1(Qt);

/** A static class that declares functions which may help in
    transferring data from one place to another.
*/
class DataTransferUtils
{
public:

    /** Writes some data to a file in blocks of size 4096.
        It can work with the PubSubSystem class to report progress of the write.
        \todo Make the block size configurable
    */
    static void WriteDataToFileInChunks(const QString &filename,
                                        const QByteArray &data,
                                        bool *cancel_flag = 0);

    static void CopyFileInChunks(const QString &source,
                                 const QString &dest,
                                 bool *cancel_flag = 0);

    static QByteArray ReadDataFromFileInChunks(const QString &filename,
                                               bool *cancel_flag = 0);
};

END_NAMESPACE_GUTIL1;

#endif // DATATRANSFERUTILS_H


text:
'use strict';

var gulp = require('gulp'),
    through = require('through'),
    chalk = require('chalk'),
    gulpLoadPlugins = require('gulp-load-plugins');
var del = require('del');
var plugins = gulpLoadPlugins();
var paths = {
    js: ['*.js', 'test/**/*.js', '!test/coverage/**', '!bower_components/**', 'packages/**/*.js', '!packages/**/node_modules/**', '!packages/contrib/**/*.js', '!packages/contrib/**/node_modules/**'],
    html: ['packages/**/public/**/views/**', 'packages/**/server/views/**'],
    css: ['!bower_components/**', 'packages/**/public/**/css/*.css', '!packages/contrib/**/public/**/css/*.css'],
    less: ['**/public/**/css/*.less'],
    sass: ['**/public/**/css/*.scss']
};

var defaultTasks = ['clean', 'jshint', 'sass', 'csslint','develop','watch'];

gulp.task('clean', function (cb) {
  return del(['bower_components/build'], cb);
});

gulp.task('jshint', function () {
  return gulp.src(paths.js)
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('jshint-stylish'))
    .pipe(count('jshint', 'files lint free'));
});

gulp.task('sass', function () {
  return gulp.src(paths.sass)
    .pipe(plugins.sass().on('error', console.log))
    .pipe(gulp.dest('.'));
});

gulp.task('csslint', function () {
  return gulp.src(paths.css)
    .pipe(plugins.csslint('.csslintrc'))
    .pipe(plugins.csslint.reporter())
    .pipe(count('csslint', 'files lint free'));
});

gulp.task('develop', ['env:develop'], function () {
  plugins.nodemon({
    script: 'server.js',
    ext: 'html js',
    env: { 'NODE_ENV': 'development' } ,
    ignore: ['node_modules/'],
    execMap : { "js": "iojs --harmony "},
    nodeArgs: ['--debug']
  });

  gulp.start('frontend');
});

gulp.task('watch', function () {
  gulp.watch(paths.js, ['jshint']).on('change', plugins.livereload.changed);
  gulp.watch(paths.html).on('change', plugins.livereload.changed);
  gulp.watch(paths.css, ['csslint']).on('change', plugins.livereload.changed);
  gulp.watch(paths.sass, ['sass']).on('change', plugins.livereload.changed);
  gulp.watch(paths.less, ['less']).on('change', plugins.livereload.changed);

  plugins.livereload.listen({interval: 500});
});

gulp.task('frontend', defaultTasks);

function count(taskName, message) {
  var fileCount = 0;

  function countFiles(file) {
    fileCount++; // jshint ignore:line
  }

  function endStream() {
    console.log(chalk.cyan(taskName + ': ' + fileCount + ' ' + message || 'files processed.'));
    this.emit('end'); // jshint ignore:line
  }

  return through(countFiles, endStream);
}


text:
<!DOCTYPE html>

  <title>
    <%= webpackConfig.metadata.title %>
  </title>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimal-ui">
  <meta name="description" content="<%= webpackConfig.metadata.title %>">

  <link rel="manifest" href="/assets/manifest.json">

  <meta name="msapplication-TileColor" content="#00bcd4">
  <meta name="msapplication-TileImage" content="/assets/icon/ms-icon-144x144.png">
  <meta name="theme-color" content="#00bcd4">
  <meta http-equiv="cache-control" content="max-age=0" />
  <meta http-equiv="cache-control" content="no-cache" />
  <meta http-equiv="expires" content="0" />
  <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
  <meta http-equiv="pragma" content="no-cache" />

  <base href="<%= webpackConfig.metadata.baseUrl %>">

      <% if (webpackConfig.metadata.ENV === 'development') { %>

        <% } %>


text:
from nova.scheduler.filters import exact_ram_filter
from nova import test
from nova.tests.unit.scheduler import fakes

class TestRamFilter(test.NoDBTestCase):

    def setUp(self):
        super(TestRamFilter, self).setUp()
        self.filt_cls = exact_ram_filter.ExactRamFilter()

    def test_exact_ram_filter_passes(self):
        filter_properties = {'instance_type': {'memory_mb': 1024}}
        host = self._get_host({'free_ram_mb': 1024})
        self.assertTrue(self.filt_cls.host_passes(host, filter_properties))

    def test_exact_ram_filter_fails(self):
        filter_properties = {'instance_type': {'memory_mb': 512}}
        host = self._get_host({'free_ram_mb': 1024})
        self.assertFalse(self.filt_cls.host_passes(host, filter_properties))

    def _get_host(self, host_attributes):
        return fakes.FakeHostState('host1', 'node1', host_attributes)


text:
namespace iresearch {

// ----------------------------------------------------------------------------
// --SECTION--                                             Java style iterators
// ----------------------------------------------------------------------------

template<typename T>
struct IRESEARCH_API_TEMPLATE iterator {
  virtual ~iterator() = default;
  virtual T value() const = 0;
  virtual bool next() = 0;
};

template<
  typename Key,
  typename Value,
  typename Base,
  typename Less = std::less<Key>
> class iterator_adaptor
    : public Base,
      private irs::compact<0, Less> {
 private:
  typedef irs::compact<0, Less> comparer_t;

 public:
  typedef Value value_type;
  typedef Key key_type;
  typedef const value_type* const_pointer;
  typedef const value_type& const_reference;

  iterator_adaptor(
      const_pointer begin,
      const_pointer end,
      const Less& less = Less())
    : comparer_t(less),
      begin_(begin),
      cur_(begin),
      end_(end) {
  }

  const_reference value() const noexcept override {
    return *cur_;
  }

  bool seek(const key_type& key) noexcept override {
    begin_ = std::lower_bound(cur_, end_, key, comparer_t::get());
    return next();
  }

  bool next() noexcept override {
    if (begin_ == end_) {
      cur_ = begin_; // seal iterator
      return false;
    }

    cur_ = begin_++;
    return true;
  }

 private:
  const_pointer begin_;
  const_pointer cur_;
  const_pointer end_;
}; // iterator_adaptor

// ----------------------------------------------------------------------------
// --SECTION--                                              C++ style iterators
// ----------------------------------------------------------------------------

namespace detail {

template<typename SmartPtr>
struct extract_element_type {
  typedef typename SmartPtr::element_type value_type;
  typedef typename SmartPtr::element_type& reference;
  typedef typename SmartPtr::element_type* pointer;
};

template<typename SmartPtr>
struct extract_element_type<const SmartPtr> {
  typedef const typename SmartPtr::element_type value_type;
  typedef const typename SmartPtr::element_type& reference;
  typedef const typename SmartPtr::element_type* pointer;
};

}

//////////////////////////////////////////////////////////////////////////////
/// @class const_ptr_iterator
/// @brief iterator adapter for containers with the smart pointers
//////////////////////////////////////////////////////////////////////////////
template<typename IteratorImpl>
class ptr_iterator
  : public ::boost::iterator_facade<
     ptr_iterator<IteratorImpl>,
     typename detail::extract_element_type<typename std::remove_reference<
       typename IteratorImpl::reference>::type
     >::value_type,
     ::boost::random_access_traversal_tag > {
 private:
  typedef detail::extract_element_type<
    typename std::remove_reference<typename IteratorImpl::reference>::type
  > element_type;

  typedef ::boost::iterator_facade<
     ptr_iterator<IteratorImpl>,
     typename detail::extract_element_type<typename std::remove_reference<
       typename IteratorImpl::reference>::type
     >::value_type,
     ::boost::random_access_traversal_tag > base;

  typedef typename base::iterator_facade_ iterator_facade;

  typedef typename element_type::value_type base_element_type;

  template<typename T>
  struct adjust_const
    : irstd::adjust_const<typename element_type::value_type, T> { };

 public:
  typedef typename iterator_facade::reference reference;
  typedef typename iterator_facade::difference_type difference_type;

  // -----------------------------------------------------------------------------
  // --SECTION--                                      constructors and destructors
  // -----------------------------------------------------------------------------

  ptr_iterator( const IteratorImpl& it ) : it_( it ) {}

  // -----------------------------------------------------------------------------
  // --SECTION--                                                   cast operations
  // -----------------------------------------------------------------------------

  //////////////////////////////////////////////////////////////////////////////
  /// @brief returns downcasted reference to the iterator's value
  //////////////////////////////////////////////////////////////////////////////
  template<typename T>
  typename adjust_const<T>::reference as() const {
    typedef typename std::enable_if<
      std::is_base_of< base_element_type, T >::value, T
    >::type type;

#ifdef IRESEARCH_DEBUG
    return dynamic_cast<typename adjust_const<type>::reference>(dereference());
#else
    return static_cast<typename adjust_const<type>::reference>(dereference());
#endif // IRESEARCH_DEBUG
  }

  //////////////////////////////////////////////////////////////////////////////
  /// @brief returns downcasted pointer to the iterator's value
  ///        or nullptr if there is no available conversion
  //////////////////////////////////////////////////////////////////////////////
  template<typename T>
  typename adjust_const<T>::pointer safe_as() const {
    typedef typename std::enable_if<
      std::is_base_of< base_element_type, T >::value, T
    >::type type;

    reference it = dereference();
    return dynamic_cast<typename adjust_const<type>::pointer>(&it);
  }

 private:
  friend class ::boost::iterator_core_access;

  reference dereference() const {
    assert( *it_ );
    return **it_;
  }
  void advance( difference_type n ) { it_ += n; }
  difference_type distance_to( const ptr_iterator& rhs ) const {
    return rhs.it_ - it_;
  }
  void increment() { ++it_; }
  void decrement() { --it_; }
  bool equal( const ptr_iterator& rhs ) const {
    return it_ == rhs.it_;
  }

  IteratorImpl it_;
};

}

#endif


text:
# Bespoken

Learn how to use Bespoken Analytics for your Alexa Skills and Google Actions built with Jovo.

* [About Bespoken](#about-bespoken)
* [Installation](#bespoken)
   * [Create a Bespoken Dashboard Account](#create-a-bespoken-dashboard-account)
   * [Enable Bespoken Analytics](#enable-bespoken-analytics)
   * [Test Bespoken](#test-bespoken)

## About Bespoken

![Bespoken Website](../../img/bespoken-home.jpg)

[Bespoken](https://bespoken.io/) offers monitoring and testing tools for voice apps, including a command line interface, logging, and unit testing.

With the Bespoken Analytics integration for Jovo, you can get access to logging and monitoring features for your Alexa Skills and Google Actions.

## Installation

To use Bespoken Analytics for your voice app, you need to complete the following steps:

1. Create a Bespoken Dashboard account
2. Enable Bespoken Analytics in your Jovo voice app
3. Test your app

### Create a Bespoken Dashboard Account

1. Create a Bespoken account or log in at https://apps.bespoken.io/dashboard/.

2. Click the plus sign on the Home page:

![Bespoken Add a Skill or Action](../../img/bespoken-dashboard.jpg)

3. Set the name for your app and click on "Validate your new skill"
![Bespoken Set source name](../../img/bespoken-dashboard-create.jpg)

4. Click on "Get Started" to the right
![Bespoken Get Started](../../img/bespoken-dashboard-main.jpg)

5. Copy the Secret Key as shown below
![Bespoken Key](../../img/bespoken-dashboard-key.jpg)

### Enable Bespoken Analytics

You have to options to add Bespoken Analytics to your voice app:

* Use the Jovo app config
* Use the add commands

Below is an example for both:

```javascript
// Option 1: Use the Jovo app config
const config = {
    /**
     * Other settings
     */
    analytics: {
        services: {
            BespokenAlexa: {
                key: '<key>',
            },
            BespokenGoogleAction: {
                key: '<key>',
            },
        },
    },
};

// Option 2: Use the add command
app.addBespokenAnalytics(key);
```

### Test Bespoken

Test your voice app, after a bit your session should appear in the created skill.

<!--[metadata]: {"description": "Add Bespoken Analytics to your Alexa Skills and Google Actions with Jovo",
"route": "analytics/bespoken" }-->


text:
package com.adben.testdatabuilder.core.analyzers.generators.generator;

import static com.adben.testdatabuilder.core.helper.ReflectionHelper.getClz;
import static java.lang.System.currentTimeMillis;
import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import org.slf4j.Logger;

/**
 * {@link com.adben.testdatabuilder.core.analyzers.generators.Generator Generator} for {@link
 * Timestamp}.
 *
 *

 *
 * Gets the timestamp from the return generatedValue of {@link System#currentTimeMillis()}.
 */
public class TimestampGenerator extends AbstractGenerator<Timestamp> {

  private static final Logger LOGGER = getLogger(lookup().lookupClass());

  /**
   * Default constructor.
   */
  public TimestampGenerator() {
    super();
    LOGGER.trace("Default constructor");
  }

  /**
   * Applicable type is {@link Timestamp}.
   *
   *

   *
   * {@inheritDoc}
   */
  @Override
  protected boolean isApplicable(final Type type) {
    return Timestamp.class.isAssignableFrom(getClz(type));
  }

  /**
   * Get the next value for this generator, which is the current time millis.
   *
   *

   *
   * {@inheritDoc}
   */
  @Override
  protected Timestamp getNextValue(final Type type) {
    return new Timestamp(currentTimeMillis());
  }

}


text:
import os
from pathlib import Path
from . import models
from . import queues
from .content_types import guess_content_type

FOLDER = 'application/x-directory'

class Walker(object):

    def __init__(self, root, prefix, container_doc, collection):
        self.root = Path(root)
        self.prefix = Path(prefix) if prefix else None
        self.container_doc = container_doc
        self.documents = []
        self.collection = collection

    def record_document(self, new_doc, created):
        if self.container_doc:
            self.documents.append((new_doc, created))

    @classmethod
    def walk(cls, root, prefix, container_doc, collection):
        self = cls(root, prefix, container_doc, collection)
        try:
            first_item = self.root / self.prefix if self.prefix else self.root
            first_parent = self.container_doc
            self.handle(first_item, first_parent)
        except KeyboardInterrupt:
            pass
        return self.documents

    def _path(self, file):
        return file.relative_to(self.root)

    def handle(self, item, parent):
        print("WALK ENTER   ", str(self._path(item)))
        if item.is_dir():
            self.handle_folder(item, parent)
        else:
            self.handle_file(item, parent)
        print("WALK EXIT    ", str(self._path(item)))

    def handle_folder(self, folder, parent):
        path = self._path(folder)
        print("HANDLE FOLDER", str(path))
        if str(path) == '.':
            if self.container_doc:
                new_doc = self.container_doc
                created = True
            else:
                new_doc, created = models.Document.objects.get_or_create(
                    path='',
                    disk_size=0,
                    content_type=FOLDER,
                    filename='',
                    collection=self.collection,
                )
        else:
            new_doc, created = models.Document.objects.get_or_create(
                path=path,
                disk_size=0,
                content_type=FOLDER,
                filename=path.name,
                parent=parent,
                container=self.container_doc,
                collection=self.collection,
            )
            self.record_document(new_doc, created)

        folder_mtime = os.path.getmtime(str(folder.resolve()))
        if created or \
                not new_doc.digested_at or \
                new_doc.digested_at.timestamp() <= folder_mtime:
            if new_doc.path:  # avoid digesting / indexing the root
                queues.put('digest', {'id': new_doc.id})

        for child in folder.iterdir():
            self.handle(child, new_doc)

    def handle_file(self, file, parent):
        path = self._path(file)
        print("HANDLE FILE  ", str(path))
        new_doc, created = models.Document.objects.get_or_create(
            path=path,
            parent=parent,
            container=self.container_doc,
            collection=self.collection,
            defaults={
                'disk_size': file.stat().st_size,
                'content_type': guess_content_type(file.name),
                'filename': path.name,
            },
        )
        self.record_document(new_doc, created)
        file_mtime = os.path.getmtime(str(file.resolve()))
        if created or \
                not new_doc.digested_at or \
                new_doc.digested_at.timestamp() <= file_mtime:
            queues.put('digest', {'id': new_doc.id})

def files_in(doc):
    child_documents = models.Document.objects.filter(parent=doc)
    return [{
        'id': child.id,
        'filename': child.filename,
        'size': child.disk_size,
        'content_type': child.content_type,
    } for child in child_documents]

def _fix_mimetypes():
    for doc in models.Document.objects.iterator():
        if doc.content_type:
            lower_content_type = doc.content_type.lower()
            if doc.content_type != lower_content_type:
                print('lowercasing', doc.id, doc.content_type)
                doc.content_type = lower_content_type
                doc.save()

        else:
            if doc.container_id is None:
                content_type = guess_content_type(Path(doc.path).name)
                if content_type:
                    print('adding', doc.id, content_type)
                    doc.content_type = content_type
                    doc.save()


text:
package com.ibm.spark.kernel.protocol.v5.content

/**
 * Indicates that the implementation contains a method to return the type
 * string representing the object.
 */
trait TypeString {
  /**
   * Returns the type string associated with this object.
   *
   * @return The type as a string
   */
  def toTypeString: String
}


text:
exports.searchAndReplaceFiles = function(env, grunt) {
  var config = {
    test: {
      files: [{
        cwd: 'target/',
        src: ['**/*.js', '**/*.xml', '!node/node_modules/**/*.js'],
        dest: 'target/',
        expand: true,
      }],
      options: {
        replacements: [{
          pattern: 'VALUE TO BE REPLACED #1',
          replacement: '<%= grunt.template.today() %>_test'
        }, /*{
          pattern: 'VALUE TO BE REPLACED #2',
          replacement: 'REPLACE VALUE #2_TEST'
        }, { //fragment from common folder (Git submodule)
          pattern: '@@EXAMPLE-STEP-COMMON-XML-TO-JSON-GIT-SUBMODULE-FRAGMENT#1',
          replacement: "<%= grunt.file.read('common/apiproxy/proxies/xmltojson-js-steps-common-frag.xml') %>"
        }, { //fragment from common folder (Git submodule)
          pattern: '@@EXAMPLE-STEP-COMMON-XML-TO-JSON-GIT-SUBMODULE-FRAGMENT#2',
          replacement: "<%= grunt.file.read('common/apiproxy/proxies/xmltojson-js-steps-common-frag.xml') %>"
        }, { //fragment from common folder (Git submodule)
          pattern: '@@EXAMPLE-STEP-COMMON-XML-TO-JSON-GIT-SUBMODULE-FRAGMENT#3',
          replacement: "<%= grunt.file.read('common/apiproxy/proxies/xmltojson-js-steps-common-frag.xml') %>"
        }, {
          pattern: '@@XMLtoJSON-Common.xml',
          replacement: "<%= grunt.file.read('common/apiproxy/policies/XMLtoJSON-Common.xml') %>"
        }, { //fragment from common folder (Git submodule)
          pattern: '@@Script-External-Variables.xml',
          replacement: "<%= grunt.file.read('common/apiproxy/policies/Script-External-Variables.xml') %>"
        }, { //fragment from common folder (Git submodule)
          pattern: '@@js_external_vars.js',
          replacement: "<%= grunt.file.read('common/apiproxy/resources/jsc/js_external_vars.js') %>"
        }, {
          pattern: '@@JSON-to-XML.xml',
          replacement: "<%= grunt.file.read('common/apiproxy/policies/JSON-to-XML.xml') %>"
        },*/ ]
      }
    },
    prod: {
      files: [{
        cwd: 'target/',
        src: ['**/*.js', '**/*.xml', '!node/node_modules/**/*.js'],
        dest: 'target/',
        expand: true,
      }],
      options: {
        replacements: [{
          pattern: 'VALUE TO BE REPLACED #1',
          replacement: '<%= grunt.template.today() %>_test'
        }, /*{
          pattern: 'VALUE TO BE REPLACED #2',
          replacement: 'REPLACE VALUE #2_TEST'
        }, { //fragment from common folder (Git submodule)
          pattern: '@@EXAMPLE-STEP-COMMON-XML-TO-JSON-GIT-SUBMODULE-FRAGMENT#1',
          replacement: "<%= grunt.file.read('common/apiproxy/proxies/xmltojson-js-steps-common-frag.xml') %>"
        }, { //fragment from common folder (Git submodule)
          pattern: '@@EXAMPLE-STEP-COMMON-XML-TO-JSON-GIT-SUBMODULE-FRAGMENT#2',
          replacement: "<%= grunt.file.read('common/apiproxy/proxies/xmltojson-js-steps-common-frag.xml') %>"
        }, { //fragment from common folder (Git submodule)
          pattern: '@@EXAMPLE-STEP-COMMON-XML-TO-JSON-GIT-SUBMODULE-FRAGMENT#3',
          replacement: "<%= grunt.file.read('common/apiproxy/proxies/xmltojson-js-steps-common-frag.xml') %>"
        }, {
          pattern: '@@XMLtoJSON-Common.xml',
          replacement: "<%= grunt.file.read('common/apiproxy/policies/XMLtoJSON-Common.xml') %>"
        }, { //fragment from common folder (Git submodule)
          pattern: '@@Script-External-Variables.xml',
          replacement: "<%= grunt.file.read('common/apiproxy/policies/Script-External-Variables.xml') %>"
        }, { //fragment from common folder (Git submodule)
          pattern: '@@js_external_vars.js',
          replacement: "<%= grunt.file.read('common/apiproxy/resources/jsc/js_external_vars.js') %>"
        }, {
          pattern: '@@JSON-to-XML.xml',
          replacement: "<%= grunt.file.read('common/apiproxy/policies/JSON-to-XML.xml') %>"
        },*/ ]
      }
    },
  }
  if (!config[env]) grunt.fail.fatal('Environment ' + env + ' does not exist under grunt/search-and-replace-files.js')
  return (config[env])
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>iron Bank Network</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="vendor/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="vendor/simple-line-icons/css/simple-line-icons.css">
    <link href="//fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="//fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
    <link href="//fonts.googleapis.com/css?family=Muli" rel="stylesheet">

    <link rel="stylesheet" href="device-mockups/device-mockups.min.css">

    <link href="css/new-age.min.css" rel="stylesheet">

           iron Bank Network

              How it works

              Token

              Dapp

              White Paper

              Developers

 Agreements Library

All the power of Decentralized Banking in your hands.

 © iron Bank Network (2018). All rights reserved.


text:
package persistence

import (
	"bytes"
	"errors"
	"io"
	"io/ioutil"
	"strings"
	"time"
)

type BucketData map[string][]byte

// inMemoryObjectStore is a simple implementation of the ObjectStore interface
// that stores its data in-memory/in-proc. This is mainly intended to be used
// as a test fake.
type inMemoryObjectStore struct {
	Data map[string]BucketData
}

func newInMemoryObjectStore(buckets ...string) *inMemoryObjectStore {
	o := &inMemoryObjectStore{
		Data: make(map[string]BucketData),
	}

	for _, bucket := range buckets {
		o.Data[bucket] = make(map[string][]byte)
	}

	return o
}

//
// Interface Implementation
//

func (o *inMemoryObjectStore) Init(config map[string]string) error {
	return nil
}

func (o *inMemoryObjectStore) PutObject(bucket, key string, body io.Reader) error {
	bucketData, ok := o.Data[bucket]
	if !ok {
		return errors.New("bucket not found")
	}

	obj, err := ioutil.ReadAll(body)
	if err != nil {
		return err
	}

	bucketData[key] = obj

	return nil
}

func (o *inMemoryObjectStore) ObjectExists(bucket, key string) (bool, error) {
	bucketData, ok := o.Data[bucket]
	if !ok {
		return false, errors.New("bucket not found")
	}

	_, ok = bucketData[key]
	return ok, nil
}

func (o *inMemoryObjectStore) GetObject(bucket, key string) (io.ReadCloser, error) {
	bucketData, ok := o.Data[bucket]
	if !ok {
		return nil, errors.New("bucket not found")
	}

	obj, ok := bucketData[key]
	if !ok {
		return nil, errors.New("key not found")
	}

	return ioutil.NopCloser(bytes.NewReader(obj)), nil
}

func (o *inMemoryObjectStore) ListCommonPrefixes(bucket, prefix, delimiter string) ([]string, error) {
	keys, err := o.ListObjects(bucket, prefix)
	if err != nil {
		return nil, err
	}

	// For each key, check if it has an instance of the delimiter *after* the prefix.
	// If not, skip it; if so, return the prefix of the key up to/including the delimiter.

	var prefixes []string
	for _, key := range keys {
		// everything after 'prefix'
		afterPrefix := key[len(prefix):]

		// index of the *start* of 'delimiter' in 'afterPrefix'
		delimiterStart := strings.Index(afterPrefix, delimiter)
		if delimiterStart == -1 {
			continue
		}

		// return the prefix, plus everything after the prefix and before
		// the delimiter, plus the delimiter
		fullPrefix := prefix + afterPrefix[0:delimiterStart] + delimiter

		prefixes = append(prefixes, fullPrefix)
	}

	return prefixes, nil
}

func (o *inMemoryObjectStore) ListObjects(bucket, prefix string) ([]string, error) {
	bucketData, ok := o.Data[bucket]
	if !ok {
		return nil, errors.New("bucket not found")
	}

	var objs []string
	for key := range bucketData {
		if strings.HasPrefix(key, prefix) {
			objs = append(objs, key)
		}
	}

	return objs, nil
}

func (o *inMemoryObjectStore) DeleteObject(bucket, key string) error {
	bucketData, ok := o.Data[bucket]
	if !ok {
		return errors.New("bucket not found")
	}

	delete(bucketData, key)

	return nil
}

func (o *inMemoryObjectStore) CreateSignedURL(bucket, key string, ttl time.Duration) (string, error) {
	bucketData, ok := o.Data[bucket]
	if !ok {
		return "", errors.New("bucket not found")
	}

	_, ok = bucketData[key]
	if !ok {
		return "", errors.New("key not found")
	}

	return "a-url", nil
}

//
// Test Helper Methods
//

func (o *inMemoryObjectStore) ClearBucket(bucket string) {
	if _, ok := o.Data[bucket]; !ok {
		return
	}

	o.Data[bucket] = make(map[string][]byte)
}


text:
//---------------------------------------------------------------------
// <copyright file="StubEdmModel.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace EdmLibTests.StubEdm
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.OData.Edm;
    using Microsoft.OData.Edm.Annotations;
    using Microsoft.OData.Edm.Library;
    using Microsoft.OData.Edm.Library.Annotations;

    /// <summary>
    /// Stub implementation of the EdmModel
    /// </summary>
    public class StubEdmModel : StubEdmElement, IEdmModel, IEnumerable
    {
        private List<IEdmEntityContainer> entityContainers = new List<IEdmEntityContainer>();
        private List<IEdmSchemaElement> schemaElements = new List<IEdmSchemaElement>();
        private StubAnnotationsManager annotationsManager = new StubAnnotationsManager();

        /// <summary>
        /// Gets the schema elements
        /// </summary>
        public IEnumerable<IEdmSchemaElement> SchemaElements
        {
            get { return this.schemaElements.AsEnumerable().Concat(this.entityContainers.Cast<IEdmSchemaElement>()); }
        }

        /// <summary>
        /// Gets the collection of namespaces that schema elements use contained in this model.
        /// </summary>
        public IEnumerable<string> DeclaredNamespaces
        {
            get { return this.SchemaElements.Select(s => s.Namespace).Distinct(); }
        }

        /// <summary>
        /// Gets the vocabulary annotations
        /// </summary>
        public IEnumerable<IEdmVocabularyAnnotation> VocabularyAnnotations
        {
            get { return Enumerable.Empty<IEdmVocabularyAnnotation>(); }
        }

        /// <summary>
        /// Gets the collection of models referred to by this model.
        /// </summary>
        public IEnumerable<IEdmModel> ReferencedModels
        {
            get { return new IEdmModel[] { EdmCoreModel.Instance }; }
        }

        /// <summary>
        /// Gets the model's annotations manager.
        /// </summary>
        public IEdmDirectValueAnnotationsManager DirectValueAnnotationsManager
        {
            get { return this.annotationsManager; }
        }

        /// <summary>
        /// Gets the only one entity container of the model.
        /// </summary>
        public IEdmEntityContainer EntityContainer
        {
            get { return this.entityContainers.FirstOrDefault(); }
        }

        /// <summary>
        /// Finds a schema type by name
        /// </summary>
        /// <param name="qualifiedName">the qualified name of the element</param>
        /// <returns>the schema type</returns>
        public IEdmSchemaType FindDeclaredType(string qualifiedName)
        {
            if (qualifiedName == null)
            {
                throw new ArgumentNullException("qualifiedName");
            }

            return this.schemaElements.OfType<IEdmSchemaType>().FirstOrDefault(e => (e.FullName() == qualifiedName));
        }

        /// <summary>
        /// Finds a value term by name
        /// </summary>
        /// <param name="qualifiedName">the qualified name of the element</param>
        /// <returns>the value term</returns>
        public IEdmValueTerm FindDeclaredValueTerm(string qualifiedName)
        {
            if (qualifiedName == null)
            {
                throw new ArgumentNullException("qualifiedName");
            }

            return this.schemaElements.OfType<IEdmValueTerm>().FirstOrDefault(e => e.FullName() == qualifiedName);
        }

        /// <summary>
        /// Finds a schema type by name
        /// </summary>
        /// <param name="qualifiedName">the qualified name of the element</param>
        /// <returns>the schema type</returns>
        public IEnumerable<IEdmOperation> FindDeclaredOperations(string qualifiedName)
        {
            if (qualifiedName == null)
            {
                throw new ArgumentNullException("qualifiedName");
            }

            return this.schemaElements.OfType<IEdmOperation>().Where(e => e.FullName() == qualifiedName);
        }

        /// <summary>
        /// Finds all operations with the given name which are bindable to an instance of the giving binding type or a more derived type.
        /// </summary>
        /// <param name="bindingType">The binding entity type.</param>
        /// <param name="operationName">The name of the operations to find. May be qualified with an entity container name.</param>
        /// <returns>The operations that match the search criteria.</returns>
        public IEnumerable<IEdmOperation> FindDeclaredBoundOperations(IEdmType bindingType)
        {
            return this.schemaElements.OfType<IEdmOperation>().Where(f => f.IsBound
                        && f.Parameters.Any()
                        && f.HasEquivalentBindingType(bindingType));
        }

        /// <summary>
        /// Searches for bound operations based on the qualified name and binding type, returns an empty enumerable if no operation exists.
        /// </summary>
        /// <param name="qualifiedName">The qualified name of the operation.</param>
        /// <param name="bindingType">Type of the binding.</param>
        /// <returns>
        /// A set of operations that share the qualified name and binding type or empty enumerable if no such operation exists.
        /// </returns>
        public IEnumerable<IEdmOperation> FindDeclaredBoundOperations(string qualifiedName, IEdmType bindingType)
        {
            return this.FindDeclaredOperations(qualifiedName).Where(o => o.IsBound && o.Parameters.Any() && o.HasEquivalentBindingType(bindingType));
        }

        /// <summary>
        /// Searches for vocabulary annotations specified by this model or a referenced model for a given element.
        /// </summary>
        /// <param name="element">The annotated element.</param>
        /// <returns>The vocabulary annotations for the element.</returns>
        public IEnumerable<IEdmVocabularyAnnotation> FindDeclaredVocabularyAnnotations(IEdmVocabularyAnnotatable element)
        {
            StubEdmElement stubElement = element as StubEdmElement;
            return stubElement != null ? stubElement.InlineVocabularyAnnotations : Enumerable.Empty<IEdmVocabularyAnnotation>();
        }

        /// <summary>
        /// Finds a list of types that derive from the supplied type.
        /// </summary>
        /// <param name="baseType">The base type that derived types are being searched for.</param>
        /// <returns>A list of types that derive from the type.</returns>
        public IEnumerable<IEdmStructuredType> FindDirectlyDerivedTypes(IEdmStructuredType baseType)
        {
            throw new NotImplementedException("Find derived types is not implemented in the stub model");
        }

        /// <summary>
        /// Adds a container
        /// </summary>
        /// <param name="container">the container</param>
        public void Add(IEdmEntityContainer container)
        {
            this.entityContainers.Add(container);
        }

        /// <summary>
        /// Adds a schema element
        /// </summary>
        /// <param name="schemaElement">the schema element</param>
        public void Add(IEdmSchemaElement schemaElement)
        {
            this.schemaElements.Add(schemaElement);
        }

        private class StubAnnotationsManager : IEdmDirectValueAnnotationsManager
        {
            private Dictionary<IEdmElement, List<IEdmDirectValueAnnotation>> annotations = new Dictionary<IEdmElement, List<IEdmDirectValueAnnotation>>();

            /// <summary>
            /// Sets an annotation value for an EDM element. If the value is null, no annotation is added and an existing annotation with the same name is removed.
            /// </summary>
            /// <param name="element">The annotated element.</param>
            /// <param name="namespaceName">Namespace that the annotation belongs to.</param>
            /// <param name="localName">Name of the annotation within the namespace.</param>
            /// <param name="value">New annotation to set.</param>
            public void SetAnnotationValue(IEdmElement element, string namespaceName, string localName, object value)
            {
                List<IEdmDirectValueAnnotation> elementAnnotations = this.FindAnnotations(element, true);

                IEdmDirectValueAnnotation annotation = FindAnnotation(elementAnnotations, namespaceName, localName);
                if (annotation != null)
                {
                    elementAnnotations.Remove(annotation);
                }

                if (value != null)
                {
                    elementAnnotations.Add(new EdmDirectValueAnnotation(namespaceName, localName, value));
                }
            }

            /// <summary>
            /// Sets a set of annotation values. If a supplied value is null, no annotation is added and an existing annotation with the same name is removed.
            /// </summary>
            /// <param name="annotationBindings">The annotations to set</param>
            public void SetAnnotationValues(IEnumerable<IEdmDirectValueAnnotationBinding> annotationBindings)
            {
                foreach (IEdmDirectValueAnnotationBinding annotation in annotationBindings)
                {
                    this.SetAnnotationValue(annotation.Element, annotation.NamespaceUri, annotation.Name, annotation.Value);
                }
            }

            /// <summary>
            /// Retrieves an annotation value for an EDM element. Returns null if no annotation with the given name exists.
            /// </summary>
            /// <param name="element">The annotated element.</param>
            /// <param name="namespaceName">Namespace that the annotation belongs to.</param>
            /// <param name="localName">Local name of the annotation.</param>
            /// <returns>Returns the annotation that corresponds to the provided name. Returns null if no annotation with the given name exists. </returns>
            public object GetAnnotationValue(IEdmElement element, string namespaceName, string localName)
            {
                List<IEdmDirectValueAnnotation> elementAnnotations = this.FindAnnotations(element, false);
                IEdmDirectValueAnnotation annotation = FindAnnotation(elementAnnotations, namespaceName, localName);
                return annotation != null ? annotation.Value : null;
            }

            /// <summary>
            /// Retrieves a set of annotation values. For each requested value, returns null if no annotation with the given name exists for the given element.
            /// </summary>
            /// <param name="annotationBindings">The set of requested annotations</param>
            /// <returns>Returns values that correspond to the provided annotations. A value is null if no annotation with the given name exists for the given element.</returns>
            public object[] GetAnnotationValues(IEnumerable<IEdmDirectValueAnnotationBinding> annotationBindings)
            {
                object[] values = new object[annotationBindings.Count()];

                int index = 0;
                foreach (IEdmDirectValueAnnotationBinding annotation in annotationBindings)
                {
                    values[index++] = this.GetAnnotationValue(annotation.Element, annotation.NamespaceUri, annotation.Name);
                }

                return values;
            }

            /// <summary>
            /// Gets annotations associated with an element.
            /// </summary>
            /// <param name="element">The annotated element.</param>
            /// <returns>The immediate value annotations for the element.</returns>
            public IEnumerable<IEdmDirectValueAnnotation> GetDirectValueAnnotations(IEdmElement element)
            {
                return this.FindAnnotations(element, false) ?? Enumerable.Empty<IEdmDirectValueAnnotation>();
            }

            private static IEdmDirectValueAnnotation FindAnnotation(List<IEdmDirectValueAnnotation> annotations, string namespaceName, string localName)
            {
                return annotations != null ? annotations.FirstOrDefault(a => a.NamespaceUri == namespaceName && a.Name == localName) : null;
            }

            private List<IEdmDirectValueAnnotation> FindAnnotations(IEdmElement element, bool create)
            {
                List<IEdmDirectValueAnnotation> elementAnnotations;
                if (!this.annotations.TryGetValue(element, out elementAnnotations))
                {
                    if (create)
                    {
                        elementAnnotations = new List<IEdmDirectValueAnnotation>();
                        this.annotations[element] = elementAnnotations;
                    }
                }

                return elementAnnotations;
            }
        }
    }
}


text:
module Tags
  class Index < ::Layouts::Application

    def has_tags?
      Tag.count > 0
    end

    def tags
      tag_links(Tag.all, true)
    end

  end
end


text: This folder is for NN


text:
package org.fastcatsearch.service;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.fastcatsearch.env.Environment;
import org.fastcatsearch.exception.FastcatSearchException;
import org.fastcatsearch.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

	private static ServiceManager instance;
	private Environment environment;
	private Map<Class<?>, AbstractService> serviceMap;

	public static ServiceManager getInstance(){
		return instance;
	}

	public void asSingleton(){
		instance = this;
	}

	public ServiceManager(Environment environment){
		this.environment = environment;
		serviceMap = new ConcurrentHashMap<Class<?>, AbstractService>();
	}

	public <T extends AbstractService> T createService(String settingName, Class<T> serviceClass){
		try {
			Constructor<T> construct = serviceClass.getConstructor(Environment.class, Settings.class, ServiceManager.class);
			T t = construct.newInstance(environment, environment.settingManager().getSystemSettings().getSubSettings(settingName), this);
			serviceMap.put(serviceClass, t);
			return t;
		} catch (Exception e) {
			logger.error("can not make instance of class <"+serviceClass.getName()+">, {}", e);
		}
		return null;
	}

	public <T extends AbstractService> T getService(Class<T> serviceClass) {
		return (T) serviceMap.get(serviceClass);
	}

	public <T extends AbstractService> boolean stopService(Class<T> serviceClass) throws FastcatSearchException {
		T service = (T) serviceMap.get(serviceClass);
		if(service != null){
			return service.stop();
		}else{
			return false;
		}
	}

	public <T extends AbstractService> boolean closeService(Class<T> serviceClass) throws FastcatSearchException {
		T service = (T) serviceMap.get(serviceClass);
		if(service != null){
			return service.close();
		}else{
			return false;
		}
	}

	public Set<Class<?>> getServiceClasses() {
		return serviceMap.keySet();
	}
}


text:
package com.msi.tough.monitor.common.model.helper;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.msi.tough.model.monitor.DimensionBean;
import com.msi.tough.utils.CWUtil;

/**
 * @author jgardner
 *
 */
@Component
public class DimensionHelper {

    private static SessionFactory sessionFactory = null;

    @Transactional
    public DimensionBean getDimensionBean(
            final String key, final String value,
            final boolean addNew) {

        Session session = sessionFactory.getCurrentSession();

        try {
            return CWUtil.getDimensionBean(session, 0L, key, value, addNew);
        } catch (RuntimeException e) {
            // Not
            throw e;
        }
        catch (Exception e) {
            // No checked exceptions
            return null;
        }
    }

    @Autowired(required=true)
    public void setSessionFactory(SessionFactory sessionFactory) {
        DimensionHelper.sessionFactory = sessionFactory;
    }
}


text:
import json
import os
from shutil import rmtree
from tempfile import mkdtemp, gettempdir
from contextlib import contextmanager
from unittest import TestCase
from functools import wraps
from glob import glob

import mock

import peepin

@contextmanager
def tmpfile(name='requirements.txt'):
    dir_ = mkdtemp('peepintest')
    try:
        yield os.path.join(dir_, name)
    finally:
        rmtree(dir_)

def cleanup_tmpdir(pattern):

    def decorator(test):
        @wraps(test)
        def inner(self, *args, **kwargs):
            try:
                return test(self, *args, **kwargs)
            finally:
                for each in glob(os.path.join(gettempdir(), pattern)):
                    os.remove(each)
        return inner
    return decorator

class _Response(object):
    def __init__(self, content, status_code=200, headers=None):
        if isinstance(content, dict):
            content = json.dumps(content).encode('utf-8')
        self.content = content
        self.status_code = status_code
        if headers is None:
            headers = {'Content-Type': 'text/html'}
        self.headers = headers

    def read(self):
        return self.content

class Tests(TestCase):

    @mock.patch('peepin.urlopen')
    def test_get_latest_version_simple(self, murlopen):
        version = peepin.get_latest_version({'info': {'version': '0.3'}})
        self.assertEqual(version, '0.3')

    @mock.patch('peepin.urlopen')
    def test_get_hashes_error(self, murlopen):

        def mocked_get(url, **options):
            if url == "https://pypi.python.org/pypi/somepackage/json":
                return _Response({})
            raise NotImplementedError(url)

        murlopen.side_effect = mocked_get

        self.assertRaises(
            peepin.PackageError,
            peepin.run,
            'somepackage==1.2.3',
            'doesntmatter.txt'
        )

    def test_amend_requirements_content_new(self):
        requirements = """
# empty so far
        """.strip() + '\n'
        new_lines = """
# sha256: 6QTt-5DahBKcBiUs06BfkLTuvBu1uF7pblb_bPaUONU
autocompeter==1.2.3
        """.strip()
        result = peepin.amend_requirements_content(
            requirements, 'autocompeter', new_lines
        )
        self.assertEqual(result, requirements + new_lines)

    def test_amend_requirements_content_replacement(self):
        requirements = """
# sha256: hHK_EwLbFb3yxDk6XpGAzb8ps_jtWwbAa_XGuo9DNYg
autocompeter==1.2.2
        """.strip() + '\n'
        new_lines = """
# sha256: 6QTt-5DahBKcBiUs06BfkLTuvBu1uF7pblb_bPaUONU
autocompeter==1.2.3
        """.strip()
        result = peepin.amend_requirements_content(
            requirements, 'autocompeter', new_lines
        )
        self.assertEqual(result, new_lines)

    def test_amend_requirements_content_replacement_2(self):
        requirements = """
# sha256: 3jrATsqwp-CvZO7jCnHnI7pYhrlYIF9zVN1iQ52mA4k
# sha256: hHK_EwLbFb3yxDk6XpGAzb8ps_jtWwbAa_XGuo9DNYg
autocompeter==1.2.2
        """.strip() + '\n'
        new_lines = """
# sha256: 6QTt-5DahBKcBiUs06BfkLTuvBu1uF7pblb_bPaUONU
autocompeter==1.2.3
        """.strip()
        result = peepin.amend_requirements_content(
            requirements, 'autocompeter', new_lines
        )
        self.assertEqual(result, new_lines)

    def test_amend_requirements_content_replacement_amonst_others(self):
        previous = """
# sha256: cHay6ATFKumO3svU3B-8qBMYb-f1_dYlR4OgClWntEI
otherpackage==1.0.0
""".strip() + '\n'
        requirements = previous + """
# sha256: 3jrATsqwp-CvZO7jCnHnI7pYhrlYIF9zVN1iQ52mA4k
# sha256: hHK_EwLbFb3yxDk6XpGAzb8ps_jtWwbAa_XGuo9DNYg
autocompeter==1.2.2
        """.strip() + '\n'
        new_lines = """
# sha256: 6QTt-5DahBKcBiUs06BfkLTuvBu1uF7pblb_bPaUONU
autocompeter==1.2.3
        """.strip()
        result = peepin.amend_requirements_content(
            requirements, 'autocompeter', new_lines
        )
        self.assertEqual(result, previous + new_lines)

    def test_amend_requirements_content_replacement_amonst_others_2(self):
        previous = """
# sha256: 6nj05rvk7z_4OHM6mUIsl7GjE2plb4N3PqnJWaSRRlw
https://github.com/rhelmer/pyinotify/archive/9ff352f.zip#egg=pyinotify
""".strip() + '\n'
        requirements = previous + """
# sha256: 3jrATsqwp-CvZO7jCnHnI7pYhrlYIF9zVN1iQ52mA4k
# sha256: hHK_EwLbFb3yxDk6XpGAzb8ps_jtWwbAa_XGuo9DNYg
autocompeter==1.2.2
        """.strip() + '\n'
        new_lines = """
# sha256: 6QTt-5DahBKcBiUs06BfkLTuvBu1uF7pblb_bPaUONU
autocompeter==1.2.3
        """.strip()
        result = peepin.amend_requirements_content(
            requirements, 'autocompeter', new_lines
        )
        self.assertEqual(result, previous + new_lines)

    @cleanup_tmpdir('peepin*')
    @mock.patch('peepin.urlopen')
    def test_run(self, murlopen):

        def mocked_get(url, **options):
            if url == "https://pypi.python.org/pypi/peepin/json":
                return _Response({
                    'info': {
                        'version': '0.10',
                    },
                    'releases': {
                        '0.10': [
                            {
                                'url': 'https://pypi.python.org/packages/2.7/p/peepin/peepin-0.10-py2-none-any.whl',
                            },
                            {
                                'url': 'https://pypi.python.org/packages/3.3/p/peepin/peepin-0.10-py3-none-any.whl',
                            },
                            {
                                'url': 'https://pypi.python.org/packages/source/p/peepin/peepin-0.10.tar.gz',
                            }
                        ]
                    }
                })
            elif url == "https://pypi.python.org/packages/2.7/p/peepin/peepin-0.10-py2-none-any.whl":
                return _Response(b"Some py2 wheel content\n")
            elif url == "https://pypi.python.org/packages/3.3/p/peepin/peepin-0.10-py3-none-any.whl":
                return _Response(b"Some py3 wheel content\n")
            elif url == "https://pypi.python.org/packages/source/p/peepin/peepin-0.10.tar.gz":
                return _Response(b"Some tarball content\n")

            raise NotImplementedError(url)

        murlopen.side_effect = mocked_get

        with tmpfile() as filename:
            with open(filename, 'w') as f:
                f.write('')
            retcode = peepin.run('peepin==0.10', filename)
            self.assertEqual(retcode, 0)
            with open(filename) as f:
                output = f.read()
            lines = output.splitlines()

            self.assertEqual(lines[0], '')
            self.assertEqual(
                lines[1],
                '# sha256: MRBPjA-YFqbSE120Iyz6JIssdSVZYmMhZXfTzck6PCU'
            )
            self.assertEqual(
                lines[2],
                '# sha256: YftZIx_-lnzmk6IJnP9ZomlebQKsu2sFEDPjsRB9gAg'
            )
            self.assertEqual(
                lines[3],
                '# sha256: svBtPE0Ui2SHaKurUIavrAQU5J60gT4fPEULl1x3zuk'
            )
            self.assertEqual(
                lines[4],
                'peepin==0.10'
            )


text:
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

package org.uma.jmetal.runner.singleobjective;

import org.uma.jmetal.algorithm.Algorithm;
import org.uma.jmetal.algorithm.singleobjective.geneticalgorithm.GeneticAlgorithmBuilder;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.operator.impl.crossover.SinglePointCrossover;
import org.uma.jmetal.operator.impl.mutation.BitFlipMutation;
import org.uma.jmetal.operator.impl.selection.BinaryTournamentSelection;
import org.uma.jmetal.problem.BinaryProblem;
import org.uma.jmetal.problem.singleobjective.OneMax;
import org.uma.jmetal.solution.BinarySolution;
import org.uma.jmetal.util.AlgorithmRunner;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.fileoutput.SolutionListOutput;
import org.uma.jmetal.util.fileoutput.impl.DefaultFileOutputContext;

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

/**
 * Class to configure and run a generational genetic algorithm. The target problem is OneMax.
 *
 * @author Antonio J. Nebro <antonio@lcc.uma.es>
 */
public class GenerationalGeneticAlgorithmRunner {
  /**
   * Usage: java org.uma.jmetal.runner.singleobjective.GenerationalGeneticAlgorithmRunner
   */
  public static void main(String[] args) throws Exception {
    Algorithm<BinarySolution> algorithm;
    BinaryProblem problem = new OneMax(512) ;

    CrossoverOperator<BinarySolution> crossoverOperator = new SinglePointCrossover(0.9) ;
    MutationOperator<BinarySolution> mutationOperator = new BitFlipMutation(1.0 / problem.getNumberOfBits(0)) ;
    SelectionOperator<List<BinarySolution>, BinarySolution> selectionOperator = new BinaryTournamentSelection<BinarySolution>();

    algorithm = new GeneticAlgorithmBuilder<BinarySolution>(problem, crossoverOperator, mutationOperator)
            .setPopulationSize(100)
            .setMaxEvaluations(25000)
            .setSelectionOperator(selectionOperator)
            .build() ;

    AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
            .execute() ;

    BinarySolution solution = algorithm.getResult() ;
    List<BinarySolution> population = new ArrayList<>(1) ;
    population.add(solution) ;

    long computingTime = algorithmRunner.getComputingTime() ;

    new SolutionListOutput(population)
            .setSeparator("\t")
            .setVarFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
            .setFunFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
            .print();

    JMetalLogger.logger.info("Total execution time: " + computingTime + "ms");
    JMetalLogger.logger.info("Objectives values have been written to file FUN.tsv");
    JMetalLogger.logger.info("Variables values have been written to file VAR.tsv");

  }
}