text:
package kieker.test.common.junit.record.flow.trace.concurrency;

import java.nio.ByteBuffer;

import org.junit.Assert;
import org.junit.Test;

import kieker.common.record.flow.trace.concurrency.JoinEvent;
import kieker.common.util.registry.IRegistry;
import kieker.common.util.registry.Registry;

import kieker.test.common.junit.AbstractGeneratedKiekerTest;
import kieker.test.common.util.record.BookstoreOperationExecutionRecordFactory;

/**
 * Creates {@link OperationExecutionRecord}s via the available constructors and
 * checks the values passed values via getters.
 *
 * @author Kieker Build
 *
 * @since 1.10
 */
public class TestGeneratedJoinEvent extends AbstractGeneratedKiekerTest {

	public TestGeneratedJoinEvent() {
		// empty default constructor
	}

	/**
	 * Tests {@link JoinEvent#TestJoinEvent(String, String, long, long, long, String, int, int)}.
	 */
	@Test
	public void testToArray() { // NOPMD (assert missing)
	for (int i=0;i<ARRAY_LENGTH;i++) {
			// initialize
			JoinEvent record = new JoinEvent(LONG_VALUES.get(i % LONG_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()), INT_VALUES.get(i % INT_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()));

			// check values
			Assert.assertEquals("JoinEvent.timestamp values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTimestamp());
			Assert.assertEquals("JoinEvent.traceId values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTraceId());
			Assert.assertEquals("JoinEvent.orderIndex values are not equal.", (int) INT_VALUES.get(i % INT_VALUES.size()), record.getOrderIndex());
			Assert.assertEquals("JoinEvent.joinedTraceId values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getJoinedTraceId());

			Object[] values = record.toArray();

			Assert.assertNotNull("Record array serialization failed. No values array returned.", values);
			Assert.assertEquals("Record array size does not match expected number of properties 4.", 4, values.length);

			// check all object values exist
			Assert.assertNotNull("Array value [0] of type Long must be not null.", values[0]);
			Assert.assertNotNull("Array value [1] of type Long must be not null.", values[1]);
			Assert.assertNotNull("Array value [2] of type Integer must be not null.", values[2]);
			Assert.assertNotNull("Array value [3] of type Long must be not null.", values[3]);

			// check all types
			Assert.assertTrue("Type of array value [0] " + values[0].getClass().getCanonicalName() + " does not match the desired type Long", values[0] instanceof Long);
			Assert.assertTrue("Type of array value [1] " + values[1].getClass().getCanonicalName() + " does not match the desired type Long", values[1] instanceof Long);
			Assert.assertTrue("Type of array value [2] " + values[2].getClass().getCanonicalName() + " does not match the desired type Integer", values[2] instanceof Integer);
			Assert.assertTrue("Type of array value [3] " + values[3].getClass().getCanonicalName() + " does not match the desired type Long", values[3] instanceof Long);

			// check all object values
			Assert.assertEquals("Array value [0] " + values[0] + " does not match the desired value " + LONG_VALUES.get(i % LONG_VALUES.size()),
				LONG_VALUES.get(i % LONG_VALUES.size()), values[0]
					);
			Assert.assertEquals("Array value [1] " + values[1] + " does not match the desired value " + LONG_VALUES.get(i % LONG_VALUES.size()),
				LONG_VALUES.get(i % LONG_VALUES.size()), values[1]
					);
			Assert.assertEquals("Array value [2] " + values[2] + " does not match the desired value " + INT_VALUES.get(i % INT_VALUES.size()),
				INT_VALUES.get(i % INT_VALUES.size()), values[2]
					);
			Assert.assertEquals("Array value [3] " + values[3] + " does not match the desired value " + LONG_VALUES.get(i % LONG_VALUES.size()),
				LONG_VALUES.get(i % LONG_VALUES.size()), values[3]
					);
		}
	}

	/**
	 * Tests {@link JoinEvent#TestJoinEvent(String, String, long, long, long, String, int, int)}.
	 */
	@Test
	public void testBuffer() { // NOPMD (assert missing)
		for (int i=0;i<ARRAY_LENGTH;i++) {
			// initialize
			JoinEvent record = new JoinEvent(LONG_VALUES.get(i % LONG_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()), INT_VALUES.get(i % INT_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()));

			// check values
			Assert.assertEquals("JoinEvent.timestamp values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTimestamp());
			Assert.assertEquals("JoinEvent.traceId values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTraceId());
			Assert.assertEquals("JoinEvent.orderIndex values are not equal.", (int) INT_VALUES.get(i % INT_VALUES.size()), record.getOrderIndex());
			Assert.assertEquals("JoinEvent.joinedTraceId values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getJoinedTraceId());
		}
	}

	/**
	 * Tests {@link JoinEvent#TestJoinEvent(String, String, long, long, long, String, int, int)}.
	 */
	@Test
	public void testParameterConstruction() { // NOPMD (assert missing)
		for (int i=0;i<ARRAY_LENGTH;i++) {
			// initialize
			JoinEvent record = new JoinEvent(LONG_VALUES.get(i % LONG_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()), INT_VALUES.get(i % INT_VALUES.size()), LONG_VALUES.get(i % LONG_VALUES.size()));

			// check values
			Assert.assertEquals("JoinEvent.timestamp values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTimestamp());
			Assert.assertEquals("JoinEvent.traceId values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getTraceId());
			Assert.assertEquals("JoinEvent.orderIndex values are not equal.", (int) INT_VALUES.get(i % INT_VALUES.size()), record.getOrderIndex());
			Assert.assertEquals("JoinEvent.joinedTraceId values are not equal.", (long) LONG_VALUES.get(i % LONG_VALUES.size()), record.getJoinedTraceId());
		}
	}
}


text:
const defaultNodeFs = require('fs');
const {join, dirname} = require('path');
const EventEmitter = require('events');
const async = require('async');

const {CODES, createError, createNotExistError} = require('./errorHelpers');

/**
 * @param {DeviceManager} devicesManager  DeviceManager instance
 * @param {function}      isFileReady     calls with (device, relativePath) to check if read is possible for this file
 * @param {fs}            fs              link to nodejs fs module
 */
class MergedFs extends EventEmitter {
  constructor({devicesManager, isFileReady, fs = defaultNodeFs} = {}) {
    super();

    if (!devicesManager) {
      throw new Error('No "devicesManager" parameter');
    }

    this.devicesManager = devicesManager; // remove dependency on this
    this.isFileReady = isFileReady; // remove dependency on this
    this.fs = fs;
  }

  _getRelativePath(path) {
    return String(path)
      .replace(this.devicesManager.getDevicesPath(), '')
      .replace(/^\//, '');
  }

  _resolvePath(path, callback) {
    const relativePath = this._getRelativePath(path);

    let stat;
    async.detectSeries(
      this.devicesManager.getDevices(),
      (dev, done) =>
        this.fs.stat(join(dev, relativePath), (err, devStat) => {
          if (err || (this.isFileReady && !this.isFileReady(dev, relativePath))) {
            return done(null, false);
          }
          stat = devStat;
          return done(null, true);
        }),
      (err, dev) => {
        if (!err && typeof dev === 'undefined') {
          return callback(createNotExistError(`Failed to resolve path "${relativePath}"`));
        }
        callback(err, join(dev, relativePath), stat);
      }
    );
  }

  _resolvePathSync(path) {
    const relativePath = this._getRelativePath(path);

    const resolvedPath = this.devicesManager.getDevices().reduce((acc, dev) => {
      if (acc) {
        return acc;
      }
      const devPath = join(dev, relativePath);
      try {
        this.fs.accessSync(devPath);
        return devPath;
      } catch (e) {
        return null;
      }
    }, null);

    if (!resolvedPath) {
      throw createNotExistError(`Failed to resolve path "${relativePath}"`);
    }

    return resolvedPath;
  }

  _mkdirRecursive(path, mode, callback) {
    if (!callback) {
      callback = mode;
      mode = 0o777;
    }

    this.fs.mkdir(path, mode, (err) => {
      if (err && err.code === CODES.ENOENT) {
        return this._mkdirRecursive(dirname(path), mode, (subErr) => {
          if (subErr) {
            return callback(subErr);
          }
          this._mkdirRecursive(path, mode, callback);
        });
      }

      return callback(err);
    });
  }

  _mkdirRecursiveSync(path, mode) {
    try {
      return this.fs.mkdirSync(path, mode);
    } catch (e) {
      if (e.code === CODES.ENOENT) {
        this._mkdirRecursiveSync(dirname(path), mode);
        return this._mkdirRecursiveSync(path, mode);
      }
      throw e;
    }
  }

  exists(path, callback) {
    return this._resolvePath(path, (err, resolvedPath) => callback(Boolean(resolvedPath)));
  }

  stat(path, callback) {
    return this._resolvePath(path, (err, resolvedPath) => {
      if (err) {
        return callback(err);
      }
      this.fs.stat(resolvedPath, callback);
    });
  }

  statSync(path) {
    return this.fs.statSync(this._resolvePathSync(path));
  }

  lstat(path, callback) {
    return this._resolvePath(path, (err, resolvedPath) => {
      if (err) {
        return callback(err);
      }
      this.fs.lstat(resolvedPath, callback);
    });
  }

  mkdir(path, mode, callback) {
    if (!callback) {
      callback = mode;
      mode = 0o777;
    }

    const relativePath = this._getRelativePath(path);

    this._resolvePath(path, (err, resolvedPath) => {
      if (!err) {
        return callback(createError(`Directory already exist: ${resolvedPath}`, CODES.EEXIST));
      }

      this._resolvePath(dirname(path), (parentErr) => {
        if (parentErr) {
          return callback(parentErr);
        }

        this.devicesManager.getDeviceForWrite((devErr, devices) => {
          if (devErr) {
            return callback(devErr);
          }

          //TODO handle multiply devices
          this._mkdirRecursive(join(devices[0], relativePath), mode, (mkdirErr) => {
            if (mkdirErr) {
              return callback(mkdirErr);
            }
            return callback();
          });
        });
      });
    });
  }

  readdir(path, callback) {
    const relativePath = this._getRelativePath(path);

    let isExist = false;
    async.concat(
      this.devicesManager.getDevices().map((d) => join(d, relativePath)),
      (item, done) =>
        this.fs.readdir(item, (err, res) => {
          if (err && err.code === CODES.ENOENT) {
            return done(null, []);
          }
          isExist = true;
          return done(err, res);
        }),
      (err, contents) => {
        if (!isExist) {
          return callback(createNotExistError(`Cannot read directory: "${relativePath}"`));
        }
        return callback(err, [...new Set(contents)]);
      }
    );
  }

  rename(oldPath, newPath, callback) {
    async.waterfall(
      [
        (done) => this._resolvePath(oldPath, (oldPathErr) => done(oldPathErr)),
        (done) =>
          this._resolvePath(newPath, (newPathErr, newResolverPath, newStat) => {
            if (!newPathErr && newStat.isDirectory()) {
              // path exists
              return done(createError('Rename destination already exist', CODES.ENOTEMPTY));
            }
            return done();
          }),
        (done) => process.nextTick(() => done(null, this._getRelativePath(oldPath), this._getRelativePath(newPath))),
        (oldRelativePath, newRelativePath, done) => {
          let isRenamed = false;
          async.each(
            this.devicesManager.getDevices(),
            (dev, eachRenameDone) =>
              this.fs.rename(join(dev, oldRelativePath), join(dev, newRelativePath), (renameErr) => {
                if (renameErr && renameErr.code === CODES.ENOENT) {
                  return eachRenameDone(null);
                }
                if (!renameErr) {
                  isRenamed = true;
                }
                return eachRenameDone(renameErr);
              }),
            (renameErr) => {
              if (!isRenamed) {
                return done(createNotExistError(`Cannot rename path: "${oldRelativePath}" -> "${newRelativePath}"`));
              }
              return done(renameErr);
            }
          );
        }
      ],
      (err) => callback(err)
    );
  }

  rmdir(path, callback) {
    const relativePath = this._getRelativePath(path);

    let isExist = false;
    async.each(
      this.devicesManager.getDevices().map((d) => join(d, relativePath)),
      (item, done) =>
        this.fs.rmdir(item, (err) => {
          if (err && err.code === CODES.ENOENT) {
            return done(null);
          }
          isExist = true;
          return done(err);
        }),
      (err) => {
        if (!isExist) {
          return callback(createNotExistError(`Cannot read directory: "${relativePath}"`));
        }
        return callback(err);
      }
    );
  }

  readFile(path, options, callback) {
    if (!callback) {
      callback = options;
      options = {};
    }

    const relativePath = this._getRelativePath(path);

    async.tryEach(
      this.devicesManager.getDevices().map((dev) => (done) => this.fs.readFile(join(dev, relativePath), options, done)),
      callback
    );
  }

  unlink(path, callback) {
    const relativePath = this._getRelativePath(path);

    let isExist = false;
    async.each(
      this.devicesManager.getDevices().map((dev) => join(dev, relativePath)),
      (item, done) =>
        this.fs.unlink(item, (err) => {
          if (err && err.code === CODES.ENOENT) {
            return done(null);
          }
          isExist = true;
          return done(err);
        }),
      (err) => {
        if (!isExist) {
          return callback(createNotExistError(`Cannot remove file: "${relativePath}"`));
        }
        return callback(err);
      }
    );
  }

  writeFile(path, data, options, callback) {
    if (!callback) {
      callback = options;
      options = {};
    }

    const relativePath = this._getRelativePath(path);

    async.waterfall(
      [
        (done) =>
          this.stat(path, (err) => {
            if (!err) {
              return done(createError(`Cannot write file: File already exist: ${relativePath}`, CODES.EEXIST));
            }
            return done(null);
          }),
        (done) =>
          this.stat(dirname(path), (dirErr, dirStat) => {
            if (dirErr) {
              return done(dirErr);
            } else if (!dirStat.isDirectory()) {
              return done(
                createError(
                  `Cannot write file: Failed to resolve path "${relativePath}": path contains a file in the middle`,
                  CODES.EISFILE
                )
              );
            } else {
              return done(null);
            }
          }),
        (done) => this.devicesManager.getDeviceForWrite(done), //TODO rename, add s
        (devices, done) => done(null, devices[0]),
        (device, done) => done(null, device, join(device, relativePath)),
        (device, resolvedDevicePath, done) =>
          this._mkdirRecursive(dirname(resolvedDevicePath), (err) => {
            // device may already has this directory created
            if (err && err.code !== CODES.EEXIST) {
              return done(err);
            } else {
              return done(null, device, resolvedDevicePath);
            }
          }),
        (device, resolvedDevicePath, done) =>
          this.fs.writeFile(resolvedDevicePath, data, options, (err) => {
            process.nextTick(() => this.emit(MergedFs.EVENTS.FILE_UPDATED, device, relativePath));
            return done(err);
          })
      ],
      callback
    );
  }

  //UNSTABLE (NOT IMPLEMENTED PROPERLY)
  createReadStream(path, options) {
    let resolvedPath;

    try {
      if (!path) {
        throw new Error('path is empty');
      }

      resolvedPath = this._resolvePathSync(path);
      return this.fs.createReadStream(resolvedPath, options);
    } catch (e) {
      throw createNotExistError(`Failed to create read stream for "${resolvedPath || path}": ${e}`);
    }
  }

  //UNSTABLE (NOT IMPLEMENTED PROPERLY)
  createWriteStream(path, options) {
    const relativePath = this._getRelativePath(path);
    const device = this.devicesManager.getDeviceForWriteSync()[0];
    const resolvedPath = join(device, relativePath);

    if (!path) {
      throw createNotExistError(`Cannot create write stream, path is empty: ${path}`);
    }

    let stat;
    try {
      stat = this.statSync(path);
    } catch (e) {
      // file doesn't exist
    }

    if (stat) {
      throw createError(`File already exist: ${relativePath}`, CODES.EEXIST);
    }

    const dirStat = this.statSync(dirname(path));
    if (!dirStat.isDirectory()) {
      throw createError(`Failed to resolve path "${relativePath}": path contains a file in the middle`, CODES.EISFILE);
    }

    try {
      this._mkdirRecursiveSync(dirname(resolvedPath));
    } catch (e) {
      if (e.code !== CODES.EEXIST) {
        // device may already has this directory created
        throw e;
      }
    }

    const resolvedFileWriteStream = this.fs.createWriteStream(resolvedPath, options);

    resolvedFileWriteStream.on('finish', () => this.emit(MergedFs.EVENTS.FILE_UPDATED, device, relativePath));

    return resolvedFileWriteStream;
  }

  //TODO
  //open()
}

MergedFs.EVENTS = {
  FILE_UPDATED: 'fileUpdated'
};

module.exports = MergedFs;

redpajama_set_name: RedPajamaGithub


text:
from collections import deque

from ..apib_extra_parse_utils import parse_property_member_declaration
from ..apib_extra_parse_utils import get_indentation

def parser_json_data_structures(json_content):
    """Retrieves data structures definition from JSON file and writes them in an easier to access format"""

    if len(json_content['content']) > 0:
        json_content['data_structures'] = parse_defined_data_structures(json_content['content'][0])
    else:
        json_content['data_structures'] = {}

    # Add resource level defined data structures
    structures_from_resources = get_data_structures_from_resources(json_content)
    json_content['data_structures'].update(structures_from_resources)

def get_data_structures_from_resources(json_content):
    """Retrieve data structures defined in named resources.

    Arguments:
    json_content -- JSON object where resources will be analysed
    """

    data_structures = {}

    for resource_group in json_content["resourceGroups"]:
        for resource in resource_group["resources"]:

            if resource["name"] == "": continue

            for content in resource["content"]:
                if content["element"] == "dataStructure":
                    # Retrieve it if it is not a link to another data structure
                    if content["typeDefinition"]["typeSpecification"]["name"] == 'object':
                        attributes = get_data_structure_properties_from_json(content["sections"])
                        data_structures[resource["name"]] = {"attributes": attributes, "is_common_payload": False}

    return data_structures

def get_data_structure_properties_from_json(data_structure_content):
    """Extract simpler representation of properties from drafter JSON representation.

    Arguments:
    data_structure_content -- JSON content section of "dataStructures" element or nested property
    """
    attributes = []

    for membertype in data_structure_content:
        if "content" not in membertype: return attributes

        for property_ in membertype["content"]:
            attribute = {}

            attribute['name'] = property_['content']['name']['literal']
            attribute['required'] = 'required' in property_['content']['valueDefinition']['typeDefinition']['attributes']
            attribute['type'] = \
                property_['content']['valueDefinition']['typeDefinition']['typeSpecification']['name']
            attribute['description'] = property_['content']['description']
            try:
                values_string = property_['content']['valueDefinition']['values'][0]['literal']
                attribute['values'] = [e.strip(" ") for e in values_string.split(',')]
            except IndexError as error:
                attribute['values'] = []
            attribute['subproperties'] = get_data_structure_properties_from_json(property_['content']["sections"])

            attributes.append(attribute)

    return attributes

def parse_defined_data_structures(data):
  """Retrieves data structures definition from JSON fragment and gives them back as Python dict"""
  data_structure_dict = {}

  try:
    if data["content"][0]["sections"][0]["class"] != u'blockDescription':
        raise ValueError('Unexpected section received.')
  except:
    return data_structure_dict

  for content in data["content"]:
    data_structure = {}
    data_structure_definition = []

    if content["sections"]!=[]:
      data_structure_content = content["sections"][0]["content"]
      parse_defined_data_structure_properties(data_structure_definition, deque(data_structure_content.split('\n')))

    data_structure_name = content["name"]["literal"]
    data_structure["attributes"] = data_structure_definition
    data_structure["is_common_payload"] = True
    data_structure_dict[data_structure_name] = data_structure

  return data_structure_dict

def parse_defined_data_structure_properties(properties_list, remaining_property_lines):
    """Parses the properties definitions of a given data structure given its body

    Arguments:
    properties_list - List where we'll insert new properties to
    remaining_property_lines - Property definition lines pending to be processed
    """
    last_member_indentation = -1

    while len(remaining_property_lines) > 0:
        property_member_declaration = remaining_property_lines[0]
        if property_member_declaration != '':
            # Retrieve the indentation of the current property definition.
            current_member_indentation = get_indentation(property_member_declaration)
            if last_member_indentation == -1:
                last_member_indentation = current_member_indentation

            # Process the new property as a child, parent or uncle of the last
            # one processed according to their relative line indentations.
            if current_member_indentation == last_member_indentation:
                parsed_attribute_definition = parse_property_member_declaration(property_member_declaration)
                remaining_property_lines.popleft()
                properties_list.append(parsed_attribute_definition)
            elif current_member_indentation > last_member_indentation:
                parse_defined_data_structure_properties(parsed_attribute_definition['subproperties'], remaining_property_lines)
            else:
                return
        else:
            remaining_property_lines.popleft()


text:
import { createVNode, Inferno, InfernoMouseEvent, linkEvent, VNode } from 'inferno';
import { ChildFlags, VNodeFlags } from 'inferno-vnode-flags';
import { invariant } from './utils';
import { combineFrom, isString } from 'inferno-shared';
import type { Location } from 'history';
import { parsePath } from 'history';
import { splitLocation, normalizeToLocation } from "./locationUtils";

const isModifiedEvent = (event: InfernoMouseEvent<any>): boolean => Boolean(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);

export interface ILinkProps {
  children?: any;
  onClick?: any;
  target?: string;
  className?: string;
  replace?: boolean;
  to?: string | Location;
  innerRef?: any;
}

function handleClick({ props, context }, event: InfernoMouseEvent<any>) {
  if (props.onClick) {
    props.onClick(event);
  }

  if (
    !event.defaultPrevented && // onClick prevented default
    event.button === 0 && // ignore everything but left clicks
    !props.target && // let browser handle "target=_blank" etc.
    !isModifiedEvent(event) // ignore clicks with modifier keys
  ) {
    event.preventDefault();

    const { history } = context.router;
    const { replace = false, to: toPropIn } = props;
    const { to, state } = splitLocation(normalizeToLocation(toPropIn));

    if (replace) {
      history.replace(to, state);
    } else {
      history.push(to, state);
    }
  }
}

/**
 * The public API for rendering a history-aware <a>.
 */
export function Link(props: ILinkProps & Inferno.LinkHTMLAttributes<HTMLLinkElement>, context): VNode {
  const { replace, children, className, to = '', innerRef, ...rest } = props;
  invariant(context.router, 'You should not use <Link> outside a <Router>');

  const href = context.router.history.createHref(isString(to) ? parsePath(to) : to);
  const newProps: any = combineFrom(rest, null);

  newProps.href = href;
  newProps.onClick = linkEvent(
    {
      context,
      props
    },
    handleClick
  );

  return createVNode(VNodeFlags.HtmlElement, 'a', className, children, ChildFlags.UnknownChildren, newProps, null, innerRef);
}


text:
<?php

namespace app\assets\plugins;

use yii\web\AssetBundle;
use yii\web\View;
class RespondAsset extends AssetBundle
{
    public $sourcePath = '@vendor/rogeriopradoj/respond';
    public $baseUrl = '@web';
    public $css = [

    ];
    public $js = [
        'dest/respond.min.js',
    ];
    public $jsOptions = [
        'condition' => 'lt IE 9',
        'position' => View::POS_HEAD,
    ];
}


text:
package grpc

import (
	"encoding/binary"
	"fmt"
	"io"
)

var (
	MaxMessageSize = 1024 * 1024 * 4 // 4Mb
	maxInt         = int(^uint(0) >> 1)
)

func decode(r io.Reader) (uint8, []byte, error) {
	header := make([]byte, 5)

	// read the header
	if _, err := r.Read(header[:]); err != nil {
		return uint8(0), nil, err
	}

	// get encoding format e.g compressed
	cf := uint8(header[0])

	// get message length
	length := binary.BigEndian.Uint32(header[1:])

	// no encoding format
	if length == 0 {
		return cf, nil, nil
	}

	//
	if int64(length) > int64(maxInt) {
		return cf, nil, fmt.Errorf("grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt)
	}
	if int(length) > MaxMessageSize {
		return cf, nil, fmt.Errorf("grpc: received message larger than max (%d vs. %d)", length, MaxMessageSize)
	}

	msg := make([]byte, int(length))

	if _, err := r.Read(msg); err != nil {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
		return cf, nil, err
	}

	return cf, msg, nil
}

func encode(cf uint8, buf []byte, w io.Writer) error {
	header := make([]byte, 5)

	// set compression
	header[0] = byte(cf)

	// write length as header
	binary.BigEndian.PutUint32(header[1:], uint32(len(buf)))

	// read the header
	if _, err := w.Write(header[:]); err != nil {
		return err
	}

	// write the buffer
	_, err := w.Write(buf)
	return err
}


text:
class Post
	attr_accessor :id, :title, :body, :created_at
	def initialize
		@id=nil
		@title=""
		@body=""
		@created_at=nil
	end
end


text:
require_relative "spec_helper"
require "brpm_auto"

describe 'Request params' do
  before(:each) do
    cleanup_request_params
  end

  it 'should get a param' do
    input_request_params = {}
    input_request_params["key1"] = "value1"
    set_request_params(input_request_params)

    BrpmAuto.setup(get_default_params)
    request_params = BrpmAuto.request_params

    expect(request_params).to have_key("key1")
    expect(request_params["key1"]).to eql("value1")
  end

  it 'should resolve a tokenized param' do
    input_request_params = {}
    input_request_params["key1"] = "value1"
    input_request_params["tokenized_key"] = "The value is rpm{key1}!"
    set_request_params(input_request_params)

    BrpmAuto.setup(get_default_params)
    request_params = BrpmAuto.request_params

    expect(request_params).to have_key("tokenized_key")
    expect(request_params["tokenized_key"]).to eql("The value is value1!")
  end

  it 'should get a param by the get method' do
    input_request_params = {}
    input_request_params["key1"] = "value1"
    set_request_params(input_request_params)

    BrpmAuto.setup(get_default_params)
    request_params = BrpmAuto.request_params

    expect(request_params).to have_key("key1")
    expect(request_params.get("key1")).to eql("value1")
  end

  it 'should add a param using []=' do
    BrpmAuto.setup(get_default_params)
    request_params = BrpmAuto.request_params

    request_params["key1"] = "value1"

    output_request_params = get_request_params

    expect(output_request_params).to have_key("key1")
    expect(output_request_params["key1"]).to eql("value1")
  end

  it 'should add a param by the add method' do
    BrpmAuto.setup(get_default_params)
    request_params = BrpmAuto.request_params

    request_params.add("key1", "value1")

    output_request_params = get_request_params

    expect(output_request_params).to have_key("key1")
    expect(output_request_params["key1"]).to eql("value1")
  end

  it 'should find or add a param' do
    input_request_params = {}
    input_request_params["key1"] = "value1"
    set_request_params(input_request_params)

    BrpmAuto.setup(get_default_params)
    request_params = BrpmAuto.request_params

    expect(request_params.find_or_add("key1", "value1-bis")).to eql("value1")
    expect(request_params.count).to eql(1)

    expect(request_params.find_or_add("key2", "value2")).to eql("value2")
    expect(request_params.count).to eql(2)
    expect(request_params["key2"]).to eql("value2")
  end
end


text:
package io.warp10.script.functions;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import org.apache.commons.codec.binary.Base64;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TCompactProtocol;

import com.geoxp.GeoXPLib;
import io.warp10.WarpURLEncoder;
import io.warp10.continuum.gts.GTSDecoder;
import io.warp10.continuum.gts.GTSEncoder;
import io.warp10.continuum.gts.GTSWrapperHelper;
import io.warp10.continuum.gts.GeoTimeSerie;
import io.warp10.continuum.store.thrift.data.GTSWrapper;
import io.warp10.crypto.OrderPreservingBase64;
import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptException;
import io.warp10.script.WarpScriptStack;
import io.warp10.script.WarpScriptStackFunction;

public class TOMVSTRING extends NamedWarpScriptFunction implements WarpScriptStackFunction {
  public TOMVSTRING(String name) {
    super(name);
  }

  @Override
  public Object apply(WarpScriptStack stack) throws WarpScriptException {
    Object top = stack.pop();

    if (!(top instanceof String) && !(top instanceof byte[]) && !(top instanceof GTSEncoder) && !(top instanceof GeoTimeSerie)) {
      throw new WarpScriptException(getName() + " operates on a Geo Time Series™, ENCODER, STRING or byte array.");
    }

    if (top instanceof GTSEncoder) {
      GTSWrapper wrapper = GTSWrapperHelper.fromGTSEncoderToGTSWrapper((GTSEncoder) top, false);
      stack.push(wrapperToString(null, wrapper).toString());
    } else if (top instanceof GeoTimeSerie) {
      GTSWrapper wrapper = GTSWrapperHelper.fromGTSToGTSWrapper((GeoTimeSerie) top, false);
      stack.push(wrapperToString(null, wrapper).toString());
    } else {
      byte[] bytes = (top instanceof byte[]) ? (byte[]) top: OrderPreservingBase64.decode(top.toString().getBytes(StandardCharsets.US_ASCII));

      StringBuilder sb = bytesToString(null, bytes);

      stack.push(sb.toString());
    }

    return stack;
  }

  private static StringBuilder wrapperToString(StringBuilder sb, GTSWrapper wrapper) {
    if (null == sb) {
      sb = new StringBuilder();
    }

    if (wrapper.isCompressed()) {
      sb.append("[ ");
    } else {
      sb.append("[! ");
    }

    GTSDecoder decoder = GTSWrapperHelper.fromGTSWrapperToGTSDecoder(wrapper);

    while(decoder.next()) {
      long ts = decoder.getTimestamp();
      long location = decoder.getLocation();
      long elevation = decoder.getElevation();
      Object value = decoder.getBinaryValue();

      double[] latlon = null;

      if (GeoTimeSerie.NO_LOCATION != location) {
        latlon = GeoXPLib.fromGeoXPPoint(location);
      }

      // If the timestamp is not 0 or there is a location or an elevation, we need to
      // emit the timestamp
      if (ts != 0 || null != latlon || GeoTimeSerie.NO_ELEVATION != elevation) {
        sb.append(ts);
        sb.append("/");
      }

      if (null != latlon) {
        sb.append(latlon[0]);
        sb.append(":");
        sb.append(latlon[1]);
        sb.append("/");
      } else if (GeoTimeSerie.NO_ELEVATION != elevation) {
        sb.append("/");
      }

      if (GeoTimeSerie.NO_ELEVATION != elevation) {
        sb.append(elevation);
        sb.append("/");
      }

      if (value instanceof byte[]) {
        bytesToString(sb, (byte[]) value);
      } else if (value instanceof String) {
        sb.append("'");
        try {
          sb.append(WarpURLEncoder.encode(value.toString(), StandardCharsets.UTF_8));
        } catch (UnsupportedEncodingException uee) {
        }
        sb.append("'");
      } else if (value instanceof Boolean) {
        if (Boolean.TRUE.equals(value)) {
          sb.append("T");
        } else {
          sb.append("F");
        }
      } else { // Numbers
        sb.append(value.toString());
      }
      sb.append(" ");
    }

    sb.append("]");

    return sb;
  }

  private static StringBuilder bytesToString(StringBuilder sb, byte[] bytes) {
    TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory());
    GTSWrapper wrapper = new GTSWrapper();

    try {
      deser.deserialize(wrapper, bytes);

      return wrapperToString(sb, wrapper);
    } catch (TException te) {
      if (null == sb) {
        sb = new StringBuilder();
      }
      sb.append("b64:");
      sb.append(Base64.encodeBase64URLSafeString(bytes));
      return sb;
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$USER_HOME$/Dropbox/Work/Home website/Website/.idea/Website.iml" filepath="$USER_HOME$/Dropbox/Work/Home website/Website/.idea/Website.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/vk-giphy.iml" filepath="$PROJECT_DIR$/.idea/vk-giphy.iml" />
    </modules>
  </component>
</project>


text:
<ui-view>

Upload/Select Files

Set Options/Preview

Add to Cart

{{product.Name || product.ID}}

For best results, upload a high-resolution file.

<button type="button" class="btn btn-primary" ng-click="documents.uploadDocument()">Upload from your computer</button>

                            <ordercloud-file-upload model="documents.newDocument" keyname="document" label="Document" extensions="pdf, doc, docx, ppt, pptx" invalid-extension="x"></ordercloud-file-upload>

</ui-view>


text:
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
// Copyright (c) 2010, Nathan Brown
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

namespace FluentMigrator.Runner.Generators
{
    using System.Data;
    using FluentMigrator.Runner.Generators.Base;

    internal class SqlServerCeTypeMap : TypeMapBase
    {
        public const int AnsiStringCapacity = 8000;
        public const int AnsiTextCapacity = 2147483647;
        public const int UnicodeStringCapacity = 4000;
        public const int UnicodeTextCapacity = 1073741823;
        public const int ImageCapacity = 2147483647;
        public const int DecimalCapacity = 19;

        protected override void SetupTypeMaps()
        {
            SetTypeMap(DbType.AnsiStringFixedLength, "CHAR(255)");
            SetTypeMap(DbType.AnsiStringFixedLength, "CHAR($size)", AnsiStringCapacity);
            SetTypeMap(DbType.AnsiString, "VARCHAR(255)");
            SetTypeMap(DbType.AnsiString, "VARCHAR($size)", AnsiStringCapacity);
            SetTypeMap(DbType.AnsiString, "TEXT", AnsiTextCapacity);
            SetTypeMap(DbType.Binary, "VARBINARY(8000)");
            SetTypeMap(DbType.Binary, "VARBINARY($size)", AnsiStringCapacity);
            SetTypeMap(DbType.Binary, "VARBINARY(MAX)", int.MaxValue);
            SetTypeMap(DbType.Binary, "IMAGE", ImageCapacity);
            SetTypeMap(DbType.Boolean, "BIT");
            SetTypeMap(DbType.Byte, "TINYINT");
            SetTypeMap(DbType.Currency, "MONEY");
            SetTypeMap(DbType.Date, "DATETIME");
            SetTypeMap(DbType.DateTime, "DATETIME");
            SetTypeMap(DbType.Decimal, "NUMERIC(19,5)");
            SetTypeMap(DbType.Decimal, "NUMERIC($size,$precision)", DecimalCapacity);
            SetTypeMap(DbType.Double, "DOUBLE PRECISION");
            SetTypeMap(DbType.Guid, "UNIQUEIDENTIFIER");
            SetTypeMap(DbType.Int16, "SMALLINT");
            SetTypeMap(DbType.Int32, "INT");
            SetTypeMap(DbType.Int64, "BIGINT");
            SetTypeMap(DbType.Single, "REAL");
            SetTypeMap(DbType.StringFixedLength, "NCHAR(255)");
            SetTypeMap(DbType.StringFixedLength, "NCHAR($size)", UnicodeStringCapacity);
            SetTypeMap(DbType.String, "NVARCHAR(255)");
            SetTypeMap(DbType.String, "NVARCHAR($size)", UnicodeStringCapacity);
            SetTypeMap(DbType.String, "NTEXT", int.MaxValue);
            SetTypeMap(DbType.String, "NTEXT", UnicodeTextCapacity);
            SetTypeMap(DbType.Time, "NVARCHAR(16)");
            SetTypeMap(DbType.Xml, "NTEXT");
        }
    }
}


text:
using System.Collections.Generic;
using Messageboard.Domain.Models;

namespace Messageboard.Data.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<Messageboard.Data.Database.MessageboardContext>
    {
        public Configuration()
        {
            AutomaticMigrationDataLossAllowed = true;
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(Data.Database.MessageboardContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
            if (context.Topics.Any())
                return;

            var examens = new Topic()
            {
                Title = "Angular JS is aanzienlijk beter dan zelf alles doen met jQuery",
                CreationDate = DateTime.Now.AddMinutes(-40),
                Body = "'t Is nogal een verschil zeg, vroeger moest ik met jQuery selectors en manuele ajax calls die inhoud invullen" +
                       " maar nu kan ik in mijn view veel declaratiever programmeren en zit mijn javascript code ook mooi modulair opgebouwd." +
                       "Ik kan zelfs unit testen schrijven voor mijn javascript code nu!",
                Replies = new List<Reply>()
                {
                    new Reply()
                    {
                        Body = "Awel da's goe gezegd",
                        CreationDate = DateTime.Now.AddMinutes(-38)
                    },
                    new Reply()
                    {
                        Body = "So true!",
                        CreationDate = DateTime.Now.AddMinutes(-33)
                    },
                    new Reply()
                    {
                        Body = "Help ik ben niet goed met computers",
                        CreationDate = DateTime.Now.AddMinutes(-31)
                    }
                }
            };
            var workshop = new Topic()
            {
                Title = "Dit is de beste workshop *ever*",
                CreationDate = DateTime.Now.AddMinutes(-90),
                Body = "Ik ga gegarandeerd een positieve review schrijven over deze geweldige kerel",
                Replies = new List<Reply>()
                {
                    new Reply()
                    {
                        Body = "Ik ga voortaan alles in AngularJs maken!",
                        CreationDate = DateTime.Now.AddMinutes(-70)
                    },
                    new Reply()
                    {
                        Body = "Prikbord applicaties zijn een perfect educatief voorbeeld!",
                        CreationDate = DateTime.Now.AddMinutes(-62)
                    },
                    new Reply()
                    {
                        Body = "Ik roep graag dingen!!!!",
                        CreationDate = DateTime.Now.AddMinutes(-58)
                    },
                }
            };

            context.Topics.Add(examens);
            context.Topics.Add(workshop);
            context.SaveChanges();
        }
    }
}


text:
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);

        view()->composer('*', function ($view)
        {
            $user = request()->user();
            if ($user != NULL) {
                $token = $user->api_token;
                $view->with('user', $user);
            } else {
                $token = false;
            }
            $view->with('token', $token);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


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

namespace Cryptopals
{
  public static class HammingDistanceCalculator
  {
    /// <summary>
    /// Calculates the Hamming distance between two byte arrays
    /// </summary>
    /// <param name="originalText">First text input</param>
    /// <param name="newText">The text to change to</param>
    /// <returns>An integer calculation representing the hamming distance</returns>
    public static float CalculateDistance(byte[] originalText, byte[] newText)
    {
      if (originalText.Length != newText.Length)
        throw new Exceptions.UnequalLengthException();

      int changeCounter = 0;
      for (int i = 0; i < originalText.Length; i++)
      {
        byte XORBytes = (byte)(originalText[i] ^ newText[i]);
        while (true)
        {
          // If we finished iterating through the byte
          if (XORBytes == 0x00)
            break;

          // Check if the byte is 1
          if ((XORBytes & 0x01) == 0x01)
            changeCounter++;

          // Shift the byte to count
          XORBytes = (byte)(XORBytes >> 0x01);
        }
      }

      return changeCounter;
    }
  }
}


text:
namespace OpenSim.Region.Framework.Interfaces
{
    public interface INonSharedRegionModule : IRegionModuleBase
    {
    }
}


text:
=================
salt.states.group
=================

.. automodule:: salt.states.group
    :members:


text:
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
            </Pattern>
        </layout>
    </appender>

    <!-- Mute logging for reactivemongo to prevent spamming test output, causing
      "The job exceeded the maximum log length, and has been terminated." on Travis-->
    <logger name="reactivemongo" level="ERROR"/>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>


text:
package com.fasterxml.aalto.util;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Simple read-only iterator that iterators over one specific item, passed
 * in as constructor argument.
 */
public final class SingletonIterator
    implements Iterator<String>
{
    private final String _value;

    private boolean _done = false;

    public SingletonIterator(String value) {
        _value = value;
    }

    @Override
    public boolean hasNext() {
        return !_done;
    }

    @Override
    public String next() {
        if (_done) {
            throw new NoSuchElementException();
        }
        _done = true;
        return _value;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}


text:
$(document).ready(function() {

    /*
     * Since bootstrap and JQuery has their own form validation scheme,
     * their syntax highlighting are not quite compatiable,
     * but Bootstrap visual cues look super-nice! So ...
     * I used source 1's class alteration and code injection script,
     * with source 2's glyphicon span.
     *
     * Source 1 : http://stackoverflow.com/questions/18754020/bootstrap-3-with-jquery-validation-plugin
     * Source 2 : http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_form_horizontal_all&stacked=h
     */

    jQuery.validator.setDefaults({
            highlight: function (element, errorClass, validClass) {
                    // highlight the entire form group, with red
                    $(element).closest('.form-group').removeClass('has-success has-feedback').addClass('has-error has-feedback');

                    //remove the previous glyph
                    $(element).closest('.form-group').find('span').remove();

                    //add the new one
                    $(element).closest('.form-group').append('');

            },
            unhighlight: function (element, errorClass, validClass) {
                    // highlight the entire form group, with green
                    $(element).closest('.form-group').removeClass('has-error has-feedback').addClass('has-success has-feedback');

                    //remove the previous glyph
                    $(element).closest('.form-group').find('span').remove();

                    //add the new one
                    $(element).closest('.form-group').append('');

            }
        });
    $('#frm').validate( {
        rules : {
          x1a : {
            required: true,
            number: true,
            max : 10,
            min : -10
          } ,
          xEnd : {
            required: true,
            number: true,
            max : 10,
            min : -10
          } ,
          yBegin : {
            required: true,
            number: true,
            max : 10,
            min : -10
          } ,
          yEnd : {
            required: true,
            number: true,
            max : 10,
            min : -10
          }
        },

        messages : {
            x1a : {
                required: "It can't be empty. Insert a number.",
                number: "Only digits are allowed. Delete all letters and symbols.",
                max: "Too big. Lower it to 10 or below.",
                min: "Too small. Raise it to -10 or above."
            } ,
            xEnd : {
                required: "It can't be empty. Insert a number.",
                number: "Only digits are allowed. Delete all letters and symbols.",
                max: "Too big. Lower it to 10 or below.",
                min: "Too small. Raise it to -10 or above."
            } ,
            yBegin : {
                required: "It can't be empty. Insert a number.",
                number: "Only digits are allowed. Delete all letters and symbols.",
                max: "Too big. Lower it to 10 or below.",
                min: "Too small. Raise it to -10 or above."
            } ,
            yEnd : {
                required: "It can't be empty. Insert a number.",
                number: "Only digits are allowed. Delete all letters and symbols.",
                max: "Too big. Lower it to 10 or below.",
                min: "Too small. Raise it to -10 or above."
            }
        },

        submitHandler: function(form) {
                        builtATable();
	}
    }); // end $('#frm').validate

}); // end $(document).ready(function()

/* This is the funtion to call when the contents in forms are safe to parse and ready to generate table. */
function builtATable(){

    var inputs = document.getElementById("frm").elements;
    var rmin = parseInt(inputs[0].value);
    var rmax = parseInt(inputs[1].value);
    var cmin = parseInt(inputs[2].value);
    var cmax = parseInt(inputs[3].value);

    var str = "
	"; /* first block has no use, will take it out of sight using CSS */

    /* row multiplicands */
    for (i = cmin; i <= cmax; i++){
        str += "" + i + "	";
    }

    /* end tag */
    str += "
";

    for (i = rmin; i <= rmax; i++){
        /* column multipliers */
        str += "
" + i + "	";

        /* contents */
        for (j = cmin; j <= cmax; j++){
            str += " " + i*j + "	";
        }

        /* end tag */
        str += "
";
    }
    /* update the table (using JQuery this time)*/
    $(mytable).html(str);
}


text:
class Window_MenuCommand < Window_Command
  #--------------------------------------------------------------------------
  # * Initialize Command Selection Position (Class Method)
  #--------------------------------------------------------------------------
  def self.init_command_position
    @@last_command_symbol = nil
  end
  #--------------------------------------------------------------------------
  # * Object Initialization
  #--------------------------------------------------------------------------
  def initialize
    super(0, 0)
    select_last
  end
  #--------------------------------------------------------------------------
  # * Get Window Width
  #--------------------------------------------------------------------------
  def window_width
    return 160
  end
  #--------------------------------------------------------------------------
  # * Get Number of Lines to Show
  #--------------------------------------------------------------------------
  def visible_line_number
    item_max
  end
  #--------------------------------------------------------------------------
  # * Create Command List
  #--------------------------------------------------------------------------
  def make_command_list
    add_main_commands
    add_formation_command
    add_original_commands
    add_save_command
    add_game_end_command
  end
  #--------------------------------------------------------------------------
  # * Add Main Commands to List
  #--------------------------------------------------------------------------
  def add_main_commands
    add_command(Vocab::item,   :item,   main_commands_enabled)
    add_command(Vocab::skill,  :skill,  main_commands_enabled)
    add_command(Vocab::equip,  :equip,  main_commands_enabled)
    add_command(Vocab::status, :status, main_commands_enabled)
  end
  #--------------------------------------------------------------------------
  # * Add Formation to Command List
  #--------------------------------------------------------------------------
  def add_formation_command
    add_command(Vocab::formation, :formation, formation_enabled)
  end
  #--------------------------------------------------------------------------
  # * For Adding Original Commands
  #--------------------------------------------------------------------------
  def add_original_commands
  end
  #--------------------------------------------------------------------------
  # * Add Save to Command List
  #--------------------------------------------------------------------------
  def add_save_command
    add_command(Vocab::save, :save, save_enabled)
  end
  #--------------------------------------------------------------------------
  # * Add Exit Game to Command List
  #--------------------------------------------------------------------------
  def add_game_end_command
    add_command(Vocab::game_end, :game_end)
  end
  #--------------------------------------------------------------------------
  # * Get Activation State of Main Commands
  #--------------------------------------------------------------------------
  def main_commands_enabled
    $game_party.exists
  end
  #--------------------------------------------------------------------------
  # * Get Activation State of Formation
  #--------------------------------------------------------------------------
  def formation_enabled
    $game_party.members.size >= 2 && !$game_system.formation_disabled
  end
  #--------------------------------------------------------------------------
  # * Get Activation State of Save
  #--------------------------------------------------------------------------
  def save_enabled
    !$game_system.save_disabled
  end
  #--------------------------------------------------------------------------
  # * Processing When OK Button Is Pressed
  #--------------------------------------------------------------------------
  def process_ok
    @@last_command_symbol = current_symbol
    super
  end
  #--------------------------------------------------------------------------
  # * Restore Previous Selection Position
  #--------------------------------------------------------------------------
  def select_last
    select_symbol(@@last_command_symbol)
  end
end


text:
<?php
include_once('kml_TimePrimitive.php');

class kml_TimeSptamp extends kml_TimePrimitive {

    var $tagName = 'TimeSptamp';

    var $when;

    /* Constructor */
    function kml_TimeSptamp($when = null) {
        parent::kml_TimePrimitive();
        if ($when !== null) $this->set_when($when);
    }

    /* Assignments */
    function set_when($when) { $this->when = $when; }

    /* Render */
    function render($doc) {
        $X = parent::render($doc);

        if (isset($this->when)) $X->appendChild(XML_create_text_element($doc, 'when', $this->when));

        return $X;
    }
}

/*
$a = new kml_TimeSptamp();
$a->dump(false);
*/


text:
package at.ac.tuwien.dsg.mela.elasticydependencyAnalysis.rBasedAnalysis.engine;

import at.ac.tuwien.dsg.mela.common.elasticityAnalysis.concepts.elasticityDependencies.ElasticityDependencyCoefficient;
import at.ac.tuwien.dsg.mela.common.elasticityAnalysis.concepts.elasticityDependencies.ElasticityDependencyElement;
import at.ac.tuwien.dsg.mela.common.monitoringConcepts.MetricValue;
import at.ac.tuwien.dsg.mela.elasticydependencyAnalysis.rBasedAnalysis.concept.LinearCorrelation;
import at.ac.tuwien.dsg.mela.elasticydependencyAnalysis.rBasedAnalysis.concept.Variable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
//import java.util.Optional;
//import java.util.function.BinaryOperator;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 *
 * @author Daniel Moldovan E-Mail: d.moldovan@dsg.tuwien.ac.at
 */
@Component
public class LinearCorrelationStatisticsComputationEngine {

    static final org.slf4j.Logger log = LoggerFactory.getLogger(LinearCorrelationStatisticsComputationEngine.class);

    /**
     * compute difference between estimated and monitored values, and determine
     * max, min, and average difference as Estimation Error
     *
     * @param correlation modifies the object in place
     * @return the supplied corelation object
     */
    public static LinearCorrelation enrichWithEstimationErrorStatistics(LinearCorrelation correlation) {
        Variable dependent = correlation.getDependent();
        int valuesSize = dependent.getValues().size();
        List<Double> estimationError = new ArrayList<>();
        List<Double> deviation = new ArrayList<>();

        for (int i = 0; i < valuesSize; i++) {
            double computed = dependent.getValues().get(i);
            double estimated = correlation.getIntercept();
            for (LinearCorrelation.Coefficient predictor : correlation.getPredictors()) {
                estimated += predictor.getCoefficient() * predictor.getVariable().getValues().get(i);
            }

            double error = Math.abs(computed - estimated);

            estimationError.add(error);
            deviation.add(Math.pow(error, 2));

        }

        Double maxError = Double.NEGATIVE_INFINITY;
        Double minError = Double.POSITIVE_INFINITY;
        Double sum = 0.0d;
        Double deviationSum = 0.0d;

        for (Double d : estimationError) {
            if (maxError < d) {
                maxError = d;
            }

            if (minError > d) {
                minError = d;
            }

            sum += d;
        }

        for (Double d : deviation) {
            deviationSum += d;
        }

        correlation.setStatistic(LinearCorrelation.ESTIMATION_ERROR_MIN, minError);
        correlation.setStatistic(LinearCorrelation.ESTIMATION_ERROR_MAX, maxError);
        correlation.setStatistic(LinearCorrelation.ESTIMATION_ERROR_AVERAGE, sum / valuesSize);
        correlation.setStatistic(LinearCorrelation.ESTIMATION_ERROR_STD_DEVIATION, Math.sqrt(deviationSum / deviation.size()));

        return correlation;
    }

    public static ElasticityDependencyElement enrichWithEstimationErrorStatistics(ElasticityDependencyElement dependencyElement) {
        List<MetricValue> dependentValues = dependencyElement.getDependentMetricValues();
        int valuesSize = dependentValues.size();
        List<Double> estimationError = new ArrayList<>();
        List<Double> deviation = new ArrayList<>();

        for (int i = 0; i < valuesSize; i++) {
            double computed = Double.parseDouble(dependentValues.get(i).getValueRepresentation());
            double estimated = dependencyElement.getInterceptor();
            for (ElasticityDependencyCoefficient predictor : dependencyElement.getCoefficients()) {
                double predictorVal = Double.parseDouble(predictor.getMetricValues().get(i).getValueRepresentation());
                estimated += predictor.getCoefficient() * predictorVal;
            }

            double error = Math.abs(computed - estimated);

            estimationError.add(error);
            deviation.add(Math.pow(error, 2));

        }

        Double maxError = Double.NEGATIVE_INFINITY;
        Double minError = Double.POSITIVE_INFINITY;
        Double sum = 0.0d;
        Double deviationSum = 0.0d;

        for (Double d : estimationError) {
            if (maxError < d) {
                maxError = d;
            }

            if (minError > d) {
                minError = d;
            }

            sum += d;
        }

        for (Double d : deviation) {
            deviationSum += d;
        }

        dependencyElement.setStatistic(LinearCorrelation.ESTIMATION_ERROR_MIN, minError);
        dependencyElement.setStatistic(LinearCorrelation.ESTIMATION_ERROR_MAX, maxError);
        dependencyElement.setStatistic(LinearCorrelation.ESTIMATION_ERROR_AVERAGE, sum / valuesSize);
        dependencyElement.setStatistic(LinearCorrelation.ESTIMATION_ERROR_STD_DEVIATION, Math.sqrt(deviationSum / deviation.size()));

        return dependencyElement;
    }

    //TODO: check why outliers do not work
    //check what is with lag
    //check why outputing nicely on
}


text:
package org.apache.harmony.luni.internal.locale;
public class Locale_ar_OM extends java.util.ListResourceBundle {
protected Object[][] getContents() {
	Object[][] contents = {
		{"CurrencySymbol","\u0631.\u0639.\u200f",},
		{"IntCurrencySymbol","OMR",},
		{"Currency","\u00a4 #,##0.##;\u00a4 #,##0.##-",},
	};
return contents;
}
}


text:
import os
import re
import pickle
import numpy as np
from flask import request
from os import makedirs
from typing import Dict, List
from os.path import join as path_join
import lexos.helpers.constants as constants
import lexos.helpers.general_functions as general_functions
import lexos.managers.session_manager as session_manager
import lexos.processors.visualize.multicloud_topic as multicloud_topic
from lexos.managers.file_manager import FileManager
from lexos.managers.session_manager import session_folder

def generate_json_for_d3(file_manager: FileManager, merged_set):
    """
    Generates the data formatted nicely for the d3 visualization library.

    Args:
        merged_set: Boolean saying whether to merge all files into one data set
            or, if false, create a list of datasets.

    Returns:
        An object, formatted in the JSON that d3 needs, either a list or a
        dictionary.
    """

    active_files = []
    for l_file in list(file_manager.files.values()):
        if l_file.active:
            active_files.append(l_file)

    if merged_set:  # Create one JSON Object across all the chunks
        minimum_length = int(request.form['minlength']) \
            if 'minlength' in request.form else 0

        master_word_counts = {}
        for l_file in active_files:
            word_counts = l_file.get_word_counts()

            for key in word_counts:
                if len(key) <= minimum_length:
                    continue

                if key in master_word_counts:
                    master_word_counts[key] += word_counts[key]
                else:
                    master_word_counts[key] = word_counts[key]

        if 'maxwords' in request.form:
            # Make sure there is a number in the input form
            check_for_value = request.form['maxwords']
            if check_for_value == "":
                max_num_words = 100
            else:
                max_num_words = int(request.form['maxwords'])
            sorted_word_counts = sorted(
                master_word_counts, key=master_word_counts.__getitem__)
            j = len(sorted_word_counts) - max_num_words
            for i in range(len(sorted_word_counts) - 1, -1, -1):
                if i < j:
                    del master_word_counts[sorted_word_counts[i]]

        return_obj = general_functions.generate_d3_object(
            master_word_counts, object_label="tokens", word_label="name",
            count_label="size")

    else:  # Create a JSON object for each chunk
        return_obj = []
        for l_file in active_files:
            return_obj.append(
                l_file.generate_d3_json_object(
                    word_label="text",
                    count_label="size"))

    # NOTE: Objects in JSON are dictionaries in Python, but Lists are Arrays
    # are Objects as well.
    return return_obj

def generate_mc_json_obj(file_manager: FileManager):
    """
    Generates a JSON object for multicloud when working with a mallet .txt file

    Args:
        malletPath: path to the saved mallet .txt file

    Returns:
        An object, formatted in the JSON that d3 needs, either a list or a
        dictionary.
    """

    content_path = os.path.join(
        session_manager.session_folder(),
        constants.FILE_CONTENTS_FOLDER,
        constants.MALLET_INPUT_FILE_NAME)
    output_path = os.path.join(
        session_manager.session_folder(),
        constants.RESULTS_FOLDER,
        constants.MALLET_OUTPUT_FILE_NAME)
    try:
        makedirs(
            path_join(session_manager.session_folder(),
                      constants.RESULTS_FOLDER))
        # attempt to make the result dir
    except FileExistsError:
        pass  # result dir already exists

    if request.form['analysistype'] == 'userfiles':

        json_obj = generate_json_for_d3(file_manager, merged_set=False)

    else:  # request.form['analysistype'] == 'topicfile'

        topic_string = str(request.files['optuploadname'])
        topic_string = re.search(r"'(.*?)'", topic_string)
        topic_string = topic_string.group(1)

        if topic_string != '':
            request.files['optuploadname'].save(content_path)

        with open(content_path, 'r', encoding='utf-8') as f:
            content = f.read()  # reads content from the upload file
            # Coerce to non UTF-8 files to UTF-8
            encoding = general_functions.get_encoding(content)
            if encoding != 'utf-8':
                content = content.decode(encoding).encode('utf-8')

        if content.startswith('#doc source pos typeindex type topic'):
            # begin converting a Mallet file into the file d3 can understand
            tuples = []
            # Read the output_state file
            with open(content_path, encoding='utf-8') as f:
                # Skip the first three lines
                for _ in range(3):
                    next(f)
                # Create a list of type:topic combinations
                for line in f:
                    # Make sure the number of columns is correct
                    line = re.sub(r'\s+', ' ', line)
                    try:
                        doc, source, pos, type_index, doc_type, topic = \
                            line.rstrip().split(' ')
                        type_topic_combination = doc_type + ':' + topic
                        tuples.append(type_topic_combination)
                    except BaseException:
                        raise Exception(
                            "Your source data cannot be parsed into a regular "
                            "number of columns. Please ensure that there are "
                            "no spaces in your file names or file paths. It; "
                            "may be easiest to open the outpt_state file in a "
                            "spreadsheet using a space as; the delimiter and "
                            "text as the field type. Data should only be "
                            "present in columns; A to F. Please fix any "
                            "misaligned data and run this script again.")

            # Count the number of times each type-topic combo appears
            from collections import defaultdict

            topic_count = defaultdict(int)
            for x in tuples:
                topic_count[x] += 1

            # Populate a topic_counts dict with type: topic:count
            words = []
            topic_counts = {}
            for k, v in topic_count.items():
                doc_type, topic = k.split(':')
                count = int(v)
                tc = topic + ":" + str(count)
                if doc_type in words:
                    topic_counts[doc_type] = topic_counts[doc_type] + " " + tc
                else:
                    topic_counts[doc_type] = tc
                words.append(doc_type)

            # Add a word ID
            out = ""
            i = 0
            for k, v in topic_counts.items():
                out += str(i) + " " + k + " " + v + "\n"
                i += 1

            # Write the output file
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(out)  # Python will convert \n to os.linesep
                # end converting a Mallet file into the file d3 can understand
        else:
            with open(output_path, 'w', encoding='utf-8') as f:
                # if this is the json form,
                # just write that in the output folder
                f.write(content)

        json_obj = multicloud_topic.topic_json_maker(output_path)

    return json_obj

def save_file_manager(file_manager: FileManager):
    """
    Saves the file manager to the hard drive.

    Args:
        file_manager: File manager object to be saved.

    Returns:
        None
    """

    file_manager_path = os.path.join(
        session_folder(),
        constants.FILEMANAGER_FILENAME)
    pickle.dump(file_manager, open(file_manager_path, 'wb'))

def load_file_manager() -> FileManager:
    """
    Loads the file manager for the specific session from the hard drive.

    Args:
        None

    Returns:
        The file manager object for the session.
    """

    file_manager_path = os.path.join(
        session_folder(),
        constants.FILEMANAGER_FILENAME)

    file_manager = pickle.load(open(file_manager_path, 'rb'))

    return file_manager

def xml_handling_options(data: dict = {}):
    file_manager = load_file_manager()
    from lexos.managers import session_manager
    from xml.etree import ElementTree
    tags = []

    for file in file_manager.get_active_files():
        try:
            root = ElementTree.fromstring(file.load_contents())
            iterate = root.getiterator()

            # Remove processing instructions --
            # not necessary to get a list of tags
            # for pi in root.xpath("//processing-instruction()"):
            #     etree.strip_tags(pi.getparent(), pi.tag)
            # Get the list of the tags

            for element in iterate:
                tag = re.sub('{.+}', '', element.tag)
                tags.append(tag)

        except ElementTree.ParseError:
            import bs4
            from bs4 import BeautifulSoup
            soup = BeautifulSoup(file.load_contents(), 'xml')
            for e in soup:
                if isinstance(e, bs4.element.ProcessingInstruction):
                    e.extract()
            [tags.append(tag.name) for tag in soup.find_all()]

    # Get a sorted list of unique tags
    tags = list(set(tags))

    for tag in tags:
        if tag not in session_manager.session['xmlhandlingoptions']:
            session_manager.session['xmlhandlingoptions'][tag] = {
                "action": 'Remove Tag', "attribute": ''}

    # If they have saved, data is passed.
    # This block updates any previous entries in the dict that have been saved
    if data:
        for key in list(data.keys()):
            if key in tags:
                data_values = data[key].split(',')
                session_manager.session['xmlhandlingoptions'][key] = {
                    "action": data_values[0],
                    "attribute": data["attributeValue" + key]}
                session_manager.session.modified = True

    for key in list(session_manager.session['xmlhandlingoptions'].keys()):

        # makes sure that all current tags are in the active docs
        if key not in tags:
            del session_manager.session['xmlhandlingoptions'][key]
            session_manager.session.modified = True

def simple_vectorizer(content: str, token_type: str, token_size: int):
    """
    Creates a DTM from tokenization settings stored in the session.

    Args:
        A string generated from the document(s) to be vectorized

    Returns:
        A DTM array and a vocab term list array produced by CountVectorizer().
    """
    from sklearn.feature_extraction.text import CountVectorizer
    vectorizer = CountVectorizer(
        input=u'content',
        analyzer=token_type,
        ngram_range=(
            token_size,
            token_size),
        token_pattern=r"(?u)\b\w+\b")
    dtm = vectorizer.fit_transform(content)  # a sparse matrix
    vocab = vectorizer.get_feature_names()  # a list
    dtm = dtm.toarray()  # convert to a regular array
    vocab = np.array(vocab)
    return dtm, vocab

def get_active_document_label_map() -> Dict:
    """
    Get a map of the ids and labels of the active documents.

    :return: A map of the ids and labels of the active documents.
    """
    return {file.id: file.label for file in
            load_file_manager().get_active_files()}

def get_active_document_labels() -> List:
    """
    Get the labels of the active documents.

    :return: The labels of the active documents.
    """
    return [file.label for file in
            load_file_manager().get_active_files()]


text:
var paint = new Painting();
paint.url = imgUrl;
paint.thumbUrl = thumb;
paint.setResize = resize;
paint.originalWidth = 510;
paint.zoomWidth = 240;
paint.paint();


text:
//
//  GinContactsBook.m
//  FrameworkDemo
//
//  Created by JunhuaShao on 15/11/20.
//  Copyright © 2015年 JunhuaShao. All rights reserved.
//

#import "GinContactsBook.h"
#import "UIAlertController+GinUnit.h"
/**
    CNAuthorizationStatus枚举值
    NotDetermined: 这个状态表示用户现在为止还没有允许或者拒绝对联系人数据库的访问。应用在设备上第一次安装时就会是这个状态。
    Restricted: 这个状态表示应用不仅不能访问联系人数据,而且用户也没有权限在Settings里修改这个权限。这个状态可能是其他活跃的限制条件的结果(例如. Parental control)
    Denied: 当应用是这个状态时,表示用户已经选择了不允许访问联系人数据信息。而这个只能被用户本人改变。
    Authorized: 这是每个应用的理想状态。当应用是这个状态时,它可以自由访问联系人数据库并且实现需要联系人数据的任务。
 */

@interface GinContactsBook() <CNContactPickerDelegate>

@property (strong, nonatomic) CNContactPickerViewController *pickerViewController;

@property (strong, nonatomic) CNContactStore *contactStore;
@end

@implementation GinContactsBook

+ (instancetype)sharedInstance
{
    static GinContactsBook *share;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        share = [[GinContactsBook alloc] init];
    });
    return share;
}

+ (void)showInController:(UIViewController *)controller isNeedCheckPhoneFormat:(BOOL)isNeedCheckPhoneFormat handlerBlock:(void(^)(NSDictionary *data))resultHandlerBlock
{
    GinContactsBook *instance = [GinContactsBook sharedInstance];

    [instance requestForAccess:^(BOOL accessGranted) {

        if (accessGranted) {
            instance.pickerViewController.displayedPropertyKeys = self.defualtKeys;
            [controller presentViewController:instance.pickerViewController animated:YES completion:^{
                ;
            }];
        }
    }];
}

+ (void)showInController:(UIViewController *)controller predicate:(NSPredicate *)predicate isNeedCheckPhoneFormat:(BOOL)isNeedCheckPhoneFormat handlerBlock:(void(^)(NSDictionary *data))resultHandlerBlock
{
    GinContactsBook *instance = [GinContactsBook sharedInstance];

    [instance requestForAccess:^(BOOL accessGranted) {

        if (accessGranted) {
            instance.pickerViewController.displayedPropertyKeys = self.defualtKeys;
            [controller presentViewController:instance.pickerViewController animated:YES completion:^{
                ;
            }];
        }
    }];
}

+ (void)queryContactsByMatchingName:(NSString *)name completionHandler:(void(^)(NSArray *contacts))completionHandler
{

    [self queryContactsByMatchingName:name infoKeys:[self defualtKeys] completionHandler:completionHandler];
}

+ (void)queryContactsByMatchingName:(NSString *)name infoKeys:(NSArray *)infoKeys completionHandler:(void(^)(NSArray *contacts))completionHandler
{

    GinContactsBook *instance = [GinContactsBook sharedInstance];

    [instance requestForAccess:^(BOOL accessGranted) {
        if (accessGranted) {

            NSPredicate *predicate = [CNContact predicateForContactsMatchingName:name];

            NSError *__autoreleasing error = nil;
            NSArray *contacts = [instance.contactStore unifiedContactsMatchingPredicate:predicate keysToFetch:infoKeys error:&error];
            if (error) {
                NSLog(@"query contacts by matching name failed--->%@",error);
            }
            completionHandler(contacts);
        } else {
            completionHandler(nil);
        }
    }];
}

- (void)requestForAccess:(void(^)(BOOL accessGranted))completionHandler
{
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];

    switch (status) {
        case CNAuthorizationStatusAuthorized:
            completionHandler(YES);
            break;
        case CNAuthorizationStatusDenied:
        case CNAuthorizationStatusNotDetermined:
        {
            [self.contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    completionHandler(granted);
                } else{
                    if (status == CNAuthorizationStatusDenied) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [UIAlertController alert:@"提示" message:@"请在设置允许APP读取您的联系人列表" cancelTitle:@"确认" cancelBlock:nil completionBlock:nil];
                        });
                    }
                }
            }];
        }
        break;

        default:
            completionHandler(NO);
            break;
    }
}

- (BOOL)checkCurrentContact:(CNContact *)currentContact infoKeys:(NSArray *)infoKeys
{
    __block BOOL flag = YES;

    [infoKeys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        if (![currentContact isKeyAvailable:obj]) {
            *stop = YES;
            flag = NO;
        }
    }];

    return flag;
}

- (CNContact *)refetchContact:(CNContact *)contact store:(CNContactStore *)store keys:(NSArray *)keys
{
    NSError *__autoreleasing error;

    contact = [store unifiedContactWithIdentifier:contact.identifier keysToFetch:keys error:&error];

    if (error) {
        NSLog(@"refetch contact error-->%@",error);
    }

    return contact;
}

+ (NSArray *)defualtKeys
{
    return @[[CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName],CNContactEmailAddressesKey,CNContactBirthdayKey,CNContactImageDataKey];

}

/**
 *  Demo
 */
+ (void)customQueryContacts
{

//    GinContactsBook *instance = [self sharedInstance];
//
//    NSError *__autoreleasing error;
//
//    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:nil];
//
//    request.keysToFetch = [self defualtKeys];
//
//    [instance.contactStore enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
//
//        if (contact.birthday != nil) {
//        }
//    }];
//
//    if (error) {
//        NSLog(@"refetch contact error-->%@",error);
//    }
}

- (CNContactPickerViewController *)pickerViewController
{
    if (!_pickerViewController) {
        _pickerViewController = [[CNContactPickerViewController alloc] init];
        _pickerViewController.delegate = self;
    }
    return _pickerViewController;
}

- (CNContactStore *)contactStore
{
    if (!_contactStore) {
        _contactStore = [[CNContactStore alloc] init];
    }
    return _contactStore;
}

#pragma mark- delegate

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact
{

    NSLog(@"--->%@",contact);

    if (self.resultHandlerBlock) {
        self.resultHandlerBlock(@{});
    }

}

//- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperties:(NSArray<CNContactProperty *> *)contactProperties
//{
//
//}

@end

@implementation CNContact (GinContactsBook)

- (NSString *)fullName:(CNContact *)contact
{
    return [CNContactFormatter stringFromContact:contact style:CNContactFormatterStyleFullName];
}

@end


text:
""" Algorithms, using only one class for classification

Though this focuses on one class, the relation to the ``REST`` should still
be specified.
"""
from pySPACE.missions.nodes.classification.base import RegularizedClassifierBase
import logging

# import the external libraries
from pySPACE.missions.nodes.classification.svm_variants.external import LibSVMClassifierNode

try: # Libsvm
    import svmutil
except ImportError:
    pass

class OneClassClassifierBase(RegularizedClassifierBase):
    """ Base node to handle class labels during training to filter out irrelevant data

    :class_labels:
            List of the two or more classes,
            where first element is the relevant one
            and the second is the negative class.
    """
    def train(self, data, label):
        """ Special mapping for one-class classification

        Reduce training data to the one main class.
        """
        #one vs. REST case
        if "REST" in self.classes and not label in self.classes:
            label = "REST"
        # one vs. one case
        if not self.multinomial and len(self.classes)==2 and not label in self.classes:
            return

        if len(self.classes)==0:
            self.classes.append(label)
            self._log("No positive class label given in: %s. Taking now: %s."\
                      %(self.__class__.__name__,label),
                      level=logging.ERROR)
        if not label==self.classes[0]:
            if len(self.classes)==1:
                self.classes.append(label)
                self._log("No negative class label given in: %s. Taking now: %s."\
                          %(self.__class__.__name__,label),
                          level=logging.WARNING)
            return
        super(RegularizedClassifierBase, self).train(data,label)

class LibsvmOneClassNode(LibSVMClassifierNode, OneClassClassifierBase):
    """ Interface to one-class SVM in Libsvm package

    **Parameters**

        Parameters are as specified in
        :class:`~pySPACE.missions.nodes.classification.svm_variants.external.LibSVMClassifierNode`,
        except the ``svm_type``, which is set manually in this node to
        "one-class SVM".

        :class_labels:
            see: :class:`OneClassClassifierBase`

    **Exemplary Call**

    .. code-block:: yaml

        -
            node : LibsvmOneClass
            parameters :
                complexity : 1
                kernel_type : "LINEAR"
                class_labels : ['Target', 'Standard']
                weight : [1,3]
                debug : True
                store : True
                max_iterations : 100
    """
    def __init__(self,**kwargs):
        LibSVMClassifierNode.__init__(self,svm_type="one-class SVM", **kwargs)

    def train(self,data,label):
        OneClassClassifierBase.train(self, data, label)


text:
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Test\Handler;

use PHPUnit\Framework\TestCase;
use Tomaj\NetteApi\Handlers\EchoHandler;

class EchoHandlerTest extends TestCase
{
    public function testResponse()
    {
        $handler = new EchoHandler();
        $this->assertEquals('', $handler->summary());
        $this->assertEquals('', $handler->description());
        $this->assertFalse($handler->deprecated());
        $this->assertEquals([], $handler->tags());

        $result = $handler->handle(['status' => 'error', 'message' => 'Hello']);
        $this->assertEquals(200, $result->getCode());

        $this->assertEquals(['status' => 'error', 'params' => ['status' => 'error', 'message' => 'Hello']], $result->getPayload());
    }
}


text:
<!DOCTYPE html>
<html>
<title>Test that player will jump forwards 10 seconds if double tapped.</title>
<script src="../../resources/gesture-util.js"></script>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="../media-controls.js"></script>
<video controls width=400 src="../content/60_sec_video.webm"></video>
<script>
async_test(t => {
  const video = document.querySelector('video');
  let time = 0;

  let double_tap_gesture;

  video.addEventListener('playing', t.step_func(() => {
    // Double tap on the right side.
    time = Math.round(video.currentTime);
    const coordinates = videoRightEdgeCoordinates(video);
    double_tap_gesture = doubleTapAt(coordinates[0], coordinates[1]);
  }), { once: true });

  video.ontimeupdate = t.step_func(() => {
    // The time should never be 5 seconds as we skipped over it
    assert_not_equals(Math.round(video.currentTime), 5);
  });

  video.addEventListener('seeked', () => {
    // Check the video advanced 10 seconds
    assert_equals(Math.round(video.currentTime), time + 10);
    double_tap_gesture.then(t.step_func_done());
  }, { once: true });

  video.play();
});
</script>
</html>


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">

		<title>Porto - Responsive HTML5 Template 4.9.1</title>

		<meta name="keywords" content="HTML5 Template" />
		<meta name="description" content="Porto - Responsive HTML5 Template">
		<meta name="author" content="okler.net">

		<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon" />
		<link rel="apple-touch-icon" href="img/apple-touch-icon.png">

		<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800%7CShadows+Into+Light" rel="stylesheet" type="text/css">

		<link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.min.css">
		<link rel="stylesheet" href="vendor/font-awesome/css/font-awesome.min.css">
		<link rel="stylesheet" href="vendor/simple-line-icons/css/simple-line-icons.min.css">
		<link rel="stylesheet" href="vendor/owl.carousel/assets/owl.carousel.min.css">
		<link rel="stylesheet" href="vendor/owl.carousel/assets/owl.theme.default.min.css">
		<link rel="stylesheet" href="vendor/magnific-popup/magnific-popup.min.css">

		<link rel="stylesheet" href="css/theme.css">
		<link rel="stylesheet" href="css/theme-elements.css">
		<link rel="stylesheet" href="css/theme-blog.css">
		<link rel="stylesheet" href="css/theme-shop.css">
		<link rel="stylesheet" href="css/theme-animate.css">

		<link rel="stylesheet" href="vendor/rs-plugin/css/settings.css">
		<link rel="stylesheet" href="vendor/rs-plugin/css/layers.css">
		<link rel="stylesheet" href="vendor/rs-plugin/css/navigation.css">

		<link rel="stylesheet" href="css/skins/skin-corporate-6.css">

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

								<form id="searchForm" action="page-search-results.html" method="get">

										<input type="text" class="form-control" name="q" id="q" placeholder="Search..." required>

											<button class="btn btn-default" type="submit"></button>

								</form>

								 (123) 456-789

										<button class="btn header-btn-collapse-nav" data-toggle="collapse" data-target=".header-nav-main">

										</button>

															Home

																	Landing Page

																Classic

Classic - Original

Classic - Color

Classic - Light

Classic - Video

Classic - Video - Light

																Corporate hot

Corporate - Version 1

Corporate - Version 2

Corporate - Version 3

Corporate - Version 4

Corporate - Version 5

Corporate - Version 6

Corporate - Version 7

Corporate - Version 8

Corporate - Hosting

																One Page

One Page Original

															Overview

															Shortcodes

																			Shortcodes 1

Accordions

Toggles

Tabs

Icons

Icon Boxes

Carousels

Modals

Lightboxes

																			Shortcodes 2

Buttons

Labels

Lists

Image Gallery

Image Frames

Testimonials

Blockquotes

Word Rotator

																			Shortcodes 3

Call to Action

Pricing Tables

Tables

Progress Bars

Counters

Sections & Parallax

Tooltips & Popovers

Sticky Elements

																			Shortcodes 4

Headings

Dividers

Animations

Medias

Maps

Arrows

Alerts

Posts

															Features

																Headers

																		Default

Default

Default + Language Dropdown

Default + Big Logo

																		Flat

Flat

Flat + Top Bar

Flat + Colored Top Bar

Flat + Top Bar with Search

Center

Below Slider

Full Video

Narrow

Always Sticky

																		Transparent

Transparent

Transparent - Bottom Border

Semi Transparent

Semi Transparent - Light

Full-Width

																		Navbar

Navbar

Navbar + Extra Info

																		Side Header

Side Header Left

Side Header Right

Side Header Semi Transparent

Sign In / Sign Up

Logged

																Navigations

Default

Stripe

Top Line

Dark Dropdown

Colors

																Footers

Default

Advanced

Simple

Light

Light Narrow

																		Colors

Primary Color

Secondary Color

Tertiary Color

Quaternary Color

Latest Work

Contact Form

																Page Headers

Default

																		Colors

Primary Color

Secondary Color

Tertiary Color

Quaternary Color

Light

Light - Reverse

Custom Background

Parallax

Center

																Admin Extension hot (Not Included)

Forms Basic

Forms Advanced

Forms Wizard

Code Editor

Tables Advanced

Tables Responsive

Tables Editable

Tables Ajax

Charts

																Sliders

Revolution Slider

Nivo Slider

																Layout Options

Boxed

Dark

RTL

																Extra

Typography

Grid System

Page Loading

Lazy Load

															Pages

																About Us

About Us

About Us - Basic

About Me

																Shop

Shop - Full Width

Shop - Sidebar

Shop - Product Full Width

Shop - Product Sidebar

Shop - Cart

Shop - Login

Shop - Checkout

																Blog

Blog Full Width

Blog Large Image

Blog Medium Image

Blog Timeline

Single Post

																Layouts

Full Width

Left Sidebar

Right Sidebar

Left and Right Sidebars

Sticky Sidebar

Secondary Navbar

																Extra

404 Error

Coming Soon

Maintenance Mode

Sitemap

Custom Header

Team

Services

Careers

Our Office

FAQ

Login / Register

															Portfolio

																Single Project

Small Slider

Wide Slider

Full Width Slider

Gallery

Carousel

Medias

Full Width Video

Masonry Images

Left Sidebar

Right Sidebar

Left and Right Sidebars

Sticky Sidebar

Extended

																Grid Layouts

1 Column

2 Columns

3 Columns

4 Columns

5 Columns

6 Columns

No Margins

Full Width

Full Width No Margins

Title and Description

																Masonry Layouts

2 Columns

3 Columns

4 Columns

5 Columns

6 Columns

No Margins

Full Width

																Sidebar Layouts

Left Sidebar

Right Sidebar

Left and Right Sidebars

Sticky Sidebar

																Ajax

Ajax on Page

Ajax on Modal

																Extra

Timeline

Lightbox

Load More

Lazy Load

Pagination

Combination Filters

															Contact Us

Contact Us - Basic

Contact Us - Advanced

DO YOU NEED A NEW

WEB DESIGN?

Check out our options and features.

WELCOME TO PORTO

								<div class="tp-caption bottom-label"
									data-x="center"
									data-y="270"
									data-start="1000"
									data-transform_idle="o:1;"
									data-transform_in="y:[100%];z:0;rZ:-35deg;sX:1;sY:1;skX:0;skY:0;s:600;e:Power4.easeInOut;"
									data-transform_out="opacity:0;s:500;"
									data-mask_in="x:0px;y:0px;s:inherit;e:inherit;"
									data-splitin="chars"
									data-splitout="none"
									data-responsive_offset="on"
									style="font-size: 23px; line-height: 30px;"
									data-elementdelay="0.05">The #1 Selling HTML Site Template on ThemeForest

									The fastest way to grow your business with the leader in Technology
									Check out our options and features included.

									Get Started Now!

or learn more.

Who We Are

Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. Duis sed odio sit amet nibh vulputate cursus a sit amet mauris. Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt auctor a ornare odio. Sed non  mauris vitae erat consequat.

							Read More

Our Services

Customer Support

Lorem ipsum dolor sit amet, consectetur adipiscing metus elit. Quisque rutrum pellentesque imperdiet.

Sliders

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rutrum pellentesque imperdiet. Nulla lacinia iaculis nulla.

HTML5

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rutrum pellentesque imperdiet. Nulla lacinia iaculis nulla.

Icons

Lorem ipsum dolor sit amet, consectetur adipiscing metus elit. Quisque rutrum pellentesque imperdiet.

Colors

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rutrum pellentesque imperdiet. Nulla lacinia iaculis nulla.

Buttons

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rutrum pellentesque imperdiet. Nulla lacinia iaculis nulla.

Lightboxes

Lorem ipsum dolor sit amet, consectetur adipiscing metus elit. Quisque rutrum pellentesque imperdiet.

Shortcodes

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rutrum pellentesque imperdiet. Nulla lacinia iaculis nulla.

Videos

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rutrum pellentesque imperdiet. Nulla lacinia iaculis nulla.

Our Clients

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequatt, in consequat.

John SmithCEO & Founder - Okler

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequatt, in consequat.

John SmithCEO & Founder - Okler

Our Portfolio

Our Blog

											15
											Jan

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat libero.

										Read More

											15
											Jan

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat libero.

										Read More

											15
											Jan

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat libero.

										Read More

							Get in Touch

Newsletter

Keep up on our always evolving product features and technology. Enter your e-mail and subscribe to our newsletter.

									Success! You've been added to our email list.

								<form id="newsletterForm" action="php/newsletter-subscribe.php" method="POST">

										<input class="form-control" placeholder="Email Address" name="newsletterEmail" id="newsletterEmail" type="text">

											<button class="btn btn-default" type="submit">Go!</button>

								</form>

Latest Tweets

Please wait...

Contact Us

 Address: 1234 Street Name, City Name, United States

 Phone: (123) 456-789

 Email: mail@example.com

Follow Us

© Copyright 2016. All Rights Reserved.

FAQ's

Sitemap

Contact


text:
<?php

namespace Shopware\Plugin\Services\Repositories\Standard;

use Shopware\Plugin\Services\Repositories\BaseRepository;

class GitLab extends BaseRepository
{
    /**
     * {@inheritdoc}
     */
    public function getPluginByName($name, $exact = false): array
    {
        $plugins = $this->getPlugins();
        foreach ($plugins as $key => $plugin) {
            if (!$this->doesMatch($plugin->name, $name, $exact)) {
                unset($plugins[$key]);
            }
        }

        return $plugins;
    }

    /**
     * {@inheritdoc}
     */
    public function getPlugins(): array
    {
        echo "Reading Gitlab org {$this->name}\n";

        $content = $this->restService->get($this->repository)->getResult();

        if (isset($content['errors'])) {
            throw new \RuntimeException(
                \sprintf("Gitlab API communication error: '%s'", $content['errors'][0]['message'])
            );
        }

        $plugins = [];
        foreach ($content as $repo) {
            $pluginName = $repo['name'];

            $splitPath = \explode('_', $repo['path']);
            if (\count($splitPath) === 2) {
                $pluginName = \ucfirst($splitPath[0]) . '_' . $pluginName;
            }

            $plugins[] = $this->createPlugin($repo['ssh_url_to_repo'], $repo['http_url_to_repo'], $pluginName);
        }

        return $plugins;
    }
}


text:
public interface ILineStep {
    IProductPart buildProductPart();
}