text:
angular.module('MovnThereUI')
  .config([
    'uiGmapGoogleMapApiProvider',
    'GglKey',
    function (GoogleMapApi, GglKey) {
      GoogleMapApi.configure({
        key: GglKey,
        v: '3.17',
        libraries: 'places'
      });
}])

redpajama_set_name: RedPajamaGithub


text:
The terra-icon component is used to visually represent a literal or symbolic object intended to initiate an action, communicate a status, or navigate the workflow.

## Getting Started

- Install with [npmjs](https://www.npmjs.com):
  - `npm install terra-icon`
  - `yarn add terra-icon`

## Usage
Each Icon can be imported individually.

```jsx
import React from 'react';
import IconAdd from 'terra-icon/lib/icon/IconAdd';
import IconEdit from 'terra-icon/lib/icon/IconEdit';

<div>
  <IconAdd />
  <IconEdit />
</div>
```

## Component Features
* [Cross-Browser Support](https://github.com/cerner/terra-ui/blob/master/src/terra-dev-site/contributing/ComponentStandards.e.contributing.md#cross-browser-support)
* [Responsive Support](https://github.com/cerner/terra-ui/blob/master/src/terra-dev-site/contributing/ComponentStandards.e.contributing.md#responsive-support)
* [Mobile Support](https://github.com/cerner/terra-ui/blob/master/src/terra-dev-site/contributing/ComponentStandards.e.contributing.md#mobile-support)


text:
package integration

import (
	"crypto/rand"
	"crypto/sha256"
	"flag"
	"fmt"
	"testing"

	_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
	"k8s.io/client-go/tools/clientcmd"
	ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)

const (
	defaultNamespace = "default"
	testpodNamespace = "test-pods"
)

var clusterContext = flag.String("cluster", "kind-kind-prow-integration", "The context of cluster to use for test")

func getClusterContext() string {
	return *clusterContext
}

func NewClients(configPath, clusterName string) (ctrlruntimeclient.Client, error) {
	var loader clientcmd.ClientConfigLoader
	if configPath != "" {
		loader = &clientcmd.ClientConfigLoadingRules{ExplicitPath: configPath}
	} else {
		loader = clientcmd.NewDefaultClientConfigLoadingRules()
	}

	overrides := clientcmd.ConfigOverrides{}
	// Override the cluster name if provided.
	if clusterName != "" {
		overrides.Context.Cluster = clusterName
		overrides.CurrentContext = clusterName
	}

	cfg, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
		loader, &overrides).ClientConfig()
	if err != nil {
		return nil, fmt.Errorf("failed create rest config: %w", err)
	}
	return ctrlruntimeclient.New(cfg, ctrlruntimeclient.Options{})
}

// RandomString generates random string of 32 characters in length, and fail if it failed
func RandomString(t *testing.T) string {
	b := make([]byte, 512)
	if _, err := rand.Read(b[:]); err != nil {
		t.Fatalf("failed to generate random: %v", err)
	}
	return fmt.Sprintf("%x", sha256.Sum256(b[:]))[:32]
}


text:
require 'strscan'

module SQLite

  # A ParsedStatement instance represents a tokenized version of an SQL
  # statement. This makes it possible to do bind variable replacements multiple
  # times, fairly efficiently.
  #
  # Within the SQLite interfaces, this is used only by the Statement class.
  # However, it could be reused by other SQL-reliant classes easily.
  class ParsedStatement

    # This represents a textual token in an SQL statement. It is only used by
    # ParsedStatement.
    class Token # :nodoc:

      # Create a new Token that encapsulates the given text.
      def initialize( text )
        @text = text
      end

      # Append the given text onto the the contents of this Token.
      def <<( text )
        @text << text.to_s
      end

      # Convert this Token into a string. The +vars+ parameter is ignored.
      def to_s( vars=nil )
        @text
      end

    end

    # This represents a bind variable in a tokenized SQL stream. It is used
    # only by ParsedStatement.
    class BindVariable # :nodoc:

      # Create a new BindVariable token encapsulating the given name. The
      # name is used when looking up a bind variable to bind to the place
      # holder represented by this token. The name may be either a Fixnum
      # (in which case it represents an positional placeholder) or a
      # a String (in which case it represents a named placeholder).
      def initialize( name )
        @name = name
      end

      # Convert the token to a string. If the +vars+ parameter is +nil+, then
      # the string will be in the format <tt>?nnn</tt> (where _nnn_ is the
      # index that was used to initialize this token). Otherwise, the +vars+
      # parameter must be a hash, and the value bound to this token is the
      # element with the key given to this token when it was created. If that
      # element is +nil+, this will return the string "NULL". If the element
      # is a String, then it will be quoted and escaped and returned.
      # Otherwise, the "to_s" method of the element will be called and the
      # result returned.
      def to_s( vars=nil )
        if vars.nil?
          ":#{@name}"
        else
          var = vars[ @name ]
          case var
            when nil
              "NULL"
            when String
              "'#{var.gsub(/'/,"''")}'"
            else
              var.to_s
          end
        end
      end

    end

    # The text trailing the first recognized SQL statement that was parsed from
    # the buffer given to this object. If there was no trailing SQL statement,
    # this property will be the empty string.
    attr_reader :trailing

    # Create a new ParsedStatement. This will tokenize the given buffer. As an
    # optimization, the tokenization is only performed if the string matches
    # /[?:;]/, otherwise the string is used as-is.
    def initialize( sql )
      @bind_values = Hash.new

      if sql.index( /[?:;]/ )
        @tokens, @trailing = tokenize( sql )
      else
        @tokens, @trailing = [ Token.new(sql) ], ""
      end
    end

    # Returns an array of the placeholders known to this statement. This will
    # either be empty (if the statement has no placeholders), or will contain
    # numbers (indexes) and strings (names).
    def placeholders
      @bind_values.keys
    end

    # Returns the SQL that was given to this parsed statement when it was
    # created, with bind placeholders intact.
    def sql
      @tokens.inject( "" ) { |sql,tok| sql << tok.to_s }
    end

    # Returns the statement as an SQL string, with all placeholders bound to
    # their corresponding values.
    def to_s
      @tokens.inject( "" ) { |sql,tok| sql << tok.to_s( @bind_values ) }
    end

    alias :to_str :to_s

    # Binds the given parameters to the placeholders in the statement. It does
    # this by iterating over each argument and calling #bind_param with the
    # corresponding index (starting at 1). However, if any element is a hash,
    # the hash is iterated through and #bind_param called for each key/value
    # pair. Hash's do not increment the index.
    def bind_params( *bind_vars )
      index = 1
      bind_vars.each do |value|
        if value.is_a?( Hash )
          value.each_pair { |key, value| bind_param( key, value ) }
        else
          bind_param index, value
          index += 1
        end
      end
      self
    end

    # Binds the given value to the placeholder indicated by +param+, which may
    # be either a Fixnum or a String. If the indicated placeholder does not
    # exist in the statement, this method does nothing.
    def bind_param( param, value )
      return unless @bind_values.has_key?( param )
      @bind_values[ param ] = value
    end

    # Tokenizes the given SQL string, returning a tuple containing the array of
    # tokens (optimized so that each text token contains the longest run of
    # text possible), and any trailing text that follows the statement.
    def tokenize( sql )
      tokens = []

      scanner = StringScanner.new( sql )
      variable_index = 0
      allow_break = true

      until scanner.eos?
        tokens << " " unless tokens.empty? if scanner.scan( /\s+/ )
        break if scanner.eos?

        if scanner.scan( /;/ )
          break if allow_break
          tokens << Token.new( ";" )
        elsif scanner.scan( /\bbegin\s+transaction\b/i )
          tokens << Token.new( "begin transaction" )
        elsif scanner.scan( /\bbegin\b(?=\s*[^\s;]|$)/im )
          tokens << Token.new( "begin" )
          allow_break = false
        elsif !allow_break && scanner.scan( /\bend\b/i )
          tokens << Token.new( "end" )
          allow_break = true
        elsif scanner.scan( /---.*$/ ) || scanner.scan( %r{/\*.*?\*/}m )
          # comments
          next
        elsif scanner.scan( /[-+*\/\w=<>!(),.]+/ )
          tokens << Token.new( scanner.matched )
        elsif scanner.scan( /['"]/ )
          delim = scanner.matched
          token = delim.dup
          loop do
            token << scanner.scan_until( /#{delim}/ )
            match = scanner.matched
            break if match.length % 2 == 1
          end
          tokens << Token.new( token )
        elsif scanner.scan( /\?(\d+)?/ )
          variable_index = ( scanner[1] ? scanner[1].to_i : variable_index+1 )
          tokens << BindVariable.new( variable_index )
          @bind_values[variable_index] = nil
        elsif scanner.scan( /:(\w+):?/ )
          name = scanner[1]
          variable_index = name = name.to_i if name !~ /\D/
          tokens << BindVariable.new( name )
          @bind_values[name] = nil
        else
          raise "unknown token #{scanner.rest.inspect}"
        end
      end

      # optimize the parsed list
      tokens.pop while tokens.last == " "
      optimized = []
      tokens.each do |tok|
        last = optimized.last
        if tok.is_a?( BindVariable ) || last.nil? || last.is_a?( BindVariable )
          tok = Token.new(tok) if tok == " "
          optimized << tok
        else
          last << tok
        end
      end

      return optimized, scanner.rest
    end
    private :tokenize

  end

end


text:
---
id: browser
title: Browser
---

Run Prettier in the browser using its **standalone** version. This version doesn't depend on Node.js. It only formats the code and has no support for config files, ignore files, CLI usage, or automatic loading of plugins.

The standalone version comes as:

- ES modules: `esm/standalone.mjs`, starting in version 2.2
- UMD: `standalone.js`, starting in version 1.13

The [`browser` field](https://github.com/defunctzombie/package-browser-field-spec) in Prettier's `package.json` points to `standalone.js`. That's why you can just `import` or `require` the `prettier` module to access Prettier's API, and your code can stay compatible with both Node and the browser as long as webpack or another bundler that supports the `browser` field is used. This is especially convenient for [plugins](plugins.md).

### `prettier.format(code, options)`

Required options:

- **[`parser`](options.md#parser) (or [`filepath`](options.md#file-path))**: One of these options has to be specified for Prettier to know which parser to use.

- **`plugins`**: Unlike the `format` function from the [Node.js-based API](api.md#prettierformatsource--options), this function doesn't load plugins automatically. The `plugins` option is required because all the parsers included in the Prettier package come as plugins (for reasons of file size). These plugins are files named

  - `parser-*.js` in <https://unpkg.com/browse/prettier@2.2.1/> and
  - `parser-*.mjs` in <https://unpkg.com/browse/prettier@2.2.1/esm/>

  You need to load the ones that you're going to use and pass them to `prettier.format` using the `plugins` option.

See below for examples.

## Usage

### Global

```html
<script src="https://unpkg.com/prettier@2.3.1/standalone.js"></script>
<script src="https://unpkg.com/prettier@2.3.1/parser-graphql.js"></script>
<script>
  prettier.format("type Query { hello: String }", {
    parser: "graphql",
    plugins: prettierPlugins,
  });
</script>
```

Note that the [`unpkg` field](https://unpkg.com/#examples) in Prettier's `package.json` points to `standalone.js`, that's why `https://unpkg.com/prettier` can also be used instead of `https://unpkg.com/prettier/standalone.js`.

### ES Modules

```html
<script type="module">
  import prettier from "https://unpkg.com/prettier@2.3.1/esm/standalone.mjs";
  import parserGraphql from "https://unpkg.com/prettier@2.3.1/esm/parser-graphql.mjs";

  prettier.format("type Query { hello: String }", {
    parser: "graphql",
    plugins: [parserGraphql],
  });
</script>
```

### AMD

```js
define([
  "https://unpkg.com/prettier@2.3.1/standalone.js",
  "https://unpkg.com/prettier@2.3.1/parser-graphql.js",
], (prettier, ...plugins) => {
  prettier.format("type Query { hello: String }", {
    parser: "graphql",
    plugins,
  });
});
```

### CommonJS

```js
const prettier = require("prettier/standalone");
const plugins = [require("prettier/parser-graphql")];
prettier.format("type Query { hello: String }", {
  parser: "graphql",
  plugins,
});
```

This syntax doesn't necessarily work in the browser, but it can be used when bundling the code with browserify, Rollup, webpack, or another bundler.

### Worker

```js
importScripts("https://unpkg.com/prettier@2.3.1/standalone.js");
importScripts("https://unpkg.com/prettier@2.3.1/parser-graphql.js");
prettier.format("type Query { hello: String }", {
  parser: "graphql",
  plugins: prettierPlugins,
});
```

## Parser plugins for embedded code

If you want to format [embedded code](options.md#embedded-language-formatting), you need to load related plugins too. For example:

```html
<script type="module">
  import prettier from "https://unpkg.com/prettier@2.3.1/esm/standalone.mjs";
  import parserBabel from "https://unpkg.com/prettier@2.3.1/esm/parser-babel.mjs";

  console.log(
    prettier.format("const html=/* HTML */ `<DIV> </DIV>`", {
      parser: "babel",
      plugins: [parserBabel],
    })
  );
  // Output: const html = /* HTML */ `<DIV> </DIV>`;
</script>
```

The HTML code embedded in JavaScript stays unformatted because the `html` parser hasn't been loaded. Correct usage:

```html
<script type="module">
  import prettier from "https://unpkg.com/prettier@2.3.1/esm/standalone.mjs";
  import parserBabel from "https://unpkg.com/prettier@2.3.1/esm/parser-babel.mjs";
  import parserHtml from "https://unpkg.com/prettier@2.3.1/esm/parser-html.mjs";

  console.log(
    prettier.format("const html=/* HTML */ `<DIV> </DIV>`", {
      parser: "babel",
      plugins: [parserBabel, parserHtml],
    })
  );
  // Output: const html = /* HTML */ `<div></div>`;
</script>
```


text:
    <link type="text/css" rel="stylesheet" href="../css/earthjs.css">

    <svg id="earth-js"/>


text:
using EduHub.Data.WriteBack.Entities;
using System.IO;

namespace EduHub.Data.WriteBack
{
    internal abstract class WriteBackCsvWriter<T> : WriteBackWriter<T> where T : WriteBackEntity
    {
        private readonly MemoryStream stream;

        public WriteBackCsvWriter(WriteBackContext Context, WriteBackDataSet<T> DataSet, string[] CsvHeader)
            : base(Context, DataSet)
        {
            stream = new MemoryStream();
            CsvWriter = new CsvWriter(stream, CsvHeader, true);
        }

        protected CsvWriter CsvWriter { get; }

        public override void Commit()
        {
            // flush CSV writer
            CsvWriter.Dispose();

            // delete any existing file
            if (File.Exists(DataSet.Filename))
                File.Delete(DataSet.Filename);

            // ensure directory exists
            if (!Directory.Exists(Context.WriteBackDirectory))
                Directory.CreateDirectory(Context.WriteBackDirectory);

            // write file
            using (var fileStream = new FileStream(DataSet.Filename, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                fileStream.Write(stream.GetBuffer(), 0, (int)stream.Length);
            }
        }

        public override void Dispose(bool Disposed)
        {
            CsvWriter.Dispose();
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Braun & Mel'nik, Trudy Botanicheskogo Instituta im. V. L. Komarova 20: 103 (1997)

#### Original name
Mycovellosiella vitis-ripariae U. Braun

### Remarks
null


text:
package com.multunus.to;

public class ProductTO {

	private String productName;

	private int quantity;

	private double shelfPrice;

	private double tax;

	private double totalPrice;

	private boolean isImported;

	private boolean isExempt;

	/**
	 * @return the productName
	 */
	public String getProductName() {
		return productName;
	}

	/**
	 * @param productName
	 *            the productName to set
	 */
	public void setProductName(String productName) {
		this.productName = productName;
	}

	/**
	 * @return the quantity
	 */
	public int getQuantity() {
		return quantity;
	}

	/**
	 * @param quantity
	 *            the quantity to set
	 */
	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	/**
	 * @return the shelfPrice
	 */
	public double getShelfPrice() {
		return shelfPrice;
	}

	/**
	 * @param shelfPrice
	 *            the shelfPrice to set
	 */
	public void setShelfPrice(double shelfPrice) {
		this.shelfPrice = shelfPrice;
	}

	/**
	 * @return the tax
	 */
	public double getTax() {
		return tax;
	}

	/**
	 * @param tax
	 *            the tax to set
	 */
	public void setTax(double tax) {
		this.tax = tax;
	}

	/**
	 * @return the totalPrice
	 */
	public double getTotalPrice() {
		return totalPrice;
	}

	/**
	 * @param totalPrice
	 *            the totalPrice to set
	 */
	public void setTotalPrice(double totalPrice) {
		this.totalPrice = totalPrice;
	}

	/**
	 * @return the isImported
	 */
	public boolean isImported() {
		return isImported;
	}

	/**
	 * @param isImported
	 *            the isImported to set
	 */
	public void setImported(boolean isImported) {
		this.isImported = isImported;
	}

	/**
	 * @return the isExempt
	 */
	public boolean isExempt() {
		return isExempt;
	}

	/**
	 * @param isExempt
	 *            the isExempt to set
	 */
	public void setExempt(boolean isExempt) {
		this.isExempt = isExempt;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((productName == null) ? 0 : productName.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ProductTO other = (ProductTO) obj;
		if (productName == null) {
			if (other.productName != null)
				return false;
		} else if (!productName.equals(other.productName))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "ProductTO [productName=" + productName + ", quantity="
				+ quantity + ", shelfPrice=" + shelfPrice + ", tax=" + tax
				+ ", totalPrice=" + totalPrice + ", isImported=" + isImported
				+ ", isExempt=" + isExempt + "]";
	}
}


text:
Calendar._DN = new Array
("недеља",
 "понедељак",
 "уторак",
 "среда",
 "четвртак",
 "петак",
 "субота",
 "недеља");

// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary.  We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
//   Calendar._SDN_len = N; // short day name length
//   Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.

// short day names
Calendar._SDN = new Array
("нед",
 "пон",
 "уто",
 "сре",
 "чет",
 "пет",
 "суб",
 "нед");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 1;

// full month names
Calendar._MN = new Array
("јануар",
 "фебруар",
 "март",
 "април",
 "мај",
 "јун",
 "јул",
 "август",
 "септембар",
 "октобар",
 "новембар",
 "децембар");

// short month names
Calendar._SMN = new Array
("јан",
 "феб",
 "мар",
 "апр",
 "мај",
 "јун",
 "јул",
 "авг",
 "сеп",
 "окт",
 "нов",
 "дец");

// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "О календару";

Calendar._TT["ABOUT"] =
"DHTML бирач датума/времена\n" +
"(c) dynarch.com 2002-2005 / Аутор: Mihai Bazon\n" + // don't translate this this ;-)
"За новију верзију посетите: http://www.dynarch.com/projects/calendar/\n" +
"Дистрибуира се под GNU LGPL.  Погледајте http://gnu.org/licenses/lgpl.html за детаљe." +
"\n\n" +
"Избор датума:\n" +
"- Користите \xab, \xbb тастере за избор године\n" +
"- Користите " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " тастере за избор месеца\n" +
"- Задржите тастер миша на било ком тастеру изнад за бржи избор.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Избор времена:\n" +
"- Кликните на било који део времена за повећање\n" +
"- или Shift-клик за умањење\n" +
"- или кликните и превуците за бржи одабир.";

Calendar._TT["PREV_YEAR"] = "Претходна година (задржати за мени)";
Calendar._TT["PREV_MONTH"] = "Претходни месец (задржати за мени)";
Calendar._TT["GO_TODAY"] = "На данашњи дан";
Calendar._TT["NEXT_MONTH"] = "Наредни месец (задржати за мени)";
Calendar._TT["NEXT_YEAR"] = "Наредна година (задржати за мени)";
Calendar._TT["SEL_DATE"] = "Избор датума";
Calendar._TT["DRAG_TO_MOVE"] = "Превуците за премештање";
Calendar._TT["PART_TODAY"] = " (данас)";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "%s као први дан у седмици";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "6,7";

Calendar._TT["CLOSE"] = "Затвори";
Calendar._TT["TODAY"] = "Данас";
Calendar._TT["TIME_PART"] = "(Shift-) клик или превлачење за измену вредности";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d.%m.%Y.";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %e. %b";

Calendar._TT["WK"] = "сед.";
Calendar._TT["TIME"] = "Време:";


text:
export const ADD_ELEMENT_MODE = {
  PUSH: 'push',
  UNSHIFT: 'unshift',
}


text:
import React from 'react'
import Immutable, { Map } from 'immutable'
import Cookies from 'js-cookie'
import NavBar from './navbar/NavBar'
import SignInDialog from './signin/SignInDialog'

class App extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
      user: Map(),
      customGeo: Map(),
      realGeo: Map()
    }

    this.getLocation = this.getLocation.bind(this)
    this.handleSignIn = this.handleSignIn.bind(this)
    this.handleSignOut = this.handleSignOut.bind(this)
  }

  componentDidMount() {
    this.getLocation()

    const user = Cookies.getJSON('user')
    const customGeo = Cookies.getJSON('custom_geo')

    if (customGeo) {
      this.setState({
        customGeo: Immutable.fromJS(customGeo)
      })
    }

    if (user) {
      this.setState({
        user: Immutable.fromJS(user)
      })

      return
    }

    this.showSignInDialog()
  }

  getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        const realGeo = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        }

        this.setState({
          realGeo: Immutable.fromJS(realGeo)
        })
      })
    }
  }

  handleSignIn(user, rememberMe) {
    this.setState({ user: Immutable.fromJS(user) })

    if (rememberMe) {
      Cookies.set('user', user, { expires: 30 })
    } else {
      Cookies.set('user', user)
    }

    this.hideSignInDialog()
  }

  handleSignOut() {
    Cookies.remove('user')
    Cookies.remove('custom_geo')
    Cookies.remove('spoof_location')

    this.setState({
      user: Map(),
      customGeo: Map(),
      realGeo: Map()
    })

    this.showSignInDialog()
  }

  showSignInDialog() {
    $('#sign-in-dialog').modal({
      backdrop: 'static',
      keyboard: false
    })
  }

  hideSignInDialog() {
    $('#sign-in-dialog').modal('hide')
  }

  render() {
    let childWithProps = React.cloneElement(this.props.children, {
      user: this.state.user,
      customGeo: this.state.customGeo,
      realGeo: this.state.realGeo
    })

    return (
      <div className='wrap'>
        <NavBar activeTab={this.state.activeTab} user={this.state.user} onSignOut={this.handleSignOut} />
        <SignInDialog onSignIn={this.handleSignIn} />
        {childWithProps}
      </div>
    )
  }

}

export default App


text:
from flask.ext.restful import reqparse
from flask.ext.restful import fields

from database.music.music_model import get_music
from database.user.user_model import get_user
from database.channel.channel_model import get_channel
from database.user.login_user_model import check_login_user, update_login_user_date
from config.config import ADMIN_PASSWORD

class FileField(fields.Raw):
    def format(self, value):
        return "/api/fs/%s/" % (value._id)

class LengthField(fields.Raw):
    def format(self, value):
        return len(value)

def MusicKey(key):
    try:
        assert get_music(key=key)[0]
    except:
        raise ValueError("Invalid Music Key")
    return key

def UserKey(key):
    try:
        assert get_user(key=key)[0]
    except:
        raise ValueError("Invalid User Key")
    return key

def ChannelKey(key):
    try:
        assert get_channel(key=key)[0]
    except:
        raise ValueError("Invalid Channel Key")
    return key

def PlaylistKey(key):
    try:
        assert get_channel(key=key)[0]
    except:
        raise ValueError("Invalid Playlist Key")
    return key

class RequestParser(reqparse.RequestParser):
    def parse_args(self, req=None):
        """clean the argv without value"""
        ret = super(RequestParser, self).parse_args(req)
        new_ret = {key: val for key, val in ret.iteritems() if val is not None}
        return new_ret

class BaseArgs(object):
    """base args class, subclass should implete rules.
    use self.args to get args in request"""

    def __init__(self):
        self.parser = RequestParser()
        self.rules()
        self.args = self.parser.parse_args()

    def rules(self):
        """use add_argument to add rule here"""
        raise NotImplementedError

def login_check(session):
    if 'login_user' in session and check_login_user(user_id=session['login_user']):
        return True
    return False

def update_login_user_table(user_id):
    update_login_user_date(user_id=user_id)

"""
def administrator_check(session):
    if 'administrator' in session and session['administrator'] == ADMIN_NAME:
        return True
    return False
"""


text:
Meteor.startup(function () {

    // All values listed below are default
    collectionApi = new CollectionAPI({
      // Dev key - needs to be updated for live!
      authToken: "NmM5FsS2A45qLY6Hq7tt1Q23uCs8c9Gs0Z58DjdN2E31P1172SJFTV2Uy2wpBHk2",      // Require this string to be passed in on each request
      apiPath: 'api',                    // API path prefix
      standAlone: false,                 // Run as a stand-alone HTTP(S) server
      allowCORS: false,                  // Allow CORS (Cross-Origin Resource Sharing)
      sslEnabled: false,                 // Disable/Enable SSL (stand-alone only)
      listenPort: 3005,                  // Port to listen to (stand-alone only)
      listenHost: undefined,             // Host to bind to (stand-alone only)
      privateKeyFile: 'privatekey.pem',  // SSL private key file (only used if SSL is enabled)
      certificateFile: 'certificate.pem' // SSL certificate key file (only used if SSL is enabled)
    });

    // Add the collection categories to the API "/categories" path
    collectionApi.addCollection(Categories, 'categories');

    // Add the collection posts to the API "/posts" path
    collectionApi.addCollection(Posts, 'posts', {
      // All values listed below are default
      authToken: undefined,                   // Require this string to be passed in on each request
      methods: ['POST'],  // Allow creating, reading, updating, and deleting
      before: {  // This methods, if defined, will be called before the POST/GET/PUT/DELETE actions are performed on the collection.
                 // If the function returns false the action will be canceled, if you return true the action will take place.
        POST: undefined,    // function(obj, requestMetadata, returnObject) {do everything you wanna; returnObject.success = true; returnObject.statusCode = 201; returnObject.body = {"satus": "success"}; return true;},
        // You must return true and set returnObject.success = true, if you want to return the statusCode and body to client! If you return false it will works like ordinary api.
      },
      after: {  // This methods, if defined, will be called after the POST/GET/PUT/DELETE actions are performed on the collection.
                // Generally, you don't need this, unless you have global variable to reflect data inside collection.
                // The function doesn't need return value.
        POST: undefined,    // function() {console.log("After POST");},
      }
    });

    // Starts the API server
    collectionApi.start();
  });


text:
package com.sun.jini.test.spec.javaspace.conformance.snapshot;

import java.util.logging.Level;

// net.jini
import net.jini.core.entry.Entry;
import net.jini.core.lease.Lease;
import net.jini.core.transaction.Transaction;
import net.jini.space.JavaSpace;

// com.sun.jini
import com.sun.jini.qa.harness.TestException;
import com.sun.jini.qa.harness.QAConfig;

// com.sun.jini.qa
import com.sun.jini.test.spec.javaspace.conformance.SimpleEntry;

/**
 * SnapshotTransactionExpirationTest asserts, that when the lease expires,
 * the entry is removed from the space within the transaction.
 *
 * It tests these statements for snapshots.
 *
 *
 */
public class SnapshotTransactionExpirationTest
        extends SnapshotAbstractTestBase {

    /**
     * Sets up the testing environment.
     *
     * @param config QAConfig from the runner for setup.
     */
    public void setup(QAConfig config) throws Exception {

        // mandatory call to parent
        super.setup(config);

        // get an instance of Transaction Manager
        mgr = getTxnManager();
    }

    /**
     * This method asserts, that when the lease expires,
     * the entry is removed from the space within the transaction.
     *
     * It tests these statements for snapshots.
     *
     *
Notes:
For more information see the JavaSpaces specification
     * sections 2.3, 2.6.

     */
    public void run() throws Exception {
        SimpleEntry sampleEntry1 = new SimpleEntry("TestEntry #1", 1);
        SimpleEntry sampleEntry2 = new SimpleEntry("TestEntry #2", 2);
        Entry snapshot1;
        Entry snapshot2;
        SimpleEntry result;
        long leaseTime1 = timeout1;
        long leaseTime2 = timeout2;
        Lease lease1 = null;
        Lease lease2 = null;
        Transaction txn;

        // first check that space is empty
        if (!checkSpace(space)) {
            throw new TestException(
                    "Space is not empty in the beginning.");
        }

        // create snapshots of sample entries
        snapshot1 = space.snapshot(sampleEntry1);
        snapshot2 = space.snapshot(sampleEntry2);

        // create the non null transaction
        txn = getTransaction();

        /*
         * write two sample entries with different finite lease times
         * using their snapshots into the space within the transaction
         */
        lease1 = space.write(snapshot1, txn, leaseTime1);
        lease2 = space.write(snapshot2, txn, leaseTime2);

        // check that returned leases are not equal to null
        if (lease1 == null) {
            throw new TestException(
                    "performed write of " + sampleEntry1 + " with "
                    + leaseTime1
                    + " lease time using it's snapshot within the non null"
                    + " transaction returned null lease.");
        }

        if (lease2 == null) {
            throw new TestException(
                    "performed write of " + sampleEntry2 + " with "
                    + leaseTime2
                    + " lease time using it's snapshot within the non null"
                    + " transaction returned null lease.");
        }

        /*
         * check that written entries are available in the space
         * within the transaction
         */
        result = (SimpleEntry) space.readIfExists(sampleEntry1, txn,
	        JavaSpace.NO_WAIT);

        if (result == null) {
            throw new TestException(
                    "performed write of " + sampleEntry1 + " with "
                    + leaseTime1 + " lease time within the non null"
                    + " transaction using it's snapshot,"
                    + " written entry is not available in the space.");
        }
        result = (SimpleEntry) space.readIfExists(sampleEntry2, txn,
	        JavaSpace.NO_WAIT);

        if (result == null) {
            throw new TestException(
                    "performed write of " + sampleEntry2 + " with "
                    + leaseTime2 + " lease time within the non null"
                    + " transaction using it's snapshot,"
                    + " written entry is not available in the space.");
        }
        logDebugText(sampleEntry1.toString() + " with " + leaseTime1
                + " lease time and " + sampleEntry2 + " with " + leaseTime2
                + " lease time has been successfully written to the space "
                + "using their snapshots within the non null transaction.");

        // sleep to let 1-st lease expires
        logDebugText("Sleeping for " + (leaseTime1 + instantTime) + " ...");
        Thread.sleep(leaseTime1 + instantTime);
        logDebugText("awakening...");

        /*
         * check that 1-st entry is not available in the space
         * within the transaction
         */
        result = (SimpleEntry) space.readIfExists(sampleEntry1, txn,
	        JavaSpace.NO_WAIT);

        if (result != null) {
            throw new TestException(
                    "performed write within the non null transaction of "
                    + sampleEntry1 + " with " + leaseTime1
                    + " lease time using it's snapshot, written entry is"
                    + " still available in the"
                    + " space after expiration time.");
        }
        logDebugText("Expiration for written " + sampleEntry1 + " with "
                + leaseTime1 + " lease time within the non null transaction"
                + " works as expected.");

        /*
         * check that 2-nd entry is still available in the space
         * within the transaction
         */
        result = (SimpleEntry) space.readIfExists(sampleEntry2, txn,
	        JavaSpace.NO_WAIT);

        if (result == null) {
            throw new TestException(
                    "performed write within the non null transaction of "
                    + sampleEntry2 + " with " + leaseTime2
                    + " lease time using it's snapshot, written entry"
                    + " is not available in the space after " + leaseTime1
                    + " ms.");
        }

        // sleep to let 2-nd lease expires
        logDebugText("Sleeping for " + (leaseTime2 - leaseTime1) + " ...");
        Thread.sleep(leaseTime2 - leaseTime1);
        logDebugText("awakening...");

        /*
         * check that 2-nd entry is not available in the space
         * within the transaction
         */
        result = (SimpleEntry) space.readIfExists(sampleEntry1, null,
	        JavaSpace.NO_WAIT);

        if (result != null) {
            throw new TestException(
                    "performed write within the non null transaction of "
                    + sampleEntry2 + " with " + leaseTime2
                    + " lease time using it's snapshot, written entry"
                    + " is still available in the"
                    + " space after expiration time.");
        }
        logDebugText("Expiration for written " + sampleEntry2 + " with "
                + leaseTime2 + " lease time within the non null transaction"
                + " works as expected.");

        /*
         * write snapshot of 1-st entry twice with different finite
         * lease times within the non null transaction
         */
        lease1 = space.write(snapshot1, txn, leaseTime1);
        lease2 = space.write(snapshot1, txn, leaseTime2);

        // check that returned leases are not equal to null
        if (lease1 == null) {
            throw new TestException(
                    "performed write within the non null transaction of "
                    + sampleEntry1 + " with " + leaseTime1
                    + " lease time using it's snapshot returned null"
                    + " lease.");
        }

        if (lease2 == null) {
            throw new TestException(
                    "performed write within the non null transaction of "
                    + sampleEntry1 + " with " + leaseTime2
                    + " lease time using it's snapshot returned null"
                    + " lease.");
        }
        logDebugText(sampleEntry1.toString() + " with " + leaseTime1
                + " and " + leaseTime2 + " lease times using their"
                + " snapshots within the non null transaction has been"
                + " successfully written to the space.");

        // sleep to let 1-st lease expires
        logDebugText("Sleeping for " + (leaseTime1 + instantTime) + " ...");
        Thread.sleep(leaseTime1 + instantTime);
        logDebugText("awakening...");

        /*
         * check that only one of the 1-st entries
         * is available in the space within the transaction
         */
        result = (SimpleEntry) space.takeIfExists(sampleEntry1, txn,
	        JavaSpace.NO_WAIT);

        if (result == null) {
            throw new TestException(
                    "performed 2 writes within the non null transaction of "
                    + sampleEntry1 + " with " + leaseTime1 + " and "
                    + leaseTime2 + " lease times"
                    + "using their snapshots, there are no entries"
                    + " available in the space after " + leaseTime1
                    + " ms, while 1 is expected.");
        }
        result = (SimpleEntry) space.takeIfExists(sampleEntry1, txn,
	        JavaSpace.NO_WAIT);

        if (result != null) {
            throw new TestException(
                    "performed 2 writes within the non null transaction of "
                    + sampleEntry1 + " with " + leaseTime1 + " and "
                    + leaseTime2 + " lease times"
                    + "using their snapshots, there are 2 entries"
                    + " available in the space after " + leaseTime1
                    + " ms, while 1 is expected.");
        }
        logDebugText("Expiration for written " + sampleEntry1 + " with "
                + leaseTime1 + " lease time within the non null transaction"
                + " works as expected.");

        /*
         * write 1-st entry using it's snapshot twice with different
         * finite lease times within the non null transaction again
         */
        lease1 = space.write(snapshot1, txn, leaseTime1);
        lease2 = space.write(snapshot1, txn, leaseTime2);

        // check that returned leases are not equal to null
        if (lease1 == null) {
            throw new TestException(
                    "performed write within the non null transaction of "
                    + sampleEntry1 + " with " + leaseTime1
                    + " lease time using it's snapshot returned null"
                    + " lease.");
        }

        if (lease2 == null) {
            throw new TestException(
                    "performed write within the non null transaction of "
                    + sampleEntry1 + " with " + leaseTime2
                    + " lease time using it's snapshot returned null"
                    + " lease.");
        }
        logDebugText(sampleEntry1.toString() + " with " + leaseTime1
                + " and " + leaseTime2 + " lease times within the non null"
                + " transaction using their snapshots have been"
                + " successfully written to the space.");

        // sleep to let 2-nd lease expires
        logDebugText("Sleeping for " + (leaseTime2 + instantTime) + " ...");
        Thread.sleep(leaseTime2 + instantTime);
        logDebugText("awakening...");

        /*
         * check that there are no entries available
         * in the space within the transaction
         */
        result = (SimpleEntry) space.readIfExists(sampleEntry1, txn,
	        JavaSpace.NO_WAIT);

        if (result != null) {
            throw new TestException(
                    "performed 2 writes within the non null transaction of "
                    + sampleEntry1 + " with " + leaseTime1 + " and "
                    + leaseTime2 + " lease times using their snapshots"
                    + ", there are at lease 1 entry still available in"
                    + " the space after " + leaseTime2
                    + " ms, while 0 is expected.");
        }
        logDebugText("Expiration for written " + sampleEntry1 + " with "
                + leaseTime1 + " and " + leaseTime2
                + " lease times within the non null transaction"
                + " works as expected.");

        // commit the transaction
        txnCommit(txn);
    }
}


text:
@interface JVLinkedNode (Examples)

+ (instancetype)addNumber:(JVLinkedNode *)firstNumber toNumber:(JVLinkedNode *)secondNumber;

+ (instancetype)reverseOrder:(JVLinkedNode *)head;
+ (instancetype)reorderList:(JVLinkedNode *)head;
+ (void)splitLinkedList:(JVLinkedNode *)head
              intoFront:(JVLinkedNode **)front
                andBack:(JVLinkedNode **)back;
+ (instancetype)mergeList:(JVLinkedNode *)firstHead
                 withSecondList:(JVLinkedNode *)secondHead;

+ (BOOL)listHasCycle:(JVLinkedNode *)head;

+ (instancetype)mergeList:(JVLinkedNode *)first withList:(JVLinkedNode *)second;
+ (instancetype)mergeLists:(NSArray *)lists;

+ (instancetype)removeDuplicates:(JVLinkedNode *)head;

+ (instancetype)splitList:(JVLinkedNode *)head atValue:(id)value;

@end


text:
import pkg_resources

TASK_VENDOR = "OpenStack Foundation"
TASK_PRODUCT = "OpenStack TaskFlow"
TASK_PACKAGE = None  # OS distro package version suffix

try:
    from pbr import version as pbr_version
    _version_info = pbr_version.VersionInfo('taskflow')
    version_string = _version_info.version_string
except ImportError:
    _version_info = pkg_resources.get_distribution('taskflow')
    version_string = lambda: _version_info.version

def version_string_with_package():
    if TASK_PACKAGE is None:
        return version_string()
    else:
        return "%s-%s" % (version_string(), TASK_PACKAGE)


text: in HttpServletResponseWrapperSetHeaderTest servlet<BR>


text:
require "kahana/configuration"

module Kahana
  class Client

    def initialize(options = {})
      Kahana.available_options.each do |key|
        instance_variable_set("@#{key}", options[key] || Kahana.options[key])
      end
    end

  end
end


text:
ACCEPTED

#### According to
Euro+Med Plantbase

#### Published in
null

#### Original name
Cineraria tussilaginis L'Hér.

### Remarks
null


text:
Package.describe({
	name: 'caoliao:ui-master',
	version: '0.1.0',
	// Brief, one-line summary of the package.
	summary: '',
	// URL to the Git repository containing the source code for this package.
	git: '',
	// By default, Meteor will default to using README.md for documentation.
	// To avoid submitting documentation, set this field to null.
	documentation: 'README.md'
});

Package.onUse(function(api) {
	api.versionsFrom('1.2.1');

	api.use([
		'jquery',
		'mongo@1.1.3',
		'ecmascript',
		'templating@1.1.5',
		'coffeescript@1.0.11',
		'underscore@1.0.4',
		'yasinuslu:blaze-meta',
		'caoliao:lib',
		'caoliao:ui',
		'meteorhacks:inject-initial@1.0.4',
		'meteorhacks:fast-render@2.13.0'
	]);

	api.addFiles('master/main.html', 'client');
	api.addFiles('master/loading.html', 'client');
	api.addFiles('master/pageLoading.html', 'client');
	api.addFiles('master/error.html', 'client');
	api.addFiles('master/logoLayout.html', 'client');

	api.addFiles('master/main.coffee', 'client');
	api.addFiles('master/pageLoading.coffee', 'client');

	api.addFiles('server/inject.js', 'server');
	api.addFiles('server/fastRender.js', 'server');

	// api.addFiles('stylesheets/bootstrap.min.css', ['client']);
	// api.addFiles('stylesheets/bootstrap.min.js', ['client']);
});


text:
Here's a description of base templates, which almost all the other templates
inherit from.

## Base templates

All templates use [fluid container](https://getbootstrap.com/docs/4.1/layout/overview/)
from [Bootstrap 4.1](https://getbootstrap.com/docs/4.1/).

There are multiple types of views in AMY:

* wide (e.g. 'Dashboard') -- `base_nav.html`,
* wide with sidebar (e.g. 'All Events') -- `base_nav_sidebar.html`,
* wide with two content columns (e.g. `EventRequest` accept view, rarely used) -- `base_nav_twocolumn.html`.

These templates all inherit from `base.html`, which holds the HTML structure,
includes CSS styles and JS code, displays messages, footer, etc.

The `base_nav.html` is nothing more but `base.html` extended with a navigation.
Navigation changes depending on user - one navigation bar
(`navigation.html`) exists for admin users, a different one
(`navigation_instructor_dashboard.html`) exists for instructors/trainees.
A correct navigation bar is being included in `base_nav.html` and every
instructor-enabled template (e.g. Auto Update Profile form, Upcoming Teaching
Opportunities page, etc.).

## Blocks available in base template

Django template blocks used in `base.html` template:

* `extrastyle` in `<head>`, when you need to load some additional CSS files or
  embed styles right into the page,
* `extrajs` in `<head>`, for loading additional JavaScript files / codes,
* `navbar` used in templates that include a navigation bar,
* `main` with all the main content in case someone really needs to change it
  (caution: quite a lot is going on in this block, make sure you don't brake
  it),
* `leftcolumn` for adding a sidebar or a column (used in
  `base_nav_sidebar.html` and `base_nav_twocolumn.html`),
* `maincolumn` for changing main content column grid,
* `logo` used in views that display AMY logo (login page, log out
  page, password reset, etc.),
* `title` to display `<h1>` tag with page title,
* `content` for displaying page content.

## Widgets

Additionally there were created widgets to support some of the tedious
components:

* `assignment.html` displays a dropdown to change filtering events assigned to
  specific person (user, unassigned, or no filtering),
* `assignment_modal.html` displays a modal "window" on the page; this window
  is used to select person assigned to specified object,
* `pagination.html` displays a neat button groups split with "..." to not show
  too much pages at once.


text:
class AddUniqueIndexToUsersEmail < ActiveRecord::Migration
  def change
    add_index :locksmith_users, :email, unique: true
  end
end


text:
layout: docs
title: Button Colors
description: null
---

## Shades

      <button class="button button-white">White</button>

      <button class="button button-light">Light</button>

      <button class="button button-grey">Grey</button>

      <button class="button button-dark">Dark</button>

      <button class="button button-black">Black</button>

      <button class="button button-white button-border">White</button>

      <button class="button button-light button-border">Light</button>

      <button class="button button-grey button-border">Grey</button>

      <button class="button button-dark button-border">Dark</button>

      <button class="button button-black button-border">Black</button>

      <button class="button button-white button-text">White</button>

      <button class="button button-light button-text">Light</button>

      <button class="button button-grey button-text">Grey</button>

      <button class="button button-dark button-text">Dark</button>

      <button class="button button-black button-text">Black</button>

### Disabled

      <button class="button button-white" disabled>White</button>

      <button class="button button-light" disabled>Light</button>

      <button class="button button-grey" disabled>Grey</button>

      <button class="button button-dark" disabled>Dark</button>

      <button class="button button-black" disabled>Black</button>

      <button class="button button-white button-border" disabled>White</button>

      <button class="button button-light button-border" disabled>Light</button>

      <button class="button button-grey button-border" disabled>Grey</button>

      <button class="button button-dark button-border" disabled>Dark</button>

      <button class="button button-black button-border" disabled>Black</button>

      <button class="button button-white button-text" disabled>White</button>

      <button class="button button-light button-text" disabled>Light</button>

      <button class="button button-grey button-text" disabled>Grey</button>

      <button class="button button-dark button-text" disabled>Dark</button>

      <button class="button button-black button-text" disabled>Black</button>

### HTML

```html
<button class="button button-white">...</button>
<button class="button button-light">...</button>
<button class="button button-grey">...</button>
<button class="button button-dark">...</button>
<button class="button button-black">...</button>
<button class="button button-white button-border">...</button>
<button class="button button-light button-border">...</button>
<button class="button button-grey button-border">...</button>
<button class="button button-dark button-border">...</button>
<button class="button button-black button-border">...</button>
<button class="button button-white button-text">...</button>
<button class="button button-light button-text">...</button>
<button class="button button-grey button-text">...</button>
<button class="button button-dark button-text">...</button>
<button class="button button-black button-text">...</button>
```

### CSS

```scss
--button-white-color: var(--black);
--button-light-color: var(--dark);
--button-grey-color: var(--white);
--button-dark-color: var(--white);
--button-black-color: var(--white);
```

## Palettes

      <button class="button button-primary">Primary</button>

      <button class="button button-secondary">Secondary</button>

      <button class="button button-tertiary">Tertiary</button>

      <button class="button button-primary button-border">Primary</button>

      <button class="button button-secondary button-border">Secondary</button>

      <button class="button button-tertiary button-border">Tertiary</button>

      <button class="button button-primary button-text">Primary</button>

      <button class="button button-secondary button-text">Secondary</button>

      <button class="button button-tertiary button-text">Tertiary</button>

### Disabled

      <button class="button button-primary" disabled>Primary</button>

      <button class="button button-secondary" disabled>Secondary</button>

      <button class="button button-tertiary" disabled>Tertiary</button>

      <button class="button button-primary button-border" disabled>Primary</button>

      <button class="button button-secondary button-border" disabled>Secondary</button>

      <button class="button button-tertiary button-border" disabled>Tertiary</button>

      <button class="button button-primary button-text" disabled>Primary</button>

      <button class="button button-secondary button-text" disabled>Secondary</button>

      <button class="button button-tertiary button-text" disabled>Tertiary</button>

### HTML

```html
<button class="button button-primary">...</button>
<button class="button button-secondary">...</button>
<button class="button button-tertiary">...</button>
<button class="button button-primary button-border">...</button>
<button class="button button-secondary button-border">...</button>
<button class="button button-tertiary button-border">...</button>
<button class="button button-primary button-text">...</button>
<button class="button button-secondary button-text">...</button>
<button class="button button-tertiary button-text">...</button>
```

### CSS

```scss
--button-primary-color: var(--white);
--button-secondary-color: var(--white);
--button-tertiary-color: var(--white);
```

## Indicators

      <button class="button error">Error</button>

      <button class="button warning">Warning</button>

      <button class="button success">Success</button>

      <button class="button info">Info</button>

      <button class="button error button-border">Error</button>

      <button class="button warning button-border">Warning</button>

      <button class="button success button-border">Success</button>

      <button class="button info button-border">Info</button>

      <button class="button error button-text">Error</button>

      <button class="button warning button-text">Warning</button>

      <button class="button success button-text">Success</button>

      <button class="button info button-text">Info</button>

### Disabled

      <button class="button error" disabled>Error</button>

      <button class="button warning" disabled>Warning</button>

      <button class="button success" disabled>Success</button>

      <button class="button info" disabled>Info</button>

      <button class="button error button-border" disabled>Error</button>

      <button class="button warning button-border" disabled>Warning</button>

      <button class="button success button-border" disabled>Success</button>

      <button class="button info button-border" disabled>Info</button>

      <button class="button error button-text" disabled>Error</button>

      <button class="button warning button-text" disabled>Warning</button>

      <button class="button success button-text" disabled>Success</button>

      <button class="button info button-text" disabled>Info</button>

### HTML

```html
<button class="button error">...</button>
<button class="button warning">...</button>
<button class="button success">...</button>
<button class="button info">...</button>
<button class="button error button-border">...</button>
<button class="button warning button-border">...</button>
<button class="button success button-border">...</button>
<button class="button info button-border">...</button>
<button class="button error button-text">...</button>
<button class="button warning button-text">...</button>
<button class="button success button-text">...</button>
<button class="button info button-text">...</button>
```

### CSS

```scss
--button-error-color: var(--white);
--button-warning-color: var(--white);
--button-success-color: var(--white);
--button-info-color: var(--white);
```


text:
NOTE that steps 1-2 can be replaced by installing the *academic license* version of CANOPY from Enthought, see <https://www.enthought.com/products/canopy/>. It is also possible to get Canopy Express and add packages manually.

1. Following this link I got all the required packages for Ubuntu whih are not installed by default, with few updates.

original link: <neuroimaging.scipy.org/doc/manual/html/devel/tools/virtualenv-tutor.html>

On Ubuntu we use package manager (`sudo apt-get install package-name`):

		sudo apt-get install python-numpy python-scipy python-setuptools python-wxgtk2.8 cython swig
		python-imaging python-vtk python-pyrex python-matplotlib g++ libc6-dev libx11-dev python2.7-dev
		freeglut3-dev libtool git python-sphinx curl make cmake python-enable

if you get some error about `Gl/gl.h` or `GL/glu.h`, maybe also:

`sudo apt-get install libatlas-base-dev libgl1--mesa-dev libglu1-mesa-dev`

2. Get the necessary packages from Github:

ETS from Enthought:

* Download the Python script that installs all-in-one `ets.py`:

<https://github.com/enthought/ets/raw/master/ets.py>

  	$ mkdir ets
		$ cd ets
		$ python ets.py clone
		$ sudo python ets.py install

3. Download and install Check unit testing framework:

Download from <http://sourceforge.net/projects/check/files/latest/download?source=files> or use:

		$ curl -O http://sourceforge.net/projects/check/files/latest/download?source=files
		$ ./configure
		$ make
		$ make check
		$ sudo make install

4. Download and install `liboptv`:

		$ git clone git://github.com/OpenPTV/openptv.git
		$ cd openptv/liboptv
		$ cmake -G "Unix Makefiles" -i
		CMake will ask you some questions about your system (accepting the
		defaults is usually ok)
		$ make
		$ make check
		$ sudo make install
		$ cd ~

5. Download and install `openptv-python`:

		$ git clone git://github.com/alexlib/pyptv.git
		$ cd openptv-python/pyptv_gui
		$ python setup.py install

6. For the test, get the test_folder and see if it works:
		$ cd ~
		$ git clone https://bitbucket.org/turbulencelabtau/ptv_test_folder.git
		$ cd ptv_test_folder
		$ mkdir res
		$ cd ~/openptv-python/pyptv-gui/
		$ python pyptv_gui.py ~/ptv_test_folder/test/

For Mac OS X I found this Gist very useful: <https://gist.github.com/satra/845545> and another copy here: <https://www.ibic.washington.edu/wiki/display/faq/How+do+I+install+EPD+Python+in+a+virtualenv>


text:
package io.github.kuyer.rpc.handler;

import io.github.kuyer.rpc.codec.RpcResponse;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Sharable
public class NettyClientHandler extends SimpleChannelInboundHandler<RpcResponse> {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private Map<String, RpcResponse> responseMap = new ConcurrentHashMap<String, RpcResponse>();

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, RpcResponse response)
			throws Exception {
		logger.info("netty rpc client receive message. messageId={}, response={}", response.getMessageId(), response);
		responseMap.put(response.getMessageId(), response);
	}

	public RpcResponse getResponse(String messageId) {
		RpcResponse response = null;
		while(null == response) {
			response = responseMap.get(messageId);
		}
		responseMap.remove(messageId);
		return response;
	}

}


text:
module ManageIQClient
  class Template
    include ManageIQClient::Resource

    self.path = '/api/templates'

    attribute :id, String
    attribute :name, String
    attribute :type, String
    attribute :guid, String
    attribute :vendor, String
    attribute :location, String
    attribute :uid_ems, String
    attribute :power_state, String
    attribute :state_changed_on, String
    attribute :template, Boolean
    attribute :ems_ref, String
    attribute :cloud, Boolean
    attribute :raw_power_state, String
    attribute :publicly_available, Boolean

    attribute :created_on, DateTime
    attribute :updated_on, DateTime
  end
end


text:
#pragma once

/**
 * @brief Configure analog super WDT reset
 *
 * @param enable Boolean to enable or disable super WDT reset
 */
void bootloader_ana_super_wdt_reset_config(bool enable);

/**
 * @brief Configure analog brownout reset
 *
 * @param enable Boolean to enable or disable brownout reset
 */
void bootloader_ana_bod_reset_config(bool enable);

/**
 * @brief Configure analog clock glitch reset
 *
 * @param enable Boolean to enable or disable clock glitch reset
 */
void bootloader_ana_clock_glitch_reset_config(bool enable);


text:
import * as express from 'express';
import * as passport from 'passport';
import PassportFacebookToken = require('passport-facebook-token');

const User = {
    findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void {
        callback(null, { username: 'ray' });
    }
};

const options: PassportFacebookToken.StrategyOptions = {
    clientID: 'TEST_CLIENT_ID',
    clientSecret: 'TEST_CLIENT_SECRET'
};

const optionsWithRequest: PassportFacebookToken.StrategyOptionsWithRequest = {
    clientID: 'TEST_CLIENT_ID',
    clientSecret: 'TEST_CLIENT_SECRET',
    passReqToCallback: true
};

const verify: PassportFacebookToken.VerifyFunction =
    (accessToken: string, refreshToken: string, profile: PassportFacebookToken.Profile, done: (err: any, user?: any, info?: any) => void) => {
    User.findOrCreate(profile.id, profile.provider, (err, user) => {
        if (err) {
            done(err);
        }
        done(null, user);
    });
};

const verifyWithRequest: PassportFacebookToken.VerifyFunctionWithRequest =
    (req: express.Request, accessToken: string, refreshToken: string, profile: PassportFacebookToken.Profile, done: (err: any, user?: any, info?: any) => void) => {
    User.findOrCreate(profile.id, profile.provider, (err, user) => {
        if (err) {
            done(err);
        }
        done(null, user);
    });
};

passport.use(new PassportFacebookToken(options, verify));
passport.use(new PassportFacebookToken(optionsWithRequest, verifyWithRequest));


text:
CALI_BPF_INLINE static int extract_ports(__u32 len, struct iphdr * h,
	struct protoport *dport)
{
	struct tcphdr * thdr;
	struct udphdr * uhdr;

	dport->proto = h->protocol;

	switch (h->protocol) {
		case IPPROTO_TCP:
			// Re-check buffer space for TCP (has larger headers than UDP).
			if (len <
				sizeof(struct ethhdr) + sizeof(*h) + sizeof(struct tcphdr)) {
				return 1; // Or maybe drop the packet? It's broken anyways.
			}

			thdr = (void*)((__u64)(h) + sizeof(*h));
			dport->port = port_to_host(thdr->dest);
			break;
		case IPPROTO_UDP:
			uhdr = (void*)((__u64)(h) + sizeof(*h));
			dport->port = port_to_host(uhdr->dest);
			break;
		default:
			// Neither TCP nor UDP
			return 0;
	}

	return 1;
}

__attribute__((section("prefilter_func")))
enum xdp_action prefilter(struct xdp_md* xdp)
{
	struct ethhdr * ehdr;
	struct iphdr  * ihdr;
	struct protoport dport = {0,0};
	union ip4_bpf_lpm_trie_key sip;

	// You must be at least 'UDP header' tall to take this ride.
	if (xdp->data + sizeof(*ehdr) + sizeof(*ihdr) + sizeof(struct udphdr)
		> xdp->data_end) {
		// Packet too small to contain ethernet, ip, and UDP headers. Drop.
		return XDP_DROP;
	}

	// Make sure it's an IP packet
	// NOTE that this is a straightforward implementation that
	// does not handle e.g. V[X]LAN encapsulation.
	ehdr = (void*)(long)xdp->data;
	if (be16_to_host(ETH_P_IP) != ehdr->h_proto) {
		return XDP_PASS;
	}

	// Parse l4 protocols and ports.
	// NOTE that this is a straightforward implementation that
	// does not handle e.g. IPIP encapsulation.
	ihdr = (void*)((__u64)(ehdr) + sizeof(*ehdr));
	if (extract_ports(xdp->data_end - xdp->data, ihdr, &dport)) {
		// Check failsafe ports and XDP_PASS early
		if (NULL != bpf_map_lookup_elem(&calico_failsafe_ports, &dport)) {
			return XDP_PASS;
		}
	}

	ip4val_to_lpm(&sip, 32, ihdr->saddr);

	// Drop the packet if source IP matches a blacklist entry.
	if (NULL != bpf_map_lookup_elem(&calico_prefilter_v4, &sip)) {
		// In blacklist - "thou shall not XDP_PASS!"
		return XDP_DROP;
	}

	// Not in blacklist - pass.
	return XDP_PASS;
}

char ____license[] __attribute__((section("license")))  = "Apache-2.0";


text:
package com.base.modules.sys.service;

import java.util.List;

import com.base.modules.sys.entity.Role;

/**
* @desc
* @author zhengzy
* @version 2016年6月13日
*/
public interface IRoleService {
	public List<Role> getRolesByUserId(int userId);
}


text:
<?php

namespace UEC\MediaImageBundle\Doctrine;

use Doctrine\ORM\EntityManager;
use UEC\MediaBundle\Model\MediaProviderInterface;
use UEC\MediaBundle\Model\MediaProviderManager;
use UEC\MediaImageBundle\FileSystem\ImageInfo;
use UEC\MediaImageBundle\Model\MediaImageInterface;

class MediaImageManager extends MediaProviderManager
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $em;

    /**
     * @var string
     */
    protected $className;

    function __construct(EntityManager $em, $className)
    {
        $this->em = $em;
        $this->className = $className;
    }

    /**
     * {@inheritdoc}
     */
    public function getClass()
    {
        return $this->className;
    }

    /**
     * {@inheritdoc}
     */
    public function fillMediaProviderData(MediaProviderInterface &$mediaProvider, $data)
    {
        if ($data instanceof ImageInfo
            && $mediaProvider instanceof MediaImageInterface
        ) {
            $mediaProvider->setWidth($data->getWidth());
            $mediaProvider->setHeight($data->getHeight());
            $mediaProvider->setSize($data->getSize());
            $mediaProvider->setMime($data->getMime());
            $mediaProvider->setExif($data->getExif());
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function doSaveMediaProvider(MediaProviderInterface $mediaProvider, $andFlush = true)
    {
        $this->em->persist($mediaProvider);
        if ($andFlush) {
            $this->em->flush($mediaProvider);
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function findOneBy(array $criteria)
    {
        return $this->em->getRepository($this->className)->findOneBy($criteria);
    }
}


text:
package codetoanalyze.java.pulse;

public class Recursion {

  public static void divergeOk() {
    divergeOk();
  }

  public static void callSinkThenDiverge(Object param) {
    InferTaint.inferSensitiveSink(param);
    callSinkThenDiverge(param);
  }

  public static void callSinkThenDivergeBad() {
    callSinkThenDiverge(InferTaint.inferSecretSource());
  }

  public static void safeRecursionCallSink(int i, Object param) {
    if (i == 0) return;
    InferTaint.inferSensitiveSink(param);
    safeRecursionCallSink(i - 1, param);
  }

  public static void safeRecursionCallSinkBad() {
    safeRecursionCallSink(5, InferTaint.inferSecretSource());
  }

  // TODO (#16595757): Requires support for recursion in Ondemand
  public static void FN_recursionBad(int i, Object param) {
    if (i == 0) return;
    InferTaint.inferSensitiveSink(param);
    FN_recursionBad(i - 1, InferTaint.inferSecretSource());
  }
}


text:
package bingo.lang;

public abstract class Lazy1<T,R> implements Func1<T,R>{

	private transient R r;

	public final R apply(T in) {
		if(null == r){
			r = get(in);
		}
		return r;
    }

	protected abstract R get(T in);
}


text:
(function() {
  'use strict';

  angular.module('app.feature.weather').service('_owmWeatherIconService', [
    '$log',
    function() {
      var isNight = function() {
        return false;
      };

      this.fromIconId = function(iconId, dateTime) {
        if (!angular.isDefined(dateTime) || dateTime === null) {
          return 'wi wi-fw ' + (!angular.isDefined(iconId) ? 'wi-na' : 'wi-owm-' + iconId);
        }
        return 'wi wi-fw ' + (!angular.isDefined(iconId)
          ? 'wi-na'
          : 'wi-owm-' + isNight()
            ? 'night-'
            : 'day-' + iconId);
      };

      this.fromWindDirection = function(degrees) {
        return !angular.isNumber(degrees)
          ? 'wi wi-fw wi-wind wi-na'
          : 'wi wi-fw wi-wind from-' + Math.round(degrees) % 360 + '-deg';
      };
    }
  ]);
})();


text:
{-|Minimal Desktop for Compaq Presario V6000
 -}
module Main where

import Data.Char
import Snappy.Platform.FreeBSD
import Snappy.System
import Snappy

main = ensure script

{-|Miscelanneous things for personal use -}
misc = [
        Some port {category = "editors", packageName = "vim"},
        Some port {category = "security", packageName = "sudo"},
        Some FileLine {
                        filePath = "/etc/sysctl.conf",
                        lineText = "hw.syscons.bell=0",
                        comment = "# Disable system beep"
                      }
       ]

{-|Compaq Presario V6000 drivers-}
compaqPresarioV6000 = [
                       broadcom
                      ]
broadcom = port {category = "net", packageName = "bwi-firmware-kmod"}
           ~>
           FileLine {
                      filePath = "/boot/loader.conf",
                      lineText = "if_bwi_load=\"YES\"",
                      comment = "# Enable Broadcom driver"
                    }
           ~>
           FileLine {filePath = "/boot/loader.conf", lineText = "wlan_wep_load=\"YES\"", comment = "# WEP wireless module" }
           ~>
           FileLine {filePath = "/boot/loader.conf", lineText = "wlan_ccmp_load=\"YES\"", comment = "# CCMP wireless module" }
           ~>
           FileLine {filePath = "/boot/loader.conf", lineText = "wlan_tkip_load=\"YES\"", comment = "# TKIP wireless module" }
           ~>
           FileLine {filePath = "/etc/rc.conf", lineText = "wlans_bwi0=\"wlan0\"", comment = "# Network interface for Broadcom driver" }
           ~>
           FileLine {
                      filePath = "/etc/rc.conf",
                      lineText = "ifconfig_wlan0=\"WPA DHCP\"",
                      comment ="# Confgure wireless via wpa_supplicant and DHCP"
                    }

{-|FreeBSD minimal desktop (see FreeBSD forums) -}
 -- TODO add no HAL and no LINUX to global opts
minimalDesktop = [Some portmaster, Some xStuff, Some mouse]
mouse = FileLine {
                   filePath = "/etc/rc.conf",
                   lineText = "moused_enable=\"YES\"",
                   comment = "# Mouse support"
                 }

portmaster = port {category = "ports-mgmt", packageName = "portmaster"}
             ~>
             File {
                    path = "/usr/local/etc/portmaster.rc",
                    sourcePath = "portmaster.rc.file"
                  }

xStuff = port {
                category = "x11-servers",
                packageName = "xorg-server",
                withOpts = ["DEVD"],
                withoutOpts = ["HAL"]
              }
         ~>
         port {
                category = "x11-drivers",
                packageName = "xorg-drivers",
                withOpts = ["MOUSE", "KEYBOARD"],
                withoutOpts = ["ACECAD", "APM", "ARK", "ATI", "CHIPS", "CYRIX", "DUMMY", "ELOGRAPHICS", "FBDEV", "GLINT", "HYPERPEN", "I128", "I740", "INTEL", "JOYSTICK", "MACH64", "MAGICTOUCH", "MGA", "MUTOUCH", "NEOMAGIC", "NEWPORT", "NV", "OPENCHROME", "PENMOUNT", "R128", "RENDITION", "S3", "S3VIRGE", "SAVAGE", "SILICONMOTION", "SIS", "SYNAPTICS", "TDFX", "TGA", "TRIDENT", "TSENG", "VESA", "VMMOUSE", "VMWARE", "VOID", "VOODOO", "WACOM"]
              }
         ~>
         port {
                category = "x11",
                packageName = "xinit"
              }
         ~>
         port {
                category = "x11",
                packageName = "xauth"
              }
         ~>
         port {
                category = "x11-fonts",
                packageName = "xorg-fonts"
              }
         ~>
         port {
                category = "x11-fonts",
                packageName = "webfonts"
              }
         ~>
         Conditional {
                       condition = promptNvidia,
                       subject = nvDriver
                     }
         ~>
         GeneratedFile {
                         genFilePath = "/root/xorg.conf.new",
                         genFileCmd = "Xorg",
                         genFileCmdOpts = ["-configure"]
                       }
         {- TODO here I edited xorg.conf by hand, need Augeas support --
         ~>
         File {
                sourcePath = "/root/xorg.conf.new",
                path = "/etc/X11/xorg.conf"
              }
         -}
         ~>
         Conditional {
                       condition = (isPresent nvDriver),
                       subject = nvXConf
                     }
         ~>
         port {
                category = "x11-wm",
                packageName = "openbox"
              }
         -- TODO add support for configuration, had to do it by hand --
         ~>
         port {
                category = "deskutils",
                packageName = "pypanel"
              }
         ~>
         port {
                category = "x11",
                packageName = "xterm"
              }
         ~>
         port {
                category = "x11",
                packageName = "rxvt-unicode"
              }
         -- TODO per-user daemon start up --
         ~>
         port {
                category = "sysutils",
                packageName = "automount"
              }
         ~>
         File {
                path = "/usr/local/etc/automount.conf",
                sourcePath = "automount.conf.file"
              }
         ~>
         port {
                category = "sysutils",
                packageName = "fusefs-ntfs"
              }
         ~>
         FileLine {
                     filePath = "/boot/loader.conf",
                     lineText = "fuse_load=\"YES\"",
                     comment ="# Enable fusefs-ntfs"
                   }
         ~>
         [ -- other usefull stuff
           port {
                  category = "graphics",
                  packageName = "feh"
                },
           port { -- TODO should be optional?
                  category = "x11",
                  packageName = "setxkbmap"
                },
           port {
                  category = "x11",
                  packageName = "xscreensaver"
                },
           port {
                  category = "x11",
                  packageName = "xrootconsole"
                },
           port { -- TODO should be optional
                  category = "sysutils",
                  packageName = "xbattbar"
                },
           port {
                  category = "www",
                  packageName = "opera"
                },
           port {
                  category = "multimedia",
                  packageName = "mplayer"
                },
           port {
                  category = "graphics",
                  packageName = "mupdf"
                }
         ]
         ~>
         xdm

xdm = port {
             category = "x11",
             packageName = "xdm"
           }
-- TODO ~> change to /etc/ttys

-- TODO can detection of the driver be automated?
nvDriver = port {
                  category = "x11",
                  packageName = "nvidia-driver-304",
                  withoutOpts = ["LINUX"]
                }

nvXConf = port {
                 category = "x11",
                 packageName = "nvidia-xconfig",
                 withoutOpts = ["LINUX"]
               }
          ~>
          command { cmd = "nvidia-xconfig" }
          ~>
          FileLine {
                     filePath = "/boot/loader.conf",
                     lineText = "nvidia_load=\"YES\"",
                     comment ="# Enable NVIDIA "
                   }

script = [Some misc, Some compaqPresarioV6000, Some minimalDesktop]

{-| Ask if the user wants NVIDIA drivers -}
promptNvidia :: IO Bool
promptNvidia = putStrLn "Do you want to install NVIDIA driver? (y/n)"
            >> getLine
           >>= (\str -> case str of
                "y" -> return True
                "n" -> return False
                _  -> (putStrLn("Invalid input") >> promptNvidia))
                . (map toLower)

nvidia = port {
                category = "x11",
                packageName = "nvidia-xconfig"
              }


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

namespace SumBigNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstNumber = Console.ReadLine();
            string secondNumber = Console.ReadLine();
            int length = Math.Min(firstNumber.Length, secondNumber.Length);

            if (firstNumber.Length > secondNumber.Length) {
                secondNumber = secondNumber.PadLeft(firstNumber.Length, '0');
            }
            else
            {
                firstNumber = firstNumber.PadLeft(secondNumber.Length, '0');
            }

            int reminder = 0;
            int sum = 0;
            int number = 0;
            StringBuilder sb = new StringBuilder();
            for (int i = firstNumber.Length-1; i >=0; i--)
            {
                sum = firstNumber[i] -48 + secondNumber[i] - 48+reminder;
                number = sum % 10;
                reminder = sum / 10;
                sb.Append(number);

                if (i==0 && reminder>0)
                {
                    sb.Append(reminder);
                }
            }
            Console.WriteLine(sb.ToString().ToCharArray().Reverse().ToArray());
        }
    }
}


text:
angular.module('controller.air', [])
    .controller('AirCtrl', function ($scope, $stateParams, $sce, WeatherInfo, WeatherUtil, Units, Util,
                                     $ionicScrollDelegate, $ionicHistory, Push) {

        var cityData;
        var aqiCode;

        $scope.getLabelPosition = function (grade, val) {
            var w;
            var count;
            var gradeW;
            var startV;
            var endV;
            var diff;
            var gradeD;
            var x;
            var LABEL_WIDTH = 52;
            var AQISTD_MARGIN = 2;

            try {
                w = angular.element(document.getElementById("aqistd")).prop('offsetWidth');
                var label_w = angular.element(document.getElementById("aqistd-label")).prop('offsetWidth') || LABEL_WIDTH;
                count = $scope.aqiStandard.length;
                gradeW = w/count+AQISTD_MARGIN;
                if (grade >= 2) {
                    startV = $scope.aqiStandard[grade-2].value[aqiCode];
                }
                else {
                    startV = 0;
                }
                endV = $scope.aqiStandard[grade-1].value[aqiCode];

                diff = (val - startV)/(endV-startV);
                gradeD = diff*gradeW;
                x = gradeW*(grade-1) + gradeD;
                x -= (label_w/2);
                if (x<0) {
                    x = 0;
                }
                if (x > w-label_w) {
                    x = w-label_w;
                }
            }
            catch (err) {
                Util.ga.trackException(err, false);
                x=0;
            }
            return x;
        };

        $scope.getAirCodeUnit = function (code) {
            switch (code) {
                case 'pm25':
                    return '㎍/㎥';
                case 'pm10':
                    return '㎍/㎥';
                case 'o3':
                    return 'ppm';
                case 'no2':
                    return 'ppm';
                case 'co':
                    return 'ppm';
                case 'so2':
                    return 'ppm';
                case 'aqi':
                    return '';
            }
            return "";
        };

        function _getDustForecast(dayWeatherList) {
            var objList;

            try {
                objList = dayWeatherList.filter(function (obj) {
                    return obj.fromToday >= 0 && obj.hasOwnProperty('dustForecast');
                });

                //change new object
                objList = JSON.parse(JSON.stringify(objList));

                //pm2.5, pm10, o3
                objList.forEach(function (obj) {
                    for (var key in obj.dustForecast) {
                        if (key.indexOf(aqiCode) >= 0) {
                            if (key.indexOf('Grade') >= 0) {
                                console.log('copy '+key+ ' to grade');
                                obj.grade  = obj.dustForecast[key]
                            }
                            else if (key.indexOf('Str') >= 0) {
                                console.log('copy '+key+ ' to str');
                                obj.str  = obj.dustForecast[key]
                            }
                        }
                    }
                });

                objList = objList.filter(function (obj) {
                    return obj.hasOwnProperty('grade');
                });
            }
            catch(err) {
                Util.ga.trackException(err, false);
            }
            return objList;
        }

        function _getHourlyForecast(current, hourlyList) {
            var list;
            try {
                list = hourlyList.filter(function (obj) {
                    return obj.date > current;
                });
                list = list.map(function (obj) {
                    obj.time = parseInt(obj.date.substr(11,2));
                    return obj;
                });
            }
            catch (err) {
                Util.ga.trackException(err, false);
            }
            return list;
        }

        function _getAQIname(propertyName) {
            switch (propertyName) {
                case 'pm25':
                    return 'LOC_PM25';
                case 'pm10':
                    return 'LOC_PM10';
                case 'o3':
                    return 'LOC_O3';
                case 'no2':
                    return 'LOC_NO2';
                case 'co':
                    return 'LOC_CO';
                case 'so2':
                    return 'LOC_SO2';
                case 'aqi':
                    return 'LOC_AQI';
            }
            return "";
        }

        function _getAQIList(airInfo, pollutants) {
            var list = [];
            try {
                ['aqi', 'pm25', 'pm10', 'o3', 'no2', 'co', 'so2'].forEach(function (propertyName) {
                    var obj = {};
                    if (airInfo.hasOwnProperty(propertyName+'Value')) {
                        obj.name = _getAQIname(propertyName);
                        obj.value = airInfo[propertyName+'Value'];
                        obj.grade = airInfo[propertyName+'Grade'];
                        obj.str = airInfo[propertyName+'Str'];
                        obj.code = propertyName;
                        list.push(obj);
                    }
                    else if (pollutants && pollutants.hasOwnProperty(propertyName)) {
                        obj.name = _getAQIname(propertyName);
                        obj.code = propertyName;
                        obj.value = '-';
                        list.push(obj);
                    }
                });
            }
            catch (err) {
                Util.ga.trackException(err, false);
            }
            return list;
        }

        function _setMainAqiCode(code) {
            Util.ga.trackEvent('air', 'setMainAqiCode', code);
            $scope.aqiCode = aqiCode = code;
            $scope.airCodeName = _getAQIname(aqiCode);
            if (code === 'aqi') {
                $scope.mainName = 'LOC_AIR_STATUS';
            }
            else {
                $scope.mainName = $scope.airCodeName;
            }
        }

        function _applyWeatherData() {
            try {
                var cityIndex = WeatherInfo.getCityIndex();
                var cityData = WeatherInfo.getCityOfIndex(cityIndex);

                Util.ga.trackEvent('air', 'applyWeatherData');
                var latestAirInfo = cityData.airInfo.last || cityData.currentWeather.arpltn;
                if ((latestAirInfo.hasOwnProperty(aqiCode+'Value') && latestAirInfo[aqiCode+'Value'] == undefined)
                    && (cityData.airInfo.hasOwnProperty('pollutants') && cityData.airInfo.pollutants[aqiCode] == undefined)) {
                    //skip current aqicode
                    var newAqiCode = ['pm25', 'pm10', 'o3', 'no2', 'co', 'so2', 'aqi'].find(function (propertyName) {
                        return (latestAirInfo[propertyName+'Value'] != undefined ||
                            cityData.airInfo.pollutants[aqiCode] != undefined);
                    });
                    _setMainAqiCode(newAqiCode);
                }

                $scope.hasPush = Push.hasPushInfo(cityIndex);
                $scope.currentPosition = cityData.currentPosition;
                $scope.airInfo = latestAirInfo;
                $scope.airCodeGrade = latestAirInfo[aqiCode+'Grade'];
                $scope.airCodeValue = (function() {
                    if (latestAirInfo[aqiCode+'Value'] == undefined) {
                        return '-';
                    }
                    return latestAirInfo[aqiCode+'Value'];
                })();
                $scope.airCodeStr = latestAirInfo[aqiCode+'Str'];
                if (aqiCode === 'aqi') {
                    $scope.mainInfo = $scope.airCodeStr || '-';
                    $scope.airCodeStr = '';
                }
                else {
                    $scope.mainInfo = $scope.airCodeValue;
                }

                $scope.airCodeActionGuide = latestAirInfo[aqiCode+'ActionGuide'];

                console.log($scope.aqiList);
                $scope.cityCount = WeatherInfo.getEnabledCityCount();

                $scope.dayForecast = undefined;
                $scope.airChart = undefined;

                $scope.address = cityData.name || WeatherUtil.getShortenAddress(cityData.address);
                console.log($scope.address);

                if (cityData.hasOwnProperty('airInfo')) {
                    var airInfo = cityData.airInfo;
                    $scope.forecastPubdate = airInfo.forecastPubDate;
                    $scope.forecastSource = airInfo.forecastSource;
                    $scope.aqiList = _getAQIList($scope.airInfo, cityData.airInfo.pollutants);

                    if (airInfo.hasOwnProperty('pollutants')) {
                        var pollutant = airInfo.pollutants[aqiCode];

                        if (pollutant) {
                            var index = pollutant.hourly.findIndex(function (obj) {
                                return obj.date >= latestAirInfo.dataTime;
                            });

                            if (index === pollutant.hourly.length-1) {
                                console.log('There are not hourly forecast');
                                $scope.hourlyChartTitle = "LOC_HOURLY_AQI_INFORMATION";
                            }
                            else {
                                $scope.hourlyChartTitle = "LOC_HOURLY_AQI_FORECAST";
                            }

                            // 과거 11개 + 현재 + 미래 12개 표시
                            $scope.airChart = {
                                data: new Array(24),
                                maxValue: $scope.aqiMaxValue[aqiCode]
                            };
                            for (var i = 0; i < 24; i++) {
                                $scope.airChart.data[i] = pollutant.hourly[index - 12 + i];
                                if ($scope.airChart.data[i] == undefined) {
                                    var date = new Date(pollutant.hourly[index].date.replace(/\s+/g, 'T'));
                                    date.setHours(date.getHours() - 12 + i);
                                    var pad = function(num) {
                                        var s = '0' + num;
                                        return s.substr(s.length - 2);
                                    };

                                    $scope.airChart.data[i] = new Object({
                                        date: [date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate())].join('-') + ' '
                                                + [pad(date.getHours()), pad(date.getMinutes())].join(':')
                                    });
                                }
                            }

                            console.info({code:pollutant.code, pubDate:$scope.forecastPubdate});
                            //console.log(JSON.stringify($scope.airChart));

                            if (Array.isArray(pollutant.daily)) {
                                if ($scope.bodyWidth < 360) {
                                    $scope.dayForecast = pollutant.daily.slice(0,4);
                                }
                                else {
                                    $scope.dayForecast = pollutant.daily;
                                }
                            }
                        }
                    }
                }
                else {
                    $scope.aqiList = _getAQIList($scope.airInfo);
                }

                $scope.chartAirHeight = 100;
            }
            catch(err) {
                Util.ga.trackException(err, false);
            }
        }

        function init() {
            $ionicHistory.clearHistory();
            $scope.initSize();

            var fav = parseInt($stateParams.fav);
            if (!isNaN(fav)) {
                if (fav === 0) {
                    var city = WeatherInfo.getCityOfIndex(0);
                    if (city !== null && !city.disable) {
                        WeatherInfo.setCityIndex(fav);
                    }
                } else {
                    WeatherInfo.setCityIndex(fav);
                }
            }

            var code = $stateParams.code;
            if (code) {
                _setMainAqiCode(code);
            }
            else {
                _setMainAqiCode('aqi');
            }

            if (WeatherInfo.getEnabledCityCount() === 0) {
                Util.ga.trackEvent('city', 'error', 'No enabled cities');
                return;
            }

            _applyWeatherData();
        }

        $scope.setMainAqiCode = function(code) {
            Util.ga.trackEvent('air', 'action', 'setMainAqiCodeByUser');
            _setMainAqiCode(code);
            _applyWeatherData();
            $ionicScrollDelegate.scrollTop();
        };

        $scope.$on('applyEvent', function(event, sender) {
            Util.ga.trackEvent('event', 'apply', sender);
            _applyWeatherData();
        });

        init();
    });


text:
layout: page
permalink: /life/
title: Life Experiences
---

    {% for post in site.categories.life %}

        {% include post-cards.html %}

    {% endfor %}


text:
import * as React from "react"

const IndexPage = () => {
  return (
    <main>
      <title>Head function export integration test</title>
    </main>
  )
}

export default IndexPage


text:
package org.synchronoss.cloud.nio.multipart.io.buffer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;

/**
 * <p> A reusable circular buffer
 *
 * @author Silvano Riz.
 */
public class CircularBuffer {

    @SuppressWarnings("unused")
    private static final Logger log = LoggerFactory.getLogger(CircularBuffer.class);

    // Capacity of the buffer.
    final int size;

    // The buffer
    final byte[] buffer;

    // Pointer to the first slot with valid data
    volatile int startValidDataIndex = 0;

    // Pointer to the first available slot for write
    volatile int nextAvailablePosition = 0;

    // Number of slots of valid data
    volatile int availableReadLength = 0;

    /**
     * <p> Constructor.
     *
     * @param size The size of the buffer. Must be greater than or equal to 1
     */
    public CircularBuffer(final int size) {
        if(size < 1){
            throw new IllegalArgumentException("Size cannot be zero or negative. Size: " + size);
        }
        this.size = size;
        this.buffer = new byte[size];
    }

    /**
     * <p> Writes a byte in the first available slot in the buffer. If the buffer is full the oldest data written will be overwritten.
     *
     * @param data The byte to write.
     */
    public void write(final byte data){

        buffer[nextAvailablePosition] = data;
        nextAvailablePosition = forwards(nextAvailablePosition);

        if (availableReadLength > 0 && nextAvailablePosition == startValidDataIndex + 1){
            // buffer is full
            startValidDataIndex = forwards(startValidDataIndex);
        }

        updateAvailableReadLength(true);

    }

    /**
     * <p> Reads all the available valid data into an {@code OutputStream}
     *
     * @param outputStream The {@code OutputStream} target of the read.
     * @throws IOException If the read fails.
     */
    public void readAll(final OutputStream outputStream) throws IOException {

        if (isEmpty()){
            return;
        }
        readChunk(outputStream, availableReadLength);
    }

    /**
     * <p> Reads a chunk of available data into an {@code OutputStream}
     *
     * @param outputStream The {@code OutputStream}  target of the read.
     * @param chunkSize The size of the chunk. Must be less than or equal {@link #getAvailableDataLength()}
     * @throws IOException If the read fails.
     */
    public void readChunk(final OutputStream outputStream, final int chunkSize) throws IOException {

        if (chunkSize > availableReadLength){
            throw new IllegalArgumentException("The chunk size must be smaller or equal to the amount of available data in the buffer." +
                    " Available data: " + availableReadLength + ", Requested chunk size: " + chunkSize);
        }

        if (chunkSize <= 0 ){
            return;
        }

        if (startValidDataIndex + chunkSize > buffer.length){
            int firstChunkLength = buffer.length - startValidDataIndex;
            outputStream.write(buffer, startValidDataIndex, firstChunkLength);
            outputStream.write(buffer, 0, chunkSize - firstChunkLength);
        }else{
            outputStream.write(buffer, startValidDataIndex, chunkSize);
        }
        startValidDataIndex = forwards(startValidDataIndex, chunkSize);
        outputStream.flush();
        updateAvailableReadLength(false);

    }

    /**
     * <p> Returns if the buffer is full
     *
     * @return true if the buffer is full, false otherwise.
     */
    public boolean isFull(){
        return availableReadLength == size;
    }

    /**
     * <p> Returns if the buffer is empty
     *
     * @return true if the buffer is empty, false otherwise.
     */
    public boolean isEmpty(){
        return availableReadLength == 0;
    }

    /**
     * <p> Returns the number of slots with valid data
     *
     * @return the number of slots with valid data
     */
    public int getAvailableDataLength(){
        return availableReadLength;
    }

    /**
     * <p> Returns the buffer capacity
     *
     * @return The buffer capacity
     */
    public int getBufferSize(){
        return size;
    }

    /**
     * <p> Resets the buffer.
     */
    public void reset(){
        startValidDataIndex = 0;
        nextAvailablePosition = 0;
        availableReadLength = 0;
    }

    int forwards(final int currentPosition){
        if (currentPosition == buffer.length-1){
            return 0;
        }else{
            return currentPosition + 1;
        }
    }

    int backwards(final int currentPosition){
        if(currentPosition == 0){
            return buffer.length-1;
        }else{
            return currentPosition -1;
        }
    }

    int forwards(final int currentPosition, final int positions){

        int newPosition = currentPosition + positions;
        if (newPosition > buffer.length -1){
            newPosition = (currentPosition + positions) % size;
        }

        return newPosition;
    }

    int backwards(final int currentPosition, final int positions){

        int newPosition = currentPosition - positions;
        if (newPosition < 0){
            newPosition = size - (Math.abs(currentPosition - positions) % size);
        }

        return newPosition;
    }

    void updateAvailableReadLength(final boolean isWriteOperation) {
        if(nextAvailablePosition == startValidDataIndex) {
            if(isWriteOperation) {
                availableReadLength = size;
            } else {
                availableReadLength = 0;
            }
        } else if(nextAvailablePosition > startValidDataIndex) {
            availableReadLength = nextAvailablePosition - startValidDataIndex;
        } else {
            availableReadLength = size - startValidDataIndex + nextAvailablePosition;
        }
    }

}


text:
package golang

import (
	"fmt"
	"plugin"

	"github.com/nuclio/nuclio/pkg/processor/runtime"

	"github.com/nuclio/errors"
	"github.com/nuclio/nuclio-sdk-go"
)

type pluginHandlerLoader struct {
	abstractHandler
}

func (phl *pluginHandlerLoader) load(configuration *runtime.Configuration) error {

	// try to load via base, if successful we're done
	if err := phl.abstractHandler.load(configuration); err != nil {
		return errors.Wrap(err, "Failed to load handler")
	}

	// base loads defaults in some cases
	if phl.entrypoint != nil {
		return nil
	}

	handlerPlugin, err := plugin.Open(configuration.Spec.Build.Path)
	if err != nil {
		return errors.Wrapf(err, "Can't load plugin at %q", configuration.Spec.Build.Path)
	}

	// parse the handler name
	_, handlerName, err := phl.parseName(configuration.Spec.Handler)
	if err != nil {
		return errors.Wrap(err, "Failed to parse handler name")
	}

	handlerSymbol, err := handlerPlugin.Lookup(handlerName)
	if err != nil {
		return errors.Wrapf(err, "Can't find handler %q in %q",
			handlerName,
			configuration.Spec.Build.Path)
	}

	var ok bool

	phl.entrypoint, ok = handlerSymbol.(func(*nuclio.Context, nuclio.Event) (interface{}, error))
	if !ok {
		return fmt.Errorf("%s:%s is of wrong type - %T",
			configuration.Spec.Build.Path,
			handlerName,
			handlerSymbol)
	}

	contextInitializerSymbol, err := handlerPlugin.Lookup("InitContext")

	// if we can't find it, just carry on - it's not mandatory
	if err != nil {
		return nil
	}

	phl.contextInitializer, ok = contextInitializerSymbol.(func(*nuclio.Context) error)
	if !ok {
		return fmt.Errorf("InitContext is of wrong type - %T", contextInitializerSymbol)
	}

	return nil
}