text:
package laraifox.foxtail.core.math;

public class MathUtils {
	public static final double DOUBLE_EPSILON = 2.22e-16;
	public static final float FLOAT_EPSILON = 1.19e-07f;
	public static final long MILLIARD = 1000000000L;
	public static final double TAU = 6.283185307179586;

	public static int clamp(int value, int min, int max) {
		if (max < min)
			return value;

		if (value < min)
			value = min;
		else if (value > max)
			value = max;

		return value;
	}

	public static long clamp(long value, long min, long max) {
		if (max < min)
			return value;

		if (value < min)
			value = min;
		else if (value > max)
			value = max;

		return value;
	}

	public static float clamp(float value, float min, float max) {
		if (max < min)
			return value;

		if (value < min)
			value = min;
		else if (value > max)
			value = max;

		return value;
	}

	public static double clamp(double value, double min, double max) {
		if (max < min)
			return value;

		if (value < min)
			value = min;
		else if (value > max)
			value = max;

		return value;
	}

	public static int lerp(int a, int b, float value) {
		return (int) (a + (b - a) * value);
	}

	public static long lerp(long a, long b, float value) {
		return (long) (a + (b - a) * value);
	}

	public static float lerp(float a, float b, float value) {
		return a + (b - a) * value;
	}

	public static double lerp(double a, double b, double value) {
		return a + (b - a) * value;
	}

	public static int max(int... values) {
		if (values.length < 2) {
			return values[0];
		}

		int result = Math.max(values[0], values[1]);
		for (int i = 2; i < values.length; i++) {
			result = Math.max(result, values[i]);
		}

		return result;
	}

	public static long max(long... values) {
		if (values.length < 2) {
			return values[0];
		}

		long result = Math.max(values[0], values[1]);
		for (int i = 2; i < values.length; i++) {
			result = Math.max(result, values[i]);
		}

		return result;
	}

	public static float max(float... values) {
		if (values.length < 2) {
			return values[0];
		}

		float result = Math.max(values[0], values[1]);
		for (int i = 2; i < values.length; i++) {
			result = Math.max(result, values[i]);
		}

		return result;
	}

	public static double max(double... values) {
		if (values.length < 2) {
			return values[0];
		}

		double result = Math.max(values[0], values[1]);
		for (int i = 2; i < values.length; i++) {
			result = Math.max(result, values[i]);
		}

		return result;
	}

	public static int min(int... values) {
		if (values.length < 2) {
			return values[0];
		}

		int result = Math.min(values[0], values[1]);
		for (int i = 2; i < values.length; i++) {
			result = Math.min(result, values[i]);
		}

		return result;
	}

	public static long min(long... values) {
		if (values.length < 2) {
			return values[0];
		}

		long result = Math.min(values[0], values[1]);
		for (int i = 2; i < values.length; i++) {
			result = Math.min(result, values[i]);
		}

		return result;
	}

	public static float min(float... values) {
		if (values.length < 2) {
			return values[0];
		}

		float result = Math.min(values[0], values[1]);
		for (int i = 2; i < values.length; i++) {
			result = Math.min(result, values[i]);
		}

		return result;
	}

	public static double min(double... values) {
		if (values.length < 2) {
			return values[0];
		}

		double result = Math.min(values[0], values[1]);
		for (int i = 2; i < values.length; i++) {
			result = Math.min(result, values[i]);
		}

		return result;
	}

	public static int nextPowerOfTwo(int i) {
		i -= 1;
		i |= (i >> 1);
		i |= (i >> 2);
		i |= (i >> 4);
		i |= (i >> 8);
		i |= (i >> 16);

		return i + 1;
	}

	public static long nextPowerOfTwo(long i) {
		i -= 1;
		i |= (i >> 1);
		i |= (i >> 2);
		i |= (i >> 4);
		i |= (i >> 8);
		i |= (i >> 16);
		i |= (i >> 32);

		return i + 1;
	}
}


text:
require 'github_cloner/github_helper'

class Cloner

  include Github

  def initialize(options)
    @github_uname = options[:username]
    @mode = options[:method]
    @path = options[:path]
    @timeout = options[:timeout]
    @repos = options[:repos]
  end

  def clone
    Github::get_repos(@github_uname, @mode, @timeout).each {|repo| system("git clone #{repo[:link]} #{@path}/#{repo[:inactive]}/#{repo[:name]}") if @repos.include? repo[:name] or @repos.empty? }
  end

end

redpajama_set_name: RedPajamaGithub


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.server;

import com.google.appinventor.shared.rpc.project.ProjectSourceZip;
import com.google.appinventor.shared.rpc.project.RawFile;

import java.io.IOException;

import javax.annotation.Nullable;

/**
 * Methods for exporting project files.
 *
 */
public interface FileExporter {

  public static final String REMIX_INFORMATION_FILE_PATH = "youngandroidproject/remix_history";

  /**
   * Exports a project output file.
   *
   * @param userId the userId
   * @param projectId the project id belonging to the userId
   * @param target the output target platform, or null
   * @return RawFile with the name and content of the exported file
   * @throws IllegalArgumentException if download request cannot be fulfilled
   *         (either no output file or too many output files)
   */
  RawFile exportProjectOutputFile(String userId, long projectId, @Nullable String target)
      throws IOException;

  /**
   * Exports the project source files as a zip.
   *
   * @param userId the userId
   * @param projectId the project id belonging to the userId
   * @param includeProjectHistory indicates whether to include a file
   *        containing the project's history in the zip
   * @param includeAndroidKeystore indicates whether to include the user's android.keystore file
   * @param zipName the desired name for the zip, or null for a name to be generated
   * @param fatalError set to true to cause missing GCS file to throw exception
   * @return the zip file, which includes a count of the number of zipped files
   *         and (indirectly) the name of the file and its contents
   * @throws IllegalArgumentException if download request cannot be fulfilled
   *         (no source files)
   * @throws IOException if files cannot be written
   */
  ProjectSourceZip exportProjectSourceZip(String userId, long projectId,
    boolean includeProjectHistory,
    boolean includeAndroidKeystore, @Nullable String zipName,
    boolean includeYail,
    boolean fatalError, boolean forGallery) throws IOException;

  /**
   * Exports all of the user's projects' source files as a zip of zips.
   *
   * @param userId the userId
   * @param zipName the desired name for the zip
   * @return the name, contents, and number of files in the zip
   * @throws IllegalArgumentException if download request cannot be fulfilled
   *         (no projects)
   * @throws IOException if files cannot be written
   */
  ProjectSourceZip exportAllProjectsSourceZip(String userId, String zipName) throws IOException;

  /**
   * Exports a specific project file.
   *
   * @param userId the userId
   * @param projectId the project id belonging to the userId
   * @param filePath the full path of the file
   * @return RawFile with the name and content
   * @throws IllegalArgumentException if download request cannot be fulfilled
   *         (file is not known)
   */
  RawFile exportFile(String userId, long projectId, String filePath) throws IOException;

  /**
   * Exports a specific user file.
   *
   * @param userId the userId
   * @param filePath the full path of the file
   * @return RawFile with the name and content
   * @throws IllegalArgumentException if download request cannot be fulfilled
   *         (file is not known)
   */
  RawFile exportUserFile(String userId, String filePath) throws IOException;
}


text:
#include <fci.h>
#include <fcntl.h>
#include <msi.h>

// Callback from PFNFCIGETNEXTCABINET CabCGetNextCabinet method
// First argument is the name of splitting cabinet without extension e.g. "cab1"
// Second argument is name of the new cabinet that would be formed by splitting e.g. "cab1b.cab"
// Third argument is the file token of the first file present in the splitting cabinet
typedef void (__stdcall * FileSplitCabNamesCallback)(LPWSTR, LPWSTR, LPWSTR);

#define CAB_MAX_SIZE 0x7FFFFFFF   // (see KB: Q174866)

#ifdef __cplusplus
extern "C" {
#endif

extern const int CABC_HANDLE_BYTES;

// time vs. space trade-off
typedef enum COMPRESSION_TYPE
{
    COMPRESSION_TYPE_NONE, // fastest
    COMPRESSION_TYPE_LOW,
    COMPRESSION_TYPE_MEDIUM,
    COMPRESSION_TYPE_HIGH, // smallest
    COMPRESSION_TYPE_MSZIP
} COMPRESSION_TYPE;

// functions
HRESULT DAPI CabCBegin(
    __in_z LPCWSTR wzCab,
    __in_z LPCWSTR wzCabDir,
    __in DWORD dwMaxFiles,
    __in DWORD dwMaxSize,
    __in DWORD dwMaxThresh,
    __in COMPRESSION_TYPE ct,
    __out_bcount(CABC_HANDLE_BYTES) HANDLE *phContext
    );
HRESULT DAPI CabCNextCab(
    __in_bcount(CABC_HANDLE_BYTES) HANDLE hContext
    );
HRESULT DAPI CabCAddFile(
    __in_z LPCWSTR wzFile,
    __in_z_opt LPCWSTR wzToken,
    __in_opt PMSIFILEHASHINFO pmfHash,
    __in_bcount(CABC_HANDLE_BYTES) HANDLE hContext
    );
HRESULT DAPI CabCFinish(
    __in_bcount(CABC_HANDLE_BYTES) HANDLE hContext,
    __in_opt FileSplitCabNamesCallback fileSplitCabNamesCallback
    );
void DAPI CabCCancel(
    __in_bcount(CABC_HANDLE_BYTES) HANDLE hContext
    );

#ifdef __cplusplus
}
#endif


text:
from os.path import sep as PATH_SEP
from mock import patch
from pathlib import Path
from nose.tools import raises

from menpo.io.input.base import _pathlib_glob_for_pattern
from menpo.io.output.base import _parse_and_validate_extension

@patch('menpo.io.input.base.Path.glob')
def test_glob_parse_contains_file_glob_no_sort(mock_glob):
    path = '/tmp/test.*'
    mock_glob.return_value = ['/tmp/test.test']
    result = list(_pathlib_glob_for_pattern(path, sort=False))
    assert len(result) == 1
    mock_glob.assert_called_with('test.*')

@patch('menpo.io.input.base.Path.glob')
def test_glob_parse_contains_dir_glob_no_sort(mock_glob):
    path = '/tmp/**/*'
    mock_glob.return_value = ['/tmp/a/test.test', '/tmp/b/test.test']
    result = list(_pathlib_glob_for_pattern(path, sort=False))
    assert len(result) == 2
    mock_glob.assert_called_with('**/*'.replace('/', PATH_SEP))

@patch('menpo.io.input.base.Path.glob')
def test_glob_parse_sort(mock_glob):
    path = '/tmp/**/*'
    mock_glob.return_value = ['/tmp/b/test.test', '/tmp/a/test.test']
    result = list(_pathlib_glob_for_pattern(path, sort=True))
    assert len(result) == 2
    assert result[0] == mock_glob.return_value[1]
    mock_glob.assert_called_with('**/*'.replace('/', PATH_SEP))

def test_parse_extension_given_extension():
    filepath = 'test.jpg'
    extension = filepath[-4:]
    parsed_extension = _parse_and_validate_extension(Path(filepath), extension,
                                                     {'.jpg': None})
    assert parsed_extension == extension

def test_parse_extension_no_given_extension():
    filepath = 'test.jpg'
    extension = filepath[-4:]
    parsed_extension = _parse_and_validate_extension(Path(filepath), None,
                                                     {'.jpg': None})
    assert parsed_extension == extension

def test_parse_double_extension_given_extension():
    filepath = 'test.pkl.gz'
    extension = filepath[-7:]
    parsed_extension = _parse_and_validate_extension(Path(filepath), extension,
                                                     {'.pkl.gz': None})
    assert parsed_extension == extension

def test_parse_double_extension_no_extension():
    filepath = 'test.pkl.gz'
    extension = filepath[-7:]
    parsed_extension = _parse_and_validate_extension(Path(filepath), None,
                                                     {'.pkl.gz': None})
    assert parsed_extension == extension

def test_parse_period_in_name_given_extension():
    filepath = 'test.1.jpg'
    extension = filepath[-4:]
    parsed_extension = _parse_and_validate_extension(Path(filepath), extension,
                                                     {'.jpg': None})
    assert parsed_extension == extension

def test_parse_period_in_name_no_extension():
    filepath = 'test.1.jpg'
    extension = filepath[-4:]
    parsed_extension = _parse_and_validate_extension(Path(filepath), None,
                                                     {'.jpg': None})
    assert parsed_extension == extension

def test_parse_period_in_name_double_given_extension():
    filepath = 'test.1.pkl.gz'
    extension = filepath[-7:]
    parsed_extension = _parse_and_validate_extension(Path(filepath), extension,
                                                     {'.pkl.gz': None})
    assert parsed_extension == extension

def test_parse_period_in_name_double_no_extension():
    filepath = 'test.1.pkl.gz'
    extension = filepath[-7:]
    parsed_extension = _parse_and_validate_extension(Path(filepath), extension,
                                                     {'.pkl.gz': None})
    assert parsed_extension == extension

@raises(ValueError)
def test_parse_unknown_extension_raises_ValueError():
    filepath = 'test.1.fake'
    _parse_and_validate_extension(Path(filepath), None, {'.jpg': None})

@raises(ValueError)
def test_parse_mot_matching_extension_raises_ValueError():
    filepath = 'test.jpg2'
    _parse_and_validate_extension(Path(filepath), '.jpg', {'.jpg': None})


text:
<?php

if( !defined( 'DVWA_WEB_PAGE_TO_ROOT' ) ) {
	define( 'DVWA System error- WEB_PAGE_TO_ROOT undefined' );
	exit;
}

define( 'DVWA_WEB_ROOT_TO_PHPIDS', 'external/phpids/'.dvwaPhpIdsVersionGet().'/' );
define( 'DVWA_WEB_PAGE_TO_PHPIDS', DVWA_WEB_PAGE_TO_ROOT.DVWA_WEB_ROOT_TO_PHPIDS );

// Add PHPIDS to include path
set_include_path( get_include_path().PATH_SEPARATOR.DVWA_WEB_PAGE_TO_PHPIDS.'lib/' );

require_once 'IDS/Init.php';

function dvwaPhpIdsVersionGet() {
	return '0.6';
}

// PHPIDS Log parsing function
function dvwaReadIdsLog() {

	$file_array = file(DVWA_WEB_PAGE_TO_PHPIDS_LOG);

	$data = '';

	foreach ($file_array as $line_number => $line){
		$line = explode(",", $line);
		$line = str_replace("\""," ",$line);

		$datetime = $line[1];
		$vulnerability = $line[3];
		$variable = urldecode($line[4]);
		$request = urldecode($line[5]);
		$ip = $line[6];

		$data .= "
Date/Time: " . $datetime . "
Vulnerability: " . $vulnerability . "
Request: " . htmlspecialchars($request) . "
Variable: " . htmlspecialchars($variable) . "
IP: " . $ip . "
";
	}

return $data;
}

// Clear PHPIDS log
function dvwaClearIdsLog()	{
	if (isset($_GET['clear_log'])) {
		$fp = fopen(DVWA_WEB_PAGE_TO_PHPIDS_LOG, w);
		fclose($fp);
		dvwaMessagePush( "PHPIDS log cleared" );
		dvwaPageReload();
	}
}

// Main PHPIDS function
function dvwaPhpIdsTrap() {
	try {
		$request = array(
			'REQUEST' => $_REQUEST,
			'GET' => $_GET,
			'POST' => $_POST,
			'COOKIE' => $_COOKIE
		);

		$init = IDS_Init::init( DVWA_WEB_PAGE_TO_PHPIDS.'lib/IDS/Config/Config.ini' );

		$init->config['General']['base_path'] = DVWA_WEB_PAGE_TO_PHPIDS.'lib/IDS/';
		$init->config['General']['use_base_path'] = true;
		$init->config['Caching']['caching'] = 'none';

		// 2. Initiate the PHPIDS and fetch the results
		$ids = new IDS_Monitor( $request, $init );
		$result = $ids->run();

		if (!$result->isEmpty()) {
			require_once 'IDS/Log/File.php';
			require_once 'IDS/Log/Composite.php';

			$compositeLog = new IDS_Log_Composite();
			$compositeLog->addLogger(IDS_Log_File::getInstance($init));

			$compositeLog->execute($result);

			echo 'Hacking attempt detected and logged.';

			//echo $result;
			exit;
		}
	} catch (Exception $e) {
		/*
		* something went terribly wrong - maybe the
		* filter rules weren't found?
		*/
		printf(
			'An error occured: %s',
			$e->getMessage()
		);
	}
}

?>


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport"
          content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" type="text/css" href="stylesheets/lib/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="stylesheets/lib/bootstrap-select.min.css">
    <link rel="stylesheet" type="text/css" href="stylesheets/page.css">
    <link rel="shortcut icon" href="images/favicon.ico" type="image/icon">

    <title>RCON Web Admin by BrainFooLong</title>

    <button type="button" class="hamburger is-closed"
            data-toggle="offcanvas">

    </button>

                Github

                Issues

                                 RCON Web Admin v
                                 by BrainFooLong

                    <button type="button" class="close" data-dismiss="modal">×</button>

                    <button type="button" class="btn btn-default" data-translate="modal.ok"></button>

                    <button type="button" class="close" data-dismiss="modal">×</button>

                    <button type="button" class="btn btn-primary" data-translate="modal.accept"></button>
                    <button type="button" class="btn btn-default" data-translate="modal.cancel"></button>

                    <button type="button" class="close" data-dismiss="modal">×</button>

                    <input type="text" class="form-control">

                    <button type="button" class="btn btn-primary" data-translate="modal.accept"></button>
                    <button type="button" class="btn btn-default" data-translate="modal.cancel"></button>


text:
package com.lilarcor.portfolio.features.home;

import android.test.ActivityInstrumentationTestCase2;

import com.lilarcor.portfolio.R;
import com.lilarcor.portfolio.features.home.ui.HomeActivity;
import com.lilarcor.portfolio.testhelpers.EspressoHelper;

/**
 * Created by Marcel Braghetto on 11/07/15.
 *
 * Test suite to verify the UI behaviour of the home feature.
 */
public class HomeFeatureTest extends ActivityInstrumentationTestCase2<HomeActivity> {
    public HomeFeatureTest() {
        super(HomeActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        getActivity();
    }

    public void testContentTitle() {
        EspressoHelper.verifyTextWithId(R.id.home_content_title, "My Nanodegree Apps!");
    }

    public void testSpotifyStreamerButton() {
        EspressoHelper.verifyTextWithId(R.id.home_spotify_streamer_button, "Spotify Streamer");
        EspressoHelper.clickViewWithId(R.id.home_spotify_streamer_button);
        EspressoHelper.verifyToastMessage("This button will launch my Spotify streamer app!");
    }

    public void testScoresAppButton() {
        EspressoHelper.verifyTextWithId(R.id.home_scores_app_button, "Scores App");
        EspressoHelper.clickViewWithId(R.id.home_scores_app_button);
        EspressoHelper.verifyToastMessage("This button will launch my scores app!");
    }

    public void testLibraryAppButton() {
        EspressoHelper.verifyTextWithId(R.id.home_library_app_button, "Library App");
        EspressoHelper.clickViewWithId(R.id.home_library_app_button);
        EspressoHelper.verifyToastMessage("This button will launch my library app!");
    }

    public void testBuildItBiggerButton() {
        EspressoHelper.verifyTextWithId(R.id.home_build_it_bigger_button, "Build It Bigger");
        EspressoHelper.clickViewWithId(R.id.home_build_it_bigger_button);
        EspressoHelper.verifyToastMessage("This button will launch my 'Build It Bigger' app!");
    }

    public void testXYZReaderButton() {
        EspressoHelper.verifyTextWithId(R.id.home_xyz_reader_button, "XYZ Reader");
        EspressoHelper.clickViewWithId(R.id.home_xyz_reader_button);
        EspressoHelper.verifyToastMessage("This button will launch my 'XYZ Reader' app!");
    }

    public void testCapstoneButton() {
        EspressoHelper.verifyTextWithId(R.id.home_capstone_button, "Capstone");
        EspressoHelper.clickViewWithId(R.id.home_capstone_button);
        EspressoHelper.verifyToastMessage("This button will launch my capstone app!");
    }
}


text:
import Vue from 'vue';
import VueApollo from 'vue-apollo';
import { uniqueId } from 'lodash';
import { defaultDataIdFromObject } from 'apollo-cache-inmemory';
import createDefaultClient from '~/lib/graphql';
import activeDiscussionQuery from './graphql/queries/active_discussion.query.graphql';
import typeDefs from './graphql/typedefs.graphql';

Vue.use(VueApollo);

const resolvers = {
  Mutation: {
    updateActiveDiscussion: (_, { id = null, source }, { cache }) => {
      const data = cache.readQuery({ query: activeDiscussionQuery });
      data.activeDiscussion = {
        __typename: 'ActiveDiscussion',
        id,
        source,
      };
      cache.writeQuery({ query: activeDiscussionQuery, data });
    },
  },
};

const defaultClient = createDefaultClient(
  resolvers,
  // This config is added temporarily to resolve an issue with duplicate design IDs.
  // Should be removed as soon as https://gitlab.com/gitlab-org/gitlab/issues/13495 is resolved
  {
    cacheConfig: {
      dataIdFromObject: object => {
        // eslint-disable-next-line no-underscore-dangle, @gitlab/require-i18n-strings
        if (object.__typename === 'Design') {
          return object.id && object.image ? `${object.id}-${object.image}` : uniqueId();
        }
        return defaultDataIdFromObject(object);
      },
    },
    typeDefs,
  },
);

export default new VueApollo({
  defaultClient,
});


text:
package com.alibaba.dubbo.rpc.protocol.hessian;

import com.caucho.hessian.client.HessianConnection;
import com.caucho.hessian.client.HessianConnectionFactory;
import com.caucho.hessian.client.HessianProxyFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import java.io.IOException;
import java.net.URL;

/**
 * HttpClientConnectionFactory
 */
public class HttpClientConnectionFactory implements HessianConnectionFactory {

    private final HttpClient httpClient = new DefaultHttpClient();

    public void setHessianProxyFactory(HessianProxyFactory factory) {
        HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), (int) factory.getConnectTimeout());
        HttpConnectionParams.setSoTimeout(httpClient.getParams(), (int) factory.getReadTimeout());
    }

    public HessianConnection open(URL url) throws IOException {
        return new HttpClientConnection(httpClient, url);
    }

}


text:
/****************************************************************************************
 * Licensed under the Apache License, Version 2.0 (the "License");                      *
 * you may not use this file except in compliance with the License.                     *
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0   *
 * Unless required by applicable law or agreed to in writing, software                  *
 * distributed under the License is distributed on an "AS IS" BASIS,                    *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.             *
 * See the License for the specific language governing permissions and                  *
 * limitations under the License.                                                       *
 ****************************************************************************************/

/****************************************************************************************
 * Licensed under the Apache License, Version 2.0 (the "License");                      *
 * you may not use this file except in compliance with the License.                     *
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0   *
 * Unless required by applicable law or agreed to in writing, software                  *
 * distributed under the License is distributed on an "AS IS" BASIS,                    *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.             *
 * See the License for the specific language governing permissions and                  *
 * limitations under the License.                                                       *
 ****************************************************************************************/

package br.com.wsssoftware.materialtutorial.target;

import android.graphics.Point;
import android.graphics.Rect;
import android.view.View;

/**
 * Created by mertsimsek on 25/01/16.
 */
public interface Target {
    /**
     * Returns center point of target.
     * We can get x and y coordinates using
     * point object
     * @return
     */
    Point getPoint();

    /**
     * Returns Rectangle points of target view
     * @return
     */
    Rect getRect();

    /**
     * return target view
     * @return
     */
    View getView();
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>All Classes (grpc-netty 0.1.0-SNAPSHOT API)</title>
<meta name="date" content="2015-03-18">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

Http2Negotiator

Http2Negotiator.Negotiation

NegotiationType

NettyChannelBuilder

NettyServer

NettyServerBuilder


text:
typedef enum tagEType {
    cNothing,
    cAddress,
    cArray,
    cBoolean,
    cBytes,
    cDictionary,
    cNumber,
    cObject,
    cString,
    cOther,
} CellType;

typedef struct tagTCell {
    Number number;
    struct tagTCell *address;
    struct tagTArray *array;
    struct tagTDictionary *dictionary;
    struct tagTObject *object;
    struct tagTString *string;
    enum tagEType type;
    BOOL boolean;
    void *other;
} Cell;

Cell *cell_createAddressCell(Cell *a);
Cell *cell_createArrayCell(size_t elements);
Cell *cell_createDictionaryCell(void);
Cell *cell_createStringCell(size_t size);
Cell *cell_createOtherCell(void *ptr);

Cell *cell_newCell(void);
Cell *cell_newCellType(CellType t);

void cell_ensureAddress(Cell *a);
void cell_ensureArray(Cell *a);
void cell_ensureBoolean(Cell *b);
void cell_ensureBytes(Cell *b);
void cell_ensureDictionary(Cell *d);
void cell_ensureNumber(Cell *n);
void cell_ensureObject(Cell *o);
void cell_ensureOther(Cell *o);
void cell_ensureString(Cell *s);

void cell_clearCell(Cell *c);
void cell_freeCell(Cell *c);
void cell_resetCell(Cell *c);

Cell *cell_fromAddress(Cell *c);
Cell *cell_fromBoolean(BOOL b);
Cell *cell_fromBytes(struct tagTString *b);
Cell *cell_fromDictionary(struct tagTDictionary *d);
Cell *cell_fromPointer(void *p);
Cell *cell_fromNumber(Number n);
Cell *cell_fromObject(struct tagTObject *o);
Cell *cell_fromCString(const char *s);
Cell *cell_fromString(struct tagTString *s);
Cell *cell_fromStringLength(const char *s, int64_t length);
Cell *cell_fromOther(void *p);
Cell *cell_fromCell(const Cell *c);

void cell_copyCell(Cell *dest, const Cell *source);

int32_t cell_compareCell(const Cell *s, const Cell *d);

void cell_setString(Cell *c, struct tagTString *s);
void cell_setNumber(Cell *c, Number n);
void cell_setBoolean(Cell *c, BOOL b);

struct tagTString *cell_toString(Cell *c);

Cell *cell_arrayIndexForRead(Cell* c, size_t i);
Cell *cell_arrayIndexForWrite(Cell *c, size_t i);
void cell_arrayAppendElement(Cell *c, const Cell e);
void cell_arrayAppendElementPointer(Cell *c, Cell *e);
BOOL cell_arrayElementExists(const Cell *a, const Cell *e);

Cell *cell_dictionaryIndexForWrite(Cell *c, struct tagTString *key);
Cell *cell_dictionaryIndexForRead(Cell *c, struct tagTString *key);

#endif


text:
namespace Microsoft.ApplicationInsights.AspNetCore.Logging
{
    using Microsoft.Extensions.Logging;

    ///
    /// Class to control default debug logger and disable it if logger was added to <see cref="ILoggerFactory"/> explicetely.
    ///
    internal class DebugLoggerControl
    {
        public DebugLoggerControl()
        {
            EnableDebugLogger = true;
        }

        ///
        /// This property gets set to false by <see cref="ApplicationInsightsLoggerFactoryExtensions.AddApplicationInsights"/>.
        ///
        public bool EnableDebugLogger { get; set; }
    }
}


text:
"""Contains the logic for `aq ping`."""

from aquilon.worker.broker import BrokerCommand  # pylint: disable=W0611

class CommandPing(BrokerCommand):

    requires_transaction = False
    requires_readonly = True
    requires_azcheck = False
    requires_format = True
    defer_to_thread = False

    def render(self, **arguments):
        return "pong"


text:
"""
    This code is created with reference to torchvision/utils.py.

    Modify: torch.tensor -> jax.numpy.DeviceArray

    If you want to know about this file in detail, please visit the original code:
        https://github.com/pytorch/vision/blob/master/torchvision/utils.py
"""
import math

import jax.numpy as jnp
import numpy as np
from PIL import Image

def save_image(ndarray, fp, nrow=8, padding=2, pad_value=0.0, format=None):
    """Make a grid of images and Save it into an image file.
  Args:
    ndarray (array_like): 4D mini-batch images of shape (B x H x W x C)
    fp - A filename(string) or file object
    nrow (int, optional): Number of images displayed in each row of the grid.
      The final grid size is ``(B / nrow, nrow)``. Default: ``8``.
    padding (int, optional): amount of padding. Default: ``2``.
    scale_each (bool, optional): If ``True``, scale each image in the batch of
      images separately rather than the (min, max) over all images. Default: ``False``.
    pad_value (float, optional): Value for the padded pixels. Default: ``0``.
    format(Optional):  If omitted, the format to use is determined from the filename extension.
      If a file object was used instead of a filename, this parameter should always be used.
  """
    if not (isinstance(ndarray, jnp.ndarray) or
        (isinstance(ndarray, list) and all(isinstance(t, jnp.ndarray) for t in ndarray))):
        raise TypeError(f'array_like of tensors expected, got {type(ndarray)}')

    ndarray = jnp.asarray(ndarray)

    if ndarray.ndim == 4 and ndarray.shape[-1] == 1:  # single-channel images
        ndarray = jnp.concatenate((ndarray, ndarray, ndarray), -1)

    # make the mini-batch of images into a grid
    nmaps = ndarray.shape[0]
    xmaps = min(nrow, nmaps)
    ymaps = int(math.ceil(float(nmaps) / xmaps))
    height, width = int(ndarray.shape[1] + padding), int(ndarray.shape[2] + padding)
    num_channels = ndarray.shape[3]
    grid = jnp.full((height * ymaps + padding, width * xmaps + padding, num_channels), pad_value).astype(jnp.float32)
    k = 0
    for y in range(ymaps):
      for x in range(xmaps):
        if k >= nmaps:
          break
        grid = grid.at[y * height + padding:(y + 1) * height,
                       x * width + padding:(x + 1) * width].set(ndarray[k])
        k = k + 1

    # Add 0.5 after unnormalizing to [0, 255] to round to nearest integer
    ndarr = np.array(jnp.clip(grid * 255.0 + 0.5, 0, 255).astype(jnp.uint8))
    im = Image.fromarray(ndarr.copy())
    im.save(fp, format=format)


text:
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * appProdUrlMatcher
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class appProdUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);
        $context = $this->context;
        $request = $this->request;

        if (0 === strpos($pathinfo, '/trivial')) {
            // homepage
            if (rtrim($pathinfo, '/') === '/trivial') {
                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'homepage');
                }

                return array (  '_controller' => 'Acme\\TrivialWarsServerBundle\\Controller\\TrivialController::indexAction',  '_route' => 'homepage',);
            }

            // player
            if ($pathinfo === '/trivial/player') {
                return array (  '_controller' => 'Acme\\TrivialWarsServerBundle\\Controller\\UserController::playerAction',  '_route' => 'player',);
            }

            // board
            if ($pathinfo === '/trivial/game') {
                return array (  '_controller' => 'Acme\\TrivialWarsServerBundle\\Controller\\TrivialController::tableroAction',  '_route' => 'board',);
            }

            // register
            if ($pathinfo === '/trivial/register') {
                return array (  '_controller' => 'Acme\\TrivialWarsServerBundle\\Controller\\TrivialController::registerAction',  '_route' => 'register',);
            }

            if (0 === strpos($pathinfo, '/trivial/user')) {
                // user
                if ($pathinfo === '/trivial/user') {
                    return array (  '_controller' => 'Acme\\TrivialWarsServerBundle\\Controller\\UsuarioController::indexAction',  '_route' => 'user',);
                }

                // user_show
                if (0 === strpos($pathinfo, '/trivial/user/show') && preg_match('#^/trivial/user/show/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'user_show')), array (  '_controller' => 'Acme\\TrivialWarsServerBundle\\Controller\\UsuarioController::showAction',));
                }

            }

            // user_login
            if ($pathinfo === '/trivial/pregunta/id') {
                return array (  '_controller' => 'Acme\\TrivialWarsServerBundle\\Controller\\PreguntaController::indexAction',  '_route' => 'user_login',);
            }

        }

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}


text:
#import "JCNotificationBannerPresenterIOSStyle.h"
#import "JCNotificationBannerPresenter_Private.h"
#import "JCNotificationBannerWindow.h"
#import "JCNotificationBannerViewIOSStyle.h"
#import "JCNotificationBannerView.h"
#import "JCNotificationBannerViewController.h"

@implementation JCNotificationBannerPresenterIOSStyle

- (void) presentNotification:(JCNotificationBanner *)notification
                    inWindow:(JCNotificationBannerWindow*)window
                    finished:(JCNotificationBannerPresenterFinishedBlock)finished {
  JCNotificationBannerView* banner = [self newBannerViewForNotification:notification];

  JCNotificationBannerViewController* bannerViewController = [JCNotificationBannerViewController new];
  window.rootViewController = bannerViewController;
  UIView* originalControllerView = bannerViewController.view;

  UIView* containerView = [self newContainerViewForNotification:notification];
  [containerView addSubview:banner];
  bannerViewController.view = containerView;

  window.bannerView = banner;

  containerView.bounds = originalControllerView.bounds;
  containerView.transform = originalControllerView.transform;
  [banner getCurrentPresentingStateAndAtomicallySetPresentingState:YES];

  CGSize statusBarSize = [[UIApplication sharedApplication] statusBarFrame].size;
  CGFloat width = 320.0;
  CGFloat height = 60.0;
  CGFloat x = (MAX(statusBarSize.width, statusBarSize.height) - width) / 2.0;
  CGFloat y = -60.0;
  banner.frame = CGRectMake(x, y, width, height);

  JCNotificationBannerTapHandlingBlock originalTapHandler = notification.tapHandler;
  JCNotificationBannerTapHandlingBlock wrappingTapHandler = ^{
    if ([banner getCurrentPresentingStateAndAtomicallySetPresentingState:NO]) {
      if (originalTapHandler) {
        originalTapHandler();
      }

      [banner removeFromSuperview];
      finished();
    }
    // Break the retain cycle
    notification.tapHandler = nil;
  };
  notification.tapHandler = wrappingTapHandler;

  double startOpacity = 1.0;
  double endOpacity = 1.0;
  double animationDuration = 0.5;

  CGRect bannerFrameAfterTransition = banner.frame;
  bannerFrameAfterTransition.origin.y = MIN(statusBarSize.width, statusBarSize.height);
  UIImage* image = [self captureWindowPartWithRect:bannerFrameAfterTransition];

  // Prepare view transform
  CALayer* layer = banner.layer;
  banner.alpha = startOpacity;
  banner.frame = CGRectOffset(banner.frame, 0.0, banner.frame.size.height);
  banner.alpha = endOpacity;
  layer.anchorPointZ = 0.5f * banner.frame.size.height;
  [self rotateLayer:layer fromAngle:-90.0 toAngle:0.0 duration:animationDuration onCompleted:^(){}];

  // Add image of background to layer.
  CALayer* imageLayer = [CALayer layer];
  imageLayer.frame = banner.frame;
  imageLayer.anchorPointZ = 0.5f * banner.frame.size.height;
  imageLayer.contents = (id)image.CGImage;
  imageLayer.shadowOffset = CGSizeMake(0.0, 1.0);
  imageLayer.shadowColor = [UIColor darkGrayColor].CGColor;
  imageLayer.shadowRadius = 3.0;
  imageLayer.shadowOpacity = 0.8;
  [self rotateLayer:imageLayer fromAngle:0.0 toAngle:90.0 duration:animationDuration onCompleted:^(){} ];
  [containerView.layer addSublayer:imageLayer];

  // On timeout, slide it up while fading it out.
  if (notification.timeout > 0.0) {
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, notification.timeout * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
      // Add image of background to layer.
      CALayer* imageLayer = [CALayer layer];
      imageLayer.frame =  banner.frame;
      imageLayer.anchorPointZ = 0.5f * banner.frame.size.height;
      imageLayer.contents = (id)image.CGImage;
      imageLayer.shadowOffset = CGSizeMake(0, 1);
      imageLayer.shadowColor = [UIColor darkGrayColor].CGColor;
      imageLayer.shadowRadius = 3.0;
      imageLayer.shadowOpacity = 0.8;
      [self rotateLayer:imageLayer fromAngle:-90.0 toAngle:0.0 duration:animationDuration onCompleted:^(){} ];
      [[containerView layer] addSublayer:imageLayer];

      CALayer* layer = [banner layer];
      [self rotateLayer:layer fromAngle:0.0 toAngle:90.0 duration:animationDuration onCompleted:^(){
        if ([banner getCurrentPresentingStateAndAtomicallySetPresentingState:NO]) {
          [banner removeFromSuperview];
          [containerView removeFromSuperview];
          finished();
        }
        // Break the retain cycle
        notification.tapHandler = nil;
      }];
    });
  }
}

#pragma mark - View helpers

- (UIView*) newContainerViewForNotification:(JCNotificationBanner*)notification {
  UIView* view = [super newContainerViewForNotification:notification];
  view.autoresizesSubviews = YES;
  return view;
}

- (JCNotificationBannerView*) newBannerViewForNotification:(JCNotificationBanner*)notification {
  JCNotificationBannerView* view = [[JCNotificationBannerViewIOSStyle alloc]
                                    initWithNotification:notification];
  view.userInteractionEnabled = YES;
  view.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin
  | UIViewAutoresizingFlexibleLeftMargin
  | UIViewAutoresizingFlexibleRightMargin;
  return view;
}

#pragma mark - Screenshot

/**
 * @returns part of the keyWindow screenshot rotated by 180 degrees.
 */
- (UIImage*) captureWindowPartWithRect:(CGRect)rect {
  UIWindow* keyWindow = [[UIApplication sharedApplication] keyWindow];

  CGRect firstCaptureRect = keyWindow.bounds;

  UIGraphicsBeginImageContextWithOptions(firstCaptureRect.size, YES, 0.0);
  CGContextRef context = UIGraphicsGetCurrentContext();
  [keyWindow.layer renderInContext:context];
  UIImage* capturedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  CGRect contentRectToCrop = rect;
  CGFloat rotationNeeded = 0;
  CGRect originalRect = rect;
  switch ([UIApplication sharedApplication].statusBarOrientation) {
    case UIInterfaceOrientationLandscapeLeft:
      rotationNeeded = 90;
      contentRectToCrop.origin.x = originalRect.origin.y;
      contentRectToCrop.origin.y = keyWindow.bounds.size.height - originalRect.origin.x - originalRect.size.width;
      contentRectToCrop.size.width = originalRect.size.height;
      contentRectToCrop.size.height = originalRect.size.width;
      break;

    case UIInterfaceOrientationLandscapeRight:
      rotationNeeded = -90;
      contentRectToCrop.origin.x = keyWindow.bounds.size.width - originalRect.origin.y - originalRect.size.height;
      contentRectToCrop.origin.y = keyWindow.bounds.size.height - originalRect.origin.x - originalRect.size.width ;
      contentRectToCrop.size.width = originalRect.size.height;
      contentRectToCrop.size.height = originalRect.size.width;
      break;

    case UIInterfaceOrientationPortrait:
    case UIInterfaceOrientationUnknown:
      break;

    case UIInterfaceOrientationPortraitUpsideDown:
      rotationNeeded = 180;
      contentRectToCrop.origin.x = originalRect.origin.x;
      contentRectToCrop.origin.y = keyWindow.bounds.size.height - originalRect.origin.y - originalRect.size.height;
      contentRectToCrop.size.width = originalRect.size.width;
      contentRectToCrop.size.height = originalRect.size.height;
      break;
  }

  contentRectToCrop.origin.x *= capturedImage.scale;
  contentRectToCrop.origin.y *= capturedImage.scale;
  contentRectToCrop.size.width *= capturedImage.scale;
  contentRectToCrop.size.height *= capturedImage.scale;

  CGImageRef imageRef = CGImageCreateWithImageInRect([capturedImage CGImage], contentRectToCrop);
  UIImage* croppedImage = [UIImage imageWithCGImage:imageRef scale:capturedImage.scale orientation: UIImageOrientationUp];
  CGImageRelease(imageRef);

  if (rotationNeeded) {
    croppedImage = [self.class rotateImage:croppedImage byDegrees:rotationNeeded];
  }

  return croppedImage;
}

// -----------------------------------------------------------------------
// UIImage Extensions for preparing screenshots under banner by HardyMacia
// (Catamount Software).
// http://www.catamount.com/forums/viewtopic.php?f=21&t=967

CGFloat DegreesToRadians(CGFloat degrees) { return degrees * M_PI / 180.0; };
CGFloat RadiansToDegrees(CGFloat radians) { return radians * 180.0 / M_PI; };

+ (UIImage*) rotateImage:(UIImage*)image byDegrees:(CGFloat)degrees {
  // Calculate the size of the rotated view's containing box for our drawing space
  UIView* rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height)];
  CGAffineTransform transform = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
  rotatedViewBox.transform = transform;
  CGSize rotatedSize = rotatedViewBox.frame.size;

  // Create the bitmap context
  UIGraphicsBeginImageContext(rotatedSize);
  CGContextRef bitmap = UIGraphicsGetCurrentContext();

  // Move the origin to the middle of the image so we will rotate and scale around the center.
  CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

  // Rotate the image context
  CGContextRotateCTM(bitmap, DegreesToRadians(degrees));

  // Now, draw the rotated/scaled image into the context
  CGContextScaleCTM(bitmap, 1.0, -1.0);
  CGRect imageRect = CGRectMake(-image.size.width / 2.0, -image.size.height / 2.0, image.size.width, image.size.height);
  CGContextDrawImage(bitmap, imageRect, image.CGImage);

  UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return newImage;
}

// -----------------------------------------------------------------------

- (void) rotateLayer:(CALayer*)imageLayer
           fromAngle:(CGFloat)fromAngle
             toAngle:(CGFloat)toAngle
            duration:(CFTimeInterval)duration
         onCompleted:(void (^)())onCompletedBlock {
  CGFloat fromInRadians = fromAngle * M_PI / 180.0f;
  CGFloat toInRadians = toAngle * M_PI / 180.0f;

  // Create animation that rotates by to the end rotation.
  CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];
  animation.delegate = self;
  animation.duration = duration;
  animation.fromValue = @(fromInRadians);
  animation.toValue = @(toInRadians);
  animation.fillMode = kCAFillModeForwards;
  animation.removedOnCompletion = NO;
  [animation setValue:[onCompletedBlock copy] forKey:@"onCompleted"];
  [imageLayer addAnimation:animation forKey:@"transform.rotation.x"];
}

- (void) animationDidStop:(CAAnimation*)animation finished:(BOOL)finished {
  if (finished) {
    void(^onCompletedBlock)() = [animation valueForKey:@"onCompleted"];
    if (onCompletedBlock)
      onCompletedBlock();
  }
  [animation setValue:nil forKey:@"onCompleted"];
}

@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. R. Soc. Edinb. 24: 442 (1867)

#### Original name
Phymatopsis dubia Linds., 1867

### Remarks
null


text:
<!DOCTYPE html>
<html>
    <head>
        <style>
            .hide {
                display: none;
            }

            .show {
                display: block;
            }
        </style>
        <script type="text/javascript" src="chrome_ex_oauthsimple.js"></script>
        <script type="text/javascript" src="chrome_ex_oauth.js"></script>
        <script type="text/javascript" src="onload.js"></script>
        <!--<script src="popup.js"></script>-->
    </head>
    <body>
        <div id="signInButton">
            <input type="button" value="Sign In" onclick="signIn()" />
        </div>
    </body>
</html>


text:
import os

import Aggregator
from SmellDetector import Constants as CONSTS, Analyzer

root = CONSTS.REPO_ROOT
print("Initiating Analyzer...")
totalRepos = len(os.listdir(root))
currentItem = 0
for item in os.listdir(root):
    currentFolder = os.path.join(root, item)
    #print("Anlyzing: " + currentFolder)
    if not os.path.isfile(currentFolder):
        Analyzer.analyze(currentFolder, item)
    currentItem += 1
    print (str("{:.2f}".format(float(currentItem * 100)/float(totalRepos))) + "% analysis done.")
print("Analyzer - Done.")

print("Initiating metrics and smells aggregator...")
aggregatedFile = open(root + "/" + CONSTS.AGGREGATOR_FILE, 'wt')
aggregatedFile.write(CONSTS.CSV_HEADER)
for item in os.listdir(root):
    currentFolder = os.path.join(root, item)
    if not os.path.isfile(currentFolder):
        Aggregator.aggregate(currentFolder, item, aggregatedFile)
aggregatedFile.close()
print("Metrics and smells aggregator - Done.")


text:
import time
from selenium.webdriver.common.keys import Keys
from random import randint
from methods import generators
import os.path
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC

def login_to_admin(wd):
    wd.get("http://localhost/litecart/admin/")
    wd.find_element_by_name("username").send_keys("admin")
    wd.find_element_by_name("password").send_keys("admin")
    wd.find_element_by_name("login").click()
    assert not wd.current_url.endswith("/login.php")

def logout_from_admin(wd):
    wd.find_element_by_css_selector("i.fa.fa-sign-out").click()
    assert wd.current_url.endswith("/login.php")

def check_left_menu_elements(wd):
    menu_list = wd.find_elements_by_css_selector("li#app-")
    for i in range(0, len(menu_list)):
        wd.find_elements_by_css_selector("li#app-")[i].click()
        assert len(wd.find_elements_by_css_selector("td#content h1")) == 1
        submenu_list = wd.find_elements_by_css_selector("li#app-")[i].find_elements_by_css_selector("li")
        if len(submenu_list)>0:
            check_left_sumbenu_elements(wd, i, len(submenu_list))

def check_left_sumbenu_elements(wd, i, submenu_length):
    for j in range(0, submenu_length):
        wd.find_elements_by_css_selector("li#app-")[i].find_elements_by_css_selector("li")[j].click()
        assert len(wd.find_elements_by_css_selector("td#content h1")) == 1

def open_main_page(wd):
    wd.get("http://localhost/litecart/")

def check_stickers_presence(wd):
    products_list = wd.find_elements_by_css_selector("li.product")
    for product in products_list:
        assert len(product.find_elements_by_css_selector("div[class ^= sticker]")) == 1

def check_countries_abc(wd):
    wd.get("http://localhost/litecart/admin/?app=countries&doc=countries")
    country_list = wd.find_elements_by_css_selector("tr.row")
    countries = []
    countries_with_several_zones = []
    for row in country_list:
        countries.append(row.find_element_by_css_selector("a").text)
        if row.find_elements_by_css_selector("td")[5].text != "0":
            countries_with_several_zones.append(country_list.index(row))
    assert countries == sorted(countries)
    check_zones_abc_in_country(wd, countries_with_several_zones)

def check_zones_abc_in_country(wd, countries_with_several_zones):
    for country_list_number in countries_with_several_zones:
        wd.get("http://localhost/litecart/admin/?app=countries&doc=countries")
        country = wd.find_elements_by_css_selector("tr.row")[country_list_number]
        country.find_element_by_css_selector("a").click()
        zones_list = wd.find_elements_by_css_selector("table#table-zones tr")
        zones_list.pop(0)
        zones_list.pop()
        zones = []
        for row in zones_list:
            zones.append(row.find_elements_by_css_selector("td")[2].text)
        assert zones == sorted(zones)

def check_zones_abc(wd):
    wd.get("http://localhost/litecart/admin/?app=geo_zones&doc=geo_zones")
    zones_list = wd.find_elements_by_css_selector("tr.row")
    for i in range(0, len(zones_list)):
        wd.get("http://localhost/litecart/admin/?app=geo_zones&doc=geo_zones")
        wd.find_elements_by_css_selector("tr.row")[i].find_element_by_css_selector("a").click()
        zones_list = wd.find_elements_by_css_selector("table#table-zones tr")
        zones_list.pop(0)
        zones_list.pop()
        zones = []
        country_in_header = wd.find_element_by_css_selector("input[name=name]").get_attribute("value")
        for row in zones_list:
            country_in_list = row.find_elements_by_css_selector("td")[1].find_element_by_css_selector("span.selection").text
            #This part defines whether the list describes zones in country or countries in area (such as European Union)
            if country_in_list in country_in_header:
                zone_name = row.find_elements_by_css_selector("td")[2].find_element_by_css_selector("option[selected = selected]").text
                zones.append(zone_name)
            else:
                zones.append(country_in_list)
        assert zones == sorted(zones)

def check_product_page(wd):
    open_main_page(wd)
    product = wd.find_element_by_css_selector("div#box-campaigns li.product")

    #product name
    mp_product_name = product.find_element_by_css_selector("div.name").text

    #regular price properties obtaining from main page
    regular_price = product.find_element_by_css_selector("s.regular-price")
    main_page_regular_price = regular_price.text
    regular_price_color = regular_price.value_of_css_property("color")
    regular_price_color_RGB = define_RGB_values(regular_price_color)
    regular_price_font_size = regular_price.value_of_css_property("font-size")
    regular_price_font_size_float = define_font_size(regular_price_font_size)
    regular_price_text_decoration = regular_price.value_of_css_property("text-decoration")

    #action price properties obtaining from main page
    action_price = product.find_element_by_css_selector("strong.campaign-price")
    main_page_action_price = action_price.text
    action_price_color = action_price.value_of_css_property("color")
    action_price_color_RGB = define_RGB_values(action_price_color)
    action_price_font_size = action_price.value_of_css_property("font-size")
    action_price_font_size_float = define_font_size(action_price_font_size)
    action_price_font_weight = action_price.value_of_css_property("font-weight")

    #main page properties verification
    regular_price_color_check(regular_price_color_RGB)
    action_price_color_check(action_price_color_RGB)
    assert action_price_font_size_float > regular_price_font_size_float
    assert regular_price_text_decoration == "line-through"
    assert action_price_font_weight == "bold" or action_price_font_weight == "900"

    #open product page
    product.click()
    # product name
    product_name = wd.find_element_by_css_selector("h1.title").text
    # regular price properties obtaining from product page
    product_regular_price = wd.find_element_by_css_selector("s.regular-price")
    product_page_regular_price = product_regular_price.text
    product_regular_price_color = product_regular_price.value_of_css_property("color")
    product_regular_price_color_RGB = define_RGB_values(product_regular_price_color)
    product_regular_price_font_size = product_regular_price.value_of_css_property("font-size")
    product_regular_price_font_size_float = define_font_size(product_regular_price_font_size)
    product_regular_price_text_decoration = product_regular_price.value_of_css_property("text-decoration")
    # action price properties obtaining from product page
    product_action_price = wd.find_element_by_css_selector("strong.campaign-price")
    product_page_action_price = product_action_price.text
    product_action_price_color = product_action_price.value_of_css_property("color")
    product_action_price_color_RGB = define_RGB_values(product_action_price_color)
    product_action_price_font_size = product_action_price.value_of_css_property("font-size")
    product_action_price_font_size_float = define_font_size(product_action_price_font_size)
    product_action_price_font_weight = product_action_price.value_of_css_property("font-weight")

    #compliance verification
    assert mp_product_name == product_name
    assert main_page_regular_price == product_page_regular_price
    assert main_page_action_price == product_page_action_price

    #product page properties verification
    regular_price_color_check(product_regular_price_color_RGB)
    action_price_color_check(product_action_price_color_RGB)
    assert product_action_price_font_size_float > product_regular_price_font_size_float
    assert product_regular_price_text_decoration == "line-through"
    assert product_action_price_font_weight == "bold" or product_action_price_font_weight == "700"

def define_RGB_values(color):
    cleared_color = color[color.find("(")+1:-1]
    color_RGB = [int(color) for color in cleared_color.replace(",", "").split(" ")]
    return color_RGB

def regular_price_color_check(color_RGB):
    assert color_RGB[0] == color_RGB[1] == color_RGB[2]

def action_price_color_check(color_RGB):
    assert color_RGB[1] == 0 and color_RGB[2] == 0

def define_font_size(font_size_string):
    font_size = float(font_size_string[:-2])
    return (font_size)

def new_user_registration(wd, email):
    wd.find_element_by_link_text("New customers click here").click()
    wd.find_element_by_name("firstname").send_keys("Tester")
    wd.find_element_by_name("lastname").send_keys("Mustermann")
    wd.find_element_by_name("address1").send_keys("Mainstr. 15")
    wd.find_element_by_name("postcode").send_keys("65432")
    wd.find_element_by_name("city").send_keys("New-York")
    wd.find_element_by_css_selector("span.select2-selection__arrow").click()
    wd.find_element_by_css_selector("input.select2-search__field").click()
    wd.find_element_by_css_selector("input.select2-search__field").send_keys("United States" + Keys.ENTER)
    wd.find_element_by_css_selector("select[name = zone_code]").click()
    states = wd.find_elements_by_css_selector("select[name = zone_code] option")
    states[randint(0, len(states)-1)].click()
    wd.find_element_by_name("email").send_keys(email)
    wd.find_element_by_name("phone").send_keys("+150512345678")
    if wd.find_element_by_name("newsletter").is_selected():
        wd.find_element_by_name("newsletter").click()
    wd.find_element_by_name("password").send_keys("Pa$$w0rd1")
    wd.find_element_by_name("confirmed_password").send_keys("Pa$$w0rd1")
    wd.find_element_by_name("create_account").click()

def user_logout(wd):
    open_main_page(wd)
    wd.find_element_by_link_text("Logout").click()

def user_login(wd, email):
    open_main_page(wd)
    wd.find_element_by_name("email").send_keys(email)
    wd.find_element_by_name("password").send_keys("Pa$$w0rd1")
    wd.find_element_by_name("login").click()

def add_new_product(wd, name):
    wd.find_element_by_link_text("Catalog").click()
    wd.find_element_by_link_text("Add New Product").click()
    wd.find_element_by_css_selector("input[name = status][value = '1']").click()
    wd.find_element_by_name("name[en]").send_keys(name)
    wd.find_element_by_name("code").send_keys(generators.generate_code())
    wd.find_element_by_name("new_images[]").send_keys(picture_file_name())
    wd.find_element_by_name("date_valid_from").send_keys("03/28/2017")
    wd.find_element_by_name("date_valid_to").send_keys("03/28/2018")

    wd.find_element_by_link_text("Information").click()
    select_manufacturer = Select(wd.find_element_by_name("manufacturer_id"))
    select_manufacturer.select_by_visible_text("ACME Corp.")
    wd.find_element_by_name("keywords").send_keys("Butterfly")
    wd.find_element_by_name("short_description[en]").send_keys("Strange butterfly")
    wd.find_element_by_name("head_title[en]").send_keys(name)

    wd.find_element_by_link_text("Prices").click()
    wd.find_element_by_name("purchase_price").clear()
    wd.find_element_by_name("purchase_price").send_keys("40")
    select_currency = Select(wd.find_element_by_name("purchase_price_currency_code"))
    select_currency.select_by_visible_text("Euros")
    wd.find_element_by_name("prices[USD]").send_keys("60")
    wd.find_element_by_name("gross_prices[USD]").clear()
    wd.find_element_by_name("gross_prices[USD]").send_keys("60")
    wd.find_element_by_name("prices[EUR]").send_keys("50")
    wd.find_element_by_name("gross_prices[EUR]").clear()
    wd.find_element_by_name("gross_prices[EUR]").send_keys("50")
    wd.find_element_by_name("save").click()

def picture_file_name():
    path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "pictures", "IMG_2295.jpg"))
    return path

def verify_product_presence(wd, name):
    wd.find_element_by_link_text("Catalog").click()
    products_list = wd.find_elements_by_css_selector("tr.row")
    product_names = []
    for row in products_list:
        product_names.append(row.find_elements_by_css_selector("td")[2].text)
    assert name in product_names

def add_product_to_cart(wd, number):
    wd.find_element_by_css_selector("li.product").click()
    if len(wd.find_elements_by_name("options[Size]")) > 0:
        select_size = Select(wd.find_element_by_name("options[Size]"))
        select_size.select_by_visible_text("Small")
    wd.find_element_by_name("add_cart_product").click()
    wait = WebDriverWait(wd, 3)
    wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, "span.quantity"), str(number)))

def open_cart(wd):
    wd.find_element_by_partial_link_text("Checkout").click()

def delete_all_products_from_cart(wd):
    while(len(wd.find_elements_by_css_selector("table.dataTable td.item")) > 0):
        wait = WebDriverWait(wd, 3)
        if len(wd.find_elements_by_css_selector("ul.shortcuts a")) > 0:
            wd.find_element_by_css_selector("ul.shortcuts a").click()
        wd.find_element_by_name("remove_cart_item").click()
        table_line = wd.find_element_by_css_selector("table.dataTable td.item")
        wait.until(EC.staleness_of(table_line))

def check_links_on_country_page(wd):
    wait = WebDriverWait(wd, 10)
    open_new_country_creation_form(wd)
    links_list = wd.find_elements_by_css_selector("i.fa.fa-external-link")
    main_window = wd.current_window_handle
    opened_windows = wd.window_handles
    for link in links_list:
        link.click()
        wait.until(EC.new_window_is_opened(opened_windows))
        new_windows = wd.window_handles
        for window in opened_windows:
            new_windows.remove(window)
        wd.switch_to_window(new_windows[0])
        wd.close()
        wd.switch_to_window(main_window)

def open_new_country_creation_form(wd):
    wd.get("http://localhost/litecart/admin/?app=countries&doc=countries")
    wd.find_element_by_css_selector("a.button").click()

def open_products_links_and_check_log(wd):
    open_products_list(wd)
    products_list = wd.find_elements_by_css_selector("tr.row")
    log = wd.get_log("browser")
    for i in range(0, len(products_list)):
        row = wd.find_elements_by_css_selector("tr.row")[i]
        if len(row.find_elements_by_css_selector("i.fa.fa-folder")) == 0 and \
                        len(row.find_elements_by_css_selector("i.fa.fa-folder-open")) == 0:
            row.find_element_by_css_selector("a").click()
            assert wd.get_log("browser") == log
            open_products_list(wd)
        else:
            pass

def open_products_list(wd):
    wd.get("http://localhost/litecart/admin/?app=catalog&doc=catalog&category_id=1")


text: Code for my team 3501. First Robotics Competition


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>jfoley.waltz</groupId>
  <artifactId>waltz-galago-io</artifactId>
  <version>0.5-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <javaVersion>1.8</javaVersion>
    <galagoVersion>3.10-SNAPSHOT</galagoVersion>
  </properties>

  <distributionManagement>
    <repository>
      <id>deployment</id>
      <name>Internal Releases</name>
      <url>http://scm-ciir.cs.umass.edu:8080/nexus/content/repositories/releases/</url>
    </repository>
    <snapshotRepository>
      <id>deployment</id>
      <name>Internal Releases</name>
      <url>http://scm-ciir.cs.umass.edu:8080/nexus/content/repositories/snapshots/</url>
    </snapshotRepository>
  </distributionManagement>
  <repositories>
    <repository>
      <id>edu.umass.ciir.releases</id>
      <url>http://scm-ciir.cs.umass.edu:8080/nexus/content/repositories/releases</url>
    </repository>
    <repository>
      <id>edu.umass.ciir.snapshots</id>
      <url>http://scm-ciir.cs.umass.edu:8080/nexus/content/repositories/snapshots</url>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>edu.umass.ciir.snapshots</id>
      <name>CIIR Nexus Snapshots</name>
      <url>http://scm-ciir.cs.umass.edu:8080/nexus/content/repositories/snapshots</url>
    </pluginRepository>
    <pluginRepository>
      <id>edu.umass.ciir.releases</id>
      <name>CIIR Nexus Releases</name>
      <url>http://scm-ciir.cs.umass.edu:8080/nexus/content/repositories/releases</url>
    </pluginRepository>
  </pluginRepositories>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
      <type>jar</type>
    </dependency>

    <dependency>
      <groupId>jfoley.waltz</groupId>
      <artifactId>waltz-base</artifactId>
      <version>0.5-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>org.lemurproject.galago</groupId>
      <artifactId>utility</artifactId>
      <version>${galagoVersion}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>

      <!-- build a jar with relative classpath -->
      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <archive>
            <index>true</index>
            <manifest>
              <classpathPrefix>lib/</classpathPrefix>
              <addClasspath>true</addClasspath>
              <useUniqueVersions>false</useUniqueVersions>
            </manifest>
          </archive>
        </configuration>
      </plugin>

      <!-- this is entirely to set the java version -->
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>${javaVersion}</source>
          <target>${javaVersion}</target>
        </configuration>
      </plugin>

      <!-- copy dependencies to relative classpath -->
      <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/lib</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <!-- tupleflow-typebuilder -->
      <plugin>
        <groupId>org.lemurproject.galago</groupId>
        <artifactId>tupleflow-typebuilder</artifactId>
        <version>${galagoVersion}</version>
        <executions>
          <execution>
            <phase>generate-sources</phase>
            <goals>
              <goal>typebuilder</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <!-- tell Java 8 JavaDoc tool to not complain about imperfect docs -->
      <plugin>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.10.3</version>
        <configuration>
          <additionalparam>-Xdoclint:none</additionalparam>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
package org.jboss.pnc.rest.provider;

import org.jboss.pnc.dto.response.ErrorResponse;
import org.jboss.pnc.dto.response.Validation;
import org.jboss.pnc.dto.response.Validations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import java.lang.invoke.MethodHandles;

import static javax.ws.rs.core.Response.Status.BAD_REQUEST;

/**
 * @author Honza Brázdil <jbrazdil@redhat.com>
 */
@Provider
public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    @Override
    public Response toResponse(ConstraintViolationException e) {
        Validations.Builder detailBuilder = Validations.builder();
        for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
            String attribute = constraintViolation.getPropertyPath().toString();
            String message = constraintViolation.getMessage();
            Object value = constraintViolation.getInvalidValue();
            detailBuilder.validation(new Validation(attribute, message, value));
        }

        Response.ResponseBuilder builder = Response.status(BAD_REQUEST);
        return builder.entity(
                new ErrorResponse("VALIDATION", "Constraint violation: " + e.getMessage(), detailBuilder.build()))
                .type(MediaType.APPLICATION_JSON)
                .build();
    }
}


text:
require 'rails_helper'

describe SpellPolicy do

  let(:spell) { create(:spell) }
  subject { described_class }

  context "for guest user" do
    let(:user) { build(:user) }

    permissions :show? do
      it "grants access" do
        expect(subject).to permit(user, spell)
      end
    end

    permissions :create? do
      it "denies access" do
        expect(subject).not_to permit(user, spell)
      end
    end

    permissions :update? do
      it "denies access" do
        expect(subject).not_to permit(user, spell)
      end
    end

    permissions :destroy? do
      it "denies access" do
        expect(subject).not_to permit(user, spell)
      end
    end
  end

  context "for admin user" do
    let(:user) { create(:user, :admin) }

    permissions :show? do
      it "grants access" do
        expect(subject).to permit(user, spell)
      end
    end

    permissions :create? do
      it "grants access" do
        expect(subject).to permit(user, spell)
      end
    end

    permissions :update? do
      it "grants access" do
        expect(subject).to permit(user, spell)
      end
    end

    permissions :destroy? do
      it "grants access" do
        expect(subject).to permit(user, spell)
      end
    end
  end

  context "for regular user" do
    let(:user) { create(:user) }

    permissions :show? do
      it "grants access" do
        expect(subject).to permit(user, spell)
      end
    end

    permissions :create? do
      it "grants access" do
        expect(subject).to permit(user, spell)
      end
    end

    permissions :update? do
      context "when user owns record" do
        let(:spell) { create(:spell, owner: user)}

        it "grants access" do
          expect(subject).to permit(user, spell)
        end
      end
      context "when user doesnt own record" do
        it "denies access" do
          expect(subject).not_to permit(user, spell)
        end
      end
    end

    permissions :destroy? do
      context "when user owns record" do
        let(:spell) { create(:spell, owner: user)}

        it "grants access" do
          expect(subject).to permit(user, spell)
        end
      end
      context "when user doesnt own record" do
        it "denies access" do
          expect(subject).not_to permit(user, spell)
        end
      end
    end
  end
end


text:
package perceptron

import (
	base "github.com/sjwhitworth/golearn/base"
	"math"
)

const MaxEpochs = 10

type AveragePerceptron struct {
	TrainingData base.FixedDataGrid
	weights      []float64
	edges        []float64
	bias         float64
	threshold    float64
	learningRate float64
	trainError   float64
	trained      bool
	count        float64
}

type instance struct {
	class    string
	features []float64
}

type instances []instance

func (p *AveragePerceptron) updateWeights(features []float64, correction float64) {

	for i, _ := range p.weights {
		fv := &features[i]
		if fv != nil {
			update := p.learningRate * correction * *fv
			p.weights[i] = update
			p.edges[i]++
		}
	}

	p.average()
}

func (p *AveragePerceptron) average() {

	for i, fcount := range p.edges {
		wv := &p.weights[i]
		if wv != nil {
			p.weights[i] = (p.count**wv + fcount) / (fcount + 1)
		}
	}
	p.count++
}

func (p *AveragePerceptron) score(datum instance) float64 {
	score := 0.0

	for i, wv := range p.weights {
		score += datum.features[i] * wv
	}

	if score >= p.threshold {
		return 1.0
	}
	return -1.0

}

func (p *AveragePerceptron) Fit(trainingData base.FixedDataGrid) {

	epochs := 0
	p.trainError = 0.1
	learning := true

	data := processData(trainingData)
	for learning {
		for _, datum := range data {
			response := p.score(datum)
			expected := 0.0
			correction := expected - response

			if expected != response {
				p.updateWeights(datum.features, correction)
				p.trainError += math.Abs(correction)
			}
		}

		epochs++

		if epochs >= MaxEpochs {
			learning = false
		}
	}

	p.average()
	p.trained = true
	p.TrainingData = trainingData
}

// param base.IFixedDataGrid
// return base.IFixedDataGrid
func (p *AveragePerceptron) Predict(what base.FixedDataGrid) base.FixedDataGrid {

	if !p.trained {
		panic("Cannot call Predict on an untrained AveragePerceptron")
	}

	data := processData(what)

	allAttrs := base.CheckCompatible(what, p.TrainingData)
	if allAttrs == nil {
		// Don't have the same Attributes
		return nil
	}

	// Remove the Attributes which aren't numeric
	allNumericAttrs := make([]base.Attribute, 0)
	for _, a := range allAttrs {
		if fAttr, ok := a.(*base.FloatAttribute); ok {
			allNumericAttrs = append(allNumericAttrs, fAttr)
		}
	}

	ret := base.GeneratePredictionVector(what)
	classAttr := ret.AllClassAttributes()[0]
	classSpec, err := ret.GetAttribute(classAttr)
	if err != nil {
		panic(err)
	}

	for i, datum := range data {
		result := p.score(datum)
		if result > 0.0 {
			ret.Set(classSpec, i, base.PackU64ToBytes(1))
		} else {
			ret.Set(classSpec, 1, []byte{0, 0, 0, 0, 0, 0, 0, 0})
		}
	}

	return ret
}

func processData(x base.FixedDataGrid) instances {
	_, rows := x.Size()

	result := make(instances, rows)

	// Retrieve numeric non-class Attributes
	numericAttrs := base.NonClassFloatAttributes(x)
	numericAttrSpecs := base.ResolveAttributes(x, numericAttrs)

	// Retrieve class Attributes
	classAttrs := x.AllClassAttributes()
	if len(classAttrs) != 1 {
		panic("Only one classAttribute supported!")
	}

	// Check that the class Attribute is categorical
	// (with two values) or binary
	classAttr := classAttrs[0]
	if attr, ok := classAttr.(*base.CategoricalAttribute); ok {
		if len(attr.GetValues()) != 2 {
			panic("To many values for Attribute!")
		}
	} else if _, ok := classAttr.(*base.BinaryAttribute); ok {
	} else {
		panic("Wrong class Attribute type!")
	}

	// Convert each row
	x.MapOverRows(numericAttrSpecs, func(row [][]byte, rowNo int) (bool, error) {
		// Allocate a new row
		probRow := make([]float64, len(numericAttrSpecs))

		// Read out the row
		for i, _ := range numericAttrSpecs {
			probRow[i] = base.UnpackBytesToFloat(row[i])
		}

		// Get the class for the values
		class := base.GetClass(x, rowNo)
		instance := instance{class, probRow}
		result[rowNo] = instance
		return true, nil
	})
	return result
}

func NewAveragePerceptron(features int, learningRate float64, startingThreshold float64, trainError float64) *AveragePerceptron {

	weights := make([]float64, features)
	edges := make([]float64, features)

	p := AveragePerceptron{nil, weights, edges, startingThreshold, learningRate, trainError, 0.0, false, 0}

	return &p
}


text:
<!--This file is generated-->

# remark-lint-no-missing-blank-lines

[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]
[![Sponsors][sponsors-badge]][collective]
[![Backers][backers-badge]][collective]
[![Chat][chat-badge]][chat]

Warn when missing blank lines before block content (and frontmatter
content).

This rule can be configured to allow tight list items without blank lines
between their contents by passing `{exceptTightLists: true}` (default:
`false`).

## Fix

[`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
always uses one blank line between blocks if possible, or two lines when
needed.
The style of the list items persists.

See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
on how to automatically fix warnings for this rule.

## Presets

This rule is not included in any default preset

## Example

##### `ok.md`

###### In

```markdown
# Foo

## Bar

- Paragraph

  + List.

Paragraph.
```

###### Out

No messages.

##### `not-ok.md`

###### In

```markdown
# Foo
## Bar

- Paragraph
  + List.

Paragraph.
```

###### Out

```text
2:1-2:7: Missing blank line before block node
5:3-5:10: Missing blank line before block node
```

##### `tight.md`

When configured with `{ exceptTightLists: true }`.

###### In

```markdown
# Foo
## Bar

- Paragraph
  + List.

Paragraph.
```

###### Out

```text
2:1-2:7: Missing blank line before block node
```

## Install

[npm][]:

```sh
npm install remark-lint-no-missing-blank-lines
```

## Use

You probably want to use it on the CLI through a config file:

```diff
 …
 "remarkConfig": {
   "plugins": [
     …
     "lint",
+    "lint-no-missing-blank-lines",
     …
   ]
 }
 …
```

Or use it on the CLI directly

```sh
remark -u lint -u lint-no-missing-blank-lines readme.md
```

Or use this on the API:

```diff
 var remark = require('remark')
 var report = require('vfile-reporter')

 remark()
   .use(require('remark-lint'))
+  .use(require('remark-lint-no-missing-blank-lines'))
   .process('_Emphasis_ and **importance**', function (err, file) {
     console.error(report(err || file))
   })
```

## Contribute

See [`contributing.md`][contributing] in [`remarkjs/.github`][health] for ways
to get started.
See [`support.md`][support] for ways to get help.

This project has a [code of conduct][coc].
By interacting with this repository, organization, or community you agree to
abide by its terms.

## License

[MIT][license] © [Titus Wormer][author]

[build-badge]: https://github.com/remarkjs/remark-lint/workflows/main/badge.svg

[build]: https://github.com/remarkjs/remark-lint/actions

[coverage-badge]: https://img.shields.io/codecov/c/github/remarkjs/remark-lint.svg

[coverage]: https://codecov.io/github/remarkjs/remark-lint

[downloads-badge]: https://img.shields.io/npm/dm/remark-lint-no-missing-blank-lines.svg

[downloads]: https://www.npmjs.com/package/remark-lint-no-missing-blank-lines

[size-badge]: https://img.shields.io/bundlephobia/minzip/remark-lint-no-missing-blank-lines.svg

[size]: https://bundlephobia.com/result?p=remark-lint-no-missing-blank-lines

[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg

[backers-badge]: https://opencollective.com/unified/backers/badge.svg

[collective]: https://opencollective.com/unified

[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg

[chat]: https://github.com/remarkjs/remark/discussions

[npm]: https://docs.npmjs.com/cli/install

[health]: https://github.com/remarkjs/.github

[contributing]: https://github.com/remarkjs/.github/blob/HEAD/contributing.md

[support]: https://github.com/remarkjs/.github/blob/HEAD/support.md

[coc]: https://github.com/remarkjs/.github/blob/HEAD/code-of-conduct.md

[license]: https://github.com/remarkjs/remark-lint/blob/main/license

[author]: https://wooorm.com


text:
import HTMLElement from '../../HTMLElement';

/**
 * HTML select elements share all of the properties and methods
 * of other HTML elements described in the element section.
 * They also have the specialized interface HTMLSelectElement.
 *
 * @see https://developer.mozilla.org/en/docs/Web/API/HTMLSelectElement
 *
 */
export default class HTMLSelectElement extends HTMLElement {
    /**
     * Is a Boolean that reflects the autofocus HTML attribute,
     * which indicates whether the control should have input focus when the page loads,
     * unless the user overrides it, for example by typing in a different control.
     * Only one form-associated element in a document can have this attribute specified
     *
     * @type {boolean}
     */
    get autoFocus() {
        return this.hasAttribute('autofocus');
    }

    /**
     * @param {boolean} value
     */
    set autoFocus(value) {
        if (value) {
            this.setAttribute('autofocus', '');
        } else {
            this.removeAttribute('autofocus');
        }
    }

    /**
     * Is a Boolean that reflects the disabled HTML attribute,
     * which indicates whether the control is disabled.
     * If it is disabled, it does not accept clicks.
     *
     * @type {boolean}
     */
    get disabled() {
        return this.hasAttribute('disabled');
    }

    /**
     * @param {boolean} value
     */
    set disabled(value) {
        if (value) {
            this.setAttribute('disabled', 'disabled');
        } else {
            this.removeAttribute('disabled');
        }
    }

    /**
     * The form that this element is associated with. If this element is a descendant of a form element,
     * then this attribute is the ID of that form element.
     * If the element is not a descendant of a form element, then:
     * The attribute can be the ID of any form element in the same document.
     *
     * @type {HTMLFormElement}
     * @readonly
     */
    get form() {
        return this._closestParent('form') || null;
    }

    set form(value) {
        throw new Error('form is read only');
    }

    /**
     * Returns a NodeList containing the list of label elements associated with this select element.
     *
     * @type {HTMLLabelElement[]}
     * @readonly
     */
    get labels() {
        if (!this.hasAttribute('id')) {
            return [];
        }

        const id = this.getAttribute('id');
        const highestParent = this._highestParent();

        if (!highestParent) {
            return [];
        }

        return highestParent._filterDescendantNodes(n => n.tagName === 'label' && n.getAttribute('for') === id);
    }

    /**
     * The number of option elements in this select element.
     *
     * @type {number}
     * @readonly
     */
    get length() {
        return this.options.length;
    }

    set length(value) {
        throw new Error('length is read only');
    }

    /**
     * Reflects the multiple HTML attribute, which indicates whether multiple items can be selected.
     *
     * @type {boolean}
     */
    get multiple() {
        return this.hasAttribute('multiple');
    }

    /**
     * @param {boolean} multiple
     */
    set multiple(multiple) {
        if (multiple) {
            this.setAttribute('multiple', 'multiple');
        } else {
            this.removeAttribute('multiple');
        }
    }

    /**
     * Reflects the name HTML attribute, containing the name of this control
     * used by servers and DOM search functions.
     *
     * @type {string}
     */
    get name() {
        return this.getAttribute('name');
    }

    /**
     * @param {string} name
     */
    set name(name) {
        this.setAttribute('name', name);
    }

    /**
     * The set of option elements contained by this element.
     *
     * @type {Array.<Element>}
     * @readonly
     */
    get options() {
        return this.getElementsByTagName('option');
    }

    set options(value) {
        throw new Error('options is read only');
    }

    /**
     * Reflects the required HTML attribute, which indicates whether the user is required
     * to select a value before submitting the form
     *
     * @type {boolean}
     */
    get required() {
        return this.hasAttribute('required');
    }

    set required(required) {
        if (required) {
            this.setAttribute('required', 'required');
        } else {
            this.removeAttribute('required');
        }
    }

    /**
     * The index of the first selected option element.
     * The value -1 is returned if no element is selected.
     *
     * @type {number}
     */
    get selectedIndex() {
        let index = -1;
        let emptyIndex = -1;
        const options = this.options;

        if (!options.length) {
            return index;
        }

        options.some((option, idx) => {
            if (option.selected) {
                index = idx;
                return true;
            }

            if (emptyIndex === -1 && option.value === '') {
                emptyIndex = idx;
            }
        });

        if (index === -1 && !this.multiple) {
            index = emptyIndex;

            if (index === -1) {
                return 0;
            }
        }

        return index;
    }

    /**
     * @param {number} index
     */
    set selectedIndex(index) {
        this.selectedOptions.forEach(option => option.selected = false);
        this.options[index].selected = true;
    }

    /**
     * The set of options that are selected.
     *
     * @type {Element[]}
     * @readonly
     */
    get selectedOptions() {
        return this.options.filter(option => option.selected);
    }

    /**
     * The first selected option.
     *
     * @type {HtmlOptionElement|null}
     * @readonly
     */
    get selectedOption() {
        let selectedIndex = this.selectedIndex;

        if (selectedIndex === -1) {
            return null;
        }

        return this.options[selectedIndex];
    }

    /**
     * Reflects the size HTML attribute, which contains the number of visible items in the control.
     * The default is 1, unless multiple is true, in which case it is 4.
     *
     * @type {number}
     */
    get size() {
        return Number(this.getAttribute('size')) || (this.multiple ? 4 : 1);
    }

    /**
     * @param {number} size
     */
    set size(size) {
        this.setAttribute('size', size);
    }

    get tabIndex() {
        throw new Error('Obsolete since HTML5');
    }

    /**
     * The form control's type. When multiple is true, it returns select-multiple; otherwise, it returns select-one.
     * Read only.
     *
     * @type {string}
     * @readonly
     */
    get type() {
        return this.multiple ? 'select-multiple' : 'select-one';
    }

    set type(value) {
        throw new Error('type is read only');
    }

    get validationMessage() {
        throw new Error('Not implemented');
    }

    set validationMessage(value) {
        throw new Error('validationMessage is read only');
    }

    get validity() {
        throw new Error('Not implemented');
    }

    set validity(value) {
        throw new Error('validity is read only');
    }

    /**
     * The value of this form control, that is, of the first selected option.
     *
     * @type {string}
     */
    get value() {
        return this.selectedOption && this.selectedOption.value;
    }

    /**
     * @ignore
     * @param {string} value
     */
    set value(value) {
        this.selectedOption.value = value;
        return value;
    }

    get willValidate() {
        throw new Error('Not implemented');
    }

    set willValidate(value) {
        throw new Error('willValidate is read only');
    }

    /**
     * Gets an item from the options collection for this select element.
     *
     * @param {number} index
     * @ return {HTMLSelectElement}
     */
    item(index) {
        throw new Error('Not implemented');
    }

    /**
     * Gets the item in the options collection with the specified name.
     * The name string can match either the id or the name attribute of an option node
     *
     * @ignore Not implemented
     * @param {string} name
     * @ return {HTMLSelectElement}
     */
    namedItem(name) {
        throw new Error('Not implemented');
    }

    /**
     * Removes the element at the specified index from the options collection for this select element.
     *
     * @ignore Not implemented
     * @param {number} index
     */
    remove(index) {
        throw new Error('Not implemented');
    }
}

/**
 * @constant {string} HTMLSelectElement#nodeName option
 */
Object.defineProperty(HTMLSelectElement.prototype, 'nodeName', { value: 'select' });


text:
/*
 * A Bit of Everything
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * API version: 1.0
 * Contact: none@example.com
 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
 */

package abe

import (
	"time"
)

type TheBookToUpdateTheBooksNameFieldIsUsedToIdentifyTheBookToBeUpdatedFormatPublisherspublisherbooksbook struct {
	// Output only. The book's ID.
	Id string `json:"id,omitempty"`
	// Output only. Creation time of the book.
	CreateTime time.Time `json:"createTime,omitempty"`
}


text:
'use strict';
global.$ROOT = __dirname;

var app = require('./index'),
    fs = require('fs'),
    //http = require('http'),
    http2 = require('spdy'),
    server;
var privateKey = fs.readFileSync('ssl/ca.key'),
    certificate = fs.readFileSync('ssl/ca.crt'),
    credentials = {key: privateKey, cert: certificate};

server = http2.createServer(credentials, app);
server.listen(process.env.PORT || 8000);
server.on('listening', function () {
    var date = new Date();
    console.log('%s [%s] Listening on http://localhost:%d', date, app.settings.env, this.address().port);
});


text:
<!DOCTYPE html>

<meta charset="utf-8">

<title>Arduino Bluefruit LED On/Off Example</title>

Arduino Bluefruit LED On/Off BLE

Control The Arduino From An App Using BLE. This example shows you how to make an app that controls an Arduino board and lights up an LED.

Communication with the Arduino is made using Bluetooth Low Energy (BLE) through Adafruit's Bluefruit LE UART Friend board.

Source code

You can browse the source code for this example at the
	Evothings GitHub repository

The file index.html is the entry point of the app.

The file Bluefruit_LE_LED_on_off.ino contains the Arduino BLE server code that listens for commands from the app.

What you need

This example runs in Evothings Viewer on Android or iOS.

You need to run the example in Evothings Viewer. Alternatively, you can make a Cordova application if you wish to distribute the app. You then need to include the Cordova plugin com.evothings.ble.

An iOS device or an Android device with support for Bluetooth 4.0 (which includes BLE) is required. In addition Android 4.3 or later is needed. Please note that BLE support on Android is still not fully mature. As a result, you may experience difficulties running this example. If the app stops working, restart Evothings Viewer.

For the Arduino setup, you need:

LED

A 220Ω resistor

Bluefruit LE UART Friend board

Install Adafruit's library in the Arduino IDE library folder. You can download it from Adafruit's website.

Here is the sketch:

The LED is connected to pin 5.
The Bluefruit board is connected as follows (default configuration):

CTS on pin 11

TXO on pin 10

RXI on pin 9

VIN on 5V

GND on GND

The MOD, RTS and DFU pins are not used in this example Note that for this example the Bluefruit board has to be set to CMD mode on the small switch.

How to get up and running

Follow these steps to get started with this example:

Wire up the Arduino board.

Open Bluefruit_LE_LED_on_off.ino in the Arduino development tool.

Upload the program to the Arduino.

Run Evothings Workbench on your desktop/laptop computer.

Run Evothings Viewer on an iOS or Android mobile device and connect to the Workbench.

Launch the example Arduino Bluefruit LE UART Friend LED On/Off from the Workbench window.

Follow on-screen instructions in the app.

If everything works, you should now be able to turn the LED on and off using the buttons in the app. If it does not work, check your wiring and that the right pins are used (remember pin 5 is used for output).

Now you can proceed with making your own sketch designs and add more buttons to the app.


text:
<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Article extends Model
{
  use SoftDeletes;

  protected $hidden = ['deleted_at', 'created_at'];

  protected $fillable = ['title', 'category_id', 'sort', 'views', 'tag', 'is_recommend', 'is_show', 'info', 'url', 'cover', 'thumb', 'text', 'subtitle', 'author', 'source', 'keywords', 'description', 'hash'];

  public function setIsRecommendAttribute($value)
  {
    $this->attributes['is_recommend'] = intval($value);
  }

  public function setIsShowAttribute($value)
  {
    $this->attributes['is_show'] = intval($value);
  }

  public function setTagAttribute($value)
  {
    $this->attributes['tag'] = json_encode(explode(',', strip_tags($value)));
  }

  public function setDescriptionAttribute($value)
  {
    $this->attributes['description'] = $value ? $value : '';
  }

  public function setTextAttribute($value)
  {
    $this->attributes['text'] = $value ? $value : '';
  }

  public function scopeSortByDesc($query,$key)
  {
    if($key != 'id') return $query->orderBy($key,'desc')->orderBy('id','desc');
    return $query->orderBy($key,'desc');
  }

  public function scopeSortBy($query,$key)
  {
    return $query->orderBy($key);
  }

  public function category()
  {
    return $this->belongsTo('App\Model\Category');
  }

  public function getCover()
  {
    if($this->thumb != ''){
      return $this->thumb;
    } else {
      $this->cover;
    }
  }

}


text:
require 'jekyll/minibundle/development_file'

module Jekyll::Minibundle
  class DevelopmentFileCollection
    attr_reader :files

    def initialize(site, config)
      @type = config.fetch('type')

      source_dir = config.fetch('source_dir')
      destination_path = config.fetch('destination_path')

      @files = config.fetch('assets').map do |asset_path|
        asset_basename = "#{asset_path}.#{@type}"
        asset_source = File.join(source_dir, asset_basename)
        asset_destination = File.join(destination_path, asset_basename)
        DevelopmentFile.new(site, asset_source, asset_destination)
      end
    end

    def cleanup
      # no-op
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
    Copyright (c) 2012 Hai Bison

    See the file LICENSE at the root directory of this project for copying
    permission.
-->

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/afc_button_sort_as_pressed" android:state_pressed="true"/> <!-- pressed -->
    <item android:drawable="@drawable/afc_button_sort_as_disabled" android:state_enabled="false"/> <!-- enabled -->
    <item android:drawable="@drawable/afc_button_sort_as"/> <!-- default -->

</selector>


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <stand.h>
#include <efi.h>
#include <efilib.h>

/*
 * We could use linker sets for some or all of these, but
 * then we would have to control what ended up linked into
 * the bootstrap.  So it's easier to conditionalise things
 * here.
 *
 * XXX rename these arrays to be consistent and less namespace-hostile
 */

/* Exported for libstand */
struct devsw *devsw[] = {
	&efipart_dev,
	&efinet_dev,
	NULL
};

struct fs_ops *file_system[] = {
	&dosfs_fsops,
	&ufs_fsops,
	&cd9660_fsops,
	&nfs_fsops,
	&gzipfs_fsops,
	NULL
};

struct netif_driver *netif_drivers[] = {
	&efinetif,
	NULL
};

/*
 * Consoles
 *
 * We don't prototype these in efiboot.h because they require
 * data structures from bootstrap.h as well.
 */
extern struct console efi_console;

struct console *consoles[] = {
	&efi_console,
	NULL
};


text:
package csrf

import (
	"context"
	"net/http"

	"github.com/pkg/errors"
)

func contextGet(r *http.Request, key string) (interface{}, error) {
	val := r.Context().Value(key)
	if val == nil {
		return nil, errors.Errorf("no value exists in the context for key %q", key)
	}

	return val, nil
}

func contextSave(r *http.Request, key string, val interface{}) *http.Request {
	ctx := r.Context()
	ctx = context.WithValue(ctx, key, val)
	return r.WithContext(ctx)
}

func contextClear(r *http.Request) {
	// no-op for go1.7+
}


text:
These are message types sent from controllers contained within the WebApi project and handled within the App project.
Commands are sent to alter the state of resources managed by the application and can have an optional return type.

Messaging:  https://github.com/grecosoft/NetFusion/wiki/core.messaging.overview#messaging---overview
Commands:   https://github.com/grecosoft/NetFusion/wiki/core.messaging.commands#messaging---commands

A command can have only one in-process message handler and can be delivered out of process using the following
infrastructure plug-ins:

NetFusion.RabbitMq  [https://github.com/grecosoft/NetFusion/wiki/integration.rabbitmq.overview#rabbitmq-overview]
NetFusion.AMQP      [https://github.com/grecosoft/NetFusion/wiki/integration.amqp.overview#amqp-overview]


text:
package CommonComponent;
import java.awt.*;
import javax.swing.*;
public class CommonComponent {
Frame f = new Frame("²âÊÔ");
Button ok = new Button("È·ÈÏ");
CheckboxGroup a = new CheckboxGroup();
Checkbox male = new Checkbox("ÄÐ",a,true);
Checkbox female = new Checkbox("Å®",a,false);
Choice color =  new Choice();
List colorList = new List();
TextArea ta = new TextArea(5,20);
TextField name = new TextField(50);
public void init()
{
    color.add("ºì");
    color.add("ÂÌ");
    color.add("˦");
    colorList.add("ºì");
    colorList.add("ÂÌ");
    Panel bottom =new Panel();
    bottom.add(name);
    bottom.add(ok);
    f.add(bottom,BorderLayout.SOUTH);
    Panel checkPanel = new Panel();
    checkPanel.add(color);
    checkPanel.add(male);
    checkPanel.add(female);
    Box topLeft = Box.createVerticalBox();
    topLeft.add(ta);
    topLeft.add(checkPanel);
    Box tope = Box.createHorizontalBox();
    tope.add(topLeft);
    tope.add(colorList);
    f.add(tope);
    f.pack();
    f.setVisible(true);

}
public static void main(String[] args)
{
    new CommonComponent().init();
}

}