text:
<!DOCTYPE html>

  <title>About me</title>
  <link rel="stylesheet" type="text/css" href="style.css"/>

  <img src ="https://storage.googleapis.com/idx-acnt-gs.ihouseprd.com/AR527112/file_manager/Placerville.jpg"

About me

I am from Placerville California.

I have been a waiter, maintenace worker, food clerk, a teller at a Credit Union and havce held a few more jobs.

Currently, I am currently Washington trying to get into web development. Also, I'm kind of a big deal and I rock at coding.

In a year I would like to be a front end devoloper.

But, for now I am studying HTML, CSS and JavaScript in a 201 class at CodeFellows in Portland.

Top ten places I would like to visit.

Spain

Texas

Geneva

Germany

Mexico

Arizona

Europe

Puerto Rico

Hawaii

China


text:
class String
  def step_name
    self
  end

  def arg_regexp
    ::Spec::Story::Step::PARAM_OR_GROUP_PATTERN
  end
end

redpajama_set_name: RedPajamaGithub


text:
package fi.nls.oskari.map.userlayer.service;

import com.ibatis.sqlmap.client.SqlMapSession;
import fi.nls.oskari.domain.map.userlayer.UserLayer;
import fi.nls.oskari.domain.map.userlayer.UserLayerData;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.service.db.BaseIbatisService;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserLayerDataDbServiceIbatisImpl extends
        BaseIbatisService<UserLayerData> implements UserLayerDataDbService {

    private static final Logger log = LogFactory.getLogger(UserLayerDataDbServiceIbatisImpl.class);

    @Override
    protected String getNameSpace() {
        return "UserLayerData";
    }

    /*
     * The purpose of this method is to allow many SqlMapConfig.xml files in a
     * single portlet
     */
    protected String getSqlMapLocation() {
        return "META-INF/SqlMapConfig_UserLayer.xml";
    }

    /**
     * insert UserLayerData table row
     *
     * @param userLayer
     */

    public long insertUserLayerDataRow(final UserLayerData userLayer) {

       // log.debug("Insert user layer data row:", userLayer);
        final Long id = queryForObject(getNameSpace() + ".insertUserLayerData", userLayer);
        userLayer.setId(id);

        return id;
    }

    /**
     * update UserLayerData table row field mapping
     *
     * @param userLayer
     */
    public int updateUserLayerDataCols(final UserLayerData userLayer) {

        try {
            return getSqlMapClient().update(
                    getNameSpace() + ".updateUserLayerDataCols", userLayer);
        } catch (SQLException e) {
            log.error(e, "Failed to update userLayer col mapping", userLayer);
        }
        return 0;
    }

}


text:
@class SpeakerPlainObject;

@protocol SpeakerShortInfoViewInput <NSObject>

- (void)configureViewWithDefaultSizeWithSpeaker:(SpeakerPlainObject *)speaker;
- (void)configureViewWithBigSizeWithSpeaker:(SpeakerPlainObject *)speaker;

@end


text:
"""MD5 cryptographic hash algorithm.

MD5 is specified in RFC1321_ and produces the 128 bit digest of a message.

    >>> from Crypto.Hash import MD5
    >>>
    >>> h = MD5.new()
    >>> h.update(b'Hello')
    >>> print h.hexdigest()

MD5 stand for Message Digest version 5, and it was invented by Rivest in 1991.

This algorithm is insecure. Do not use it for new designs.

.. _RFC1321: http://tools.ietf.org/html/rfc1321
"""

_revision__ = "$Id$"

__all__ = ['new', 'digest_size', 'MD5Hash' ]

from Crypto.Util.py3compat import *
from Crypto.Hash.hashalgo import HashAlgo

try:
    # The md5 module is deprecated in Python 2.6, so use hashlib when possible.
    import hashlib
    hashFactory = hashlib.md5

except ImportError:
    from . import md5
    hashFactory = md5

class MD5Hash(HashAlgo):
    """Class that implements an MD5 hash

    :undocumented: block_size
    """

    #: ASN.1 Object identifier (OID)::
    #:
    #:  id-md5      OBJECT IDENTIFIER ::= {
    #:      iso(1) member-body(2) us(840) rsadsi(113549)
    #:       digestAlgorithm(2) 5
    #:  }
    #:
    #: This value uniquely identifies the MD5 algorithm.
    oid = b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05')

    digest_size = 16
    block_size = 64

    def __init__(self, data=None):
        HashAlgo.__init__(self, hashFactory, data)

    def new(self, data=None):
        return MD5Hash(data)

def new(data=None):
    """Return a fresh instance of the hash object.

    :Parameters:
       data : byte string
        The very first chunk of the message to hash.
        It is equivalent to an early call to `MD5Hash.update()`.
        Optional.

    :Return: A `MD5Hash` object
    """
    return MD5Hash().new(data)

#: The size of the resulting hash in bytes.
digest_size = MD5Hash.digest_size

#: The internal block size of the hash algorithm in bytes.
block_size = MD5Hash.block_size


text:
from oscar.app import Shop

from apps.checkout.app import application as checkout_app

class PayPalShop(Shop):
    checkout_app = checkout_app

application = PayPalShop()


text:
<?php

namespace PamiModule\Service;

use ArrayObject;
use PAMI\Client\Impl\ClientImpl;
use PAMI\Message\OutgoingMessage;
use PAMI\Message\Response\ResponseMessage;
use Zend\EventManager\Event;
use Zend\EventManager\EventManagerAwareTrait;
use Zend\EventManager\EventsCapableInterface;

/**
 * Class Client.
 */
class Client implements EventsCapableInterface
{
    use EventManagerAwareTrait;

    /**
     * PAMI client.
     *
     * @var ClientImpl
     */
    protected $connection;
    /**
     * Custom parameters.
     *
     * @var array
     */
    protected $params = [];
    /**
     * @var string
     */
    protected $host;

    /**
     * Client constructor.
     *
     * @param string     $host
     * @param ClientImpl $pami PAMI client
     */
    public function __construct($host, ClientImpl $pami)
    {
        $this->host = $host;
        $this->connection = $pami;
    }

    /**
     * Return the hostname of the connection.
     *
     * @return string
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * Return the PAMI client.
     *
     * @return ClientImpl
     */
    public function getConnection()
    {
        return $this->connection;
    }

    /**
     * Return the custom parameters.
     *
     * @return array
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * Set the custom parameters.
     *
     * @param array $params Parameters
     *
     * @return $this
     */
    public function setParams(array $params)
    {
        $this->params = $params;

        return $this;
    }

    /**
     * Connect to the Asterisk Manager Interface.
     *
     * @throws \PAMI\Client\Exception\ClientException
     *
     * @return $this
     */
    public function connect()
    {
        $results = $this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this);
        if ($results->stopped()) {
            return $this;
        }

        $this->connection->open();

        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this);

        return $this;
    }

    /**
     * Disconnect from the Asterisk Manager Interface.
     *
     * @return $this
     */
    public function disconnect()
    {
        $results = $this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this);
        if ($results->stopped()) {
            return $this;
        }

        $this->connection->close();

        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this);

        return $this;
    }

    /**
     * Main processing loop. Also called from send(), you should call this in
     * your own application in order to continue reading events and responses
     * from ami.
     *
     * @return $this
     */
    public function process()
    {
        $results = $this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this);

        if ($results->stopped()) {
            return $this;
        }

        $this->connection->process();

        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this);

        return $this;
    }

    /**
     * Sends a message to AMI.
     *
     * @param OutgoingMessage $action Action to send
     *
     * @throws \PAMI\Client\Exception\ClientException
     *
     * @return \PAMI\Message\Response\ResponseMessage
     */
    public function sendAction(OutgoingMessage $action)
    {
        $params = new ArrayObject(['action' => $action]);
        $event = new Event(__FUNCTION__ . '.pre', $this, $params);
        $results = $this->getEventManager()->triggerEventUntil(
            function ($response) {
                return $response instanceof ResponseMessage;
            },
            $event
        );
        if ($results->stopped()) {
            return $results->last();
        }

        $response = $this->connection->send($action);

        $params['response'] = $response;
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, $params);

        return $response;
    }
}


text:
var MATH_CONST = require('../../math/const');
var Angle = require('./Angle');

/**
 * [description]
 *
 * @function Phaser.Geom.Line.NormalY
 * @since 3.0.0
 *
 * @param {Phaser.Geom.Line} line - [description]
 *
 * @return {number} [description]
 */
var NormalY = function (line)
{
    return Math.sin(Angle(line) - MATH_CONST.TAU);
};

module.exports = NormalY;


text:
package com.ajah.css;

import lombok.Data;

import com.ajah.util.compare.CompareUtils;

/**
 * Represents a CSS declaration (property/value within a rule).
 *
 * @author Eric F. Savage, code@efsavage.com.
 */
@Data
public class CssDeclaration implements Comparable<CssDeclaration> {

	private final CssRule rule;
	private final CssProperty property;
	private String value;

	/**
	 * Public constructor.
	 *
	 * @param rule
	 * 		The rule this declaration belongs to, required.
	 * @param property
	 * 		The property this declaration represents, required.
	 * @param value
	 * 		The value of the property.
	 */
	public CssDeclaration(final CssRule rule, final CssProperty property, final String value) {
		this.rule = rule;
		this.property = property;
		this.value = value;
		rule.add(this);
	}

	@Override
	public int compareTo(final CssDeclaration other) {
		int retVal = this.property.getName().compareTo(other.getProperty().getName());
		if (retVal == 0) {
			retVal = CompareUtils.compare(this.value, other.getValue());
		}
		return retVal;
	}

	/**
	 * Returns the valid, usable version of this declaration.
	 *
	 * @return The valid, usable version of this document
	 */
	@Override
	public String toString() {
		return toString(true);
	}

	/**
	 * Returns the valid, usable version of this declaration.
	 *
	 * @param semicolon
	 * 		Append a semicolon at the end?
	 * @return The valid, usable version of this document
	 */
	public String toString(final boolean semicolon) {
		return this.property.getName() + ':' + this.value + (semicolon ? ";" : "");
	}

}


text:
const path = require('path');
const webpack = require('webpack')
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const ReactStaticPlugin = require('react-static-webpack-plugin');

var nodeModules = path.resolve(path.join(__dirname, 'node_modules'));
module.exports = {
   entry: [
    'react-hot-loader/patch',
    // activate HMR for React

    'webpack-dev-server/client?http://localhost:8080',
    // bundle the client for webpack-dev-server
    // and connect to the provided endpoint

    'webpack/hot/only-dev-server',
    // bundle the client for hot reloading
    // only- means to only hot reload for successful updates

    './index.jsx'
    // the entry point of our app
  ],
  output: {
    path: path.resolve(__dirname,'static'),
    filename: 'bundle.js',
    publicPath: '/static'
  },
  devtool: 'inline-source-map',

  devServer: {
    hot: true,
    // enable HMR on the server
    contentBase: path.resolve(__dirname,'static'),
    // match the output path
    publicPath: '/static'
    // match the output `publicPath`
  },

  module: {
    loaders: [
      { test: /\.js$/, loader: ['babel-loader'], exclude: /node_modules/ },
      { test: /\.jsx$/, loader: ['babel-loader'], exclude: /node_modules/ },
     // { test: /jquery\.js$/, loader: 'expose', query: {jQuery: true,$: true}},
      { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
      { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
      { test: /\.png$/, loader: "url-loader?limit=100000" },
      { test: /\.jpg$/, loader: "file-loader" },
      { test: /bootstrap\/dist\/js\/umd\//, use: 'imports-loader?jQuery=jquery'},
      { test: /\.scss$/, use: ['raw-loader', 'sass-loader']},
      {
            test: /\.css$/,
            use: 'css-loader'
        }

    ]
  },
  resolve: {
    extensions: [".jsx", ".js"]
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    }),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery",
      Tether: "tether",
      "window.Tether": "tether",
      Tooltip: "exports-loader?Tooltip!bootstrap/js/dist/tooltip",
      Alert: "exports-loader?Alert!bootstrap/js/dist/alert",
      Button: "exports-loader?Button!bootstrap/js/dist/button",
      Carousel: "exports-loader?Carousel!bootstrap/js/dist/carousel",
      Collapse: "exports-loader?Collapse!bootstrap/js/dist/collapse",
      Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
      Modal: "exports-loader?Modal!bootstrap/js/dist/modal",
      Popover: "exports-loader?Popover!bootstrap/js/dist/popover",
      Scrollspy: "exports-loader?Scrollspy!bootstrap/js/dist/scrollspy",
      Tab: "exports-loader?Tab!bootstrap/js/dist/tab",
      Util: "exports-loader?Util!bootstrap/js/dist/util"
    }),
    new webpack.HotModuleReplacementPlugin(),
    // enable HMR globally
    new webpack.NamedModulesPlugin(),
    // prints more readable module names in the browser console on HMR updates
  ],
}


text:
// Copyright (c) 2013 Mark Pearce
// http://opensource.org/licenses/MIT

using System;
using System.Globalization;
using System.Diagnostics;
using System.Text;

namespace PasswordUtilities
{
    /// <summary>
    /// This class lets you encode a password hash and accompanying info for storage.
    /// It also lets you decode a stored password hash and accompanying info.
    /// Finally it lets you verify a password against a stored password hash.
    /// </summary>
    internal sealed class HashStorage
    {
        // Type constants.
        private const string DEFAULT_STORAGE_DELIMITER = ".";
        private const Int32 CORRECT_NUMBER_OF_HASH_SECTIONS = 6;
        private const Int32 SECTION_HASH_ALGORITHM = 1;
        private const Int32 SECTION_STORAGE_FORMAT = 2;
        private const Int32 SECTION_WORK_FACTOR = 3;
        private const Int32 SECTION_ENCODED_SALT = 4;
        private const Int32 SECTION_ENCODED_HASH = 5;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public HashStorage()
        {
        }

        /// <summary>
        /// Algorithm used to generate the hash.
        /// </summary>
        public HashAlgorithm HashMethod { get; private set; }

        /// <summary>
        /// Storage format used to encode the password
        /// hash and its accompanying info.
        /// </summary>
        public StorageFormat HashStorageFormat { get; private set; }

        /// <summary>
        /// Number of hash iterations expressed as 2^WorkFactor.
        /// </summary>
        public Int32 WorkFactor { get; private set; }

        /// <summary>
        /// Password salt as a byte array.
        /// </summary>
        public byte[] PasswordSalt { get; set; }

        /// <summary>
        /// Password hash as a byte array.
        /// </summary>
        public byte[] PasswordHash { get; set; }

        /// <summary>
        /// Password salt encoded using the specified storage format.
        /// </summary>
        public string PasswordSaltEncoded
        {
            get
            {
                string hexSalt;
                switch (this.HashStorageFormat)
                {
                    // Hexadecimal.
                    case StorageFormat.Hexadecimal:
                        hexSalt = BitConverter.ToString(this.PasswordSalt);
                        return hexSalt.Replace("-", "");
                    // Base64.
                    case StorageFormat.Base64:
                        return Convert.ToBase64String(this.PasswordSalt);
                    // Invalid - default to hexadecimal.
                    default:
                        Debug.Assert(false, "Invalid storage format!");
                        hexSalt = BitConverter.ToString(this.PasswordSalt);
                        return hexSalt.Replace("-", "");
                }
            }
        }

        /// <summary>
        /// Password hash encoded using the specified storage format.
        /// </summary>
        public string PasswordHashEncoded
        {
            get
            {
                string hexHash;
                switch (this.HashStorageFormat)
                {
                    // Hexadecimal.
                    case StorageFormat.Hexadecimal:
                        hexHash = BitConverter.ToString(this.PasswordHash);
                        return hexHash.Replace("-", "");
                    // Base64.
                    case StorageFormat.Base64:
                        return Convert.ToBase64String(this.PasswordHash);
                    // Invalid - default to hexadecimal.
                    default:
                        Debug.Assert(false, "Invalid storage format!");
                        hexHash = BitConverter.ToString(this.PasswordHash);
                        return hexHash.Replace("-", "");
                }
            }
        }

        /// <summary>
        /// ASCII string in the format ".AAAA.BBBB.NNNN.XXXX.YYYY"
        /// where . = delimiter character, AAAA = hash algorithm,
        /// BBBB = encoding format, NNNN = work factor,
        /// XXXX = encoded password salt, YYYY = encoded password hash.
        /// </summary>
        public string StoredHash
        {
            get
            {
                return String.Concat(DEFAULT_STORAGE_DELIMITER,
                                     this.HashMethod.ToString(),
                                     DEFAULT_STORAGE_DELIMITER,
                                     this.HashStorageFormat.ToString(),
                                     DEFAULT_STORAGE_DELIMITER,
                                     this.WorkFactor.ToString(CultureInfo.InvariantCulture),
                                     DEFAULT_STORAGE_DELIMITER,
                                     this.PasswordSaltEncoded,
                                     DEFAULT_STORAGE_DELIMITER,
                                     this.PasswordHashEncoded
                                    );
            }
        }

        /// <summary>
        /// Encodes everything needed to store a password hash
        /// so that its associated password can be verified later.
        /// </summary>
        /// <param name="passwordSalt">
        /// The password salt in the form of a Unicode string.
        /// </param>
        /// <param name="passwordHash">
        /// The password hash in the form of a Unicode string.
        /// </param>
        /// <param name="hashPolicy">
        /// The hash policy. This is used to extract the hash
        /// algorithm, the hash work factor, and the hash
        /// storage format.
        /// </param>
        /// <returns>
        /// ASCII string in the format ".AAAA.BBBB.NNNN.XXXX.YYYY"
        /// where . = delimiter character, AAAA = hash algorithm,
        /// BBBB = encoding format, NNNN = work factor,
        /// XXXX = encoded password salt, YYYY = encoded password hash.
        /// </returns>
        public string HashEncode(string passwordSalt, string passwordHash, HashPolicy hashPolicy)
        {
            return this.HashEncode(Encoding.UTF8.GetBytes(passwordSalt), Encoding.UTF8.GetBytes(passwordHash), hashPolicy);
        }

        /// <summary>
        /// Encodes everything needed to store a password hash
        /// so that its associated password can be verified later.
        /// </summary>
        /// <param name="passwordSalt">
        /// The password salt in the form of a byte array.
        /// </param>
        /// <param name="passwordHash">
        /// The password hash in the form of a byte array.
        /// </param>
        /// <param name="hashPolicy">
        /// The hash policy. This is used to extract the hash
        /// algorithm, the hash work factor, and the hash
        /// storage format.
        /// </param>
        /// <returns>
        /// ASCII string in the format ".AAAA.BBBB.NNNN.XXXX.YYYY"
        /// where . = delimiter character, AAAA = hash algorithm,
        /// BBBB = encoding format, NNNN = work factor,
        /// XXXX = encoded password salt, YYYY = encoded password hash.
        /// </returns>
        public string HashEncode(byte[] passwordSalt, byte[] passwordHash, HashPolicy hashPolicy)
        {
            this.PasswordSalt = ValidatePasswordSalt(passwordSalt);
            this.PasswordHash = ValidatePasswordHash(passwordHash);
            this.HashMethod = hashPolicy.HashMethod;
            this.WorkFactor = hashPolicy.WorkFactor;
            this.HashStorageFormat = hashPolicy.HashStorageFormat;
            return this.StoredHash;
        }

        /// <summary>
        /// Decodes a stored hash into its component parts.
        /// </summary>
        /// <param name="storedHash">
        /// ASCII string in the format ".AAAA.BBBB.NNNN.XXXX.YYYY"
        /// where . = delimiter character, AAAA = hash algorithm,
        /// BBBB = encoding format, NNNN = work factor,
        /// XXXX = encoded password salt, YYYY = encoded password hash.
        /// </param>
        /// <returns>
        /// True if the stored hash is valid, or an exception.
        /// explaining why the stored hash is invalid.
        /// </returns>
        public bool HashDecode(string storedHash)
        {
            return this.ValidateEncodedHash(storedHash);
        }

        private bool ValidateEncodedHash(string storedHash)
        {
            // Must not be empty.
            if (String.IsNullOrEmpty(storedHash))
            {
                throw new ArgumentNullException("storedHash", String.Format(CultureInfo.InvariantCulture, "Stored password hash cannot be null or empty"));
            }

            // Must have 5 sections: hash algorithm, encoding format,
            // hash work factor, encoded password salt, encoded password hash.
            char delimiter = Convert.ToChar(storedHash.Substring(0, 1), CultureInfo.InvariantCulture);
            string[] storedSections = storedHash.Split(delimiter);
            if (storedSections.Length != CORRECT_NUMBER_OF_HASH_SECTIONS)
            {
                throw new ArgumentException("storedHash", String.Format(CultureInfo.InvariantCulture, "Stored password hash must have {0} sections", CORRECT_NUMBER_OF_HASH_SECTIONS));
            }

            // Validate and store each of the 5 relevant sections (section zero should be empty).
            this.HashMethod = ValidateHashAlgorithm(storedSections[SECTION_HASH_ALGORITHM]);
            this.HashStorageFormat = ValidateStorageFormat(storedSections[SECTION_STORAGE_FORMAT]);
            this.WorkFactor = ValidateWorkFactor(storedSections[SECTION_WORK_FACTOR]);
            this.PasswordSalt = this.ValidatePasswordSaltEncoded(storedSections[SECTION_ENCODED_SALT]);
            this.PasswordHash = this.ValidatePasswordHashEncoded(storedSections[SECTION_ENCODED_HASH]);
            return true;
        }

        private static HashAlgorithm ValidateHashAlgorithm(string hashAlgorithm)
        {
            if (String.IsNullOrEmpty(hashAlgorithm))
            {
                throw new ArgumentNullException("hashAlgorithm", String.Format(CultureInfo.InvariantCulture, "Hash algorithm cannot be null or empty"));
            }

            // Hash algorithm must be within storage enumeration range.
            if (hashAlgorithm == HashAlgorithm.SHA1_160.ToString())
            {
                return HashAlgorithm.SHA1_160;
            }
            else if (hashAlgorithm == HashAlgorithm.SHA2_256.ToString())
            {
                return HashAlgorithm.SHA2_256;
            }
            else if (hashAlgorithm == HashAlgorithm.SHA3_512.ToString())
            {
                return HashAlgorithm.SHA3_512;
            }
            else if (hashAlgorithm == HashAlgorithm.BCRYPT_192.ToString())
            {
                return HashAlgorithm.BCRYPT_192;
            }
            else if (hashAlgorithm == HashAlgorithm.SCRYPT_512.ToString())
            {
                return HashAlgorithm.SCRYPT_512;
            }
            else
            {
                throw new ArgumentOutOfRangeException("hashAlgorithm", String.Format(CultureInfo.InvariantCulture, "Hash algorithm isn't recognised!"));
            }
        }

        private static StorageFormat ValidateStorageFormat(string storageFormat)
        {
            if (String.IsNullOrEmpty(storageFormat))
            {
                throw new ArgumentNullException("storageFormat", String.Format(CultureInfo.InvariantCulture, "Storage format cannot be null or empty"));
            }

            // Storage format must be within storage enumeration range.
            if (storageFormat == StorageFormat.Hexadecimal.ToString())
            {
                return StorageFormat.Hexadecimal;
            }
            else if (storageFormat == StorageFormat.Base64.ToString())
            {
                return StorageFormat.Base64;
            }
            else
            {
                throw new ArgumentOutOfRangeException("storageFormat", String.Format(CultureInfo.InvariantCulture, "Storage format isn't recognised!"));
            }
        }

        private static byte[] ValidatePasswordSalt(byte[] passwordSalt)
        {
            if (passwordSalt == null)
            {
                throw new ArgumentNullException("passwordSalt", String.Format(CultureInfo.InvariantCulture, "Password salt must not be null!"));
            }
            return passwordSalt;
        }

        private static byte[] ValidatePasswordHash(byte[] passwordHash)
        {
            if ((passwordHash == null) || (passwordHash.Length == 0))
            {
                throw new ArgumentNullException("passwordHash", String.Format(CultureInfo.InvariantCulture, "Password hash must not be null or empty!"));
            }
            return passwordHash;
        }

        private static Int32 ValidateWorkFactor(string workFactor)
        {
            if (String.IsNullOrEmpty(workFactor))
            {
                throw new ArgumentOutOfRangeException("workFactor", String.Format(CultureInfo.InvariantCulture, "Hash work factor must not be null or empty!"));
            }

            Int32 iterations = 0;
            if (!Int32.TryParse(workFactor, out iterations))
            {
                throw new ArgumentOutOfRangeException("workFactor", String.Format(CultureInfo.InvariantCulture, "Hash work factor must be numeric!"));
            }

            if (iterations < 1)
            {
                throw new ArgumentOutOfRangeException("workFactor", String.Format(CultureInfo.InvariantCulture, "Hash work factor must be at least zero!"));
            }
            return iterations;
        }

        private byte[] ValidatePasswordSaltEncoded(string passwordSaltEncoded)
        {
            if (passwordSaltEncoded == null)
            {
                throw new ArgumentNullException("passwordSaltEncoded", String.Format(CultureInfo.InvariantCulture, "Encoded password salt must not be null!"));
            }

            switch (this.HashStorageFormat)
            {
                // Hexadecimal.
                case StorageFormat.Hexadecimal:
                    return ConvertFromHexString(passwordSaltEncoded);
                // Base64.
                case StorageFormat.Base64:
                    return Convert.FromBase64String(passwordSaltEncoded);
                // Invalid storage format.
                default:
                    Debug.Assert(false, this.HashStorageFormat.ToString() + " is an invalid storage format!");
                    return null;
            }
        }

        private byte[] ValidatePasswordHashEncoded(string passwordHashEncoded)
        {
            if (String.IsNullOrEmpty(passwordHashEncoded))
            {
                throw new ArgumentNullException("passwordHashEncoded", String.Format(CultureInfo.InvariantCulture, "Encoded password hash must not be null or empty!"));
            }

            switch (this.HashStorageFormat)
            {
                // Hexadecimal.
                case StorageFormat.Hexadecimal:
                    return ConvertFromHexString(passwordHashEncoded);
                // Base64.
                case StorageFormat.Base64:
                    return Convert.FromBase64String(passwordHashEncoded);
                // Invalid storage format.
                default:
                    Debug.Assert(false, this.HashStorageFormat.ToString() + " is an invalid storage format!");
                    return null;
            }
        }

        private static byte[] ConvertFromHexString(string hexString)
        {
            int offset = hexString.StartsWith("0x", true, CultureInfo.CurrentCulture) ? 2 : 0;

            if ((hexString.Length % 2) != 0)
            {
                throw new ArgumentException("hexString", String.Format(CultureInfo.InvariantCulture, "Length of hex string must be even, not {0}", hexString.Length));
            }
            byte[] ret = new byte[(hexString.Length - offset) / 2];

            for (int i = 0; i < ret.Length; i++)
            {
                ret[i] = (byte)((ParseNybble(hexString[offset]) << 4) | ParseNybble(hexString[offset + 1]));
                offset += 2;
            }
            return ret;
        }

        private static int ParseNybble(char symbol)
        {
            if (symbol >= '0' && symbol <= '9')
            {
                return symbol - '0';
            }
            if (symbol >= 'A' && symbol <= 'F')
            {
                return symbol - 'A' + 10;
            }
            if (symbol >= 'a' && symbol <= 'f')
            {
                return symbol - 'a' + 10;
            }
            throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Invalid hex character: " + symbol), "symbol");
        }

        /// <summary>
        /// Overrides the default ToString().
        /// </summary>
        /// <returns>
        /// The password as a Unicode (UTF-8) string.
        /// </returns>
        public override string ToString()
        {
            return String.Format(CultureInfo.InvariantCulture, "HashStorage: " + this.StoredHash);
        }
    }
}


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_AudioCompressionFormat : LuaObject {
	static public void reg(IntPtr l) {
		getEnumTable(l,"UnityEngine.AudioCompressionFormat");
		addMember(l,0,"PCM");
		addMember(l,1,"Vorbis");
		addMember(l,2,"ADPCM");
		addMember(l,3,"MP3");
		addMember(l,4,"VAG");
		addMember(l,5,"HEVAG");
		addMember(l,6,"XMA");
		addMember(l,7,"AAC");
		LuaDLL.lua_pop(l, 1);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 2: 166 (1883)

#### Original name
Metasphaeria corticola f. corticola

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.intel.bugkoops" >

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/MainTheme" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ScannerActivity"
            android:label="@string/title_activity_scanner" >
        </activity>
        <activity
            android:name=".SettingsActivity"
            android:label="@string/title_activity_settings" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name=".ReportActivity"
            android:label="@string/title_activity_report" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name=".ReportDetailActivity"
            android:label="@string/title_activity_report_detail"
            android:windowSoftInputMode="stateHidden" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".ReportActivity" />
        </activity>
        <activity
            android:name=".BugzillaSendActivity"
            android:label="@string/title_activity_bugzilla_send"
            android:theme="@android:style/Theme.Holo.Light.Dialog">
        </activity>

        <provider
            android:name=".Data.BugKoopsProvider"
            android:authorities="@string/content_authority"
            android:exported="false" />
    </application>

</manifest>


text:
<?php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class TournamentScore
{
    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="TournamentRound", inversedBy="scores")
     * @ORM\JoinColumn(onDelete="cascade")
     */
    protected $round;

    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Participant")
     * @ORM\JoinColumn(onDelete="cascade")
     */
    protected $participant;

    /**
     * @ORM\Column(type="integer")
     */
    protected $score;

    // CUSTOM FUNCTIONS FOR ADMIN

    public function __toString()
    {
        return $this->getParticipant()->getName() . " : " . $this->getScore();
    }

    // End Of Customs

    /**
     * Get round
     *
     * @return \App\Entity\TournamentRound
     */
    public function getRound()
    {
        return $this->round;
    }

    /**
     * Set round
     *
     * @param \App\Entity\TournamentRound $round
     * @return \App\Entity\TournamentRound
     */
    public function setRound(\App\Entity\TournamentRound $round = null)
    {
        $this->round = $round;

        return $this;
    }

    /**
     * Set score
     *
     * @param integer $score
     * @return \App\Entity\TournamentRound
     */
    public function setScore($score)
    {
        $this->score = $score;

        return $this;
    }

    /**
     * Get score
     *
     * @return integer
     */
    public function getScore()
    {
        return $this->score;
    }

    /**
     * Set participant
     *
     * @param \App\Entity\Participant $participant
     * @return \App\Entity\TournamentRound
     */
    public function setParticipant(\App\Entity\Participant $participant = null)
    {
        $this->participant = $participant;

        return $this;
    }

    /**
     * Get participant
     *
     * @return \App\Entity\Participant
     */
    public function getParticipant()
    {
        return $this->participant;
    }

}


text:
const React = require('react');

const Button = require('react-bootstrap').Button;

const RefreshButton = React.createClass({
	propTypes : {
		spinning : React.PropTypes.bool.isRequired
		,onClick : React.PropTypes.func.isRequired
	},

	render() {
		return (
			<Button bsStyle="info" onClick={this.props.onClick} disabled={this.props.spinning}>
	    		<RefreshSpinner spinning={this.props.spinning} /> Refresh
	    	</Button>
	    )
	}
});

const RefreshSpinner = React.createClass({
	propTypes : {
		spinning : React.PropTypes.bool.isRequired
	},

	render() {
		if (this.props.spinning) {
			return (

		    )
		} else {
			return (

			)
		}
	}
});

module.exports = RefreshButton;


text:
<?php

namespace Mopa\Bundle\BootstrapBundle\Twig;

use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Add new twig functions related to forms
 *
 * @author Paweł Madej (nysander) <pawel.madej@profarmaceuta.pl>
 * @author Charles Sanquer <charles.sanquer@gmail.com>
 */
class MopaBootstrapTwigExtension extends \Twig_Extension
{
    /**
     * Returns a list of functions to add to the existing list.
     *
     * @return array An array of functions
     */
    public function getFunctions()
    {
        return array(
            'form_help' => new \Twig_Function_Node('Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', array('is_safe' => array('html'))),
        );
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'bootstrap_form';
    }
}


text:
package com.jcwhatever.nucleus.managed.commands;

import com.jcwhatever.nucleus.managed.language.Localizable;

import org.bukkit.permissions.PermissionDefault;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Required annotation for all commands.
 *
 *
Defines basic operation of command.

 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandInfo {

    /**
     * Optional parent command sanity check.
     *
     *
If set, the parent command must match the name provided.

     */
    String parent() default "";

    /**
     * The command as it should be typed by the user
     *
     *
format example: { "command" }

     *
format example: { "command", "c" } (multiple commands defined,
     *    first one is primary)

     */
    String[] command();

    /**
     * Define static arguments of command.
     *
     *
Static parameters are typed by the user as the argument value in
     * the order specified in the staticParams annotation property. Static
     * parameters must always be typed as the first group of arguments.

     *
     *
Only the last static parameter may have a default value.

     *
     *
i.e. /command param1Arg param2Arg

     *
     *
Annotation format example: staticParams =
     *                                    { "param1Name", "param2Name" }

     *
     *
Annotation format example: staticParams =
     *                          "param1Name", "param2Name=defaultValue" }

     */
    String[] staticParams() default {};

    /**
     * Define floating parameters of command.
     *
     *
The floating parameter is typed as 2 dashes followed by the parameter
     * name, a space, then the parameter value.

     *
     *
The order that users type floating parameters is not enforced, except
     * that they must occur after all static arguments.

     *
     *
Any floating parameter may have a default value.

     *
     *
i.e. /command static1Arg static2Arg --param1Name param1Arg

     *
     *
Annotation format example: floatingParams =
     *                                          { "param1Name", "param2Name" }

     *
Annotation format example: floatingParams =
     *                              { "param1Name=defaultValue", "param2Name" }

     */
    String[] floatingParams() default {};

    /**
     * Define flag parameters.
     *
     *
Flag parameters return false if not present as a command argument or true
     * when present. They are written by the user a single dash followed by the
     * flag name.

     *
     *
i.e. /command static1 static2 -flag1Name

     *
     *
Annotation format example: { "flag1Name", "flag2Name" }

     */
    String[] flags() default {};

    /**
     * Define descriptions for parameters. Include descriptions for
     * static, floating and flag arguments. (Optional)
     *
     *
If descriptions are not provided, a substitute may be provided where
     * possible.

     *
     *
Annotation format example: paramDescriptions =
     *                  { "paramName1=description", "paramName2=description" }

     */
    String[] paramDescriptions() default {};

    /**
     * Optional usage instructions for the command.
     *
     *
This is normally auto generated. You can override the auto-generated usage
     * by providing a template or hardcoded usage.

     *
     *
A template has markers that define where to insert text as well
     * as colors. See {@link com.jcwhatever.nucleus.utils.text.TextUtils#format}.

     *
     *
The following are the format markers used in a template:

     *
     *

     *
{0} - root command name

     *
{1} - command path excluding the root command and the command.

     *
{2} - the command name

     *
{3} - command parameters

     *

     *
     *
Hardcode example: "/command subcommand
     *                      <parameter1> [parameter2] [--floatingParam] [-flag]"

     *
     *
Template example: "{GOLD}/{0}{GREEN}{1}{2}{BLUE}{3}"

     *
     *
Auto generated is recommended. Templates are preferable to hardcoded usage.

     */
    String usage() default "";

    /**
     * A short description of the commands function
     */
    @Localizable
    String description();

    /**
     * A longer description of the commands function
     */
    @Localizable
    String longDescription() default "";

    /**
     * Define if the command can be seen in help command lists.
     */
    boolean isHelpVisible() default true;

    /**
     * Define the default permission for the command.
     *
     *
The permission name is generated using the owning plugins name and
     * the commands path.

     *
     *
i.e. mypluginname.mycommand.mysubcommand

     *
     *
Wildcards can be used to enable or disable a command and its sub commands.

     */
    PermissionDefault permissionDefault() default PermissionDefault.OP;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Xenomai: Scheduling management</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

<link rel="search" href="search_opensearch.php?v=opensearch.xml" type="application/opensearchdescription+xml" title="Xenomai"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

Xenomai
    3.0.4

Functions

Scheduling management
Cobalt » POSIX interface

Cobalt scheduling management services.
More...

Collaboration diagram for Scheduling management:

<map name="group____cobalt____api____sched" id="group____cobalt____api____sched">
<area shape="rect" id="node2" href="group__cobalt__api.html" title="The Cobalt/POSIX interface is an implementation of a subset of the Single Unix specification over the..." alt="" coords="5,5,123,32"/>
</map>

Functions

int 	pthread_setschedparam (pthread_t thread, int policy, const struct sched_param *param)

 	Set the scheduling policy and parameters of the specified thread.  More...

int 	pthread_setschedparam_ex (pthread_t thread, int policy, const struct sched_param_ex *param_ex)

 	Set extended scheduling policy of thread.  More...

int 	pthread_getschedparam (pthread_t thread, int *__restrict__ policy, struct sched_param *__restrict__ param)

 	Get the scheduling policy and parameters of the specified thread.  More...

int 	pthread_getschedparam_ex (pthread_t thread, int *__restrict__ policy_r, struct sched_param_ex *__restrict__ param_ex)

 	Get extended scheduling policy of thread.  More...

int 	pthread_yield (void)

 	Yield the processor.  More...

Detailed Description

Cobalt scheduling management services.

Function Documentation

◆ pthread_getschedparam()

          int pthread_getschedparam
          (
          pthread_t
          thread,

          int *__restrict__
          policy,

          struct sched_param *__restrict__
          param

          )

Get the scheduling policy and parameters of the specified thread.

This service returns, at the addresses policy and par, the current scheduling policy and scheduling parameters (i.e. priority) of the Cobalt thread tid. If thread is not the identifier of a Cobalt thread, this service fallback to the regular POSIX pthread_getschedparam() service.

Parameters

thread	target thread;

policy	address where the scheduling policy of tid is stored on success;

param	address where the scheduling parameters of tid is stored on success.

Returns

0 on success;

an error number if:

ESRCH, tid is invalid.

See also

Specification.

Tags

thread-unrestricted

References pthread_getschedparam_ex().

Referenced by pthread_getschedparam_ex().

◆ pthread_getschedparam_ex()

          int pthread_getschedparam_ex
          (
          pthread_t
          thread,

          int *__restrict__
          policy_r,

          struct sched_param_ex *__restrict__
          param_ex

          )

Get extended scheduling policy of thread.

This service is an extended version of the regular pthread_getschedparam() service, which also supports Cobalt-specific policies, not available with the host Linux environment.

Parameters

thread	target thread;

policy_r	address where the scheduling policy of thread is stored on success;

param_ex	address where the scheduling parameters of thread are stored on success.

Returns

0 on success;

an error number if:

ESRCH, thread is invalid.

See also

Specification.

Tags

thread-unrestricted

References pthread_getschedparam().

Referenced by pthread_getschedparam().

◆ pthread_setschedparam()

          int pthread_setschedparam
          (
          pthread_t
          thread,

          int
          policy,

          const struct sched_param *
          param

          )

Set the scheduling policy and parameters of the specified thread.

This service set the scheduling policy of the Cobalt thread identified by pid to the value policy, and its scheduling parameters (i.e. its priority) to the value pointed to by param.

If pthread_self() is passed, this service turns the current thread into a Cobalt thread. If thread is not the identifier of a Cobalt thread, this service falls back to the regular pthread_setschedparam() service.

Parameters

thread	target Cobalt thread;

policy	scheduling policy, one of SCHED_FIFO, SCHED_RR, or SCHED_OTHER;

param	address of scheduling parameters.

Returns

0 on success;

an error number if:

ESRCH, pid is invalid;

EINVAL, policy or param->sched_priority is invalid;

EAGAIN, insufficient memory available from the system heap, increase CONFIG_XENO_OPT_SYS_HEAPSZ;

EFAULT, param is an invalid address;

See also

Specification.

Note

See pthread_create(), pthread_setschedparam_ex().

Tags

thread-unrestricted, switch-secondary, switch-primary

References pthread_setschedparam_ex().

Referenced by pthread_join().

◆ pthread_setschedparam_ex()

          int pthread_setschedparam_ex
          (
          pthread_t
          thread,

          int
          policy,

          const struct sched_param_ex *
          param_ex

          )

Set extended scheduling policy of thread.

This service is an extended version of the regular pthread_setschedparam() service, which supports Cobalt-specific scheduling policies, not available with the host Linux environment.

This service set the scheduling policy of the Cobalt thread thread to the value policy, and its scheduling parameters (e.g. its priority) to the value pointed to by param_ex.

If thread does not match the identifier of a Cobalt thread, this action falls back to the regular pthread_setschedparam() service.

Parameters

thread	target Cobalt thread;

policy	scheduling policy, one of SCHED_WEAK, SCHED_FIFO, SCHED_COBALT, SCHED_RR, SCHED_SPORADIC, SCHED_TP, SCHED_QUOTA or SCHED_NORMAL;

param_ex	scheduling parameters address. As a special exception, a negative sched_priority value is interpreted as if SCHED_WEAK was given in policy, using the absolute value of this parameter as the weak priority level.

When CONFIG_XENO_OPT_SCHED_WEAK is enabled, SCHED_WEAK exhibits priority levels in the [0..99] range (inclusive). Otherwise, sched_priority must be zero for the SCHED_WEAK policy.

Returns

0 on success;

an error number if:

ESRCH, thread is invalid;

EINVAL, policy or param_ex->sched_priority is invalid;

EAGAIN, insufficient memory available from the system heap, increase CONFIG_XENO_OPT_SYS_HEAPSZ;

EFAULT, param_ex is an invalid address;

EPERM, the calling process does not have superuser permissions.

See also

Specification.

Note

See pthread_create(), pthread_setschedparam().

Tags

thread-unrestricted, switch-secondary, switch-primary

Referenced by pthread_setschedparam().

◆ pthread_yield()

          int pthread_yield
          (
          void
          	)

Yield the processor.

This function move the current thread at the end of its priority group.

Return values

0

See also

Specification.

Tags

thread-unrestricted, switch-primary

References sched_yield().

Generated by

     1.8.13


text:
export const JSON_HEADERS = {
  Accept: "application/json",
  "Content-Type": "application/json"
};

export const JSON_AUTHORIZATION_HEADERS = {
  Authorization: `Token ${localStorage.token}`
};

export const JSON_POST_AUTHORIZATION_HEADERS = {
  Accept: "application/json",
  "Content-Type": "application/json",
  Authorization: `Token ${localStorage.token}`
};


text:
<?php
$files=Array("../plugins/jq.css3animate.js","../plugins/jq.scroller.js","../plugins/jq.popup.js","../plugins/jq.actionsheet.js","../plugins/jq.passwordBox.js","../plugins/jq.selectBox.js","../plugins/jq.touchEvents.js","../plugins/jq.touchLayer.js","./src/jq.ui.js","transitions/all.js");

$fp=fopen("jq.ui.js","w+");
$data="";
foreach($files as $fname){
    $data.=file_get_contents($fname)."\n";
}
//$data=preg_replace('#/\*.+?\*/#s',"",$data);
fputs($fp,$data);
fclose($fp);
?>


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: String.prototype.localeCompare(that)
es5id: 15.5.4.9_A1_T1
description: This string is symbol and arguments are symbols
---*/

var str1 = new String("h");
//CHECK#1
var str2 = new String ("\x68");
if  (str1.localeCompare(str2)!==0){
  $ERROR('#1: var str1 = new String("h"); var str2 = new String ("\\x68"); str1.localeCompare(str2)===0. Actual: '+str1.localeCompare(str2));
}

//CHECK#2
var str2 = new String ("\u0068");
if  (str1.localeCompare(str2)!==0){
  $ERROR('#2: var str1 = new String("h"); var str2 = new String ("\\u0068"); str1.localeCompare(str2)===0. Actual: '+str1.localeCompare(str2));
}

//CHECK#3
var str2 = new String ("h");
if  (str1.localeCompare(str2)!==0){
  $ERROR('#3: var str1 = new String("h"); var str2 = new String ("h"); str1.localeCompare(str2)===0. Actual: '+str1.localeCompare(str2));
}


text:
import platform
from multiprocessing import cpu_count
import json
from os import statvfs
from math import pow
from docker import Client
from uptime import uptime
import utils

def host_stats():
    return {
        'uptime': int(uptime()),
        'linux': ''.join(platform.linux_distribution()),
        'kernel': platform.uname()[2],
        'cpu': {
            'cpu_count': cpu_count(),
            'model_name': cpu_model_name()
        },
        'memory': memory_stats(),
        'network': network_stats(),
        'disk': disk_stats(),
        'docker': docker_stats()
    }

def memory_stats():
    _meminfo=dict()

    with open('/proc/meminfo') as f:
        for line in f:
            _meminfo[line.split(':')[0]] = line.split(':')[1].strip().split(' ')[0]
    return {
        'memory_total': _meminfo['MemTotal'],
        'memory_free': _meminfo['MemFree'],
        'swap_total': _meminfo['SwapTotal'],
        'swap_free': _meminfo['SwapFree']
    }

def cpu_model_name():
    with open('/proc/cpuinfo') as f:
        for line in f:
            # Ignore the blank line separating the information between
            # details about two processing units
            if line.strip():
                if line.rstrip('\n').startswith('model name'):
                    model_name = line.rstrip('\n').split(':')[1]
                    return model_name

def network_stats():
    data = {}

    network_stats_file = '/tmp/network_stats'

    # last_stats = False
    # last_stats_time = False
    #
    # if path.isfile(network_stats_file):
    #     last_stats_time = datetime.fromtimestamp(path.getmtime(network_stats_file))
    #
    #     with open(network_stats_file, 'r') as _file:
    #         last_stats = json.loads(_file.read())

    with open('/proc/net/dev', 'r') as _file:
        next(_file)
        next(_file)

        for line in _file:
            line = list(filter(None, line.strip().split(' ')))

            _interface = line[0].replace(':', '')

            total_received_bytes = line[1]
            total_transmitted_bytes = line[9]

            #print(total_received_bytes+':'+last_stats[_interface]['receive']['total_bytes'])

            # avg_received_bytes = 0
            # avg_transmitted_bytes = 0
            #
            # if last_stats_time:
            #     seconds = (datetime.now() - last_stats_time).total_seconds()
            #     avg_received_bytes = int((int(total_received_bytes) - int(last_stats[_interface]['receive']['total_bytes'])) / seconds)
            #     avg_received_bytes = int(avg_received_bytes/1024)

            data[_interface] = {
                'receive': {
                    'total_bytes': total_received_bytes,
                    'total_packets': line[2],
                    'total_errors': line[3],
                    'avg': 0
                },
                'transmit': {
                    'total_bytes': total_transmitted_bytes,
                    'total_packets': line[10],
                    'total_errors': line[11],
                    'avg': 0
                }
            }

    with open(network_stats_file, 'w+') as dumpfile:
        dumpfile.write(json.dumps(data, sort_keys=True, indent=4))

    return data

def disk_stats():
    stats = statvfs('/')

    data = {
        '/': {
            'total': int((stats.f_bsize * stats.f_blocks) / pow(1024, 2)),
            'free': int((stats.f_bsize * stats.f_bfree) / pow(1024, 2))
        }
    }

    return data

def docker_stats():
    docker_client = Client(base_url='unix://var/run/docker.sock', version='1.20')

    data = {
        'version': docker_client.version(),
        'images': docker_client.images(),
        'containers': []
    }

    containers = docker_client.containers()

    for container in containers:
        _container_details = docker_client.inspect_container(container=container['Id'])
        _image_details = docker_client.inspect_image(image=_container_details['Image'])

        container['Image'] = _image_details

        last_log = docker_client.logs(
            container=container['Id'],
            stdout=True,
            stderr=True,
            tail=1,
            timestamps=True
        )

        container['last_log'] = str(last_log, 'UTF-8').strip().split(' ')[0]

        data['containers'].append(container)

    return utils.dict_keys_to_lower(data)

if __name__ == "__main__":
    print(json.dumps(host_stats(), sort_keys=True, indent=4))


text:
// standard namespaces
using System;
using System.Collections.Generic;

// project namespaces
using TwitchLibrary.Enums.Helpers.Paging;
using TwitchLibrary.Models.API.Channels;

// imported .dll's
using Newtonsoft.Json;

namespace TwitchLibrary.Models.API.Videos
{
    public class Video
    {
        [JsonProperty("_id")]
        public string _id { get; protected set; }

        [JsonProperty("broadcast_id")]
        public string broadcast_id { get; protected set; }

        [JsonProperty("broadcast_type")]
        public BroadcastType broadcast_type { get; protected set; }

        // TODO: (Models) API - Videos - Not a full channel object, just the name and display name
        [JsonProperty("channel")]
        public Channel channel { get; protected set; }

        [JsonProperty("created_at")]
        public DateTime created_at { get; protected set; }

        [JsonProperty("description")]
        public string description { get; protected set; }

        [JsonProperty("description_html")]
        public string description_html { get; protected set; }

        [JsonProperty("fps")]
        public Dictionary<string, double> fps { get; protected set; }               // varies by video type and channel

        [JsonProperty("game")]
        public string game { get; protected set; }

        [JsonProperty("language")]
        public string language { get; protected set; }

        [JsonProperty("length")]
        public int length { get; protected set; }

        [JsonProperty("muted_segments")]
        public string muted_segments { get; protected set; }

        [JsonProperty("preview")]
        public Preview preview { get; protected set; }

        [JsonProperty("published_at")]
        public DateTime published_at { get; protected set; }

        [JsonProperty("resolutions")]
        public Dictionary<string, string> resolutions { get; protected set; }       // could be 1080p or chucked, etc

        [JsonProperty("status")]
        public string status { get; protected set; }

        [JsonProperty("tag_list")]
        public string tag_list { get; protected set; }

        [JsonProperty("thumbnails")]
        public Thumbnails thumbnails { get; protected set; }

        [JsonProperty("title")]
        public string title { get; protected set; }

        [JsonProperty("url")]
        public string url { get; protected set; }

        [JsonProperty("viewable")]
        public string viewable { get; protected set; }

        [JsonProperty("viewable_at")]
        public string viewable_at { get; protected set; }

        [JsonProperty("views")]
        public int views { get; protected set; }
    }
}


text:
package Aula.FilaEncadeada;

import Aula.PilhaEncadeada.*;
import java.io.*;

class Cliente implements Serializable {
    private String nome;
    private int telefone;

    Cliente(String n, int t) {
        nome = n;
        telefone = t;
    }

    String getNome() {
        return nome;
    }

    int getTelefone() {
        return telefone;
    }

    void setNome(String nome) {
        this.nome = nome;
    }

    void setTelefone(int t ) {
        telefone = t;
    }
}


text:
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using SixLabors.ImageSharp.Processing.Processors.Dithering;
using SixLabors.ImageSharp.Processing.Processors.Quantization;
using SixLabors.ImageSharp.Processing.Processors.Transforms;
using System.Numerics;

namespace Rocks.CodeGenerationTest.Mappings
{
	internal static class ImageSharpMappings
	{
		internal static Dictionary<Type, Dictionary<string, string>> GetMappedTypes() =>
			new()
			{
				{
					typeof(CloningImageProcessor<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(ICloningImageProcessor<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(IImageProcessor<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(Image<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(ImageFrame<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(ImageProcessor<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(IndexedImageFrame<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(IPaletteDitherImageProcessor<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(IPixel<>), new()
					{
						{ "TSelf", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(IQuantizer<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(IResamplingTransformImageProcessor<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(PixelBlender<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
				{
					typeof(PixelOperations<>), new()
					{
						{ "TPixel", "global::Rocks.CodeGenerationTest.Mappings.ImageSharp.MappedPixel" },
					}
				},
			};
	}

	namespace ImageSharp
	{
		public struct MappedPixel
			: IPixel<MappedPixel>
		{
			public PixelOperations<MappedPixel> CreatePixelOperations() => throw new NotImplementedException();
			public bool Equals(MappedPixel other) => throw new NotImplementedException();
			public void FromAbgr32(Abgr32 source) => throw new NotImplementedException();
			public void FromArgb32(Argb32 source) => throw new NotImplementedException();
			public void FromBgr24(Bgr24 source) => throw new NotImplementedException();
			public void FromBgra32(Bgra32 source) => throw new NotImplementedException();
			public void FromBgra5551(Bgra5551 source) => throw new NotImplementedException();
			public void FromL16(L16 source) => throw new NotImplementedException();
			public void FromL8(L8 source) => throw new NotImplementedException();
			public void FromLa16(La16 source) => throw new NotImplementedException();
			public void FromLa32(La32 source) => throw new NotImplementedException();
			public void FromRgb24(Rgb24 source) => throw new NotImplementedException();
			public void FromRgb48(Rgb48 source) => throw new NotImplementedException();
			public void FromRgba32(Rgba32 source) => throw new NotImplementedException();
			public void FromRgba64(Rgba64 source) => throw new NotImplementedException();
			public void FromScaledVector4(Vector4 vector) => throw new NotImplementedException();
			public void FromVector4(Vector4 vector) => throw new NotImplementedException();
			public void ToRgba32(ref Rgba32 dest) => throw new NotImplementedException();
			public Vector4 ToScaledVector4() => throw new NotImplementedException();
			public Vector4 ToVector4() => throw new NotImplementedException();
		}
	}
}


text:
import * as React from 'react';
import { css, Button } from 'office-ui-fabric-react';
import { HttpClient } from '@microsoft/sp-client-base';

import styles from '../ReactCrud.module.scss';
import { IReactCrudWebPartProps } from '../IReactCrudWebPartProps';

export interface IReactCrudProps extends IReactCrudWebPartProps {
  httpClient: HttpClient;
  siteUrl: string;
}

export interface IReactCrudState {
  status: string;
  items: IListItem[];
}

export interface IListItem {
  Title?: string;
  Id: number;
}

export default class ReactCrud extends React.Component<IReactCrudProps, IReactCrudState> {
  private listItemEntityTypeName: string = undefined;

  constructor(props: IReactCrudProps, state: IReactCrudState) {
    super(props);

    this.state = {
      status: this.listNotConfigured(this.props) ? 'Please configure list in Web Part properties' : 'Ready',
      items: []
    };
  }

  public componentWillReceiveProps(nextProps: IReactCrudProps): void {
    this.listItemEntityTypeName = undefined;
    this.setState({
      status: this.listNotConfigured(nextProps) ? 'Please configure list in Web Part properties' : 'Ready',
      items: []
    });
  }

  public render(): JSX.Element {
    const items: JSX.Element[] = this.state.items.map((item: IListItem, i: number): JSX.Element => {
      return (

{item.Title} ({item.Id})

      );
    });

    return (

                Sample SharePoint CRUD operations in React

              <Button disabled={this.listNotConfigured(this.props) } onClick={() => this.createItem() }>Create item</Button>
              <Button disabled={this.listNotConfigured(this.props) } onClick={() => this.readItem() }>Read item</Button>

              <Button disabled={this.listNotConfigured(this.props) } onClick={() => this.readItems() }>Read all items</Button>

              <Button disabled={this.listNotConfigured(this.props) } onClick={() => this.updateItem() }>Update item</Button>
              <Button disabled={this.listNotConfigured(this.props) } onClick={() => this.deleteItem() }>Delete item</Button>

              {this.state.status}

                {items}

    );
  }

  private createItem(): void {
    this.setState({
      status: 'Creating item...',
      items: []
    });

    this.getListItemEntityTypeName()
      .then((listItemEntityTypeName: string): Promise<Response> => {
        const body: string = JSON.stringify({
          '__metadata': {
            'type': listItemEntityTypeName
          },
          'Title': `Item ${new Date()}`
        });
        return this.props.httpClient.post(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items`, {
          headers: {
            'Accept': 'application/json;odata=nometadata',
            'Content-type': 'application/json;odata=verbose',
            'odata-version': ''
          },
          body: body
        });
      })
      .then((response: Response): Promise<IListItem> => {
        return response.json();
      })
      .then((item: IListItem): void => {
        this.setState({
          status: `Item '${item.Title}' (ID: ${item.Id}) successfully created`,
          items: []
        });
      }, (error: any): void => {
        this.setState({
          status: 'Error while creating the item: ' + error,
          items: []
        });
      });
  }

  private readItem(): void {
    this.setState({
      status: 'Loading latest items...',
      items: []
    });
    this.getLatestItemId()
      .then((itemId: number): Promise<Response> => {
        if (itemId === -1) {
          throw new Error('No items found in the list');
        }

        this.setState({
          status: `Loading information about item ID: ${itemId}...`,
          items: []
        });
        return this.props.httpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items(${itemId})?$select=Title,Id`, {
          headers: {
            'Accept': 'application/json;odata=nometadata',
            'odata-version': ''
          }
        });
      })
      .then((response: Response): Promise<IListItem> => {
        return response.json();
      })
      .then((item: IListItem): void => {
        this.setState({
          status: `Item ID: ${item.Id}, Title: ${item.Title}`,
          items: []
        });
      }, (error: any): void => {
        this.setState({
          status: 'Loading latest item failed with error: ' + error,
          items: []
        });
      });
  }

  private readItems(): void {
    this.setState({
      status: 'Loading all items...',
      items: []
    });
    this.props.httpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items?$select=Title,Id`, {
      headers: {
        'Accept': 'application/json;odata=nometadata',
        'odata-version': ''
      }
    })
      .then((response: Response): Promise<{ value: IListItem[] }> => {
        return response.json();
      })
      .then((response: { value: IListItem[] }): void => {
        this.setState({
          status: `Successfully loaded ${response.value.length} items`,
          items: response.value
        });
      }, (error: any): void => {
        this.setState({
          status: 'Loading all items failed with error: ' + error,
          items: []
        });
      });
  }

  private getLatestItemId(): Promise<number> {
    return new Promise<number>((resolve: (itemId: number) => void, reject: (error: any) => void): void => {
      this.props.httpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items?$orderby=Id desc&$top=1&$select=id`, {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'odata-version': ''
        }
      })
        .then((response: Response): Promise<{ value: { Id: number }[] }> => {
          return response.json();
        }, (error: any): void => {
          reject(error);
        })
        .then((response: { value: { Id: number }[] }): void => {
          if (response.value.length === 0) {
            resolve(-1);
          }
          else {
            resolve(response.value[0].Id);
          }
        });
    });
  }

  private updateItem(): void {
    this.setState({
      status: 'Loading latest items...',
      items: []
    });
    let latestItemId: number = undefined;
    let etag: string = undefined;
    let listItemEntityTypeName: string = undefined;
    this.getListItemEntityTypeName()
      .then((listItemType: string): Promise<number> => {
        listItemEntityTypeName = listItemType;
        return this.getLatestItemId();
      })
      .then((itemId: number): Promise<Response> => {
        if (itemId === -1) {
          throw new Error('No items found in the list');
        }

        latestItemId = itemId;
        this.setState({
          status: `Loading information about item ID: ${latestItemId}...`,
          items: []
        });
        return this.props.httpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items(${latestItemId})?$select=Id`, {
          headers: {
            'Accept': 'application/json;odata=nometadata',
            'odata-version': ''
          }
        });
      })
      .then((response: Response): Promise<IListItem> => {
        etag = response.headers.get('ETag');
        return response.json();
      })
      .then((item: IListItem): Promise<Response> => {
        this.setState({
          status: `Updating item with ID: ${latestItemId}...`,
          items: []
        });
        const body: string = JSON.stringify({
          '__metadata': {
            'type': listItemEntityTypeName
          },
          'Title': `Item ${new Date()}`
        });
        return this.props.httpClient.post(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items(${item.Id})`, {
          headers: {
            'Accept': 'application/json;odata=nometadata',
            'Content-type': 'application/json;odata=verbose',
            'odata-version': '',
            'IF-MATCH': etag,
            'X-HTTP-Method': 'MERGE'
          },
          body: body
        });
      })
      .then((response: Response): void => {
        this.setState({
          status: `Item with ID: ${latestItemId} successfully updated`,
          items: []
        });
      }, (error: any): void => {
        this.setState({
          status: `Error updating item: ${error}`,
          items: []
        });
      });
  }

  private deleteItem(): void {
    if (!window.confirm('Are you sure you want to delete the latest item?')) {
      return;
    }

    this.setState({
      status: 'Loading latest items...',
      items: []
    });
    let latestItemId: number = undefined;
    let etag: string = undefined;
    this.getLatestItemId()
      .then((itemId: number): Promise<Response> => {
        if (itemId === -1) {
          throw new Error('No items found in the list');
        }

        latestItemId = itemId;
        this.setState({
          status: `Loading information about item ID: ${latestItemId}...`,
          items: []
        });
        return this.props.httpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items(${latestItemId})?$select=Id`, {
          headers: {
            'Accept': 'application/json;odata=nometadata',
            'odata-version': ''
          }
        });
      })
      .then((response: Response): Promise<IListItem> => {
        etag = response.headers.get('ETag');
        return response.json();
      })
      .then((item: IListItem): Promise<Response> => {
        this.setState({
          status: `Deleting item with ID: ${latestItemId}...`,
          items: []
        });
        return this.props.httpClient.post(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items(${item.Id})`, {
          headers: {
            'Accept': 'application/json;odata=nometadata',
            'Content-type': 'application/json;odata=verbose',
            'odata-version': '',
            'IF-MATCH': etag,
            'X-HTTP-Method': 'DELETE'
          }
        });
      })
      .then((response: Response): void => {
        this.setState({
          status: `Item with ID: ${latestItemId} successfully deleted`,
          items: []
        });
      }, (error: any): void => {
        this.setState({
          status: `Error deleting item: ${error}`,
          items: []
        });
      });
  }

  private listNotConfigured(props: IReactCrudProps): boolean {
    return props.listName === undefined ||
      props.listName === null ||
      props.listName.length === 0;
  }

  private getListItemEntityTypeName(): Promise<string> {
    return new Promise<string>((resolve: (listItemEntityTypeName: string) => void, reject: (error: any) => void): void => {
      if (this.listItemEntityTypeName) {
        resolve(this.listItemEntityTypeName);
        return;
      }

      this.props.httpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')?$select=ListItemEntityTypeFullName`, {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'odata-version': ''
        }
      })
        .then((response: Response): Promise<{ ListItemEntityTypeFullName: string }> => {
          return response.json();
        }, (error: any): void => {
          reject(error);
        })
        .then((response: { ListItemEntityTypeFullName: string }): void => {
          this.listItemEntityTypeName = response.ListItemEntityTypeFullName;
          resolve(this.listItemEntityTypeName);
        });
    });
  }
}


text:
package org.orekit.forces.gravity.potential;

import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathUtils;
import org.apache.commons.math3.util.Precision;
import org.junit.Assert;
import org.junit.Test;
import org.orekit.Utils;
import org.orekit.errors.OrekitException;
import org.orekit.forces.gravity.potential.NormalizedSphericalHarmonicsProvider.NormalizedSphericalHarmonics;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider.UnnormalizedSphericalHarmonics;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;

public class ICGEMFormatReaderTest {

    @Test
    public void testReadLimits() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("g007_eigen_05c_coef", false));
        UnnormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getUnnormalizedProvider(3, 2);
        UnnormalizedSphericalHarmonics harmonics = provider.onDate(provider.getReferenceDate());
        Assert.assertEquals(TideSystem.TIDE_FREE, provider.getTideSystem());
        try {
            harmonics.getUnnormalizedCnm(3, 3);
            Assert.fail("an exception should have been thrown");
        } catch (OrekitException oe) {
            // expected
        } catch (Exception e) {
            Assert.fail("wrong exception caught: " + e.getLocalizedMessage());
        }
        try {
            harmonics.getUnnormalizedCnm(4, 2);
            Assert.fail("an exception should have been thrown");
        } catch (OrekitException oe) {
            // expected
        } catch (Exception e) {
            Assert.fail("wrong exception caught: " + e.getLocalizedMessage());
        }
        harmonics.getUnnormalizedCnm(3, 2);
        Assert.assertEquals(3, provider.getMaxDegree());
        Assert.assertEquals(2, provider.getMaxOrder());
    }

    @Test
    public void testRegular05cNormalized() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("g007_eigen_05c_coef", false));
        NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(5, 5);
        Assert.assertEquals(TideSystem.TIDE_FREE, provider.getTideSystem());
        AbsoluteDate refDate = new AbsoluteDate("2004-10-01T12:00:00", TimeScalesFactory.getTT());
        Assert.assertEquals(refDate, provider.getReferenceDate());
        AbsoluteDate date = new AbsoluteDate("2013-01-08T10:46:53", TimeScalesFactory.getTT());
        NormalizedSphericalHarmonics harmonics = provider.onDate(date);
        Assert.assertEquals(date.durationFrom(refDate), provider.getOffset(date), Precision.SAFE_MIN);

        double offset     = date.durationFrom(refDate);
        double offsetYear = offset / Constants.JULIAN_YEAR;
        Assert.assertEquals(0.957212879862e-06 + offsetYear * 0.490000000000e-11,
                            harmonics.getNormalizedCnm(3, 0), 1.0e-15);
        Assert.assertEquals( 0.174804558032e-06, harmonics.getNormalizedCnm(5, 5), 1.0e-15);
        Assert.assertEquals( 0.0,                harmonics.getNormalizedSnm(4, 0), 1.0e-15);
        Assert.assertEquals( 0.308816581016e-06, harmonics.getNormalizedSnm(4, 4), 1.0e-15);
        Assert.assertEquals(0.3986004415E+15, provider.getMu(), 1.0e-20);
        Assert.assertEquals(0.6378136460E+07, provider.getAe(), 1.0e-20);
    }

    @Test
    public void testRegular05cUnnormalized() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("g007_eigen_05c_coef", false));
        UnnormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getUnnormalizedProvider(5, 5);
        Assert.assertEquals(TideSystem.TIDE_FREE, provider.getTideSystem());
        AbsoluteDate refDate = new AbsoluteDate("2004-10-01T12:00:00", TimeScalesFactory.getTT());
        Assert.assertEquals(refDate, provider.getReferenceDate());
        AbsoluteDate date = new AbsoluteDate("2013-01-08T10:46:53", TimeScalesFactory.getTT());
        Assert.assertEquals(date.durationFrom(refDate), provider.getOffset(date), Precision.SAFE_MIN);
        UnnormalizedSphericalHarmonics harmonics = provider.onDate(date);
        int maxUlps = 2;
        checkValue(harmonics.getUnnormalizedCnm(3, 0),
                   date, 3, 0, 2004, 10, 1, 0.957212879862e-06, 0.490000000000e-11, 0, 0, 0, 0,
                   maxUlps);
        checkValue(harmonics.getUnnormalizedCnm(5, 5),
                   date, 5, 5, 2004, 10, 1, 0.174804558032e-06, 0, 0, 0, 0, 0,
                   maxUlps);
        checkValue(harmonics.getUnnormalizedSnm(4, 0),
                   date, 4, 0, 2004, 10, 1, 0, 0, 0, 0, 0, 0,
                   maxUlps);
        checkValue(harmonics.getUnnormalizedSnm(4, 4),
                   date, 4, 4, 2004, 10, 1, 0.308816581016e-06, 0, 0, 0, 0, 0,
                   maxUlps);
        Assert.assertEquals(0.3986004415E+15, provider.getMu(), 1.0e-20);
        Assert.assertEquals(0.6378136460E+07, provider.getAe(), 1.0e-20);
    }

    @Test
    public void testEigen06() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("eigen-6s-truncated", false));
        UnnormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getUnnormalizedProvider(5, 5);
        Assert.assertEquals(TideSystem.TIDE_FREE, provider.getTideSystem());
        AbsoluteDate refDate = new AbsoluteDate("2005-01-01T12:00:00", TimeScalesFactory.getTT());
        Assert.assertEquals(refDate, provider.getReferenceDate());
        AbsoluteDate date = new AbsoluteDate("2013-01-08T10:46:53", TimeScalesFactory.getTT());
        Assert.assertEquals(date.durationFrom(refDate), provider.getOffset(date), Precision.SAFE_MIN);
        UnnormalizedSphericalHarmonics harmonics = provider.onDate(date);
        int maxUlps = 2;
        checkValue(harmonics.getUnnormalizedCnm(3, 0),
                   date, 3, 0, 2005, 1, 1, 9.57211326674e-07, -8.37191630994e-12,
                   -1.76087178236e-11, 9.47617140143e-11, 1.06252954726e-11, -9.12524501214e-12,
                   maxUlps);
        checkValue(harmonics.getUnnormalizedCnm(5, 5),
                   date, 5, 5, 2005, 1, 1, 1.74807033099e-07, -1.33498578664e-12,
                   -2.76043013690e-12, -8.28591865697e-12, 1.57898939101e-12, 2.90931436419e-12,
                   maxUlps);
        checkValue(harmonics.getUnnormalizedSnm(4, 0),
                   date, 4, 0, 2005, 1, 1, 0, 0, 0, 0, 0, 0,
                   maxUlps);
        checkValue(harmonics.getUnnormalizedSnm(4, 4),
                   date, 4, 4, 2005, 1, 1, 3.08820169866e-07, 4.35447782358e-13,
                   -1.21823769110e-11, 3.89722186321e-11, 7.28153817742e-12, -7.64506592459e-12,
                   maxUlps);
        Assert.assertEquals(0.3986004415E+15, provider.getMu(), 1.0e-20);
        Assert.assertEquals(0.6378136460E+07, provider.getAe(), 1.0e-20);
    }

    @Test(expected=OrekitException.class)
    public void testCorruptedFile1() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("corrupted-1-g007_eigen_coef", false));
        GravityFieldFactory.getUnnormalizedProvider(5, 5);
    }

    @Test(expected=OrekitException.class)
    public void testCorruptedFile2() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("corrupted-2-g007_eigen_coef", false));
        GravityFieldFactory.getUnnormalizedProvider(5, 5);
    }

    @Test(expected=OrekitException.class)
    public void testInvalidNorm() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("dummy_invalid_norm_icgem", false));
        GravityFieldFactory.getUnnormalizedProvider(3, 3);
    }

    @Test(expected=OrekitException.class)
    public void testInvalidTide() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("dummy_invalid_tide_icgem", false));
        GravityFieldFactory.getUnnormalizedProvider(3, 3);
    }

    @Test
    public void testZeroTide() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("dummy_zero_tide_icgem", false));
        Assert.assertEquals(TideSystem.ZERO_TIDE,
                            GravityFieldFactory.getUnnormalizedProvider(3, 3).getTideSystem());
    }

    @Test
    public void testUnknownTide() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("dummy_unknown_tide_icgem", false));
        Assert.assertEquals(TideSystem.UNKNOWN,
                            GravityFieldFactory.getUnnormalizedProvider(3, 3).getTideSystem());
    }

    /** Check numbers in the format 1.0d0 can be parsed. */
    @Test
    public void testLowercaseD() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("dummy_small_d_icgem", false));
        Assert.assertEquals(10.0,
                GravityFieldFactory
                        .getUnnormalizedProvider(3, 3)
                        .onDate(AbsoluteDate.J2000_EPOCH)
                        .getUnnormalizedCnm(2,2),
                0.0);
    }

    /** check files without 1,0 and 1,1 can be parsed. */
    @Test
    public void testMissingDegree1() throws OrekitException {
        Utils.setDataRoot("potential");
        GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("dummy_missing_degree_1", false));
        UnnormalizedSphericalHarmonics harmonics = GravityFieldFactory
                .getUnnormalizedProvider(2, 2)
                .onDate(AbsoluteDate.J2000_EPOCH);
        //check coefficients not in the file are initialized correctly
        Assert.assertEquals(0.0, harmonics.getUnnormalizedCnm(1, 0), 0.0);
        Assert.assertEquals(0.0, harmonics.getUnnormalizedCnm(1, 1), 0.0);
        //check a coefficient is read correctly
        Assert.assertEquals(10.0, harmonics.getUnnormalizedCnm(2, 2), 0.0);
    }

    private void checkValue(final double value,
                            final AbsoluteDate date, final int n, final int m,
                            final int refYear, final int refMonth, final int refDay,
                            final double constant, final double trend,
                            final double cosYear, final double sinYear,
                            final double cosHalfYear, final double sinHalfYear,
                            final int maxUlps)
        throws OrekitException {
        double factor = GravityFieldFactory.getUnnormalizationFactors(n, m)[n][m];
        AbsoluteDate refDate = new AbsoluteDate(refYear, refMonth, refDay, 12, 0, 0, TimeScalesFactory.getTT());
        double dtYear = date.durationFrom(refDate) / Constants.JULIAN_YEAR;
        double normalized = factor * (constant +
                                      trend       * dtYear +
                                      cosYear     * FastMath.cos(MathUtils.TWO_PI * dtYear) +
                                      sinYear     * FastMath.sin(MathUtils.TWO_PI * dtYear) +
                                      cosHalfYear * FastMath.cos(MathUtils.TWO_PI * dtYear * 2) +
                                      sinHalfYear * FastMath.sin(MathUtils.TWO_PI * dtYear * 2));
        double epsilon = maxUlps * FastMath.ulp(normalized);
        Assert.assertEquals(normalized, value, epsilon);
    }

}


text:
all: test

# Clean

clean: clean-cov clean-node

clean-node:
	@rm -rf node_modules

clean-cov:
	@rm -rf coverage

# CI

test:
	@npm test

test-browser: node_modules
	@node_modules/serve/bin/serve -Slojp 0

coveralls:
	@./node_modules/.bin/istanbul cover ./node_modules/.bin/_hydro --report lcovonly -- \
		&& cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js

# Support

node_modules: clean-node
	@npm install

.PHONY: all test coverage


text:
class ChosenObjectView;

class ChosenObjectViewObserver {
 public:
  // This method is called when permission for the object is revoked.
  virtual void OnChosenObjectDeleted(
      const WebsiteSettingsUI::ChosenObjectInfo& info) = 0;

 protected:
  virtual ~ChosenObjectViewObserver() {}
};

#endif  // CHROME_BROWSER_UI_VIEWS_WEBSITE_SETTINGS_CHOSEN_OBJECT_VIEW_OBSERVER_H_


text:
package com.how.tfg;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.how.tfg.data.domain.UserDetails;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebAppConfiguration
@IntegrationTest("server.port=0")
@DirtiesContext
public class SocialUserDetailsServiceTest {

	@Mock
	private SocialUserDetailsService service;

	@Mock
	private UserDetails user;

	// Start method
	// ---------------------------------------------------------------
	@Before
	public void setUp() {
		 MockitoAnnotations.initMocks(this);
		 user.setId(new Long(1));
	}

	// Test methods
	// ---------------------------------------------------------------
	// Positive test methods
	// -----------------------------------------------------

	@Test
	public void getById() {
		Long idL = new Long(11);
		when(service.loadUserByUserId(idL.toString())).thenReturn(user);
		when(user.getId()).thenReturn(idL);

		UserDetails temp = (UserDetails) service.loadUserByUserId(idL.toString());
		temp.setId(idL);

        assertNotNull(temp);
        assertThat(temp.getId(), equalTo(user.getId()));
	}

}


text:
package org.gradle.api.internal.externalresource.metadata;

import org.gradle.api.Nullable;
import org.gradle.internal.hash.HashValue;

import java.io.Serializable;
import java.util.Date;

public class DefaultExternalResourceMetaData implements ExternalResourceMetaData, Serializable {

    private final String location;
    private final Date lastModified;
    private final long contentLength;
    private final String etag;
    private final String sha1;

    public DefaultExternalResourceMetaData(String location) {
        this(location, -1, -1, null, null);
    }

    public DefaultExternalResourceMetaData(String location, long lastModified, long contentLength, @Nullable String etag, @Nullable HashValue sha1) {
        this(location, lastModified > 0 ? new Date(lastModified) : null, contentLength, etag, sha1);
    }

    public DefaultExternalResourceMetaData(String location, @Nullable Date lastModified, long contentLength, @Nullable String etag, @Nullable HashValue sha1) {
        this.location = location;
        this.lastModified = lastModified;
        this.contentLength = contentLength;
        this.etag = etag;
        this.sha1 = sha1 == null ? null : sha1.asHexString();
    }

    public String getLocation() {
        return location;
    }

    @Nullable
    public Date getLastModified() {
        return lastModified;
    }

    public long getContentLength() {
        return contentLength;
    }

    @Nullable
    public String getEtag() {
        return etag;
    }

    public HashValue getSha1() {
        return sha1 == null ? null : HashValue.parse(sha1);
    }
}


text:
{- -*- Mode: haskell; -*-
Haskell LDAP Interface
Copyright (C) 2005-2009 John Goerzen <jgoerzen@complete.org>

This code is under a 3-clause BSD license; see COPYING for details.
-}

{- |
   Module     : LDAP.Exceptions
   Copyright  : Copyright (C) 2005-2009 John Goerzen
   License    : BSD

   Maintainer : John Goerzen,
   Maintainer : jgoerzen\@complete.org
   Stability  : provisional
   Portability: portable

Handling LDAP Exceptions

Written by John Goerzen, jgoerzen\@complete.org
-}

module LDAP.Exceptions (-- * Types
                        LDAPException(..),
                        -- * General Catching
                        catchLDAP,
                        handleLDAP,
                        failLDAP,
                        throwLDAP
                        )

where
import Data.Typeable
import Control.Exception
import LDAP.Types
import LDAP.Data

#if __GLASGOW_HASKELL__ < 610
import Data.Dynamic
#endif

{- | The basic type of LDAP exceptions.  These are raised when an operation
does not indicate success. -}

data LDAPException = LDAPException
    {code :: LDAPReturnCode,     -- ^ Numeric error code
     description :: String,     -- ^ Description of error
     caller :: String           -- ^ Calling function
    }
instance Show LDAPException where
    show x = caller x ++ ": LDAPException " ++ show (code x) ++
             "(" ++ show (fromEnum $ code x) ++ "): " ++
             description x

instance Eq LDAPException where
    x == y = code x == code y

instance Ord LDAPException where
    compare x y = compare (code x) (code y)

instance Typeable LDAPException where
    typeOf _ = mkTyConApp ldapExceptionTc []

ldapExceptionTc :: TyCon
ldapExceptionTc = mkTyCon "LDAP.LDAPException"

#if __GLASGOW_HASKELL__ >= 610
instance Exception LDAPException where
{-
    toException = SomeException
    fromException (SomeException e) = Just e
    fromException _ = Nothing
-}

{- | Execute the given IO action.

If it raises a 'LDAPException', then execute the supplied handler and return
its return value.  Otherwise, process as normal. -}
catchLDAP :: IO a -> (LDAPException -> IO a) -> IO a
catchLDAP action handler =
    catchJust ldapExceptions action handler

{- | Like 'catchLDAP', with the order of arguments reversed. -}
handleLDAP :: (LDAPException -> IO a) -> IO a -> IO a
handleLDAP = flip catchLDAP

{- | Given an Exception, return Just LDAPException if it was an
'LDAPExcetion', or Nothing otherwise.  Useful with functions
like catchJust. -}
ldapExceptions :: LDAPException -> Maybe LDAPException
ldapExceptions e = Just e

#else

{- | Execute the given IO action.

If it raises a 'LDAPException', then execute the supplied handler and return
its return value.  Otherwise, process as normal. -}
catchLDAP :: IO a -> (LDAPException -> IO a) -> IO a
catchLDAP = catchDyn

{- | Like 'catchLDAP', with the order of arguments reversed. -}
handleLDAP :: (LDAPException -> IO a) -> IO a -> IO a
handleLDAP = flip catchLDAP

#endif

{- | Catches LDAP errors, and re-raises them as IO errors with fail.
Useful if you don't care to catch LDAP errors, but want to see a sane
error message if one happens.  One would often use this as a high-level
wrapper around LDAP calls.
-}
failLDAP :: IO a -> IO a
failLDAP action =
    catchLDAP action handler
    where handler e = fail ("LDAP error: " ++ show e)

{- | A utility function to throw an 'LDAPException'.  The mechanics of throwing
such a thing differ between GHC 6.8.x, Hugs, and GHC 6.10.  This function
takes care of the special cases to make it simpler.

With GHC 6.10, it is a type-restricted alias for throw.  On all other systems,
it is a type-restricted alias for throwDyn. -}
throwLDAP :: LDAPException -> IO a
#if __GLASGOW_HASKELL__ >= 610
throwLDAP = throw
#else
throwLDAP = throwDyn
#endif


text:
import mistune, datetime, yaml

def tilde(line):
    try: command = line[line.index("~")+1:line.index(":")] # get the command
    except ValueError:
        print("Malformed command: \"" + line + "\"")
        sys.exit()

    args = line[line.index(":")+1:].split() # get the rest of the args in a list

    if command == "import":
        with open("templates/" + args[0] + ".html", "r") as tempFile:
            data = tempFile.read() # open the template

        parsedTemp = []
        for line in data.splitlines():
            parsedTemp.append(parseLine(line))
        data = "\n".join(parsedTemp)

        if len(args) > 1:
            for arg in args[1:]: # skip first arg (command)
                key = arg[:arg.index("=")] # before the =
                value = arg[arg.index("=")+1:] # after the =
                data = data.replace("{{ " + key + " }}", value) # replace
        return data # return the template

def dot(line):
    if line.startswith(".."):
        if line == "..":
            return ""
        else:
            return ""
    if line == ".":
        return "
"
    else:
        return "
"

def parseLine(line): # Function for parsing our HTML templates
    config = yaml.load(open("config/painless.yml", "r").read()) # load config

    for name in config["customValues"]: # iterate
        value = config["customValues"][name] # get name
        line = replaceSpecials(line, name, value)

    # pre-made one
    line = replaceSpecials(line, "time", datetime.datetime.now().strftime(config["options"]["timeFormat"]))
    line = replaceSpecials(line, "branding", "
Built painlessly.
")

    return line

def replaceSpecials(line, name, value, BRACKETS="["):
    bracketPairs = {
        "[" : "]",
        "{" : "}",
        "(" : ")"
    }
    RBRACKETS = bracketPairs[BRACKETS]

    line = line.replace((BRACKETS * 2) + " " + name + " " + (RBRACKETS * 2), value)
    line = line.replace((BRACKETS * 2) + name + (RBRACKETS * 2), value)

    return line

def default(line): # do to all lines in markdown
    line = parseLine(line)
    line = mistune.markdown(line)
    return line


text:
require('commons');
require('lessDir/about/about_header.less');
require('lessDir/about/about.less');

define(['jquery','script/index/load_init','script/utils/angular','script/utils/angular-route.1.2.9.min','script/utils/angular-sanitize.1.2.9.min','script/utils/req','script/about/zx_common'],function($ , LOAD, angular,route,sanitize,req,zx_common){
	var url = LOAD.getUrlParams(window.location.href,'?');
	angular.module('about',['ngRoute','ngSanitize','zxCommon']).
	run(['$rootScope','$location', function($rootScope,$location) {
		//请求列表也
		var jsonData = {};
		req.jsonp({
			url:base_url + "/news/getNewsByTypeSnList",
			data: {typeSn : url.typeSn , start :1 , length: 2},
			success: function(d){
				//console.log(d)
				$rootScope.pageLoading = true;
	        	if(d.data.length>0){
        			$rootScope.total_data = d.data;
        			//console.log($rootScope.total_data)
        			//console.log('------')
        			if ($rootScope.total_data.length>=2) {
	        			req.jsonp({
							url:base_url + "/news/getNewsByTypeSn",
							data: {typeSn:url.typeSn, sn:$rootScope.total_data[1].sn},
							success: function(d){
								$rootScope.tljj = d.data;
								//console.log($rootScope.tljj)
								$rootScope.$apply();
							},
							error: function(e){
								alert('请求失败!')
							}
						});
					};
					if ($rootScope.total_data.length>=1) {
						req.jsonp({
							url:base_url + "/news/getNewsByTypeSn",
							data: {typeSn:url.typeSn, sn:$rootScope.total_data[0].sn},
							success: function(d){
								$rootScope.tjtl = d.data;
								//console.log($rootScope.tjtl)
								$rootScope.$apply();
							},
							error: function(e){
								alert('请求失败!')
							}
						});
					}
        			$rootScope.$apply();
				}else{
					alert('没有数据')
				}
			},
			error: function(e){
				alert('请求失败!')
			}
		});
		$rootScope.abuo = function(){
			window.location.reload();
		}
		//请求详情页
	}])
	//初始化
	angular.element(document).ready(function() {
		angular.bootstrap(document, ['about']);
	});
})