text:
import Vue from 'vue'
import Equipment from '@/components/Equipment'

describe('Equipment.vue', () => {
  it('should render correct contents', () => {
    const Constructor = Vue.extend(Equipment)
    const vm = new Constructor().$mount()
    expect(vm.$el.querySelector('.equipment h1').textContent)
      .to.equal('Welcome to Your Vue.js PWA')
  })
})


text:
<?php
/**
 * Created by PhpStorm.
 * User: zhangjincheng
 * Date: 16-7-15
 * Time: 下午2:43
 */

namespace Server\Pack;

use Server\CoreBase\SwooleException;

class LenJsonPack implements IPack
{
    protected $package_length_type = 'N';
    protected $package_length_type_length = 4;
    protected $package_length_offset = 0;
    protected $package_body_offset = 0;

    protected $last_data = null;
    protected $last_data_result = null;

    /**
     * 数据包编码
     * @param $buffer
     * @return string
     * @throws SwooleException
     */
    public function encode($buffer)
    {
        $total_length = $this->package_length_type_length + strlen($buffer) - $this->package_body_offset;
        return pack($this->package_length_type, $total_length) . $buffer;
    }

    /**
     * @param $buffer
     * @return string
     */
    public function decode($buffer)
    {
        return substr($buffer, $this->package_length_type_length);
    }

    public function pack($data, $topic = null)
    {
        if ($this->last_data != null && $this->last_data == $data) {
            return $this->last_data_result;
        }
        $this->last_data = $data;
        $this->last_data_result = $this->encode(json_encode($data, JSON_UNESCAPED_UNICODE));
        return $this->last_data_result;
    }

    public function unPack($data)
    {
        $value = json_decode($this->decode($data));
        if (empty($value)) {
            throw new SwooleException('json unPack 失败');
        }
        return $value;
    }

    public function getProbufSet()
    {
        return [
            'open_length_check' => true,
            'package_length_type' => $this->package_length_type,
            'package_length_offset' => $this->package_length_offset,       //第N个字节是包长度的值
            'package_body_offset' => $this->package_body_offset,       //第几个字节开始计算长度
            'package_max_length' => 2000000,  //协议最大长度)
        ];
    }

    public function errorHandle(\Throwable $e, $fd)
    {
        get_instance()->close($fd);
    }
}

redpajama_set_name: RedPajamaGithub


text:
{% extends 'base.html' %}
{% load i18n sizeformat %}
{% block title %}{% trans "Attachments detail" %}{% endblock %}

{% block page_header %}
  {% include "horizon/common/_page_header.html" with title="Attachments detail: "  %}
{% endblock page_header %}

{% block main %}

  {{ tab_group.render }}

{% endblock %}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Module: Sys</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />

          Module
          Sys

            In:

                lib/rake/contrib/sys.rb

Sys provides a number of file manipulation tools for
the convenience of writing Rakefiles. All commands in this module will
announce their activity on standard output if the $verbose flag is set ($verbose = true is the default). You can control
this by globally setting $verbose or by
using the <tt>verbose</tt> and <tt>quiet</tt> methods.

Sys has been deprecated in favor of the FileUtils module available in Ruby 1.8.

Methods

      copy
      copy_files
      delete
      delete_all
      for_files
      indir
      install
      link
      link_files
      log
      makedirs
      quiet
      ruby
      run
      split_all
      symlink
      symlink_files
      verbose

Constants

          RUBY
          =
          Config::CONFIG['ruby_install_name']

Public Instance methods

          copy(file_name, dest_file)

Copy a single file from <tt>file_name</tt> to <tt>dest_file</tt>.

          copy_files(wildcard, dest_dir)

Copy all files matching <tt>wildcard</tt> into the directory
<tt>dest_dir</tt>.

          delete(*wildcards)

Remove all files matching <tt>wildcard</tt>. If a matching file is a
directory, it must be empty to be removed. used <tt>delete_all</tt> to recursively delete directories.

          delete_all(*wildcards)

Recursively delete all files and directories
matching <tt>wildcard</tt>.

          for_files(*wildcards) {|fn| ...}

Perform a block with each file matching a set of wildcards.

          indir(dir) {|| ...}

Make <tt>dir</tt> the current working directory for the duration of
executing the given block.

          install(wildcard, dest_dir, mode)

Install all the files matching <tt>wildcard</tt> into the <tt>dest_dir</tt>
directory. The permission mode is set to <tt>mode</tt>.

          link(file_name, dest_file)

Link <tt>file_name</tt> to <tt>dest_file</tt>.

          link_files(wildcard, dest_dir)

Link all files matching <tt>wildcard</tt> into the directory
<tt>dest_dir</tt>.

          log(msg)

Write a message to standard out if $verbose
is enabled.

          makedirs(*dirs)

Make the directories given in <tt>dirs</tt>.

          quiet(&block)

Perform a block with $verbose disabled.

          ruby(*args)

Run a Ruby interpreter with the given arguments.

          run(cmd)

Run the system command <tt>cmd</tt>.

          split_all(path)

Split a file path into individual directory names.

For example:

  split_all("a/b/c") =>  ['a', 'b', 'c']

          symlink(file_name, dest_file)

Symlink <tt>file_name</tt> to <tt>dest_file</tt>.

          symlink_files(wildcard, dest_dir)

Symlink all files matching <tt>wildcard</tt> into the directory
<tt>dest_dir</tt>.

          verbose(&block)

Perform a block with $verbose enabled.

[Validate]


text:
utils
=========

gramfuzz will work with most native Python types, as well
as any :any:`gramfuzz.fields.Field` type.

gramfuzz uses the :any:`gramfuzz.utils.val` function to convert
values into data.

For native Python types, ``str()`` is used to convert the
object into a string.

For :any:`gramfuzz.fields.Field` classes, a new instance is created,
and then ``build()`` is called on the created instance.

For :any:`gramfuzz.fields.Field` instances, ``build()`` is simply
called on the instance.

utils Reference Documentation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. automodule:: gramfuzz.utils
   :members:


text:
<?php
/**
 * Content for Optimizely A/B SEO tests used on Pitch pages.
 * Currently not included into any templates via Drupal, but will be in future after A/B tests completed.
 */
?>

<?php print t('The Problem'); ?>

<?php print t('7 in 10 girls believe they don't measure up in terms of looks, performance in school, or in relationships with friends and family.'); ?>

<?php print t('The Solution'); ?>

<?php print t('You can raise your friends' self-esteem by complimenting them on their unique traits and skills. In other words, reminding them how awesome they are at the stuff they're awesome at.'); ?>

<?php print t('To celebrate the release of Fifth Harmony's new single, "BO$$," join Normani, Dinah, Lauren, Camila & Ally, and tell a friend what they're the boss of to boost their confidence.'); ?>

<?php print t('What You Get'); ?>

<?php print t('Sign up and you'll get facts on women's empowerment, tips on raising your friends' self-esteem, a sign for telling your friends what they are boss at, an entry into the contest to win a $2,500 scholarship for school, plus the chance to boss around Fifth Harmony for a day (seriously you could meet them).'); ?>

<?php print t('Sign up for #ImABoss to boost your friends' self-esteem.'); ?>

    <?php print t('Sign Up'); ?>


text:
var gulp = require('gulp');
var connect = require('gulp-connect');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var minifyCSS = require('gulp-clean-css');
var clean = require('gulp-clean');
var runSequence = require('run-sequence');

gulp.task('lint', function() {
  gulp.src(['./src/**/*.js', '!./bower_components/**'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('clean', function() {
  return gulp.src('dist', {read: false})
    .pipe(clean({force: true}));
});

gulp.task('minify-css', function() {
  var opts = {comments:true,spare:true};
  return gulp.src(['src/**/*.css'])
    .pipe(minifyCSS(opts))
    .pipe(gulp.dest('dist/src/'));
});

gulp.task('minify-js', function() {
  return gulp.src(['src/**/*.js'])
    .pipe(uglify())
    .pipe(gulp.dest('dist/src/'));
});

gulp.task('copy-bower-components', function() {
  return gulp.src('bower_components/**/*')
    .pipe(gulp.dest('dist/bower_components'));
});

gulp.task('copy-html-files', function() {
  return gulp.src('src/**/*.html')
    .pipe(gulp.dest('dist/src/'));
});

gulp.task('connect', function() {
  connect.server({
    root: ['src'],
    port: 8080,
    livereload: true,
    middleware: function(connect) {
      return [connect().use('/bower_components', connect.static('bower_components'))];
    }
  });
});

gulp.task('connectDist', function() {
  connect.server({
    root: ['dist/src/'],
    port: 8080,
    livereload: true,
    middleware: function(connect) {
      return [connect().use('/bower_components', connect.static('bower_components'))];
    }
  });
});

gulp.task('default', function() {
  runSequence(
    'lint',
    'connect'
  );
});

gulp.task('build', function() {
  runSequence(
    'lint',
    'clean',
    ['minify-css', 'minify-js'],
    'copy-html-files',
    'copy-bower-components',
    'connectDist'
  );
});


text:
Fibonacci Heap
=============

A Fibonacci Heap implementation in Python, kaitoy@qq.com

Fibonacci Heap is a great data structure and works perfectly for graph algorithms like Dijkstra, I find it's necessary to write a python version during study.
It's majorly based on the original pseudo code and take advantage of some of python features.
Also there is a test available for study.
Anything you want to discuss please email.

Interface:
-------------

    minimun()
        - Get the node with minimun key value.
    merge(heap)
        - Merge another Fibonacci Heap into this one.
    insert(key, data)
        - Insert a new node with (key, data) pair.
    extract_min()
        - Extract the node in heap with minmun key value.
    decrease_key(node, key)
        - Decrease the key value of node provided.
    delete(node)
        - Delete the node from heap.

Reference:
-------------
Wiki:

[http://en.wikipedia.org/wiki/Fibonacci_heap](http://en.wikipedia.org/wiki/Fibonacci_heap)

Pseudo code:

[http://www.cs.princeton.edu/~wayne/cs423/fibonacci/FibonacciHeapAlgorithm.html](http://www.cs.princeton.edu/~wayne/cs423/fibonacci/FibonacciHeapAlgorithm.html)

Java code:

[http://keithschwarz.com/interesting/code/?dir=fibonacci-heap](http://keithschwarz.com/interesting/code/?dir=fibonacci-heap)

Median of Medians
=============

Median of Medians select algorithm implementation in python.
O(n) time complexity and O(1) space.

Reference:
-------------
Wiki:

[https://en.wikipedia.org/wiki/Median_of_medians](https://en.wikipedia.org/wiki/Median_of_medians)


text:
std::vector<IShaderParameter*> IShaderParameter::values_assigned {};

template <>
bool ShaderParameter<bool>::commit(IDirect3DDevice9* device)
{
	if (is_modified())
	{
		const auto f = current_ ? 1.0f : 0.0f;
		const float buffer[4] = { f, f, f, f };

		if (type_ & Type::vertex)
		{
			device->SetVertexShaderConstantF(index_, buffer, 1);
		}

		if (type_ & Type::pixel)
		{
			device->SetPixelShaderConstantF(index_, buffer, 1);
		}

		clear();
		return true;
	}

	assigned_ = false;
	return false;
}

template <>
bool ShaderParameter<int>::commit(IDirect3DDevice9* device)
{
	if (is_modified())
	{
		const auto f = static_cast<float>(current_);
		const float buffer[4] = { f, f, f, f };

		if (type_ & Type::vertex)
		{
			device->SetVertexShaderConstantF(index_, buffer, 1);
		}

		if (type_ & Type::pixel)
		{
			device->SetPixelShaderConstantF(index_, buffer, 1);
		}

		clear();
		return true;
	}

	assigned_ = false;
	return false;
}

template <>
bool ShaderParameter<float>::commit(IDirect3DDevice9* device)
{
	if (is_modified())
	{
		D3DXVECTOR4 value = { current_, current_, current_, current_ };

		if (type_ & Type::vertex)
		{
			device->SetVertexShaderConstantF(index_, value, 1);
		}

		if (type_ & Type::pixel)
		{
			device->SetPixelShaderConstantF(index_, value, 1);
		}

		clear();
		return true;
	}

	assigned_ = false;
	return false;
}

template <>
bool ShaderParameter<D3DXVECTOR4>::commit(IDirect3DDevice9* device)
{
	if (is_modified())
	{
		if (type_ & Type::vertex)
		{
			device->SetVertexShaderConstantF(index_, current_, 1);
		}

		if (type_ & Type::pixel)
		{
			device->SetPixelShaderConstantF(index_, current_, 1);
		}

		clear();
		return true;
	}

	assigned_ = false;
	return false;
}

template <>
bool ShaderParameter<D3DXVECTOR3>::commit(IDirect3DDevice9* device)
{
	if (is_modified())
	{
		D3DXVECTOR4 value = { current_.x, current_.y, current_.z, 0.0f };

		if (type_ & Type::vertex)
		{
			device->SetVertexShaderConstantF(index_, value, 1);
		}

		if (type_ & Type::pixel)
		{
			device->SetPixelShaderConstantF(index_, value, 1);
		}

		clear();
		return true;
	}

	assigned_ = false;
	return false;
}

template <>
bool ShaderParameter<D3DXVECTOR2>::commit(IDirect3DDevice9* device)
{
	if (is_modified())
	{
		D3DXVECTOR4 value = { current_.x, current_.y, 0.0f, 1.0f };

		if (type_ & Type::vertex)
		{
			device->SetVertexShaderConstantF(index_, value, 1);
		}

		if (type_ & Type::pixel)
		{
			device->SetPixelShaderConstantF(index_, value, 1);
		}

		clear();
		return true;
	}

	assigned_ = false;
	return false;
}

template <>
bool ShaderParameter<D3DXCOLOR>::commit(IDirect3DDevice9* device)
{
	if (is_modified())
	{
		static_assert(sizeof(D3DXCOLOR) == sizeof(D3DXVECTOR4), "D3DXCOLOR size does not match D3DXVECTOR4.");

		if (type_ & Type::vertex)
		{
			device->SetVertexShaderConstantF(index_, current_, 1);
		}

		if (type_ & Type::pixel)
		{
			device->SetPixelShaderConstantF(index_, current_, 1);
		}

		clear();
		return true;
	}

	assigned_ = false;
	return false;
}

template <>
bool ShaderParameter<D3DXMATRIX>::commit(IDirect3DDevice9* device)
{
	if (is_modified())
	{
		if (type_ & Type::vertex)
		{
			device->SetVertexShaderConstantF(index_, current_, 4);
		}

		if (type_ & Type::pixel)
		{
			device->SetPixelShaderConstantF(index_, current_, 4);
		}

		clear();
		return true;
	}

	assigned_ = false;
	return false;
}

template <>
bool ShaderParameter<Texture>::commit(IDirect3DDevice9* device)
{
	if (is_modified())
	{
		if (type_ & Type::vertex)
		{
			device->SetTexture(D3DVERTEXTEXTURESAMPLER0 + index_, current_);
		}

		if (type_ & Type::pixel)
		{
			device->SetTexture(index_, current_);
		}

		clear();
		return true;
	}

	assigned_ = false;
	return false;
}

template <>
void ShaderParameter<Texture>::release()
{
	clear();
	current_ = nullptr;
	last_ = nullptr;
}


text:
module CloudModel
  module Notifiers
    class BaseNotifier
      def initialize options={}
        @options = options
      end

      def send_message subject, message
      end
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Fusarium translucens Berk. & Broome

### Remarks
null


text:
/* Taken from
- http://adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/
- http://jsfiddle.net/kumarmuthaliar/GG9Sa/1/
*/

.modal_dialog__overlay {
  /* A dark translucent div that covers the whole screen */
  position:absolute;
  z-index:9999;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background-color:#000000;
  opacity: 0.8;
}

.modal_dialog__window {
  /* A centered div above the overlay with a box shadow. */
  z-index:10000;
  position: absolute;
  width: 50%; /* Default */
  max-height: 300px;
  overflow: auto;

  /* Center the dialog */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);

  background-color: #fff;
  box-shadow: 4px 4px 80px #000;

  padding: 10px 20px 10px 20px;
  border-radius: 10px;
  background: #fff;
  background: -moz-linear-gradient(#fff, #999);
  background: -webkit-linear-gradient(#fff, #999);
  background: -o-linear-gradient(#fff, #999);
}

.modal_dialog__title {
  padding: 10px 0 5px 0;
}

.modal_dialog__content {
  text-align: justify;
  overflow: auto;
}

.modal_dialog__close {
  position: absolute;
  top: 3px;
  right: 5px;
  padding: 5px;
  cursor: pointer;
  font-size: 120%;
  display: inline-block;
  font-weight: bold;
  font-family: Arial, Helvetica, sans-serif;
}

.modal_dialog__close:hover {
  color: #00d9ff;
}


text:
#region References

using System.Collections.Generic;

#endregion

namespace Scribe.Models.Views
{
	public class SearchView
	{
		#region Constructors

		public SearchView(string term)
		{
			Term = term;
			Results = new List<SearchResultView>();
		}

		#endregion

		#region Properties

		public ICollection<SearchResultView> Results { get; set; }
		public string Term { get; set; }

		#endregion
	}
}


text:
from azure.identity import DefaultAzureCredential
from azure.mgmt.datafactory import DataFactoryManagementClient

"""
# PREREQUISITES
    pip install azure-identity
    pip install azure-mgmt-datafactory
# USAGE
    python triggers_update.py

    Before run the sample, please set the values of the client ID, tenant ID and client secret
    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
    https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""

def main():
    client = DataFactoryManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id="12345678-1234-1234-1234-12345678abc",
    )

    response = client.triggers.create_or_update(
        resource_group_name="exampleResourceGroup",
        factory_name="exampleFactoryName",
        trigger_name="exampleTrigger",
        trigger={
            "properties": {
                "description": "Example description",
                "pipelines": [
                    {
                        "parameters": {"OutputBlobNameList": ["exampleoutput.csv"]},
                        "pipelineReference": {"referenceName": "examplePipeline", "type": "PipelineReference"},
                    }
                ],
                "type": "ScheduleTrigger",
                "typeProperties": {
                    "recurrence": {
                        "endTime": "2018-06-16T00:55:14.905167Z",
                        "frequency": "Minute",
                        "interval": 4,
                        "startTime": "2018-06-16T00:39:14.905167Z",
                        "timeZone": "UTC",
                    }
                },
            }
        },
    )
    print(response)

# x-ms-original-file: specification/datafactory/resource-manager/Microsoft.DataFactory/stable/2018-06-01/examples/Triggers_Update.json
if __name__ == "__main__":
    main()


text:
<?php

use opensrs\backwardcompatibility\dataconversion\trust\QueryApproverList;

/**
 * @group backwardcompatibility
 * @group dataconversion
 * @group trust
 * @group BC_QueryApproverList
 */
class BC_QueryApproverListTest extends PHPUnit_Framework_TestCase
{
    protected $validSubmission = array(
        'data' => array(
            'product_type' => '',
            'domain' => '',
            ),
        );

    /**
     * Valid conversion should complete with no
     * exception thrown.
     *
     *
     * @group validconversion
     */
    public function testValidDataConversion()
    {
        $data = json_decode(json_encode($this->validSubmission));

        $data->data->product_type = 'comodo_ev';
        $data->data->domain = 'google.com';

        $shouldMatchNewDataObject = new \stdClass();
        $shouldMatchNewDataObject->attributes = new \stdClass();

        $shouldMatchNewDataObject->attributes->product_type = $data->data->product_type;
        $shouldMatchNewDataObject->attributes->domain = $data->data->domain;

        $qal = new QueryApproverList();

        $newDataObject = $qal->convertDataObject($data);

        $this->assertTrue($newDataObject == $shouldMatchNewDataObject);
    }
}


text:
"""Rec 2020 color class."""
from ..cat import WHITES
from .srgb import sRGB
import math
from .. import algebra as alg
from ..types import Vector

ALPHA = 1.09929682680944
BETA = 0.018053968510807
BETA45 = 0.018053968510807 * 4.5

def lin_2020(rgb: Vector) -> Vector:
    """
    Convert an array of rec-2020 RGB values in the range 0.0 - 1.0 to linear light (un-corrected) form.

    https://en.wikipedia.org/wiki/Rec._2020#Transfer_characteristics
    """

    result = []
    for i in rgb:
        # Mirror linear nature of algorithm on the negative axis
        abs_i = abs(i)
        if abs_i < BETA45:
            result.append(i / 4.5)
        else:
            result.append(math.copysign(alg.nth_root((abs_i + ALPHA - 1) / ALPHA, 0.45), i))
    return result

def gam_2020(rgb: Vector) -> Vector:
    """
    Convert an array of linear-light rec-2020 RGB  in the range 0.0-1.0 to gamma corrected form.

    https://en.wikipedia.org/wiki/Rec._2020#Transfer_characteristics
    """

    result = []
    for i in rgb:
        # Mirror linear nature of algorithm on the negative axis
        abs_i = abs(i)
        if abs_i < BETA:
            result.append(4.5 * i)
        else:
            result.append(math.copysign(ALPHA * (abs_i ** 0.45) - (ALPHA - 1), i))
    return result

class Rec2020(sRGB):
    """Rec 2020 class."""

    BASE = "rec2020-linear"
    NAME = "rec2020"
    WHITE = WHITES['2deg']['D65']

    def to_base(self, coords: Vector) -> Vector:
        """To XYZ from Rec 2020."""

        return lin_2020(coords)

    def from_base(self, coords: Vector) -> Vector:
        """From XYZ to Rec 2020."""

        return gam_2020(coords)


text:
namespace EasyCpp
{
	namespace Net
	{
		namespace Services
		{
			namespace Microsoft
			{
				namespace Cognitive
				{
					class DLL_EXPORT CVOCRRegion : public Serialize::Serializable
					{
					public:
						CVOCRRegion();
						virtual ~CVOCRRegion();

						///<summary>Returns all lines as a single string by concatening with "\n"</summary>
						std::string getText() const;
						const CVBoundingBox& getBoundingBox() const;
						const std::vector<CVOCRLine>& getLines() const;

						// Geerbt über Serializable
						virtual AnyValue toAnyValue() const override;
						virtual void fromAnyValue(const AnyValue & state) override;
					private:
						std::vector<CVOCRLine> _lines;
						CVBoundingBox _bounding_box;
					};
				}
			}
		}
	}
}


text:
/*
 * Adapted from ErlangParserTest.java. Downloaded 21 Apr 2014 from:
 *
 * https://github.com/ignatov/intellij-erlang.
 */

package com.haskforce.parser;

import com.haskforce.HaskellParserDefinition;

public class HaskellParserTest extends HaskellParserTestBase {
    public HaskellParserTest() {
        super("parser", "hs", new HaskellParserDefinition());
    }

    // See comment in HaskellLexerTest.java.
    public void testAStack00001()       { doTest(true, true); }

    public void testArrow00001()        { doTest(true, true); }
    public void testCase00001()         { doTest(true, true); }
    public void testCPP00001()          { doTest(true, true); }
    public void testExport00001()       { doTest(true, true); }
    public void testFun00001()          { doTest(true, true); }
    public void testFun00002()          { doTest(true, true); }
    public void testFun00003()          { doTest(true, true); }
    public void testFun00004()          { doTest(true, true); }
    public void testFun00005()          { doTest(true, true); }
    public void testFun00006()          { doTest(true, true); }
    public void testFun00007()          { doTest(true, true); }
    public void testFun00008()          { doTest(true, true); }
    public void testFun00009()          { doTest(true, true); }
    public void testFun00010()          { doTest(true, true); }
    public void testFun00011()          { doTest(true, true); }
    public void testFun00012()          { doTest(true, true); }
    public void testFun00013()          { doTest(true, true); }
    public void testFFI00001()          { doTest(true, true); }
    public void testFFI00002()          { doTest(true, true); }
    public void testHello00001()        { doTest(true, true); }
    public void testHello00002()        { doTest(true, true); }
    public void testHello00003()        { doTest(true, false); }
    public void testImport00001()       { doTest(true, true); }
    public void testImport00002()       { doTest(true, true); }
    public void testImport00003()       { doTest(true, true); }
    public void testImport00004()       { doTest(true, true); }
    public void testImport00005()       { doTest(true, true); }
    public void testInstanceSigs00001() { doTest(true, true); }
    public void testInfix00001()        { doTest(true, true); }
    public void testKind00001()         { doTest(true, true); }
    // FIXME: Disabled for now. Fails JSON comparison. Line looks truncated.
    // public void testKind00002()         { doTest(true, true); }
    public void testKind00003()         { doTest(true, true); }
    public void testKind00004()         { doTest(true, true); }
    public void testLayout00001()       { doTest(true, true); }
    public void testLayout00002()       { doTest(true, true); }
    public void testLayout00003()       { doTest(true, true); }
    public void testLayout00004()       { doTest(true, true); }
    public void testLayout00005()       { doTest(true, true); }
    public void testLayout00006()       { doTest(true, true); }
    public void testLayout00008()       { doTest(true, true); }
    public void testLayout00009()       { doTest(true, false); }
    public void testLayout00010()       { doTest(true, true); }
    public void testLayout00011()       { doTest(true, true); }
    public void testLayout00012()       { doTest(true, true); }
    public void testLayout00013()       { doTest(true, true); }
    public void testLayout00014()       { doTest(true, true); }
    public void testLayout00015()       { doTest(true, true); }
    public void testLayout00016()       { doTest(true, true); }
    public void testLayout00017()       { doTest(true, true); }
    public void testLayout00018()       { doTest(true, true); }
    // FIXME: Layout00019.hs fails to parse.
    // public void testLayout00019()       { doTest(true, true); }
    public void testLayout00020()       { doTest(true, true); }
    public void testLayout00021()       { doTest(true, true); }
    public void testLayout00022()       { doTest(true, true); }
    public void testLayout00023()       { doTest(true, true); }
    public void testList00001()         { doTest(true, true); }
    public void testComment00001()      { doTest(true, true); }
    public void testComment00002()      { doTest(true, true); }
    public void testComment00003()      { doTest(true, true); }
    public void testComment00006()      { doTest(true, true); }
    public void testComment00007()      { doTest(true, true); }
    public void testComment00008()      { doTest(true, true); }
    public void testLambda00001()       { doTest(true, true); }
    public void testMagicHash00001()    { doTest(true, true); }
    public void testMinimal00001()      { doTest(true, true); }
    public void testModule00001()       { doTest(true, true); }
    public void testOperator00001()     { doTest(true, true); }
    public void testRecord00001()       { doTest(true, true); }
    public void testRecord00002()       { doTest(true, true); }
    public void testPragma00001()       { doTest(true, true); }
    public void testPragma00002()       { doTest(true, true); }
    public void testPragma00003()       { doTest(true, true); }
    public void testPragma00004()       { doTest(true, true); }
    public void testProc00001()         { doTest(true, true); }
    public void testStrict00001()       { doTest(true, true); }
    public void testString00001()       { doTest(true, true); }
    public void testString00002()       { doTest(true, true); }
    public void testString00003()       { doTest(true, true); }
    public void testString00004()       { doTest(true, false); }
    public void testString00005()       { doTest(true, true); }
    public void testString00006()       { doTest(true, true); }
    public void testTempHask00001()     { doTest(true, true); }
    public void testTempHask00002()     { doTest(true, true); }
    public void testTempHask00003()     { doTest(true, true); }
    public void testTempHask00004()     { doTest(true, true); }
    public void testTempHask00005()     { doTest(true, true); }
    public void testUnicode00001()      { doTest(true, true); }
    public void testType00001()         { doTest(true, true); }
    public void testType00002()         { doTest(true, true); }
    public void testType00003()         { doTest(true, true); }
    public void testType00004()         { doTest(true, true); }
    public void testType00005()         { doTest(true, true); }
    public void testType00006()         { doTest(true, true); }
    public void testVar00001()          { doTest(true, true); }
    public void testViewPatterns00001() { doTest(true, true); }
    public void testQuote00001()        { doTest(true, true); }
    public void testForAll00001()        { doTest(true, true); }
    // public void testParseMonad()        { doTest(true, true); }

    // TODO: Change to doTest(true, true) after bug fixes.
    // Note that testInternalLexer seems to output different parse trees between IntelliJ 13 and 14.
    // This is probably due to the excessive DUMMY_BLOCKs throughout the parse result.
    // public void testInternalLexer()     { doTest(true, false); }
}


text:
if test x"$CHROME_VALGRIND_BIN" = x
then
  # Figure out which valgrind is installed.  Use most recent one.
  # See build-valgrind-for-chromium.sh and its history for these constants.
  for SVNREV in 10880-redzone 10880 10771 20090715
  do
    CHROME_VALGRIND_BIN=/usr/local/valgrind-$SVNREV/bin
    test -x $CHROME_VALGRIND_BIN/valgrind && break
  done
fi

if ! test -x $CHROME_VALGRIND_BIN/valgrind
then
  echo "Could not find chromium's version of valgrind."
  echo "Please run build-valgrind-for-chromium.sh or set CHROME_VALGRIND_BIN."
  echo "Defaulting to system valgrind."
else
  echo "Using ${CHROME_VALGRIND_BIN}/valgrind."
  PATH="${CHROME_VALGRIND_BIN}:$PATH"
fi

cat > vlayout-wrapper.sh <<"_EOF_"
#!/bin/sh
valgrind --suppressions=tools/valgrind/memcheck/suppressions.txt --tool=memcheck --smc-check=all --num-callers=30 --trace-children=yes --leak-check=full --show-possibly-lost=no --log-file=vlayout-%p.log --gen-suppressions=all --track-origins=yes "$@"
_EOF_
chmod +x vlayout-wrapper.sh

rm -f vlayout-*.log
export BROWSER_WRAPPER=`pwd`/vlayout-wrapper.sh
export G_SLICE=always-malloc
export NSS_DISABLE_ARENA_FREE_LIST=1
sh webkit/tools/layout_tests/run_webkit_tests.sh --run-singly -v --noshow-results --time-out-ms=200000 --nocheck-sys-deps --debug "$@"

# Have to wait a bit for the output files to finish
nfiles=`ls vlayout-*.log | wc -l`
while true
do
  ndone=`egrep -l "LEAK SUMMARY|no leaks are possible" vlayout-*.log | wc -l`
  if test $nfiles = $ndone
  then
    break
  fi
  echo "Waiting for valgrind to finish..."
  sleep 1
done
cat vlayout-*.log


text:
<?php

return [

    'heading' => 'OUR WORK PROCESS',
    'subheading' => 'ANALYZE, DESIGN, IMPLEMENT, MEASURE, EDUCATE, SUPPORT',
    'i1_h4' => 'PLAN',
    'i1_p' => 'Set up goals, actions, budget and timing. Allocate resources. Identify challanges. Monitoring progress. Assign tasks. ',
    'i2_h4' => 'ACT',
    'i2_p' => 'Start execution. Manage processes. Follow priorities. Collect and analyze data. Measure and monitor. Evaluate. Make adjustments. ',
    'i3_h4' => 'STUDY',
    'i3_p' => 'Celebrate success. Communicate results. Review, Revise and Continuously Improve. Evaluate strategy. Learn and educate.',
    'button' => 'GET A FREE QUOTE',
    'c1' => '2', //javascript-ből jön, ez csak a fallback-je (main.js)
    'ct1' => 'CONTINENTS',
    'c2' => '14', //javascript-ből jön, ez csak a fallback-je (main.js)
    'ct2' => 'COUNTRIES',
    'c3' => '128', //javascript-ből jön, ez csak a fallback-je (main.js)
    'ct3' => 'CUSTOMERS',
    'c4' => '167', //javascript-ből jön, ez csak a fallback-je (main.js)
    'ct4' => 'BUSINESS PARTNERS',
];


text:
.. _ref_edgeql_http:

================
EdgeQL over HTTP
================

EdgeDB can expose an HTTP endpoint for EdgeQL queries. Since HTTP is a
stateless protocol, no :ref:`DDL <ref_eql_ddl>`,
:ref:`transaction commands <ref_eql_statements_start_tx>`,
can be executed using this endpoint.  Only one query per request can be
executed.

In order to set up HTTP access to the database add the following to
the schema:

.. code-block:: sdl

    using extension edgeql_http;

Then create a new migration and apply it using
:ref:`ref_cli_edgedb_migration_create` and
:ref:`ref_cli_edgedb_migrate`, respectively.

Your instance can now receive EdgeQL queries over HTTP at
``http://<hostname>:<port>/db/<database-name>/edgeql``.

In development:

- The ``hostname`` will be ``localhost``
- Find the ``port`` by running ``edgedb instance list``. This will print a
  table of all EdgeDB instances on your machine, including their associated
  port number.
- In most cases, ``database_name`` will be ``edgedb``. An EdgeDB *instance*
  can contain multiple databases. On initialization, a default database called
  ``edgedb`` is created; all queries are executed against this database unless
  otherwise specified.

.. toctree::
    :maxdepth: 2
    :hidden:

    protocol


text:
package br.com.felipo.banco.conta;

/**
 * Conta base que oferece uma implementação padrão a ser usada pelos tipos específicos de conta.
 *
 * @author Felipo
 *
 */
public class Conta {

	private int numero;
	protected double saldo;
	private double limite;

	public int getNumero() {
		return numero;
	}

	public void setNumero(int numero) {
		this.numero = numero;
	}

	@Override
	public boolean equals(Object obj) {
		Conta c = (Conta) obj;
		return this.numero == c.numero;
	}

	/**
	 * Efetua o depósito de um valor, mas não permite valores negativos.
	 * @param valor Valor que será depositado na conta.
	 * @throws ValorInvalidoException Se o valor for negativo.
	 */
	public void deposita(double valor) throws ValorInvalidoException {
		if (valor < 0) {
			throw new ValorInvalidoException(valor);
		} else {
			this.saldo += valor;
		}
	}

	public double getSaldo() {
		return this.saldo;
	}

	public void setLimite(double limite) {
		this.limite = limite;
	}

	/**
	 * Realiza o saque de um determinado valor da conta. Não permite sacar além do limite definido na conta.
	 *
	 * @param valor Valor a ser sacado da conta.
	 * @throws SaldoInsuficienteException Se o valor do saque for maior que o saldo e o limite da conta.
	 */
	public void saca(double valor) throws SaldoInsuficienteException {
		if (valor < this.saldo + this.limite) {
			this.saldo -= valor;
		} else {
			throw new SaldoInsuficienteException("Saldo insuficiente, tente um valor menor.");
		}
	}

	/**
	 * Transfere de uma conta para outra, respeitando se a conta de origem possui saldo.
	 * @param destino Conta para a qual será feita a transferência.
	 * @param valor Valor a ser transferido.
	 * @throws SaldoInsuficienteException Se a conta de origem não tiver saldo suficiente.
	 * @throws ValorInvalidoException Se o valor transferido for negativo.
	 */
	public void transferePara(IConta destino, double valor) throws SaldoInsuficienteException, ValorInvalidoException {
		this.saca(valor);
		destino.deposita(valor);
	}
}


text:
namespace webkit_blob {

namespace {
void SetupBasicBlob(BlobStorageHost* host, const std::string& id) {
  EXPECT_TRUE(host->StartBuildingBlob(id));
  BlobData::Item item;
  item.SetToBytes("1", 1);
  EXPECT_TRUE(host->AppendBlobDataItem(id, item));
  EXPECT_TRUE(host->FinishBuildingBlob(id, "text/plain"));
  EXPECT_FALSE(host->StartBuildingBlob(id));
}
}  // namespace

TEST(BlobStorageContextTest, IncrementDecrementRef) {
  BlobStorageContext context;
  BlobStorageHost host(&context);
  base::MessageLoop fake_io_message_loop;

  // Build up a basic blob.
  const std::string kId("id");
  SetupBasicBlob(&host, kId);

  // Make sure it's there, finish building implies a ref of one.
  scoped_ptr<BlobDataHandle> blob_data_handle;
  blob_data_handle = context.GetBlobDataFromUUID(kId);
  EXPECT_TRUE(blob_data_handle);
  blob_data_handle.reset();

  // Make sure its still there after inc/dec.
  EXPECT_TRUE(host.IncrementBlobRefCount(kId));
  EXPECT_TRUE(host.DecrementBlobRefCount(kId));
  blob_data_handle = context.GetBlobDataFromUUID(kId);
  EXPECT_TRUE(blob_data_handle);
  blob_data_handle.reset();

  // Make sure it goes away in the end.
  EXPECT_TRUE(host.DecrementBlobRefCount(kId));
  blob_data_handle = context.GetBlobDataFromUUID(kId);
  EXPECT_FALSE(blob_data_handle);
  EXPECT_FALSE(host.DecrementBlobRefCount(kId));
  EXPECT_FALSE(host.IncrementBlobRefCount(kId));
}

TEST(BlobStorageContextTest, BlobDataHandle) {
  BlobStorageContext context;
  BlobStorageHost host(&context);
  base::MessageLoop fake_io_message_loop;

  // Build up a basic blob.
  const std::string kId("id");
  SetupBasicBlob(&host, kId);

  // Get a handle to it.
  scoped_ptr<BlobDataHandle> blob_data_handle =
      context.GetBlobDataFromUUID(kId);
  EXPECT_TRUE(blob_data_handle);

  // Drop the host's ref to it.
  EXPECT_TRUE(host.DecrementBlobRefCount(kId));

  // Should still be there due to the handle.
  scoped_ptr<BlobDataHandle> another_handle =
      context.GetBlobDataFromUUID(kId);
  EXPECT_TRUE(another_handle);

  // Should disappear after dropping both handles.
  blob_data_handle.reset();
  another_handle.reset();
  blob_data_handle = context.GetBlobDataFromUUID(kId);
  EXPECT_FALSE(blob_data_handle);
}

TEST(BlobStorageContextTest, CompoundBlobs) {
  const std::string kId1("id1");
  const std::string kId2("id2");
  const std::string kId2Prime("id2.prime");

  base::MessageLoop fake_io_message_loop;

  // Setup a set of blob data for testing.
  base::Time time1, time2;
  base::Time::FromString("Tue, 15 Nov 1994, 12:45:26 GMT", &time1);
  base::Time::FromString("Mon, 14 Nov 1994, 11:30:49 GMT", &time2);

  scoped_refptr<BlobData> blob_data1(new BlobData(kId1));
  blob_data1->AppendData("Data1");
  blob_data1->AppendData("Data2");
  blob_data1->AppendFile(base::FilePath(FILE_PATH_LITERAL("File1.txt")),
    10, 1024, time1);

  scoped_refptr<BlobData> blob_data2(new BlobData(kId2));
  blob_data2->AppendData("Data3");
  blob_data2->AppendBlob(kId1, 8, 100);
  blob_data2->AppendFile(base::FilePath(FILE_PATH_LITERAL("File2.txt")),
      0, 20, time2);

  scoped_refptr<BlobData> canonicalized_blob_data2(new BlobData(kId2Prime));
  canonicalized_blob_data2->AppendData("Data3");
  canonicalized_blob_data2->AppendData("a2___", 2);
  canonicalized_blob_data2->AppendFile(
      base::FilePath(FILE_PATH_LITERAL("File1.txt")),
      10, 98, time1);
  canonicalized_blob_data2->AppendFile(
      base::FilePath(FILE_PATH_LITERAL("File2.txt")), 0, 20, time2);

  BlobStorageContext context;
  scoped_ptr<BlobDataHandle> blob_data_handle;

  // Test a blob referring to only data and a file.
  blob_data_handle = context.AddFinishedBlob(blob_data1.get());
  ASSERT_TRUE(blob_data_handle.get());
  EXPECT_TRUE(*(blob_data_handle->data()) == *blob_data1.get());

  // Test a blob composed in part with another blob.
  blob_data_handle = context.AddFinishedBlob(blob_data2.get());
  ASSERT_TRUE(blob_data_handle.get());
  EXPECT_TRUE(*(blob_data_handle->data()) == *canonicalized_blob_data2.get());
}

TEST(BlobStorageContextTest, PublicBlobUrls) {
  BlobStorageContext context;
  BlobStorageHost host(&context);
  base::MessageLoop fake_io_message_loop;

  // Build up a basic blob.
  const std::string kId("id");
  SetupBasicBlob(&host, kId);

  // Now register a url for that blob.
  GURL kUrl("blob:id");
  EXPECT_TRUE(host.RegisterPublicBlobURL(kUrl, kId));
  scoped_ptr<BlobDataHandle> blob_data_handle =
      context.GetBlobDataFromPublicURL(kUrl);
  ASSERT_TRUE(blob_data_handle.get());
  EXPECT_EQ(kId, blob_data_handle->data()->uuid());
  blob_data_handle.reset();

  // The url registration should keep the blob alive even after
  // explicit references are dropped.
  EXPECT_TRUE(host.DecrementBlobRefCount(kId));
  blob_data_handle = context.GetBlobDataFromPublicURL(kUrl);
  EXPECT_TRUE(blob_data_handle);
  blob_data_handle.reset();

  // Finally get rid of the url registration and the blob.
  EXPECT_TRUE(host.RevokePublicBlobURL(kUrl));
  blob_data_handle = context.GetBlobDataFromPublicURL(kUrl);
  EXPECT_TRUE(!blob_data_handle.get());
  EXPECT_FALSE(host.RevokePublicBlobURL(kUrl));
}

TEST(BlobStorageContextTest, HostCleanup) {
  BlobStorageContext context;
  scoped_ptr<BlobStorageHost> host(new BlobStorageHost(&context));
  base::MessageLoop fake_io_message_loop;

  // Build up a basic blob and register a url
  const std::string kId("id");
  GURL kUrl("blob:id");
  SetupBasicBlob(host.get(), kId);
  EXPECT_TRUE(host->RegisterPublicBlobURL(kUrl, kId));

  // All should disappear upon host deletion.
  host.reset();
  scoped_ptr<BlobDataHandle> handle = context.GetBlobDataFromPublicURL(kUrl);
  EXPECT_TRUE(!handle.get());
  handle = context.GetBlobDataFromUUID(kId);
  EXPECT_TRUE(!handle.get());
}

TEST(BlobStorageContextTest, EarlyContextDeletion) {
  scoped_ptr<BlobStorageContext> context(new BlobStorageContext);
  BlobStorageHost host(context.get());
  base::MessageLoop fake_io_message_loop;

  // Deleting the context should not induce crashes.
  context.reset();

  const std::string kId("id");
  GURL kUrl("blob:id");
  EXPECT_FALSE(host.StartBuildingBlob(kId));
  BlobData::Item item;
  item.SetToBytes("1", 1);
  EXPECT_FALSE(host.AppendBlobDataItem(kId, item));
  EXPECT_FALSE(host.FinishBuildingBlob(kId, "text/plain"));
  EXPECT_FALSE(host.RegisterPublicBlobURL(kUrl, kId));
  EXPECT_FALSE(host.IncrementBlobRefCount(kId));
  EXPECT_FALSE(host.DecrementBlobRefCount(kId));
  EXPECT_FALSE(host.RevokePublicBlobURL(kUrl));
}

}  // namespace webkit_blob


text:
package com.taobao.weex.bridge;

import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ws.WebSocket;
import com.taobao.weex.WXEnvironment;
import com.taobao.weex.WXSDKManager;
import com.taobao.weex.common.IWXBridge;
import com.taobao.weex.utils.WXLogUtils;
import com.taobao.weex.websocket.WXWebSocketManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okio.BufferedSource;

/**
 * websocket bridge
 *
 * @author gulin
 */
public class WXWebsocketBridge implements IWXBridge,WXWebSocketManager.JSDebuggerCallback {

    private WXBridgeManager mJsManager;
    private volatile boolean mInit = false;

    public WXWebsocketBridge(WXBridgeManager jm) {
        mJsManager = jm;
        WXWebSocketManager.getInstance().registerListener(this);
    }

    @Override
    public int execJS(String instanceId, String namespace, String function,
                      WXJSObject[] args) {
        if (!mInit || TextUtils.isEmpty(instanceId)
                || TextUtils.isEmpty(function)) {
            return -1;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("method", function);

        ArrayList<Object> array = new ArrayList<>();
        int argsCount = args == null ? 0 : args.length;
        for (int i = 0; i < argsCount; i++) {
            if (args[i].type != WXJSObject.String) {
                array.add(JSON.parse(args[i].data.toString()));
            } else {
                array.add(args[i].data);
            }
        }
        map.put("arguments", array);
        WXWebSocketManager.getInstance().sendMessage(JSON.toJSONString(map));
        return 0;
    }

    @Override
    public int callNative(String instanceId, String tasks, String callback) {
        if (!mInit || mJsManager == null)
            return WXBridgeManager.INSTANCE_RENDERING_ERROR ;
        mJsManager.callNative(instanceId, tasks, callback);
        return WXBridgeManager.INSTANCE_RENDERING;
    }

    @Override
    public int initFramework(String scriptsFramework,WXParams params) {
        if (!mInit) {
            return -1;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("method", "evalFramework");
        ArrayList<String> args = new ArrayList<>();
        args.add(scriptsFramework);
        map.put("arguments", args);
        WXWebSocketManager.getInstance().sendMessage(JSON.toJSONString(map));
        return 0;
    }

    @Override
    public void reportJSException(String instanceId, String func, String exception) {
        if (mJsManager != null) {
            mJsManager.reportJSException(instanceId, func, exception);
        }
    }

    @Override
    public void onMessage(BufferedSource payload, WebSocket.PayloadType type) {
        if (type != WebSocket.PayloadType.TEXT) {
            WXLogUtils.w("Websocket received unexpected message with payload of type " + type);
            return;
        }

        String message = null;
        try {
            message = payload.readUtf8();
            JSONObject jsonObject = JSONObject.parseObject(message);
            Object name = jsonObject.get("name");
            Object value = jsonObject.get("value");
            if (name == null || value == null) {
                return;
            }
            if (name.toString().equals("callNative")) {
                JSONArray jsonArray = JSONObject.parseArray(value.toString());
                callNative(jsonArray.getString(0), jsonArray.getString(1),
                           jsonArray.getString(2));
            }
        } catch (Exception e) {

        } finally {
            try {
                payload.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onSuccess(Response response) {
        if(response.isSuccessful()){
            WXSDKManager.getInstance().postOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(WXEnvironment.sApplication,"Has switched to DEBUG mode, you can see the DEBUG information on the browser!",Toast.LENGTH_SHORT).show();
                }
            },0);
        }
    }

    @Override
    public void onFailure(Throwable cause) {
        Toast.makeText(WXEnvironment.sApplication,"socket connect failure!",Toast.LENGTH_SHORT).show();
    }
}


text:
package is.landsbokasafn.crawler.rss;

import com.rometools.rome.feed.synd.SyndCategory;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndPerson;

/**
 * Created by abhijit on 04/11/15.
 */
public class RssEntry {
    public final String link;
    public final String title;
    public final List<String> author;
    public final String description;
    public final List<String> categories;
    public final Date date;

//    public RssEntry(String link, String title, List<String> author, String description, String categories, Date date) {
//        this.link = link;
//        this.title = title;
//        this.author = author;
//        this.description = description;
//        this.categories = categories;
//        this.date = date;
//    }

    public RssEntry(SyndEntry entry) {
        this.link = entry.getLink();
        this.title = entry.getTitle();
        this.author = new ArrayList<String>(entry.getAuthors().size());
        for (SyndPerson person : entry.getAuthors() )
            this.author.add(person.getName());

        this.categories = new ArrayList<String>(entry.getCategories().size());
        for (SyndCategory category : entry.getCategories())
            this.categories.add(category.getName());

        this.date = entry.getPublishedDate();
        this.description = entry.getDescription().getValue();
    }

    public Map<String, String> getRecords() {
        Map<String, String> map = new HashMap<String, String>();
        String[][] vals = new String[][] {
                { "link", this.link },
                { "title" , this.title},
                { "author", this.author.toString()},
                { "categories", this.categories.toString()},
                { "date", this.date.toString() },
                { "description", this.description }
        };

        for (String[] val : vals) {
            if (vals[1] != null)
                map.put(val[0], val[1]);
        }

        return map;
    }
}


text:
1- Create a work directory
```
mkdir -p lk-work && cd lk-work
```
2- Clone the repo
```
git clone https://github.com/littlekernel/lk
```
3- Download appropriate toolchain and extract it
```
wget https://newos.org/toolchains/riscv64-elf-12.1.0-Linux-x86_64.tar.xz

mkdir -p toolchain
tar xf riscv64-elf-12.1.0-Linux-x86_64.tar.xz
cd ..
```
4- Add toolchain to PATH
```
export PATH=$PWD/toolchain/riscv64-elf-12.1.0-Linux-x86_64/bin:$PATH
```
5- Change dir to lk to build and find available project
```
cd lk
ls project/*
```
6- E.g pick `qemu-virt-riscv64-test` and build kernel
```
make qemu-virt-riscv64-test
```
7- Test kernel with Qemu by using prepared script
```
scripts/do-qemuriscv -6
```

#### Build A Hello App
Continue from Quick Start's 3.step

4- Create your workspace and enter in it
```
mkdir -p mylk/{project,app} && cd mylk
```
5- Configure your main makefile; set your toolchain path and point up your lk main path correctly
```
cat << EOF > makefile
export PATH := /home/myuser/lk-work/toolchain/riscv64-elf-12.1.0-Linux-x86_64/bin:$(PATH)
-include lk_inc.mk
LOCAL_DIR := .
LKMAKEROOT := .
LKROOT := ../lk
LKINC := $(LOCAL_DIR)
DEFAULT_PROJECT ?= myqr
BUILDROOT ?= $(LOCAL_DIR)

ifeq ($(filter $(LKROOT),$(LKINC)), )
LKINC := $(LKROOT) $(LKINC)
endif

ifneq ($(LKROOT),.)
LKINC += $(LKROOT)/external
else
LKINC += external
endif

export LKMAKEROOT
export LKROOT
export LKINC
export BUILDROOT
export DEFAULT_PROJECT
export TOOLCHAIN_PREFIX
_top:
    @$(MAKE) -C $(LKMAKEROOT) -rR -f $(LKROOT)/engine.mk $(addprefix -I,$(LKINC)) $(MAKECMDGOALS)
$(MAKECMDGOALS): _top
    @:
.PHONY: _top
EOF
```
6- Copy an exisiting project as your new project
```
cp ../lk/project/qemu-virt-riscv64-test.mk project/project1.mk
```
7- Create a new hello app under app directory
```
mkdir app/hello
```
```
cat << EOF > app/hello/hello.c
production:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <app.h>
#include <platform.h>
#include <lk/console_cmd.h>

static int hello(int argc, const console_cmd_args *argv) {
    printf("hello world\n");
    return 0;
}

STATIC_COMMAND_START
STATIC_COMMAND("hello", "hello tests", &hello)
STATIC_COMMAND_END(hello);

APP_START(hello)
APP_END
EOF
```
```
cat << EOF > app/hello/rules.mk
LOCAL_DIR := $(GET_LOCAL_DIR)

MODULE := $(LOCAL_DIR)

MODULE_SRCS += $(LOCAL_DIR)/hello.c

include make/module.mk
EOF
```
8- Add below line to project's makefile (project/project1.mk), your project will build also your app:
```
MODULES +=  app/hello
```

9- Check your directories structure
```
# mylk
tree
.
├── app
│   └── hello
│       ├── hello.c
│       └── rules.mk
├── makefile
└── project
    └── project1.mk
```
```
# lk-work
tree ../ -d -L 1
../.
├── lk
├── mylk
└── toolchain/riscv64-elf-12.1.0-Linux-x86_64

```
10- Build your project
```
make project1
```

11- Run your kernel with Qemu
```
qemu-system-riscv64 -machine virt -cpu rv64 -m 48 -smp 1 -bios none -nographic -kernel build-project1/lk.elf
```
You will see this output
```
FDT: found memory arena, base 0x80000000 size 0x3000000
FDT: found 1 cpus

welcome to lk/MP

boot args 0x0 0x1020 0x0 0x0
INIT: cpu 0, calling hook 0x8001e3b8 (version) at level 0x3ffff, flags 0x1
version:
	arch:     riscv
	platform: qemu-virt-riscv
	target:   qemu-virt-riscv
	project:  project1
	buildid:  L96DH_LOCAL
initializing heap
calling constructors
initializing mp
initializing threads
initializing timers
initializing ports
creating bootstrap completion thread
top of bootstrap2()
INIT: cpu 0, calling hook 0x8001a848 (minip) at level 0x70000, flags 0x1
INIT: cpu 0, calling hook 0x8001b6c6 (pktbuf) at level 0x70000, flags 0x1
pktbuf: creating 256 pktbuf entries of size 1536 (total 393216)
INIT: cpu 0, calling hook 0x8001fe08 (virtio) at level 0x70000, flags 0x1
RISCV: percpu cpu num 0x0 hart id 0x0
RISCV: Machine mode
RISCV: mvendorid 0x0 marchid 0x0 mimpid 0x0 mhartid 0x0
RISCV: misa 0x800000000014112d
RISCV: Releasing 0 secondary harts from purgatory
initializing platform
PCIE: initializing pcie with ecam at 0x30000000 found in FDT
PCI: pci ecam functions installed
PCI: last pci bus is 255
PCI dump:
  bus 0
   dev 0000:00:00.0 vid:pid 1b36:0008 base:sub:intr 6:0:0
PCI dump post assign:
  bus 0
   dev 0000:00:00.0 vid:pid 1b36:0008 base:sub:intr 6:0:0
initializing target
initializing apps
starting app inetsrv
starting internet servers
starting app shell
entering main console loop
]
```
12- Test your hello application
```
] hello
hello world

```


text: """Support for Ezviz devices via Ezviz Cloud API."""


text:
'use strict';

function precompileGlobal(templates, opts) {
    var out = '', name, template;
    opts = opts || {};

    for ( var i = 0; i < templates.length; i++ ) {
        // replace all backslashes with forward slashes
        var normalizedName = templates[i].name.replace(/\\/g, '');
        name = JSON.stringify(normalizedName);
        template = templates[i].template;

        out += '(function() {' +
            '(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})' +
            '[' + name + '] = (function() {\n' + template + '\n})();\n';

        if(opts.asFunction) {
            out += 'return function(ctx, cb) { return nunjucks.render(' + name + ', ctx, cb); }\n';
        }

        out += '})();\n';
    }
    return out;
}

module.exports = precompileGlobal;


text:
package com.gbr.nyan.appdirect.entity;

public class SubscriptionAccount {
    private String accountIdentifier;

    public String getAccountIdentifier() {
        return accountIdentifier;
    }

    public void setAccountIdentifier(String accountIdentifier) {
        this.accountIdentifier = accountIdentifier;
    }
}


text:
@implementation DJSearchResultsController
{
    UISearchBar         *mSearchBar;
    NSArray             *mContentsList;
    NSInteger           mSelectedIndex;
    DJContentsManager   *mContentsManager;

    BOOL                mSearchBarEditting;
}

@synthesize searchBarEditting = mSearchBarEditting;

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    if (self)
    {
        mSearchBarEditting = NO;
    }

    return self;
}

#pragma mark - view

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setupViewAttributes];

    mContentsManager = [[DJContentsManager alloc] init];
    [mContentsManager setDelegate:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

    if ([self isViewLoaded])
    {
        mSearchBar = nil;
        mContentsList = nil;
        mContentsManager = nil;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self setupSearchBar];

    if (mSearchBarEditting)
    {
        [mSearchBar becomeFirstResponder];
    }
    mSearchBarEditting = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [mSearchBar removeFromSuperview];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [mContentsList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DJSearchResultsCell *cell = [[self tableView] dequeueReusableCellWithIdentifier:@"searchList"];
    DJContents *contents = [mContentsList objectAtIndex:[indexPath row]];
    NSString *title = [[[contents reference] componentsSeparatedByString:@"中"] objectAtIndex:0];
    [cell inputTitle:title body:[contents body] category:[contents category]];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    mSelectedIndex = [indexPath row];
    [self performSegueWithIdentifier:@"search" sender:self];
}

#pragma mark - navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"search"])
    {
        id destinationController = [segue destinationViewController];
        [destinationController setContents:[mContentsList objectAtIndex:mSelectedIndex]];
    }

}

#pragma mark - search bar delegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setText:@""];
    mContentsList = nil;
    [[self tableView] reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([searchText isEqualToString:@""])
    {
        mContentsList = nil;
        [[self tableView] reloadData];
        return;
    }

    [mContentsManager contentsFromParseDBWithSearchText:searchText];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [mSearchBar endEditing:YES];
}

#pragma mark - contents manager delegate

- (void)contentsManager:(DJContentsManager *)aContentsManager didFinishGetContentsList:(NSArray *)contentsList
{
    mContentsList = [NSArray arrayWithArray:contentsList];
    [[self tableView] reloadData];
}

#pragma mark - setup

- (void)setupViewAttributes
{
    [[self tableView] setDataSource:self];
    [[self tableView] setDelegate:self];
    [[self tableView] setBackgroundColor:[UIColor DJIvoryColor]];
    [[self tableView] setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}

- (void)setupSearchBar
{
    UINavigationBar *navBar = [[self navigationController] navigationBar];
    CGFloat width = [navBar bounds].size.width - 70;
    CGFloat height = [navBar bounds].size.height;

    mSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(80, 0, width - 20, height)];
    [mSearchBar setTranslucent:YES];
    [mSearchBar setBarTintColor:[UIColor DJMintColor]];
    [mSearchBar setDelegate:self];

    [navBar addSubview:mSearchBar];
}

@end


text:
package org.onosproject.net.host.impl;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import org.junit.After;
import org.junit.Test;
import org.onlab.packet.ARP;
import org.onlab.packet.Ethernet;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onlab.packet.VlanId;
import org.onosproject.incubator.net.intf.Interface;
import org.onosproject.incubator.net.intf.InterfaceService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Host;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceServiceAdapter;
import org.onosproject.net.flow.instructions.Instruction;
import org.onosproject.net.flow.instructions.Instructions.OutputInstruction;
import org.onosproject.net.host.HostProvider;
import org.onosproject.net.host.InterfaceIpAddress;
import org.onosproject.net.host.PortAddresses;
import org.onosproject.net.packet.OutboundPacket;
import org.onosproject.net.packet.PacketServiceAdapter;
import org.onosproject.net.provider.ProviderId;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class HostMonitorTest {

    private static final IpAddress TARGET_IP_ADDR =
            IpAddress.valueOf("10.0.0.1");
    private static final IpAddress SOURCE_ADDR =
            IpAddress.valueOf("10.0.0.99");
    private static final InterfaceIpAddress IA1 =
            new InterfaceIpAddress(SOURCE_ADDR, IpPrefix.valueOf("10.0.0.0/24"));
    private MacAddress sourceMac = MacAddress.valueOf(1L);

    private HostMonitor hostMonitor;

    @After
    public void shutdown() {
        hostMonitor.shutdown();
    }

    @Test
    public void testMonitorHostExists() throws Exception {
        ProviderId id = new ProviderId("fake://", "id");

        Host host = createMock(Host.class);
        expect(host.providerId()).andReturn(id);
        replay(host);

        HostManager hostManager = createMock(HostManager.class);
        expect(hostManager.getHostsByIp(TARGET_IP_ADDR))
                .andReturn(Collections.singleton(host));
        replay(hostManager);

        HostProvider hostProvider = createMock(HostProvider.class);
        expect(hostProvider.id()).andReturn(id).anyTimes();
        hostProvider.triggerProbe(host);
        expectLastCall().once();
        replay(hostProvider);

        hostMonitor = new HostMonitor(null, hostManager, null);

        hostMonitor.registerHostProvider(hostProvider);
        hostMonitor.addMonitoringFor(TARGET_IP_ADDR);

        hostMonitor.run(null);

        verify(hostProvider);
    }

    @Test
    public void testMonitorHostDoesNotExist() throws Exception {

        HostManager hostManager = createMock(HostManager.class);

        DeviceId devId = DeviceId.deviceId("fake");

        Device device = createMock(Device.class);
        expect(device.id()).andReturn(devId).anyTimes();
        replay(device);

        PortNumber portNum = PortNumber.portNumber(1L);

        Port port = createMock(Port.class);
        expect(port.number()).andReturn(portNum).anyTimes();
        replay(port);

        TestDeviceService deviceService = new TestDeviceService();
        deviceService.addDevice(device, Collections.singleton(port));

        ConnectPoint cp = new ConnectPoint(devId, portNum);
        PortAddresses pa =
                new PortAddresses(cp, Collections.singleton(IA1), sourceMac, VlanId.NONE);

        expect(hostManager.getHostsByIp(TARGET_IP_ADDR))
                .andReturn(Collections.emptySet()).anyTimes();
        replay(hostManager);

        InterfaceService interfaceService = createMock(InterfaceService.class);
        expect(interfaceService.getMatchingInterface(TARGET_IP_ADDR))
                .andReturn(new Interface(cp, Collections.singleton(IA1), sourceMac, VlanId.NONE))
                .anyTimes();
        replay(interfaceService);

        TestPacketService packetService = new TestPacketService();

        // Run the test
        hostMonitor = new HostMonitor(packetService, hostManager, interfaceService);

        hostMonitor.addMonitoringFor(TARGET_IP_ADDR);
        hostMonitor.run(null);

        // Check that a packet was sent to our PacketService and that it has
        // the properties we expect
        assertEquals(1, packetService.packets.size());
        OutboundPacket packet = packetService.packets.get(0);

        // Check the output port is correct
        assertEquals(1, packet.treatment().immediate().size());
        Instruction instruction = packet.treatment().immediate().get(0);
        assertTrue(instruction instanceof OutputInstruction);
        OutputInstruction oi = (OutputInstruction) instruction;
        assertEquals(portNum, oi.port());

        // Check the output packet is correct (well the important bits anyway)
        final byte[] pktData = new byte[packet.data().remaining()];
        packet.data().get(pktData);
        Ethernet eth = Ethernet.deserializer().deserialize(pktData, 0, pktData.length);
        assertEquals(Ethernet.VLAN_UNTAGGED, eth.getVlanID());
        ARP arp = (ARP) eth.getPayload();
        assertArrayEquals(SOURCE_ADDR.toOctets(),
                          arp.getSenderProtocolAddress());
        assertArrayEquals(sourceMac.toBytes(),
                          arp.getSenderHardwareAddress());
        assertArrayEquals(TARGET_IP_ADDR.toOctets(),
                          arp.getTargetProtocolAddress());
    }

    @Test
    public void testMonitorHostDoesNotExistWithVlan() throws Exception {

        HostManager hostManager = createMock(HostManager.class);

        DeviceId devId = DeviceId.deviceId("fake");
        short vlan = 5;

        Device device = createMock(Device.class);
        expect(device.id()).andReturn(devId).anyTimes();
        replay(device);

        PortNumber portNum = PortNumber.portNumber(1L);

        Port port = createMock(Port.class);
        expect(port.number()).andReturn(portNum).anyTimes();
        replay(port);

        TestDeviceService deviceService = new TestDeviceService();
        deviceService.addDevice(device, Collections.singleton(port));

        ConnectPoint cp = new ConnectPoint(devId, portNum);
        PortAddresses pa =
                new PortAddresses(cp, Collections.singleton(IA1), sourceMac,
                                  VlanId.vlanId(vlan));

        expect(hostManager.getHostsByIp(TARGET_IP_ADDR))
                .andReturn(Collections.emptySet()).anyTimes();
        replay(hostManager);

        InterfaceService interfaceService = createMock(InterfaceService.class);
        expect(interfaceService.getMatchingInterface(TARGET_IP_ADDR))
                .andReturn(new Interface(cp, Collections.singleton(IA1), sourceMac, VlanId.vlanId(vlan)))
                .anyTimes();
        replay(interfaceService);

        TestPacketService packetService = new TestPacketService();

        // Run the test
        hostMonitor = new HostMonitor(packetService, hostManager, interfaceService);

        hostMonitor.addMonitoringFor(TARGET_IP_ADDR);
        hostMonitor.run(null);

        // Check that a packet was sent to our PacketService and that it has
        // the properties we expect
        assertEquals(1, packetService.packets.size());
        OutboundPacket packet = packetService.packets.get(0);

        // Check the output port is correct
        assertEquals(1, packet.treatment().immediate().size());
        Instruction instruction = packet.treatment().immediate().get(0);
        assertTrue(instruction instanceof OutputInstruction);
        OutputInstruction oi = (OutputInstruction) instruction;
        assertEquals(portNum, oi.port());

        // Check the output packet is correct (well the important bits anyway)
        final byte[] pktData = new byte[packet.data().remaining()];
        packet.data().get(pktData);
        Ethernet eth = Ethernet.deserializer().deserialize(pktData, 0, pktData.length);
        assertEquals(vlan, eth.getVlanID());
        ARP arp = (ARP) eth.getPayload();
        assertArrayEquals(SOURCE_ADDR.toOctets(),
                          arp.getSenderProtocolAddress());
        assertArrayEquals(sourceMac.toBytes(),
                          arp.getSenderHardwareAddress());
        assertArrayEquals(TARGET_IP_ADDR.toOctets(),
                          arp.getTargetProtocolAddress());
    }

    class TestPacketService extends PacketServiceAdapter {

        List<OutboundPacket> packets = new ArrayList<>();

        @Override
        public void emit(OutboundPacket packet) {
            packets.add(packet);
        }
    }

    class TestDeviceService extends DeviceServiceAdapter {

        List<Device> devices = Lists.newArrayList();
        Multimap<DeviceId, Port> devicePorts = HashMultimap.create();

        void addDevice(Device device, Set<Port> ports) {
            devices.add(device);
            for (Port p : ports) {
                devicePorts.put(device.id(), p);
            }
        }

        @Override
        public int getDeviceCount() {
            return 0;
        }

        @Override
        public Iterable<Device> getDevices() {
            return devices;
        }

        @Override
        public Device getDevice(DeviceId deviceId) {
            return null;
        }

        @Override
        public MastershipRole getRole(DeviceId deviceId) {
            return null;
        }

        @Override
        public List<Port> getPorts(DeviceId deviceId) {
            List<Port> ports = Lists.newArrayList();
            for (Port p : devicePorts.get(deviceId)) {
                ports.add(p);
            }
            return ports;
        }

        @Override
        public Port getPort(DeviceId deviceId, PortNumber portNumber) {
            return null;
        }

        @Override
        public boolean isAvailable(DeviceId deviceId) {
            return false;
        }

        @Override
        public void addListener(DeviceListener listener) {
        }

        @Override
        public void removeListener(DeviceListener listener) {
        }
    }
}


text:
import numpy as np
from Bio.Seq import Seq
#------------------------------
penalty = {'MATCH': 1, 'MISMATCH': -1, 'GAP': -2}
arrows = np.array([[0, 0, 0, 0]])

def match_score(alpha, beta):
    if alpha == beta:
        return penalty['MATCH']
    else:
        return penalty['MISMATCH']

def finalize(align1, align2, score):
    align1 = align1[::-1]  # reverse sequence 1
    align2 = align2[::-1]  # reverse sequence 2

    i, j = 0, 0

    # calcuate identity, score and aligned sequeces
    symbol = ''
    found = 0
    for i in range(0, len(align1)):
        # if two AAs are the same, then output the letter
        if align1[i] == align2[i]:
            symbol += '|'

        # if they are not identical and none of them is gap
        elif align1[i] != align2[i] and align1[i] != '-' and align2[i] != '-':
            symbol += ' '
            found = 0

        # if one of them is a gap, output a space
        elif align1[i] == '-' or align2[i] == '-':
            symbol += ' '

    print ('Score =', score)
    print (align1)
    print (symbol)
    print (align2)

def needleman_wunsch(seq_alpha_col, seq_beta_row, p_penalty, score_only):
    """
    Llena las matrices de acuerdo al algoritmo Needleman-Wunsch.

    Esta función realiza las operaciones necesarias para lograr el
    alineamiento global (Needleman-Wunsch) entre dos secuencias.
    Un alineamiento global encuentra la mejor concordancia entre
    todos los caracteres de las dos secuencias.

    Al realizar alineamientos, se puede especificar el match score,
    el mismath score y el gap penalty. El match score indica la compatibilidad
    entre un alineamiento entre dos caracteres en las secuencias.
    Los caracteres altamente compatibles deben recibir la puntuación del match,
    y los que no sean compatibles deben recibir la puntuación de mismatch.
    Los gaps deben ser negativos.

    Parameters
    ----------
    seq_alpha_col : Bio.Seq.Seq
        Primer secuencia a ser comparada

    seq_beta_row : Bio.Seq.Seq
        Segunda secuencia a ser comparada

    p_penalty : dict(str -> int)
        Diccionario que contiene los valores de MATCH, MISMATCH y GAP

    score_only : boolean
        Cuando es True solamente muestra el alineamiento y el valor del score,
        así se utiliza menos memoria y es más rápido.
        Cuando es False guarda la matriz y la traza que recorre el alineamiento
        en la carpeta `/output`.

    Returns
    -------
    np.array, np.array, np.array
        Tres arreglos que contienen los puntajes, los punteros y la matriz del mejor alineamiento

    """
    if not seq_alpha_col or not seq_beta_row:
        print("Alguna de las secuencias está vacía.")
        return
    global penalty
    penalty = p_penalty
    m, n = len(seq_beta_row), len(seq_alpha_col)  # length of two sequences
    #---------
    pointer_mat = []  # pointer matrix

    if not score_only:
        # Custom datatype 3-tuple for ('D','U','L')
        dt = np.dtype([('diagonal', np.str, 1),
                       ('up', np.str, 1), ('left', np.str, 1)])

        pointer_mat = np.zeros((m + 1, n + 1), dtype=dt)

    #---------
    score_matrix = np.zeros((m + 1, n + 1), dtype=int)      # the DP table
    # Calculate DP table
    for i in range(0, m + 1):
        score_matrix[i][0] = penalty['GAP'] * i
        if not score_only:
            pointer_mat[i][0]['up'] = 'U'
    for j in range(0, n + 1):
        score_matrix[0][j] = penalty['GAP'] * j
        if not score_only:
            pointer_mat[0][j]['left'] = 'L'
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            diagonal = score_matrix[i - 1][j - 1] + \
                match_score(seq_beta_row[i - 1], seq_alpha_col[j - 1])
            up = score_matrix[i - 1][j] + penalty['GAP']
            left = score_matrix[i][j - 1] + penalty['GAP']
            max_pointer = max(diagonal, up, left)
            score_matrix[i][j] = max_pointer
            if not score_only:
                if (diagonal == max_pointer):
                    pointer_mat[i][j]['diagonal'] = 'D'
                if (up == max_pointer):
                    pointer_mat[i][j]['up'] = 'U'
                if (left == max_pointer):
                    pointer_mat[i][j]['left'] = 'L'
    if score_only:
        print(score_matrix)
    # print(pt_mat)

    # Traceback and compute the alignment
    align1, align2 = '', ''
    i, j = m, n  # start from the bottom right cell
    a = np.array([[0, 0, 0, 0]])

    first = True
    global arrows
    score = score_matrix[i][j]
    while i > 0 and j > 0:  # end toching the top or the left edge
        score_current = score_matrix[i][j]
        score_diagonal = score_matrix[i - 1][j - 1]
        score_up = score_matrix[i][j - 1]
        score_left = score_matrix[i - 1][j]
        if not score_only:
            a[:, :2] = j, i

        match_score_val = match_score(
            seq_beta_row[i - 1], seq_alpha_col[j - 1])

        if score_current == score_diagonal + match_score_val:
            align1 += seq_beta_row[i - 1]
            align2 += seq_alpha_col[j - 1]
            i -= 1
            j -= 1
            score = score + match_score_val
        elif score_current == score_left + penalty['GAP']:
            align1 += seq_beta_row[i - 1]
            align2 += '-'
            i -= 1
            score = score + penalty['GAP']
        elif score_current == score_up + penalty['GAP']:
            align1 += '-'
            align2 += seq_alpha_col[j - 1]
            j -= 1
            score = score + penalty['GAP']
        if not score_only:
            a[:, 2:] = j, i
            if first:
                arrows = np.copy(a)
                first = False
            else:
                arrows = np.concatenate((arrows, a), axis=0)
    if not score_only:
        a[:, :2] = a[:, 2:]
    # print(arrows)
    # print(a)

    # Finish tracing up to the top left cell
    while i > 0:
        align1 += seq_beta_row[i - 1]
        align2 += '-'
        i -= 1
        if not score_only:
            a[:, 2:] = j, i
            arrows = np.concatenate((arrows, a), axis=0)
    while j > 0:
        align1 += '-'
        align2 += seq_alpha_col[j - 1]
        j -= 1
        if not score_only:
            a[:, 2:] = j, i
            arrows = np.concatenate((arrows, a), axis=0)

    finalize(align1, align2, score)
    return score_matrix, pointer_mat, arrows

if __name__ == '__main__':
    alpha = Seq("MADRE")
    beta = Seq("PADRE")
    needleman_wunsch(alpha, beta, penalty, score_only=True)


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

<title>G-Index</title>
<meta name="date" content="2016-05-27">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

G

g - Variable in class graphics.rooms.Room

Game - Class in graphics.rooms.game

Game(int, int, String) - Constructor for class graphics.rooms.game.Game

game - Variable in class logic.Input

game(Input.KEY, Input.KEY) - Static method in class logic.StatesMachine

Game mode

Game - Class in main

Game() - Constructor for class main.Game

Game.STATE - Enum in graphics.rooms.game

game3D - Static variable in class logic.StatesMachine

game3d(Input.KEY, Input.KEY) - Static method in class logic.StatesMachine

3D Game mode

gameButton - Static variable in class graphics.rooms.mainMenu.MainMenuRepository

gameOver(Room) - Method in class logic.misc.objectives.Objective

Method to check if the game is over and the player defeated

gameOver - Static variable in class sound.MusicRepository

GAMEOVER_MUSIC - Static variable in class sound.SoundTrack

GameRepository - Class in graphics.rooms.game

GameRepository() - Constructor for class graphics.rooms.game.GameRepository

gameScreen - Static variable in class logic.StatesMachine

generateListOfObjects() - Static method in class logic.misc.Map

Generates a list of types of destroyable blocks to use when generating
 random maps

generateMap(Room) - Static method in class logic.misc.Map

Generates a random map from various templates

generateRandomObject(int, int, Room, List<Character>) - Static method in class logic.misc.Map

Generates a random object

getCenterX() - Method in class logic.Sprite

getCenterXFromSpriteName(String) - Static method in class main.Initialization

Method to get the center-x from a sprite

getCenterY() - Method in class logic.Sprite

getCenterYFromSpriteName(String) - Static method in class main.Initialization

Method to get the center-y from a sprite

getCharInt(char) - Static method in class utils.PaintService

Method that returns the integer codification of a character

getCodeKey(Input.KEY) - Method in class logic.KeyMapper

getCol(int) - Static method in class logic.misc.Map

getDepth(String) - Static method in class main.Initialization

Method to get the predefined depth of an object

getDirection() - Method in class logic.Input

Gets the direction key, taking long-pressed keys into account

getFile(String) - Static method in class utils.FileUtils

Gets the file referenced by the path @param file, creating a temp file
 that will be deleted on exit

getHeight() - Method in class logic.collisions.BoundingBox

getHeight() - Method in class logic.Sprite

getImageIndex() - Method in class graphics.rooms.optionsMenu.OptionsMenu

getKey() - Method in class logic.Input

Gets the key pressed (no rebounds, does not take into account
 long-pressed keys)

getKeyText(Input.KEY) - Method in class graphics.rooms.controlsMenu.Controls

Get text from a key

getMap(String, Room) - Static method in class logic.misc.Map

Creates a map from a file

getNoReboundsKey() - Method in class logic.Input

Gets the key pressed.

getObjective() - Method in class logic.misc.LevelFile

getPintable() - Method in class graphics.effects.ControlButton

getPowerUp(Item) - Method in class logic.characters.Player

Get the power up from the item

getRecords() - Method in class logic.misc.Ranking

getRectangle() - Method in class logic.collisions.BoundingBox

Transforms the bounding box to a rectangle

getRow(int) - Static method in class logic.misc.Map

getScore() - Method in class logic.misc.Record

getSpriteFromFile(String, String) - Static method in class main.Initialization

Method to get a sprite from an ini file

getSpriteFromMap(String) - Static method in class main.Initialization

Method to get the sprite named name from the map_file ini file

getSpriteFromMenu(String) - Static method in class main.Initialization

Method to get a sprite from the menu_file ini file

getSpriteFromSprites(String) - Static method in class main.Initialization

Method to get a sprite from the sprite_file ini file

getSpritesFromImage(BufferedImage, int, int, int) - Static method in class utils.Animation

Method to get the sprites from a spritesheet (only one row allowed)

getSpritesFromImage(BufferedImage, int, int, int, int) - Static method in class utils.Animation

Method to get the sprites from a spritesheet (only one row allowed)
 adding transparency to pixels with 'transparency' color

getSpritesFromTableSprites(String, String[]) - Static method in class main.Initialization

Method to get the sprites from the sprite_file ini file

getStage() - Method in class logic.misc.LevelFile

getSubimages() - Method in class logic.Sprite

getSubsprites() - Method in class logic.Sprite

getToTheStairs(Room) - Method in class logic.misc.objectives.GetToTheStairsObjective

Check if the player has reached the stairs on the room

GetToTheStairsObjective - Class in logic.misc.objectives

GetToTheStairsObjective() - Constructor for class logic.misc.objectives.GetToTheStairsObjective

getType() - Method in class logic.characters.Item

getValue(String, String, String) - Static method in class utils.IniUtils

Method to get the value of a term on a specific section of the ini file

getWidth() - Method in class logic.collisions.BoundingBox

getWidth() - Method in class logic.Sprite

getX() - Method in class logic.collisions.BoundingBox

getX() - Method in class logic.collisions.Point2D

getX(int) - Static method in class logic.misc.Map

getY() - Method in class logic.collisions.BoundingBox

getY() - Method in class logic.collisions.Point2D

getY(int) - Static method in class logic.misc.Map

Global - Class in logic

Global() - Constructor for class logic.Global

goToRoom(StatesMachine.STATE, boolean) - Static method in class logic.StatesMachine

Changes room

graphics.d3 - package graphics.d3

graphics.effects - package graphics.effects

graphics.effects.slider - package graphics.effects.slider

graphics.rooms - package graphics.rooms

graphics.rooms.controlsMenu - package graphics.rooms.controlsMenu

graphics.rooms.credits - package graphics.rooms.credits

graphics.rooms.game - package graphics.rooms.game

graphics.rooms.intro - package graphics.rooms.intro

graphics.rooms.mainMenu - package graphics.rooms.mainMenu

graphics.rooms.optionsMenu - package graphics.rooms.optionsMenu

graphics.rooms.pauseMenu - package graphics.rooms.pauseMenu

graphics.rooms.rankMenu - package graphics.rooms.rankMenu

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
@interface ViewController () <LEAmountInputTextFieldDelegate>

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setup];
}

#pragma mark - LEAmountInputView

- (void)setup
{
    LEAmountInputView *amountInputView = [[LEAmountInputView alloc] initWithFrame:CGRectZero numberStyle:NSNumberFormatterCurrencyStyle];
    amountInputView.translatesAutoresizingMaskIntoConstraints = NO;
    amountInputView.textField.delegate = self;
    [self.view addSubview:amountInputView];

    NSDictionary *views = NSDictionaryOfVariableBindings(amountInputView);
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[amountInputView]-10-|" options:0 metrics:0 views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[amountInputView]-10-|" options:0 metrics:0 views:views]];
}

#pragma mark - LEAmountInputTextFieldDelegate

- (BOOL)textField:(LEAmountInputTextField *)textField shouldChangeAmount:(NSNumber *)amount
{
    NSLog(@"%s %@", __PRETTY_FUNCTION__, amount);

    double maxAmount = 999999.99;
    double totalAmount = amount.doubleValue;
    if (totalAmount > maxAmount) {
        textField.amount = @(maxAmount);
        return NO;
    }
    return YES;
}

- (void)textField:(LEAmountInputTextField *)textField didChangeAmount:(NSNumber *)amount
{
    NSLog(@"%s %@", __PRETTY_FUNCTION__, amount);
}

@end


text:
package org.jvnet.jaxb2_commons.strategy;

import com.sun.tools.xjc.Options;
import com.sun.tools.xjc.outline.FieldOutline;

public interface FieldOutlineProcessor<T, C> {
	public T process(C context, FieldOutline fieldOutline, Options options) throws Exception;

}


text:
package com.anaplan.client.logging;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.color.ANSIConstants;
import ch.qos.logback.core.pattern.color.ForegroundCompositeConverterBase;

/**
 * Sets Logback level colors
 */
public class LogLevelHighlighter extends ForegroundCompositeConverterBase<ILoggingEvent> {
    @Override
    protected String getForegroundColorCode(ILoggingEvent event) {
        Level level = event.getLevel();
        switch (level.toInt()) {
            case Level.DEBUG_INT:
                return ANSIConstants.YELLOW_FG;
            case Level.ERROR_INT:
                return ANSIConstants.BOLD + ANSIConstants.RED_FG; // same as default color scheme
            case Level.WARN_INT:
                return ANSIConstants.RED_FG;// same as default color scheme
            case Level.INFO_INT:
                return ANSIConstants.GREEN_FG;
            default:
                return ANSIConstants.DEFAULT_FG;
        }
    }
}


text:
'use strict'

const path = require('path')

const fs = jest.genMockFromModule('fs')

let mockFiles = {}

const __setMockFiles = (_mockFiles) => {
    mockFiles = _mockFiles
}

const readFile = (file, cb) => {
    const mockedContent = mockFiles[file]
    if (mockedContent !== undefined) return cb(null, mockedContent)
    cb(new Error(`File does not exist (${file})`))
}

fs.__setMockFiles = __setMockFiles
fs.readFile = readFile

module.exports = fs


text:
describe('Airport', function(){
  var airport;
  var plane;

  beforeEach(function(){
    airport = new Airport();
    plane = 'plane';

    Airport.prototype.isStormy = function(){
        return (Math.floor(Math.random()*4)+1) === 1;
    };

  });

  it('can land a plane', function(){
    airport.land(plane);
    expect(airport.planes).toEqual([plane]);
  });

  it('can take off a plane', function(){
    spyOn(airport, 'isStormy').and.returnValue(false);
    airport.land(plane);
    airport.takeOff(plane);
    expect(airport.planes).toEqual([]);
  });

});


text:
package com.axemblr.service.cm.models.cm;

import com.google.common.collect.ImmutableSet;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;

import java.util.Set;

/**
 * A list of role names.
 * <p/>
 * http://cloudera.github.com/cm_api/apidocs/v1/el_ns0_roleNames.html
 * http://cloudera.github.com/cm_api/apidocs/v1/ns0_apiRoleNameList.html
 */
public class RoleNameList {
  private final ImmutableSet<String> items;

  public RoleNameList(String... roles) {
    this(ImmutableSet.copyOf(roles));
  }

  @JsonCreator
  public RoleNameList(@JsonProperty("items") Set<String> items) {
    this.items = (items == null) ? ImmutableSet.<String>of() : ImmutableSet.copyOf(items);
  }

  public ImmutableSet<String> getItems() {
    return items;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof RoleNameList)) return false;

    RoleNameList that = (RoleNameList) o;

    if (items != null ? !items.equals(that.items) : that.items != null) return false;

    return true;
  }

  @Override
  public int hashCode() {
    return items != null ? items.hashCode() : 0;
  }

  @Override
  public String toString() {
    return "RoleNameList{" +
        "items=" + items +
        '}';
  }
}


text:
package br.unb.cic.poo.gol

class RuleBook(rules: Rules) extends GameEngine {

  def shouldKeepAlive(i: Int, j: Int): Boolean = rules.shouldKeepAlive(i, j)
  def shouldRevive(i: Int, j: Int): Boolean = rules.shouldRevive(i, j)

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 6: 420 (1908)

#### Original name
Gloeoglossum affine E.J. Durand

### Remarks
null


text:
package org.dasein.cloud.examples.compute.image;

import org.dasein.cloud.CloudException;
import org.dasein.cloud.CloudProvider;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.compute.*;
import org.dasein.cloud.examples.ProviderLoader;

import javax.annotation.Nullable;

/**
 * Example showing how to search a public image library like the AWS image library using Dasein Cloud. You can call this
 * command with one, two, or three arguments:
 *

 *
keyword or 'none' indicating no keyword preference

 *
platform or 'none' indicating no platform choice

 *
architecture or 'none' indicating no architecture choice

 *

 *

 * The platform and architecture values should be values from the {@link org.dasein.cloud.compute.Platform} and
 * {@link org.dasein.cloud.compute.Architecture} enums, respectively.
 *

 *
Created by George Reese: 10/3/12 6:57 PM

 * @author George Reese
 * @version 2012.09 initial version
 * @since 2012.09
 */
public class SearchImages {
    static public void main(String ... args) throws Exception {
        ProviderLoader loader = new ProviderLoader();

        SearchImages searcher = new SearchImages(loader.getConfiguredProvider());

        try {
            Architecture architecture = null;
            Platform platform = null;
            String keyword = null;

            if( args.length > 0 ) {
                keyword = args[0];
                if( keyword.equalsIgnoreCase("none") ) {
                    keyword = null;
                }
                if( args.length > 1 ) {
                    if( !args[1].equalsIgnoreCase("none") ) {
                        try { platform = Platform.valueOf(args[1].toUpperCase()); }
                        catch( Throwable ignore ) { }
                    }
                    if( args.length > 2 ) {
                        if( !args[2].equalsIgnoreCase("none") ) {
                            try { architecture = Architecture.valueOf(args[2].toUpperCase()); }
                            catch( Throwable ignore ) { }
                        }
                    }
                }
            }
            searcher.list(keyword, platform, architecture);
        }
        finally {
            searcher.provider.close();
        }
    }

    private CloudProvider provider;

    public SearchImages(CloudProvider provider) { this.provider = provider; }

    public void list(@Nullable String keyword, @Nullable Platform platform, @Nullable Architecture architecture) {
        // see if the cloud provider has any compute services
        ComputeServices compute = provider.getComputeServices();

        if( compute == null ) {
            System.out.println(provider.getCloudName() + " does not support any compute services.");
        }
        else {
            // see if it specifically supports machine images
            MachineImageSupport imgSupport = compute.getImageSupport();

            if( imgSupport == null ) {
                System.out.println(provider.getCloudName() + " does not support machine images/templates.");
            }
            else {
                // search the machine images
                try {
                    int count = 0;

                    System.out.println("Machine images in " + provider.getCloudName() + " matching your terms:");
                    for( MachineImage img : imgSupport.searchImages(null, keyword, platform, architecture, ImageClass.MACHINE) ) {
                        count++;
                        System.out.println("\t" + img.getName() + "[" + img.getProviderMachineImageId() + "] (" + img.getCurrentState() + ")");
                    }
                    System.out.println("Total: " + count);
                }
                catch( CloudException e ) {
                    System.err.println("An error occurred with the cloud provider: " + e.getMessage());
                    e.printStackTrace();
                }
                catch( InternalException e ) {
                    System.err.println("An error occurred inside Dasein Cloud: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }
}


text:
const Nightmare = require('nightmare');
const regularNightmare = Nightmare({show: false});

function getProxy() {
    let ip, port, proxy;
    let list = [];
    $('#proxylisttable tr.odd,#proxylisttable tr.even').each(function (index) {
        let value = this.innerText;
        if (value.includes('elite')) {
            ip = $(this).children('td:nth-child(1)').text();
            port = $(this).children('td:nth-child(2)').text();
            proxy = ip + ':' + port;
            list.push(proxy);
        }
    });
    return list;
}

function checkIp(proxy) {
    return proxy.includes(document.querySelector('b').innerText.replace(/[^\d\.]/g, ''));

}

let getProxies = function*() {
    let result = yield regularNightmare
        .goto('https://www.us-proxy.org')
        .wait('#proxylisttable')
        .evaluate(getProxy);
    yield regularNightmare.end();
    return result;
};

let ipCheck = function*(client, proxy) {
    let result = yield client
        .goto('http://www.ipchicken.com')
        .evaluate(checkIp, proxy);
    return result;
};

module.exports = {
    getProxies: getProxies,
    ipCheck: ipCheck
};


text:
1. Install [VSCode](https://code.visualstudio.com/).

2. If you haven't already, install `gulp-cli` globally, with
`npm install -g gulp-cli` from a bash prompt.  This does not require
administrative rights, and places a `gulp` shim into your path that will
invoke a copy of gulp from the local project folder.  This is needed for
VSCode's build tasks to work with Cesium.

3. Click `File -> Open Folder...` and open the Cesium root folder.

## Shell Integration (optional)

VSCode has an integrated shell, exposed on Windows by pressing CTRL-\` (CTRL-backtick).
You may want to switch this to be a git bash shell by default.  If so, click
File -> Preferences -> Settings... and enter `integrated.shell` into the search
box.  Choose the appropriate key for your operating system, for example
`terminal.integrated.shell.windows` for Windows, and click the edit icon.
The default setting will be copied to your user settings.  The default for
Windows is `"C:\\Windows\\system32\\cmd.exe"`.  Change this to point to your
git bash install.  For example:

```
{
    "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
}
```

Note that on Windows, the git bash desktop icon points at a different exe file,
one that forces a separate (non-integrated) window to pop open outside of VSCode.
Make sure you are pointed at the correct exe as shown above, with Git 2.0.0 or
higher installed, to get the correct integrated shell behavior.

## VSCode Extensions (mostly optional)

Click on the extensions icon, or press CTRL-SHIFT-X to see the list of installed
VSCode extensions.  While we don't officially endorse any particular 3rd-party
extension, there are some that appear to be quite useful to Cesium.  Just enter
the desired extension name in the search box and click install.  You will need to
restart VSCode after you are done installing extensions.

* **[eslint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)**
by Dirk Baeumer -- This extension picks up on Cesium's own eslint settings,
and will warn of any violations.  The Cesium main repository should pass eslint
using the Cesium eslint settings with no warnings and no errors.  Proposed
contributions to Cesium that introduce eslint warnings will need to be corrected
before they are accepted.

* **[Shader languages support for VS Code](https://marketplace.visualstudio.com/items?itemName=slevesque.shader)**
by slevesque -- This extension provides syntax highlighting for Cesium's shader code.

* **[Prettify JSON](https://marketplace.visualstudio.com/items?itemName=mohsen1.prettify-json)**
 by Mohsen Azimi -- This seems generally useful.

* **[glTF Extension for VS Code](https://marketplace.visualstudio.com/items?itemName=cesium.gltf-vscode)**
by CesiumJS.org -- This extension adds features for previewing and editing 3D models in glTF files.

## VSCode Tasks and Files

You can launch any of Cesium's npm tasks from within VSCode by pressing
CTRL-P and typing `task ` (with a trailing space).  Autocomplete will
offer the list of npm tasks for you to run.  The first time you do this,
allow a moment for it to read the available tasks from the gulpfile.

You can also jump to any source file with the same CTRL-P keypress
followed by the name of the file.

## Building Cesium

Cesium has a number of GLSL shaders and auto-generated files that must be
built before Cesium can be used.  The simplest way in VSCode is to type
`CTRL-P` `task build` to trigger a single build.

You can also start the build watcher with `CTRL-P` `task build-watch`.  This
leaves a watcher running until you exit VSCode, that will automatically
update any shaders or auto-generated files to reflect changes to Cesium as
you save them.

Keep in mind that `build-watch` will quietly terminate when
you quit VSCode, so should be restarted manually on next launch.