text:
from cms_redirects.models import CMSRedirect
from django import http
from django.conf import settings

def get_redirect(old_path):
    try:
        r = CMSRedirect.objects.get(site__id__exact=settings.SITE_ID,
                                    old_path=old_path)
    except CMSRedirect.DoesNotExist:
        r = None
    return r

def remove_slash(path):
    return path[:path.rfind('/')]+path[path.rfind('/')+1:]

def remove_query(path):
    return path.split('?', 1)[0]

class RedirectFallbackMiddleware(object):
    def process_exception(self, request, exception):
        if isinstance(exception, http.Http404):

            # First try the whole path.
            path = request.get_full_path()
            r = get_redirect(path)

            # It could be that we need to try without a trailing slash.
            if r is None and settings.APPEND_SLASH:
                r = get_redirect(remove_slash(path))

            # It could be that the redirect is defined without a query string.
            if r is None and path.count('?'):
                r = get_redirect(remove_query(path))

            # It could be that we need to try without query string and without a trailing slash.
            if r is None and path.count('?') and settings.APPEND_SLASH:
                r = get_redirect(remove_slash(remove_query(path)))

            if r is not None:
                if r.page:
                    if r.response_code == '302':
                        return http.HttpResponseRedirect(r.page.get_absolute_url())
                    else:
                        return http.HttpResponsePermanentRedirect(r.page.get_absolute_url())
                if r.new_path == '':
                    return http.HttpResponseGone()
                if r.response_code == '302':
                    return http.HttpResponseRedirect(r.new_path)
                else:
                    return http.HttpResponsePermanentRedirect(r.new_path)


text:
<?php

namespace Weliano\ResourceObjects\Compute;
use Weliano\ResourceObjects as ResourceObject;

/**
 * Weliano Image
 *
 * @author Weliano GmbH
 */
class Image extends ResourceObject\ObjectHelper implements ResourceObject\Resource {

	/**
	 * Instance Image ID
	 *
	 * @access private
	 * @var string
	 */
	private $imageId;

	/**
	 * Get the value of Instance Image ID
	 *
	 * @access public
	 * @return string
	 */
	public function getImageId(){
		return $this->imageId;
	}

	/**
	 * Set the value of Instance Image ID
	 *
	 * @param string $imageId Value to set
	 *
	 * @access public
	 * @return void
	 */
	public function setImageId($imageId){
		$this->imageId = $imageId;
	}

	/**
	 * Volume Size in Gigabyte
	 *
	 * @access private
	 * @var integer
	 */
	private $imageVolumeSize;

	/**
	 * Get the value of Volume Size in Gigabyte
	 *
	 * @access public
	 * @return integer
	 */
	public function getImageVolumeSize(){
		return $this->imageVolumeSize;
	}

	/**
	 * Set the value of Volume Size in Gigabyte
	 *
	 * @param integer $imageVolumeSize Value to set
	 *
	 * @access public
	 * @return void
	 */
	public function setImageVolumeSize($imageVolumeSize){
		$this->imageVolumeSize = $imageVolumeSize;
	}

	/**
	 * Root device name used in kernel configuration
	 *
	 * @access private
	 * @var string
	 */
	private $imageRootDeviceName;

	/**
	 * Get the value of Root device name used in kernel configuration
	 *
	 * @access public
	 * @return string
	 */
	public function getImageRootDeviceName(){
		return $this->imageRootDeviceName;
	}

	/**
	 * Set the value of Root device name used in kernel configuration
	 *
	 * @param string $imageRootDeviceName Value to set
	 *
	 * @access public
	 * @return void
	 */
	public function setImageRootDeviceName($imageRootDeviceName){
		$this->imageRootDeviceName = $imageRootDeviceName;
	}

	/**
	 * Storage URL to download the object meta xml configuration file
	 *
	 * @access private
	 * @var string
	 */
	private $imageLocaltion;

	/**
	 * Get the value of Storage URL to download the object meta xml configuration file
	 *
	 * @access public
	 * @return string
	 */
	public function getImageLocaltion(){
		return $this->imageLocaltion;
	}

	/**
	 * Set the value of Storage URL to download the object meta xml configuration file
	 *
	 * @param string $imageLocaltion Value to set
	 *
	 * @access public
	 * @return void
	 */
	public function setImageLocaltion($imageLocaltion){
		$this->imageLocaltion = $imageLocaltion;
	}

	/**
	 * Architecture required by image
	 *
	 * @access private
	 * @var string
	 */
	private $imageArchitecture;

	/**
	 * Get the value of Architecture required by image
	 *
	 * @access public
	 * @return string
	 */
	public function getImageArchitecture(){
		return $this->imageArchitecture;
	}

	/**
	 * Set the value of Architecture required by image
	 *
	 * @param string $imageArchitecture Value to set
	 *
	 * @access public
	 * @return void
	 */
	public function setImageArchitecture($imageArchitecture){
		$this->imageArchitecture = $imageArchitecture;
	}

	/**
	 * Individuell name of of image chosen by createImage
	 *
	 * @access private
	 * @var string
	 */
	private $imageName;

	/**
	 * Get the value of Individuell name of of image chosen by createImage
	 *
	 * @access public
	 * @return string
	 */
	public function getImageName(){
		return $this->imageName;
	}

	/**
	 * Set the value of Individuell name of of image chosen by createImage
	 *
	 * @param string $imageName Value to set
	 *
	 * @access public
	 * @return void
	 */
	public function setImageName($imageName){
		$this->imageName = $imageName;
	}

	/**
	 * Optional image description
	 *
	 * @access private
	 * @var string
	 */
	private $imageDescription;

	/**
	 * Get the value of Optional image description
	 *
	 * @access public
	 * @return string
	 */
	public function getImageDescription(){
		return $this->imageDescription;
	}

	/**
	 * Set the value of Optional image description
	 *
	 * @param string $imageDescription Value to set
	 *
	 * @access public
	 * @return void
	 */
	public function setImageDescription($imageDescription){
		$this->imageDescription = $imageDescription;
	}

}

redpajama_set_name: RedPajamaGithub


text:
require 'ostruct'
require 'gitpeer'
require 'gitpeer/representation'

describe GitPeer::Representation do

  User = Struct.new(:name, :birthday)

  class UserRepr < GitPeer::Representation
    prop :name
    prop :birthday
    link :self, href: '/x'
  end

  it 'renders props and links' do
    repr = UserRepr.new(User.new("Andrey", "1987"))
    repr.to_hash.should == {
      name: "Andrey",
      birthday: "1987",
      _links: {self: {href: '/x'}}
    }
  end

  it 'represents values from hashes' do
    repr_cls = Class.new(GitPeer::Representation) do
      value :id
    end
    repr = repr_cls.new({id: 1})
    repr.to_hash.should == {id: 1}
  end

  it 'allows getting props from different name' do
    class Repr < GitPeer::Representation
      prop :a, from: :b
    end

    repr = Repr.new(OpenStruct.new(b: 2))
    repr.to_hash.should == {a: 2}
  end

  PowerUser = Struct.new(:name, :birthday, :power)
  class PowerUserRepr < UserRepr
    prop :power
    link :power, href: '/y', templated: true
  end

  it 'allows subclassing representations' do
    repr = PowerUserRepr.new(PowerUser.new("Andrey", "1987", 100))
    repr.to_hash.should == {
      name: "Andrey",
      birthday: "1987",
      power: 100,
      _links: {
        self: {href: '/x'},
        power: {href: '/y', templated: true}
      }
    }
  end

  it 'allows computed props' do
    class MyRepr < GitPeer::Representation
      prop :c, from: proc { @obj.a + @obj.b }
    end

    repr = MyRepr.new(OpenStruct.new(a: 1, b: 2))
    repr.to_hash.should == {c: 3}
  end

  it 'allows representations to depend on context' do
    class ContextualRepr < GitPeer::Representation
      prop :c, from: proc { @context[:b] + @obj.a }
    end

    repr = ContextualRepr.new(OpenStruct.new(a: 1), b: 2)
    repr.to_hash.should == {c: 3}
  end

  it 'allows define props with their own representations' do
    brepr = Class.new(GitPeer::Representation) do
      prop :c
    end
    arepr = Class.new(GitPeer::Representation) do
      prop :a
      prop :b, repr: brepr
    end

    repr = arepr.new(OpenStruct.new(a: 1, b: OpenStruct.new(c: 2)))
    repr.to_hash.should == {a: 1, b: {c: 2}}
  end

  it 'allows define props with inline representations' do
    arepr = Class.new(GitPeer::Representation) do
      prop :a
      prop :b do
        prop :c
      end
    end

    repr = arepr.new(OpenStruct.new(a: 1, b: OpenStruct.new(c: 2)))
    repr.to_hash.should == {a: 1, b: {c: 2}}
  end

  it 'allows override props' do
    class XRepr < GitPeer::Representation
      prop :a
    end
    class YRepr < XRepr
      prop :a, from: :b
    end

    repr1 = XRepr.new(OpenStruct.new(a: 1, b: 2))
    repr1.to_hash.should == {a: 1}
    repr2 = YRepr.new(OpenStruct.new(a: 1, b: 2))
    repr2.to_hash.should == {a: 2}
  end

  describe 'representing links with URI templates' do

    it 'allows representing templated links with URI templates' do
      repr_class = Class.new(GitPeer::Representation) do
        link :self, template: '/{x}', templated: true
      end
      repr = repr_class.new(OpenStruct.new(x: 1))
      repr.to_hash.should == {_links: {self: {href: '/{x}', templated: true}}}
    end

    it 'expands URI template if link is not meant to be templated' do
      repr_class = Class.new(GitPeer::Representation) do
        prop :x
        link :self, template: '/{x}'
      end
      repr = repr_class.new(OpenStruct.new(x: 1))
      repr.to_hash.should == {x: 1, _links: {self: {href: '/1'}}}
    end
  end

  describe 'representing collections' do

    it 'represents collections as arrays' do
      a = Class.new(GitPeer::Representation) do
        collection :a
        collection :b
      end
      repr = a.new(OpenStruct.new(a: [1, 2], b: [1, 2].to_enum))
      repr.to_hash.should == {a: [1, 2], b: [1, 2]}
    end

    it 'allows to represent elements in collection with custom representer' do
      ea = Class.new(GitPeer::Representation) do
        prop :a, from: :b
      end
      a = Class.new(GitPeer::Representation) do
        collection :a, repr: ea
      end
      repr = a.new(OpenStruct.new(a: [OpenStruct.new(b: 2)]))
      repr.to_hash.should == {a: [{a: 2}]}
    end

    it 'allows to represent elements in collection with inline representer' do
      a = Class.new(GitPeer::Representation) do
        collection :a do
          prop :a, from: :b
        end
      end
      repr = a.new(OpenStruct.new(a: [OpenStruct.new(b: 2)]))
      repr.to_hash.should == {a: [{a: 2}]}
    end
  end

  describe 'representation error' do

    it 'fails if represented obj cannot respond to needed methods' do
      class FailRepr1 < GitPeer::Representation
        prop :x
      end
      expect {
        FailRepr1.new(OpenStruct.new(z: 1)).to_hash
      }.to raise_error(GitPeer::Representation::RepresentationError)
    end

    it 'fails if represented obj cannot respond to needed methods' do
      class FailRepr2 < GitPeer::Representation
        prop :x, from: :y
      end
      expect {
        FailRepr2.new(OpenStruct.new(x: 1)).to_hash
      }.to raise_error(GitPeer::Representation::RepresentationError)
    end

  end

  describe 'automatic representation generation for Structs' do

    it 'automatically generates representations for Structs' do
      user = Struct.new(:name, :age)
      repr = GitPeer::Representation.for_struct(user)
      repr.new(user.new("Andrey", 27)).to_hash.should == {name: "Andrey", age: 27}
    end

    it 'allows to override generated representation' do
      user = Struct.new(:name, :age)
      repr = GitPeer::Representation.for_struct(user) do
        prop :age, from: proc { obj.age + 3 }
      end
      repr.new(user.new("Andrey", 27)).to_hash.should == {name: "Andrey", age: 30}
    end

  end

end


text:
Python Machine Learning - Code Examples

##  Chapter 3: A Tour of Machine Learning Classifiers Using scikit-learn

### Chapter Outline

- Choosing a classification algorithm
- First steps with scikit-learn -- training a perceptron
- Modeling class probabilities via logistic regression
  - Logistic regression intuition and conditional probabilities
  - Learning the weights of the logistic cost function
  - Converting an Adaline implementation into an algorithm for logistic regression
  - Training a logistic regression model with scikit-learn
  - Tackling over tting via regularization
- Maximum margin classification with support vector machines
  - Maximum margin intuition
  - Dealing with a nonlinearly separable case using slack variables
  - Alternative implementations in scikit-learn
- Solving nonlinear problems using a kernel SVM
  - Kernel methods for linearly inseparable data
  - Using the kernel trick to find separating hyperplanes in high-dimensional space
- Decision tree learning
  - Maximizing information gain – getting the most bang for your buck
  - Building a decision tree
  - Combining multiple decision trees via random forests
- K-nearest neighbors – a lazy learning algorithm
- Summary

### A note on using the code examples

The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.

![](../ch02/images/jupyter-example-1.png)

Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:

    conda install jupyter notebook

Then you can launch jupyter notebook by executing

    jupyter notebook

A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.

**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.

**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch03.ipynb`](ch03.ipynb))**

In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.

![](../ch02/images/jupyter-example-2.png)

When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.


text:
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
Rails.application.initialize!

require 'json'
require 'open-uri'


text:
# moonrover

[![Build Status](https://travis-ci.org/Scalera/moonrover.svg?branch=master)](https://travis-ci.org/Scalera/moonrover)
[![Coverage Status](https://coveralls.io/repos/Scalera/moonrover/badge.svg?branch=master&service=github)](https://coveralls.io/github/Scalera/moonrover?branch=master)

This is the source code for Scalera's first challenge.

## From Earth to the moon

The ESA (European Space Agency) wants to send two robots (rovers) to the Moon.
They are fitted with a sophisticated landing support: a parachute.
The problem here is that it seems both robots won't land at the same place…
Once they've landed at the same place as their own parachutes at the Moon, which has a discrete surface of infinite size, both rovers must find each other to start the mission together.

The challenge consists on programming the rovers using a limited command set, so they finally manage to find each other.
Keep in mind that the same program will be loaded on both robots and they don't have any programatic way to know which their identifiers are.

## DSL for manouver

The command set that will be used for programming the rovers is composed of:

* MOVE <direction> : It moves the rover a discrete space unit to the left or to the right.

* IF FOUND PARACHUTE <command> : If the rover finds a parachute on the floor, at its feet wheels, then execute the
given command.

* NOP: Rover does nothing…

* GOTO <lineId> : It jumps to the command placed at the given line.

## How to define the Rover program

You can define your rover program at ```moonrover/display/src/main/scala/scalera/moonrover/Launch.scala``` file.

It should look similar to this:

```scala
package scalera.moonrover

import scalera.moonrover.RoverProgram._
import scalera.moonrover.interpreter.Program

/**
 * Define here the program that
 * your rovers must execute
 */
object Launch {

  val program = Program(
    1 -> RIGHT,
    2 -> GOTO(1))
}

```

Remember that all possibilities when defining the program are:

* RIGHT : Move right.
* LEFT : Move left.
* GOTO(lineId) : Jump to program's lineId.
* NOP : Do nothing
* \`IF FOUND PARACHUTE\`(command) : If the rover finds a parachute, execute another command.

## How does the simulator looks like?

![example](/doc/moonrover_example.png)

The most remarkable things are:
* At top-right you'll find the number of ticks have passed so far.
* At middle-center you'll find the distance between both rovers.
* At the bottom of the page you'll see both rovers' program execution (current execution line is highlighted with
blue color).

## Run it

Just execute ```sbt ~fastOptJS``` and you'll be able to simulate your rovers' landing at
```
http://localhost:12345/display/target/scala-2.11/classes/index.html
```

If you want to make changes at your rover program definition,
just change ```scalera.moonrover.Launch.scala``` contents, save the file and refresh the web browser page.
NB: Sometimes it's necessary to refresh with ```Ctrl``` + ```F5```.

If you want to change the simulation speed, you can do it at the ```scalera.moonrover.display.Config``` at line:

```scala
lazy val millisInterval = 1000
```

## Extra documentation

* [Hands-on scala](http://lihaoyi.github.io/hands-on-scala-js/)
* [Scalajs-dom](http://scala-js.github.io/scala-js-dom/)
* [Workbench-example](https://github.com/lihaoyi/workbench-example-app)


text:
var ele_help = null;

function createHelpDiv()
{
	ele_help = document.createElement('div');
	ele_help.innerHTML = 'a';
	var style = ele_help.style;
		style.position = 'absolute';
		style.zIndex = 1;
	//	style.backgroundColor = '#fff2f2';
	//	style.backgroundImage = 'url(img/box_bg.gif)';
	//	style.color = '#ff2222';
		style.width = '250px';
	//	style.height = '200px';
		style.display = 'none';
		style.visibility = 'hidden';
	//	style.borderWidth = '1px';
	//	style.borderStyle = 'solid';
	//	style.borderColor = '#000000';
	//	style.fontSize='12px';
		style.margin = '0px'
		style.padding = '0px'
	document.getElementsByTagName("body").item(0).appendChild(ele_help);
}

function showHelp(message,obj,event)
{
	if(!ele_help){
		createHelpDiv();
	}
	ele_help.innerHTML = message;
	var style = ele_help.style;
	style.display = '';
	style.visibility = 'visible';
	if(!isNaN(event.offsetX)){
		style.left = getEventPageX(event)-event.offsetX + 55 + 'px';
	}
	else
	{
		style.left = getEventPageX(event) + 10 + 'px';
	}
	style.top = getEventPageY(event) + 0 + 'px';
	style.zIndex = 1;
	obj.onmouseout = function(){hideHelp(obj);}
}

function showHelp2(message,obj,event)
{
	if(!ele_help){
		createHelpDiv();
	}
	ele_help.innerHTML = message;
	var style = ele_help.style;
	style.display = '';
	style.visibility = 'visible';
	if(!isNaN(event.offsetX)){
		style.left = getEventPageX(event)-event.offsetX+ 255 + 'px';
	}
	else
	{
		style.left = getEventPageX(event) + 10 + 'px';
	}
	style.top = getEventPageY(event) - 5 + 'px';
	style.zIndex = 1;
	obj.onmouseout = function(){hideHelp(obj);}
}

function hideHelp(obj)
{
	var style = ele_help.style;
	style.display = 'none';
	style.visibility = 'hidden';
	obj.onmouseout = null;
}

function getEventPageX(e){
	if(!e) var e = window.event;
	if(window.opera){
		return (document.documentElement?window.pageXOffset:0)+e.clientX;
	}
	else if(e.pageX)
		return e.pageX;
	else if(e.clientX){
		var sl=0;
		if(document.documentElement && document.documentElement.scrollLeft)
			sl=document.documentElement.scrollLeft;
		else if(document.body && document.body.scrollLeft)
			sl=document.body.scrollLeft;
		else if(window.scrollX||window.pageXOffset)
			sl=(window.scrollX||window.pageXOffset);
		return sl+e.clientX;
	}
	return 0;
}

function getEventPageY(e){
	if(!e) var e = window.event;
	if(window.opera){
		return (document.documentElement?window.pageYOffset:0)+e.clientY;
	}
	else if(e.pageY)
		return e.pageY;
	else if(e.clientY){
		var st = 0;
		if(document.documentElement && document.documentElement.scrollTop)
			st=document.documentElement.scrollTop;
		else if(document.body && document.body.scrollTop)
			st=document.body.scrollTop;
		else if(window.scrollY||window.pageYOffset)
			st=(window.scrollY||window.pageYOffset);
		return st+e.clientY;
	}
	return 0;
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width initial-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <title>Inspiración, frustración y transpiración: Sobre como los trenes cambian de dirección</title>
  <meta name="description" content="Las Cosas son como deben, no como deberían Ser.">
  <meta name="author" content="Mauricio Navarro Miranda">
  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <meta name="twitter:card" content="summary">
  <meta name="twitter:title" content="El rincón de mautemático">
  <meta name="twitter:description" content="Las Cosas son como deben, no como deberían Ser.">

  <meta property="og:type" content="article">
  <meta property="og:title" content="El rincón de mautemático">
  <meta property="og:description" content="Las Cosas son como deben, no como deberían Ser.">

  <link rel="apple-touch-icon" sizes="57x57" href="/images/favicons/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="/images/favicons/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/images/favicons/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="/images/favicons/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="/images/favicons/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="/images/favicons/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/images/favicons/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="/images/favicons/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicons/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-194x194.png" sizes="194x194">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="/images/favicons/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="/images/favicons/manifest.json">
  <link rel="shortcut icon" href="/images/favicons/favicon.ico">
  <meta name="msapplication-TileColor" content="#ffc40d">
  <meta name="msapplication-TileImage" content="/images/favicons/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="https://blog.mautematico.com//2012/inspiracion-frustracion-y-transpiracion-sobre-como-los-trenes-cambian-de-direccion.html">
  <link rel="alternate" type="application/rss+xml" title="El rincón de mautemático" href="/feed.xml">

El rincón de mautemático

Las Cosas son como deben, no como deberían Ser.

Blog

                  Twitter

                  GitHub

                  Email

                RSS

      <time datetime="4 Dec 2012" class="post-meta__date date">4 Dec 2012</time> • on

Inspiración, frustración y transpiración: Sobre como los trenes cambian de dirección

En un martes al azar, como en cualquier otro, uno puede elegir entre ver una serie hot y hacer algo importante. Hoy decidí hacer ambas, aunque en tiempos distintos. Me resulta curioso mencionarlo, porque a estas horas del día no he concluído ninguna.

Para este martes en particular, tenía un plan. ¡Cómo me odio por hablar en pretérito para evadir el presente!

Para este martes en particular, tengo un plan. Lo bueno de los planes es que pueden adaptarse y si son lo suficientemente buenos permiten incluso improvisar. Los míos no son siempre robustos, pero hoy heme aquí: Improvisando.

¿Has leído sobre pilas y colas? Son técnicas empleadas en programación para manejo de algunos datos. Supongamos que los datos son libros:

En una pila, los libros apilados primero deberán salir al final. Ya sabes, porque si sacas el libro de hasta abajo, la pila entera se cae.

En una fila cola es similar, pero al revés: Los libros que se forman primero, son los que primero salen.

¿Y si los datos son dichos? Dependerá de cada quien. Yo intentaré hoy con una fila.

Mientras GrooveShark me ofrece “Eres”, de Café Tacvba, te conataré un poco sobre mi anoche y mi hoy:

El lunes, por azares del destino, terminé en casa cenando tacos con Quique, un buen amigo de la facultad, mientras hablábamos de amores y cotorreos varios. Hablando de amores y noches: Mi amor se despidió ese día poco antes de las 00:00 del martes. Pero el cotorreo entre Quique y yo se extendería varias horas más.

En algún momento, entre uno de mis nuevos facebook-amigos y yo comenzó una ciber-ronda de confesiones. De nuevo, de amores. ¡Qué pequeño es el mundo y cuan importante el amor! Llegó el momento de despedida del facebook-amigo, junto con el momento de descargar películas para verlas posteriormente.

Para no entretenernos en detalles innecesarios: Quique y yo permanecimos despiertos hasta eso de las 6:00. Le tocó ser testigo de mi mensaje matutinimísimo, serían por ahí de las 4:37 cuando lo envié. Luego nada.

Desaparezcamos a Quique, veamos sólos una película donde aparezca Ana Claudia Talancón, y tomémosle una foto a Flatland, el libro que Larry me prestó ayer. Mi celular sigue sin ser reanimado.

Y que el tiempo vuele, tanto para ver por la tarde un capítulo y medio de Satisfaction, una serie que me sugirieron anoche.

¡Un momento emocionante se avecina! Mi amor ha llegado y me presume algo que yo en su lugar también presumiría. ¡Qué felicidad! <img src='http://blog.mautematico.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> (y esta fue la primera carita, apenas puedo creer que resistí tanto sin poner una)

¿Te acuerdas de mi celular muerto? Cuando le comenté a mi amor al respecto, y dije que extrañaba sus mensajes, respondió algo que no logré comprender. Maldito mi cerebro que se me adeltanta y traduce a Oh, he estado ignorándote.

Es este el punto en que ya no me apetece la cursi Satisfaction, y que veo como mi plan para hoy necesitará de mucha improvisación.

Minutos después, mientras camino por las calles de Guanajuato y respiro aire fresco, me acuerdo de mi reciente descubrimiento: ¡Los trenes! Por dios, no lo he contado todavía. Y parece que ha llegado el momento:

Nacho preguntó:

¿Saben como hacen los trenes para girar? Tras algunas aclaraciones y explicaciones, entendimos la pregunta:

Los automóviles tienen un mecanísmo interesante para “doblar a la izquierda” o a la derecha: Cuando giras el volante, a simple vista puedes apreciar que las ruedas “giran” en la misma dirección. Si observas un poco más, notarás que mientras el automóvil está doblando una de las ruedas recorre una distancia mayor. ¿Y eso qué? Es ahí donde entra el mecanismo diferencial del automóvil: La rueda que recorre distancia mayor debe girar más rápido, debe dar más vueltas.

¡Pero los trenes no tienen volante, van sobre rieles! ¿Qué tal si el tren del que hablamos tampoco tiene ese maravilloso mecanísmo diferencial? Y no culparía a los fabricantes por no implementarlo: Después de todo, sería un alto costo considerando la cantidad de ejes que tiene un tren. Seguro podemos hacer una breve prueba: Si las ruedas del tren giran a la misma velocidad, el tren se descarrila al girar.

Además de alto, ponerle mecanismo diferencial a un tren es innecesario, porque existen otras soluciones. La pregunta de Nacho fue ¿Cuál es una de ellas?

Durante la clase, se me ocuriró una solución: ¡Levantar un riel! Sí, en serio. Levantar el riel “interior” en la zona de curva. Nacho pensó un momento y comentó que mi solución no funcionaba, que resolvía un problema diferente. Hoy sé que mi solución sí funciona; sospecho que Nacho pensó en el riel exterior.

Pero la solución no está en los rieles, sino en las ruedas. Y lo descubrí por fin varios dias después de entendida la pregunta.

…Era una tranquila tarde de miércoles, y hacía hambre. Fuí a erizos a comer, donde fuí recibidopor varias mesas  parcialmente ocupadas por personas a quienes no conozco. Con todas las mesas, lo mismo, a excepción de una: La mesa en que estaban Nacho y quien parece ser su alumno de tesis. Me senté con ellos.

Nacho y el jóven con quien estaba hacían Matemáticas que todavía no comprendo. Lo que sí sé es que hacían ecuaciones diferenciales para modelado de fenómenos epidemiolóǵicos, parafraseando a Nacho. Sé que no me mintió porque en el pizarrón de su oficina había hace meses justo eso.

Con mi curiosidad momentánea satisfecha, volvió a mi la pregunta sobre los trenes. Con una botella de pet en mano y vagas ideas sobre velocidades angulares, luego de algunos minutos la idea llegó: ¡Las ruedas de los trenes no son ruedas, sino conos! Con diámetros distintos en puntos de apollo distintos, se tiene una misma velocidad de rotación, pero diferentes velocidades angulares (ahora mismo no estoy seguro sobre el nombre, pero la idea intuitiva es: Diametro menor => La rueda en forma de cono recorre una distancia menor).

¡Y fin! Los trenes no requieren mecanismo diferencial ni volante, ni elevación de rieles para cambiar de dirección. Basta que sus ruedas no sean ruedas.

Hoy es martes, y tengo un plan pendiente. Pero ya tengo una historia menos que compartir. Carpe diem.

  © 2020 Mauricio Navarro Miranda. All rights reserved.


text:
/*global AWPCP*/
/*global jQuery*/

AWPCP.define('jquery', [], function() { return jQuery; });


text:
from __future__ import unicode_literals, division, absolute_import
from builtins import *  # pylint: disable=unused-import, redefined-builtin
import os
import time
import logging

from flexget import plugin
from flexget.event import event
from flexget.utils.tools import parse_timedelta
from flexget.utils.pathscrub import pathscrub

log = logging.getLogger('convert_magnet')

class ConvertMagnet(object):
    """Convert magnet only entries to a torrent file"""

    schema = {
        "oneOf": [
            # Allow convert_magnet: no form to turn off plugin altogether
            {"type": "boolean"},
            {
                "type": "object",
                "properties": {
                    "timeout": {"type": "string", "format": "interval", "default": "30 seconds"},
                },
                "additionalProperties": False
            }
        ]
    }

    def magnet_to_torrent(self, magnet_uri, destination_folder, timeout):
        import libtorrent
        params = libtorrent.parse_magnet_uri(magnet_uri)
        session = libtorrent.session()
        # for some reason the info_hash needs to be bytes but it's a struct called sha1_hash
        params['info_hash'] = bytes(params['info_hash'])
        handle = libtorrent.add_magnet_uri(session, magnet_uri, params)
        log.debug('Acquiring torrent metadata for magnet %s', magnet_uri)
        timeout_value = timeout
        while not handle.has_metadata():
            time.sleep(0.1)
            timeout_value -= 0.1
            if timeout_value <= 0:
                raise plugin.PluginError('Timed out after {} seconds trying to magnetize'.format(timeout))
        log.debug('Metadata acquired')
        torrent_info = handle.get_torrent_info()
        torrent_file = libtorrent.create_torrent(torrent_info)
        torrent_path = pathscrub(os.path.join(destination_folder, torrent_info.name() + ".torrent"))
        with open(torrent_path, "wb") as f:
            f.write(libtorrent.bencode(torrent_file.generate()))
        log.debug('Torrent file wrote to %s', torrent_path)
        return torrent_path

    def prepare_config(self, config):
        if not isinstance(config, dict):
            config = {}
        config.setdefault('timeout', '30 seconds')
        return config

    @plugin.priority(255)
    def on_task_start(self, task, config):
        if config is False:
            return
        try:
            import libtorrent
        except ImportError:
            raise plugin.DependencyError('convert_magnet', 'libtorrent', 'libtorrent package required', log)

    @plugin.priority(130)
    def on_task_download(self, task, config):
        if config is False:
            return
        config = self.prepare_config(config)
        # Create the conversion target directory
        converted_path = os.path.join(task.manager.config_base, 'converted')

        timeout = parse_timedelta(config['timeout']).total_seconds()

        if not os.path.isdir(converted_path):
            os.mkdir(converted_path)

        for entry in task.accepted:
            if entry['url'].startswith('magnet:'):
                entry.setdefault('urls', [entry['url']])
                try:
                    log.info('Converting entry {} magnet URI to a torrent file'.format(entry['title']))
                    torrent_file = self.magnet_to_torrent(entry['url'], converted_path, timeout)
                except (plugin.PluginError, TypeError) as e:
                    log.error('Unable to convert Magnet URI for entry %s: %s', entry['title'], e)
                    continue
                # Windows paths need an extra / prepended to them for url
                if not torrent_file.startswith('/'):
                    torrent_file = '/' + torrent_file
                entry['url'] = torrent_file
                entry['file'] = torrent_file
                # make sure it's first in the list because of how download plugin works
                entry['urls'].insert(0, 'file://{}'.format(torrent_file))

@event('plugin.register')
def register_plugin():
    plugin.register(ConvertMagnet, 'convert_magnet', api_ver=2)


text:
package org.hisp.dhis.chart;

import org.hisp.dhis.common.AnalyticalObjectService;
import org.hisp.dhis.common.GenericAnalyticalObjectDeletionHandler;

/**
 * @author Lars Helge Overland
 */
public class ChartDeletionHandler
    extends GenericAnalyticalObjectDeletionHandler<Chart>
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private ChartService chartService;

    public void setChartService( ChartService chartService )
    {
        this.chartService = chartService;
    }

    // -------------------------------------------------------------------------
    // DeletionHandler implementation
    // -------------------------------------------------------------------------

    @Override
    protected AnalyticalObjectService<Chart> getAnalyticalObjectService()
    {
        return chartService;
    }

    @Override
    public String getClassName()
    {
        return Chart.class.getSimpleName();
    }
}


text:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>

            <group id="culqi" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="0">
                Culqi
                <comment> <![CDATA[Conéctate a nuestra pasarela de pagos para aumentar tus ventas. Acepta pago con tarjetas, pagoefectivo, billeteras móviles y cuotéalo desde tu tienda virtual.]]> </comment>
                <fieldset_css>culqi-other-section</fieldset_css>
                <frontend_model>Magento\Paypal\Block\Adminhtml\System\Config\Fieldset\Payment</frontend_model>
                <field id="info_block" translate="label" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0">
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\Info</frontend_model>
                </field>

                <field id="active" translate="label" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="0">
                    Culqi Checkout
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\Active</frontend_model>

                </field>
                <field id="enviroment" translate="label" type="radios" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="0">
                    Elige el entorno donde activarás tu checkout
                    <source_model>Culqi\Pago\Block\Adminhtml\Form\Field\Enviroment</source_model>
                </field>
                <field id="login" translate="label" sortOrder="4" showInDefault="1" showInWebsite="0" showInStore="0">
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\Login</frontend_model>
                    <attribute type="shared">1</attribute>
                </field>
                 <field id="llave_publica" translate="label" sortOrder="4" showInDefault="1" showInWebsite="0" showInStore="0">
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\PublicKey</frontend_model>
                    <attribute type="shared">1</attribute>
                    <comment>Ingresa tu llave pública</comment>
                </field>
                <field id="llave_secreta" translate="label" sortOrder="4" showInDefault="1" showInWebsite="0" showInStore="0">
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\SecretKey</frontend_model>
                    <attribute type="shared">1</attribute>
                </field>
                <field id="payment_methods" translate="label" sortOrder="7" showInDefault="1" showInWebsite="1" showInStore="0">
                    Métodos de pago
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\PaymentMethods</frontend_model>
                </field>

                <field id="timexp" translate="label" type="text" sortOrder="8" showInDefault="1" showInWebsite="1" showInStore="0">
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\TimeExpiration</frontend_model>
                </field>
                <field id="notpay" translate="label" type="text" sortOrder="9" showInDefault="1" showInWebsite="1" showInStore="0">

                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\NotifyPayment</frontend_model>
                </field>
                <field id="personalize" translate="label" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\PersonalizeTheme</frontend_model>
                    <attribute type="shared">1</attribute>
                </field>
                <field id="logo" translate="label" type="text" sortOrder="11" showInDefault="1" showInWebsite="1" showInStore="0">
                    Logo URL
                    <comment>Este logo aparecerá en tu Culqi Checkout</comment>
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\Disable</frontend_model>
                </field>
                <field id="theme" translate="label" type="text" sortOrder="12" showInDefault="1" showInWebsite="1" showInStore="0">
                    Tema elegido
                    <comment>Utilizaremos estos colores para personalizar tu checkout.</comment>
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\Disable</frontend_model>
                </field>
                <field id="username_webhook" translate="label" type="text" sortOrder="13" showInDefault="1" showInWebsite="1" showInStore="0">
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\UserNameWebhook</frontend_model>
                </field>
                <field id="password_webhook" translate="label" type="text" sortOrder="14" showInDefault="1" showInWebsite="1" showInStore="0">
                    <frontend_model>Culqi\Pago\Block\Adminhtml\Form\Field\PasswordWebhook</frontend_model>
                </field>
            </group>

    </system>
</config>


text:
package edu.uci.ics.asterix.external.library;

import edu.uci.ics.asterix.external.library.java.JObjects.JBoolean;
import edu.uci.ics.asterix.external.library.java.JObjects.JCircle;
import edu.uci.ics.asterix.external.library.java.JObjects.JDate;
import edu.uci.ics.asterix.external.library.java.JObjects.JDateTime;
import edu.uci.ics.asterix.external.library.java.JObjects.JDouble;
import edu.uci.ics.asterix.external.library.java.JObjects.JDuration;
import edu.uci.ics.asterix.external.library.java.JObjects.JFloat;
import edu.uci.ics.asterix.external.library.java.JObjects.JInt;
import edu.uci.ics.asterix.external.library.java.JObjects.JLine;
import edu.uci.ics.asterix.external.library.java.JObjects.JOrderedList;
import edu.uci.ics.asterix.external.library.java.JObjects.JPoint;
import edu.uci.ics.asterix.external.library.java.JObjects.JPoint3D;
import edu.uci.ics.asterix.external.library.java.JObjects.JPolygon;
import edu.uci.ics.asterix.external.library.java.JObjects.JRecord;
import edu.uci.ics.asterix.external.library.java.JObjects.JString;
import edu.uci.ics.asterix.external.library.java.JObjects.JTime;
import edu.uci.ics.asterix.external.library.java.JObjects.JUnorderedList;
import edu.uci.ics.asterix.external.library.java.JTypeTag;

public class AllTypesFunction implements IExternalScalarFunction {

    private JOrderedList newFieldList;

    @Override
    public void initialize(IFunctionHelper functionHelper) {
        newFieldList = new JOrderedList(functionHelper.getObject(JTypeTag.INT));
    }

    @Override
    public void deinitialize() {
    }

    @Override
    public void evaluate(IFunctionHelper functionHelper) throws Exception {
        newFieldList.clear();
        JRecord inputRecord = (JRecord) functionHelper.getArgument(0);
        JInt id = (JInt) inputRecord.getValueByName("id");
        JString name = (JString) inputRecord.getValueByName("name");
        JFloat age = (JFloat) inputRecord.getValueByName("age");
        JDouble salary = (JDouble) inputRecord.getValueByName("salary");
        JBoolean married = (JBoolean) inputRecord.getValueByName("married");
        JUnorderedList interest = (JUnorderedList) inputRecord.getValueByName("interests");
        JOrderedList children = (JOrderedList) inputRecord.getValueByName("children");
        JRecord address = (JRecord) inputRecord.getValueByName("address");
        JDate dob = (JDate) inputRecord.getValueByName("dob");
        JTime time = (JTime) inputRecord.getValueByName("time");
        JDateTime dateTime = (JDateTime) inputRecord.getValueByName("datetime");
        JDuration duration = (JDuration) inputRecord.getValueByName("duration");
        JPoint location2d = (JPoint) inputRecord.getValueByName("location2d");
        JPoint3D location3d = (JPoint3D) inputRecord.getValueByName("location3d");
        JLine line = (JLine) inputRecord.getValueByName("line");
        JPolygon polygon = (JPolygon) inputRecord.getValueByName("polygon");
        JCircle circle = (JCircle) inputRecord.getValueByName("circle");

        JRecord result = (JRecord) functionHelper.getResultObject();
        result.setField("id", id);
        result.setField("name", name);
        result.setField("age", age);
        result.setField("salary", salary);
        result.setField("married", married);
        result.setField("interests", interest);
        result.setField("children", children);
        JInt zipCode = (JInt) functionHelper.getObject(JTypeTag.INT);
        zipCode.setValue(92841);
        address.addField("Zipcode", zipCode);
        result.setField("address", address);
        result.setField("dob", dob);
        result.setField("time", time);
        result.setField("datetime", dateTime);
        result.setField("duration", duration);
        result.setField("location2d", location2d);
        result.setField("location3d", location3d);
        result.setField("line", line);
        result.setField("polygon", polygon);
        result.setField("circle", circle);

        JString newFieldString = (JString) functionHelper.getObject(JTypeTag.STRING);
        newFieldString.setValue("processed");
        result.addField("status", newFieldString);

        /*
         * JString element = (JString)
         * functionHelper.getObject(JTypeTag.STRING); element.setValue("raman");
         * newFieldList.add(element); result.addField("mylist", newFieldList);
         */

        JString newFieldString2 = (JString) functionHelper.getObject(JTypeTag.STRING);
        newFieldString2.setValue("this is working");
        result.addField("working", newFieldString);
        functionHelper.setResult(result);
    }
}


text:
Number of records to return from remote data source per attempt.

    Integer, default = 100

This property only applies if your data source for the grid is remote. As of 1.3, the default behavior of the grid is infinite
scroll, which means as user scrolls more records will be loaded. Each time a request will be sent to the server to
retrieve records, it will submit .limit as the number of records to return.

This property can be set during object creation:
<textarea class="javascript">
$('#grid').w2grid({
    name    : 'grid',
    limit     : 500,
    columns : [
        { field: 'recid', caption: 'ID', size: '50px' },
        { field: 'lname', caption: 'Last Name', size: '30%' },
        { field: 'fname', caption: 'First Name', size: '30%' },
        { field: 'email', caption: 'Email', size: '40%' },
        { field: 'sdate', caption: 'Start Date', size: '120px' },
        { field: 'sdate', caption: 'End Date', size: '120px' }
    ]
});
</textarea>

Or any time during run-time:
<textarea class="javascript">
w2ui['grid'].limit = 500;
</textarea>


text:
package org.openstack.atlas.rax.api.validation.validator;

import org.openstack.atlas.api.validation.Validator;
import org.openstack.atlas.api.validation.ValidatorBuilder;
import org.openstack.atlas.api.validation.result.ValidatorResult;
import org.openstack.atlas.api.validation.validator.ResourceValidator;
import org.openstack.atlas.api.validation.validator.ValidatorUtilities;
import org.openstack.atlas.api.validation.verifier.IsInstanceOf;
import org.openstack.atlas.rax.domain.entity.RaxAccessList;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import static org.openstack.atlas.api.validation.ValidatorBuilder.build;
import static org.openstack.atlas.api.validation.context.HttpRequestType.POST;

@Primary
@Component
@Scope("request")
public class RaxLoadBalancerValidator implements ResourceValidator<Object> {

    private final Validator<Object> validator;

    public RaxLoadBalancerValidator() {
        validator = build(new ValidatorBuilder<Object>(Object.class) {
            {
                // POST EXPECTATIONS
                if_().adhereTo(new IsInstanceOf(RaxAccessList.class)).then().must().delegateTo(new AccessListValidator().getValidator(), POST).forContext(POST);
            }
        });
    }

    @Override
    public ValidatorResult validate(Object object, Object type) {
        ValidatorResult result = validator.validate(object, type);
        return ValidatorUtilities.removeEmptyMessages(result);
    }

    @Override
    public Validator<Object> getValidator() {
        return validator;
    }
}


text:
exports.lazyLoad = function (context, container){
    var doc = document,
        body = doc.body,
        win = window,
        winDoc = win.document.documentElement,
        $win = angular.element(win),
        $cont = container ? container : null,
        uid = 0,
        elements = {},
        imgArr = [],
        curW = winDoc.clientWidth - (1.28 * parseFloat(winDoc.style.fontSize));

    function getUid(el){
        return el.__uid || (el.__uid = ('' + (++uid)));
    }

    function getWindowOffset(){
        var t,
            pageXOffset = (typeof win.pageXOffset == 'number') ? win.pageXOffset : (((t = doc.documentElement) || (t = body.parentNode)) && typeof t.ScrollLeft == 'number' ? t : body).ScrollLeft,
            pageYOffset = (typeof win.pageYOffset == 'number') ? win.pageYOffset : (((t = doc.documentElement) || (t = body.parentNode)) && typeof t.ScrollTop == 'number' ? t : body).ScrollTop;
        return {
            offsetX: pageXOffset,
            offsetY: pageYOffset
        };
    }

    function isVisible(iElement){
        var elem = iElement[0],
            elemRect = elem.getBoundingClientRect(),
            windowOffset = getWindowOffset(),
            winOffsetX = windowOffset.offsetX,
            winOffsetY = windowOffset.offsetY,
            elemWidth = elemRect.width,
            elemHeight = elemRect.height,
            elemOffsetX = elemRect.left + winOffsetX,
            elemOffsetY = elemRect.top + winOffsetY,
            viewWidth = Math.max(doc.documentElement.clientWidth, win.innerWidth || 0),
            viewHeight = Math.max(doc.documentElement.clientHeight, win.innerHeight || 0),
            xVisible,
            yVisible;

        if(elemOffsetY <= winOffsetY){
            if(elemOffsetY + elemHeight >= winOffsetY){
                yVisible = true;
            }
        }else if(elemOffsetY >= winOffsetY){
            if(elemOffsetY <= winOffsetY + viewHeight){
                yVisible = true;            }
        }

        if(elemOffsetX <= winOffsetX){
            if(elemOffsetX + elemWidth >= winOffsetX){
                xVisible = true;
            }
        }else if(elemOffsetX >= winOffsetX){
            if(elemOffsetX <= winOffsetX + viewWidth){
                xVisible = true;
            }
        }

        return xVisible && yVisible;
    };

    function checkImage(){
        Object.keys(elements).forEach(function(key){
            var obj = elements[key],
                iElement = obj.iElement,
                lazySrc = obj.lazySrc,
                eleSrc = iElement.attr('src');

            if(isVisible(iElement) && !eleSrc){
                iElement.attr('src', lazySrc)
                    .css({'opacity': 1});
            }
        });
    }

    if($cont){
        var contLen = $cont.length;
        if(contLen > 1){
            for(var i=0; i<contLen; i++){
                $cont[i].addEventListener('scroll', checkImage);
            }
        }else{
            $cont.addEventListener('scroll', checkImage);
        }
    }else{
        $win.bind('scroll', checkImage);
    }
    $win.bind('resize', checkImage);
    $win.bind('touchmove', checkImage);

    function onLoad(){
        var $el = angular.element(this),
            uid = getUid($el);

        $el.css('opacity', 1);

        if(elements.hasOwnProperty(uid)){
            delete elements[uid];
        }
    }

    if(context){
        imgArr = context.getElementsByTagName('img');
    }else{
        imgArr = doc.getElementsByTagName('img');
    }

    for(var i=0; i<imgArr.length; i++){
        var el = angular.element(imgArr[i]),
            src = imgArr[i].getAttribute('lazy-src'),
            oriW = el.attr('data-width') ? parseFloat(el.attr('data-width')) : 0,
            oriH = el.attr('data-height') ? parseFloat(el.attr('data-height')) : 0,
            ratio = oriW && oriH ? oriH/oriW : 0,
            curH = ratio ? Math.ceil(curW*ratio) : 0;

        el.bind('load', onLoad);

        if(src){
            if(isVisible(el)){
                el.attr('src', src)
                    .css('opacity', 1);
            }else{
                var uid = getUid(el[0]);
                el.css({
                    'background-color': '#fff',
                    'opacity': 1,
                    '-webkit-transition': 'opacity .2s',
                    'transition': 'opacity .2s'
                });
                elements[uid] = {
                    iElement: el,
                    lazySrc: src
                };
            }
            if(curH){
                el.css('height', curH + 'px');
            }
        }

        el.unbind('load');
    }

    setTimeout(function(){checkImage();}, 200);
};


text:
<?php

namespace Point\PointPurchasing\Models\Service;

use Illuminate\Database\Eloquent\Model;
use Point\Core\Traits\ByTrait;
use Point\Framework\Traits\FormulirTrait;

class PurchaseOrderDetail extends Model {
  use ByTrait, FormulirTrait;

  /**
   * @var string
   */
  protected $table = 'point_purchasing_service_purchase_order_detail';
  /**
   * @var mixed
   */
  public $timestamps = false;

  /**
   * @var array
   */
  protected $guarded = [];

  /**
   * @return mixed
   */
  public function service() {
    return $this->belongsTo('\Point\Framework\Models\Master\Service', 'service_id');
  }

  /**
   * @return mixed
   */
  public function allocation() {
    return $this->belongsTo('\Point\Framework\Models\Master\Allocation', 'allocation_id');
  }
}


text:
def getSslString():
	print "args: ",sys.argv
	# default ssl is false
	ldapssl=0
	if (len(sys.argv) > 0):
	  ldapserver=sys.argv[0]
	  ldapssl=("SSLEnabledTDS" == ldapserver)

	if ldapssl:
	  sslEnabledString = " -sslEnabled true"
	else:
	  sslEnabledString = " -sslEnabled false"

	return  sslEnabledString

def singleWAS():
	celllist = AdminConfig.list('Cell').split("\n")
	if (len(celllist) == 1 ):
	    cellname = AdminConfig.showAttribute(celllist[0], 'name')
	    print "cell name is: " + cellname
	else:
	    print "this script works with single cell only"
	    sys.exit()

	serverlist = AdminTask.listServers('[-serverType APPLICATION_SERVER ]').splitlines()
	if (len(serverlist) == 1 ):
	    servername = AdminConfig.showAttribute(serverlist[0], 'name')
	    print "server name is: " + servername
	else:
	    print "this script works with single server only. there are " + len(serverlist)
	    sys.exit()
	print "====== end server info ===============\n"

	stuffAfterNodes=serverlist[0].split("nodes/")[1]
	nodename=stuffAfterNodes.split("/servers/")[0]
	print "the nodename is " + nodename + "\n"

def genProp():
	print "-------Configure LDAP General Properties-------"
	ldapGenProps = "[-ldapHost " + propertiesLDAP.getProperty("jazz_ldap_host")
	ldapGenProps = ldapGenProps + " -ldapPort " + propertiesLDAP.getProperty("jazz_ldap_port")
	ldapGenProps = ldapGenProps + " -ldapServerType CUSTOM "
	ldapGenProps = ldapGenProps + " -baseDN " + propertiesLDAP.getProperty("jazz_ldap_baseDN")
	ldapGenProps = ldapGenProps + " -bindDN " + propertiesLDAP.getProperty("jazz_ldap_bindDN")
	ldapGenProps = ldapGenProps + " -bindPassword " + propertiesLDAP.getProperty("jazz_ldap_bindPassword")
	ldapGenProps = ldapGenProps + " -searchTimeout 120 -reuseConnection false " + sslEnabledString + " -sslConfig -autoGenerateServerId true"
	ldapGenProps = ldapGenProps + " -primaryAdminId " + propertiesLDAP.getProperty("jazz_ldap_primaryid")
	ldapGenProps = ldapGenProps + " -ignoreCase false -customProperties -verifyRegistry false]"
	rc = AdminTask.configureAdminLDAPUserRegistry(ldapGenProps)
	rc = AdminConfig.save()

def addlProp():
	print "-------Configure Perf LDAP Additional Properties-------"
	ldapAddProps = "[-userFilter " + propertiesLDAP.getProperty("jazz_ldap_userFilter")
	ldapAddProps = ldapAddProps + " -groupFilter " + propertiesLDAP.getProperty("jazz_ldap_groupFilter")
	ldapAddProps = ldapAddProps + " -userIdMap " + propertiesLDAP.getProperty("jazz_ldap_userIdMap")
	ldapAddProps = ldapAddProps + " -groupIdMap " + propertiesLDAP.getProperty("jazz_ldap_groupIdMap")
	ldapAddProps = ldapAddProps + " -groupMemberIdMap " + propertiesLDAP.getProperty("jazz_ldap_groupMemberIdMap")
	ldapAddProps = ldapAddProps + " -certificateFilter -certificateMapMode EXACT_DN -krbUserFilter"
	ldapAddProps = ldapAddProps + ' -customProperties ["com.ibm.websphere.security.ldap.recursiveSearch="] -verifyRegistry false'
	ldapAddProps = ldapAddProps + "]"
	rc = AdminTask.configureAdminLDAPUserRegistry(ldapAddProps)
	rc = AdminConfig.save()
def setRealmTrust():
	print "-------Set Realm Trust-------"
	AdminTask.configureTrustedRealms('[-communicationType inbound -trustAllRealms false]')
	AdminConfig.save()

def testCon():
	print "-------Test LDAP Connection-------"
	ldapConn = "[-type CUSTOM -hostname " + propertiesLDAP.getProperty("jazz_ldap_host")
	ldapConn = ldapConn + " -port " + propertiesLDAP.getProperty("jazz_ldap_port")
	ldapConn = ldapConn + " -baseDN " + propertiesLDAP.getProperty("jazz_ldap_baseDN")
	ldapConn = ldapConn + " -bindDN " + propertiesLDAP.getProperty("jazz_ldap_bindDN")
	ldapConn = ldapConn + " -bindPassword " + propertiesLDAP.getProperty("jazz_ldap_bindPassword")
	ldapConn = ldapConn + sslEnabledString + "]"
	rc = AdminTask.validateLDAPConnection(ldapConn)
	rc = AdminConfig.save()
	rc = AdminTask.configureAdminLDAPUserRegistry('[-verifyRegistry true ]')
	rc = AdminConfig.save()

def setCurrentSecurity():
	print "-------Set Security Current Settings-------"
	AdminTask.setAdminActiveSecuritySettings('-enableGlobalSecurity true -cacheTimeout 600 -enforceJava2Security false -appSecurityEnabled true -activeUserRegistry LDAPUserRegistry -activeAuthMechanism LTPA')
	rc = AdminConfig.save()

	print "-------Save Registry as Current & Display Current Registry Settings-------"
	#Saves Registry
	print AdminTask.getUserRegistryInfo('[-userRegistryType LDAPUserRegistry]')
	AdminConfig.save()

def syncNodes():
	print "------------------ sync nodes ---------------"
	nodelist = AdminConfig.list('Node').split("\n")

	for n in nodelist:
		nodename = AdminConfig.showAttribute(n, 'name')
		objname = "type=NodeSync,node=" + nodename + ",*"
		Syncl = AdminControl.completeObjectName(objname)
		if Syncl != "":
			AdminControl.invoke(Syncl, 'sync')
			print "Done with node " + nodename
		else:
			print "Skipping node " + nodename
		continue

##################################################
# Main
##################################################
print "\n"
import sys
import java.util as util
import java.io as javaio
import os
import shutil
if (len(sys.argv) > 1):
  print "PROFILE_TYPE =", sys.argv[1]
  PROFILE_TYPE = sys.argv[1]

#global variables
ldapfile="/tmp/WASCommon/LDAP/LDAPSecurity.properties"
ldapdir = "/tmp/WASCommon/LDAP"
#load LDAP Properties from properties file
propertiesLDAP = util.Properties()
propertiesLDAPfile = javaio.FileInputStream(ldapfile)
propertiesLDAP.load(propertiesLDAPfile)
# if cluster
if PROFILE_TYPE == "dmgr":
	syncNodes()
else:
	# if single
	singleWAS()

sslEnabledString = getSslString()
genProp()
addlProp()
setRealmTrust()
testCon()
setCurrentSecurity()

# if cluster
if PROFILE_TYPE == "dmgr":
	syncNodes()


text:
package com.example.mzxy.welcome;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.mzxy.view.MainActivity;
import com.example.mzxy.R;

public class SplashActivity extends AppCompatActivity {
    private ViewPagerAdapter viewPagerAdapter;
    private ViewPager viewPager;
    private Button splashBtn;
    private ImageView[] imageDot;
    private LinearLayout dot;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        dot = (LinearLayout) findViewById(R.id.splash_dot);
        initDot();
        splashBtn = (Button) findViewById(R.id.splash_btn);
        viewPager = (ViewPager) findViewById(R.id.splash_view_pager);
        //适配器初始化
        viewPagerAdapter = new ViewPagerAdapter(this, SplashImages.imageArray);
        //绑定适配器
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPagerChangedListener());
        splashBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void initDot() {
        imageDot = new ImageView[SplashImages.imageArray.length];
        for (int i = 0; i < SplashImages.imageArray.length; i++) {
            ImageView imageView = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            imageView.setLayoutParams(params);
            imageDot[i] = imageView;
            if (i == 0) {
                imageDot[i].setBackgroundResource(R.mipmap.dot_red);
            } else {
                imageDot[i].setBackgroundResource(R.mipmap.dot_blue);
            }
            dot.addView(imageView);
        }
    }

    class ViewPagerChangedListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (position == SplashImages.imageArray.length - 1) {
                splashBtn.setVisibility(View.VISIBLE);
            } else {
                splashBtn.setVisibility(View.GONE);
            }
            for (int i = 0; i < imageDot.length; i++) {
                if (i == position) {
                    imageDot[i].setBackgroundResource(R.mipmap.dot_red);
                } else {
                    imageDot[i].setBackgroundResource(R.mipmap.dot_blue);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }
}


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

<title>Overview</title>
<meta name="date" content="2017-11-17">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Packages

Package
Description

no.nordicsemi.android.dfu

no.nordicsemi.android.dfu.internal

no.nordicsemi.android.dfu.internal.exception

no.nordicsemi.android.dfu.internal.manifest

no.nordicsemi.android.dfu.internal.scanner

no.nordicsemi.android.error

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package de.danoeh.antennapodsp.util.id3reader.model;

public class TagHeader extends Header {

    protected char version;
    protected byte flags;

    public TagHeader(String id, int size, char version, byte flags) {
        super(id, size);
        this.version = version;
        this.flags = flags;
    }

    @Override
    public String toString() {
        return "TagHeader [version=" + version + ", flags=" + flags + ", id="
                + id + ", size=" + size + "]";
    }

    public char getVersion() {
        return version;
    }

}


text:
package com.blstream.myhoard.validator;

import com.blstream.myhoard.biz.model.Location;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class LocationValidator implements ConstraintValidator<GeographicLocation, Location> {

    @Override
    public void initialize(GeographicLocation a) {
        //
    }

    @Override
    public boolean isValid(Location t, ConstraintValidatorContext cvc) {
        return t == null || t.getLat() >= -90 && t.getLat() <= 90 && t.getLng() >= -180 && t.getLng() <= 180;
    }

}


text:
#pragma once

#include "Weapon.hpp"
#include "Armor.hpp"

#include <array>

class Equipment : public GameObject
{
public:
	/*
	enum Slot
	{
		MainHand,
		OffHand,
		Head,
		Chest,
		SlotCount
	};
	*/

public:
	explicit Equipment(Actor& owner);

	Weapon* getCurrentWeapon() const;
	void dropCurrentWeapon();

	void selectWeapon(int index);
	void selectPrevWeapon();
	void selectNextWeapon();

	Weapon* getWeapon(Weapon::Type type) const;
	void setWeapon(Weapon::Type type, Weapon* weapon);

	Armor* getArmor(Armor::Type type) const;
	void setArmor(Armor::Type type, Armor* armor);

private:
	Actor& actor;
	std::array<Entity::Ptr, Weapon::TypeCount> weapons;
	std::array<Entity::Ptr, Armor::TypeCount> armors;

	int currentWeapon = -1;

	// REMOVE: friend
	friend class ActorPlayer;
	friend class ActorEnemy;
};


text:
"""Implement a high level U2F API analogous to the javascript API spec.

This modules implements a high level U2F API that is analogous in spirit
to the high level U2F javascript API.  It supports both registration and
authetication.  For the purposes of this API, the "origin" is the hostname
of the machine this library is running on.
"""

import hashlib
import socket
import time

from pyu2f import errors
from pyu2f import hardware
from pyu2f import hidtransport
from pyu2f import model

def GetLocalU2FInterface(origin=socket.gethostname()):
  """Obtains a U2FInterface for the first valid local U2FHID device found."""
  hid_transports = hidtransport.DiscoverLocalHIDU2FDevices()
  for t in hid_transports:
    try:
      return U2FInterface(security_key=hardware.SecurityKey(transport=t),
                          origin=origin)
    except errors.UnsupportedVersionException:
      # Skip over devices that don't speak the proper version of the protocol.
      pass

  # Unable to find a device
  raise errors.NoDeviceFoundError()

class U2FInterface(object):
  """High level U2F interface.

  Implements a high level interface in the spirit of the FIDO U2F
  javascript API high level interface.  It supports registration
  and authentication (signing).

  IMPORTANT NOTE: This class does NOT validate the app id against the
  origin.  In particular, any user can assert any app id all the way to
  the device.  The security model of a python library is such that doing
  so would not provide significant benfit as it could be bypassed by the
  caller talking to a lower level of the API.  In fact, so could the origin
  itself.  The origin is still set to a plausible value (the hostname) by
  this library.

  TODO(gdasher): Figure out a plan on how to address this gap/document the
  consequences of this more clearly.
  """

  def __init__(self, security_key, origin=socket.gethostname()):
    self.origin = origin
    self.security_key = security_key

    if self.security_key.CmdVersion() != b'U2F_V2':
      raise errors.UnsupportedVersionException()

  def Register(self, app_id, challenge, registered_keys):
    """Registers app_id with the security key.

    Executes the U2F registration flow with the security key.

    Args:
      app_id: The app_id to register the security key against.
      challenge: Server challenge passed to the security key.
      registered_keys: List of keys already registered for this app_id+user.

    Returns:
      RegisterResponse with key_handle and attestation information in it (
        encoded in FIDO U2F binary format within registration_data field).

    Raises:
      U2FError: There was some kind of problem with registration (e.g.
        the device was already registered or there was a timeout waiting
        for the test of user presence).
    """
    client_data = model.ClientData(model.ClientData.TYP_REGISTRATION, challenge,
                                   self.origin)
    challenge_param = self.InternalSHA256(client_data.GetJson())
    app_param = self.InternalSHA256(app_id)

    for key in registered_keys:
      try:
        # skip non U2F_V2 keys
        if key.version != u'U2F_V2':
          continue
        resp = self.security_key.CmdAuthenticate(challenge_param, app_param,
                                                 key.key_handle, True)
        # check_only mode CmdAuthenticate should always raise some
        # exception
        raise errors.HardwareError('Should Never Happen')

      except errors.TUPRequiredError:
        # This indicates key was valid.  Thus, no need to register
        raise errors.U2FError(errors.U2FError.DEVICE_INELIGIBLE)
      except errors.InvalidKeyHandleError as e:
        # This is the case of a key for a different token, so we just ignore it.
        pass
      except errors.HardwareError as e:
        raise errors.U2FError(errors.U2FError.BAD_REQUEST, e)

    # Now register the new key
    for _ in range(30):
      try:
        resp = self.security_key.CmdRegister(challenge_param, app_param)
        return model.RegisterResponse(resp, client_data)
      except errors.TUPRequiredError as e:
        self.security_key.CmdWink()
        time.sleep(0.5)
      except errors.HardwareError as e:
        raise errors.U2FError(errors.U2FError.BAD_REQUEST, e)

    raise errors.U2FError(errors.U2FError.TIMEOUT)

  def Authenticate(self, app_id, challenge, registered_keys):
    """Authenticates app_id with the security key.

    Executes the U2F authentication/signature flow with the security key.

    Args:
      app_id: The app_id to register the security key against.
      challenge: Server challenge passed to the security key as a bytes object.
      registered_keys: List of keys already registered for this app_id+user.

    Returns:
      SignResponse with client_data, key_handle, and signature_data.  The client
      data is an object, while the signature_data is encoded in FIDO U2F binary
      format.

    Raises:
      U2FError: There was some kind of problem with authentication (e.g.
        there was a timeout while waiting for the test of user presence.)
    """
    client_data = model.ClientData(model.ClientData.TYP_AUTHENTICATION,
                                   challenge, self.origin)
    app_param = self.InternalSHA256(app_id)
    challenge_param = self.InternalSHA256(client_data.GetJson())
    num_invalid_keys = 0
    for key in registered_keys:
      try:
        if key.version != u'U2F_V2':
          continue
        for _ in range(30):
          try:
            resp = self.security_key.CmdAuthenticate(challenge_param, app_param,
                                                     key.key_handle)
            return model.SignResponse(key.key_handle, resp, client_data)
          except errors.TUPRequiredError:
            self.security_key.CmdWink()
            time.sleep(0.5)
      except errors.InvalidKeyHandleError:
        num_invalid_keys += 1
        continue
      except errors.HardwareError as e:
        raise errors.U2FError(errors.U2FError.BAD_REQUEST, e)

    if num_invalid_keys == len(registered_keys):
      # In this case, all provided keys were invalid.
      raise errors.U2FError(errors.U2FError.DEVICE_INELIGIBLE)

    # In this case, the TUP was not pressed.
    raise errors.U2FError(errors.U2FError.TIMEOUT)

  def InternalSHA256(self, string):
    md = hashlib.sha256()
    md.update(string.encode())
    return md.digest()


text:
module DPL
  class Provider
    class CloudFoundry < Provider

      def initial_go_tools_install
        context.shell 'wget http://go-cli.s3-website-us-east-1.amazonaws.com/releases/latest/cf-linux-amd64.tgz -qO cf-linux-amd64.tgz && tar -zxvf cf-linux-amd64.tgz && rm cf-linux-amd64.tgz'
      end

      def check_auth
        initial_go_tools_install
        context.shell "./cf api #{option(:api)} #{'--skip-ssl-validation' if options[:skip_ssl_validation]}"
        context.shell "./cf login --u #{option(:username)} --p #{option(:password)} --o #{option(:organization)} --s #{option(:space)}"
      end

      def check_app
        if options[:manifest]
          error 'Application must have a manifest.yml for unattended deployment' unless File.exists? options[:manifest]
        end
      end

      def needs_key?
        false
      end

      def push_app
        context.shell "./cf push#{manifest}"
        context.shell "./cf logout"
      end

      def cleanup
      end

      def uncleanup
      end

      def manifest
        options[:manifest].nil? ? "" : " -f #{options[:manifest]}"
      end
    end
  end
end


text:
package gov.nih.nci.cabig.ctms.suite.authorization;

import junit.framework.TestCase;

/**
 * @author Rhett Sutphin
 */
public class ScopeDescriptionTest extends TestCase {
    public void testCreatedAllScopeIsAll() throws Exception {
        assertTrue("Should be all scope",
            ScopeDescription.createForAll(ScopeType.SITE).isAll());
    }

    public void testCreatedSingleScopeIsNotAll() throws Exception {
        assertFalse("Should not be all scope",
            ScopeDescription.createForOne(ScopeType.SITE, "B").isAll());
    }

    public void testCreatedSingleScopeReturnsTheCorrectIdentifier() throws Exception {
        assertEquals("Wrong ident", "T",
            ScopeDescription.createForOne(ScopeType.STUDY, "T").getIdentifier());
    }

    public void testCreateForSingleDoesNotAllowNullIdentifier() throws Exception {
        try {
            ScopeDescription.createForOne(ScopeType.STUDY, null);
            fail("Exception not thrown");
        } catch (IllegalArgumentException iae) {
            assertEquals("An identifier is required", iae.getMessage());
        }
    }

    public void testCreateScopeFromSingleSiteProtectionElementName() throws Exception {
        ScopeDescription created = ScopeDescription.createFromCsmName("HealthcareSite.NCI014");
        assertEquals("Wrong ident", "NCI014", created.getIdentifier());
        assertEquals("Wrong scope", ScopeType.SITE, created.getScope());
    }

    public void testCreateScopeFromAllSiteProtectionElementName() throws Exception {
        ScopeDescription created = ScopeDescription.createFromCsmName("HealthcareSite");
        assertEquals("Wrong scope", ScopeType.SITE, created.getScope());
        assertTrue("Should be for all", created.isAll());
    }

    public void testCreateScopeFromSingleStudyProtectionElement() throws Exception {
        ScopeDescription created = ScopeDescription.createFromCsmName("Study.T");
        assertEquals("Wrong ident", "T", created.getIdentifier());
        assertEquals("Wrong scope", ScopeType.STUDY, created.getScope());
    }

    public void testCreateScopeFromSingleStudyProtectionElementNameThatContainsDots() throws Exception {
        ScopeDescription created = ScopeDescription.createFromCsmName("Study.T.U.V");
        assertEquals("Wrong ident", "T.U.V", created.getIdentifier());
        assertEquals("Wrong scope", ScopeType.STUDY, created.getScope());
    }

    public void testCreateScopeFromAllStudyProtectionElement() throws Exception {
        ScopeDescription created = ScopeDescription.createFromCsmName("Study");
        assertEquals("Wrong scope", ScopeType.STUDY, created.getScope());
        assertTrue("Should be for all", created.isAll());
    }

    public void testCreateScopeForUnparsableCsmNameReturnsNull() throws Exception {
        assertNull(ScopeDescription.createFromCsmName("Foo"));
    }

    public void testGetCsmNameForAllSite() throws Exception {
        assertEquals("HealthcareSite", ScopeDescription.createForAll(ScopeType.SITE).getCsmName());
    }

    public void testGetCsmNameForAllStudy() throws Exception {
        assertEquals("Study", ScopeDescription.createForAll(ScopeType.STUDY).getCsmName());
    }

    public void testGetCsmNameForOneSite() throws Exception {
        assertEquals("HealthcareSite.B",
            ScopeDescription.createForOne(ScopeType.SITE, "B").getCsmName());
    }

    public void testGetCsmNameForOneStudy() throws Exception {
        assertEquals("Study.B", ScopeDescription.createForOne(ScopeType.STUDY, "B").getCsmName());
    }

    public void testGetCsmNameForOneStudyWithDots() throws Exception {
        assertEquals("Study.B.C.D",
            ScopeDescription.createForOne(ScopeType.STUDY, "B.C.D").getCsmName());
    }

    public void testAccessingIdentForAllScopeFails() throws Exception {
        try {
            ScopeDescription.createForAll(ScopeType.STUDY).getIdentifier();
            fail("Exception not thrown");
        } catch (SuiteAuthorizationAccessException e) {
            assertEquals(
                "This description indicates access to every study.  You can't get an identifier from it.",
                e.getMessage());
        }
    }

    public void testEqualsForSameScopeAndOneEquivalentInstance() throws Exception {
        assertEquals(
            ScopeDescription.createForOne(ScopeType.SITE, "A"),
            ScopeDescription.createForOne(ScopeType.SITE, "A")
        );
    }

    public void testEqualsForAllInSameScope() throws Exception {
        assertEquals(
            ScopeDescription.createForAll(ScopeType.SITE),
            ScopeDescription.createForAll(ScopeType.SITE)
        );
    }

    public void testNotEqualsForAllWithDifferentScopes() throws Exception {
        assertFalse(
            ScopeDescription.createForAll(ScopeType.SITE).equals(
                ScopeDescription.createForAll(ScopeType.STUDY))
        );
    }

    public void testNotEqualsForOneWithDifferentScopes() throws Exception {
        assertFalse(
            ScopeDescription.createForOne(ScopeType.SITE,  "A").equals(
                ScopeDescription.createForOne(ScopeType.STUDY, "A"))
        );
    }

    public void testNotEqualsForOneWithDifferentIdents() throws Exception {
        assertFalse(
            ScopeDescription.createForOne(ScopeType.STUDY, "A").equals(
                ScopeDescription.createForOne(ScopeType.STUDY, "B"))
        );
    }
}


text:
using System;
using System.Collections;
using System.Linq;
using System.Text;

namespace EntitySystem.Utility.Bits
{
	public struct BitVector16 : IBitArray, IEquatable<BitVector16>
	{
		ushort _bits;

		public int Length => 16;

		public bool this[int index] {
			get {
				if ((index < 0) || (index >= Length))
					throw new ArgumentOutOfRangeException();
				return (((_bits >> index) & 1) != 0);
			}
			set {
				if ((index < 0) || (index >= Length))
					throw new ArgumentOutOfRangeException();
				if (value) _bits |= (ushort)(1 << index);
				else _bits &= (ushort)~(1 << index);
			}
		}

		public BitVector16(ushort bits = 0) { _bits = bits; }
		public BitVector16(uint bits) : this(unchecked((byte)bits)) {  }

		public BitVector16(BitVector16 bits) : this(bits._bits) {  }
		public BitVector16(IBitArray bits) : this(bits.GetUInt(0)) {  }

		uint IBitArray.GetUInt(int index) {
			if (index == 0) return _bits;
			throw new ArgumentOutOfRangeException("index");
		}

		public bool Equals(BitVector16 other) => (other._bits == _bits);

		public override bool Equals(object obj) =>
			((obj is BitVector16) && Equals((BitVector16)obj));

		public override int GetHashCode() => _bits.GetHashCode();

		public override string ToString() => new StringBuilder(Length + 2)
			.Append('[')
			.AppendAll(this.Select(b => (b ? '1' : '0')))
			.Append(']')
			.ToString();

		public System.Collections.Generic.IEnumerator<bool> GetEnumerator()
		{
			var bits = _bits;
			for (var i = 0; i < Length; i++, bits >>= 1)
				yield return ((bits & 1) != 0);
		}
		IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

		public static BitVector16 operator ~(BitVector16 bits) =>
			new BitVector16((ushort)~bits._bits);

		public static BitVector16 operator &(BitVector16 left, BitVector16 right) =>
			new BitVector16((byte)(left._bits & right._bits));

		public static BitVector16 operator |(BitVector16 left, BitVector16 right) =>
			new BitVector16((byte)(left._bits | right._bits));

		public static BitVector16 operator ^(BitVector16 left, BitVector16 right) =>
			new BitVector16((byte)(left._bits ^ right._bits));

		public static BitVector16 operator >>(BitVector16 bits, int shift) =>
			new BitVector16((byte)(bits._bits >> shift));

		public static BitVector16 operator <<(BitVector16 bits, int shift) =>
			new BitVector16((byte)(bits._bits << shift));

		public static bool operator ==(BitVector16 left, BitVector16 right) =>
			(left._bits == right._bits);

		public static bool operator !=(BitVector16 left, BitVector16 right) =>
			(left._bits != right._bits);
	}
}


text:
'use strict';

const fs = require('fs');

const test = require('ava');
const mockFs = require('mock-fs');

const writeArtifacts = require('../../../lib');

test.afterEach(() => mockFs.restore());

test('should include files', async t => {
    mockFs({
        'source-dir': {
            'file-1.txt': 'Hi!',
            'file-2.txt': 'Hello!'
        }
    });

    await writeArtifacts({ name: 'artifact-dir', patterns: ['source-dir/**'] });

    const files = fs.readdirSync('artifact-dir/source-dir');

    t.deepEqual(files, ['file-1.txt', 'file-2.txt']);
});

test('should exclude files', async t => {
    mockFs({
        'source-dir': {
            'file-1.txt': 'Hi!',
            'file-2.txt': 'Hello!'
        }
    });

    await writeArtifacts({ name: 'artifact-dir', patterns: ['source-dir/**', '!source-dir/file-2.txt'] });

    const files = fs.readdirSync('artifact-dir/source-dir');

    t.deepEqual(files, ['file-1.txt']);
});

test('should override negative pattern', async t => {
    mockFs({
        'source-dir': {
            'file-1.txt': 'Hi!',
            'file-2.txt': 'Hello!'
        }
    });

    await writeArtifacts({
        name: 'artifact-dir',
        patterns: [
            'source-dir/**',
            '!source-dir/file-2.txt',
            'source-dir/file-2.txt'
        ]
    });

    const files = fs.readdirSync('artifact-dir/source-dir');

    t.deepEqual(files, ['file-1.txt', 'file-2.txt']);
});