text:
/**
 * This package contains the event bridge implementation between Infinispan and CDI.
 */
package org.infinispan.cdi.event;

redpajama_set_name: RedPajamaGithub


text:
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

// function utils

/**
 * Memoize a given function by caching the computed result.
 * The cache of a memoized function can be cleared by deleting the `cache`
 * property of the function.
 *
 * @param {function} fn                     The function to be memoized.
 *                                          Must be a pure function.
 * @param {function(args: Array)} [hasher]  A custom hash builder.
 *                                          Is JSON.stringify by default.
 * @return {function}                       Returns the memoized function
 */
export function memoize(fn, hasher) {
  return function memoize() {
    if (_typeof(memoize.cache) !== 'object') {
      memoize.cache = {};
    }

    var args = [];

    for (var i = 0; i < arguments.length; i++) {
      args[i] = arguments[i];
    }

    var hash = hasher ? hasher(args) : JSON.stringify(args);

    if (!(hash in memoize.cache)) {
      memoize.cache[hash] = fn.apply(fn, args);
    }

    return memoize.cache[hash];
  };
}
/**
 * Memoize a given function by caching all results and the arguments,
 * and comparing against the arguments of previous results before
 * executing again.
 * This is less performant than `memoize` which calculates a hash,
 * which is very fast to compare. Use `memoizeCompare` only when it is
 * not possible to create a unique serializable hash from the function
 * arguments.
 * The isEqual function must compare two sets of arguments
 * and return true when equal (can be a deep equality check for example).
 * @param {function} fn
 * @param {function(a: *, b: *) : boolean} isEqual
 * @returns {function}
 */

export function memoizeCompare(fn, isEqual) {
  var memoize = function memoize() {
    var args = [];

    for (var i = 0; i < arguments.length; i++) {
      args[i] = arguments[i];
    }

    for (var c = 0; c < memoize.cache.length; c++) {
      var cached = memoize.cache[c];

      if (isEqual(args, cached.args)) {
        // TODO: move this cache entry to the top so recently used entries move up?
        return cached.res;
      }
    }

    var res = fn.apply(fn, args);
    memoize.cache.unshift({
      args: args,
      res: res
    });
    return res;
  };

  memoize.cache = [];
  return memoize;
}
/**
 * Find the maximum number of arguments expected by a typed function.
 * @param {function} fn   A typed function
 * @return {number} Returns the maximum number of expected arguments.
 *                  Returns -1 when no signatures where found on the function.
 */

export function maxArgumentCount(fn) {
  return Object.keys(fn.signatures || {}).reduce(function (args, signature) {
    var count = (signature.match(/,/g) || []).length + 1;
    return Math.max(args, count);
  }, -1);
}


text:
<!DOCTYPE html>

    <title>Select and Print</title>

Available towns

    <select id="available-towns" size="5">
        <option>Sofia</option>
        <option>Varna</option>
        <option>Pleven</option>
    </select>

    <button id="btnRight" onclick="move('right')">→</button>
    <button id="btnLeft" onclick="move('left')">←</button>
    <button id="btnPrint" onclick="move('print')">Print</button>

Selected towns

    <select id="selected-towns" size="5">
        <option>Plovdiv</option>
        <option>Ruse</option>
    </select>


text:
#region Header
// Title Name       : EnumDescriptionEditor
// Member of        : TupleGeo.General.ComponentModel.Design.dll
// Description      : Provides an editor for enumerations that is displaying value descriptions.
// Created by       : 03/03/2010, 17:23, Vasilis Vlastaras.
// Updated by       : 23/02/2010, 16:57, Vasilis Vlastaras.
//                    1.0.1 - Added preprocessor directives to make the source file compatible with .NET Framework 2.0.
//                  : 23/05/2015, 07:44, Vasilis Vlastaras.
//                    1.0.2 - Changed the code to make the editor behaving better.
// Version          : 1.0.2
// Contact Details  : TupleGeo.
// License          : Apache License.
// Copyright        : TupleGeo, 2010 - 2015.
// Comments         :
#endregion

#region Imported Namespaces

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;

#if NET350
using System.Security.Permissions;
#endif

#endregion

namespace TupleGeo.General.ComponentModel.Design {

  /// <summary>
  /// Provides an editor for enumerations that is displaying value descriptions.
  /// </summary>
#if NET350
    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
#endif
  public sealed class EnumDescriptionEditor : UITypeEditor, IDisposable {

    #region Member Variables

    private IWindowsFormsEditorService _windowsFormsEditorService;
    private EnumDescriptionEditorControl _enumDescriptionControl = null;
    private string _lastCultureUsed;

    #endregion

    #region Constructors - Destructors

    /// <summary>
    /// Initializes the <see cref="EnumDescriptionEditor"/>.
    /// </summary>
    public EnumDescriptionEditor() {
      if (_enumDescriptionControl == null) {
        _enumDescriptionControl = new EnumDescriptionEditorControl();
      }
    }

    #endregion

    #region Event Procedures

    /// <summary>
    /// Occurs when the user clicks the enumeration description control.
    /// </summary>
    /// <param name="sender">The sender of the event.</param>
    /// <param name="e">The MouseEventArgs.</param>
    private void _enumDescriptionControl_MouseClick(object sender, MouseEventArgs e) {
      _windowsFormsEditorService.CloseDropDown();
    }

    /// <summary>
    /// Occurs when the user presses a key on the enumeration description control.
    /// </summary>
    /// <param name="sender">The sender of the event.</param>
    /// <param name="e">The KeyEventArgs.</param>
    private void _enumDescriptionControl_KeyDown(object sender, KeyEventArgs e) {
      _windowsFormsEditorService.CloseDropDown();
    }

    #endregion

    #region UITypeEditor

    /// <summary>
    /// Edits a <see cref="string"/> value.
    /// </summary>
    /// <param name="context">The ITypeDescriptorContext.</param>
    /// <param name="provider">The IServiceProvider.</param>
    /// <param name="value">The value to be edited.</param>
    /// <exception cref="ArgumentNullException">
    /// Thrown when <paramref name="value"/> or <paramref name="provider"/> is <c>null</c>.
    /// </exception>
    /// <exception cref="ArgumentException">
    /// Thrown when <paramref name="value"/> is not an <see cref="Enum"/> value.
    /// </exception>
    /// <returns>An object storing the edited <see cref="string"/>.</returns>
#if NET350
    [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
#endif
    public override object EditValue(
      ITypeDescriptorContext context,
      IServiceProvider provider,
      object value
    ) {

      if (value == null) {
        throw new ArgumentNullException("value");
      }

      if (!value.GetType().IsEnum) {
        throw new ArgumentException("Invalid value type.", "value");
      }

      if (provider == null) {
        throw new ArgumentNullException("provider");
      }

      // Set the windows service.
      this._windowsFormsEditorService =
        (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

      // Unsubscribe / Subscribe to enumeration description control events.
      _enumDescriptionControl.MouseClick -= new System.Windows.Forms.MouseEventHandler(_enumDescriptionControl_MouseClick);
      _enumDescriptionControl.MouseClick += new System.Windows.Forms.MouseEventHandler(_enumDescriptionControl_MouseClick);

      _enumDescriptionControl.KeyDown -= new System.Windows.Forms.KeyEventHandler(_enumDescriptionControl_KeyDown);
      _enumDescriptionControl.KeyDown += new System.Windows.Forms.KeyEventHandler(_enumDescriptionControl_KeyDown);

      if (_enumDescriptionControl.EnumDescriptionsCollection != null) {
        // Load descriptions in the control.
        if (Application.CurrentCulture.ToString() != _lastCultureUsed) {
          _enumDescriptionControl.EnumDescriptionsCollection.Clear();

          _lastCultureUsed = Application.CurrentCulture.ToString();

          // Get the enumeration value.
          Enum enumValue = (Enum)value;

          // Get the enumeration names.
          string[] names = Enum.GetNames(value.GetType());

          // Try to get the enumeration descriptions for the current application culture.
          string[] descriptions = EnumDescriptionConverter.GetEnumDescriptions(enumValue, _lastCultureUsed);

          // Test if names and descriptions are the same.
          // If this is the case then descriptions in current culture where not found.
          bool areTheSame = true;
          for (int i = 0; i < names.Length; i++) {
            if (names[i] != descriptions[i]) {
              areTheSame = false;
              break;
            }
          }

          if (areTheSame) {
            // Since no descriptions found for the current culture, try to get the neutral culture descriptions.
            descriptions = EnumDescriptionConverter.GetEnumDescriptions(enumValue);
          }

          // Ending up here either the current culture descriptions,
          // neutral culture descriptions or enumeration named value have been retrieved.
          for (int i = 0; i < descriptions.Length; i++) {
            _enumDescriptionControl.EnumDescriptionsCollection.Add(new EnumNameDescriptionPair(names[i], descriptions[i]));
          }

          // Sort the collection and bind the data to the control.
          _enumDescriptionControl.SortEnumDescriptionsCollection();
          _enumDescriptionControl.DataBind();

          // Set the selected item on the control.
          _enumDescriptionControl.SetSelectedEnumValueName(enumValue.ToString());

        }

        // Show the enumeration editing control.
        _enumDescriptionControl.Show();
        this._windowsFormsEditorService.DropDownControl(_enumDescriptionControl);

        if (_enumDescriptionControl.SelectedEnumValueName != null) {
          // Return the enumerated value once the user has selected one.
          return Enum.Parse(value.GetType(), (string)_enumDescriptionControl.SelectedEnumValueName);
        }
        else {
          return null;
        }
      }
      else {
        return null;
      }

    }

    /// <summary>
    /// Gets the <see cref="UITypeEditorEditStyle">edit style</see> of the editor window.
    /// </summary>
    /// <param name="context">The ITypeDescriptorContext.</param>
    /// <returns>The UITypeEditorEditStyle.</returns>
#if NET350
    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
#endif
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) {
      return UITypeEditorEditStyle.DropDown;
    }

    /// <summary>
    /// Gets whether the paint value is supported or not.
    /// </summary>
    /// <param name="context">The ITypeDescriptorContext.</param>
    /// <returns>
    /// A value indicating whether the paint value is supported or not.
    /// </returns>
#if NET350
    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
#endif
    public override bool GetPaintValueSupported(ITypeDescriptorContext context) {
      return false;
    }

    /// <summary>
    /// Indicates whether the dropdown window is resizable or not.
    /// </summary>
    public override bool IsDropDownResizable {
      get {
        return true;
      }
    }

    #endregion

    #region IDisposable Members

    /// <summary>
    /// Disposes the <see cref="EnumDescriptionEditor"/> which subsequently
    /// disposes its associated <see cref="EnumDescriptionEditorControl"/>.
    /// </summary>
    public void Dispose() {
      _enumDescriptionControl.Dispose();
    }

    #endregion

  }

}


text:
package net.jloop.rejoice.types;

import net.jloop.rejoice.Value;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Quote implements Value, Iterable<Value> {

    private final List<Value> values;

    public Quote() {
        this.values = new ArrayList<>();
    }

    public Quote(Value... values) {
        this.values = new ArrayList<>();
        this.values.addAll(Arrays.asList(values));
    }

    public Quote(List<Value> values) {
        this.values = values;
    }

    @Override
    public Type type() {
        return Type.List;
    }

    public Quote append(Value value) {
        values.add(value);
        return this;
    }

    public Quote cons(Value value) {
        values.add(0, value);
        return this;
    }

    public int length() {
        return values.size();
    }

    public Value first() {
        if (values.isEmpty()) {
            return null;
        } else {
            return values.get(0);
        }
    }

    public Quote rest() {
        if (values.isEmpty()) {
            return new Quote();
        } else {
            ArrayList<Value> values = new ArrayList<>(this.values);
            values.remove(0);
            return new Quote(values);
        }
    }

    @Override
    public String print() {
        StringBuilder buffer = new StringBuilder().append("(");
        for (Value value : values) {
            buffer.append(" ").append(value.print());
        }
        return buffer.append(" )").toString();
    }

    @Override
    public Iterator<Value> iterator() {
        return values.iterator();
    }
}


text:
module MetricFu
  class Roodi < Generator

    def self.verify_dependencies!
      `roodi --help`
      raise 'sudo gem install roodi # if you want the roodi tasks' unless $?.success?
    end

    def emit
      files_to_analyze = MetricFu.roodi[:dirs_to_roodi].map{|dir| Dir[File.join(dir, "**/*.rb")] }
      @output = `roodi #{files_to_analyze.join(" ")}`
    end

    def analyze
      @matches = @output.chomp.split("\n").map{|m| m.split(" - ") }
      total = @matches.pop
      @matches.reject! {|array| array.empty? }
      @matches.map! do |match|
        file, line = match[0].split(':')
        problem = match[1]
        {:file => file, :line => line, :problem => problem}
      end
      @roodi_results = {:total => total, :problems => @matches}
    end

    def to_h
      {:roodi => @roodi_results}
    end
  end
end


text:
title: Sun Java 的安装
layout: post
categories: Java
tag: [Java,JDK]
---

# 安装 sun-java

# 从私人源安装
``` bash
$ sudo add-apt-repository "deb http://archive.canonical.com/ubuntu maverick partner"
$ sudo apt-get update
$ sudo apt-get install sun-java6-jre sun-java6-plugin # 安装jre
$ sudo apt-get install sun-java6-jdk sun-java6-plugin # 安装jdk
$ java -version # 查看版本信息
```

## 设为默认 JAVA
``` bash
sudo update-alternatives --config java
```

# Oracle 官方bin安装包
下载[官方](http://www.oracle.com/technetwork/java/javase/downloads/index.html)bin包,终端下面安装解压,然后修改环境变量指向那个`jdk`便可。

## 安装
``` bash
$ sudo mkdir /usr/lib/jvm
$ sudo tar zxvf jdk-XXXX-linux-XXX.tar.gz -C /usr/lib/jvm
$ cd /usr/lib/jvm
$ sudo mv jdkx.x.x_xx java
```
其中 `x` 指的是具体的版本

## 添加环境变量
``` bash
$ sudo vim ~/.bashrc
```
添加如下内容
``` bash
export JAVA_HOME=/usr/lib/jvm/java
export JRE_HOME=${JAVA_HOME}/jre
export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
export PATH=${JAVA_HOME}/bin:$PATH
```

## 配置默认JDK版本
``` bash
sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/java/bin/java 300
sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/java/bin/javac 300
sudo update-alternatives --install /usr/bin/jar jar /usr/lib/jvm/java/bin/jar 300
sudo update-alternatives --install /usr/bin/javah javah /usr/lib/jvm/java/bin/javah 300
sudo update-alternatives --install /usr/bin/javap javap /usr/lib/jvm/java/bin/javap 300
```
然后执行
``` bash
sudo update-alternatives --config java
```
若是初次安装 JDK, 将提示:
``` bash
There is only one alternative in link group java (providing /usr/bin/java): /usr/lib/jvm/java/bin/java
无需配置。
```
若是非初次安装,将有不同版本的 JDK 选项。

## 测试
``` bash
$ java -version
java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
Java HotSpot(TM) Server VM (build 23.21-b01, mixed mode)
```

## 脚本

``` bash
#!usr/bin/bash

JAVA_TAR_FILE='jdk-8u91-linux-x64.tar.gz'
JAVA_V='jdk1.8.0_91'

# 1. 解压安装 JAVA

sudo mkdir /usr/lib/jvm
sudo tar zxvf ${JAVA_TAR_FILE} -C /usr/lib/jvm
sudo mv /usr/lib/jvm/${JAVA_V} /usr/lib/jvm/java

# 2. 添加环境变量

echo 'export JAVA_HOME=/usr/lib/jvm/java' >> ~/.bashrc
echo 'export JRE_HOME=${JAVA_HOME}/jre' >> ~/.bashrc
echo 'export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib' >> ~/.bashrc
echo 'export PATH=${JAVA_HOME}/bin:$PATH' >> ~/.bashrc

# 3. 配置默认JDK版本

sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/java/bin/java 300
sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/java/bin/javac 300
sudo update-alternatives --install /usr/bin/jar jar /usr/lib/jvm/java/bin/jar 300
sudo update-alternatives --install /usr/bin/javah javah /usr/lib/jvm/java/bin/javah 300
sudo update-alternatives --install /usr/bin/javap javap /usr/lib/jvm/java/bin/javap 300

# 4. 配置JAVA
sudo update-alternatives --config java

# 若是初次安装 JDK, 将提示:
# There is only one alternative in link group java (providing /usr/bin/java): /usr/lib/jvm/java/bin/java
# 无需配置。

# 5. 测试

java -version
```


text:
This is a quick-and-dirty command-line tool to compare the contents of two
targets in an Xcode project.

We have a couple of products we maintain where different branded versions of the
same app are built as targets in the same overall project. When the contents of
those targets diverge, pain and misery results. There didn't seem to be an
existing tool to allow me to diff those targets against one another, so this was
born.


text:
#ifndef BOOST_CONTAINER_PMR_SLIST_HPP
#define BOOST_CONTAINER_PMR_SLIST_HPP

#if defined (_MSC_VER)
#  pragma once
#endif

#include <boost/container/slist.hpp>
#include <boost/container/pmr/polymorphic_allocator.hpp>

namespace boost {
namespace container {
namespace pmr {

#if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)

template <class T>
using slist = boost::container::slist<T, polymorphic_allocator<T>>;

#endif

//! A portable metafunction to obtain a slist
//! that uses a polymorphic allocator
template<class T>
struct slist_of
{
   typedef boost::container::slist
      < T, polymorphic_allocator<T> > type;
};

}  //namespace pmr {
}  //namespace container {
}  //namespace boost {

#endif   //BOOST_CONTAINER_PMR_VECTOR_HPP


text:
package org.apache.hadoop.hbase.protobuf;

import com.google.protobuf.ByteString;
import com.google.protobuf.ServiceException;

import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
import org.apache.hadoop.hbase.protobuf.generated.WALProtos;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
import org.apache.hadoop.hbase.regionserver.wal.HLog;
import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.UUID;

public class ReplicationProtbufUtil {
  /**
   * Get the HLog entries from a list of protocol buffer WALEntry
   *
   * @param protoList the list of protocol buffer WALEntry
   * @return an array of HLog entries
   */
  public static HLog.Entry[]
      toHLogEntries(final List<AdminProtos.WALEntry> protoList) throws IOException {
    List<HLog.Entry> entries = new ArrayList<HLog.Entry>();
    for (AdminProtos.WALEntry entry: protoList) {
      WALProtos.WALKey walKey = entry.getKey();
      HLogKey key = new HLogKey(walKey);
      WALEdit edit = new WALEdit();
      for (ByteString keyValue: entry.getKeyValueBytesList()) {
        edit.add(new KeyValue(keyValue.toByteArray()));
      }
      if (walKey.getScopesCount() > 0) {
        TreeMap<byte[], Integer> scopes =
          new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR);
        for (WALProtos.FamilyScope scope: walKey.getScopesList()) {
          scopes.put(scope.getFamily().toByteArray(),
            Integer.valueOf(scope.getScopeType().ordinal()));
        }
        key.setScopes(scopes);
      }
      entries.add(new HLog.Entry(key, edit));
    }
    return entries.toArray(new HLog.Entry[entries.size()]);
  }

  /**
   * A helper to replicate a list of HLog entries using admin protocol.
   *
   * @param admin
   * @param entries
   * @throws java.io.IOException
   */
  public static void replicateWALEntry(final AdminService.BlockingInterface admin,
      final HLog.Entry[] entries) throws IOException {
    AdminProtos.ReplicateWALEntryRequest request =
      buildReplicateWALEntryRequest(entries);
    try {
      admin.replicateWALEntry(null, request);
    } catch (ServiceException se) {
      throw ProtobufUtil.getRemoteException(se);
    }
  }

  /**
   * Create a new ReplicateWALEntryRequest from a list of HLog entries
   *
   * @param entries the HLog entries to be replicated
   * @return a ReplicateWALEntryRequest
   */
  public static AdminProtos.ReplicateWALEntryRequest
      buildReplicateWALEntryRequest(final HLog.Entry[] entries) {
    WALProtos.FamilyScope.Builder scopeBuilder = WALProtos.FamilyScope.newBuilder();
    AdminProtos.WALEntry.Builder entryBuilder = AdminProtos.WALEntry.newBuilder();
    AdminProtos.ReplicateWALEntryRequest.Builder builder =
      AdminProtos.ReplicateWALEntryRequest.newBuilder();
    for (HLog.Entry entry: entries) {
      entryBuilder.clear();
      WALProtos.WALKey.Builder keyBuilder = entryBuilder.getKeyBuilder();
      HLogKey key = entry.getKey();
      keyBuilder.setEncodedRegionName(
        ByteString.copyFrom(key.getEncodedRegionName()));
      keyBuilder.setTableName(ByteString.copyFrom(key.getTablename().getName()));
      keyBuilder.setLogSequenceNumber(key.getLogSeqNum());
      keyBuilder.setWriteTime(key.getWriteTime());
      UUID clusterId = key.getClusterId();
      if (clusterId != null) {
        HBaseProtos.UUID.Builder uuidBuilder = keyBuilder.getClusterIdBuilder();
        uuidBuilder.setLeastSigBits(clusterId.getLeastSignificantBits());
        uuidBuilder.setMostSigBits(clusterId.getMostSignificantBits());
      }
      WALEdit edit = entry.getEdit();
      NavigableMap<byte[], Integer> scopes = key.getScopes();
      if (scopes != null && !scopes.isEmpty()) {
        for (Map.Entry<byte[], Integer> scope: scopes.entrySet()) {
          scopeBuilder.setFamily(ByteString.copyFrom(scope.getKey()));
          WALProtos.ScopeType scopeType =
              WALProtos.ScopeType.valueOf(scope.getValue().intValue());
          scopeBuilder.setScopeType(scopeType);
          keyBuilder.addScopes(scopeBuilder.build());
        }
      }
      List<KeyValue> keyValues = edit.getKeyValues();
      for (KeyValue value: keyValues) {
        entryBuilder.addKeyValueBytes(ByteString.copyFrom(
          value.getBuffer(), value.getOffset(), value.getLength()));
      }
      builder.addEntry(entryBuilder.build());
    }
    return builder.build();
  }
}


text:
Component to visualize Purpose is to visualize the size of the single hierarchy elements

Link to blog: Design Studio SDK: D3 Hierarchy component


text:
package com.lonepulse.robozombie.proxy;

import org.hamcrest.core.Is;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import com.lonepulse.robozombie.annotation.Endpoint;

/**
 *
Performs unit testing for endpoint validation.

 *
 * @version 1.1.1
 *

 * @since 1.3.0
 *

 * @category test
 *

 * @author Lahiru Sahan Jayasinghe
 */
public class EndpointValidationTest {

	//represents an invalid endpoint definition with a missing @{@link Endpoint} annotation.
	private interface MissingEndpointAnnotationEndpoint {}

	//represents an invalid endpoint definition with a missing request metadata.
	@Endpoint("http://example.com")
	private interface StrayEndpointRequestEndpoint {

		void strayRequest();
	}

	@Rule
	public ExpectedException expectedException = ExpectedException.none();

	/**
	 *
Tests endpoint validation for a missing @{@link Endpoint} annotation.

	 *
	 * @since 1.3.0
	 */
	@Test @SuppressWarnings("unchecked") //safe case to Class<Throwable> from a known exception
	public final void testMissingEndpointAnnotation() throws ClassNotFoundException {

		expectedException.expect(Is.isA((Class<Throwable>)
				Class.forName("com.lonepulse.robozombie.proxy.MissingEndpointAnnotationException")));

		Validators.ENDPOINT.validate(MissingEndpointAnnotationEndpoint.class);
	}

	/**
	 *
Tests endpoint validation for missing request metadata on methods.

	 *
	 * @since 1.3.0
	 */
	@Test @SuppressWarnings("unchecked") //safe case to Class<Throwable> from a known exception
	public final void testStrayRequest() throws ClassNotFoundException {

		expectedException.expect(Is.isA((Class<Throwable>)
				Class.forName("com.lonepulse.robozombie.proxy.StrayEndpointRequestException")));

		Validators.ENDPOINT.validate(StrayEndpointRequestEndpoint.class);
	}
}


text:
include(CMakeParseArguments) # cmake_parse_arguments

include(hunter_internal_error)
include(hunter_wiki)

function(hunter_fatal_error)
  cmake_parse_arguments(hunter "" "WIKI" "" "${ARGV}")
  if(NOT hunter_WIKI)
    hunter_internal_error("Expected wiki")
  endif()
  message("")
  foreach(x ${hunter_UNPARSED_ARGUMENTS})
    message("[hunter ** FATAL ERROR **] ${x}")
  endforeach()
  message("[hunter ** FATAL ERROR **] [Directory:${CMAKE_CURRENT_LIST_DIR}]")
  message("")
  hunter_wiki("${hunter_WIKI}")
endfunction()


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package jo.util.jgl.obj;

import java.util.logging.Logger;

public class JGLCameraImpl extends JGLCamera {
    private static final Logger LOG = Logger.getLogger(JGLCameraImpl.class.getName());

}


text:
package net.apnic.rdapd.domain.controller;

import javax.servlet.http.HttpServletRequest;

import net.apnic.rdapd.history.ObjectClass;
import net.apnic.rdapd.history.ObjectHistory;
import net.apnic.rdapd.history.ObjectIndex;
import net.apnic.rdapd.history.ObjectKey;
import net.apnic.rdapd.history.Revision;
import net.apnic.rdapd.rdap.controller.RDAPControllerUtil;
import net.apnic.rdapd.rdap.controller.RDAPResponseMaker;
import net.apnic.rdapd.rdap.TopLevelObject;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Rest Controller for the RDAP /domain path segment.
 *
 * Controller is responsible for dealing with current state RDAP path segments.
 */
@RestController
@RequestMapping("/domain")
public class DomainRouteController
{
    private final static Logger LOGGER = LoggerFactory.getLogger(DomainRouteController.class);

    private final ObjectIndex objectIndex;
    private final RDAPControllerUtil rdapControllerUtil;

    @Autowired
    public DomainRouteController(ObjectIndex objectIndex,
        RDAPResponseMaker rdapResponseMaker)
    {
        this.objectIndex = objectIndex;
        this.rdapControllerUtil = new RDAPControllerUtil(rdapResponseMaker);
    }

    @RequestMapping(value="/{handle:.+}", method=RequestMethod.GET)
    public ResponseEntity<TopLevelObject> domainPathGet(
        HttpServletRequest request,
        @PathVariable("handle") String handle)
    {
        LOGGER.debug("domain GET path query for {}", handle);

        return rdapControllerUtil.singleObjectResponse(request,
            objectIndex.historyForObject(
                new ObjectKey(ObjectClass.DOMAIN, handle))
            .flatMap(ObjectHistory::mostCurrent)
            .map(Revision::getContents).orElse(null));
    }

    @RequestMapping(value="/{handle:.+}", method=RequestMethod.HEAD)
    public ResponseEntity<TopLevelObject> domainPathHead(
        HttpServletRequest request,
        @PathVariable("handle") String handle)
    {
        LOGGER.debug("domain HEAD path query for {}", handle);

        return rdapControllerUtil.singleObjectResponse(request,
            objectIndex.historyForObject(
                new ObjectKey(ObjectClass.DOMAIN, handle))
            .flatMap(ObjectHistory::mostCurrent)
            .map(Revision::getContents).orElse(null));
    }
}


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: soc2013/dpl/head/sys/sparc64/central/central.c 228129 2011-11-22 21:55:40Z marius $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/bus.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/module.h>

#include <dev/ofw/ofw_bus.h>
#include <dev/ofw/ofw_bus_subr.h>
#include <dev/ofw/openfirm.h>

#include <machine/bus.h>
#include <machine/resource.h>

#include <sys/rman.h>

#include <sparc64/sbus/ofw_sbus.h>

struct central_devinfo {
	struct ofw_bus_devinfo	cdi_obdinfo;
	struct resource_list	cdi_rl;
};

struct central_softc {
	int			sc_nrange;
	struct sbus_ranges	*sc_ranges;
};

static device_probe_t central_probe;
static device_attach_t central_attach;
static bus_print_child_t central_print_child;
static bus_probe_nomatch_t central_probe_nomatch;
static bus_alloc_resource_t central_alloc_resource;
static bus_adjust_resource_t central_adjust_resource;
static bus_get_resource_list_t central_get_resource_list;
static ofw_bus_get_devinfo_t central_get_devinfo;

static int central_print_res(struct central_devinfo *);

static device_method_t central_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe,		central_probe),
	DEVMETHOD(device_attach,	central_attach),
	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
	DEVMETHOD(device_suspend,	bus_generic_suspend),
	DEVMETHOD(device_resume,	bus_generic_resume),

	/* Bus interface */
	DEVMETHOD(bus_print_child,	central_print_child),
	DEVMETHOD(bus_probe_nomatch,	central_probe_nomatch),
	DEVMETHOD(bus_alloc_resource,	central_alloc_resource),
	DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
	DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
	DEVMETHOD(bus_adjust_resource,	central_adjust_resource),
	DEVMETHOD(bus_release_resource,	bus_generic_rl_release_resource),
	DEVMETHOD(bus_setup_intr,	bus_generic_setup_intr),
	DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
	DEVMETHOD(bus_get_resource,	bus_generic_rl_get_resource),
	DEVMETHOD(bus_get_resource_list, central_get_resource_list),
	DEVMETHOD(bus_child_pnpinfo_str, ofw_bus_gen_child_pnpinfo_str),

	/* ofw_bus interface */
	DEVMETHOD(ofw_bus_get_devinfo,	central_get_devinfo),
	DEVMETHOD(ofw_bus_get_compat,	ofw_bus_gen_get_compat),
	DEVMETHOD(ofw_bus_get_model,	ofw_bus_gen_get_model),
	DEVMETHOD(ofw_bus_get_name,	ofw_bus_gen_get_name),
	DEVMETHOD(ofw_bus_get_node,	ofw_bus_gen_get_node),
	DEVMETHOD(ofw_bus_get_type,	ofw_bus_gen_get_type),

	DEVMETHOD_END
};

static driver_t central_driver = {
	"central",
	central_methods,
	sizeof(struct central_softc),
};

static devclass_t central_devclass;

EARLY_DRIVER_MODULE(central, nexus, central_driver, central_devclass, 0, 0,
    BUS_PASS_BUS);
MODULE_DEPEND(fhc, nexus, 1, 1, 1);
MODULE_VERSION(central, 1);

static int
central_probe(device_t dev)
{

	if (strcmp(ofw_bus_get_name(dev), "central") == 0) {
		device_set_desc(dev, "central");
		return (0);
	}
	return (ENXIO);
}

static int
central_attach(device_t dev)
{
	struct central_devinfo *cdi;
	struct sbus_regs *reg;
	struct central_softc *sc;
	phandle_t child;
	phandle_t node;
	device_t cdev;
	int nreg;
	int i;

	sc = device_get_softc(dev);
	node = ofw_bus_get_node(dev);

	sc->sc_nrange = OF_getprop_alloc(node, "ranges",
	    sizeof(*sc->sc_ranges), (void **)&sc->sc_ranges);
	if (sc->sc_nrange == -1) {
		device_printf(dev, "can't get ranges\n");
		return (ENXIO);
	}

	for (child = OF_child(node); child != 0; child = OF_peer(child)) {
		cdi = malloc(sizeof(*cdi), M_DEVBUF, M_WAITOK | M_ZERO);
		if (ofw_bus_gen_setup_devinfo(&cdi->cdi_obdinfo, child) != 0) {
			free(cdi, M_DEVBUF);
			continue;
		}
		nreg = OF_getprop_alloc(child, "reg", sizeof(*reg),
		    (void **)&reg);
		if (nreg == -1) {
			device_printf(dev, "<%s>: incomplete\n",
			    cdi->cdi_obdinfo.obd_name);
			ofw_bus_gen_destroy_devinfo(&cdi->cdi_obdinfo);
			free(cdi, M_DEVBUF);
			continue;
		}
		resource_list_init(&cdi->cdi_rl);
		for (i = 0; i < nreg; i++)
			resource_list_add(&cdi->cdi_rl, SYS_RES_MEMORY, i,
			    reg[i].sbr_offset, reg[i].sbr_offset +
			    reg[i].sbr_size, reg[i].sbr_size);
		free(reg, M_OFWPROP);
		cdev = device_add_child(dev, NULL, -1);
		if (cdev == NULL) {
			device_printf(dev, "<%s>: device_add_child failed\n",
			    cdi->cdi_obdinfo.obd_name);
			resource_list_free(&cdi->cdi_rl);
			ofw_bus_gen_destroy_devinfo(&cdi->cdi_obdinfo);
			free(cdi, M_DEVBUF);
			continue;
		}
		device_set_ivars(cdev, cdi);
	}

	return (bus_generic_attach(dev));
}

static int
central_adjust_resource(device_t bus __unused, device_t child __unused,
    int type __unused, struct resource *r __unused, u_long start __unused,
    u_long end __unused)
{

	return (ENXIO);
}

static int
central_print_child(device_t dev, device_t child)
{
	int rv;

	rv = bus_print_child_header(dev, child);
	rv += central_print_res(device_get_ivars(child));
	rv += bus_print_child_footer(dev, child);
	return (rv);
}

static void
central_probe_nomatch(device_t dev, device_t child)
{
	const char *type;

	device_printf(dev, "<%s>", ofw_bus_get_name(child));
	central_print_res(device_get_ivars(child));
	type = ofw_bus_get_type(child);
	printf(" type %s (no driver attached)\n",
	    type != NULL ? type : "unknown");
}

static struct resource *
central_alloc_resource(device_t bus, device_t child, int type, int *rid,
    u_long start, u_long end, u_long count, u_int flags)
{
	struct resource_list *rl;
	struct resource_list_entry *rle;
	struct central_softc *sc;
	struct resource *res;
	bus_addr_t coffset;
	bus_addr_t cend;
	bus_addr_t phys;
	int isdefault;
	int passthrough;
	int i;

	isdefault = (start == 0UL && end == ~0UL);
	passthrough = (device_get_parent(child) != bus);
	res = NULL;
	rle = NULL;
	rl = BUS_GET_RESOURCE_LIST(bus, child);
	sc = device_get_softc(bus);
	switch (type) {
	case SYS_RES_IRQ:
		return (resource_list_alloc(rl, bus, child, type, rid, start,
		    end, count, flags));
	case SYS_RES_MEMORY:
		if (!passthrough) {
			rle = resource_list_find(rl, type, *rid);
			if (rle == NULL)
				return (NULL);
			if (rle->res != NULL)
				panic("%s: resource entry is busy", __func__);
			if (isdefault) {
				start = rle->start;
				count = ulmax(count, rle->count);
				end = ulmax(rle->end, start + count - 1);
			}
		}
		for (i = 0; i < sc->sc_nrange; i++) {
			coffset = sc->sc_ranges[i].coffset;
			cend = coffset + sc->sc_ranges[i].size - 1;
			if (start >= coffset && end <= cend) {
				start -= coffset;
				end -= coffset;
				phys = sc->sc_ranges[i].poffset |
				    ((bus_addr_t)sc->sc_ranges[i].pspace << 32);
				res = bus_generic_alloc_resource(bus, child,
				    type, rid, phys + start, phys + end,
				    count, flags);
				if (!passthrough)
					rle->res = res;
				break;
			}
		}
		break;
	}
	return (res);
}

static struct resource_list *
central_get_resource_list(device_t bus, device_t child)
{
	struct central_devinfo *cdi;

	cdi = device_get_ivars(child);
	return (&cdi->cdi_rl);
}

static const struct ofw_bus_devinfo *
central_get_devinfo(device_t bus, device_t child)
{
	struct central_devinfo *cdi;

	cdi = device_get_ivars(child);
	return (&cdi->cdi_obdinfo);
}

static int
central_print_res(struct central_devinfo *cdi)
{

	return (resource_list_print_type(&cdi->cdi_rl, "mem", SYS_RES_MEMORY,
	    "%#lx"));
}


text:
dbm.registerClass("dbm.flow.nodes.curves.GetPointOnCurveNode", "dbm.core.FlowBaseObject", function(objectFunctions, staticFunctions, ClassReference) {
	//console.log("dbm.flow.nodes.curves.GetPointOnCurveNode");

	//Self reference
	var GetPointOnCurveNode = dbm.importClass("dbm.flow.nodes.curves.GetPointOnCurveNode");

	//Error report

	//Dependencies
	var Point = dbm.importClass("dbm.core.data.points.Point");

	//Utils

	//Constants

	/**
	 * Constructor
	 */
	objectFunctions._init = function() {
		//console.log("dbm.flow.nodes.curves.GetPointOnCurveNode::_init");

		this.superCall();

		this._curve = this.createProperty("curve", null).setAlwaysUpdateFlow(true);
		this._parameter = this.createProperty("parameter", 0);
		this._outputValueX = this.createProperty("outputValueX", 0);
		this._outputValueY = this.createProperty("outputValueY", 0);
		this._outputValueZ = this.createProperty("outputValueZ", 0);

		this._tempPoint = Point.create();

		this.createUpdateFunction("default", this._update, [this._curve, this._parameter], [this._outputValueX, this._outputValueY, this._outputValueZ]);

		return this;
	};

	objectFunctions._update = function(aFlowUpdateNumber) {
		//console.log("dbm.flow.nodes.curves.GetPointOnCurveNode::_update");

		var curve = this._curve.getValueWithoutFlow();
		var parameter = this._parameter.getValueWithoutFlow();
		curve.getPointOnCurve(parameter, this._tempPoint);

		this._outputValueX.setValueWithFlow(this._tempPoint.x, aFlowUpdateNumber);
		this._outputValueY.setValueWithFlow(this._tempPoint.y, aFlowUpdateNumber);
		this._outputValueZ.setValueWithFlow(this._tempPoint.z, aFlowUpdateNumber);
	};

	objectFunctions.setAllReferencesToNull = function() {

		this._curve = null;
		this._parameter = null;
		this._outputValueX = null;
		this._outputValueY = null;
		this._outputValueZ = null;

		this.superCall();
	};

	staticFunctions.create = function(aCurve, aParameter) {
		var newNode = (new ClassReference()).init();
		newNode.setPropertyInputWithoutNull("curve", aCurve);
		newNode.setPropertyInputWithoutNull("parameter", aParameter);
		return newNode;
	};
});


text:
#include "config.h"
#include "ResourceRequestBase.h"

#include "ResourceRequest.h"

using namespace std;

namespace WebCore {

#if !USE(SOUP) && (!PLATFORM(MAC) || USE(CFNETWORK)) && !PLATFORM(QT)
double ResourceRequestBase::s_defaultTimeoutInterval = INT_MAX;
#else
// Will use NSURLRequest default timeout unless set to a non-zero value with setDefaultTimeoutInterval().
// For libsoup the timeout enabled with integer milliseconds. We set 0 as the default value to avoid integer overflow.
double ResourceRequestBase::s_defaultTimeoutInterval = 0;
#endif

inline const ResourceRequest& ResourceRequestBase::asResourceRequest() const
{
    return *static_cast<const ResourceRequest*>(this);
}

PassOwnPtr<ResourceRequest> ResourceRequestBase::adopt(PassOwnPtr<CrossThreadResourceRequestData> data)
{
    OwnPtr<ResourceRequest> request = adoptPtr(new ResourceRequest());
    request->setURL(data->m_url);
    request->setCachePolicy(data->m_cachePolicy);
    request->setTimeoutInterval(data->m_timeoutInterval);
    request->setFirstPartyForCookies(data->m_firstPartyForCookies);
    request->setHTTPMethod(data->m_httpMethod);
    request->setPriority(data->m_priority);

    request->updateResourceRequest();
    request->m_httpHeaderFields.adopt(data->m_httpHeaders.release());

    size_t encodingCount = data->m_responseContentDispositionEncodingFallbackArray.size();
    if (encodingCount > 0) {
        String encoding1 = data->m_responseContentDispositionEncodingFallbackArray[0];
        String encoding2;
        String encoding3;
        if (encodingCount > 1) {
            encoding2 = data->m_responseContentDispositionEncodingFallbackArray[1];
            if (encodingCount > 2)
                encoding3 = data->m_responseContentDispositionEncodingFallbackArray[2];
        }
        ASSERT(encodingCount <= 3);
        request->setResponseContentDispositionEncodingFallbackArray(encoding1, encoding2, encoding3);
    }
    request->setHTTPBody(data->m_httpBody);
    request->setAllowCookies(data->m_allowCookies);
    request->doPlatformAdopt(data);
    return request.release();
}

PassOwnPtr<CrossThreadResourceRequestData> ResourceRequestBase::copyData() const
{
    OwnPtr<CrossThreadResourceRequestData> data = adoptPtr(new CrossThreadResourceRequestData());
    data->m_url = url().copy();
    data->m_cachePolicy = cachePolicy();
    data->m_timeoutInterval = timeoutInterval();
    data->m_firstPartyForCookies = firstPartyForCookies().copy();
    data->m_httpMethod = httpMethod().isolatedCopy();
    data->m_httpHeaders = httpHeaderFields().copyData();
    data->m_priority = priority();

    data->m_responseContentDispositionEncodingFallbackArray.reserveInitialCapacity(m_responseContentDispositionEncodingFallbackArray.size());
    size_t encodingArraySize = m_responseContentDispositionEncodingFallbackArray.size();
    for (size_t index = 0; index < encodingArraySize; ++index) {
        data->m_responseContentDispositionEncodingFallbackArray.append(m_responseContentDispositionEncodingFallbackArray[index].isolatedCopy());
    }
    if (m_httpBody)
        data->m_httpBody = m_httpBody->deepCopy();
    data->m_allowCookies = m_allowCookies;
    return asResourceRequest().doPlatformCopyData(data.release());
}

bool ResourceRequestBase::isEmpty() const
{
    updateResourceRequest();

    return m_url.isEmpty();
}

bool ResourceRequestBase::isNull() const
{
    updateResourceRequest();

    return m_url.isNull();
}

const KURL& ResourceRequestBase::url() const
{
    updateResourceRequest();

    return m_url;
}

void ResourceRequestBase::setURL(const KURL& url)
{
    updateResourceRequest();

    m_url = url;

    m_platformRequestUpdated = false;
}

void ResourceRequestBase::removeCredentials()
{
    updateResourceRequest();

    if (m_url.user().isEmpty() && m_url.pass().isEmpty())
        return;

    m_url.setUser(String());
    m_url.setPass(String());

    m_platformRequestUpdated = false;
}

ResourceRequestCachePolicy ResourceRequestBase::cachePolicy() const
{
    updateResourceRequest();

    return m_cachePolicy;
}

void ResourceRequestBase::setCachePolicy(ResourceRequestCachePolicy cachePolicy)
{
    updateResourceRequest();

    if (m_cachePolicy == cachePolicy)
        return;

    m_cachePolicy = cachePolicy;

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

double ResourceRequestBase::timeoutInterval() const
{
    updateResourceRequest();

    return m_timeoutInterval;
}

void ResourceRequestBase::setTimeoutInterval(double timeoutInterval)
{
    updateResourceRequest();

    if (m_timeoutInterval == timeoutInterval)
        return;

    m_timeoutInterval = timeoutInterval;

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

const KURL& ResourceRequestBase::firstPartyForCookies() const
{
    updateResourceRequest();

    return m_firstPartyForCookies;
}

void ResourceRequestBase::setFirstPartyForCookies(const KURL& firstPartyForCookies)
{
    updateResourceRequest();

    if (m_firstPartyForCookies == firstPartyForCookies)
        return;

    m_firstPartyForCookies = firstPartyForCookies;

    m_platformRequestUpdated = false;
}

const String& ResourceRequestBase::httpMethod() const
{
    updateResourceRequest();

    return m_httpMethod;
}

void ResourceRequestBase::setHTTPMethod(const String& httpMethod)
{
    updateResourceRequest();

    if (m_httpMethod == httpMethod)
        return;

    m_httpMethod = httpMethod;

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

const HTTPHeaderMap& ResourceRequestBase::httpHeaderFields() const
{
    updateResourceRequest();

    return m_httpHeaderFields;
}

String ResourceRequestBase::httpHeaderField(const AtomicString& name) const
{
    updateResourceRequest();

    return m_httpHeaderFields.get(name);
}

String ResourceRequestBase::httpHeaderField(const char* name) const
{
    updateResourceRequest();

    return m_httpHeaderFields.get(name);
}

void ResourceRequestBase::setHTTPHeaderField(const AtomicString& name, const String& value)
{
    updateResourceRequest();

    m_httpHeaderFields.set(name, value);

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

void ResourceRequestBase::setHTTPHeaderField(const char* name, const String& value)
{
    setHTTPHeaderField(AtomicString(name), value);
}

void ResourceRequestBase::clearHTTPAuthorization()
{
    updateResourceRequest();

    HTTPHeaderMap::iterator iter = m_httpHeaderFields.find("Authorization");
    if (iter == m_httpHeaderFields.end())
        return;

    m_httpHeaderFields.remove(iter);

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

void ResourceRequestBase::clearHTTPContentType()
{
    updateResourceRequest();

    m_httpHeaderFields.remove("Content-Type");

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

void ResourceRequestBase::clearHTTPReferrer()
{
    updateResourceRequest();

    m_httpHeaderFields.remove("Referer");

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

void ResourceRequestBase::clearHTTPOrigin()
{
    updateResourceRequest();

    m_httpHeaderFields.remove("Origin");

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

void ResourceRequestBase::clearHTTPUserAgent()
{
    updateResourceRequest();

    m_httpHeaderFields.remove("User-Agent");

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

void ResourceRequestBase::clearHTTPAccept()
{
    updateResourceRequest();

    m_httpHeaderFields.remove("Accept");

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

void ResourceRequestBase::setResponseContentDispositionEncodingFallbackArray(const String& encoding1, const String& encoding2, const String& encoding3)
{
    updateResourceRequest();

    m_responseContentDispositionEncodingFallbackArray.clear();
    m_responseContentDispositionEncodingFallbackArray.reserveInitialCapacity(!encoding1.isNull() + !encoding2.isNull() + !encoding3.isNull());
    if (!encoding1.isNull())
        m_responseContentDispositionEncodingFallbackArray.uncheckedAppend(encoding1);
    if (!encoding2.isNull())
        m_responseContentDispositionEncodingFallbackArray.uncheckedAppend(encoding2);
    if (!encoding3.isNull())
        m_responseContentDispositionEncodingFallbackArray.uncheckedAppend(encoding3);

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

FormData* ResourceRequestBase::httpBody() const
{
    updateResourceRequest(UpdateHTTPBody);

    return m_httpBody.get();
}

void ResourceRequestBase::setHTTPBody(PassRefPtr<FormData> httpBody)
{
    updateResourceRequest();

    m_httpBody = httpBody;

    m_resourceRequestBodyUpdated = true;

    if (url().protocolIsInHTTPFamily())
        m_platformRequestBodyUpdated = false;
}

bool ResourceRequestBase::allowCookies() const
{
    updateResourceRequest();

    return m_allowCookies;
}

void ResourceRequestBase::setAllowCookies(bool allowCookies)
{
    updateResourceRequest();

    if (m_allowCookies == allowCookies)
        return;

    m_allowCookies = allowCookies;

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

ResourceLoadPriority ResourceRequestBase::priority() const
{
    updateResourceRequest();

    return m_priority;
}

void ResourceRequestBase::setPriority(ResourceLoadPriority priority)
{
    updateResourceRequest();

    if (m_priority == priority)
        return;

    m_priority = priority;

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

void ResourceRequestBase::addHTTPHeaderField(const AtomicString& name, const String& value)
{
    updateResourceRequest();
    HTTPHeaderMap::AddResult result = m_httpHeaderFields.add(name, value);
    if (!result.isNewEntry)
        result.iterator->value = result.iterator->value + ',' + value;

    if (url().protocolIsInHTTPFamily())
        m_platformRequestUpdated = false;
}

void ResourceRequestBase::addHTTPHeaderFields(const HTTPHeaderMap& headerFields)
{
    HTTPHeaderMap::const_iterator end = headerFields.end();
    for (HTTPHeaderMap::const_iterator it = headerFields.begin(); it != end; ++it)
        addHTTPHeaderField(it->key, it->value);
}

bool equalIgnoringHeaderFields(const ResourceRequestBase& a, const ResourceRequestBase& b)
{
    if (a.url() != b.url())
        return false;

    if (a.cachePolicy() != b.cachePolicy())
        return false;

    if (a.timeoutInterval() != b.timeoutInterval())
        return false;

    if (a.firstPartyForCookies() != b.firstPartyForCookies())
        return false;

    if (a.httpMethod() != b.httpMethod())
        return false;

    if (a.allowCookies() != b.allowCookies())
        return false;

    if (a.priority() != b.priority())
        return false;

    FormData* formDataA = a.httpBody();
    FormData* formDataB = b.httpBody();

    if (!formDataA)
        return !formDataB;
    if (!formDataB)
        return !formDataA;

    if (*formDataA != *formDataB)
        return false;

    return true;
}

bool ResourceRequestBase::compare(const ResourceRequest& a, const ResourceRequest& b)
{
    if (!equalIgnoringHeaderFields(a, b))
        return false;

    if (a.httpHeaderFields() != b.httpHeaderFields())
        return false;

    return ResourceRequest::platformCompare(a, b);
}

bool ResourceRequestBase::isConditional() const
{
    return (m_httpHeaderFields.contains("If-Match") ||
            m_httpHeaderFields.contains("If-Modified-Since") ||
            m_httpHeaderFields.contains("If-None-Match") ||
            m_httpHeaderFields.contains("If-Range") ||
            m_httpHeaderFields.contains("If-Unmodified-Since"));
}

void ResourceRequestBase::makeUnconditional()
{
    m_httpHeaderFields.remove("If-Match");
    m_httpHeaderFields.remove("If-Modified-Since");
    m_httpHeaderFields.remove("If-None-Match");
    m_httpHeaderFields.remove("If-Range");
    m_httpHeaderFields.remove("If-Unmodified-Since");
}

double ResourceRequestBase::defaultTimeoutInterval()
{
    return s_defaultTimeoutInterval;
}

void ResourceRequestBase::setDefaultTimeoutInterval(double timeoutInterval)
{
    s_defaultTimeoutInterval = timeoutInterval;
}

void ResourceRequestBase::updatePlatformRequest(HTTPBodyUpdatePolicy bodyPolicy) const
{
    if (!m_platformRequestUpdated) {
        ASSERT(m_resourceRequestUpdated);
        const_cast<ResourceRequest&>(asResourceRequest()).doUpdatePlatformRequest();
        m_platformRequestUpdated = true;
    }

    if (!m_platformRequestBodyUpdated && bodyPolicy == UpdateHTTPBody) {
        ASSERT(m_resourceRequestBodyUpdated);
        const_cast<ResourceRequest&>(asResourceRequest()).doUpdatePlatformHTTPBody();
        m_platformRequestBodyUpdated = true;
    }
}

void ResourceRequestBase::updateResourceRequest(HTTPBodyUpdatePolicy bodyPolicy) const
{
    if (!m_resourceRequestUpdated) {
        ASSERT(m_platformRequestUpdated);
        const_cast<ResourceRequest&>(asResourceRequest()).doUpdateResourceRequest();
        m_resourceRequestUpdated = true;
    }

    if (!m_resourceRequestBodyUpdated && bodyPolicy == UpdateHTTPBody) {
        ASSERT(m_platformRequestBodyUpdated);
        const_cast<ResourceRequest&>(asResourceRequest()).doUpdateResourceHTTPBody();
        m_resourceRequestBodyUpdated = true;
    }
}

#if !PLATFORM(MAC) && !USE(CFNETWORK) && !USE(SOUP) && !PLATFORM(QT) && !PLATFORM(BLACKBERRY)
unsigned initializeMaximumHTTPConnectionCountPerHost()
{
    // This is used by the loader to control the number of issued parallel load requests.
    // Four seems to be a common default in HTTP frameworks.
    return 4;
}
#endif

}


text:
		<form class="form-horizontal">

				Type of Statistic

		  			<select id="type" class="form-control float-left select-big"  ng-model="type" ng-init="type" ng-change="update()">
						<option value="Top Net Income">Top Net Income</option>
						<option value="Top Earners">Top Earners</option>
						<option value="Top Spenders">Top Spenders</option>
					</select>

				Number of User(s)

		  			<select id="limit" class="form-control float-left select-big" ng-model="limit" ng-init="limit" ng-change="update()">
						<option value="1">1</option>
						<option value="5">5</option>
						<option value="10">10</option>
					</select>

		</form>


text:
layout: example.html
title: Drag rotate and zoom example
shortdesc: A single interaction to drag, rotate, and zoom.
docs: >

Shift + Drag to rotate and zoom the map around its center.

tags: "drag, rotate, zoom, interaction"
---


text:
package org.eclipse.php.internal.debug.ui.breakpoint;

import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.resource.CompositeImageDescriptor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.php.internal.debug.ui.PHPDebugUIImages;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;

/**
 * An image descriptor for the PHP conditional breakpoints.
 *
 * @author shalom
 * @since 26/09/2006
 */
public class PHPBreakpointImageDescriptor extends CompositeImageDescriptor {

	/** Flag to render the enabled breakpoint adornment */
	public final static int ENABLED = 0x0020;
	/** Flag to render the conditional breakpoint adornment */
	public final static int CONDITIONAL = 0x0040;

	private ImageDescriptor fBaseImage;
	private int fFlags;
	private Point fSize;

	/**
	 * Constructs a new PHPBreakpointImageDescriptor.
	 *
	 * @param baseImage
	 *            an image descriptor used as the base image.
	 * @param flags
	 *            flags indicating which adornments are to be rendered.
	 * @see #ENABLED
	 * @see #CONDITIONAL
	 */
	public PHPBreakpointImageDescriptor(ImageDescriptor baseImage, int flags) {
		fBaseImage = baseImage;
		Assert.isNotNull(fBaseImage);
		fFlags = flags;
		Assert.isTrue(fFlags >= 0);
	}

	/**
	 * @see Object#equals(java.lang.Object)
	 */
	public boolean equals(Object object) {
		if (!(object instanceof PHPBreakpointImageDescriptor)) {
			return false;
		}

		PHPBreakpointImageDescriptor other = (PHPBreakpointImageDescriptor) object;
		return (getBaseImage().equals(other.getBaseImage()) && getFlags() == other
				.getFlags());
	}

	/**
	 * @see Object#hashCode()
	 */
	public int hashCode() {
		return getBaseImage().hashCode() | getFlags();
	}

	protected void drawCompositeImage(int width, int height) {
		ImageData bg = getBaseImage().getImageData();
		if (bg == null) {
			bg = DEFAULT_IMAGE_DATA;
		}
		drawImage(bg, 0, 0);
		drawOverlays();
	}

	private void drawOverlays() {
		int flags = getFlags();
		int x = 0;
		int y = 0;
		ImageData data = null;
		if ((flags & CONDITIONAL) != 0) {
			if ((flags & ENABLED) != 0) {
				data = getImageData(PHPDebugUIImages.IMG_OVR_CONDITIONAL_BREAKPOINT);
			} else {
				data = getImageData(PHPDebugUIImages.IMG_OVR_CONDITIONAL_BREAKPOINT_DISABLED);
			}
			x = 0;
			y = 0;
			drawImage(data, x, y);
		}
	}

	private ImageData getImageData(String imageDescriptorKey) {
		return PHPDebugUIImages.getImageDescriptor(imageDescriptorKey)
				.getImageData();
	}

	protected Point getSize() {
		if (fSize == null) {
			ImageData data = getBaseImage().getImageData();
			setSize(new Point(data.width, data.height));
		}
		return fSize;
	}

	protected ImageDescriptor getBaseImage() {
		return fBaseImage;
	}

	protected void setBaseImage(ImageDescriptor baseImage) {
		fBaseImage = baseImage;
	}

	protected int getFlags() {
		return fFlags;
	}

	protected void setFlags(int flags) {
		fFlags = flags;
	}

	protected void setSize(Point size) {
		fSize = size;
	}

}


text:
#if !defined(BOOST_SPIRIT_KARMA_OUTPUT_ITERATOR_MAY_26_2007_0506PM)
#define BOOST_SPIRIT_KARMA_OUTPUT_ITERATOR_MAY_26_2007_0506PM

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once      // MS compatible compilers support #pragma once
#endif

#include <iterator>
#include <vector>
#include <algorithm>

#include <boost/noncopyable.hpp>
#include <boost/spirit/home/karma/detail/ostream_iterator.hpp>

namespace boost { namespace spirit { namespace karma { namespace detail
{
    ///////////////////////////////////////////////////////////////////////////
    //  This class is used to keep track of the current position in the output.
    ///////////////////////////////////////////////////////////////////////////
    class position_sink
    {
    public:
        position_sink() : count(0), line(1), column(0) {}
        void tidy() { count = 0; line = 1; column = 0; }

        template <typename T>
        void output(T const& value)
        {
            ++count;
            if (value == '\n') {
                ++line;
                column = 1;
            }
            else {
                ++column;
            }
        }
        std::size_t get_count() const { return count; }
        std::size_t get_line() const { return line; }
        std::size_t get_column() const { return column; }

    private:
        std::size_t count;
        std::size_t line;
        std::size_t column;
    };

    ///////////////////////////////////////////////////////////////////////////
    //  This class is used to count the umber of characters streamed into the
    //  output.
    ///////////////////////////////////////////////////////////////////////////
    class counting_sink
    {
    public:
        counting_sink() : count(0) {}

        void init(std::size_t count_) { count = count_; }
        void tidy() { count = 0; }

        void output() { ++count; }
        std::size_t get_count() const { return count; }

    private:
        std::size_t count;
    };

    ///////////////////////////////////////////////////////////////////////////
    //  The following classes are used to intercept the output into a buffer
    //  allowing to do things like alignment, character escaping etc.
    //
    //  We need to use virtual functions because output_iterators do not have
    //  an associated value_type. The type of the buffer elements is available
    //  at insertion time only (and not at buffer creation time).
    ///////////////////////////////////////////////////////////////////////////
    template <typename OutputIterator>
    struct abstract_container
    {
        virtual ~abstract_container() {}
        virtual void output(void const *item) = 0;
        virtual void copy(OutputIterator& sink) = 0;
        virtual std::size_t buffer_size() = 0;
    };

    template <typename OutputIterator, typename T>
    class concrete_container : public abstract_container<OutputIterator>
    {
    public:
        concrete_container(std::size_t size)
        {
            buffer.reserve(size);
        }
        ~concrete_container() {}

        void output(void const *item)
        {
            buffer.push_back(*static_cast<T const*>(item));
        }
        void copy(OutputIterator& sink)
        {
            std::copy(buffer.begin(), buffer.end(), sink);
        }
        std::size_t buffer_size()
        {
            return buffer.size();
        }

    private:
        std::vector<T> buffer;
    };

    ///////////////////////////////////////////////////////////////////////////
    template <typename OutputIterator>
    class buffer_sink : boost::noncopyable
    {
    public:
        buffer_sink()
          : width(0), buffer(0)
        {}

        ~buffer_sink()
        {
            delete buffer;
        }

        void init(std::size_t width_) { width = width_; }
        void tidy() { delete buffer; buffer = 0; width = 0; }

        template <typename T>
        void output(T const& value)
        {
            if (0 == buffer)
            {
                typedef concrete_container<OutputIterator, T> container;
                buffer = new container(width);
            }
            buffer->output(&value);
        }

        void copy(OutputIterator& sink) const
        {
            if (buffer)
                buffer->copy(sink);
        }

        std::size_t buffer_size() const
        {
            return buffer ? buffer->buffer_size() : 0;
        }

    private:
        std::size_t width;
        abstract_container<OutputIterator> *buffer;
    };

    ///////////////////////////////////////////////////////////////////////////
    //  forward declaration only
    ///////////////////////////////////////////////////////////////////////////
    template <typename OutputIterator> struct enable_counting;
    template <typename OutputIterator> struct enable_buffering;

    ///////////////////////////////////////////////////////////////////////////
    //  Karma uses a output iterator wrapper for all output operations. This
    //  is necessary to avoid the dreaded 'scanner business' problem, i.e. the
    //  dependency of rules and grammars on the used output iterator.
    //
    //  By default the user supplied output iterator is wrapped inside an
    //  instance of this internal output_iterator class.
    //
    //  This output_iterator class normally just forwards to the embedded user
    //  supplied iterator. But it is possible to enable additional functionality
    //  on demand, such as counting, buffering, and position tracking.
    ///////////////////////////////////////////////////////////////////////////
    template <typename OutputIterator, typename Enable = void>
    class output_iterator : boost::noncopyable
    {
    private:
        enum output_mode
        {
            output_characters = 0,    // just hand through character
            count_characters = 1,     // additionally count characters
            buffer_characters = 2     // buffer all characters, no output
        };

        struct output_proxy
        {
            output_proxy(output_iterator& parent)
              : parent(parent)
            {}

            template <typename T>
            output_proxy& operator=(T const& value)
            {
                parent.output(value);
                return *this;
            }

        private:
            output_iterator& parent;

            // suppress warning about assignment operator not being generated
            output_proxy& operator=(output_proxy const&);
        };

#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
private:
        friend struct enable_counting<output_iterator>;
        friend struct enable_buffering<output_iterator>;
#else
public:
#endif
        // functions related to counting
        void enable_counting(std::size_t count = 0)
        {
            count_data.init(count);
            mode = output_mode(mode | count_characters);
        }
        void disable_counting()
        {
            mode = output_mode(mode & ~count_characters);
        }
        void reset_counting()
        {
            count_data.tidy();
        }

        // functions related to buffering
        void enable_buffering(std::size_t width = 0)
        {
            buffer_data.init(width);
            mode = output_mode(mode | buffer_characters);
        }
        void disable_buffering()
        {
            mode = output_mode(mode & ~buffer_characters);
        }
        void reset_buffering()
        {
            buffer_data.tidy();
        }

    public:
        typedef std::output_iterator_tag iterator_category;
        typedef void value_type;
        typedef void difference_type;
        typedef void pointer;
        typedef void reference;

        output_iterator(OutputIterator& sink_)
          : sink(sink_), mode(output_characters)
        {}

        output_proxy operator*() { return output_proxy(*this); }
        output_iterator& operator++() { ++sink; return *this; }
        output_iterator& operator++(int) { sink++; return *this; }

        template <typename T>
        void output(T const& value)
        {
            if (mode & count_characters)    // count characters, if appropriate
                count_data.output();

            // always track position in the output (this is needed by different
            // generators, such as indent, pad, etc.)
            track_position_data.output(value);

            if (mode & buffer_characters)   // buffer output, if appropriate
                buffer_data.output(value);
            else
                *sink = value;
        }

        // functions related to counting
        std::size_t count() const
        {
            return count_data.get_count();
        }

        // functions related to buffering
        std::size_t buffer_size() const
        {
            return buffer_data.buffer_size();
        }
        void buffer_copy()
        {
            buffer_data.copy(sink);
        }

        // return the current count in the output
        std::size_t get_out_count() const
        {
            return track_position_data.get_count();
        }

    protected:
        // this is the wrapped user supplied output iterator
        OutputIterator& sink;

    private:
        // these are the hooks providing optional functionality
        counting_sink count_data;                   // for counting
        buffer_sink<OutputIterator> buffer_data;    // for buffering
        position_sink track_position_data;          // for position tracking
        int mode;

        // suppress warning about assignment operator not being generated
        output_iterator& operator=(output_iterator const&);
    };

    ///////////////////////////////////////////////////////////////////////////
    template <typename T, typename Elem, typename Traits>
    class output_iterator<ostream_iterator<T, Elem, Traits> >
      : public output_iterator<ostream_iterator<T, Elem, Traits>, int>
    {
    private:
        typedef
            output_iterator<ostream_iterator<T, Elem, Traits>, int>
        base_type;
        typedef ostream_iterator<T, Elem, Traits> base_iterator_type;
        typedef std::basic_ostream<Elem, Traits> ostream_type;

    public:
        output_iterator(base_iterator_type& sink)
          : base_type(sink)
        {}

        ostream_type& get_ostream() { return this->sink.get_ostream(); }
    };

    ///////////////////////////////////////////////////////////////////////////
    //  Helper class for exception safe enabling of character counting in the
    //  output iterator
    ///////////////////////////////////////////////////////////////////////////
    template <typename OutputIterator>
    struct enable_counting
    {
        enable_counting(OutputIterator& sink_, std::size_t count = 0)
          : sink(sink_)
        {
            sink.enable_counting(count);
        }
        ~enable_counting()
        {
            sink.disable_counting();
            sink.reset_counting();
        }

        void disable()
        {
            sink.disable_counting();
        }

        OutputIterator& sink;
    };

    ///////////////////////////////////////////////////////////////////////////
    //  Helper class for exception safe enabling of character buffering in the
    //  output iterator
    ///////////////////////////////////////////////////////////////////////////
    template <typename OutputIterator>
    struct enable_buffering
    {
        enable_buffering(OutputIterator& sink_, std::size_t width = 0)
          : sink(sink_)
        {
            sink.enable_buffering(width);
        }
        ~enable_buffering()
        {
            sink.disable_buffering();
            sink.reset_buffering();
        }

        void disable()
        {
            sink.disable_buffering();
        }

        OutputIterator& sink;
    };

}}}}

#endif


text:
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.

## [8.0.7](https://github.com/serialport/node-serialport/compare/v8.0.6...v8.0.7) (2020-01-30)

**Note:** Version bump only for package @serialport/bindings

## [8.0.6](https://github.com/serialport/node-serialport/compare/v8.0.5...v8.0.6) (2019-12-25)

### Bug Fixes

* bindings.close() should cause a canceled read error ([#1972](https://github.com/serialport/node-serialport/issues/1972)) ([50f967e](https://github.com/serialport/node-serialport/commit/50f967e788f362da57d782829712542c8f15f8c8))
* No prebuilt binaries found with electron-builder ([#2003](https://github.com/serialport/node-serialport/issues/2003)) ([16f9662](https://github.com/serialport/node-serialport/commit/16f966233930bc7c7302d2b7a53d70282b42e165))


text:
var CONFIG = require('./config.js'); // Load configuration file
var five = require('johnny-five');
var CHIP = require("chip-io");
var board = new five.Board({ io: new CHIP() });

var Twit = require('twit');
var T = new Twit(CONFIG.TWITTER_API_KEYS);

board.on("ready", function() {
    postInitialStatus(); // Send tweet saying the script has started up
    var bell = new five.Button(CONFIG.BELL.pin || 'BTN'); // If no pin specified in config, it means we are using the onboard button to test by default
    bell.on('down', sendPress);
});

function sendPress() {
    // Debounces tweet notifications: only send a tweet if one has not yet been sent,
    // OR if a subsequent press has happened in a time equal to or greater than the defined time to wait.

    if (CONFIG.BELL.lastTweetSent === null || elapsedTime(CONFIG.BELL.lastTweetSent, Date.now()) >= CONFIG.BELL.debounceTime) {
        notify(CONFIG.COMMAND_RESPONSE_MAP.doorbellNotification.response());
        CONFIG.BELL.lastTweetSent = Date.now();
    }
}

function postInitialStatus() {
    T.post('statuses/update', {
        status: CONFIG.COMMAND_RESPONSE_MAP.startup.response()
    }, function(err, data, response) {
        if (err)
            console.info("[" + getTime() + "] BELLBOT_DEBUG: error in postInitialStatus() - " + JSON.stringify(err));
    });
}

function notify(text) {
    var users = "";

    for (var i = 0; i < CONFIG.AUTHORIZED_USERS.length; i++)
        users += '@' + CONFIG.AUTHORIZED_USERS[i] + ' ';

    // remove trailing whitespace
    if (users[users.length - 1] == " ")
        users = users.slice(0, users.length - 1);

    var params = {
        status: text.replace('<USER>', users),
    };

    T.post('statuses/update', params, function(err, data, response) {
        if (err)
            console.info("[" + getTime() + "] BELLBOT_DEBUG: error in notify() - " + JSON.stringify(err));
    });
}

// Computes elapsed time (used for debouncing)
function elapsedTime(startTime, endTime) {
    return ((endTime - startTime) / 1000);
}

// Converts the current time to a more human-readable format (for notification timestamping)
function getTime() {
    var dt = new Date();
    var hours = (dt.getHours() % 12 || 12);
    var minutes = dt.getMinutes();

    // ensure minutes always 2 digits
    if (dt.getMinutes() < 10)
        minutes = "0" + minutes;

    return hours + ":" + minutes;
}


text:
const date = require('../../date');
const logger = require('../../logger/logger').logger;
const ProductionEventBuilder = require('../../model/response/event/productionEvent').ProductionEventBuilder;
const EventEnum = require('../../enum/eventEnum').EventEnum;

const build = function build(event, productionYear) {
  logger.debug('build production event:', event);

  if (productionYear) {
    productionYear = `01.01.${productionYear}`;
  }
  else if (event && event.createdAt) {
    productionYear = event.createdAt;
  }

  const createdAt = date.parseIsoString(productionYear);

  if (!createdAt) {
    return null;
  }

  return new ProductionEventBuilder()
    .withType(EventEnum.PRODUCTION)
    .withCreatedAt(createdAt)
    .withDescription(`Rok produkcji: ${createdAt}`)
    .build();
};

module.exports = {
  build: build
};


text:
from flask import Flask, request, render_template, send_from_directory
app = Flask(__name__, static_folder='templates')

@app.route('/')
def Tetris():
    return render_template('index.html')

@app.route('/ai')
def AI():
    return render_template('ai.html')

@app.route('/<path:path>')
def send_static(path):
    return send_from_directory(app.static_folder, path)

if __name__ == '__main__':
    app.debug = True
    app.run(host = '0.0.0.0', port = 80, threaded = True)


text:
module.exports = function(app) {

	var api = app.api.frases;

	app.route('/frases/')
		.get(api.lista);
};


text:
package com.aspose.tasks.examples.ResourceAssignments;

import com.aspose.tasks.*;
import com.aspose.tasks.examples.Utils;

public class AssignmentBudget
{
    public static void main(String[] args) throws Exception
    {
        // The path to the documents directory.
        String dataDir = Utils.getDataDir(AssignmentBudget.class);

        Project prj = new Project(dataDir + "project5.mpp");

        for(ResourceAssignment ra:prj.getResourceAssignments())
        {
                System.out.println(ra.get(Asn.BUDGET_COST));
                System.out.println(ra.get(Asn.BUDGET_WORK).toString());
        }

    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>CodePen - A Pen by  Renee Jackson</title>

  <link rel="stylesheet" href="css/normalize.css">

    <link rel="stylesheet" href="css/style.css">

  <!DOCTYPE html>
<link rel="style.css">

<meta charset="UTF-
<title" My App by Renee Jackson</title>

<div class="My App by Renee Jackson"

    How does the web work?

  When entering the web the language used is HTML.
 Computers talk through HTTP by requesting information via a server.

HTML = stands for Hypertext Markup Language
 The web uses Hyper Links
It was invented in 1990's
HTML is made up of text content, markup and references to other documents

 Text Content - Is What you see

  Markup - Is what it looks like
References to other documents - e.g. images & videos

  www = World  Wide Web

    An example of this is:  "www.udacity.com"

Html hyperlink

Main document types on web is html

  Major pieces of web are: you+your computer+internet+http+servers

  Html markup

  HTML markup is made up of tags, name contents, name whole thing

    Examples of tags are:

b=bold tag

     em=italizied

attr = value = Html attributes attr="value"

  a href =
  Anchors makes links

  An example of this is:Udacity"

img = Images

Code requires an open and closed tag.  To specifiy that it is a void element, a "/" is included at the end of a tag.

White space is used to force to another line.  This and be accomplished with br tag and p tag.
 br=tag to break

 P = tag is paragrah

 Br tag is inline

 p = tag is a block make and invisible box

 Span is inline

    Div is block

Computers Are Stupid

 Types of Documents are:

 Html document

Doc type

Head tag has meta data, java or css

Title tag

Body tag

     They interput what is coded in

  Creating structured Document with HTML

      Adding Sytle with CSS

  CSS is code written to control the "sytle" of HTML elements
  This can be done by using elements and class

  There are 3 methods to write CSS

  Method 1: Write CSS into the HTML by adding: head element and style elements.  This is used for small projects

  Method 2: Link HTML to a seperate CSS file.  This adds additional steps but works well in larger projects.

  Method 3: Write style inline with your HTML by coding each individual HTML element.  This approach can cause a lot of repeated code.

  Boxes to HTML
Cascading
 Style Sheets

  Rule specifity

  Link are formed by a tags

  Each tag has a style tag

  You can also set rules that override

  *{=webkit-box-sizing: border-box; -moz-box=sizing: border-box;-ms-box-sizing: border-box;}

  Flexbox is a good way to have items flex in location {display: flex:}

  Code, Test, Refine

  Look for natural boxes

  Look for repeated styles and semantic elements

  Write you html

  Apply styles -Go from biggest to smallest

  Fix things

  Developer tools allow you to test

  Use Dev tools to help find background and color and copy to CSS in your app

  Refine the design

  Check margin size and background colors

    It is important to verify your css code
    It is also important to avoid repetition in your code. As project grow this becomes for important to keep your code easy to test, correct and build on


text:
require 'spec_helper'

describe CurrencyConverter::XE do
  let(:currency_converter) { described_class.new }

  context '#exchange' do
    it 'returns the correct rate' do
      expect(currency_converter.exchange('USD', 'USD', 1)).to eq 1
    end
  end

  context '#validate_currency' do
    context 'CurrencyConverter::UnknownCurrency' do
      it 'raise an error on an unsupported currency code' do
        expect { currency_converter.exchange('EUR', 'UNKNOWN', 100) }.to raise_error(CurrencyConverter::UnknownCurrency)
        expect { currency_converter.exchange('UNKNOWN', 'EUR', 100) }.to raise_error(CurrencyConverter::UnknownCurrency)
      end

      it 'doesn\'t raise an error for supported currency codes' do
        expect { currency_converter.exchange('EUR', 'USD', 100) }.to_not raise_error
      end
    end
  end
end


text:
import os
import ast
import sys
import math
import time
import string
import hashlib
import tempfile
import subprocess
from operator import itemgetter
from contextlib import contextmanager
from getpass import getpass
import random; random = random.SystemRandom()

import sdb.subprocess_compat as subprocess
from sdb.util import force_bytes
from sdb.clipboard import set_clipboard_once, ClipboardException
from sdb.diceware import WORDS
from sdb import gpg_agent

def encode(records):
    res = []
    for record in records:
        res.append(repr(record))
    return ('\n'.join(res) + '\n').encode('utf-8')

def decode(str):
    records = []
    for line in str.decode('utf-8').split('\n'):
        if line:
            records.append(ast.literal_eval(line))
    return records

CASE_ALPHABET = string.ascii_letters
ALPHANUMERIC = CASE_ALPHABET + string.digits
EVERYTHING = ALPHANUMERIC + string.punctuation

def gen_password(choices=ALPHANUMERIC, length=10):
    return ''.join(random.choice(choices) for i in range(length))

def requirements_satisfied(requirements, str):
    return all([i in str for i in requirements])

def gen_password_require(requirements, choices=ALPHANUMERIC, length=10):
    """
    Generate a password containing all the characters in requirements
    """
    if len(requirements) > length or not requirements_satisfied(requirements, choices):
        raise Exception(
            "That's impossible, you can't make a password containing %r with only %r!" % (
                requirements, choices))
    while True:
        pw = gen_password(choices, length)
        if requirements_satisfied(requirements, pw):
            return pw

def gen_password_entropy(entropy, choices=ALPHANUMERIC):
    """
    Generates a password of the desired entropy, calculating the length as
    required.
    """
    required_length = int(math.ceil(entropy / math.log(len(choices), 2)))
    return gen_password(choices=choices, length=required_length)

def match(needle, haystack):
    score = 1
    j = 0
    last_match = 0
    for c in needle:
        while j < len(haystack) and haystack[j] != c:
            j += 1
        if j >= len(haystack):
            return 0
        score += 1 / (last_match + 1.)
        last_match = j
        j += 1
    return score

def record_score(term, records):
    return match(term, records[0] + records[1] + records[3])

def search(term, records):
    records = [(record_score(term, i), i) for i in records]
    records = list(filter(itemgetter(0), records))
    records.sort(key=itemgetter(0), reverse=True)
    return [i[1] for i in records]

def is_unique_list(lst):
    return len(lst) == len(set(lst))

def disambiguate(records):
    choices = [itemgetter(0),
               itemgetter(0, 1),
               itemgetter(0, 1, 3)]
    for choice in choices:
        result = list(map(choice, records))
        if is_unique_list(result):
            return result
    # just in case none were unique
    return records

class GPGException(Exception):
    pass

class IncorrectPasswordException(GPGException):
    pass

class InvalidEncryptedFileException(GPGException):
    pass

class FileCorruptionException(GPGException):
    pass

def gpg_exception_factory(returncode, message):
    if returncode == 2:
        if b'decryption failed: bad key' in message:
            return IncorrectPasswordException(message)
        if b'CRC error;' in message:
            return FileCorruptionException(message)
        if b'fatal: zlib inflate problem: invalid distance' in message:
            return FileCorruptionException(message)
        if b'decryption failed: invalid packet' in message:
            return FileCorruptionException(message)
        if b'no valid OpenPGP data found':
            return InvalidEncryptedFileException(message)
    return Exception("unkown error", returncode, message)

def dencrypt(command, pw, data):
    """
    Encrypts or decrypts, by running command
    """
    if '\n' in pw:
        raise Exception('Newlines not allowed in passwords')
    proc = subprocess.Popen(
        command,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    proc.stdin.write(force_bytes(pw))
    proc.stdin.write(b'\n')
    proc.stdin.write(data)
    output, erroroutput = proc.communicate()
    if proc.returncode != 0:
        raise gpg_exception_factory(proc.returncode, erroroutput)
    return output

def encrypt(pw, data):
    return dencrypt(
        ['gpg', '-c',
         '--passphrase-fd', '0',
         '--batch',
         '--armor',
         '--cipher-algo', 'AES',
         '--digest-algo', 'SHA256'],
        pw,
        data,
    )

def decrypt(pw, data):
    return dencrypt(
        ['gpg', '-d', '--passphrase-fd', '0', '--batch'],
        pw,
        data
    )

def get_tmp_file(filename):
    file_parts = os.path.split(filename)
    return os.path.join(*file_parts[:-1] + ('.' + file_parts[-1].lstrip('.') + '.tmp',))

def get_backup_file(filename):
    file_parts = os.path.split(filename)
    return os.path.join(*file_parts[:-1] + ('.' + file_parts[-1].lstrip('.') + '.bak',))

@contextmanager
def atomic_replace(filename):
    """
    ::
        with atomic_replace(filename) as f:
            f.write('asdf')

        with atomic_replace(filename) as f:
            f.write('asdf')
            raise Exception
        # nothing happens to the file
    """
    tmpfile_name = get_tmp_file(filename)
    fd = os.open(tmpfile_name, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600)
    try:
        f = os.fdopen(fd, "w+b")
        yield f
        f.flush()
        os.fsync(fd)  # fdatasync? I don't know
        f.seek(0)
        new_content = f.read()
        if not new_content:
            raise Exception("I don't think you want to blank this file...")
        try:
            with open(filename, 'rb') as current_f:
                current_content = current_f.read()
        except IOError:
            current_content = b''
        if current_content != new_content:
            with open(get_backup_file(filename), 'w+b') as backup_file:
                backup_file.write(current_content)
    except:
        # If there was an exception, remove the temporary file and reraise
        os.unlink(tmpfile_name)
        raise
    else:
        # No exception, rename the temp file over the original
        os.rename(tmpfile_name, filename)
    finally:
        f.close()

def edit_in_editor(current):
    EDITOR = os.environ.get('EDITOR', 'vim')
    with tempfile.NamedTemporaryFile(mode='w+') as f:
        try:
            f.write(current)
            f.flush()
            subprocess.call([EDITOR, f.name])
            f.seek(0)
            return f.read()
        finally:
            # don't leave potentially private data lying around
            f.write('0' * os.path.getsize(f.name))
            f.flush()

def pretty_record(record):
    s = '%s@%s' % (record[1], record[0])
    if record[3]:
        s += ': ' + record[3]
    return s

class InteractiveSession(object):
    def __init__(self, args, output=sys.stdout, input=sys.stdin, password=None):
        self.args = args
        self.file = args.file
        self.output = output
        self.input = input

        try:
            self.gpg_agent = gpg_agent.GpgAgent()
        except KeyError:
            self.gpg_agent = None

        self.gpg_agent_password_id = 'sdb_m:{file_fingerprint}'.format(
            file_fingerprint=hashlib.md5(force_bytes(self.file)).hexdigest()
        )

        self.password = password
        if not self.password:
            self.password = self.get_master_password()

    def get_master_password(self, error=None):
        if self.password:
            return self.password

        if self.input == sys.stdin:
            if self.gpg_agent:
                error = error or 'X'
                self.password = self.gpg_agent.get_passphrase(
                    self.gpg_agent_password_id,
                    prompt='Master password',
                    error=error
                )
            else:
                if error:
                    self.output.write('Error: {error}, try again: '.format(error=error))
                self.password = getpass()
        else:
            self.output.write('Password: ')
            self.output.flush()
            self.password = self.input.readline().rstrip('\n')
        return self.password

    def clear_master_password(self):
        self.password = None
        if self.gpg_agent:
            self.gpg_agent.clear_passphrase(self.gpg_agent_password_id)

    def prompt(self, prompt='', required=True, password=False):
        while True:
            if password and self.input == sys.stdin:
                line = getpass(prompt)
            else:
                self.output.write(prompt)
                self.output.flush()
                line = self.input.readline().rstrip('\n')
            if not required or line:
                return line

    def get_record(self, domain=None):
        domain = domain or self.prompt('Domain: ')
        username = self.prompt('Username: ')
        password = self.prompt(
            'Password [blank to generate]: ',
            required=False,
            password=True
        ) or gen_password_entropy(128)
        notes = self.prompt('Notes: ', required=False)

        return (domain, username, password, notes)

    def edit_record(self, record):
        new_record = list(record)
        new_record[0] = self.prompt('Name [%s]: ' % record[0], required=False) or record[0]
        new_record[1] = self.prompt('Username [%s]: ' % record[1], required=False) or record[1]
        pw = self.prompt('Password []/g: ', required=False, password=True) or record[2]
        if pw == 'g':
            new_record[2] = gen_password_entropy(128)
        elif pw:
            new_record[2] = pw
        self.output.write("Notes: %s\n" % record[3])
        edit = self.prompt('Edit? [n]: ', required=False) or 'n'
        if edit[0] == 'y':
            new_record[3] = edit_in_editor(record[3])
        return tuple(new_record)

    def find_record(self, query, records):
        possibilities = search(query, records)
        if len(possibilities) > 1:
            choices = disambiguate(possibilities)
            for i, choice in enumerate(choices):
                self.output.write('%s) %s\n' % (i, choice))
            choice = self.prompt('Which did you mean? [0]: ', required=False) or 0
            return possibilities[int(choice)]
        else:
            return possibilities[0]

    def read_records(self, error=None):
        try:
            with open(self.file, 'rb') as f:
                password = self.get_master_password(error)
                try:
                    return decode(decrypt(password, f.read()))
                except IncorrectPasswordException:
                    self.clear_master_password()
                    return self.read_records(error='Incorrect password')
                except:
                    self.clear_master_password()
                    raise
        except IOError:
            return []

    def add_action(self):
        record = self.get_record(self.args.domain or self.prompt('Domain: '))

        def add(records):
            return records + [record]
        self.edit_transaction(add)

    def show_action(self, clipboard=10):
        record = self.find_record(self.args.domain or self.prompt("Domain: "), self.read_records())
        self.output.write(pretty_record(record))
        self.output.write("\n")
        if clipboard:
            try:
                self.output.write("username in clipboard\n")
                set_clipboard_once(record[1])
                self.output.write("password in clipboard\n")
                set_clipboard_once(record[2])
            except ClipboardException as e:
                self.output.write("couldn't set clipboard: %s\n" % e.output.split('\n')[0])
                self.output.write(record[2])
                self.output.write("\n")
        else:
            return record[2]

    def edit_transaction(self, callback):
        with atomic_replace(self.file) as out:
            records = callback(self.read_records())
            assert isinstance(records, list)
            if not is_unique_list(records):
                raise Exception("You have two identical records. I don't think you want this.")
            out.write(encrypt(self.password, encode(records)))
            out.seek(0)
            assert records == decode(decrypt(self.password, out.read()))

    def edit_action(self):
        def edit(records):
            record = self.find_record(self.args.domain or self.prompt('Domain: '), records)
            new_record = self.edit_record(record)
            for i, choice in enumerate(records):
                if choice == record:
                    records[i] = tuple(new_record)
            return records
        self.edit_transaction(edit)

    def delete_action(self):
        def delete(records):
            record = self.find_record(self.args.domain or self.prompt('Domain: '), records)
            self.output.write(pretty_record(record))
            self.output.write('\n')
            confirm = self.prompt('Really? [n]: ', required=False) or 'n'
            if confirm[0] == 'y':
                for i, choice in enumerate(records):
                    if choice == record:
                        del records[i]
            else:
                self.output.write("Ok, cancelled\n")
            return records
        self.edit_transaction(delete)

    def raw_action(self):
        try:
            # PY3
            output = self.output.buffer
        except AttributeError:
            output = self.output
        output.write(encode(self.read_records()))