text:
import {rethrowAsync, user} from '../../log';

export const PARSER_IGNORE_FLAG = '`';

/** Rudamentary parser to handle nested Url replacement. */
export class Expander {

  /**
   * Link this instance of parser to the calling UrlReplacment
   * @param {!../variable-source.VariableSource|null} variableSource the keywords to replace
   */
  constructor(variableSource) {
    this.variableSource_ = variableSource;
  }

  /**
   * take the template url and return a promise of its evaluated value
   * @param {string} url url to be substituted
   * @param {!Object<string, *>=} opt_bindings additional one-off bindings
   * @param {!Object<string, boolean>=} opt_whiteList Optional white list of names
   *     that can be substituted.
   * @return {!Promise<string>}
   */
  expand(url, opt_bindings, opt_whiteList) {
    if (!url.length) {
      return Promise.resolve(url);
    }
    const expr = this.variableSource_
        .getExpr(opt_bindings, /*opt_ignoreArgs */ true);

    const matches = this.findMatches_(url, expr);
    // if no keywords move on
    if (!matches.length) {
      return Promise.resolve(url);
    }
    return this.parseUrlRecursively_(url, matches, opt_bindings);
  }

  /**
   * Structures the regex matching into the desired format
   * @param {string} url url to be substituted
   * @param {RegExp} expression regex containing all keywords
   * @return {Array<Object<string, string|number>>} array of objects representing
   *  matching keywords
   */
  findMatches_(url, expression) {
    const matches = [];
    url.replace(expression, (match, name, startPosition) => {
      const length = match.length;
      const stopPosition = length + startPosition - 1;
      const info = {
        start: startPosition,
        stop: stopPosition,
        name,
        length,
      };
      matches.push(info);
    });
    return matches;
  }

  /**
   * @param {string} url
   * @param {!Array<Object<string, string|number>>} matches array of objects representing
   *  matching keywords
   * @param {!Object<string, *>=} opt_bindings additional one-off bindings
   * @return {!Promise<string>}
   */
  parseUrlRecursively_(url, matches, opt_bindings) {
    const stack = [];
    let urlIndex = 0;
    let matchIndex = 0;
    let match = matches[matchIndex];
    let numOfPendingCalls = 0;
    let ignoringChars = false;
    let nextArgShouldBeRaw = false;

    const evaluateNextLevel = () => {
      let builder = '';
      const results = [];

      while (urlIndex < url.length && matchIndex <= matches.length) {
        if (match && urlIndex === match.start) {
          let binding;
          // find out where this keyword is coming from
          if (opt_bindings && opt_bindings.hasOwnProperty(match.name)) {
            // the optional bindings
            binding = opt_bindings[match.name];
          } else {
            // or the global source
            binding = this.variableSource_.get(match.name);
            binding = binding.async || binding.sync;
          }

          urlIndex = match.stop + 1;
          match = matches[++matchIndex];

          if (url[urlIndex] === '(') {
            // if we hit a left parenthesis we still need to get args
            urlIndex++;
            numOfPendingCalls++;
            stack.push(binding);
            if (builder.length) {
              results.push(builder);
            }
            results.push(evaluateNextLevel());
          } else {
            if (builder.length) {
              results.push(builder);
            }
            results.push(this.evaluateBinding_(binding));
          }

          builder = '';
        }

        else if (url[urlIndex] === PARSER_IGNORE_FLAG) {
          if (!ignoringChars) {
            ignoringChars = true;
            nextArgShouldBeRaw = true;
            user().assert(builder.trim() === '',
                `The substring "${builder}" was lost during url-replacement. ` +
                'Please ensure the url syntax is correct');
            builder = '';
          } else {
            ignoringChars = false;
          }
          urlIndex++;
        }

        else if (numOfPendingCalls && url[urlIndex] === ',' && !ignoringChars) {
          if (builder.length) {
            const nextArg = nextArgShouldBeRaw ? builder : builder.trim();
            results.push(nextArg);
            nextArgShouldBeRaw = false;
          }
          // support existing two comma format
          // eg CLIENT_ID(__ga,,ga-url)
          if (url[urlIndex + 1] === ',') {
            results.push(''); // TODO(ccordry): may want this to be undefined at some point
            urlIndex++;
          }
          builder = '';
          urlIndex++;
        }

        else if (url[urlIndex] === ')' && !ignoringChars) {
          urlIndex++;
          numOfPendingCalls--;
          const binding = stack.pop();
          const nextArg = nextArgShouldBeRaw ? builder : builder.trim();
          results.push(nextArg);
          nextArgShouldBeRaw = false;
          const value = this.evaluateBinding_(binding, results);
          return value;
        }

        else {
          builder += url[urlIndex];
          urlIndex++;
        }

        //capture trailing characters
        if (urlIndex === url.length && builder.length) {
          results.push(builder);
        }
      }
      return Promise.all(results)
          .then(promiseArray => promiseArray.join(''))
          .catch(e => {
            rethrowAsync(e);
            return '';
          });
    };

    return evaluateNextLevel();
  }

  /**
   * resolves binding to value to be substituted
   * @param {*} binding container for sync/async resolutions
   * @param {?Array=} opt_args arguments to be passed if binding is function
   * @return {!Promise<string>} resolved value
   */
  evaluateBinding_(binding, opt_args) {
    let value;
    try {
      if (typeof binding === 'function') {
        if (opt_args) {
          value = Promise.all(opt_args)
              .then(args => binding.apply(null, args));
        } else {
          value = Promise.resolve(binding.apply(null, opt_args));
        }
      } else {
        value = Promise.resolve(binding);
      }
      return value.then(val => val == null ? '' : encodeURIComponent(val))
          .catch(e => {
            rethrowAsync(e);
            return '';
          });

    } catch (e) {
      // Report error, but do not disrupt URL replacement. This will
      // interpolate as the empty string.
      rethrowAsync(e);
      return Promise.resolve('');
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html><title>Minimal tQuery Page</title>
<script src="../../../build/tquery-bundle-require.js"></script>
<body><script>
require(['tquery.webaudio'], function(){
	var world	= tQuery.createWorld().boilerplate().start();
	var object	= tQuery.createTorus().addTo(world);

	// enable webaudio
	WebAudio.isAvailable && world.enableWebAudio();

	if( WebAudio.isAvailable ){
		tQuery.createSound().load('../../assets/sounds/eatpill.mp3', function(sound){
			sound.loop(true).play()
		});

		// init the library without tQuery plugins to avoid the listener localisation
		var webaudio	= new WebAudio();
		// create a sound
		webaudio.createSound().load('../../assets/sounds/techno.mp3', function(sound){
			sound.loop(true).play();
		});

	}
});
</script></body>


text:
layout: page
title: Nosotros
permalink: /about
tags: about
---

Contributores:

- Paco Aparicio
- Morten Jacobsen
- Pepe Lloret
- Antonio Chapa
- Ricardo


text:
class CreateCustomers < ActiveRecord::Migration
  def self.up
    create_table :customers, :force => true do |t|
      t.string :name
      t.text :description
      t.timestamps
    end
  end

  def self.down
    drop_table :customers
  end
end


text:
package client // import "github.com/docker/docker/client"

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"os"
	"strings"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/versions"
	"github.com/docker/docker/errdefs"
	"github.com/pkg/errors"
)

// serverResponse is a wrapper for http API responses.
type serverResponse struct {
	body       io.ReadCloser
	header     http.Header
	statusCode int
	reqURL     *url.URL
}

// head sends an http request to the docker API using the method HEAD.
func (cli *Client) head(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) {
	return cli.sendRequest(ctx, "HEAD", path, query, nil, headers)
}

// get sends an http request to the docker API using the method GET with a specific Go context.
func (cli *Client) get(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) {
	return cli.sendRequest(ctx, "GET", path, query, nil, headers)
}

// post sends an http request to the docker API using the method POST with a specific Go context.
func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) {
	body, headers, err := encodeBody(obj, headers)
	if err != nil {
		return serverResponse{}, err
	}
	return cli.sendRequest(ctx, "POST", path, query, body, headers)
}

func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) {
	return cli.sendRequest(ctx, "POST", path, query, body, headers)
}

// put sends an http request to the docker API using the method PUT.
func (cli *Client) put(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) {
	body, headers, err := encodeBody(obj, headers)
	if err != nil {
		return serverResponse{}, err
	}
	return cli.sendRequest(ctx, "PUT", path, query, body, headers)
}

// putRaw sends an http request to the docker API using the method PUT.
func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) {
	return cli.sendRequest(ctx, "PUT", path, query, body, headers)
}

// delete sends an http request to the docker API using the method DELETE.
func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) {
	return cli.sendRequest(ctx, "DELETE", path, query, nil, headers)
}

type headers map[string][]string

func encodeBody(obj interface{}, headers headers) (io.Reader, headers, error) {
	if obj == nil {
		return nil, headers, nil
	}

	body, err := encodeData(obj)
	if err != nil {
		return nil, headers, err
	}
	if headers == nil {
		headers = make(map[string][]string)
	}
	headers["Content-Type"] = []string{"application/json"}
	return body, headers, nil
}

func (cli *Client) buildRequest(method, path string, body io.Reader, headers headers) (*http.Request, error) {
	expectedPayload := (method == "POST" || method == "PUT")
	if expectedPayload && body == nil {
		body = bytes.NewReader([]byte{})
	}

	req, err := http.NewRequest(method, path, body)
	if err != nil {
		return nil, err
	}
	req = cli.addHeaders(req, headers)

	if cli.proto == "unix" || cli.proto == "npipe" {
		// For local communications, it doesn't matter what the host is. We just
		// need a valid and meaningful host name. (See #189)
		req.Host = "docker"
	}

	req.URL.Host = cli.addr
	req.URL.Scheme = cli.scheme

	if expectedPayload && req.Header.Get("Content-Type") == "" {
		req.Header.Set("Content-Type", "text/plain")
	}
	return req, nil
}

func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers headers) (serverResponse, error) {
	req, err := cli.buildRequest(method, cli.getAPIPath(ctx, path, query), body, headers)
	if err != nil {
		return serverResponse{}, err
	}
	resp, err := cli.doRequest(ctx, req)
	if err != nil {
		return resp, errdefs.FromStatusCode(err, resp.statusCode)
	}
	err = cli.checkResponseErr(resp)
	return resp, errdefs.FromStatusCode(err, resp.statusCode)
}

func (cli *Client) doRequest(ctx context.Context, req *http.Request) (serverResponse, error) {
	serverResp := serverResponse{statusCode: -1, reqURL: req.URL}

	req = req.WithContext(ctx)
	resp, err := cli.client.Do(req)
	if err != nil {
		if cli.scheme != "https" && strings.Contains(err.Error(), "malformed HTTP response") {
			return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err)
		}

		if cli.scheme == "https" && strings.Contains(err.Error(), "bad certificate") {
			return serverResp, errors.Wrap(err, "The server probably has client authentication (--tlsverify) enabled. Please check your TLS client certification settings")
		}

		// Don't decorate context sentinel errors; users may be comparing to
		// them directly.
		switch err {
		case context.Canceled, context.DeadlineExceeded:
			return serverResp, err
		}

		if nErr, ok := err.(*url.Error); ok {
			if nErr, ok := nErr.Err.(*net.OpError); ok {
				if os.IsPermission(nErr.Err) {
					return serverResp, errors.Wrapf(err, "Got permission denied while trying to connect to the Docker daemon socket at %v", cli.host)
				}
			}
		}

		if err, ok := err.(net.Error); ok {
			if err.Timeout() {
				return serverResp, ErrorConnectionFailed(cli.host)
			}
			if !err.Temporary() {
				if strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial unix") {
					return serverResp, ErrorConnectionFailed(cli.host)
				}
			}
		}

		// Although there's not a strongly typed error for this in go-winio,
		// lots of people are using the default configuration for the docker
		// daemon on Windows where the daemon is listening on a named pipe
		// `//./pipe/docker_engine, and the client must be running elevated.
		// Give users a clue rather than the not-overly useful message
		// such as `error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.26/info:
		// open //./pipe/docker_engine: The system cannot find the file specified.`.
		// Note we can't string compare "The system cannot find the file specified" as
		// this is localised - for example in French the error would be
		// `open //./pipe/docker_engine: Le fichier spécifié est introuvable.`
		if strings.Contains(err.Error(), `open //./pipe/docker_engine`) {
			// Checks if client is running with elevated privileges
			if f, elevatedErr := os.Open("\\\\.\\PHYSICALDRIVE0"); elevatedErr == nil {
				err = errors.Wrap(err, "In the default daemon configuration on Windows, the docker client must be run with elevated privileges to connect.")
			} else {
				f.Close()
				err = errors.Wrap(err, "This error may indicate that the docker daemon is not running.")
			}
		}

		return serverResp, errors.Wrap(err, "error during connect")
	}

	if resp != nil {
		serverResp.statusCode = resp.StatusCode
		serverResp.body = resp.Body
		serverResp.header = resp.Header
	}
	return serverResp, nil
}

func (cli *Client) checkResponseErr(serverResp serverResponse) error {
	if serverResp.statusCode >= 200 && serverResp.statusCode < 400 {
		return nil
	}

	var body []byte
	var err error
	if serverResp.body != nil {
		bodyMax := 1 * 1024 * 1024 // 1 MiB
		bodyR := &io.LimitedReader{
			R: serverResp.body,
			N: int64(bodyMax),
		}
		body, err = ioutil.ReadAll(bodyR)
		if err != nil {
			return err
		}
		if bodyR.N == 0 {
			return fmt.Errorf("request returned %s with a message (> %d bytes) for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), bodyMax, serverResp.reqURL)
		}
	}
	if len(body) == 0 {
		return fmt.Errorf("request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), serverResp.reqURL)
	}

	var ct string
	if serverResp.header != nil {
		ct = serverResp.header.Get("Content-Type")
	}

	var errorMessage string
	if (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) && ct == "application/json" {
		var errorResponse types.ErrorResponse
		if err := json.Unmarshal(body, &errorResponse); err != nil {
			return errors.Wrap(err, "Error reading JSON")
		}
		errorMessage = strings.TrimSpace(errorResponse.Message)
	} else {
		errorMessage = strings.TrimSpace(string(body))
	}

	return errors.Wrap(errors.New(errorMessage), "Error response from daemon")
}

func (cli *Client) addHeaders(req *http.Request, headers headers) *http.Request {
	// Add CLI Config's HTTP Headers BEFORE we set the Docker headers
	// then the user can't change OUR headers
	for k, v := range cli.customHTTPHeaders {
		if versions.LessThan(cli.version, "1.25") && k == "User-Agent" {
			continue
		}
		req.Header.Set(k, v)
	}

	if headers != nil {
		for k, v := range headers {
			req.Header[k] = v
		}
	}
	return req
}

func encodeData(data interface{}) (*bytes.Buffer, error) {
	params := bytes.NewBuffer(nil)
	if data != nil {
		if err := json.NewEncoder(params).Encode(data); err != nil {
			return nil, err
		}
	}
	return params, nil
}

func ensureReaderClosed(response serverResponse) {
	if response.body != nil {
		// Drain up to 512 bytes and close the body to let the Transport reuse the connection
		io.CopyN(ioutil.Discard, response.body, 512)
		response.body.Close()
	}
}


text:
<template is="dom-if"
    if="[[showPerNetworkAllowRoamingToggle_(isRoamingAllowedForNetwork_)]]">

        $i18n{networkAllowDataRoaming}

        [[getRoamingDetails_(managedProperties, prefs.cros.signed.data_roaming_enabled)]]

    <template is="dom-if"
        if="[[isRoamingProhibitedByPolicy_(prefs.cros.signed.data_roaming_enabled)]]">
      <cr-policy-indicator indicator-type="devicePolicy" on-click="doNothing_">
      </cr-policy-indicator>
    </template>
    <cr-toggle id="control" checked="{{isRoamingAllowedForNetwork_}}"
        disabled="[[isPerNetworkToggleDisabled_(disabled, prefs.cros.signed.data_roaming_enabled)]]"
        aria-labelledby="cellularRoamingToggleLabel"
        aria-describedby="cellularRoamingToggleSubLabel">
    </cr-toggle>

</template>


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.StorageSync.Models
{
    public partial class RestoreFileSpec : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Path))
            {
                writer.WritePropertyName("path");
                writer.WriteStringValue(Path);
            }
            if (Optional.IsDefined(IsDirectory))
            {
                writer.WritePropertyName("isdir");
                writer.WriteBooleanValue(IsDirectory.Value);
            }
            writer.WriteEndObject();
        }
    }
}


text:
package com.hkurokawa.qiitandroid.screens.board;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hkurokawa.qiitandroid.domain.article.ListItem;

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

/**
 * PagingListAdapter specifies a behaviour required on BoardView.
 * Created by hiroshi on 8/23/15.
 */
public abstract class BoardListAdapter<T extends ListItem> extends RecyclerView.Adapter<ViewHolder> {
    private static final int VIEW_TYPE_FOOTER = 0;
    private static final int VIEW_TYPE_ITEM = 1;
    private List<T> articles = new ArrayList<>();
    private View footerView;
    private OnBoardListItemClickListener<T> listener;

    @Override
    public int getItemViewType(int position) {
        if (position >= this.articles.size()) {
            return VIEW_TYPE_FOOTER;
        }
        return VIEW_TYPE_ITEM;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        switch (viewType) {
            case VIEW_TYPE_FOOTER:
                return new FooterViewHolder(this.footerView);
            case VIEW_TYPE_ITEM:
                return this.createItemViewHolder(inflater);
            default:
                throw new IllegalArgumentException("Invalid view type: " + viewType);
        }
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        if (holder instanceof ViewHolder.ItemViewHolder) {
            final T a = this.articles.get(position);
            final ViewHolder.ItemViewHolder<T> h = ((ViewHolder.ItemViewHolder) holder);
            h.setItem(a);
            h.setOnClickListener(v -> {
                if (BoardListAdapter.this.listener != null) {
                    BoardListAdapter.this.listener.onItemClick(a, position);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return this.articles.size() + (this.footerView != null ? 1 : 0);
    }

    @Override
    public long getItemId(int position) {
        if (position >= this.articles.size()) {
            return -1L;
        } else {
            return this.articles.get(position).getId();
        }
    }

    public void set(List<T> articles) {
        this.articles = articles;
    }

    public void setFooterView(View footerView) {
        this.footerView = footerView;
    }

    public void setOnItemClickListener(OnBoardListItemClickListener<T> listener) {
        this.listener = listener;
    }

    private static class FooterViewHolder extends ViewHolder {
        public FooterViewHolder(View footer) {
            super(footer);
        }
    }

    protected abstract ViewHolder.ItemViewHolder createItemViewHolder(LayoutInflater inflater);
}


text:
static const char kMainWebrtcTestHtmlPage[] =
    "/webrtc/webrtc_jsep01_test.html";

static const char kTestLoggingSessionId[] = "0123456789abcdef";

// Top-level integration test for WebRTC. Requires a real webcam and microphone
// on the running system. This test is not meant to run in the main browser
// test suite since normal tester machines do not have webcams.
class WebrtcBrowserTest : public WebRtcTestBase {
 public:
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    PeerConnectionServerRunner::KillAllPeerConnectionServersOnCurrentSystem();
  }

  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // TODO(phoglund): check that user actually has the requisite devices and
    // print a nice message if not; otherwise the test just times out which can
    // be confusing.
    // This test expects real device handling and requires a real webcam / audio
    // device; it will not work with fake devices.
    EXPECT_FALSE(command_line->HasSwitch(
        switches::kUseFakeDeviceForMediaStream));
    EXPECT_FALSE(command_line->HasSwitch(
        switches::kUseFakeUIForMediaStream));

    // The video playback will not work without a GPU, so force its use here.
    command_line->AppendSwitch(switches::kUseGpuInTests);
  }

  // Convenience method which executes the provided javascript in the context
  // of the provided web contents and returns what it evaluated to.
  std::string ExecuteJavascript(const std::string& javascript,
                                content::WebContents* tab_contents) {
    std::string result;
    EXPECT_TRUE(content::ExecuteScriptAndExtractString(
        tab_contents, javascript, &result));
    return result;
  }

  // Ensures we didn't get any errors asynchronously (e.g. while no javascript
  // call from this test was outstanding).
  // TODO(phoglund): this becomes obsolete when we switch to communicating with
  // the DOM message queue.
  void AssertNoAsynchronousErrors(content::WebContents* tab_contents) {
    EXPECT_EQ("ok-no-errors",
              ExecuteJavascript("getAnyTestFailures()", tab_contents));
  }

  // The peer connection server lets our two tabs find each other and talk to
  // each other (e.g. it is the application-specific "signaling solution").
  void ConnectToPeerConnectionServer(const std::string peer_name,
                                     content::WebContents* tab_contents) {
    std::string javascript = base::StringPrintf(
        "connect('http://localhost:8888', '%s');", peer_name.c_str());
    EXPECT_EQ("ok-connected", ExecuteJavascript(javascript, tab_contents));
  }

  void EstablishCall(content::WebContents* from_tab,
                     content::WebContents* to_tab,
                     bool enable_logging = false) {
    std::string javascript = enable_logging ?
        base::StringPrintf("preparePeerConnection(\"%s\")",
            kTestLoggingSessionId) :
        "preparePeerConnection(false)";
    EXPECT_EQ("ok-peerconnection-created",
              ExecuteJavascript(javascript, from_tab));
    EXPECT_EQ("ok-added",
              ExecuteJavascript("addLocalStream()", from_tab));
    EXPECT_EQ("ok-negotiating",
              ExecuteJavascript("negotiateCall()", from_tab));

    // Ensure the call gets up on both sides.
    EXPECT_TRUE(PollingWaitUntil("getPeerConnectionReadyState()",
                                 "active", from_tab));
    EXPECT_TRUE(PollingWaitUntil("getPeerConnectionReadyState()",
                                 "active", to_tab));
  }

  void StartDetectingVideo(content::WebContents* tab_contents,
                           const std::string& video_element) {
    std::string javascript = base::StringPrintf(
        "startDetection('%s', 'frame-buffer', 320, 240)",
        video_element.c_str());
    EXPECT_EQ("ok-started", ExecuteJavascript(javascript, tab_contents));
  }

  void WaitForVideoToPlay(content::WebContents* tab_contents) {
    EXPECT_TRUE(PollingWaitUntil("isVideoPlaying()", "video-playing",
                                 tab_contents));
  }

  void WaitForVideoToStopPlaying(content::WebContents* tab_contents) {
    EXPECT_TRUE(PollingWaitUntil("isVideoPlaying()", "video-not-playing",
                                 tab_contents));
  }

  void HangUp(content::WebContents* from_tab) {
    EXPECT_EQ("ok-call-hung-up", ExecuteJavascript("hangUp()", from_tab));
  }

  void WaitUntilHangupVerified(content::WebContents* tab_contents) {
    EXPECT_TRUE(PollingWaitUntil("getPeerConnectionReadyState()",
                                 "no-peer-connection", tab_contents));
  }

  std::string ToggleLocalVideoTrack(content::WebContents* tab_contents) {
    // Toggle the only video track in the page (e.g. video track 0).
    return ExecuteJavascript("toggleLocalStream("
        "function(local) { return local.getVideoTracks()[0]; }, "
        "'video');", tab_contents);
  }

  std::string ToggleRemoteVideoTrack(content::WebContents* tab_contents) {
    // Toggle the only video track in the page (e.g. video track 0).
    return ExecuteJavascript("toggleRemoteStream("
        "function(local) { return local.getVideoTracks()[0]; }, "
        "'video');", tab_contents);
  }

  void PrintProcessMetrics(base::ProcessMetrics* process_metrics,
                           const std::string& suffix) {
    perf_test::PrintResult("cpu", "", "cpu" + suffix,
                           process_metrics->GetCPUUsage(),
                           "%", true);
    perf_test::PrintResult("memory", "", "ws_peak" + suffix,
                           process_metrics->GetPeakWorkingSetSize(),
                           "bytes", true);
    perf_test::PrintResult("memory", "", "ws_final" + suffix,
                           process_metrics->GetWorkingSetSize(),
                           "bytes", false);

    size_t private_mem;
    size_t shared_mem;
    if (process_metrics->GetMemoryBytes(&private_mem, &shared_mem)) {
      perf_test::PrintResult("memory", "", "private_mem_final" + suffix,
                             private_mem, "bytes", false);
      perf_test::PrintResult("memory", "", "shared_mem_final" + suffix,
                             shared_mem, "bytes", false);
    }
  }

  PeerConnectionServerRunner peerconnection_server_;
};

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,
                       MANUAL_RunsAudioVideoWebRTCCallInTwoTabs) {
  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
  ASSERT_TRUE(peerconnection_server_.Start());

  ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage));
  content::WebContents* left_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  GetUserMediaAndAccept(left_tab);

  chrome::AddBlankTabAt(browser(), -1, true);
  content::WebContents* right_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  ui_test_utils::NavigateToURL(
        browser(), embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage));
  GetUserMediaAndAccept(right_tab);

  ConnectToPeerConnectionServer("peer 1", left_tab);
  ConnectToPeerConnectionServer("peer 2", right_tab);

  EstablishCall(left_tab, right_tab);

  AssertNoAsynchronousErrors(left_tab);
  AssertNoAsynchronousErrors(right_tab);

  StartDetectingVideo(left_tab, "remote-view");
  StartDetectingVideo(right_tab, "remote-view");

  WaitForVideoToPlay(left_tab);
  WaitForVideoToPlay(right_tab);

  HangUp(left_tab);
  WaitUntilHangupVerified(left_tab);
  WaitUntilHangupVerified(right_tab);

  AssertNoAsynchronousErrors(left_tab);
  AssertNoAsynchronousErrors(right_tab);

  ASSERT_TRUE(peerconnection_server_.Stop());
}

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, MANUAL_CpuUsage15Seconds) {
  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
  ASSERT_TRUE(peerconnection_server_.Start());

  base::FilePath results_file;
  ASSERT_TRUE(file_util::CreateTemporaryFile(&results_file));

  ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage));
  content::WebContents* left_tab =
      browser()->tab_strip_model()->GetActiveWebContents();

#if defined(OS_MACOSX)
  // Don't measure renderer CPU on mac: requires a mach broker we don't have
  // access to from the browser test.
  scoped_ptr<base::ProcessMetrics> browser_process_metrics(
      base::ProcessMetrics::CreateProcessMetrics(
      base::Process::Current().handle(), NULL));
  browser_process_metrics->GetCPUUsage();
#else
  // Measure rendering CPU on platforms that support it.
  base::ProcessHandle renderer_pid =
      left_tab->GetRenderProcessHost()->GetHandle();
  scoped_ptr<base::ProcessMetrics> renderer_process_metrics(
      base::ProcessMetrics::CreateProcessMetrics(renderer_pid));
  renderer_process_metrics->GetCPUUsage();

  scoped_ptr<base::ProcessMetrics> browser_process_metrics(
      base::ProcessMetrics::CreateProcessMetrics(
          base::Process::Current().handle()));
  browser_process_metrics->GetCPUUsage();
#endif

  GetUserMediaAndAccept(left_tab);

  chrome::AddBlankTabAt(browser(), -1, true);
  content::WebContents* right_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  ui_test_utils::NavigateToURL(
        browser(), embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage));
  GetUserMediaAndAccept(right_tab);

  ConnectToPeerConnectionServer("peer 1", left_tab);
  ConnectToPeerConnectionServer("peer 2", right_tab);

  EstablishCall(left_tab, right_tab);

  AssertNoAsynchronousErrors(left_tab);
  AssertNoAsynchronousErrors(right_tab);

  SleepInJavascript(left_tab, 15000);

  HangUp(left_tab);
  WaitUntilHangupVerified(left_tab);
  WaitUntilHangupVerified(right_tab);

#if !defined(OS_MACOSX)
  PrintProcessMetrics(renderer_process_metrics.get(), "_r");
#endif
  PrintProcessMetrics(browser_process_metrics.get(), "_b");

  AssertNoAsynchronousErrors(left_tab);
  AssertNoAsynchronousErrors(right_tab);

  ASSERT_TRUE(peerconnection_server_.Stop());
}

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,
                       MANUAL_TestMediaStreamTrackEnableDisable) {
  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
  ASSERT_TRUE(peerconnection_server_.Start());

  ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage));
  content::WebContents* left_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  GetUserMediaAndAccept(left_tab);

  chrome::AddBlankTabAt(browser(), -1, true);
  content::WebContents* right_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  ui_test_utils::NavigateToURL(
        browser(), embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage));
  GetUserMediaAndAccept(right_tab);

  ConnectToPeerConnectionServer("peer 1", left_tab);
  ConnectToPeerConnectionServer("peer 2", right_tab);

  EstablishCall(left_tab, right_tab);

  AssertNoAsynchronousErrors(left_tab);
  AssertNoAsynchronousErrors(right_tab);

  StartDetectingVideo(left_tab, "remote-view");
  StartDetectingVideo(right_tab, "remote-view");

  WaitForVideoToPlay(left_tab);
  WaitForVideoToPlay(right_tab);

  EXPECT_EQ("ok-video-toggled-to-false", ToggleLocalVideoTrack(left_tab));

  WaitForVideoToStopPlaying(right_tab);

  EXPECT_EQ("ok-video-toggled-to-true", ToggleLocalVideoTrack(left_tab));

  WaitForVideoToPlay(right_tab);

  HangUp(left_tab);
  WaitUntilHangupVerified(left_tab);
  WaitUntilHangupVerified(right_tab);

  AssertNoAsynchronousErrors(left_tab);
  AssertNoAsynchronousErrors(right_tab);

  ASSERT_TRUE(peerconnection_server_.Stop());
}

// See comment in test where this class is used for purpose.
class BrowserMessageFilter : public content::BrowserMessageFilter {
 public:
  explicit BrowserMessageFilter(
      const base::Closure& on_channel_closing)
      : on_channel_closing_(on_channel_closing) {}

  virtual void OnChannelClosing() OVERRIDE {
    // Posting on the file thread ensures that the callback is run after
    // WebRtcLogUploader::UploadLog has finished. See also comment in
    // MANUAL_RunsAudioVideoWebRTCCallInTwoTabsWithLogging test.
    content::BrowserThread::PostTask(content::BrowserThread::FILE,
        FROM_HERE, on_channel_closing_);
  }

  virtual bool OnMessageReceived(const IPC::Message& message,
                                 bool* message_was_ok) OVERRIDE {
    return false;
  }

private:
  virtual ~BrowserMessageFilter() {}

  base::Closure on_channel_closing_;
};

// Tests WebRTC diagnostic logging. Sets up the browser to save the multipart
// contents to a buffer instead of uploading it, then verifies it after a call.
// Example of multipart contents:
// ------**--yradnuoBgoLtrapitluMklaTelgooG--**----
// Content-Disposition: form-data; name="prod"
//
// Chrome_Linux
// ------**--yradnuoBgoLtrapitluMklaTelgooG--**----
// Content-Disposition: form-data; name="ver"
//
// 30.0.1554.0
// ------**--yradnuoBgoLtrapitluMklaTelgooG--**----
// Content-Disposition: form-data; name="guid"
//
// 0
// ------**--yradnuoBgoLtrapitluMklaTelgooG--**----
// Content-Disposition: form-data; name="type"
//
// webrtc_log
// ------**--yradnuoBgoLtrapitluMklaTelgooG--**----
// Content-Disposition: form-data; name="app_session_id"
//
// 0123456789abcdef
// ------**--yradnuoBgoLtrapitluMklaTelgooG--**----
// Content-Disposition: form-data; name="url"
//
// http://127.0.0.1:43213/webrtc/webrtc_jsep01_test.html
// ------**--yradnuoBgoLtrapitluMklaTelgooG--**----
// Content-Disposition: form-data; name="webrtc_log"; filename="webrtc_log.gz"
// Content-Type: application/gzip
//
// <compressed data (zip)>
// ------**--yradnuoBgoLtrapitluMklaTelgooG--**------
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,
                       MANUAL_RunsAudioVideoWebRTCCallInTwoTabsWithLogging) {
  EXPECT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
  ASSERT_TRUE(peerconnection_server_.Start());

  // Add command line switch that forces allowing log uploads.
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  command_line->AppendSwitch(switches::kEnableMetricsReportingForTesting);

  // Tell the uploader to save the multipart to a buffer instead of uploading.
  std::string multipart;
  g_browser_process->webrtc_log_uploader()->
      OverrideUploadWithBufferForTesting(&multipart);
  ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage));
  content::WebContents* left_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  GetUserMediaAndAccept(left_tab);

  chrome::AddBlankTabAt(browser(), -1, true);
  content::WebContents* right_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage));
  GetUserMediaAndAccept(right_tab);

  ConnectToPeerConnectionServer("peer 1", left_tab);
  ConnectToPeerConnectionServer("peer 2", right_tab);

  EstablishCall(left_tab, right_tab, true);

  AssertNoAsynchronousErrors(left_tab);
  AssertNoAsynchronousErrors(right_tab);

  StartDetectingVideo(left_tab, "remote-view");
  StartDetectingVideo(right_tab, "remote-view");

  WaitForVideoToPlay(left_tab);
  WaitForVideoToPlay(right_tab);

  HangUp(left_tab);
  WaitUntilHangupVerified(left_tab);
  WaitUntilHangupVerified(right_tab);

  AssertNoAsynchronousErrors(left_tab);
  AssertNoAsynchronousErrors(right_tab);

  // Uploading (or storing to our buffer in our test case) is triggered when
  // the tab is closed. We must ensure that WebRtcLogUploader::UploadLog, which
  // runs on the FILE thread, has finished after closing the tab before
  // continuing.
  // 1. Add a filter which just acts as a listener. It's added after
  //    WebRtcLoggingHandlerHost, which is the filter that posts a task for
  //    WebRtcLogUploader::UploadLog. So it's guarantueed to be removed after
  //    WebRtcLoggingHandlerHost.
  // 2. When the filter goes away post a task on the file thread to signal the
  //    event.
  base::WaitableEvent ipc_channel_closed(false, false);
  left_tab->GetRenderProcessHost()->GetChannel()->AddFilter(
      new BrowserMessageFilter(base::Bind(
          &base::WaitableEvent::Signal,
          base::Unretained(&ipc_channel_closed))));
  chrome::CloseWebContents(browser(), left_tab, false);
  ASSERT_TRUE(ipc_channel_closed.TimedWait(TestTimeouts::action_timeout()));

  const char boundary[] = "------**--yradnuoBgoLtrapitluMklaTelgooG--**----";

  // Remove the compressed data, it may contain "\r\n". Just verify that its
  // size is > 0.
  const char zip_content_type[] = "Content-Type: application/gzip";
  size_t zip_pos = multipart.find(&zip_content_type[0]);
  ASSERT_NE(std::string::npos, zip_pos);
  // Move pos to where the zip begins. - 1 to remove '\0', + 4 for two "\r\n".
  zip_pos += sizeof(zip_content_type) + 3;
  size_t zip_length = multipart.find(boundary, zip_pos);
  ASSERT_NE(std::string::npos, zip_length);
  // Calculate length, adjust for a "\r\n".
  zip_length -= zip_pos + 2;
  ASSERT_GT(zip_length, 0u);
  multipart.erase(zip_pos, zip_length);

  // Check the multipart contents.
  std::vector<std::string> multipart_lines;
  base::SplitStringUsingSubstr(multipart, "\r\n", &multipart_lines);
  ASSERT_EQ(31, static_cast<int>(multipart_lines.size()));

  EXPECT_STREQ(&boundary[0], multipart_lines[0].c_str());
  EXPECT_STREQ("Content-Disposition: form-data; name=\"prod\"",
               multipart_lines[1].c_str());
  EXPECT_TRUE(multipart_lines[2].empty());
  EXPECT_NE(std::string::npos, multipart_lines[3].find("Chrome"));

  EXPECT_STREQ(&boundary[0], multipart_lines[4].c_str());
  EXPECT_STREQ("Content-Disposition: form-data; name=\"ver\"",
               multipart_lines[5].c_str());
  EXPECT_TRUE(multipart_lines[6].empty());
  // Just check that the version contains a dot.
  EXPECT_NE(std::string::npos, multipart_lines[7].find('.'));

  EXPECT_STREQ(&boundary[0], multipart_lines[8].c_str());
  EXPECT_STREQ("Content-Disposition: form-data; name=\"guid\"",
               multipart_lines[9].c_str());
  EXPECT_TRUE(multipart_lines[10].empty());
  EXPECT_STREQ("0", multipart_lines[11].c_str());

  EXPECT_STREQ(&boundary[0], multipart_lines[12].c_str());
  EXPECT_STREQ("Content-Disposition: form-data; name=\"type\"",
               multipart_lines[13].c_str());
  EXPECT_TRUE(multipart_lines[14].empty());
  EXPECT_STREQ("webrtc_log", multipart_lines[15].c_str());

  EXPECT_STREQ(&boundary[0], multipart_lines[16].c_str());
  EXPECT_STREQ("Content-Disposition: form-data; name=\"app_session_id\"",
               multipart_lines[17].c_str());
  EXPECT_TRUE(multipart_lines[18].empty());
  EXPECT_STREQ(kTestLoggingSessionId, multipart_lines[19].c_str());

  EXPECT_STREQ(&boundary[0], multipart_lines[20].c_str());
  EXPECT_STREQ("Content-Disposition: form-data; name=\"url\"",
               multipart_lines[21].c_str());
  EXPECT_TRUE(multipart_lines[22].empty());
  EXPECT_NE(std::string::npos,
            multipart_lines[23].find(&kMainWebrtcTestHtmlPage[0]));

  EXPECT_STREQ(&boundary[0], multipart_lines[24].c_str());
  EXPECT_STREQ("Content-Disposition: form-data; name=\"webrtc_log\";"
               " filename=\"webrtc_log.gz\"",
               multipart_lines[25].c_str());
  EXPECT_STREQ("Content-Type: application/gzip",
               multipart_lines[26].c_str());
  EXPECT_TRUE(multipart_lines[27].empty());
  EXPECT_TRUE(multipart_lines[28].empty());  // The removed zip part.
  std::string final_delimiter = boundary;
  final_delimiter += "--";
  EXPECT_STREQ(final_delimiter.c_str(), multipart_lines[29].c_str());
  EXPECT_TRUE(multipart_lines[30].empty());

  ASSERT_TRUE(peerconnection_server_.Stop());
}


text:
import Tkinter
import Pmw

class ThresholdScale(Pmw.MegaWidget):
    """ Megawidget containing a scale and an indicator.
    """

    def __init__(self, parent = None, **kw):
        # Define the megawidget options.
        optiondefs = (
	    ('colors',      ('green', 'red'), None),
	    ('orient',      'vertical',       Pmw.INITOPT),
	    ('labelmargin', 0,                Pmw.INITOPT),
	    ('labelpos',    None,             Pmw.INITOPT),
	    ('threshold',   (50,),            None),
	    ('value',       None,             Pmw.INITOPT),
        )
        self.defineoptions(kw, optiondefs)

        # Initialise base class (after defining options).
        Pmw.MegaWidget.__init__(self, parent)

        # Create the components.
        interior = self.interior()

        # Create the indicator component.
        self.indicator = self.createcomponent('indicator',
                (), None,
                Tkinter.Frame, interior,
			width = 16,
			height = 16,
			borderwidth = 2,
			relief = 'raised')

        # Create the value component.
        self.value = self.createcomponent('value',
                (), None,
                Tkinter.Label, interior,
		    width = 3)

        # Create the scale component.
	if self['orient'] == 'vertical':
	    # The default scale range seems to be
	    # the wrong way around - reverse it.
	    from_ = 100
	    to = 0
	else:
	    from_ = 0
	    to = 100

        self.scale = self.createcomponent('scale',
                (), None,
                Tkinter.Scale, interior,
			orient = self['orient'],
			command = self._doCommand,
			tickinterval = 20,
			length = 200,
			from_ = from_,
			to = to,
			showvalue = 0)

        value = self['value']
        if value is not None:
            self.scale.set(value)

	# Use grid to position all components
	if self['orient'] == 'vertical':
	    self.indicator.grid(row = 1, column = 1)
	    self.value.grid(row = 2, column = 1)
	    self.scale.grid(row = 3, column = 1)
	    # Create the label.
	    self.createlabel(interior, childRows=3)
	else:
	    self.indicator.grid(row = 1, column = 1)
	    self.value.grid(row = 1, column = 2)
	    self.scale.grid(row = 1, column = 3)
	    # Create the label.
	    self.createlabel(interior, childCols=3)

        # Check keywords and initialise options.
        self.initialiseoptions()

    def _doCommand(self, valueStr):
	valueInt = self.scale.get()
	colors = self['colors']
	thresholds = self['threshold']
	color = colors[-1]
	for index in range(len(colors) - 1):
	    if valueInt <= thresholds[index]:
		color = colors[index]
		break
	self.indicator.configure(background = color)
	self.value.configure(text = valueStr)

Pmw.forwardmethods(ThresholdScale, Tkinter.Scale, 'scale')

# Initialise Tkinter and Pmw.
root = Pmw.initialise()
root.title('Pmw ThresholdScale demonstration')

# Create and pack two ThresholdScale megawidgets.
mega1 = ThresholdScale(scale_showvalue = 1)
mega1.pack(side = 'left', padx = 10, pady = 10)

mega2 = ThresholdScale(
	colors = ('green', 'yellow', 'red'),
	threshold = (50, 75),
        value = 80,
	indicator_width = 32,
	scale_width = 25)
mega2.pack(side = 'left', padx = 10, pady = 10)

# Create and pack two horizontal ThresholdScale megawidgets.
mega3 = ThresholdScale(
	orient = 'horizontal',
	labelpos = 'n',
	label_text = 'Horizontal')
mega3.pack(side = 'top', padx = 10, pady = 10)
mega4 = ThresholdScale(orient = 'horizontal')
mega4.pack(side = 'top', padx = 10, pady = 10)

# Let's go.
root.mainloop()


text:
Using Celery with Flask-SocketIO
=======================

This repository contains example code based off of Miguel Grinberg's excellent blog article [Using Celery with Flask](http://blog.miguelgrinberg.com/post/using-celery-with-flask) and his [example code](https://github.com/miguelgrinberg/flask-celery-example).

The difference is that this code uses Flask-SocketIO (another excellent package by Miguel) to communicate status to the client without the client having to poll the server for status.

Quick Setup
-----------

1. Clone this repository.
2. Create a virtualenv and install the requirements.
3. Open a second terminal window and start a local Redis server (if you are on Linux or Mac, execute `run-redis.sh` to install and launch a private copy).
4. Open a third terminal window. Start a Celery worker: `venv/bin/celery worker -A app.celery --loglevel=info`.
5. Start the Flask application on your original terminal window: `venv/bin/python app.py`.
6. Go to `http://localhost:5000/` and enjoy this application!


text:
function CameraFX.onFollowObjectVelocityZoom ( hObject, nSpeed )
--------------------------------------------------------------------------------

	this.hTrackingTarget ( hObject )
    this.nTrackingSpeed ( nSpeed )
    this.FollowObjectVelocityZoom ( )

--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------


text:
using System;

namespace SocketHttpListener
{
  /// <summary>
  /// The exception that is thrown when a <see cref="WebSocket"/> gets a fatal error.
  /// </summary>
  public class WebSocketException : Exception
  {
    #region Internal Constructors

    internal WebSocketException ()
      : this (CloseStatusCode.Abnormal, null, null)
    {
    }

    internal WebSocketException (string message)
      : this (CloseStatusCode.Abnormal, message, null)
    {
    }

    internal WebSocketException (CloseStatusCode code)
      : this (code, null, null)
    {
    }

    internal WebSocketException (string message, Exception innerException)
      : this (CloseStatusCode.Abnormal, message, innerException)
    {
    }

    internal WebSocketException (CloseStatusCode code, string message)
      : this (code, message, null)
    {
    }

    internal WebSocketException (CloseStatusCode code, string message, Exception innerException)
      : base (message ?? code.GetMessage (), innerException)
    {
      Code = code;
    }

    #endregion

    #region Public Properties

    /// <summary>
    /// Gets the status code indicating the cause for the exception.
    /// </summary>
    /// <value>
    /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code indicating
    /// the cause for the exception.
    /// </value>
    public CloseStatusCode Code {
      get; private set;
    }

    #endregion
  }
}


text:
namespace base {
class SingleThreadTaskRunner;
}  // namespace base

namespace remoting {

// Creates native messaging host on Lacros. Must be called on the UI thread of
// the browser process.

std::unique_ptr<extensions::NativeMessageHost>
CreateIt2MeNativeMessagingHostForLacros(
    scoped_refptr<base::SingleThreadTaskRunner> ui_runner);

}  // namespace remoting

#endif  // REMOTING_HOST_IT2ME_IT2ME_NATIVE_MESSAGING_HOST_LACROS_H_


text:
from django.template.loader import render_to_string
from skins import get_skin

class Bargraph(object):
    def __init__(
            self, percent, width, widthpercent,
            toppadding=6, bottompadding=4):
        # percent graph is filled.
        self.percent = percent

        # total width of the graph (in pixels, unless widthpercent is 1)
        self.width = width
        self.height = 12

        # boolean to indicate if the width variable is a percent
        self.widthpercent = widthpercent

        self.toppadding = toppadding
        self.bottompadding = bottompadding

        self.border = 1                   # border size (in pixels)

        # left or right - controls which side the filled comes from.
        self.alignment = 'left'

        # boolean to indicate if display % label on the graph
        self.labels = 1

        # whether to use the 3d background for the empty section
        self.background = True

    def render(self):
        skin = get_skin()

        render_context = {
            'bordercolor': skin.colors['border_alternate'],
            'filledcolor': skin.colors['graphs'],
            'emptycolor': skin.colors['cell_title'],
            'labelfilledcolor': skin.colors['cell_background'],
            'labelemptycolor': skin.colors['text'],
            'emptybg': skin.images['empty_bargraph_background'],

            'toppadding': self.toppadding,
            'bottompadding': self.bottompadding,
            'width': self.width,
            'height': self.height,
            'alignment': self.alignment,
            'border': self.border,
            'background': self.background,

            'display_percentage': round(self.percent * 100),
            'width_middlepart': '{}%'.format(round(
                self.width - self.percent *
                self.width
            )),
            'width_firstpart': '{}%'.format(round(
                self.percent *
                self.width
            )),
            'widthpercent': '%' if self.widthpercent else ''
        }

        return render_to_string('cl_bargraph.html', render_context)


text:
{%extends "base.html"%}
{% block content %}

<form method="post" action="{% url 'student_register' %}"> {% csrf_token %}

{{ form.as_p }}

{{ formset.as_p }}

<input class="btn btn-default btn-primary" type="submit" value="Done"> </form>

{% endblock %}


text:
using PPTail.Entities;
using PPTail.Enumerations;
using PPTail.Exceptions;
using PPTail.Extensions;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

namespace PPTail.Data.Forestry
{
    public static class StringExtensions
    {
        public static String Sanitize(this string value)
        {
            return value?
                .Replace(" : ", " -- ")
                .Replace(" :", " -- ")
                .Replace(": ", " -- ")
                .Replace(":", "--");
        }

        public static String ToMarkdown(this string html)
        {
            var config = new ReverseMarkdown.Config() { UnknownTags = ReverseMarkdown.Config.UnknownTagsOption.Bypass };
            var converter = new ReverseMarkdown.Converter(config);
            return converter.Convert(html).Replace("<br>", "\r\n");
        }

        public static String ToHtml(this string markdown, Markdig.MarkdownPipeline markdownPipeline)
        {
            return Markdig.Markdown.ToHtml(markdown, markdownPipeline);
        }

        public static String ConditionalWrap(this string value, char? delimiter)
        {
            return delimiter.HasValue ? $"{delimiter}{value}{delimiter}" : value;
        }

        public static StringBuilder ConditionalAppendLine(this StringBuilder builder, bool addLine, String name, String value)
        {
            if (builder is null)
                throw new ArgumentNullException(nameof(builder));

            if (addLine)
                _ = string.IsNullOrEmpty(name)
                    ? builder.AppendLine(value)
                    : builder.AppendLine($"{name}: {value}");

            return builder;
        }

        public static StringBuilder ConditionalAppendList(this StringBuilder builder, bool addList, String name, IEnumerable<String> values)
        {
            if (builder is null)
                throw new ArgumentNullException(nameof(builder));

            if (addList)
            {
                if (values.IsNotNull() && values.Any())
                {
                    builder.AppendLine($"{name}:");
                    foreach (var value in values ?? Array.Empty<String>())
                        builder.AppendLine($"- {value}");
                }
                else
                    builder.AppendLine($"{name}: []");
            }
            return builder;
        }

        public static StringBuilder ConditionalAppendSiteVariables(this StringBuilder builder, bool addList, String collectionName, String fieldNameKey, String fieldValueKey, IEnumerable<Entities.SiteVariable> values)
        {
            if (builder is null)
                throw new ArgumentNullException(nameof(builder));

            if (addList)
            {
                if (values.IsNotNull() && values.Any())
                {
                    builder.AppendLine($"{collectionName}:");
                    foreach (var value in values ?? new List<Entities.SiteVariable>())
                    {
                        builder.AppendLine($"{fieldNameKey}: {value.Name}");
                        builder.AppendLine($"{fieldValueKey}: \"{value.Value}\"");
                    }
                }
                else
                    builder.AppendLine($"{collectionName}: []");
            }
            return builder;
        }

        internal static (string FrontMatter, string Content) ParseForestryYaml(this string value)
        {
            const string HR = "---";
            var fileSections = value.Split(new[] { HR }, StringSplitOptions.RemoveEmptyEntries);
            var frontMatter = fileSections[0];
            var content = String.Join(HR, fileSections.Skip(1));
            return (frontMatter, content);
        }

        public static Entities.SiteSettings ParseSettings(this string value)
        {
            if (String.IsNullOrWhiteSpace(value))
                throw new ArgumentNullException(nameof(value));

            var (frontMatter, content) = value.ParseForestryYaml();
            var yamlDeserializer = new DeserializerBuilder()
            .WithNamingConvention(LowerCaseNamingConvention.Instance)
            .Build();

            SiteSettings results = null;
            try
            {
                results = yamlDeserializer
                    .Deserialize<SiteSettings>(frontMatter);
            }
            catch (Exception ex)
            {
                throw new SettingNotFoundException(nameof(SiteSettings), ex);
            }

            return results.AsEntity();
        }

        public static Entities.ContentItem ParseContentItem(this string value, IEnumerable<Category> categories, Markdig.MarkdownPipeline markdownPipeline)
        {
            if (String.IsNullOrWhiteSpace(value))
                throw new ArgumentNullException(nameof(value));

            var (frontMatter, content) = value.ParseForestryYaml();
            var yamlDeserializer = new DeserializerBuilder()
            .WithNamingConvention(LowerCaseNamingConvention.Instance)
            .Build();

            var results = yamlDeserializer
                .Deserialize<ContentItem>(frontMatter);
            results.ByLine = String.IsNullOrEmpty(results.Author) ? String.Empty : $"by {results.Author}";
            results.Content = content.ToHtml(markdownPipeline);

            return results.AsEntity(categories);
        }

        public static Entities.Widget ParseWidget(this string value, Markdig.MarkdownPipeline markdownPipeline)
        {
            if (String.IsNullOrWhiteSpace(value))
                throw new ArgumentNullException(nameof(value));

            var (frontMatter, content) = value.ParseForestryYaml();
            var yamlDeserializer = new DeserializerBuilder()
            .WithNamingConvention(LowerCaseNamingConvention.Instance)
            .Build();

            var results = yamlDeserializer
                .Deserialize<Widget>(frontMatter);

            var entity = results.AsEntity();
            entity.Dictionary = new List<Tuple<string, string>>()
            {
                new Tuple<string, string>("Content", content.ToHtml(markdownPipeline))
            };

            return entity;
        }

        public static IEnumerable<Entities.Category> ParseCategories(this string value)
        {
            if (String.IsNullOrWhiteSpace(value))
                throw new ArgumentNullException(nameof(value));

            var (frontMatter, content) = value.ParseForestryYaml();
            var yamlDeserializer = new DeserializerBuilder()
            .WithNamingConvention(LowerCaseNamingConvention.Instance)
            .Build();

            var results = yamlDeserializer
                .Deserialize<CategoryCollection>(frontMatter);

            return results.AsEntity();
        }
    }
}


text:
using System;
using System.Reflection;

[assembly: System.Reflection.AssemblyFileVersionAttribute("5.0.14.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("5.0.14")]

// Generated by the MSBuild WriteCodeFragment class.


text:
#!/usr/bin/env node

/**********
 * Globals
 **********/

// Pre-existing Cordova npm modules
var deferral, path, cwd;

// Npm dependencies
var logger,
    fs,
    _,
    fileUtils;

// Other globals
var hooksPath;

var restoreBackups = (function(){

    /**********************
     * Internal properties
     *********************/
    var restoreBackups = {}, context, projectName, logFn, settings;

    var PLATFORM_CONFIG_FILES = {
        "ios":{
            "{projectName}-Info.plist": "{projectName}/{projectName}-Info.plist",
            "project.pbxproj": "{projectName}.xcodeproj/project.pbxproj",
            "build.xcconfig": "cordova/build.xcconfig",
            "build-extras.xcconfig": "cordova/build-extras.xcconfig",
            "build-debug.xcconfig": "cordova/build-debug.xcconfig",
            "build-release.xcconfig": "cordova/build-release.xcconfig"
        },
        "android":{
            "AndroidManifest.xml": "AndroidManifest.xml"
        }
    };

    /*********************
     * Internal functions
     *********************/

    function restorePlatformBackups(platform){
        var configFiles = PLATFORM_CONFIG_FILES[platform],
            backupFile, backupFileName, backupFilePath, backupFileExists, targetFilePath;

        logger.debug("Checking to see if there are backups to restore...");
        for(backupFile in configFiles){
            backupFileName = parseProjectName(backupFile);
            backupFilePath = path.join(cwd, 'plugins', context.opts.plugin.id, "backup", platform, backupFileName);
            backupFileExists = fileUtils.fileExists(backupFilePath);
            if(backupFileExists){
                targetFilePath = path.join(cwd, 'platforms', platform, parseProjectName(configFiles[backupFile]));
                fs.copySync(backupFilePath, targetFilePath);
                logFn("Restored backup of '"+backupFileName+"' to :"+targetFilePath);
            }
        }
    }

    function parseProjectName(fileName){
        return fileName.replace(/{(projectName)}/g, projectName);
    }

    // Script operations are complete, so resolve deferred promises
    function complete(){
        deferral.resolve();
    }

    /*************
     * Public API
     *************/
    restoreBackups.loadDependencies = function(ctx){
        fs = require('fs-extra'),
        _ = require('lodash'),
        fileUtils = require(path.resolve(hooksPath, "fileUtils.js"))(ctx);
        logger.debug("Loaded module dependencies");
        restoreBackups.init(ctx);
    };

    restoreBackups.init = function(ctx){
        context = ctx;

        projectName = fileUtils.getProjectName();
        logFn = context.hook === "before_plugin_uninstall" ? logger.log : logger.debug;

        settings = fileUtils.getSettings();
        if(typeof(settings.autorestore) === "undefined" || settings.autorestore == "false"){
            logger.log("Skipping auto-restore of config file backup(s)");
            complete();
            return;
        }

        // go through each of the platform directories
        var platforms = _.filter(fs.readdirSync('platforms'), function (file) {
            return fs.statSync(path.resolve('platforms', file)).isDirectory();
        });
        _.each(platforms, function (platform, index) {
            platform = platform.trim().toLowerCase();
            try{
                restorePlatformBackups(platform);
                if(index == platforms.length - 1){
                    logger.debug("Finished restoring backups");
                    complete();
                }
            }catch(e){
                var msg = "Error restoring backups for platform '"+platform+"': "+ e.message;
                logger.error(msg);
                if(settings.stoponerror){
                    deferral.reject(msg);
                }
            }
        });
    };

    return restoreBackups;
})();

module.exports = function(ctx) {
    deferral = ctx.requireCordovaModule('q').defer();
    path = ctx.requireCordovaModule('path');
    cwd = path.resolve();

    hooksPath = path.resolve(ctx.opts.projectRoot, "plugins", ctx.opts.plugin.id, "hooks");
    logger = require(path.resolve(hooksPath, "logger.js"))(ctx);
    logger.debug("Running restoreBackups.js");
    try{
        restoreBackups.loadDependencies(ctx);
    }catch(e){
        logger.warn("Error loading dependencies ("+e.message+") - attempting to resolve");
        require(path.resolve(hooksPath, "resolveDependencies.js"))(ctx).then(restoreBackups.loadDependencies.bind(this, ctx));
    }

    return deferral.promise;
};


text:
package com.joda.tentatime;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

public class Result extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);

        Bundle b = getIntent().getExtras();
        ExamResult mExam = (ExamResult) b.getSerializable("key");

        setupWidgets(mExam);
    }

    private void setupWidgets(ExamResult exam){
        TextView name = (TextView) findViewById(R.id.examName); if (name == null) { Log.w("", "TextView is null"); }
        name.append(exam.getName().trim());
        TextView code = (TextView) findViewById(R.id.examCode); if (code == null) { Log.w("", "TextView is null"); }
        code.append(exam.getCode());
        TextView date = (TextView) findViewById(R.id.examDate); if (date == null) { Log.w("", "TextView is null"); }
        date.append(exam.getExamDate());
        TextView time = (TextView) findViewById(R.id.examTime); if (time == null) { Log.w("", "TextView is null"); }
        time.append(exam.getBeginsAt());
        TextView description = (TextView) findViewById(R.id.examDescription); if (description == null) { Log.w("", "TextView is null"); }
        description.append(exam.getExamDate());
    }
}


text:
<html>
	<head>
		<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
		<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
	</head>

	<body>
		<div class="container">

		</div>
	</body>

	<footer>
		<script src="js/jquery-1.10.2.min.js"></script>
		<script src="js/bootstrap.min.js"></script>
		<script src="js/options.js"></script>
	</footer>
</html>


text:
namespace fxcrt {

// A shared pointer to an object with Copy on Write semantics that makes it
// appear as if all instances were independent. |ObjClass| must implement the
// requirements of |Retainable| from retain_ptr.h, and must also provide a
// Clone() method. Often this will just call MakeRetain<>(*this) but will need
// to be virtual if |ObjClass| is subclassed.
template <class ObjClass>
class SharedCopyOnWrite {
 public:
  SharedCopyOnWrite() {}
  SharedCopyOnWrite(const SharedCopyOnWrite& other)
      : m_pObject(other.m_pObject) {}
  ~SharedCopyOnWrite() {}

  template <typename... Args>
  ObjClass* Emplace(Args... params) {
    m_pObject = pdfium::MakeRetain<ObjClass>(params...);
    return m_pObject.Get();
  }

  SharedCopyOnWrite& operator=(const SharedCopyOnWrite& that) {
    if (*this != that)
      m_pObject = that.m_pObject;
    return *this;
  }

  void SetNull() { m_pObject.Reset(); }
  const ObjClass* GetObject() const { return m_pObject.Get(); }

  template <typename... Args>
  ObjClass* GetPrivateCopy(Args... params) {
    if (!m_pObject)
      return Emplace(params...);
    if (!m_pObject->HasOneRef())
      m_pObject = m_pObject->Clone();
    return m_pObject.Get();
  }

  bool operator==(const SharedCopyOnWrite& that) const {
    return m_pObject == that.m_pObject;
  }
  bool operator!=(const SharedCopyOnWrite& that) const {
    return !(*this == that);
  }
  explicit operator bool() const { return !!m_pObject; }

 private:
  RetainPtr<ObjClass> m_pObject;
};

}  // namespace fxcrt

using fxcrt::SharedCopyOnWrite;

#endif  // CORE_FXCRT_SHARED_COPY_ON_WRITE_H_


text:
<resources>

    <style name="MultiPaneSupportTheme" parent="MaterialNavigationDrawerTheme.Light">
        <item name="multipaneSupport">true</item>
    </style>

    <style name="MultiPaneBelowToolbarSupportTheme" parent="MaterialNavigationDrawerTheme.Light">
        <item name="multipaneSupport">true</item>
        <item name="belowToolbar">true</item>
    </style>

    <style name="ActionBarOverlayTheme" parent="MaterialNavigationDrawerTheme.Light">
        <item name="actionBarOverlay">true</item>
        <item name="actionBarOverlayAlpha">0.6</item>
    </style>

    <style name="BelowToolbarTheme" parent="MaterialNavigationDrawerTheme.Light">
        <item name="belowToolbar">true</item>
    </style>

    <style name="UniqueToolbarColorTheme" parent="MaterialNavigationDrawerTheme.Light">
    <item name="uniqueToolbarColor">true</item>
    <item name="colorPrimary">#8bc34a</item>
    <item name="autoDarkStatusBar">true</item>
    <!-- if autoDarkStatusBar false, then the statusbar gets the color from colorPrimaryDark-->
    <!--<item name="colorPrimaryDark">#1C375B</item>-->
</style>

    <style name="MyOwnTheme" parent="MaterialNavigationDrawerTheme.Light.DarkActionBar">
        <item name="colorPrimary">#8bc34a</item>
        <item name="labelColor">#E67E22</item>
        <item name="colorAccent">#FFFFFF</item>
        <item name="drawerColor">#558b2f</item>
        <!-- use colorPrimaryDark color for the status bar (here dark blue), otherwiese it creates his own dark color -->
        <item name="autoDarkStatusBar">true</item>
        <!-- doesn't change the toolbar color on fragment change-->
        <item name="uniqueToolbarColor">false</item>
        <item name="sectionStyle">@style/MySectionTheme</item>
        <item name="headItemStyle">@style/MyMaterialHeadItemTheme</item>
        <item name="multipaneSupport">false</item>
        <item name="dividerStrokeWidth">1dp</item>
        <item name="dividerColor">@drawable/divider_my_theme</item>
    </style>

    <style name="MySectionTheme" >
        <item name="sectionColorIcon">#3A74C5</item>
        <item name="sectionColorText">#3A74C5</item>
        <item name="sectionColorNotification">#3A74C5</item>
        <item name="sectionOnPressHighLightColor">#dbcbbc</item>
        <item name="sectionBackgroundColorSelected">#feacff</item>
        <item name="sectionBackgroundColor">#b9faff</item>
        <item name="sectionRippleColor">#f89d54</item>
    </style>

    <style name="MyMaterialHeadItemTheme">
        <item name="titleColor">#f9bd80</item>
        <item name="subTitleColor">#f9bd80</item>
        <item name="backgroundGradient">@drawable/red_gradient</item>
    </style>

</resources>