text:
class EventsController < ApplicationController
  include EventHandler
  include ContactProcessor

  before_action :require_sign_in
  before_action :set_company

  def show
    @event = Event.find params[:id]
    authorize! :read, @event
    event_details @event
  end

  def new
    @event = Event.new company_id: @company.id
    @primary_contact = Customer.new
    @contact_card = ContactCard.new
    @event.primary_contact = @primary_contact
    authorize! :create, @event
  end

  def create
    @event = @company.events.new(event_params)
    authorize! :create, @event
    contact_processor = create_contact_processor
    if @event.save && contact_processor.add_primary_contact_to?(@event)
      render_contact contact_processor
      redirect_to company_event_path(@company, @event), notice: "Event was added succesfully."
    else
      flash[:alert] =  "Something went wrong, event not created."
      render :new
    end
  end

  private

  def create_contact_processor
    cp = ContactProcessor.new(
      customer_params: primary_contact_attributes,
      contact_params: contact_card_params
    )
  end

  def set_company
    @company = Company.find params[:company_id]
  end

  def primary_contact_attributes
    params[:event].require(:primary_contact_attributes).permit(:first_name, :last_name, :password, :email)
  end

  def contact_card_params
    params[:event].require(:contact_card).permit(:phone, :street_address, :address_second_line, :city, :state, :zip)
  end

  def event_params
    params.require(:event).permit(:date, :name, :start_time, :room_id)
  end
end


text:
"""
A simple launcher script for TPU training

Inspired by https://github.com/pytorch/pytorch/blob/master/torch/distributed/launch.py

::
    >>> python xla_spawn.py --num_cores=NUM_CORES_YOU_HAVE
               YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other
               arguments of your training script)

"""

import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path

import torch_xla.distributed.xla_multiprocessing as xmp

def parse_args():
    """
    Helper function parsing the command line options
    @retval ArgumentParser
    """
    parser = ArgumentParser(
        description=(
            "PyTorch TPU distributed training launch "
            "helper utility that will spawn up "
            "multiple distributed processes"
        )
    )

    # Optional arguments for the launch helper
    parser.add_argument("--num_cores", type=int, default=1, help="Number of TPU cores to use (1 or 8).")

    # positional
    parser.add_argument(
        "training_script",
        type=str,
        help=(
            "The full path to the single TPU training "
            "program/script to be launched in parallel, "
            "followed by all the arguments for the "
            "training script"
        ),
    )

    # rest from the training program
    parser.add_argument("training_script_args", nargs=REMAINDER)

    return parser.parse_args()

def main():
    args = parse_args()

    # Import training_script as a module.
    script_fpath = Path(args.training_script)
    sys.path.append(str(script_fpath.parent.resolve()))
    mod_name = script_fpath.stem
    mod = importlib.import_module(mod_name)

    # Patch sys.argv
    sys.argv = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores)]

    xmp.spawn(mod._mp_fn, args=(), nprocs=args.num_cores)

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
ip2name
=======

A script to convert all IPs in a text file to resolved hostnames

Here is an example:

```
$ cat testfile.txt
8.8.8.8 google dns server #1
8.8.4.4 google dns server #2

299.222.222.222 not a valid IP
this is what www.microsoft.com resolves to: 64.4.11.42

8.8.8.8 8.8.4.4

$ python ip2name.py < testfile.txt
[google-public-dns-a.google.com] google dns server #1
[google-public-dns-b.google.com] google dns server #2

299.222.222.222 not a valid IP
this is what www.microsoft.com resolves to: [64.4.11.42]

[google-public-dns-a.google.com] [google-public-dns-b.google.com]
```


text:
namespace mojo {

template <>
struct StructTraits<ax::mojom::AXTreeDataDataView, ui::AXTreeData> {
  static const ui::AXTreeID& tree_id(const ui::AXTreeData& p) {
    return p.tree_id;
  }
  static const ui::AXTreeID& parent_tree_id(const ui::AXTreeData& p) {
    return p.parent_tree_id;
  }
  static const ui::AXTreeID& focused_tree_id(const ui::AXTreeData& p) {
    return p.focused_tree_id;
  }
  static const std::string& doctype(const ui::AXTreeData& p) {
    return p.doctype;
  }
  static bool loaded(const ui::AXTreeData& p) { return p.loaded; }
  static float loading_progress(const ui::AXTreeData& p) {
    return p.loading_progress;
  }
  static const std::string& mimetype(const ui::AXTreeData& p) {
    return p.mimetype;
  }
  static const std::string& title(const ui::AXTreeData& p) { return p.title; }
  static const std::string& url(const ui::AXTreeData& p) { return p.url; }
  static int32_t focus_id(const ui::AXTreeData& p) { return p.focus_id; }
  static bool sel_is_backward(const ui::AXTreeData& p) {
    return p.sel_is_backward;
  }
  static int32_t sel_anchor_object_id(const ui::AXTreeData& p) {
    return p.sel_anchor_object_id;
  }
  static int32_t sel_anchor_offset(const ui::AXTreeData& p) {
    return p.sel_anchor_offset;
  }
  static ax::mojom::TextAffinity sel_anchor_affinity(const ui::AXTreeData& p) {
    return p.sel_anchor_affinity;
  }
  static int32_t sel_focus_object_id(const ui::AXTreeData& p) {
    return p.sel_focus_object_id;
  }
  static int32_t sel_focus_offset(const ui::AXTreeData& p) {
    return p.sel_focus_offset;
  }
  static ax::mojom::TextAffinity sel_focus_affinity(const ui::AXTreeData& p) {
    return p.sel_focus_affinity;
  }
  static int32_t root_scroller_id(const ui::AXTreeData& p) {
    return p.root_scroller_id;
  }
  static std::vector<std::string> metadata(const ui::AXTreeData& p) {
    return p.metadata;
  }

  static bool Read(ax::mojom::AXTreeDataDataView data, ui::AXTreeData* out);
};

}  // namespace mojo

#endif  // UI_ACCESSIBILITY_MOJOM_AX_TREE_DATA_MOJOM_TRAITS_H_


text:
ACCEPTED

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

#### Published in
Syst. nat. 1:164. 1817

#### Original name
null

### Remarks
null


text:
'use strict';

const path = require('path');

const opn = require('opn');

opn(path.resolve(__dirname, 'index.html'));


text:
<?php

namespace Kisphp\NewsletterBundle\Services;

use AppBundle\Utils\Status;
use Doctrine\ORM\EntityManager;
use Finite\Loader\ArrayLoader;
use Finite\State\StateInterface;
use Finite\StateMachine\StateMachine;
use Kisphp\NewsletterBundle\Entity\NewsletterEntity;

class NewsletterService
{
    const TRANSITION_SEND = 'send';
    const TRANSITION_SENT = 'sent';
    const TRANSITION_CANCEL = 'cancel';
    const TRANSITION_REACTIVATE = 'reactivate';

    const NEWSLETTER_ENTITY = 'KisphpNewsletterBundle:NewsletterEntity';

    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * @param EntityManager $em
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * @param int $newsletterId
     *
     * @return NewsletterEntity|null|object
     */
    public function getNewsletterById($newsletterId)
    {
        return $this->em
            ->getRepository(self::NEWSLETTER_ENTITY)
            ->find($newsletterId)
        ;
    }

    /**
     * @param NewsletterEntity $entity
     *
     * @return NewsletterEntity
     */
    public function saveNewsletter(NewsletterEntity $entity)
    {
        $this->em->persist($entity);
        $this->em->flush();

        return $entity;
    }

    /**
     * @param NewsletterEntity $entity
     *
     * @return NewsletterEntity
     */
    public function deleteNewsletter(NewsletterEntity $entity)
    {
        $entity->setStatus(Status::DELETED);

        return $this->saveNewsletter($entity);
    }

    /**
     * @return array|\Kisphp\NewsletterBundle\Entity\NewsletterEntity[]
     */
    public function getPendingNewsletters()
    {
        return $this->em
            ->getRepository(self::NEWSLETTER_ENTITY)
            ->findBy([
                'state' => NewsletterEntity::STATE_PENDING,
            ])
        ;
    }

    /**
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function queryNewsletters()
    {
        return $this->em
            ->getRepository(self::NEWSLETTER_ENTITY)
            ->queryNewsletters()
        ;
    }

    /**
     * @return array
     */
    public function createNewsletterStateMachine()
    {
        $service = $this;

        return [
            'class' => 'NewsletterEntity',
            'states' => [
                'draft' => [
                    'type' => StateInterface::TYPE_INITIAL,
                    'properties' => [
                        'edit' => true,
                        'delete' => true,
                    ],
                ],
                'pending' => [
                    'type' => StateInterface::TYPE_NORMAL,
                    'properties' => [
                        'edit' => false,
                        'delete' => false,
                        'manual' => false,
                    ],
                ],
                self::TRANSITION_SENT => [
                    'type' => StateInterface::TYPE_FINAL,
                    'properties' => [
                        'edit' => false,
                        'delete' => false,
                    ],
                ],
                'canceled' => [
                    'type' => StateInterface::TYPE_NORMAL,
                    'properties' => [
                        'edit' => false,
                        'delete' => true,
                    ],
                ],
            ],
            'transitions' => [
                self::TRANSITION_SEND => [
                    'from' => ['draft'],
                    'to' => 'pending',
                ],
                self::TRANSITION_SENT => [
                    'from' => ['pending'],
                    'to' => self::TRANSITION_SENT,
                ],
                self::TRANSITION_CANCEL => [
                    'from' => ['draft', 'pending'],
                    'to' => 'canceled',
                ],
                self::TRANSITION_REACTIVATE => [
                    'from' => ['canceled'],
                    'to' => 'draft',
                ],
//                'reset' => [
//                    'from' => ['sent'],
//                    'to' => 'draft',
//                ],
            ],
            'callbacks' => [
                'after' => [
                    [
                        'to' => [],
                        'do' => function (NewsletterEntity $entity) use ($service) {
                            $service->saveNewsletter($entity);
                        },
                    ],
                ],
            ],
        ];
    }

    /**
     * @param NewsletterEntity $entity
     *
     * @throws \Finite\Exception\ObjectException
     *
     * @return StateMachine
     */
    public function getStateMachine(NewsletterEntity $entity)
    {
        $stateMachine = new StateMachine();
        $loader = new ArrayLoader($this->createNewsletterStateMachine());
        $loader->load($stateMachine);
        $stateMachine->setObject($entity);
        $stateMachine->initialize();

        return $stateMachine;
    }
}


text:
'use strict'

// Selects saveImagesOption checkbox element
let saveImagesOption = document.getElementById('save_images');
// Selects thumbnailOption checkbox element
let thumbnailOption = document.getElementById('thumbnails');

function setCheckbox(data, checkbox) {
  checkbox.checked = data;
};

// Gets thumbnails and saveImages value from storage
chrome.storage.local.get(['saveImages', 'thumbnails'], function(data) {
  setCheckbox(data.saveImages, saveImagesOption);
  saveImagesOption.checked = data.saveImages === true;
  setCheckbox(data.thumbnails, thumbnailOption);
});

// Saves users prefrences
function storeOption(optionName, optionValue) {
  let data = {};
  data[optionName] = optionValue;
  chrome.storage.local.set(data);
};

saveImagesOption.onchange = function() {
  storeOption('saveImages', saveImagesOption.checked);
};

thumbnailOption.onchange = function() {
  storeOption('thumbnails', thumbnailOption.checked);
};

let savedImages = document.getElementById('savedImages');

let deleteButton = document.getElementById('delete_button');

deleteButton.onclick = function() {
  let blankArray = [];
  chrome.storage.local.set({'savedImages': blankArray});
  location.reload();
};
// Gets saved downloaded images from storage
chrome.storage.local.get('savedImages', function(element) {
  let pageImages = element.savedImages;
  pageImages.forEach(function(image) {
    // Create div element and give it class of square
    let newDiv = document.createElement('div');
    newDiv.className = 'square';
    // Create image element
    let newImage = document.createElement('img');
    // let lineBreak = document.createElement('br');
    // Image source is equal to saved download image
    newImage.src = image;
    newImage.addEventListener('click', function() {
      chrome.downloads.download({url: newImage.src});
    });
    // Append all elements to options page
    newDiv.appendChild(newImage);
    savedImages.appendChild(newDiv);
  });
});


text:
package models

import "github.com/astaxie/beego/orm"

type Role struct {
	Id    int64 `json:"id"`
	Name  string
	Users []*User `orm:"reverse(many)" json:"-"`
}

func init() {
	// Register model
	orm.RegisterModel(new(Role))
}


text:
using UnityEngine;

public class EnumFlagsAttribute : PropertyAttribute
{
    public string enumName;

    public EnumFlagsAttribute() { }

    public EnumFlagsAttribute(string name)
    {
        enumName = name;
    }
}


text:
- Optimized the rebuild of the authorizations

## 1.1.0

- `ACL::unGrant()` is deprecated in favor of the new `ACL::revoke()` method. `unGrant()` will be removed eventually.

## 1.0.0

First stable release.


text:
import Shorthand from './Shorthand';
import PlayerManager from '../../players/PlayerManager';

class Mine extends Shorthand {
  /**
   * Executes the bound logic
   * @param {object} manager - ShorthandManager instance
   */
  execute(manager) {
    const selectedEntities = manager.getSelectedEntities();
    const resetActivityQueue = manager.willActivityQueueReset();
    const targetEntity = manager.getTargetEntity();

    this.getEventEmitter(selectedEntities).mine({
      targetEntity,
      resetActivityQueue,
    });

    targetEntity.selectedAsTarget();
  }

  /**
   * Returns true if the shorthand must be executed
   * @param {object} manager - ShorthandManager instance
   * @return {boolean}
   */
  test(manager) {
    const selectedEntities = manager.getSelectedEntities();
    const playerManager = PlayerManager.getInstance();
    const targetEntity = manager.getTargetEntity();
    // if there is no target selected
    if (!targetEntity) return false;

    // if there is at least one unit that cannot dock
    if (selectedEntities.some(entity => !entity.canMine())) return false;

    // if the selected entity does not have hanger capacity
    if (!targetEntity.isMinable()) return false;
    return true;
  }
}

export default Mine;


text:
<?php

class TestTimberPostGetter extends Timber_UnitTestCase {

	/**
	 * @group wp_query_hacks
	 */
	function testGettingWithCatAndOtherStuff() {
		$pids = $this->factory->post->create_many(6);
		$cat = $this->factory->term->create(array('name' => 'Something', 'taxonomy' => 'category'));
		$cat_post = $this->factory->post->create(array('post_title' => 'Germany', 'post_category' => array($cat)) );
		$cat_post = $this->factory->post->create(array('post_title' => 'France', 'post_category' => array($cat)) );
		$cat_post = $this->factory->post->create(array('post_title' => 'England', 'post_category' => array($cat)) );
		$args = array(
            'post_type' => 'post',
            'posts_per_page' => 2,
            'post_status' => 'publish',
            'cat' => $cat
        );
		$posts = Timber::get_posts($args);
		$this->assertEquals(2, count($posts));
	}

	/**
	 * @group wp_query_hacks
	 */
	function testGettingWithCategoryAndOtherStuff() {
		$pids = $this->factory->post->create_many(6);
		$cat = $this->factory->term->create(array('name' => 'Something', 'taxonomy' => 'category'));
		$cat_post = $this->factory->post->create(array('post_title' => 'Germany', 'post_category' => array($cat)) );
		$cat_post = $this->factory->post->create(array('post_title' => 'France', 'post_category' => array($cat)) );
		$cat_post = $this->factory->post->create(array('post_title' => 'England', 'post_category' => array($cat)) );
		$args = array(
            'post_type' => 'post',
            'posts_per_page' => 2,
            'post_status' => 'publish',
            'category' => $cat
        );
		$posts = Timber::get_posts($args);
		$this->assertEquals(2, count($posts));
	}

	/**
	 * @group wp_query_hacks
	 */
	function testGettingWithCat() {
		$cat = $this->factory->term->create(array('name' => 'News', 'taxonomy' => 'category'));

		$pids = $this->factory->post->create_many(6);
		$cats = $this->factory->post->create_many(3, array('post_category' => array($cat)) );
		$cat_post = $this->factory->post->create(array('post_category' => array($cat)) );

		$cat_post = new TimberPost($cat_post);
		$this->assertEquals('News', $cat_post->category()->name());

		$posts = Timber::get_posts(array('cat' => $cat));
		$this->assertEquals(4, count($posts));
	}

	/**
	 * @group wp_query_hacks
	 */
	function testGettingWithCatList() {
		$cat = array();
		$cat[] = $this->factory->term->create(array('name' => 'News', 'taxonomy' => 'category'));
		$cat[] = $this->factory->term->create(array('name' => 'Local', 'taxonomy' => 'category'));
		$pids = $this->factory->post->create_many(6);
		$cat_post = $this->factory->post->create(array('post_category' => array($cat[0])) );
		$cat_post = $this->factory->post->create(array('post_category' => array($cat[1])) );
		$cat_post = $this->factory->post->create(array('post_category' => $cat) );

		$posts = Timber::get_posts( array('cat' => implode(',', $cat)));
		$this->assertEquals(3, count($posts));
	}

	/**
	 * @group wp_query_hacks
	 */
	function testGettingWithCategory() {
		$cat = $this->factory->term->create(array('name' => 'News', 'taxonomy' => 'category'));
		$pids = $this->factory->post->create_many(6);
		$cats = $this->factory->post->create_many(3, array('post_category' => array($cat)) );
		$cat_post = $this->factory->post->create(array('post_category' => array($cat)) );

		$cat_post = new TimberPost($cat_post);
		$this->assertEquals('News', $cat_post->category()->name());

		$posts = Timber::get_posts(array('category' => $cat));
		$this->assertEquals(4, count($posts));
	}

	/**
	 * @group wp_query_hacks
	 */
	function testGettingWithCategoryList() {
		$cat = array();
		$cat[] = $this->factory->term->create(array('name' => 'News', 'taxonomy' => 'category'));
		$cat[] = $this->factory->term->create(array('name' => 'Local', 'taxonomy' => 'category'));
		$pids = $this->factory->post->create_many(6);
		$cat_post = $this->factory->post->create(array('post_category' => array($cat[0])) );
		$cat_post = $this->factory->post->create(array('post_category' => array($cat[1])) );
		$cat_post = $this->factory->post->create(array('post_category' => $cat) );

		$posts = Timber::get_posts( array('category' => implode(',', $cat)));
		$this->assertEquals(3, count($posts));
	}

	function testGettingArrayWithSticky(){
		$pids = $this->factory->post->create_many(6);
		$sticky_id = $this->factory->post->create();
		$sticky = array($sticky_id, $pids[0]);
		update_option('sticky_posts', $sticky);
		$posts = Timber::get_posts($pids);
		$post_ids_gotten = array();
		foreach($posts as $post) {
			$post_ids_gotten[] = $post->ID;
		}
		$this->assertNotContains($sticky_id, $post_ids_gotten);
		$this->assertContains($pids[0], $post_ids_gotten);
	}

	function testGetPostsWithClassMap() {
		register_post_type('portfolio', array('public' => true));
		register_post_type('alert', array('public' => true));
		$this->factory->post->create(array('post_type' => 'portfolio', 'post_title' => 'A portfolio item', 'post_date' => '2015-04-23 15:13:52'));
		$this->factory->post->create(array('post_type' => 'alert', 'post_title' => 'An alert', 'post_date' => '2015-06-23 15:13:52'));
		$posts = Timber::get_posts('post_type=any', array('portfolio' => 'TimberPortfolio', 'alert' => 'TimberAlert'));
		$this->assertEquals( 'TimberAlert', get_class($posts[0]) );
		$this->assertEquals( 'TimberPortfolio', get_class($posts[1]) );
	}

	function testGetPostWithClassMap() {
		register_post_type('portfolio', array('public' => true));
		$post_id_portfolio = $this->factory->post->create(array('post_type' => 'portfolio', 'post_title' => 'A portfolio item', 'post_date' => '2015-04-23 15:13:52'));
		$post_id_alert = $this->factory->post->create(array('post_type' => 'alert', 'post_title' => 'An alert', 'post_date' => '2015-06-23 15:13:52'));
		$post_portfolio = Timber::get_post($post_id_portfolio, array('portfolio' => 'TimberPortfolio', 'alert' => 'TimberAlert'));
		$post_alert = Timber::get_post($post_id_alert, array('portfolio' => 'TimberPortfolio', 'alert' => 'TimberAlert'));
		$this->assertEquals( 'TimberPortfolio', get_class($post_portfolio) );
		$this->assertEquals( $post_id_portfolio, $post_portfolio->ID );
		$this->assertEquals( 'TimberAlert', get_class($post_alert) );
		$this->assertEquals( $post_id_alert, $post_alert->ID );
	}

	function test587() {
		register_post_type('product');
		$pids = $this->factory->post->create_many(6, array('post_type' => 'product'));
		$args = array(
        	'post_type' => 'project'
    	);
		$context['projects'] = Timber::get_posts($args);
	}

	function testGettingEmptyArray(){
		$pids = $this->factory->post->create_many( 15 );
		$posts = Timber::get_posts(array());
		$this->assertEmpty($posts);
	}

	function testGettingWithFalse(){
		$pids = $this->factory->post->create_many( 15 );
		$posts = Timber::get_posts(false);
		$this->assertEmpty($posts);
	}

	function testGetAttachment() {
		$upload_dir = wp_upload_dir();
		$post_id = $this->factory->post->create();
		$filename = TestTimberImage::copyTestImage( 'flag.png' );
		$destination_url = str_replace( ABSPATH, 'http://'.$_SERVER['HTTP_HOST'].'/', $filename );
		$wp_filetype = wp_check_filetype( basename( $filename ), null );
		$attachment = array(
			'post_mime_type' => $wp_filetype['type'],
			'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
			'post_content' => '',
			'post_status' => 'inherit'
		);
		$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
		add_post_meta( $post_id, '_thumbnail_id', $attach_id, true );
		$data = array();
		$data['post'] = new TimberPost( $post_id );
		$data['size'] = array( 'width' => 100, 'height' => 50 );
		$data['crop'] = 'default';
		Timber::compile( 'assets/thumb-test.twig', $data );
		$exists = file_exists( $filename );
		$this->assertTrue( $exists );
		$resized_path = $upload_dir['path'].'/flag-'.$data['size']['width'].'x'.$data['size']['height'].'-c-'.$data['crop'].'.png';
		$exists = file_exists( $resized_path );
		$this->assertTrue( $exists );
		$attachments = Timber::get_posts('post_type=attachment&post_status=inherit');
		$this->assertGreaterThan(0, count($attachments));
	}

	function testNumberPosts() {
		$pids = $this->factory->post->create_many( 15 );
		$query = 'post_type=post&numberposts=7';
		$posts = Timber::get_posts($query);
		$this->assertEquals(7, count($posts));

	}

	function testNumberPostsBig() {
		$pids = $this->factory->post->create_many( 15 );
		$query = 'post_type=post&numberposts=15';
		$posts = Timber::get_posts($query);
		$this->assertEquals(15, count($posts));

	}

	/**
	 * @group wp_query_hacks
	 */
	function testNumberPostsAll() {
		$pids = $this->factory->post->create_many( 17 );
		$query = 'post_type=post&numberposts=-1';
		$posts = Timber::get_posts($query);
		$this->assertEquals(17, count($posts));

	}

	function testPostsPerPage() {
		$pids = $this->factory->post->create_many( 15 );
		$query = 'post_type=post&posts_per_page=7';
		$posts = Timber::get_posts($query);
		$this->assertEquals(7, count($posts));
	}

	function testPostsPerPageAll() {
		$pids = $this->factory->post->create_many( 23 );
		$query = 'post_type=post&posts_per_page=-1';
		$posts = Timber::get_posts($query);
		$this->assertEquals(23, count($posts));
	}

	function testPostsPerPageBig() {
		$pids = $this->factory->post->create_many( 15 );
		$query = 'post_type=post&posts_per_page=15';
		$posts = Timber::get_posts($query);
		$this->assertEquals(15, count($posts));
	}

	function testQueryPost() {
		$posts = $this->factory->post->create_many( 6 );
		$post = Timber::get_post( $posts[3] );
		$this->go_to( home_url( '/?p='.$posts[2] ) );
		$this->assertNotEquals( get_the_ID(), $post->ID );
		$post = Timber::query_post( $posts[3] );
		$this->assertEquals( get_the_ID(), $post->ID );
	}

	function testBlankQueryPost() {
		$pid = $this->factory->post->create( );
		$this->go_to( home_url( '/?p='.$pid ) );
		$post = Timber::query_post();
		$this->assertEquals( $pid, $post->ID );
	}

	function testGetPostsInLoop() {
		$posts = $this->factory->post->create_many( 55 );
		$this->go_to( '/' );
		$start = microtime( true );
		if ( have_posts() ) {
			while ( have_posts() ) {
				the_post();
				$posts = Timber::get_posts();
			}
		}
		$end = microtime( true );
		$diff = $end - $start;
		//if this takes more than 10 seconds, we're in trouble
		$this->assertLessThan( 10, $diff );
	}

	function testGetPostsFromLoop() {
		$posts = $this->factory->post->create_many( 15 );
		$this->go_to( '/' );
		$posts = Timber::get_posts();
		$this->assertEquals( 10, count( $posts ) );
		$pc = new Timber\PostQuery();
		$this->assertEquals( 10, count( $pc ) );
	}

	function testGetPostsFromArray() {
		$pids = $this->factory->post->create_many( 15 );
		$posts = Timber::get_posts( $pids );
		$this->assertEquals( 15, count( $posts ) );
		$this->assertEquals( $pids[3], $posts[3]->ID );
	}

	function testGetPostWithSlug() {
		$post = $this->factory->post->create( array( 'post_name' => 'silly-post' ) );
		$posts = Timber::get_posts( 'silly-post' );
		$this->assertEquals( 1, count( $posts ) );
		$this->assertEquals( 'silly-post', $posts[0]->slug );
	}

	function testCustomPostTypeAndClass() {
		register_post_type('job');
		$jobs = $this->factory->post->create_many( 10, array('post_type' => 'job'));
		$jobPosts = Timber::get_posts(array('post_type' => 'job'));
		$this->assertEquals(10, count($jobPosts));
	}

	function testCustomPostTypeAndClassOnSinglePage() {
		register_post_type('job');
		$post_id = $this->factory->post->create( array( 'post_type' => 'job' ) );
		$post = new TimberPost($post_id);
		$this->go_to('?p='.$post->ID);
		$jobs = $this->factory->post->create_many( 10, array('post_type' => 'job'));
		$jobPosts = Timber::get_posts(array('post_type' => 'job'));
		$this->assertEquals(10, count($jobPosts));
	}

	function testStringWithPostClass() {
		$yes = \Timber\PostGetter::is_post_class_or_class_map('job');
		$this->assertTrue($yes);
	}

	function testStringWithPostClassBogus() {
		$no = \Timber\PostGetter::is_post_class_or_class_map('pants');
		$this->assertFalse($no);
	}

	function testNotATimberPost() {
		self::enable_error_log(false);
		$post_id = $this->factory->post->create( array( 'post_type' => 'state' ) );
		$use = \Timber\PostGetter::get_post_class('state', 'MyState');
		$this->assertEquals('\Timber\Post', $use);
		$post = new $use($post_id);
		$this->assertEquals('Timber\Post', get_class($post));
		self::enable_error_log(true);
	}

	function testPostTypeReturnAgainstArgType() {
		register_post_type('person');
		$jobs = $this->factory->post->create_many( 4, array('post_type' => 'person'));
		$personPostsArray = Timber::get_posts(array('post_type' => 'person'), 'Person');
		$personPostsString = Timber::get_posts('post_type=person', 'Person');
		$this->assertEquals(4, count($personPostsArray));
		$this->assertEquals(4, count($personPostsString));
	}

}

class MyState {

}

class job extends \Timber\Post {

}

class Person extends \Timber\Post {

}

class TimberAlert extends \Timber\Post {

}

class TimberPortfolio extends \Timber\Post {

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Bjd;
using Bjd.log;
using Bjd.net;
using Bjd.sock;
using Bjd.util;

namespace ProxyHttpServer {
    class Proxy:IDisposable {
        readonly Kernel _kernel;
        public Logger Logger { get; private set; }
        public int OptionTimeout { get; private set; }
        //ソケット
        Dictionary<CS,SockTcp> _sock = new Dictionary<CS,SockTcp>(2);
        //上位プロキシ情報
        public UpperProxy UpperProxy { get; private set; }
        //接続中のサーバ情報(URLから取得したホスト名)
        public string HostName="";
        public int Port = 0;//Ver5.0.1

        public Proxy(Kernel kernel,Logger logger,SockTcp clientSocket,int optionTimeout,UpperProxy upperProxy) {
            _kernel = kernel;
            Logger = logger;
            OptionTimeout = optionTimeout;
            UpperProxy = upperProxy;

            _sock[CS.Client] = clientSocket;
            _sock[CS.Server] = null;
            //sock[CS.CLIENT].SendTimeout = optionTimeout; //Ver5.0.2 送信タイムアウトは設定しない

            ProxyProtocol = ProxyProtocol.Unknown;
        }
        // 終了処理
        public void Dispose(){
            if (_sock[CS.Client] != null)
                _sock[CS.Client].Close();
            if (_sock[CS.Server] != null)
                _sock[CS.Server].Close();

            //Ver5.0.0-b3 使用終了を明示的に記述する
            foreach (CS cs in Enum.GetValues(typeof (CS))){
                _sock[cs] = null;
            }
            _sock = null;
        }

        public ProxyProtocol ProxyProtocol { get; private set; }

        public SockTcp Sock(CS cs) {
            return _sock[cs];
        }

        //ソケットに到着しているデータ量
        public int Length(CS cs) {
            return _sock[cs].Length();
        }

        public void NoConnect(string host,int port) {//キャッシュにヒットした場合に、サーバ側のダミーソケットを作成する
            _sock[CS.Server] = new SockTcp(_kernel,new Ip(IpKind.V4_0),0,0,null);
            HostName = host;//Request.HostNameを保存して、現在接続中のホストを記憶する
            Port = port;
        }

        public bool Connect(ILife iLife, string host1, int port1, string requestStr, ProxyProtocol proxyProtocol) {

            ProxyProtocol = proxyProtocol;

            if(Sock(CS.Server) != null) {
                //Ver5.0.1
                //if(_host == HostName) {
                if(host1 == HostName && port1==Port) {
                    return true;
                }
                //Ver5.0.0-b21
                Sock(CS.Server).Close();
            }

            if(UpperProxy.Use) {//上位プロキシのチェック
                // 上位プロキシを経由しないサーバの確認
                foreach(string address in UpperProxy.DisableAdderssList) {
                    if (ProxyProtocol == ProxyProtocol.Ssl) {
                        if(host1.IndexOf(address) == 0) {
                            UpperProxy.Use = false;
                            break;
                        }
                    } else {
                        string str = requestStr.Substring(11);
                        if(str.IndexOf(address) == 0) {
                            UpperProxy.Use = false;
                            break;
                        }
                    }

                }
            }

            string host = host1;
            int port = port1;
            if(UpperProxy.Use) {
                host = UpperProxy.Server;
                port = UpperProxy.Port;
            }

            List<Ip> ipList = null;
            try{
                ipList = new List<Ip>();
                ipList.Add(new Ip(host));
            }catch (ValidObjException){
                ipList = _kernel.DnsCache.GetAddress(host).ToList();
                if(ipList == null || ipList.Count == 0) {
                    Logger.Set(LogKind.Error,null,11,host);
                    return false;
                }
            }

            Ssl ssl = null;
            foreach(Ip ip in ipList){
                int timeout = 3;
                _sock[CS.Server] = Inet.Connect(_kernel,ip,port,timeout,ssl);
                if(_sock[CS.Server] != null)
                    break;
            }
            if(_sock[CS.Server] == null) {
                Logger.Set(LogKind.Detail,_sock[CS.Client],26,string.Format("{0}:{1}",ipList[0],port));
                return false;
            }
            //sock[CS.SERVER].SendTimeout = OptionTimeout;//Ver5.0.2 送信タイムアウトは設定しない

            HostName = host1;//Request.HostNameを保存して、現在接続中のホストを記憶する
            //Ver5.6.1
            Port = port1;
            return true;

        }

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <description>
        Defines a pluggable datasource which allow varying connection pool type
        and database type without having to recompile the application.
    </description>

    <context:annotation-config/>

    <context:property-placeholder location="classpath:com/github/rbuck/dash/services/spring/application.properties,classpath:com/github/rbuck/dash/services/spring/${dash.db.type:hsqldb}.properties"
                                  ignore-unresolvable="true" order="0"/>

    <import resource="classpath:com/github/rbuck/dash/services/spring/spring-${dash.db.pool.type:bonecp}-ds.xml"/>

</beans>


text:
def sum_of_array_plus_one array
  array.inject(:+) + array.count
end


text:
<!DOCTYPE html>

<title>Canvas test: 2d.gradient.interpolate.multiple</title>

<link rel="stylesheet" href="/html/canvas/resources/canvas-tests.css">

2d.gradient.interpolate.multiple

Actual output:

<canvas id="c" class="output" width="100" height="50">
FAIL (fallback content)
</canvas>

Expected output:


text:
package dynamic

import (
	"context"
	"fmt"

	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/rest"
)

type dynamicClient struct {
	client *rest.RESTClient
}

var _ Interface = &dynamicClient{}

// ConfigFor returns a copy of the provided config with the
// appropriate dynamic client defaults set.
func ConfigFor(inConfig *rest.Config) *rest.Config {
	config := rest.CopyConfig(inConfig)
	config.AcceptContentTypes = "application/json"
	config.ContentType = "application/json"
	config.NegotiatedSerializer = basicNegotiatedSerializer{} // this gets used for discovery and error handling types
	if config.UserAgent == "" {
		config.UserAgent = rest.DefaultKubernetesUserAgent()
	}
	return config
}

// NewForConfigOrDie creates a new Interface for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) Interface {
	ret, err := NewForConfig(c)
	if err != nil {
		panic(err)
	}
	return ret
}

// NewForConfig creates a new dynamic client or returns an error.
func NewForConfig(inConfig *rest.Config) (Interface, error) {
	config := ConfigFor(inConfig)
	// for serializing the options
	config.GroupVersion = &schema.GroupVersion{}
	config.APIPath = "/if-you-see-this-search-for-the-break"

	restClient, err := rest.RESTClientFor(config)
	if err != nil {
		return nil, err
	}

	return &dynamicClient{client: restClient}, nil
}

type dynamicResourceClient struct {
	client    *dynamicClient
	namespace string
	resource  schema.GroupVersionResource
}

func (c *dynamicClient) Resource(resource schema.GroupVersionResource) NamespaceableResourceInterface {
	return &dynamicResourceClient{client: c, resource: resource}
}

func (c *dynamicResourceClient) Namespace(ns string) ResourceInterface {
	ret := *c
	ret.namespace = ns
	return &ret
}

func (c *dynamicResourceClient) Create(obj *unstructured.Unstructured, opts metav1.CreateOptions, subresources ...string) (*unstructured.Unstructured, error) {
	outBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)
	if err != nil {
		return nil, err
	}
	name := ""
	if len(subresources) > 0 {
		accessor, err := meta.Accessor(obj)
		if err != nil {
			return nil, err
		}
		name = accessor.GetName()
		if len(name) == 0 {
			return nil, fmt.Errorf("name is required")
		}
	}

	result := c.client.client.
		Post().
		AbsPath(append(c.makeURLSegments(name), subresources...)...).
		Body(outBytes).
		SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).
		Do(context.TODO())
	if err := result.Error(); err != nil {
		return nil, err
	}

	retBytes, err := result.Raw()
	if err != nil {
		return nil, err
	}
	uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
	if err != nil {
		return nil, err
	}
	return uncastObj.(*unstructured.Unstructured), nil
}

func (c *dynamicResourceClient) Update(obj *unstructured.Unstructured, opts metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error) {
	accessor, err := meta.Accessor(obj)
	if err != nil {
		return nil, err
	}
	name := accessor.GetName()
	if len(name) == 0 {
		return nil, fmt.Errorf("name is required")
	}
	outBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)
	if err != nil {
		return nil, err
	}

	result := c.client.client.
		Put().
		AbsPath(append(c.makeURLSegments(name), subresources...)...).
		Body(outBytes).
		SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).
		Do(context.TODO())
	if err := result.Error(); err != nil {
		return nil, err
	}

	retBytes, err := result.Raw()
	if err != nil {
		return nil, err
	}
	uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
	if err != nil {
		return nil, err
	}
	return uncastObj.(*unstructured.Unstructured), nil
}

func (c *dynamicResourceClient) UpdateStatus(obj *unstructured.Unstructured, opts metav1.UpdateOptions) (*unstructured.Unstructured, error) {
	accessor, err := meta.Accessor(obj)
	if err != nil {
		return nil, err
	}
	name := accessor.GetName()
	if len(name) == 0 {
		return nil, fmt.Errorf("name is required")
	}

	outBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)
	if err != nil {
		return nil, err
	}

	result := c.client.client.
		Put().
		AbsPath(append(c.makeURLSegments(name), "status")...).
		Body(outBytes).
		SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).
		Do(context.TODO())
	if err := result.Error(); err != nil {
		return nil, err
	}

	retBytes, err := result.Raw()
	if err != nil {
		return nil, err
	}
	uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
	if err != nil {
		return nil, err
	}
	return uncastObj.(*unstructured.Unstructured), nil
}

func (c *dynamicResourceClient) Delete(name string, opts *metav1.DeleteOptions, subresources ...string) error {
	if len(name) == 0 {
		return fmt.Errorf("name is required")
	}
	if opts == nil {
		opts = &metav1.DeleteOptions{}
	}
	deleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: "v1"}), opts)
	if err != nil {
		return err
	}

	result := c.client.client.
		Delete().
		AbsPath(append(c.makeURLSegments(name), subresources...)...).
		Body(deleteOptionsByte).
		Do(context.TODO())
	return result.Error()
}

func (c *dynamicResourceClient) DeleteCollection(opts *metav1.DeleteOptions, listOptions metav1.ListOptions) error {
	if opts == nil {
		opts = &metav1.DeleteOptions{}
	}
	deleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: "v1"}), opts)
	if err != nil {
		return err
	}

	result := c.client.client.
		Delete().
		AbsPath(c.makeURLSegments("")...).
		Body(deleteOptionsByte).
		SpecificallyVersionedParams(&listOptions, dynamicParameterCodec, versionV1).
		Do(context.TODO())
	return result.Error()
}

func (c *dynamicResourceClient) Get(name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) {
	if len(name) == 0 {
		return nil, fmt.Errorf("name is required")
	}
	result := c.client.client.Get().AbsPath(append(c.makeURLSegments(name), subresources...)...).SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).Do(context.TODO())
	if err := result.Error(); err != nil {
		return nil, err
	}
	retBytes, err := result.Raw()
	if err != nil {
		return nil, err
	}
	uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
	if err != nil {
		return nil, err
	}
	return uncastObj.(*unstructured.Unstructured), nil
}

func (c *dynamicResourceClient) List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {
	result := c.client.client.Get().AbsPath(c.makeURLSegments("")...).SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).Do(context.TODO())
	if err := result.Error(); err != nil {
		return nil, err
	}
	retBytes, err := result.Raw()
	if err != nil {
		return nil, err
	}
	uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
	if err != nil {
		return nil, err
	}
	if list, ok := uncastObj.(*unstructured.UnstructuredList); ok {
		return list, nil
	}

	list, err := uncastObj.(*unstructured.Unstructured).ToList()
	if err != nil {
		return nil, err
	}
	return list, nil
}

func (c *dynamicResourceClient) Watch(opts metav1.ListOptions) (watch.Interface, error) {
	opts.Watch = true
	return c.client.client.Get().AbsPath(c.makeURLSegments("")...).
		SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).
		Watch(context.TODO())
}

func (c *dynamicResourceClient) Patch(name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*unstructured.Unstructured, error) {
	if len(name) == 0 {
		return nil, fmt.Errorf("name is required")
	}
	result := c.client.client.
		Patch(pt).
		AbsPath(append(c.makeURLSegments(name), subresources...)...).
		Body(data).
		SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).
		Do(context.TODO())
	if err := result.Error(); err != nil {
		return nil, err
	}
	retBytes, err := result.Raw()
	if err != nil {
		return nil, err
	}
	uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
	if err != nil {
		return nil, err
	}
	return uncastObj.(*unstructured.Unstructured), nil
}

func (c *dynamicResourceClient) makeURLSegments(name string) []string {
	url := []string{}
	if len(c.resource.Group) == 0 {
		url = append(url, "api")
	} else {
		url = append(url, "apis", c.resource.Group)
	}
	url = append(url, c.resource.Version)

	if len(c.namespace) > 0 {
		url = append(url, "namespaces", c.namespace)
	}
	url = append(url, c.resource.Resource)

	if len(name) > 0 {
		url = append(url, name)
	}

	return url
}


text:
<?php
/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */
declare(strict_types=1);

namespace App\Model\Repository;

use Cycle\ORM\Select\Repository;

class FortuneRepository extends Repository
{

}


text:
Clazz.declarePackage ("JSV.dialog");
Clazz.load (["JSV.api.AnnotationData", "JSV.common.Annotation"], "JSV.dialog.JSVDialog", ["java.lang.Double", "JU.DF", "$.PT", "JSV.common.IntegralData", "$.PeakData"], function () {
c$ = Clazz.decorateAsClass (function () {
this.optionKey = null;
this.options = null;
this.type = null;
this.title = null;
this.vwr = null;
this.$spec = null;
this.manager = null;
this.dialog = null;
this.jsvp = null;
this.txt1 = null;
this.txt2 = null;
this.txt3 = null;
this.combo1 = null;
this.xyData = null;
this.myParams = null;
this.precision = 1;
this.loc = null;
this.showHideButton = null;
this.addClearBtn = false;
this.addCombo1 = false;
this.addApplyBtn = false;
this.isNumeric = false;
this.defaultVisible = false;
this.subType = null;
this.graphSetKey = null;
this.tableData = null;
this.addUnits = false;
this.unitOptions = null;
this.formatOptions = null;
this.unitPtr = null;
this.isON = true;
this.lastNorm = 1;
this.iRowColSelected = -1;
this.iSelected = -1;
this.skipCreate = false;
this.iRowSelected = -1;
this.iColSelected = -1;
Clazz.instantialize (this, arguments);
}, JSV.dialog, "JSVDialog", JSV.common.Annotation, JSV.api.AnnotationData);
Clazz.defineMethod (c$, "setParams",
function (title, viewer, spec) {
this.title = title;
this.vwr = viewer;
this.$spec = spec;
this.manager = viewer.getDialogManager ();
this.jsvp = viewer.selectedPanel;
this.myParams = (viewer.getPlatformInterface ("Parameters")).setName ("dialogParams");
this.subType = (spec == null ? "!" : spec.getTypeLabel ());
this.optionKey = this.type + "_" + this.subType;
this.options = this.manager.getDialogOptions ();
if (spec != null) {
var specOptions = spec.getDefaultAnnotationInfo (this.type);
this.options.put (this.optionKey, specOptions);
this.unitOptions = specOptions[0];
this.formatOptions = specOptions[1];
this.unitPtr = this.options.get (this.optionKey + "_unitPtr");
if (this.unitPtr == null) this.unitPtr = specOptions[2];
}switch (this.type) {
case JSV.common.Annotation.AType.Integration:
this.isNumeric = true;
this.addClearBtn = true;
this.defaultVisible = true;
this.addApplyBtn = true;
break;
case JSV.common.Annotation.AType.Measurements:
this.isNumeric = true;
this.addClearBtn = true;
this.addCombo1 = true;
this.defaultVisible = true;
break;
case JSV.common.Annotation.AType.OverlayLegend:
break;
case JSV.common.Annotation.AType.PeakList:
this.isNumeric = true;
this.addApplyBtn = true;
this.defaultVisible = true;
break;
case JSV.common.Annotation.AType.Views:
this.defaultVisible = true;
break;
case JSV.common.Annotation.AType.NONE:
break;
}
this.initDialog ();
return this;
}, "~S,JSV.common.JSViewer,JSV.common.Spectrum");
Clazz.defineMethod (c$, "initDialog",
 function () {
this.dialog = this.manager.getDialog (this);
this.restoreDialogPosition (this.jsvp, this.getPosXY ());
this.dialog.setTitle (this.title);
this.layoutDialog ();
});
Clazz.defineMethod (c$, "layoutDialog",
function () {
this.dialog.startLayout ();
this.addUniqueControls ();
if (this.isNumeric) {
this.getUnitOptions ();
if (this.addCombo1) this.combo1 = this.dialog.addSelectOption ("cmbUnits", "Units", this.unitOptions, this.unitPtr.intValue (), this.addUnits);
if (this.addApplyBtn) this.dialog.addButton ("btnApply", "Apply");
this.showHideButton = this.dialog.addButton ("btnShow", "Show");
if (this.addClearBtn) this.dialog.addButton ("btnClear", "Clear");
}this.dialog.endLayout ();
this.checkEnables ();
this.dialog.setVisible (this.defaultVisible);
});
Clazz.defineMethod (c$, "callbackAD",
function (id, msg) {
if (id.equals ("FOCUS")) {
this.eventFocus ();
} else if (id.equals ("tableSelect")) {
this.tableSelect (msg);
} else if (id.equals ("btnClear")) {
this.clear ();
} else if (id.equals ("btnApply")) {
this.eventApply ();
} else if (id.equals ("btnShow")) {
var label = this.dialog.getText (this.showHideButton);
this.eventShowHide (label.equals ("Show"));
} else if (id.equals ("cmbUnits")) {
this.setPrecision (this.dialog.getSelectedIndex (this.combo1));
} else if (id.startsWith ("txt")) {
this.eventApply ();
} else if (id.equals ("windowClosing")) {
this.done ();
return true;
}if (this.jsvp != null) this.jsvp.doRepaint (true);
return true;
}, "~S,~S");
Clazz.defineMethod (c$, "addUniqueControls",
function (dialogHelper) {
}, "JSV.dialog.DialogManager");
Clazz.overrideMethod (c$, "getAType",
function () {
return this.type;
});
Clazz.overrideMethod (c$, "getGraphSetKey",
function () {
return this.graphSetKey;
});
Clazz.overrideMethod (c$, "setGraphSetKey",
function (key) {
this.graphSetKey = key;
}, "~S");
Clazz.overrideMethod (c$, "getSpectrum",
function () {
return this.$spec;
});
Clazz.overrideMethod (c$, "getState",
function () {
return this.isON;
});
Clazz.overrideMethod (c$, "setState",
function (b) {
this.isON = b;
}, "~B");
Clazz.defineMethod (c$, "checkEnables",
function () {
var isShow = this.checkVisible ();
this.dialog.setText (this.showHideButton, isShow ? "Hide" : "Show");
});
Clazz.defineMethod (c$, "createTable",
function (data, header, widths) {
this.tableData = data;
this.dialog.createTable (data, header, widths);
}, "~A,~A,~A");
Clazz.defineMethod (c$, "setTableSelectionEnabled",
function (enabled) {
this.dialog.setCellSelectionEnabled (enabled);
}, "~B");
Clazz.defineMethod (c$, "getParameters",
function () {
return this.myParams;
});
Clazz.defineMethod (c$, "showMessage",
function (msg, title, msgType) {
this.manager.showMessageDialog (this.dialog, msg, title, msgType);
}, "~S,~S,~N");
Clazz.defineMethod (c$, "setThreshold",
function (y) {
this.dialog.setText (this.txt1, this.getThreasholdText (y));
}, "~N");
Clazz.defineMethod (c$, "setComboSelected",
function (i) {
this.dialog.setSelectedIndex (this.combo1, i);
}, "~N");
Clazz.defineMethod (c$, "applyFromFields",
function () {
this.apply (null);
});
Clazz.defineMethod (c$, "reEnable",
function () {
this.paramsReEnable ();
return this;
});
Clazz.defineMethod (c$, "dispose",
function () {
this.dialog.dispose ();
});
Clazz.defineMethod (c$, "setVisible",
function (visible) {
this.dialog.setVisible (visible);
}, "~B");
Clazz.overrideMethod (c$, "isVisible",
function () {
return this.dialog.isVisible ();
});
Clazz.defineMethod (c$, "selectTableRow",
function (i) {
this.dialog.selectTableRow (i);
}, "~N");
Clazz.defineMethod (c$, "repaint",
function () {
this.dialog.repaint ();
});
Clazz.defineMethod (c$, "setFields",
function () {
switch (this.type) {
case JSV.common.Annotation.AType.Integration:
break;
case JSV.common.Annotation.AType.Measurements:
break;
case JSV.common.Annotation.AType.NONE:
break;
case JSV.common.Annotation.AType.PeakList:
this.myParams = this.xyData.getParameters ();
this.setThreshold (this.myParams.peakListThreshold);
this.setComboSelected (this.myParams.peakListInterpolation.equals ("none") ? 1 : 0);
this.createData ();
break;
case JSV.common.Annotation.AType.OverlayLegend:
break;
case JSV.common.Annotation.AType.Views:
break;
}
});
Clazz.defineMethod (c$, "setFocus",
function (tf) {
this.dialog.setFocus (tf);
}, "~B");
Clazz.defineMethod (c$, "update",
function (clicked, xRange, yOffset) {
this.selectTableRow (-1);
switch (this.type) {
case JSV.common.Annotation.AType.Integration:
this.loadData ();
this.checkEnables ();
break;
case JSV.common.Annotation.AType.Measurements:
this.loadData ();
this.checkEnables ();
break;
case JSV.common.Annotation.AType.NONE:
break;
case JSV.common.Annotation.AType.PeakList:
if (yOffset > 20) this.applyFromFields ();
if (this.xyData == null || clicked == null || yOffset > 20) return;
var ipt = 0;
var dx0 = 1e100;
var xval = clicked.getXVal ();
var md = this.xyData;
var min = Math.abs (xRange / 20);
for (var i = md.size (); --i >= 0; ) {
var dx = Math.abs (xval - md.get (i).getXVal ());
if (dx < dx0) {
dx0 = dx;
ipt = i;
}}
if (dx0 < min) {
this.selectTableRow (md.size () - 2 - ipt);
this.repaint ();
}break;
case JSV.common.Annotation.AType.OverlayLegend:
break;
case JSV.common.Annotation.AType.Views:
break;
}
}, "JSV.common.Coordinate,~N,~N");
Clazz.defineMethod (c$, "getPeakData",
function () {
var md =  new JSV.common.PeakData (JSV.common.Annotation.AType.PeakList, this.$spec);
md.setPeakList (this.myParams, this.precision, this.jsvp.getPanelData ().getView ());
this.xyData = md;
return null;
});
Clazz.overrideMethod (c$, "getData",
function () {
if (this.xyData == null) this.createData ();
return this.xyData;
});
Clazz.defineMethod (c$, "setData",
function (data) {
this.myParams = data.getParameters ();
this.xyData = data;
}, "JSV.api.AnnotationData");
Clazz.overrideMethod (c$, "setSpecShift",
function (dx) {
if (this.xyData != null) this.xyData.setSpecShift (dx);
}, "~N");
Clazz.defineMethod (c$, "setType",
function (type) {
this.type = type;
switch (type) {
case JSV.common.Annotation.AType.Measurements:
this.addUnits = true;
break;
case JSV.common.Annotation.AType.Integration:
break;
case JSV.common.Annotation.AType.PeakList:
break;
case JSV.common.Annotation.AType.OverlayLegend:
break;
case JSV.common.Annotation.AType.Views:
break;
case JSV.common.Annotation.AType.NONE:
break;
}
}, "JSV.common.Annotation.AType");
Clazz.defineMethod (c$, "apply",
function (objects) {
try {
switch (this.type) {
case JSV.common.Annotation.AType.Integration:
var offset = Double.parseDouble (objects[0]);
var scale = Double.parseDouble (objects[1]);
this.myParams.integralOffset = offset;
this.myParams.integralRange = scale;
this.myParams.integralDrawAll = false;
(this.getData ()).update (this.myParams);
break;
case JSV.common.Annotation.AType.Measurements:
break;
case JSV.common.Annotation.AType.NONE:
return;
case JSV.common.Annotation.AType.PeakList:
if (!this.skipCreate) {
this.setThreshold (NaN);
this.createData ();
}this.skipCreate = false;
break;
case JSV.common.Annotation.AType.OverlayLegend:
break;
case JSV.common.Annotation.AType.Views:
this.vwr.parameters.viewOffset = Double.parseDouble (objects[0]);
break;
}
this.loadData ();
this.checkEnables ();
this.jsvp.doRepaint (true);
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
} else {
throw e;
}
}
}, "~A");
Clazz.defineMethod (c$, "done",
function () {
if (this.jsvp != null && this.$spec != null) this.jsvp.getPanelData ().removeDialog (this);
if (this.xyData != null) this.xyData.setState (this.isON);
this.saveDialogPosition (this.getPosXY ());
this.dispose ();
this.jsvp.doRepaint (true);
});
Clazz.defineMethod (c$, "restoreDialogPosition",
 function (panel, posXY) {
if (panel != null) {
if (posXY[0] == -2147483648) {
posXY[0] = 0;
posXY[1] = -20;
}var pt = this.manager.getLocationOnScreen (panel);
var height = panel.getHeight ();
this.loc = [Math.max (0, pt[0] + posXY[0]), Math.max (0, pt[1] + height + posXY[1])];
this.dialog.setIntLocation (this.loc);
}}, "JSV.api.JSVPanel,~A");
Clazz.defineMethod (c$, "saveDialogPosition",
 function (posXY) {
try {
var pt = this.manager.getLocationOnScreen (this.dialog);
posXY[0] += pt[0] - this.loc[0];
posXY[1] += pt[1] - this.loc[1];
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
} else {
throw e;
}
}
}, "~A");
Clazz.defineMethod (c$, "getThreasholdText",
 function (y) {
if (Double.isNaN (y)) {
var pd = this.jsvp.getPanelData ();
var f = (pd.getSpectrum ().isInverted () ? 0.1 : 0.9);
var c = pd.getClickedCoordinate ();
y = (c == null ? (pd.getView ().minYOnScale * f + pd.getView ().maxYOnScale) * (1 - f) : c.getYVal ());
}var sy = JU.DF.formatDecimalDbl (y, y < 1000 ? 2 : -2);
return " " + sy;
}, "~N");
Clazz.defineMethod (c$, "checkVisible",
 function () {
return this.vwr.pd ().getShowAnnotation (this.type);
});
Clazz.defineMethod (c$, "getUnitOptions",
 function () {
var key = this.optionKey + "_format";
var format = this.options.get (key);
if (format == null) this.options.put (key, format = Integer.$valueOf (this.formatOptions[this.unitPtr == null ? 0 : this.unitPtr.intValue ()]));
});
Clazz.defineMethod (c$, "eventFocus",
function () {
if (this.$spec != null) this.jsvp.getPanelData ().jumpToSpectrum (this.$spec);
switch (this.type) {
case JSV.common.Annotation.AType.Integration:
if (this.iRowSelected >= 0) {
this.iRowSelected++;
this.tableCellSelect (-1, -1);
}break;
case JSV.common.Annotation.AType.Measurements:
break;
case JSV.common.Annotation.AType.NONE:
break;
case JSV.common.Annotation.AType.PeakList:
this.createData ();
this.skipCreate = true;
break;
case JSV.common.Annotation.AType.OverlayLegend:
break;
case JSV.common.Annotation.AType.Views:
break;
}
});
Clazz.defineMethod (c$, "eventApply",
function () {
switch (this.type) {
case JSV.common.Annotation.AType.Integration:
break;
case JSV.common.Annotation.AType.Measurements:
break;
case JSV.common.Annotation.AType.NONE:
break;
case JSV.common.Annotation.AType.PeakList:
this.createData ();
this.skipCreate = true;
break;
case JSV.common.Annotation.AType.OverlayLegend:
break;
case JSV.common.Annotation.AType.Views:
break;
}
this.applyFromFields ();
});
Clazz.defineMethod (c$, "eventShowHide",
 function (isShow) {
this.isON = isShow;
if (isShow) this.eventApply ();
this.jsvp.doRepaint (true);
this.checkEnables ();
}, "~B");
Clazz.defineMethod (c$, "clear",
 function () {
this.setState (true);
if (this.xyData != null) {
this.xyData.clear ();
this.applyFromFields ();
}});
Clazz.defineMethod (c$, "paramsReEnable",
 function () {
switch (this.type) {
case JSV.common.Annotation.AType.Integration:
break;
case JSV.common.Annotation.AType.Measurements:
break;
case JSV.common.Annotation.AType.NONE:
break;
case JSV.common.Annotation.AType.PeakList:
this.skipCreate = true;
break;
case JSV.common.Annotation.AType.OverlayLegend:
break;
case JSV.common.Annotation.AType.Views:
break;
}
this.setVisible (true);
this.isON = true;
this.applyFromFields ();
});
Clazz.defineMethod (c$, "tableCellSelect",
 function (iRow, iCol) {
System.out.println (iRow + " jSVDial " + iCol);
if (iRow < 0) {
iRow = Clazz.doubleToInt (this.iRowColSelected / 1000);
iCol = this.iRowColSelected % 1000;
this.iRowColSelected = -1;
}var value = this.tableData[iRow][1];
var icolrow = iRow * 1000 + iCol;
if (icolrow == this.iRowColSelected) return;
this.iRowColSelected = icolrow;
System.out.println ("Setting rc = " + this.iRowColSelected + " " + this.$spec);
this.selectTableRow (this.iRowSelected);
try {
switch (this.type) {
case JSV.common.Annotation.AType.Integration:
this.callback ("SHOWSELECTION", value.toString ());
this.checkEnables ();
break;
case JSV.common.Annotation.AType.Measurements:
break;
case JSV.common.Annotation.AType.NONE:
break;
case JSV.common.Annotation.AType.PeakList:
try {
switch (iCol) {
case 6:
case 5:
case 4:
var x1 = Double.parseDouble (value);
var x2 = Double.parseDouble (this.tableData[iRow + 3 - iCol][1]);
this.jsvp.getPanelData ().setXPointers (this.$spec, x1, this.$spec, x2);
break;
default:
this.jsvp.getPanelData ().findX (this.$spec, Double.parseDouble (value));
}
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
this.jsvp.getPanelData ().findX (this.$spec, 1E100);
} else {
throw e;
}
}
this.jsvp.doRepaint (false);
break;
case JSV.common.Annotation.AType.OverlayLegend:
this.jsvp.getPanelData ().setSpectrum (iRow, false);
break;
case JSV.common.Annotation.AType.Views:
break;
}
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
} else {
throw e;
}
}
}, "~N,~N");
Clazz.defineMethod (c$, "loadData",
function () {
var data;
var header;
var widths;
switch (this.type) {
case JSV.common.Annotation.AType.Integration:
if (this.xyData == null) this.createData ();
this.iSelected = -1;
data = (this.xyData).getMeasurementListArray (null);
header = this.xyData.getDataHeader ();
widths = [40, 65, 65, 50];
this.createTable (data, header, widths);
break;
case JSV.common.Annotation.AType.Measurements:
if (this.xyData == null) return;
data = this.xyData.getMeasurementListArray (this.dialog.getSelectedItem (this.combo1).toString ());
header = this.xyData.getDataHeader ();
widths = [40, 65, 65, 50];
this.createTable (data, header, widths);
break;
case JSV.common.Annotation.AType.NONE:
break;
case JSV.common.Annotation.AType.PeakList:
if (this.xyData == null) this.createData ();
data = (this.xyData).getMeasurementListArray (null);
header = (this.xyData).getDataHeader ();
widths = [40, 65, 50, 50, 50, 50, 50];
this.createTable (data, header, widths);
this.setTableSelectionEnabled (true);
break;
case JSV.common.Annotation.AType.OverlayLegend:
header = ["No.", "Plot Color", "Title"];
data = this.vwr.selectedPanel.getPanelData ().getOverlayLegendData ();
widths = [30, 60, 250];
this.createTable (data, header, widths);
this.setTableSelectionEnabled (true);
break;
case JSV.common.Annotation.AType.Views:
break;
}
});
Clazz.defineMethod (c$, "createData",
 function () {
switch (this.type) {
case JSV.common.Annotation.AType.Integration:
this.xyData =  new JSV.common.IntegralData (this.$spec, this.myParams);
this.iSelected = -1;
break;
case JSV.common.Annotation.AType.Measurements:
break;
case JSV.common.Annotation.AType.NONE:
break;
case JSV.common.Annotation.AType.PeakList:
try {
var thresh = Double.parseDouble (this.dialog.getText (this.txt1));
this.myParams.peakListThreshold = thresh;
this.myParams.peakListInterpolation = this.dialog.getSelectedItem (this.combo1).toString ();
this.myParams.precision = this.precision;
var md =  new JSV.common.PeakData (JSV.common.Annotation.AType.PeakList, this.$spec);
md.setPeakList (this.myParams, this.precision, this.jsvp.getPanelData ().getView ());
this.xyData = md;
this.loadData ();
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
} else {
throw e;
}
}
break;
case JSV.common.Annotation.AType.OverlayLegend:
break;
case JSV.common.Annotation.AType.Views:
break;
}
});
Clazz.defineMethod (c$, "setPrecision",
 function (i) {
this.precision = this.formatOptions[i];
}, "~N");
Clazz.defineMethod (c$, "tableSelect",
 function (url) {
var isAdjusting = "true".equals (this.getField (url, "adjusting"));
if (isAdjusting) {
this.iColSelected = this.iRowSelected = -1;
System.out.println ("adjusting" + url);
return;
}var index = JU.PT.parseInt (this.getField (url, "index"));
switch ("ROW COL ROWCOL".indexOf (this.getField (url, "selector"))) {
case 8:
this.iColSelected = JU.PT.parseInt (this.getField (url, "index2"));
case 0:
this.iRowSelected = index;
System.out.println ("r set to " + index);
break;
case 4:
this.iColSelected = index;
System.out.println ("c set to " + index);
break;
}
if (this.iColSelected >= 0 && this.iRowSelected >= 0) {
this.tableCellSelect (this.iRowSelected, this.iColSelected);
}}, "~S");
Clazz.defineMethod (c$, "getField",
 function (url, name) {
url += "&";
var key = "&" + name + "=";
var pt = url.indexOf (key);
return (pt < 0 ? null : url.substring (pt + key.length, url.indexOf ("&", pt + 1)));
}, "~S,~S");
});


text:
import axios from 'axios';

/* -----------------    ACTIONS     ------------------ */

const SET_STORY = 'SET_STORY';
const SET_SCENE = 'SET_SCENE';

/* ------------   ACTION CREATORS     ------------------ */

const setStory = story => ({
  type: SET_STORY,
  title: story.title,
  scenes: story.scenes,
  user: story.user,
  currScene: story.scenes[0]
});

export const setCurrScene = scene => ({
  type: SET_SCENE,
  currScene: scene
})

/* ------------       REDUCERS     ------------------ */

export default function reducer(state = {
  title: '',
  scenes: [],
  user: {},
  currScene: {
    id: 0, // need to adjust
    paragraphs: [],
    paragraphsHTML: [],
    position: 0,
    actors: [],
    locations: [],
    maps: [],
    heroURL: '',
    heroPhotog: '',
    heroPhotogURL: '',
    heroUnsplash: false
  }
}, action) {
  const newState = Object.assign({}, state);
  switch (action.type) {
    case SET_STORY:
      newState.title = action.title;
      newState.scenes = action.scenes;
      newState.currScene = action.currScene;
      newState.user = action.user;
      break;
    case SET_SCENE:
      newState.currScene = action.currScene;
      break;
    default:
      return newState;
  }
  return newState;
}

/* ------------       DISPATCHERS     ------------------ */
import { featuredStory } from '../components/featuredStory';

export const fetchStory = (id) => dispatch => {
  axios.get(`/api/stories/${id}`)
    .then(res => {
      dispatch(setStory(res.data))
    })
    .catch(err => console.error(`Fetching story ${id} unsuccessful`, err));
};

export const fetchFakeStory = () => dispatch => {
  axios.get(`/api/stories/`) // make random call to fake asynchronicity
    .then(() => dispatch(setStory(featuredStory)));
};

export const fetchScene = position => (dispatch, getState) => {
  dispatch(setCurrScene(getState().displayState.scenes[position]));
};


text:
'use strict';

var Promise = require('bluebird');
var byline = require('byline');

var HOST_REGEXP = /^\s*?(?:[a-f0-9\.:]+)\s+?([a-z0-9\._\-]+)\s*.*?$/i;

function matchHost(line) {
  var matches = HOST_REGEXP.exec(line);
  if (matches && matches.length === 2) {
    return matches[1];
  }
}

module.exports = function (readStream) {
  return Promise.resolve(readStream)
    .then(function (stream) {
      return new Promise(function (resolve, reject) {
        var hosts = [];

        byline(stream)
          .on('data', function (line) {
            var match = matchHost(line);
            if (match) {
              hosts.push(match);
            }
          })
          .on('error', reject)
          .on('finish', function () {
            resolve(hosts);
          });
      });
    });
};


text:
/*
'use strict';

describe('Directive: modal', function () {

  // load the directive's module
  beforeEach(module('openstorefrontApp'));

  var element,
    scope;

  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
  }));

  it('should make hidden element visible', inject(function ($compile) {
    element = angular.element('<modal></modal>');

    // Don't know why this doesn't work?
    //element = $compile(element)(scope);
    expect(element.html()).toBe('');
  }));
 alert('Directive:  modal; should make hidden element visible = PASS (1 expect)');
});
*/