text:
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
* @file tera_sample.cc
* @author yanshiguang02@baidu.com
* @date 2014/02/05 19:55:54
* @brief Sample of Tera API
*  每个表都有个默认的LocalityGroup "default" 要么被用户显示创建, 要么被系统创建
*  每个表都有个某人的ColumnFamily ""
*      要么被用户显示创建, 要么被系统创建, 默认属于lg default
*      不包含列和版本
*  这么创建表:
*  create table
*{{localitygrop:{{"lg1":{"block_size":5}},{"lg2":{"store_type":"disk"}}},{"columnfamily":{"cf1":{}}}}}
**/

#include <stdio.h>
#include <time.h>
#include <unistd.h>

#include "tera.h"

/// 创建一个表格
int CreateTable(tera::Client* client) {
  // 创建一个表格的描述
  tera::TableDescriptor table_desc("webdb");

  // 创建LocalityGroup
  tera::LocalityGroupDescriptor* lgd0 = table_desc.AddLocalityGroup("lg0");
  lgd0->SetBlockSize(128 * 1024);
  lgd0->SetCompress(tera::kSnappyCompress);

  tera::LocalityGroupDescriptor* lgd1 = table_desc.AddLocalityGroup("lg1");
  lgd1->SetBlockSize(32 * 1024);
  lgd1->SetCompress(tera::kSnappyCompress);

  // 创建ColumnFamily
  tera::ColumnFamilyDescriptor* cfd1 = table_desc.AddColumnFamily("html", "lg0");
  cfd1->SetMaxVersions(5);
  cfd1->SetMinVersions(3);
  cfd1->SetTimeToLive(86400 * 100);
  tera::ColumnFamilyDescriptor* cfd2 = table_desc.AddColumnFamily("links", "lg1");
  cfd2->SetMaxVersions(5);
  cfd2->SetMinVersions(0);
  cfd2->SetTimeToLive(86400 * 100);
  tera::ColumnFamilyDescriptor* cfd3 = table_desc.AddColumnFamily("title", "lg1");
  cfd3->SetMaxVersions(5);
  table_desc.AddColumnFamily("anchor", "lg1");

  tera::ErrorCode error_code;
  if (!client->CreateTable(table_desc, &error_code)) {
    printf("Create Table fail: %s\n", tera::strerr(error_code));
  }
  return 0;
}

/// 修改一个表的内容
int ModifyTable(tera::Table* table) {
  tera::ErrorCode error_code;

  // 修改需要先创建一个 RowMutation

  tera::RowMutation* row = table->NewRowMutation("com.baidu.www/");
  // 写一个column
  row->Put("title", "abc", "Baidu.com");
  row->Put("title", "abd", "Baidu.com");
  row->Put("title", "abe", "Baidu.com");
  row->Put("title", "abf", "Baidu.com");
  row->Put("anchor", "www.hao123.com/", "百度");
  row->Put("html", "", time(NULL), "<html>Test content</html>");
  // 删除一个column过去24小时内的所有版本
  // row->DeleteColumns("title", "abc", time(NULL), time(NULL) - 86400);
  // 删除一个column24小时之前的所有版本
  row->DeleteColumns("title", "abd", time(NULL) - 86400);
  // 删除一个column的所有版本
  row->DeleteColumns("title", "abe");
  // 删除一个columnfamily的所有列
  row->DeleteFamily("links");

  // 提交修改
  table->ApplyMutation(row);
  printf("Write to table : %s\n", tera::strerr(row->GetError()));
  delete row;

  // 批量提交修改
  tera::RowMutation* row2 = table->NewRowMutation("com.baidu.tieba/");
  // 删除一行的所有column family
  row2->DeleteRow();
  std::vector<tera::RowMutation*> mutation_list;
  mutation_list.push_back(row2);
  table->ApplyMutation(mutation_list);
  printf("Write to table : %s\n", tera::strerr(mutation_list[0]->GetError()));
  delete row2;

  return 0;
}

/// 扫描一个表
int ScanTable(tera::Table* table) {
  tera::ErrorCode error_code;

  // 创建一个scan表述
  tera::ScanDescriptor scan_desc("com.baidu.");
  // 只扫描百度主域
  scan_desc.SetEnd("com.baidu.~");
  // 设置扫描的column family
  scan_desc.AddColumnFamily("anchor");
  // 设置最多返回的版本
  scan_desc.SetMaxVersions(3);
  // 设置扫描的时间范围
  scan_desc.SetTimeRange(time(NULL), time(NULL) - 3600);

  tera::ResultStream* scanner = table->Scan(scan_desc, &error_code);
  for (scanner->LookUp("com.baidu."); !scanner->Done(); scanner->Next()) {
    printf("Row: %s\%s\%ld\%s\n", scanner->RowName().c_str(), scanner->ColumnName().c_str(),
           scanner->Timestamp(), scanner->Value().c_str());
  }
  delete scanner;
  return 0;
}

bool finish = false;

void ReadRowCallBack(tera::RowReader* row_reader) {
  while (!row_reader->Done()) {
    printf("Row: %s\%s\%ld\%s\n", row_reader->RowName().c_str(), row_reader->ColumnName().c_str(),
           row_reader->Timestamp(), row_reader->Value().c_str());
    row_reader->Next();
  }
  delete row_reader;
  finish = true;
}

int ReadRowFromTable(tera::Table* table) {
  tera::ErrorCode error_code;
  tera::RowReader* row_reader = table->NewRowReader("com.baidu.www/");
  row_reader->AddColumnFamily("html");
  row_reader->AddColumn("anchor", "www.hao123.com/");
  row_reader->SetMaxVersions(3);
  row_reader->SetAsync();
  row_reader->SetCallBack(ReadRowCallBack);
  // Async Read one row
  table->Get(row_reader);

  while (!finish) {
    sleep(1);
  }

  // Sync Read Batch Rows

  std::vector<tera::RowReader*> rows_reader;
  tera::RowReader* row_reader1 = table->NewRowReader("com.baidu.www/");
  row_reader1->AddColumnFamily("html");
  row_reader1->SetMaxVersions(3);
  row_reader1->SetTimeOut(5000);
  rows_reader.push_back(row_reader1);
  tera::RowReader* row_reader2 = table->NewRowReader("com.baidu.www/");
  row_reader2->AddColumnFamily("anchor");
  row_reader2->SetMaxVersions(3);
  row_reader2->SetTimeOut(5000);
  rows_reader.push_back(row_reader2);
  table->Get(rows_reader);

  while (!row_reader1->Done()) {
    printf("Row: %s\%s\%ld\%s\n", row_reader1->RowName().c_str(), row_reader1->ColumnName().c_str(),
           row_reader1->Timestamp(), row_reader1->Value().c_str());
    row_reader1->Next();
  }
  delete row_reader1;
  while (!row_reader2->Done()) {
    printf("Row: %s\%s\%ld\%s\n", row_reader2->RowName().c_str(), row_reader2->ColumnName().c_str(),
           row_reader2->Timestamp(), row_reader2->Value().c_str());
    row_reader2->Next();
  }
  delete row_reader2;
  return 0;
}

/// 三维表格
int ShowBigTable(tera::Client* client) {
  tera::ErrorCode error_code;
  // Create
  CreateTable(client);
  // Open
  tera::Table* table = client->OpenTable("webdb", &error_code);
  if (table == NULL) {
    printf("Open table fail: %s\n", tera::strerr(error_code));
    return 1;
  }
  // Write
  ModifyTable(table);
  // Scan
  // ScanTable(table);
  // Read
  ReadRowFromTable(table);
  delete table;
  return 0;
}

/// 二维表格
int ShowSampleTable(tera::Client* client) {
  tera::ErrorCode error_code;
  // 创建表格,并关闭多版本
  tera::TableDescriptor desc("sample_table");
  tera::ColumnFamilyDescriptor* cfd = desc.AddColumnFamily("weight");
  cfd->SetMaxVersions(0);
  client->CreateTable(desc, &error_code);

  // Open
  tera::Table* table = client->OpenTable("sample_table", &error_code);
  // Write
  table->Put("com.baidu.www/", "weight", "", "serialized_weights", &error_code);
  // Read
  std::string value;
  if (table->Get("com.baidu.www/", "weight", "", &value, &error_code)) {
    printf("Read return %s\n", value.c_str());
  }
  // Close
  delete table;
  return 0;
}

/// 把表格作为一个kv使用
int ShowKv(tera::Client* client) {
  tera::ErrorCode error_code;
  // Create
  tera::TableDescriptor schema("kvstore");
  client->CreateTable(schema, &error_code);
  // Open
  tera::Table* table = client->OpenTable("kvstore", &error_code);
  // Write
  table->Put("test_key", "", "", "test_value", &error_code);
  // Read
  std::string value;
  if (table->Get("test_key", "", "", &value, &error_code)) {
    printf("Read return %s\n", value.c_str());
  }
  // Close
  delete table;
  return 0;
};

/// 演示程序
int main(int argc, char* argv[]) {
  tera::ErrorCode error_code;
  // 根据配置创建一个client
  tera::Client* client = tera::Client::NewClient("./tera.flag", "tera_sample", &error_code);
  if (client == NULL) {
    printf("Create tera client fail: %s\n", tera::strerr(error_code));
    return 1;
  }

  // CreateTable(client);
  // 演示三种使用方式
  ShowBigTable(client);
  // ShowSampleTable(client);
  // ShowKv(client);
  return 0;
}

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */


text:
<!DOCTYPE html>

      <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no" >
      <meta http-equiv='cache-control' content='no-cache'>
      <meta http-equiv='expires' content='0'>
      <meta http-equiv='pragma' content='no-cache'>
        <title>FactiGIS</title>

        <link rel="stylesheet" type="text/css" href="arcgis_js_api/library/3.17/3.17/dijit/themes/tundra/tundra.css" />
        <link rel="stylesheet" type="text/css" href="arcgis_js_api/library/3.17/3.17/esri/css/esri.css" />
        <link rel="stylesheet" href="dist/css/login.css">

redpajama_set_name: RedPajamaGithub


text:
require 'excon'

module HttpCallback
  def http_callback(web_hook)
    http_execute(web_hook[:url], web_hook[:message])
  end

  alias_method :https_callback, :http_callback

  def http_execute(uri, data, options={})
    connection = Excon.new(
      uri.to_s,
      ssl_verify_peer: ENV['SSL_VERIFY_PEER'],
      omit_default_port: true
    )
    request = {
      method: options[:method] || :post,
      headers: options[:headers] || {},
      expects: (200..207).to_a,
      idempotent: !options[:no_retry],
      retry_limit: (options.key?(:retry_max) ? options[:retry_max].to_i : 6),
      middlewares: Excon.defaults[:middlewares] + [Excon::Middleware::RedirectFollower]
    }

    if [:post, :put, :patch].include?(request[:method])
      request[:headers]['Content-Type'] = mime_type_string(options[:content_type] || :json)
      request[:body] = data
    elsif data.is_a?(Hash)
      headers[:query] = data
    end

    connection.request(request)
  end

  def mime_type_string(type)
    case type
    when :json
      'application/json; charset=utf-8'
    when :form
      'application/x-www-form-urlencoded'
    else
      'text/html; charset=utf-8'
    end
  end
end


text:
package wordCount;

/**
 * Hello World of MapReduce
 */
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WordCount {

    public static void main(String[] args) throws Exception {
        String[] argc = {"MRdata/wordcount","output/wc"};  // local
//        String[] argc = {"hdfs://hdhost:9000/user/hadooper/input","hdfs://hdhost:9000/user/hadooper/output/wc"}; // hdfs
        args = argc;
        if(args.length !=2){
            System.err.println("Invalid Command");
            System.err.println("Usage: WordCount <input path> <output path>");
            System.exit(0);
        }

        Configuration conf = new Configuration();
        Job job = new Job(conf, "wordcount");
        job.setJarByClass(WordCount.class);
        job.setJobName("Word Count");
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        System.exit(job.waitForCompletion(true)?0:1);
    }
}


text:
package com.iphone567.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFilterConfig implements Filter {

	private FilterConfig filterConfig;

	public MyFilterConfig() {
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String encoding = filterConfig.getInitParameter("encoding");
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);

		System.out.println("用拦截器 设置默认编码方式");

		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">LolliPin</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="activity_not_locked_text">Nothing should happen on this page, here for test purpose</string>
    <string name="activity_dialog_title">Forgot you Pincode?</string>
    <string name="activity_dialog_accept">OK</string>
    <string name="activity_dialog_decline">CANCEL</string>
    <string name="activity_dialog_content">Tap \'OK\' to log out, when you log back in you\'ll be able to create a new Pincode.\n\nIf you remember your Pincode, tap \'Cancel\' to go back.</string>
    <string name="activity_appcompat_message">I am a PinCompatActivity!</string>

</resources>


text:
Datatables are an enhanced version of an HTML table and are used to display tabular data.

You should provide an array of objects in the `[data]` property and define each column using a `ngl-datatable-column` component.

Optionally, you can specify a template inside a column, that will be used to render each cell of this column. Inside this template you can have access to the implicit value of the cell, it's `index` and the `row`'s' data.

You can easily support sorting by adding the `sortable` on each column that you want to be sortable, and listen to `sortChange` events that produce event objects like `<INglDatatableSort>{ key: 'key of sorted column', order: 'asc or desc'}`.

You can optionally specify a `ng-template[nglLoadingOverlay]` thats gets displayed when it is `loading` data, and a `ng-template[nglNoRowsOverlay]` to be displayed when there are no rows to show.


text:
package main

type UnionType struct {
	pkg  *Package
	name string
}

func (t *UnionType) String() string {
	return t.pkg.Path + "::" + t.name
}

func (t *UnionType) Equals(t2 Type) bool {
	ut, ok := t2.(*UnionType)
	if !ok {
		return false
	}
	return t == ut
}

func (t *UnionType) Resolved() Type {
	panic("bug")
}

func (t *UnionType) Resolve() {
}

func (t *UnionType) Name() string {
	return t.name
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ceská Mykol. 45(4): 136 (1992)

#### Original name
Psilocistella parca Svrcek

### Remarks
null


text:
@implementation CollectionViewCell

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self.contentView addSubview:self.imgView];
    }
    return self;

}

-(UIImageView *)imgView {
    if (!_imgView) {
        _imgView = [[UIImageView alloc] initWithFrame:self.bounds];
        _imgView.image = [UIImage imageNamed:@"img"];

    }
    return _imgView;
}
@end


text:
\chapter{Logistic Regression}

\section{Representation}
Logistic regression can be binomial or multinomial. The \textbf{binomial logistic regression} model has the following form
\begin{equation}
p(y|\vec{x},\vec{w})=\mathrm{Ber}(y|\mathrm{sigm}(\vec{w}^T\vec{x}))
\end{equation}
where $\vec{w}$ and $\vec{x}$ are extended vectors, i.e., $\vec{w}=(b, w_1, w_2,\cdots, w_D)$, $\vec{x}=(1, x_1, x_2,\cdots, x_D)$.

\section{Optimization}
\label{sec:binomial-LR-Optimization}

\subsection{MLE}
\begin{align}
\ell(\vec{w}) &= \log\left\{\prod\limits_{i=1}^N{\left[\pi(\vec{x}_i)\right]^{y_i}\left[1-\pi(\vec{x}_i)\right]^{1-y_i}}\right\} \nonumber \\
              & \quad \text{, where } \pi(\vec{x}) \triangleq P(y=1|\vec{x},\vec{w}) \nonumber \\
           &= \sum\limits_{i=1}^N\left[y_i\log\pi(\vec{x}_i)+(1-y_i)\log(1-\pi(\vec{x}_i))\right] \label{eqn:cross-entropy-error} \nonumber \\
		   &= \sum\limits_{i=1}^N\left[y_i\log\dfrac{\pi(\vec{x}_i)}{1-\pi(\vec{x}_i)}+\log(1-\pi(\vec{x}_i))\right] \nonumber \\
		   &= \sum\limits_{i=1}^N\left[y_i(\vec{w}\cdot\vec{x}_i)-\log(1+\exp(\vec{w}\cdot\vec{x}_i))\right] \nonumber \\
J(\vec{w}) & \triangleq \mathrm{NLL}(\vec{w})= -\ell(\vec{w}) \nonumber \\
           & = -\sum\limits_{i=1}^N\left[y_i(\vec{w}\cdot\vec{x}_i)-\log(1+\exp(\vec{w}\cdot\vec{x}_i))\right]
\end{align}

Equation \ref{eqn:cross-entropy-error} is also called the \textbf{cross-entropy} error function (see Equation \ref{eqn:cross-entropy}).

Unlike linear regression, we can no longer write down the MLE in closed form. Instead, we need to use an optimization algorithm to compute it, see Appendix \ref{chap:Optimization-methods}. For this, we need to derive the gradient and Hessian.

In the case of logistic regression, one can show that the gradient and Hessian of this are given by the following
\begin{align}
\vec{g}(\vec{w}) &= \dfrac{\mathrm{d} J}{\mathrm{d} \vec{w}} = \sum\limits_{i=1}^N \left[\pi(\vec{x}_i) - y_i \right]\vec{x}_i = \vec{X}(\vec{\pi}-\vec{y})\\
\vec{H}(\vec{w}) &= \dfrac{\mathrm{d} \vec{g}^T}{\mathrm{d} \vec{w}}= \dfrac{\mathrm{d}}{\mathrm{d} \vec{w}} (\vec{\pi}-\vec{y})^T\vec{X}^T \nonumber \\
        &= \dfrac{\mathrm{d}}{\mathrm{d} \vec{w}} \vec{\pi}^T\vec{X}^T \nonumber \\
		&= (\pi(\vec{x}_i)(1-\pi(\vec{x}_i))\vec{x}_i, \cdots,)\vec{X}^T \nonumber \\
		&= \vec{X}\vec{S}\vec{X}^T, \quad \vec{S} \triangleq \mathrm{diag}(\pi(\vec{x}_i)(1-\pi(\vec{x}_i))\vec{x}_i)
\end{align}

\subsubsection{Iteratively reweighted least squares (IRLS)}
\label{sec:IRLS}
TODO

\subsection{MAP}
Just as we prefer ridge regression to linear regression, so we should prefer MAP estimation for logistic regression to computing the MLE.
$\ell_2$ regularization

we can use $\ell_2$ regularization, just as we did with ridge regression. We note that the new objective, gradient and Hessian have the following forms:
\begin{align}
J'(\vec{w}) & \triangleq \mathrm{NLL}(\vec{w})+\lambda \vec{w}^T\vec{w} \\
\vec{g}'(\vec{w}) &= \vec{g}(\vec{w})+\lambda\vec{w} \\
\vec{H}'(\vec{w}) &= \vec{H}(\vec{w})+\lambda\vec{I}
\end{align}

It is a simple matter to pass these modified equations into any gradient-based optimizer.

\section{Multinomial logistic regression}

\subsection{Representation}
\textbf{Multinomial logistic regression} model is also called a \textbf{maximum entropy classifier}, which has the following form
\begin{align}
p(y=c|\vec{x},\vec{W}) & =\dfrac{\exp(\vec{w}_c^T\vec{x})}{\sum_{c=1}^C \exp(\vec{w}_c^T\vec{x})}
\end{align}

\subsection{MLE}
Let $\vec{y}_i=(\mathbb{I}(y_i=1),\mathbb{I}(y_i=1),\cdots, \mathbb{I}(y_i=C))$, $\vec{\mu}_i=(p(y=1|\vec{x}_i,\vec{W}),p(y=2|\vec{x}_i,\vec{W}),\cdots, p(y=C|\vec{x}_i,\vec{W}))$, then the log-likelihood function can be written as
\begin{align}
\ell(\vec{W}) & =\log\prod\limits_{i=1}^N\prod\limits_{c=1}^C \mu_{ic}^{y_{ic}}=\sum\limits_{i=1}^N\sum\limits_{c=1}^C y_{ic}\log \mu_{ic} \\
     & = \sum\limits_{i=1}^N\left[\left(\sum\limits_{c=1}^C y_{ic}\vec{w}_c^T\vec{x}_i\right)-\log\left(\sum\limits_{c=1}^C \exp(\vec{w}_c^T\vec{x}_i)\right)\right]
\end{align}

Define the objective function as NLL
\begin{equation}
J(\vec{W})=\mathrm{NLL}(\vec{W})=-\ell(\vec{W})
\end{equation}

Define $\vec{A} \otimes \vec{B}$ be the \textbf{kronecker product} of matrices $\vec{A}$ and $\vec{B}$.If $\vec{A}$ is an $m \times n$ matrix and $\vec{B}$ is a $p \times q$ matrix, then $\vec{A} \otimes \vec{B}$ is the $mp \times nq$ block matrix
\begin{equation}
\vec{A} \otimes \vec{B} \triangle \left(\begin{array}{ccc}
a_{11}\vec{B} & \cdots & a_{1n}\vec{B} \\
\vdots & \vdots & \vdots \\
a_{m1}\vec{B} & \cdots & a_{mn}\vec{B}
\end{array}\right)
\end{equation}

The gradient and Hessian are given by
\begin{align}
\vec{g}(\vec{W}) & =\sum\limits_{i=1}^N (\vec{\mu}-\vec{y}_i) \otimes \vec{x}_i \\
\vec{H}(\vec{W}) & =\sum\limits_{i=1}^N (\mathrm{diag}(\vec{\mu}_i)-\vec{\mu}_i\vec{\mu}_i^T) \otimes (\vec{x}_i\vec{x}_i^T)
\end{align}
where $\vec{y}_i=(\mathbb{I}(y_i=1),\mathbb{I}(y_i=1),\cdots, \mathbb{I}(y_i=C-1))$ and $\vec{\mu}_i=(p(y=1|\vec{x}_i,\vec{W}),p(y=2|\vec{x}_i,\vec{W}),\cdots, p(y=C-1|\vec{x}_i,\vec{W}))$ are column vectors of length $C-1$.

Pass them to any gradient-based optimizer.

\subsection{MAP}
The new objective
\begin{align}
J'(\vec{W}) & =\mathrm{NLL}(\vec{w})-\log{p(\vec{W})} \\
            & \quad \text{, where } p(\vec{W}) \triangleq \prod\limits_{c=1}^C \mathcal{N}(\vec{w}_c|\vec{0},\vec{V}_0) \nonumber \\
   & = J(\vec{W})+\dfrac{1}{2}\sum\limits_{c=1}^C \vec{w}_c\vec{V}_0^{-1}\vec{w}_c \\
\end{align}

Its gradient and Hessian are given by
\begin{align}
\vec{g}'(\vec{w}) & =\vec{g}(\vec{W})+\vec{V}_0^{-1}\left(\sum\limits_{c=1}^C \vec{w}_c\right) \\
\vec{H}'(\vec{w}) & =\vec{H}(\vec{w})+\vec{I_C} \otimes \vec{V}_0^{-1}
\end{align}

This can be passed to any gradient-based optimizer to find the MAP estimate. Note, however, that the Hessian has size $((CD)×(CD))$, which is $C$ times more row and columns than in the binary case, so limited memory BFGS is more appropriate than Newton's method.

\section{Bayesian logistic regression}
It is natural to want to compute the full posterior over the parameters, $p(\vec{w}|\mathcal{D})$, for logistic regression models. This can be useful for any situation where we want to associate confidence intervals with our predictions (e.g., this is necessary when solving contextual bandit problems, discussed in Section TODO).

Unfortunately, unlike the linear regression case, this cannot be done exactly, since there is no convenient conjugate prior for logistic regression. We discuss one simple approximation below; some other approaches include MCMC (Section TODO), variational inference (Section TODO), expectation propagation (Kuss and Rasmussen 2005), etc. For notational simplicity, we stick to binary logistic regression.

\subsection{Laplace approximation}

\subsection{Derivation of the BIC}

\subsection{Gaussian approximation for logistic regression}
\label{sec:Gaussian-approximation-for-logistic-regression}

\subsection{Approximating the posterior predictive}

\subsection{Residual analysis (outlier detection) *}

\section{Online learning and stochastic optimization}
Traditionally machine learning is performed \textbf{offline}, however, if we have \textbf{streaming data}, we need to perform \textbf{online learning}, so we can update our estimates as each new data point arrives rather than waiting until "the end" (which may never occur). And even if we have a batch of data, we might want to treat it like a stream if it is too large to hold in main memory. Below we discuss learning methods for this kind of scenario.

TODO

\subsection{The perceptron algorithm}

\subsubsection{Representation}
\begin{equation}
\mathcal{H}:y=f(\vec{x})=\text{sign}(\vec{w}^T\vec{x}+b)
\end{equation}
where $\text{sign}(x)=\begin{cases}+1, & x \geq 0\\-1, & x<0\\\end{cases}$, see Fig. \ref{fig:perceptron}\footnote{\url{https://en.wikipedia.org/wiki/Perceptron}}.

\begin{figure}[hbtp]
\centering
    \includegraphics[scale=.50]{perceptron.png}
\caption{Perceptron}
\label{fig:perceptron}
\end{figure}

\subsubsection{Evaluation}
\begin{eqnarray}
L(\vec{w},b)&=&-y_i(\vec{w}^T\vec{x}_i+b)\\
R_{emp}(f)&=&-\sum\limits_i y_i(\vec{w}^T\vec{x}_i+b)\\
\end{eqnarray}

\subsubsection{Optimization}
\textbf{Primal form}
\begin{algorithm}[htbp]
\caption{Perceptron learning algorithm, primal form, using SGD}

    $\vec{w} \leftarrow 0;\; b \leftarrow 0;\; k \leftarrow 0$\;
    \While{no mistakes made within the for loop}{
        \For{$i\leftarrow 1$ \KwTo $N$}{
			\If{$y_i(\vec{w} \cdot \vec{x}_i+b) \leq 0$}{
				$\vec{w} \leftarrow \vec{w}+\eta y_i \vec{x}_i$\;
				$b \leftarrow b+\eta y_i$\;
				$k \leftarrow k+1$\;
			}
		}
    }
\end{algorithm}

\textbf{Convergency}
\begin{theorem}
(\textbf{Novikoff}) If traning data set $\mathcal{D}$ is linearly separable, then
\begin{enumerate}
\item There exists a hyperplane denoted as $\widehat{\vec{w}}_{opt} \cdot \vec{x}+b_{opt}=0$ which can correctly seperate all samples, and
\begin{equation}
\exists\gamma>0,\; \forall i, \; y_i(\vec{w}_{opt} \cdot \vec{x}_i+b_{opt}) \geq \gamma
\end{equation}
\item \begin{equation}k \leq \left(\dfrac{R}{\gamma}\right)^2,\text{ where } R=\max\limits_{1 \leq i \leq N} \abs{\abs{\widehat{\vec{x}}_i}}
\end{equation}
\end{enumerate}
\end{theorem}

\begin{proof}
(1) let $\gamma=\min\limits_{i} y_i(\vec{w}_{opt} \cdot \vec{x}_i+b_{opt})$, then we get $y_i(\vec{w}_{opt} \cdot \vec{x}_i+b_{opt}) \geq \gamma$.

(2) The algorithm start from $\widehat{\vec{x}}_0=0$, if a instance is misclassified, then update the weight. Let $\widehat{\vec{w}}_{k-1}$ denotes the extended weight before the k-th misclassified instance, then we can get
\begin{eqnarray}
y_i(\widehat{\vec{w}}_{k-1} \cdot \widehat{\vec{x}_i})&=&y_i(\vec{w}_{k-1} \cdot \vec{x}_i+b_{k-1}) \leq 0\\
\widehat{\vec{w}}_k&=&\widehat{\vec{w}}_{k-1}+\eta y_i \widehat{\vec{x}_i}
\end{eqnarray}

We could infer the following two equations, the proof procedure are omitted.
\begin{enumerate}
\item $\widehat{\vec{w}}_k \cdot \widehat{\vec{w}}_{opt} \geq k\eta\gamma$
\item $\abs{\abs{\widehat{\vec{w}}_k}}^2 \leq k\eta^2R^2$
\end{enumerate}

From above two equations we get
\begin{eqnarray}
\nonumber k\eta\gamma & \leq & \widehat{\vec{w}}_k \cdot \widehat{\vec{w}}_{opt} \leq \abs{\abs{\widehat{\vec{w}}_k}}\abs{\abs{\widehat{\vec{w}}_{opt}}} \leq \sqrt k \eta R \\
\nonumber k^2\gamma^2 & \leq & kR^2 \\
\nonumber \text{i.e. } k & \leq & \left(\dfrac{R}{\gamma}\right)^2
\end{eqnarray}
\end{proof}

\textbf{Dual form}
\begin{eqnarray}
\vec{w}&=&\sum\limits_{i=1}^{N} \alpha_iy_i\vec{x}_i \\
b&=&\sum\limits_{i=1}^{N} \alpha_iy_i \\
f(\vec{x})&=&\text{sign}\left(\sum\limits_{j=1}^{N} \alpha_jy_j\vec{x}_j \cdot \vec{x}+b\right)
\end{eqnarray}

\begin{algorithm}[htbp]
    %\SetAlgoLined
    \SetAlgoNoLine

    $\vec{\alpha} \leftarrow 0;\; b \leftarrow 0;\; k \leftarrow 0$\;
    \While{no mistakes made within the for loop}{
        \For{$i\leftarrow 1$ \KwTo $N$}{
			\If{$y_i\left(\sum\limits_{j=1}^{N} \alpha_jy_j\vec{x}_j \cdot \vec{x}_i+b\right) \leq 0$}{
				$\vec{\alpha} \leftarrow \vec{\alpha}+\eta$\;
				$b \leftarrow b+\eta y_i$\;
				$k \leftarrow k+1$\;
			}
		}
    }
\caption{Perceptron learning algorithm, dual form}
\end{algorithm}

\section{Generative vs discriminative classifiers}

\subsection{Pros and cons of each approach}
\begin{itemize}
\item{\textbf{Easy to fit?} As we have seen, it is usually very easy to fit generative classifiers. For example, in Sections \ref{sec:NBC-Optimization} and \ref{sec:MLE-for-discriminant-analysis}, we show that we can fit a naive Bayes model and an LDA model by simple counting and averaging. By contrast, logistic regression requires solving a convex optimization problem (see Section \ref{sec:binomial-LR-Optimization} for the details), which is much slower.}

\item{\textbf{Fit classes separately?} In a generative classifier, we estimate the parameters of each class conditional density independently, so we do not have to retrain the model when we add more classes. In contrast, in discriminative models, all the parameters interact, so the whole model must be retrained if we add a new class. (This is also the case if we train a generative model to maximize a discriminative objective Salojarvi et al. (2005).)}

\item{\textbf{Handle missing features easily?} Sometimes some of the inputs (components ofx) are not observed. In a generative classifier, there is a simple method for dealing with this, as we discuss in Section \ref{sec:Dealing-with-missing-data}. However, in a discriminative classifier, there is no principled solution to this problem, since the model assumes that $\vec{x}$is always available to be conditioned on (although see (Marlin 2008) for some heuristic approaches).}

\item{\textbf{Can handle unlabeled training data?} There is much interest in \textbf{semi-supervised learning}, which uses unlabeled data to help solve a supervised task. This is fairly easy to do using generative models (see e.g., (Lasserre et al. 2006; Liang et al. 2007)), but is much harder to do with discriminative models.}

\item{\textbf{Symmetric in inputs and outputs?} We can run a generative model "backwards", and infer probable inputs given the output by computing $p(\vec{x}|y)$. This is not possible with a discriminative model. The reason is that a generative model defines a joint distribution on $\vec{x}$ and $y$, and hence treats both inputs and outputs symmetrically.}

\item{\textbf{Can handle feature preprocessing?} A big advantage of discriminative methods is that they allow us to preprocess the input in arbitrary ways, e.g., we can replace $\vec{x}$ with $\phi(\vec{x})$, which could be some basis function expansion, etc. It is often hard to define a generative model on such pre-processed data, since the new features are correlated in complex ways.}

\item{\textbf{Well-calibrated probabilities?} Some generative models, such as naive Bayes, make strong independence assumptions which are often not valid. This can result in very extreme posterior class probabilities (very near 0 or 1). Discriminative models, such as logistic regression, are usually better calibrated in terms of their probability estimates.}
\end{itemize}

See Table \ref{tab:List-of-various-models-for-classification} for a summary of the classification and regression techniques we cover in this book.

\begin{table*}
\centering
\begin{tabular}{lllll}
\hline\noalign{\smallskip}
\textbf{Model} & \textbf{Classif/regr} & \textbf{Gen/Discr} & \textbf{Param/Non} & \textbf{Section} \\
\noalign{\smallskip}\svhline\noalign{\smallskip}
Discriminant analysis & Classif & Gen & Param & Sec. \ref{sec:Linear-discriminant-analysis}, \ref{sec:MLE-for-discriminant-analysis} \\
Naive Bayes classifier & Classif & Gen & Param & Sec. \ref{sec:NBC}, \ref{sec:Bayesian-naive-Bayes} \\
Tree-augmented Naive Bayes classifier & Classif & Gen & Param & Sec. 10.2.1 \\
Linear regression & Regr & Discrim & Param & Sec. 1.4.5, 7.3, 7.6 \\
Logistic regression & Classif & Discrim & Param & Sec. 1.4.6, \ref{sec:IRLS}, \ref{sec:Gaussian-approximation-for-logistic-regression}, 21.8.1.1 \\
Sparse linear/ logistic regression & Both & Discrim & Param & Ch. 13 \\
Mixture of experts & Both & Discrim & Param & Sec. 11.2.4 \\
Multilayer perceptron (MLP)/ Neural network & Both & Discrim & Param & Ch. 16 \\
Conditional random field (CRF) & Classif & Discrim & Param & Sec. 19.6 \\
\noalign{\smallskip}\hline \\
$K$ nearest neighbor classifier & Classif & Gen & Non & Sec. TODO, TODO \\
(Infinite) Mixture Discriminant analysis & Classif & Gen & Non & Sec. 14.7.3 \\
Classification and regression trees (CART) & Both & Discrim & Non & Sec. 16.2 \\
Boosted model & Both & Discrim & Non & Sec. 16.4 \\
Sparse kernelized lin/logreg (SKLR) & Both & Discrim & Non & Sec. 14.3.2 \\
Relevance vector machine (RVM) & Both & Discrim & Non & Sec. 14.3.2 \\
Support vector machine (SVM) & Both & Discrim & Non & Sec. 14.5 \\
Gaussian processes (GP) & Both & Discrim & Non & Ch. 15 \\
Smoothing splines & Regr & Discrim & Non & Section 15.4.6 \\
\noalign{\smallskip}\hline
\end{tabular}
\caption{List of various models for classification and regression which we discuss in this book. Columns are as follows: Model name; is the model suitable for classification, regression, or both; is the model generative or discriminative; is the model parametric or non-parametric; list of sections in book which discuss the model. See also \url{http://pmtk3.googlecode.com/svn/trunk/docs/tutorial/html/tutSupervised.html} for the PMTK equivalents of these models. Any generative probabilistic model (e.g., HMMs, Boltzmann machines, Bayesian networks, etc.) can be turned into a classifier by using it as a class conditional density}
\label{tab:List-of-various-models-for-classification}
\end{table*}

\subsection{Dealing with missing data}
\label{sec:Dealing-with-missing-data}
Sometimes some of the inputs (components of $\vec{x}$) are not observed; this could be due to a sensor failure, or a failure to complete an entry in a survey, etc. This is called the \textbf{missing data problem} (Little. and Rubin 1987). The ability to handle missing data in a principled way is one of the biggest advantages of generative models.

To formalize our assumptions, we can associate a binary response variable $r_i \in \{0,1\}$ that specifies whether each value $\vec{x}_i$ is observed or not. The joint model has the form $p(\vec{x}_i,r_i|\vec{\theta},\vec{\phi})=p(r_i|\vec{x}_i,\vec{\phi})p(\vec{x}_i|\vec{\theta})$, where $\vec{\phi}$ are the parameters controlling whether the item is observed or not.
\begin{itemize}
\item{If we assume $p(r_i|\vec{x}_i,\vec{\phi})=p(r_i|\vec{\phi})$, we say the data is \textbf{missing completely at random} or \textbf{MCAR}.}
\item{If we assume $p(r_i|\vec{x}_i,\vec{\phi})=p(r_i|\vec{x}_i^o,\vec{\phi})$, where $\vec{x}_i^o$ is the observed part of $\vec{x}_i$, we say the data is \textbf{missing at random} or \textbf{MAR}.}
\item{If neither of these assumptions hold, we say the data is \textbf{not missing at random} or \textbf{NMAR}. In this case, we have to model the missing data mechanism, since the pattern of missingness is informative about the values of the missing data and the corresponding parameters. This is the case in most collaborative filtering problems, for example.}
\end{itemize}

See e.g., (Marlin 2008) for further discussion. We will henceforth assume the data is MAR.

When dealing with missing data, it is helpful to distinguish the cases when there is missingness only at test time (so the training data is \textbf{complete data}), from the harder case when there is missingness also at training time. We will discuss these two cases below. Note that the class label is always missing at test time, by definition; if the class label is also sometimes missing at training time, the problem is called semi-supervised learning.

\subsubsection{Missing data at test time}
In a generative classifier, we can handle features that are MAR by marginalizing them out. For example, if we are missing the value ofx1, we can compute
\begin{align}
p(y=c|\vec{x}_{2:D},\vec{\theta}) & \propto p(y=c|\vec{\theta})p(\vec{x}_{2:D}|y=c,\vec{\theta}) \\
      & = \propto p(y=c|\vec{\theta})\sum\limits_{x_1}p(x_1, \vec{x}_{2:D}|y=c,\vec{\theta})
\end{align}

Similarly, in discriminant analysis, no matter what regularization method was used to estimate the parameters, we can always analytically marginalize out the missing variables (see Section \ref{sec:Inference-in-jointly-Gaussian-distributions}):
\begin{equation}
p(\vec{x}_{2:D}|y=c,\vec{\theta})=\mathcal{N}(\vec{x}_{2:D}|\vec{\mu}_{c,2:D},\vec{\Sigma}_{c,2:D})
\end{equation}

\subsubsection{Missing data at training time}
Missing data at training time is harder to deal with. In particular, computing the MLE or MAP estimate is no longer a simple optimization problem, for reasons discussed in Section TODO. However, soon we will study are a variety of more sophisticated algorithms (such as EM algorithm, in Section 11.4) for finding approximate ML or MAP estimates in such cases.

\subsection{Fisher's linear discriminant analysis (FLDA) *}
TODO


text:
package org.mingy.jcm;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.mingy.kernel.context.GlobalBeanContext;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "org.mingy.jcm"; //$NON-NLS-1$

	// The shared instance
	private static Activator plugin;

	/**
	 * The constructor
	 */
	public Activator() {
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
		loadApplicationContext();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
	 * )
	 */
	public void stop(BundleContext context) throws Exception {
		GlobalBeanContext.getInstance().shutdownContext();
		plugin = null;
		super.stop(context);
	}

	private void loadApplicationContext() {
		ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
		try {
			Thread.currentThread().setContextClassLoader(
					getDefault().getClass().getClassLoader());
			GlobalBeanContext.getInstance().loadClassPathContext(
					new String[] { "applicationContext.xml",
							"applicationContext-jcm.xml" });
			GlobalBeanContext.getInstance().registerShutdownHook();
		} finally {
			Thread.currentThread().setContextClassLoader(oldLoader);
		}
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}

	/**
	 * Returns an image descriptor for the image file at the given plug-in
	 * relative path
	 *
	 * @param path
	 *            the path
	 * @return the image descriptor
	 */
	public static ImageDescriptor getImageDescriptor(String path) {
		return imageDescriptorFromPlugin(PLUGIN_ID, path);
	}
}


text:
// If you want to access any of these options in React, don't forget to update CLIENT_CONFIG_OPTIONS array
// in loaders/styleguide-loader.js

const EXTENSIONS = 'js,jsx,ts,tsx';
const DEFAULT_COMPONENTS_PATTERN = `src/@(components|Components)/**/*.{${EXTENSIONS}}`;

const path = require('path');
const startCase = require('lodash/startCase');
const kleur = require('kleur');
const reactDocgen = require('react-docgen');
const createDisplayNameHandler = require('react-docgen-displayname-handler')
	.createDisplayNameHandler;
const annotationResolver = require('react-docgen-annotation-resolver').default;
const logger = require('glogg')('rsg');
const findUserWebpackConfig = require('../utils/findUserWebpackConfig');
const getUserPackageJson = require('../utils/getUserPackageJson');
const fileExistsCaseInsensitive = require('../utils/findFileCaseInsensitive');
const StyleguidistError = require('../utils/error');
const consts = require('../consts');

module.exports = {
	assetsDir: {
		type: 'existing directory path',
		example: 'assets',
	},
	compilerConfig: {
		type: 'object',
		default: {
			objectAssign: 'Object.assign',
		},
	},
	// `components` is a shortcut for { sections: [{ components }] },
	// see `sections` below
	components: {
		type: ['string', 'function', 'array'],
		example: 'components/**/[A-Z]*.js',
	},
	configDir: {
		process: (value, config, rootDir) => rootDir,
	},
	context: {
		type: 'object',
		default: {},
		example: {
			map: 'lodash/map',
		},
	},
	contextDependencies: {
		type: 'array',
	},
	configureServer: {
		type: 'function',
	},
	dangerouslyUpdateWebpackConfig: {
		type: 'function',
	},
	defaultExample: {
		type: ['boolean', 'existing file path'],
		default: false,
		process: val =>
			val === true ? path.resolve(__dirname, '../templates/DefaultExample.md') : val,
	},
	exampleMode: {
		type: 'string',
		process: (value, config) => {
			return config.showCode === undefined ? value : config.showCode ? 'expand' : 'collapse';
		},
		default: 'collapse',
	},
	getComponentPathLine: {
		type: 'function',
		default: componentPath => componentPath,
	},
	getExampleFilename: {
		type: 'function',
		default: componentPath => {
			const files = [
				path.join(path.dirname(componentPath), 'Readme.md'),
				componentPath.replace(path.extname(componentPath), '.md'),
			];

			for (const file of files) {
				const existingFile = fileExistsCaseInsensitive(file);
				if (existingFile) {
					return existingFile;
				}
			}

			return false;
		},
		example: componentPath => componentPath.replace(/\.jsx?$/, '.examples.md'),
	},
	handlers: {
		type: 'function',
		default: componentPath =>
			reactDocgen.defaultHandlers.concat(createDisplayNameHandler(componentPath)),
	},
	ignore: {
		type: 'array',
		default: [
			'**/__tests__/**',
			`**/*.test.{${EXTENSIONS}}`,
			`**/*.spec.{${EXTENSIONS}}`,
			'**/*.d.ts',
		],
	},
	highlightTheme: {
		type: 'string',
		default: 'base16-light',
		deprecated: 'Use the theme property in the editorConfig option instead',
	},
	editorConfig: {
		type: 'object',
		process: (value, config) => {
			const defaults = {
				theme: 'base16-light',
				mode: 'jsx',
				lineWrapping: true,
				smartIndent: false,
				matchBrackets: true,
				viewportMargin: Infinity,
				lineNumbers: false,
			};
			return Object.assign(
				{},
				defaults,
				config.highlightTheme && {
					theme: config.highlightTheme,
				},
				value
			);
		},
	},
	logger: {
		type: 'object',
	},
	mountPointId: {
		type: 'string',
		default: 'rsg-root',
	},
	pagePerSection: {
		type: 'boolean',
		default: false,
	},
	previewDelay: {
		type: 'number',
		default: 500,
	},
	printBuildInstructions: {
		type: 'function',
	},
	printServerInstructions: {
		type: 'function',
	},
	propsParser: {
		type: 'function',
	},
	require: {
		type: 'array',
		default: [],
		example: ['babel-polyfill', 'path/to/styles.css'],
	},
	resolver: {
		type: 'function',
		default: (ast, recast) => {
			const findAllExportedComponentDefinitions =
				reactDocgen.resolver.findAllExportedComponentDefinitions;
			const annotatedComponents = annotationResolver(ast, recast);
			const exportedComponents = findAllExportedComponentDefinitions(ast, recast);
			return annotatedComponents.concat(exportedComponents);
		},
	},
	ribbon: {
		type: 'object',
		example: {
			url: 'http://example.com/',
			text: 'Fork me on GitHub',
		},
	},
	sections: {
		type: 'array',
		default: [],
		process: (val, config) => {
			if (!val) {
				// If root `components` isn't empty, make it a first section
				// If `components` and `sections` weren't specified, use default pattern
				const components = config.components || DEFAULT_COMPONENTS_PATTERN;
				return [
					{
						components,
					},
				];
			}
			return val;
		},
		example: [
			{
				name: 'Documentation',
				content: 'Readme.md',
			},
			{
				name: 'Components',
				components: './lib/components/**/[A-Z]*.js',
			},
		],
	},
	serverHost: {
		type: 'string',
		default: '0.0.0.0',
	},
	serverPort: {
		type: 'number',
		default: 6060,
	},
	showCode: {
		type: 'boolean',
		default: false,
		deprecated: 'Use exampleMode option instead',
	},
	showUsage: {
		type: 'boolean',
		default: false,
		deprecated: 'Use usageMode option instead',
	},
	showSidebar: {
		type: 'boolean',
		default: true,
	},
	skipComponentsWithoutExample: {
		type: 'boolean',
		default: false,
	},
	sortProps: {
		type: 'function',
	},
	styleguideComponents: {
		type: 'object',
	},
	styleguideDir: {
		type: 'directory path',
		default: 'styleguide',
	},
	styles: {
		type: 'object',
		default: {},
		example: {
			Logo: {
				logo: {
					fontStyle: 'italic',
				},
			},
		},
	},
	template: {
		type: ['object', 'function'],
		default: {},
		process: val => {
			if (typeof val === 'string') {
				throw new StyleguidistError(
					`${kleur.bold(
						'template'
					)} config option format has been changed, you need to update your config.`,
					'template'
				);
			}
			return val;
		},
	},
	theme: {
		type: 'object',
		default: {},
		example: {
			link: 'firebrick',
			linkHover: 'salmon',
		},
	},
	title: {
		type: 'string',
		process: val => {
			if (val) {
				return val;
			}
			const name = getUserPackageJson().name || '';
			return `${startCase(name)} Style Guide`;
		},
		example: 'My Style Guide',
	},
	updateDocs: {
		type: 'function',
	},
	updateExample: {
		type: 'function',
		default: props => {
			if (props.lang === 'example') {
				props.lang = 'js';
				logger.warn(
					'"example" code block language is deprecated. Use "js", "jsx" or "javascript" instead:\n' +
						consts.DOCS_DOCUMENTING
				);
			}
			return props;
		},
	},
	updateWebpackConfig: {
		type: 'function',
		removed: `Use "webpackConfig" option instead:\n${consts.DOCS_WEBPACK}`,
	},
	usageMode: {
		type: 'string',
		process: (value, config) => {
			return config.showUsage === undefined ? value : config.showUsage ? 'expand' : 'collapse';
		},
		default: 'collapse',
	},
	verbose: {
		type: 'boolean',
		default: false,
	},
	version: {
		type: 'string',
	},
	webpackConfig: {
		type: ['object', 'function'],
		process: val => {
			if (val) {
				return val;
			}

			const file = findUserWebpackConfig();
			if (file) {
				logger.info(`Loading webpack config from:\n${file}`);
				// eslint-disable-next-line import/no-dynamic-require
				return require(file);
			}

			logger.warn(
				'No webpack config found. ' +
					'You may need to specify "webpackConfig" option in your style guide config:\n' +
					consts.DOCS_WEBPACK
			);

			return undefined;
		},
		example: {
			module: {
				rules: [
					{
						test: /\.jsx?$/,
						exclude: /node_modules/,
						loader: 'babel-loader',
					},
				],
			},
		},
	},
};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">RoadKings</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="title_activity_welcome_page">WelcomePage</string>
    <string name="title_activity_search_shops">SearchShops</string>

    <string-array name="car_models">
        <item>Hyunday i40</item>
        <item>Hyundai Santro</item>
        <item>Mercedez Benz</item>
        <item>Ford Figo</item>
    </string-array>
    <string-array name="car_parts">
        <item>Tyre</item>
        <item>AC</item>
        <item>Front Mirror</item>
    </string-array>

    <string name="title_activity_search_map">SearchMap</string>
    <string name="title_activity_road_king_map">RoadKingMapActivity</string>
    <string name="title_activity_place_one">PlaceOneActivity</string>
    <string name="title_activity_registration">RegistrationActivity</string>
    <string name="title_activity_report_problem">Report Problem</string>
    <string name="title_activity_repair_history">Repair History</string>
    <string name="title_activity_tab">TabActivity</string>
    <string name="title_activity_road_kings_tab">RoadKingsTabActivity</string>
    <string name="action_location_found">Found Location</string>
    <string name="action_refresh">Refresh</string>
    <string name="action_help">Help</string>
    <string name="action_check_updates">Check Updates</string>
    <string name="title_activity_uplaod_image">UplaodImage</string>
    <string name="title_activity_upload_image">UploadImage</string>
    <string name="title_activity_display_repair_history">DisplayRepairHistory</string>
    <string name="title_activity_vendor_offers">VendorOffersActivity</string>

</resources>


text:
package com.alibaba.csp.sentinel.slotchain;

import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.slots.DefaultSlotChainBuilder;
import com.alibaba.csp.sentinel.spi.SpiLoader;

/**
 * A provider for creating slot chains via resolved slot chain builder SPI.
 *
 * @author Eric Zhao
 * @since 0.2.0
 */
public final class SlotChainProvider {

    private static volatile SlotChainBuilder slotChainBuilder = null;

    /**
     * The load and pick process is not thread-safe, but it's okay since the method should be only invoked
     * via {@code lookProcessChain} in {@link com.alibaba.csp.sentinel.CtSph} under lock.
     *
     * @return new created slot chain
     */
    public static ProcessorSlotChain newSlotChain() {
        if (slotChainBuilder != null) {
            return slotChainBuilder.build();
        }

        // Resolve the slot chain builder SPI.
        slotChainBuilder = SpiLoader.of(SlotChainBuilder.class).loadFirstInstanceOrDefault();

        if (slotChainBuilder == null) {
            // Should not go through here.
            RecordLog.warn("[SlotChainProvider] Wrong state when resolving slot chain builder, using default");
            slotChainBuilder = new DefaultSlotChainBuilder();
        } else {
            RecordLog.info("[SlotChainProvider] Global slot chain builder resolved: {}",
                slotChainBuilder.getClass().getCanonicalName());
        }
        return slotChainBuilder.build();
    }

    private SlotChainProvider() {}
}


text:
#ifndef __BVH_H__
#define __BVH_H__

#include <Eigen/Core>
#include "bounding_box.h"
#include <queue>
#include <algorithm>
#include <assert.h>
#include <vector>
#include <iostream>

/*
  Declaration of Bounding Volume Heirarchy (BVH) data struct
*/

class BVHNode {
  public:
    BVHNode *left;
    BVHNode *right;
    Eigen::RowVector4i triangle;
    BoundingBox *boundingBox;

    BVHNode(Eigen::MatrixXd *allV, Eigen::MatrixXi *allF, std::vector<Eigen::MatrixXd> *allTriPoints, std::vector<int> triInds);
    ~BVHNode() {};
    bool isLeaf() { return (left == nullptr && right == nullptr); };
    void inspectTree();
    static Eigen::MatrixXd triangleToPoints(Eigen::MatrixXd *points, Eigen::VectorXi triangle);

  private:
    void buildNode(Eigen::MatrixXd *allV, Eigen::MatrixXi *allF, std::vector<Eigen::MatrixXd> *allTriPoints, std::vector<int> triInds);
    BoundingBox* findBoundingBoxSet(std::vector<Eigen::MatrixXd> *allTriPoints, std::vector<int> triInds);
};

#endif


text:
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview A LinkedMap data structure that is accessed using key/value
 * pairs like an ordinary Map, but which guarantees a consistent iteration
 * order over its entries. The iteration order is either insertion order (the
 * default) or ordered from most recent to least recent use. By setting a fixed
 * size, the LRU version of the LinkedMap makes an effective object cache. This
 * data structure is similar to Java's LinkedHashMap.
 *
 * @author brenneman@google.com (Shawn Brenneman)
 */

goog.provide('goog.structs.LinkedMap');

goog.require('goog.structs.Map');

/**
 * Class for a LinkedMap datastructure, which combines O(1) map access for
 * key/value pairs with a linked list for a consistent iteration order. Sample
 * usage:
 *
 * <pre>
 * var m = new LinkedMap();
 * m.set('param1', 'A');
 * m.set('param2', 'B');
 * m.set('param3', 'C');
 * alert(m.getKeys()); // param1, param2, param3
 *
 * var c = new LinkedMap(5, true);
 * for (var i = 0; i < 10; i++) {
 *   c.set('entry' + i, false);
 * }
 * alert(c.getKeys()); // entry9, entry8, entry7, entry6, entry5
 *
 * c.set('entry5', true);
 * c.set('entry1', false);
 * alert(c.getKeys()); // entry1, entry5, entry9, entry8, entry7
 * </pre>
 *
 * @param {number=} opt_maxCount The maximum number of objects to store in the
 *     LinkedMap. If unspecified or 0, there is no maximum.
 * @param {boolean=} opt_cache When set, the LinkedMap stores items in order
 *     from most recently used to least recently used, instead of insertion
 *     order.
 * @constructor
 * @template KEY, VALUE
 */
goog.structs.LinkedMap = function(opt_maxCount, opt_cache) {
  /**
   * The maximum number of entries to allow, or null if there is no limit.
   * @type {?number}
   * @private
   */
  this.maxCount_ = opt_maxCount || null;

  /**
   * @type {boolean}
   * @private
   */
  this.cache_ = !!opt_cache;

  /**
   * @private {!goog.structs.Map.<string,
   *     goog.structs.LinkedMap.Node_.<string, VALUE>>}
   */
  this.map_ = new goog.structs.Map();

  this.head_ = new goog.structs.LinkedMap.Node_('', undefined);
  this.head_.next = this.head_.prev = this.head_;
};

/**
 * Finds a node and updates it to be the most recently used.
 * @param {string} key The key of the node.
 * @return {goog.structs.LinkedMap.Node_} The node or null if not found.
 * @private
 */
goog.structs.LinkedMap.prototype.findAndMoveToTop_ = function(key) {
  var node = this.map_.get(key);
  if (node) {
    if (this.cache_) {
      node.remove();
      this.insert_(node);
    }
  }
  return node;
};

/**
 * Retrieves the value for a given key. If this is a caching LinkedMap, the
 * entry will become the most recently used.
 * @param {string} key The key to retrieve the value for.
 * @param {VALUE=} opt_val A default value that will be returned if the key is
 *     not found, defaults to undefined.
 * @return {VALUE} The retrieved value.
 */
goog.structs.LinkedMap.prototype.get = function(key, opt_val) {
  var node = this.findAndMoveToTop_(key);
  return node ? node.value : opt_val;
};

/**
 * Retrieves the value for a given key without updating the entry to be the
 * most recently used.
 * @param {string} key The key to retrieve the value for.
 * @param {VALUE=} opt_val A default value that will be returned if the key is
 *     not found.
 * @return {VALUE} The retrieved value.
 */
goog.structs.LinkedMap.prototype.peekValue = function(key, opt_val) {
  var node = this.map_.get(key);
  return node ? node.value : opt_val;
};

/**
 * Sets a value for a given key. If this is a caching LinkedMap, this entry
 * will become the most recently used.
 * @param {string} key The key to retrieve the value for.
 * @param {VALUE} value A default value that will be returned if the key is
 *     not found.
 */
goog.structs.LinkedMap.prototype.set = function(key, value) {
  var node = this.findAndMoveToTop_(key);
  if (node) {
    node.value = value;
  } else {
    node = new goog.structs.LinkedMap.Node_(key, value);
    this.map_.set(key, node);
    this.insert_(node);
  }
};

/**
 * Returns the value of the first node without making any modifications.
 * @return {VALUE} The value of the first node or undefined if the map is empty.
 */
goog.structs.LinkedMap.prototype.peek = function() {
  return this.head_.next.value;
};

/**
 * Returns the value of the last node without making any modifications.
 * @return {VALUE} The value of the last node or undefined if the map is empty.
 */
goog.structs.LinkedMap.prototype.peekLast = function() {
  return this.head_.prev.value;
};

/**
 * Removes the first node from the list and returns its value.
 * @return {VALUE} The value of the popped node, or undefined if the map was
 *     empty.
 */
goog.structs.LinkedMap.prototype.shift = function() {
  return this.popNode_(this.head_.next);
};

/**
 * Removes the last node from the list and returns its value.
 * @return {VALUE} The value of the popped node, or undefined if the map was
 *     empty.
 */
goog.structs.LinkedMap.prototype.pop = function() {
  return this.popNode_(this.head_.prev);
};

/**
 * Removes a value from the LinkedMap based on its key.
 * @param {string} key The key to remove.
 * @return {boolean} True if the entry was removed, false if the key was not
 *     found.
 */
goog.structs.LinkedMap.prototype.remove = function(key) {
  var node = this.map_.get(key);
  if (node) {
    this.removeNode(node);
    return true;
  }
  return false;
};

/**
 * Removes a node from the {@code LinkedMap}. It can be overridden to do
 * further cleanup such as disposing of the node value.
 * @param {!goog.structs.LinkedMap.Node_} node The node to remove.
 * @protected
 */
goog.structs.LinkedMap.prototype.removeNode = function(node) {
  node.remove();
  this.map_.remove(node.key);
};

/**
 * @return {number} The number of items currently in the LinkedMap.
 */
goog.structs.LinkedMap.prototype.getCount = function() {
  return this.map_.getCount();
};

/**
 * @return {boolean} True if the cache is empty, false if it contains any items.
 */
goog.structs.LinkedMap.prototype.isEmpty = function() {
  return this.map_.isEmpty();
};

/**
 * Sets the maximum number of entries allowed in this object, truncating any
 * excess objects if necessary.
 * @param {number} maxCount The new maximum number of entries to allow.
 */
goog.structs.LinkedMap.prototype.setMaxCount = function(maxCount) {
  this.maxCount_ = maxCount || null;
  if (this.maxCount_ != null) {
    this.truncate_(this.maxCount_);
  }
};

/**
 * @return {!Array.<string>} The list of the keys in the appropriate order for
 *     this LinkedMap.
 */
goog.structs.LinkedMap.prototype.getKeys = function() {
  return this.map(function(val, key) {
    return key;
  });
};

/**
 * @return {!Array.<VALUE>} The list of the values in the appropriate order for
 *     this LinkedMap.
 */
goog.structs.LinkedMap.prototype.getValues = function() {
  return this.map(function(val, key) {
    return val;
  });
};

/**
 * Tests whether a provided value is currently in the LinkedMap. This does not
 * affect item ordering in cache-style LinkedMaps.
 * @param {VALUE} value The value to check for.
 * @return {boolean} Whether the value is in the LinkedMap.
 */
goog.structs.LinkedMap.prototype.contains = function(value) {
  return this.some(function(el) {
    return el == value;
  });
};

/**
 * Tests whether a provided key is currently in the LinkedMap. This does not
 * affect item ordering in cache-style LinkedMaps.
 * @param {string} key The key to check for.
 * @return {boolean} Whether the key is in the LinkedMap.
 */
goog.structs.LinkedMap.prototype.containsKey = function(key) {
  return this.map_.containsKey(key);
};

/**
 * Removes all entries in this object.
 */
goog.structs.LinkedMap.prototype.clear = function() {
  this.truncate_(0);
};

/**
 * Calls a function on each item in the LinkedMap.
 *
 * @see goog.structs.forEach
 * @param {function(this:T, VALUE, KEY, goog.structs.LinkedMap.<KEY,VALUE>)} f
 * @param {T=} opt_obj The value of "this" inside f.
 * @template T
 */
goog.structs.LinkedMap.prototype.forEach = function(f, opt_obj) {
  for (var n = this.head_.next; n != this.head_; n = n.next) {
    f.call(opt_obj, n.value, n.key, this);
  }
};

/**
 * Calls a function on each item in the LinkedMap and returns the results of
 * those calls in an array.
 *
 * @see goog.structs.map
 * @param {function(this:T, VALUE, KEY,
 *         goog.structs.LinkedMap.<KEY,VALUE>): RESULT} f
 *     The function to call for each item. The function takes
 *     three arguments: the value, the key, and the LinkedMap.
 * @param {T=} opt_obj The object context to use as "this" for the
 *     function.
 * @return {!Array.<RESULT>} The results of the function calls for each item in
 *     the LinkedMap.
 * @template T,RESULT
 */
goog.structs.LinkedMap.prototype.map = function(f, opt_obj) {
  var rv = [];
  for (var n = this.head_.next; n != this.head_; n = n.next) {
    rv.push(f.call(opt_obj, n.value, n.key, this));
  }
  return rv;
};

/**
 * Calls a function on each item in the LinkedMap and returns true if any of
 * those function calls returns a true-like value.
 *
 * @see goog.structs.some
 * @param {function(this:T, VALUE, KEY,
 *         goog.structs.LinkedMap.<KEY,VALUE>):boolean} f
 *     The function to call for each item. The function takes
 *     three arguments: the value, the key, and the LinkedMap, and returns a
 *     boolean.
 * @param {T=} opt_obj The object context to use as "this" for the
 *     function.
 * @return {boolean} Whether f evaluates to true for at least one item in the
 *     LinkedMap.
 * @template T
 */
goog.structs.LinkedMap.prototype.some = function(f, opt_obj) {
  for (var n = this.head_.next; n != this.head_; n = n.next) {
    if (f.call(opt_obj, n.value, n.key, this)) {
      return true;
    }
  }
  return false;
};

/**
 * Calls a function on each item in the LinkedMap and returns true only if every
 * function call returns a true-like value.
 *
 * @see goog.structs.some
 * @param {function(this:T, VALUE, KEY,
 *         goog.structs.LinkedMap.<KEY,VALUE>):boolean} f
 *     The function to call for each item. The function takes
 *     three arguments: the value, the key, and the Cache, and returns a
 *     boolean.
 * @param {T=} opt_obj The object context to use as "this" for the
 *     function.
 * @return {boolean} Whether f evaluates to true for every item in the Cache.
 * @template T
 */
goog.structs.LinkedMap.prototype.every = function(f, opt_obj) {
  for (var n = this.head_.next; n != this.head_; n = n.next) {
    if (!f.call(opt_obj, n.value, n.key, this)) {
      return false;
    }
  }
  return true;
};

/**
 * Appends a node to the list. LinkedMap in cache mode adds new nodes to
 * the head of the list, otherwise they are appended to the tail. If there is a
 * maximum size, the list will be truncated if necessary.
 *
 * @param {goog.structs.LinkedMap.Node_} node The item to insert.
 * @private
 */
goog.structs.LinkedMap.prototype.insert_ = function(node) {
  if (this.cache_) {
    node.next = this.head_.next;
    node.prev = this.head_;

    this.head_.next = node;
    node.next.prev = node;
  } else {
    node.prev = this.head_.prev;
    node.next = this.head_;

    this.head_.prev = node;
    node.prev.next = node;
  }

  if (this.maxCount_ != null) {
    this.truncate_(this.maxCount_);
  }
};

/**
 * Removes elements from the LinkedMap if the given count has been exceeded.
 * In cache mode removes nodes from the tail of the list. Otherwise removes
 * nodes from the head.
 * @param {number} count Number of elements to keep.
 * @private
 */
goog.structs.LinkedMap.prototype.truncate_ = function(count) {
  for (var i = this.map_.getCount(); i > count; i--) {
    this.removeNode(this.cache_ ? this.head_.prev : this.head_.next);
  }
};

/**
 * Removes the node from the LinkedMap if it is not the head, and returns
 * the node's value.
 * @param {!goog.structs.LinkedMap.Node_} node The item to remove.
 * @return {VALUE} The value of the popped node.
 * @private
 */
goog.structs.LinkedMap.prototype.popNode_ = function(node) {
  if (this.head_ != node) {
    this.removeNode(node);
  }
  return node.value;
};

/**
 * Internal class for a doubly-linked list node containing a key/value pair.
 * @param {KEY} key The key.
 * @param {VALUE} value The value.
 * @constructor
 * @template KEY, VALUE
 * @private
 */
goog.structs.LinkedMap.Node_ = function(key, value) {
  this.key = key;
  this.value = value;
};

/**
 * The next node in the list.
 * @type {!goog.structs.LinkedMap.Node_}
 */
goog.structs.LinkedMap.Node_.prototype.next;

/**
 * The previous node in the list.
 * @type {!goog.structs.LinkedMap.Node_}
 */
goog.structs.LinkedMap.Node_.prototype.prev;

/**
 * Causes this node to remove itself from the list.
 */
goog.structs.LinkedMap.Node_.prototype.remove = function() {
  this.prev.next = this.next;
  this.next.prev = this.prev;

  delete this.prev;
  delete this.next;
};


text:
namespace Ab {
namespace Wasm {

///  The NoOp Visitor
class NoOpVisitor : public Visitor {
public:
	/// Initialization
	virtual ~NoOpVisitor() override {}

	virtual void module_start() override {}

	virtual void module_end() override {}

	virtual void header(std::uint32_t, std::uint32_t) override {}

	/// Any section

	virtual void section_start(const Section&) override {}

	virtual void section_end(const Section&) override {}

	/// Type Section

	virtual void type_section(std::size_t) override {}

	virtual void function_type(const FunctionType&) override {}

	/// Import Section

	virtual void import_section(std::size_t) override {}

	virtual void import_entry(const ImportEntry&) override {}

	/// Function Section

	virtual void function_section(std::size_t) override {}

	virtual void function_entry(std::size_t, std::uint32_t) override {}

	/// Global Section

	virtual void global_section(std::size_t) override {}

	virtual void global_entry(const GlobalType&, const InitExpr&) override {}

	/// Export Section

	virtual void export_section(std::size_t) override {}

	virtual void export_entry(const ExportEntry&) override {}

	/// Element Section

	virtual void element_section(std::size_t) override {}

	virtual void element_entry(const ElementEntry&) override {}

	virtual void element(const ElementEntry&, std::uint32_t) override {}

	virtual void element_entry_end(const ElementEntry&) override {}

	/// Code Section

	virtual void code_section(std::size_t) override {}

	virtual void function_body(std::size_t, const FunctionBody&, ReaderInput&) override {}

	virtual void function_body_end(const FunctionBody&) override {}

	/// Custom Section

	/// Data Section

	virtual void data_segment(const DataSegment&) override {}

	// virtual void customSection(const Section& section) override {}
};

}  // namespace Wasm
}  // namespace Ab

#endif  // AB_WASM_NOOPVISITOR_HPP_


text:
<?php
defined( 'ABSPATH' ) || die( 'Cheatin’ uh?' );

/**
 * Wrapper for get_rocket_browser_cache_busting except when minification is active.
 *
 * @since 2.9
 * @author Remy Perona
 *
 * @param string $src CSS/JS file URL.
 * @return string updated CSS/JS file URL.
 */
function rocket_browser_cache_busting( $src ) {
	$current_filter = current_filter();

	if ( 'style_loader_src' === $current_filter && get_rocket_option( 'minify_css' ) && ( ! defined( 'DONOTMINIFYCSS' ) || ! DONOTMINIFYCSS ) && ! is_rocket_post_excluded_option( 'minify_css' ) ) {
		return $src;
	}

	if ( 'script_loader_src' === $current_filter && get_rocket_option( 'minify_js' ) && ( ! defined( 'DONOTMINIFYJS' ) || ! DONOTMINIFYJS ) && ! is_rocket_post_excluded_option( 'minify_js' ) ) {
		return $src;
	}

	return get_rocket_browser_cache_busting( $src, $current_filter );
}
add_filter( 'style_loader_src', 'rocket_browser_cache_busting', PHP_INT_MAX );
add_filter( 'script_loader_src', 'rocket_browser_cache_busting', PHP_INT_MAX );

/**
 * Create a cache busting file with the version in the filename
 *
 * @since 2.9
 * @author Remy Perona
 *
 * @param string $src CSS/JS file URL.
 * @param string $current_filter Current WordPress filter.
 * @return string updated CSS/JS file URL
 */
function get_rocket_browser_cache_busting( $src, $current_filter = '' ) {
	global $pagenow;

	if ( defined( 'DONOTROCKETOPTIMIZE' ) && DONOTROCKETOPTIMIZE ) {
		return $src;
	}

	if ( ! get_rocket_option( 'remove_query_strings' ) ) {
		return $src;
	}

	if ( is_user_logged_in() && ! get_rocket_option( 'cache_logged_user', 0 ) ) {
		return $src;
	}

	if ( 'wp-login.php' === $pagenow ) {
		return $src;
	}

	if ( false === strpos( $src, '.css' ) && false === strpos( $src, '.js' ) ) {
		return $src;
	}

	if ( false !== strpos( $src, 'ver=' . $GLOBALS['wp_version'] ) ) {
		$src = rtrim( str_replace( array( 'ver=' . $GLOBALS['wp_version'], '?&', '&&' ), array( '', '?', '&' ), $src ), '?&' );
	}

	/**
	 * Filters files to exclude from cache busting
	 *
	 * @since 2.9.3
	 * @author Remy Perona
	 *
	 * @param array $excluded_files An array of filepath to exclude.
	 */
	$excluded_files = apply_filters( 'rocket_exclude_cache_busting', array() );
	$excluded_files = implode( '|', $excluded_files );

	if ( preg_match( '#^(' . $excluded_files . ')$#', rocket_clean_exclude_file( $src ) ) ) {
		return $src;
	}

	if ( empty( $current_filter ) ) {
		$current_filter = current_filter();
	}

	$full_src = ( substr( $src, 0, 2 ) === '//' ) ? rocket_add_url_protocol( $src ) : $src;

	switch ( $current_filter ) {
		case 'script_loader_src':
			$extension = 'js';
			break;
		case 'style_loader_src':
			$extension = 'css';
			break;
	}

	$hosts         = get_rocket_cnames_host( array( 'all', 'css_and_js', $extension ) );
	$hosts['home'] = rocket_extract_url_component( home_url(), PHP_URL_HOST );
	$hosts_index   = array_flip( $hosts );
	$file          = get_rocket_parse_url( $full_src );

	if ( '' === $file['host'] ) {
		$full_src = home_url() . $src;
	}

	if ( false !== strpos( $full_src, '://' ) && ! isset( $hosts_index[ $file['host'] ] ) ) {
		return $src;
	}

	if ( empty( $file['query'] ) ) {
		return $src;
	}

	$relative_src           = ltrim( $file['path'] . '?' . $file['query'], '/' );
	$abspath_src            = rocket_realpath( strtok( $full_src, '?' ), true, $hosts_index );
	$cache_busting_filename = preg_replace( '/\.(js|css)\?(?:timestamp|ver)=([^&]+)(?:.*)/', '-$2.$1', $relative_src );

	if ( $cache_busting_filename === $relative_src ) {
		return $src;
	}

	/*
     * Filters the cache busting filename
     *
     * @since 2.9
     * @author Remy Perona
     *
     * @param string $filename filename for the cache busting file
     */
	$cache_busting_filename = apply_filters( 'rocket_cache_busting_filename', $cache_busting_filename );
	$cache_busting_paths    = rocket_get_cache_busting_paths( $cache_busting_filename, $extension );

	if ( file_exists( $cache_busting_paths['filepath'] ) && is_readable( $cache_busting_paths['filepath'] ) ) {
		return $cache_busting_paths['url'];
	}

	if ( rocket_fetch_and_cache_busting( $abspath_src, $cache_busting_paths, $abspath_src, $current_filter ) ) {
		return $cache_busting_paths['url'];
	} else {
		return $src;
	}
}

/**
 * Create a static file for dynamically generated CSS/JS from PHP
 *
 * @since 2.9
 * @author Remy Perona
 *
 * @param string $src dynamic CSS/JS file URL.
 * @return string URL of the generated static file
 */
function rocket_cache_dynamic_resource( $src ) {
	global $pagenow;

	if ( defined( 'DONOTROCKETOPTIMIZE' ) && DONOTROCKETOPTIMIZE ) {
		return $src;
	}

	if ( is_user_logged_in() && ! get_rocket_option( 'cache_logged_user' ) ) {
		return $src;
	}

	if ( 'wp-login.php' === $pagenow ) {
		return $src;
	}

	if ( false === strpos( $src, '.php' ) ) {
		return $src;
	}

	/**
	 * Filters files to exclude from static dynamic resources
	 *
	 * @since 2.9.3
	 * @author Remy Perona
	 *
	 * @param array $excluded_files An array of filepath to exclude.
	 */
	$excluded_files   = apply_filters( 'rocket_exclude_static_dynamic_resources', array() );
	$excluded_files[] = '/wp-admin/admin-ajax.php';
	$excluded_files   = array_flip( $excluded_files );

	if ( isset( $excluded_files[ rocket_clean_exclude_file( $src ) ] ) ) {
		return $src;
	}

	$full_src = ( substr( $src, 0, 2 ) === '//' ) ? rocket_add_url_protocol( $src ) : $src;

	$current_filter = current_filter();

	switch ( $current_filter ) {
		case 'script_loader_src':
			$extension  = '.js';
			$minify_key = get_rocket_option( 'minify_js_key' );
			break;
		case 'style_loader_src':
			$extension  = '.css';
			$minify_key = get_rocket_option( 'minify_css_key' );
			break;
	}

	$hosts       = get_rocket_cnames_host( array( 'all', 'css_and_js', $extension ) );
	$hosts[]     = rocket_extract_url_component( home_url(), PHP_URL_HOST );
	$hosts_index = array_flip( $hosts );
	$file        = get_rocket_parse_url( $full_src );

	if ( $file['query'] ) {
		return $src;
	}

	if ( '' === $file['host'] ) {
		$full_src = home_url() . $src;
	}

	if ( strpos( $full_src, '://' ) !== false && ! isset( $hosts_index[ $file['host'] ] ) ) {
		return $src;
	}

	$relative_src = ltrim( $file['path'], '/' );
	$abspath_src  = rocket_realpath( strtok( $full_src, '?' ), true, $hosts_index );

	/*
     * Filters the dynamic resource cache filename
     *
     * @since 2.9
     * @author Remy Perona
     *
     * @param string $filename filename for the cache file
     */
	$cache_dynamic_resource_filename = apply_filters( 'rocket_dynamic_resource_cache_filename', preg_replace( '/\.(php)$/', '-' . $minify_key . '.' . $extension, $relative_src ) );
	$cache_busting_paths             = rocket_get_cache_busting_paths( $cache_dynamic_resource_filename, $extension );

	if ( file_exists( $cache_busting_paths['filepath'] ) && is_readable( $cache_busting_paths['filepath'] ) ) {
		return $cache_busting_paths['url'];
	}

	if ( rocket_fetch_and_cache_busting( $full_src, $cache_busting_paths, $abspath_src, $current_filter ) ) {
		return $cache_busting_paths['url'];
	} else {
		return $src;
	}
}
add_filter( 'style_loader_src', 'rocket_cache_dynamic_resource', 16 );
add_filter( 'script_loader_src', 'rocket_cache_dynamic_resource', 16 );


text:
namespace XlsToEf.Import
{
    public enum CommitMode
    {
        AnySuccessfulOneAtATime,
        AnySuccessfulAtEndAsBulk,
        CommitAllAtEndIfAllGoodOrRejectAll,
        NoCommit
    }
}


text:
"""
Tests asserting that ModelTypes convert to and from json when working
with ModelDatas
"""

# Allow inspection of private class members
# pylint: disable=protected-access

from __future__ import absolute_import, division, print_function, unicode_literals

from mock import Mock

from xblock.core import XBlock
from xblock.fields import Field, Scope, ScopeIds
from xblock.field_data import DictFieldData

from xblock.test.tools import assert_equals, assert_is_instance, TestRuntime

class TestJSONConversionField(Field):
    """Field for testing json conversion"""
    def from_json(self, value):
        assert_equals('set', value['$type'])
        return set(value['$vals'])

    def to_json(self, value):
        return {
            '$type': 'set',
            '$vals': sorted(value)
        }

class TestBlock(XBlock):
    """XBlock for testing json conversion"""
    field_a = TestJSONConversionField(scope=Scope.content)
    field_b = TestJSONConversionField(scope=Scope.content)

class TestModel(DictFieldData):
    """ModelData for testing json conversion"""
    def default(self, block, name):
        return {'$type': 'set', '$vals': [0, 1]}

class TestJsonConversion(object):
    """
    Verify that all ModelType operations correctly convert
    the json that comes out of the ModelData to python objects
    """

    def setUp(self):
        field_data = TestModel({
            'field_a': {'$type': 'set', '$vals': [1, 2, 3]}
        })
        runtime = TestRuntime(services={'field-data': field_data})
        self.block = TestBlock(runtime, scope_ids=Mock(spec=ScopeIds))

    def test_get(self):
        # Test field with a value
        assert_is_instance(self.block.field_a, set)

        # Test ModelData default
        assert_is_instance(self.block.field_b, set)

    def test_set(self):
        self.block.field_b = set([5, 6, 5])
        self.block.save()
        assert_is_instance(self.block.field_b, set)
        assert_equals(
            {'$type': 'set', '$vals': [5, 6]},
            self.block._field_data.get(self.block, 'field_b')
        )


text: Experimenting with the React framework


text:
package saar.ui.panels;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Line2D;
import java.util.Arrays;

import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * @author Marc van Almkerk
 *
 */

public class Graph extends JPanel {

	private int NumberOfSteps;

	private Double[][] drawStepsAgent;
	private int nAgents = 0;
	private String message = "";
	private Double drawline = -1.0;

	public void setMessage(String message){ this.message = message; }
	public void clearMessage(){ this.message = ""; }

	public void drawLine(Double percentage){	this.drawline = (1-percentage);	}

	public Graph(int width, int height, int nAgents, int numberOfSteps)
	{
		setSize(width, height);
		setPreferredSize(new Dimension(width,height));
		setBackground(Color.DARK_GRAY);

		drawStepsAgent = new Double[nAgents][numberOfSteps];
		for(int i = 0; i < nAgents-1; i++)
		{	Arrays.fill(drawStepsAgent[i], 0.5);	}

		this.NumberOfSteps = numberOfSteps;
		this.nAgents = nAgents;
	}

	public void addStep(Double[] RPagent)
	{
		for(int j = 0; j < nAgents-1; j++)
		{
			for(int i = 0; i < NumberOfSteps-1; i++)
			{	drawStepsAgent[j][i] = drawStepsAgent[j][i+1];	}
			drawStepsAgent[j][NumberOfSteps-1] = (1-RPagent[j]);
		}

		this.repaint();
	}

	public void paintComponent(Graphics g)
	{

		super.paintComponent(g);

		Graphics2D g2 = (Graphics2D) g;
		for(int j = 0; j < nAgents-1; j++)
		{
		    for(int i = 1; i < NumberOfSteps-1; i++)
			{
		    	int rgb = Color.HSBtoRGB((float)((1.0f/nAgents)*j), 1.0f, 1.0f);
		    	g2.setColor(new Color(rgb));
		    	Point p1 = new Point((i-1)*(this.getWidth()/NumberOfSteps),(int)(this.getHeight()*drawStepsAgent[j][i-1]));
		    	Point p2 = new Point((i)*(this.getWidth()/NumberOfSteps),(int)(this.getHeight()*drawStepsAgent[j][i]));

		    	g2.draw(new Line2D.Float(p1.x,p1.y,p2.x,p2.y));
			}
		}

		g2.setColor(Color.white);
		g2.draw(new Line2D.Float(this.getWidth()/2,0,this.getWidth()/2,this.getHeight()));
		g2.draw(new Line2D.Float(0,this.getHeight()/2,this.getWidth(),this.getHeight()/2));

		g2.setFont(new Font("Arial", Font.PLAIN, 8));
		g2.drawString("100%", this.getWidth()/2+5, 10);
		g2.drawString("0%", this.getWidth()/2+5, this.getHeight()-4);

		if(message != "")
		{
			g2.drawString(message, 5, this.getHeight()-4);
		}

		if(drawline >= 0.0)
		{
			g2.setColor(Color.yellow);
			g2.drawString("avg RP", 5, (float)(this.getHeight()*drawline)-4);
			g2.draw(new Line2D.Float(0,(float)(this.getHeight()*drawline),this.getWidth(),(float)(this.getHeight()*drawline)));
			drawline = -1.0;
		}

	}

	public void reset()
	{
		for(int i = 0; i < nAgents-1; i++)
		{	Arrays.fill(drawStepsAgent[i], 0.5);	}
		drawline = -1.0;
	}

	public void reset(int nAgents)
	{
		drawStepsAgent = new Double[nAgents][NumberOfSteps];
		for(int i = 0; i < nAgents-1; i++)
		{	Arrays.fill(drawStepsAgent[i], 0.5);	}

		drawline = -1.0;
		this.nAgents = nAgents;
	}
}


text:
require 'rest-client'
require 'json'

#Build request URL
#Replace AAA-BBB-CCC with your Marketo instance
marketo_instance = "https://AAA-BBB-CCC.mktorest.com"
#Specify batch id
batchId = 1234
endpoint = "/bulk/v1/leads/batch/" + batchId + "/failures.json"
#Replace with your access token
auth_token =  "?access_token=" + "ac756f7a-d54d-41ac-8c3c-f2d2a39ee325:ab"
request_url = marketo_instance + endpoint + auth_token

#Make request
response = RestClient.get request_url

#Returns Marketo API response
puts response


text:
<ek-header-layout>

charts

        <ek-search-filter class="ek-charts__search"
                          search-field="name"
                          collection-to-be-filtered="ctrl.charts"
                          filtered-collection="ctrl.chartsFilteredBySearch"></ek-search-filter>

            <ek-chart-sorter collection-to-sort="ctrl.chartsFilteredBySearch"
                             sorted-collection="ctrl.chartsSortedByType"></ek-chart-sorter>

            No chart found

        <ek-chart-grid ng-if="!ctrl.showEmpty"
                       charts="ctrl.chartsSortedByType" flex></ek-chart-grid>

</ek-header-layout>


text:
package com.ned.admitone.domain.api.purchase.request;

import com.ned.admitone.domain.api.AbstractRequest;

public class PurchaseRequest extends AbstractRequest implements PurchaseRequestInterface {

}