text:
package org.jetbrains.plugins.scala.lang.lexer;

import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.plugins.scala.lang.scaladoc.lexer.ScalaDocTokenType;
import org.jetbrains.plugins.scala.lang.scaladoc.parser.ScalaDocElementTypes;

import static com.intellij.psi.xml.XmlTokenType.*;
import static org.jetbrains.plugins.scala.lang.parser.ScalaElementTypes.*;

/**
 * @author ilyas
 *         Date: 24.09.2006
 */
public interface ScalaTokenTypes {

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////// Wrong token //////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  final IElementType tWRONG = new ScalaElementType("wrong token");

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////// White spaces in line /////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  final IElementType tWHITE_SPACE_IN_LINE = new ScalaElementType("white space in line");

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////// Stub /////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  final IElementType tSTUB = new ScalaElementType("stub");

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////// Comments /////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  final IElementType tDOC_COMMENT = new ScalaElementType("DocComment");
  final IElementType tLINE_COMMENT = new ScalaElementType("comment");
  final IElementType tBLOCK_COMMENT = new ScalaElementType("BlockComment");
  final IElementType tSH_COMMENT = new ScalaElementType("ShellComment");

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////// Strings & chars //////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  final IElementType tSTRING = new ScalaElementType("string content");
  final IElementType tMULTILINE_STRING = new ScalaElementType("multiline string");
  final IElementType tINTERPOLATED_STRING = new ScalaElementType("interpolated string");
  final IElementType tINTERPOLATED_MULTILINE_STRING = new ScalaElementType("interpolatedmultiline string");
  final IElementType tINTERPOLATED_STRING_ID = new ScalaElementType("interpolated string id");
  final IElementType tINTERPOLATED_STRING_INJECTION = new ScalaElementType("interpolated string injection");
  final IElementType tINTERPOLATED_STRING_END = new ScalaElementType("interpolated string end");
  final IElementType tINTERPOLATED_STRING_ESCAPE = new ScalaElementType("interpolated string escape");
  final IElementType tWRONG_STRING = new ScalaElementType("wrong string content");

  final IElementType tCHAR = new ScalaElementType("Character");
  final IElementType tSYMBOL = new ScalaElementType("Symbol");

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////// integer and float literals ///////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  final IElementType tINTEGER = new ScalaElementType("integer");
  final IElementType tFLOAT = new ScalaElementType("float");

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////// Operators ////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  final IElementType tEQUAL = new ScalaElementType("==");
  final IElementType tNOTEQUAL = new ScalaElementType("!=");
  final IElementType tLESS = new ScalaElementType("<");
  final IElementType tLESSOREQUAL = new ScalaElementType("<=");
  final IElementType tGREATER = new ScalaElementType(">");
  final IElementType tGREATEROREQUAL = new ScalaElementType(">=");

  final IElementType tTILDA = new ScalaElementType("~");
  final IElementType tNOT = new ScalaElementType("!");
  final IElementType tSTAR = new ScalaElementType("*");
  final IElementType tDIV = new ScalaElementType("/");

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////// Braces ///////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  final IElementType tLSQBRACKET = new ScalaElementType("[");
  final IElementType tRSQBRACKET = new ScalaElementType("]");
  final IElementType tLBRACE = new ScalaElementType("{");
  final IElementType tRBRACE = new ScalaElementType("}");
  final IElementType tLPARENTHESIS = new ScalaElementType("(");
  final IElementType tRPARENTHESIS = new ScalaElementType(")");

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////// keywords /////////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  final IElementType kABSTRACT = new ScalaElementType("abstract");
  final IElementType kCASE = new ScalaElementType("case");
  final IElementType kCATCH = new ScalaElementType("catch");
  final IElementType kCLASS = new ScalaElementType("class");
  final IElementType kDEF = new ScalaElementType("def");
  final IElementType kDO = new ScalaElementType("do");
  final IElementType kELSE = new ScalaElementType("else");
  final IElementType kEXTENDS = new ScalaElementType("extends");
  final IElementType kFALSE = new ScalaElementType("false");
  final IElementType kFINAL = new ScalaElementType("final");
  final IElementType kFINALLY = new ScalaElementType("finally");
  final IElementType kFOR = new ScalaElementType("for");
  final IElementType kFOR_SOME = new ScalaElementType("forSome");
  final IElementType kIF = new ScalaElementType("if");
  final IElementType kIMPLICIT = new ScalaElementType("implicit");
  final IElementType kIMPORT = new ScalaElementType("import");
  final IElementType kLAZY = new ScalaElementType("lazy");
  final IElementType kMATCH = new ScalaElementType("match");
  final IElementType kNEW = new ScalaElementType("new");
  final IElementType kNULL = new ScalaElementType("null");
  final IElementType kOBJECT = new ScalaElementType("object");
  final IElementType kOVERRIDE = new ScalaElementType("override");
  final IElementType kPACKAGE = new ScalaElementType("package");
  final IElementType kPRIVATE = new ScalaElementType("private");
  final IElementType kPROTECTED = new ScalaElementType("protected");
  final IElementType kRETURN = new ScalaElementType("return");
  final IElementType kSEALED = new ScalaElementType("sealed");
  final IElementType kSUPER = new ScalaElementType("super");
  final IElementType kTHIS = new ScalaElementType("this");
  final IElementType kTHROW = new ScalaElementType("throw");
  final IElementType kTRAIT = new ScalaElementType("trait");
  final IElementType kTRY = new ScalaElementType("try");
  final IElementType kTRUE = new ScalaElementType("true");
  final IElementType kTYPE = new ScalaElementType("type");
  final IElementType kVAL = new ScalaElementType("val");
  final IElementType kVAR = new ScalaElementType("var");
  final IElementType kWHILE = new ScalaElementType("while");
  final IElementType kWITH = new ScalaElementType("with");
  final IElementType kYIELD = new ScalaElementType("yield");
  final IElementType kMACRO = new ScalaElementType("macro");
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////// variables and constants //////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  final IElementType tIDENTIFIER = new ScalaElementType("identifier");

  ////////////////////////// xml tag /////////////////////////////////////////////////////////////////////////////////////
  final IElementType tOPENXMLTAG = new ScalaElementType("opened xml tag");
  final IElementType tCLOSEXMLTAG = new ScalaElementType("closed xml tag");
  final IElementType tBADCLOSEXMLTAG = new ScalaElementType("closing tag without opening");
  final IElementType tXMLTAGPART = new ScalaElementType("tag part");
  final IElementType tBEGINSCALAEXPR = new ScalaElementType("begin of scala expression");
  final IElementType tENDSCALAEXPR = new ScalaElementType("end of scala expression");
  final IElementType tXML_COMMENT_START = new ScalaElementType("Xml Comment Start");
  final IElementType tXML_COMMENT_END = new ScalaElementType("Xml Comment End");

  final IElementType tDOT = new ScalaElementType(".");
  final IElementType tCOMMA = new ScalaElementType(",");
  final IElementType tSEMICOLON = new ScalaElementType(";");

  final IElementType tUNDER = new ScalaElementType("_");
  final IElementType tCOLON = new ScalaElementType(":");
  final IElementType tASSIGN = new ScalaElementType("=");
  final IElementType tAND = new ScalaElementType("&");
  final IElementType tOR = new ScalaElementType("|");
  final IElementType tFUNTYPE = new ScalaElementType("=>");
  final IElementType tFUNTYPE_ASCII = new ScalaElementType(Character.toString('\u21D2'));
  final IElementType tCHOOSE = new ScalaElementType("<-");
  final IElementType tLOWER_BOUND = new ScalaElementType(">:");
  final IElementType tUPPER_BOUND = new ScalaElementType("<:");
  final IElementType tVIEW = new ScalaElementType("<%");
  final IElementType tINNER_CLASS = new ScalaElementType("#");
  final IElementType tAT = new ScalaElementType("@");
  final IElementType tQUESTION = new ScalaElementType("?");

  public static TokenSet WHITES_SPACES_FOR_FORMATTER_TOKEN_SET = TokenSet.create(
      tWHITE_SPACE_IN_LINE,
      ScalaDocTokenType.DOC_WHITESPACE,
      XML_REAL_WHITE_SPACE,
      XML_WHITE_SPACE,
      TAG_WHITE_SPACE
  );

  public static TokenSet WHITES_SPACES_TOKEN_SET = TokenSet.create(
          tWHITE_SPACE_IN_LINE,
          XML_REAL_WHITE_SPACE,
          XML_WHITE_SPACE,
          TAG_WHITE_SPACE
  );

  TokenSet COMMENTS_TOKEN_SET = TokenSet.create(
          tLINE_COMMENT,
          tBLOCK_COMMENT,
          tSH_COMMENT,
          ScalaDocElementTypes.SCALA_DOC_COMMENT
  );

  TokenSet WHITES_SPACES_AND_COMMENTS_TOKEN_SET = TokenSet.orSet(COMMENTS_TOKEN_SET, WHITES_SPACES_TOKEN_SET);

  public static TokenSet KEYWORDS = TokenSet.create(
          kABSTRACT,
          kCASE,
          kCATCH,
          kCLASS,
          kDEF,
          kDO,
          kELSE,
          kEXTENDS,
          kFALSE,
          kFINAL,
          kFINALLY,
          kFOR,
          kFOR_SOME,
          kIF,
          kIMPLICIT,
          kIMPORT,
          kLAZY,
          kMATCH,
          kNEW,
          kNULL,
          kOBJECT,
          kOVERRIDE,
          kPACKAGE,
          kPRIVATE,
          kPROTECTED,
          kRETURN,
          kSEALED,
          kSUPER,
          kTHIS,
          kTHROW,
          kTRAIT,
          kTRY,
          kTRUE,
          kTYPE,
          kVAL,
          kVAR,
          kWHILE,
          kWITH,
          kYIELD,
          kMACRO
  );

  TokenSet IDENTIFIER_TOKEN_SET = TokenSet.create(tIDENTIFIER);
  TokenSet STRING_LITERAL_TOKEN_SET = TokenSet.create(tSTRING, tWRONG_STRING, tMULTILINE_STRING, tINTERPOLATED_MULTILINE_STRING, tINTERPOLATED_STRING);

  TokenSet XML_ELEMENTS = TokenSet.create(XML_PI(), XML_ATTRIBUTE(), XML_CD_SECT(),
      XML_COMMENT(), XML_ELEMENT(), XML_EMPTY_TAG(), XML_END_TAG(), XML_EXPR(), XML_PATTERN(),
      XML_START_TAG(), ScalaTokenTypesEx.SCALA_IN_XML_INJECTION_START, ScalaTokenTypesEx.SCALA_IN_XML_INJECTION_END,
      XML_EQ, XML_ATTRIBUTE_VALUE_START_DELIMITER, XML_NAME, XML_TAG_END, XML_CDATA_END, XML_PI_END,
      XML_EMPTY_ELEMENT_END, XML_START_TAG_START, XML_END_TAG_START, XML_CDATA_START, XML_PI_START,
      XML_DATA_CHARACTERS, XML_COMMENT_CHARACTERS);
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "contents".
 *
 * @property integer $id
 * @property string $title
 * @property string $abstract
 * @property string $content
 * @property integer $status
 * @property string $tags
 * @property integer $categoryId
 * @property integer $thumbnail
 * @property string $publishTime
 * @property string $createTime
 * @property integer $createBy
 * @property string $lastUpdateTime
 * @property integer $lastUpdateBy
 * @property integer $theme
 * @property string $postTitle
 * @property string $credit
 * @property string $viewCount
 * @property string $web
 * @property string $expireTime
 * @property string $remark
 */
class Contents extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'contents';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'required'],
            [['content'], 'string'],
            [['status', 'categoryId', 'thumbnail', 'createBy', 'lastUpdateBy', 'theme', 'viewCount'], 'integer'],
            [['publishTime', 'createTime', 'lastUpdateTime', 'expireTime'], 'safe'],
            [['title', 'postTitle', 'credit'], 'string', 'max' => 300],
            [['abstract'], 'string', 'max' => 400],
            [['tags'], 'string', 'max' => 250],
            [['web'], 'string', 'max' => 10],
            [['remark'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'abstract' => 'Abstract',
            'content' => 'Content',
            'status' => 'Status',
            'tags' => 'Tags',
            'categoryId' => 'Category ID',
            'thumbnail' => 'Thumbnail',
            'publishTime' => 'Publish Time',
            'createTime' => 'Create Time',
            'createBy' => 'Create By',
            'lastUpdateTime' => 'Last Update Time',
            'lastUpdateBy' => 'Last Update By',
            'theme' => 'Theme',
            'postTitle' => 'Post Title',
            'credit' => 'Credit',
            'viewCount' => 'View Count',
            'web' => 'Web',
            'expireTime' => 'Expire Time',
            'remark' => 'Remark',
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: dragosc
 * Date: 8/31/14
 * Time: 12:23 PM
 */

namespace AthemTest\Code\Cache;

use Athem\Code\CacheAdapter;

class DoctrineCache extends CacheAdapter
{
    protected $cache = null;

    protected $item = null;

    public function __construct($item)
    {
        $this->item = $item;
        $this->cache = new \Doctrine\Common\Cache\ArrayCache();

    }

    /**
     * @return string
     */
    public function read()
    {
        return $this->cache->fetch($this->item)[0];
    }

    /**
     * @param string $data
     */
    public function write($data)
    {
        $this->cache->save($this->item, array($data));
    }

    /**
     * @return boolean
     */
    public function exists()
    {
        return $this->cache->contains($this->item);
    }
}


text:
<!DOCTYPE html>

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

  <title>Recipes</title>
  <meta name="description" content="a personal blog for all of the little things">

  <link rel="stylesheet" href="http://localhost:4000/css/font-awesome.min.css">
  <link rel="stylesheet" href="http://localhost:4000/css/main.css">

  <link rel="canonical" href="http://localhost:4000/recipes/">
  <link rel="alternate" type="application/rss+xml" title="Ellis Enchanted" href="http://localhost:4000 /feed.xml " />

  <link rel="shortcut icon" href="http://localhost:4000/favicon.ico">

  <link rel="shortcut icon" href="http://localhost:4000/favicon.png">

  <meta name="p:domain_verify" content="cc5801c3aa4fab77c2360185c9f1fd65"/>

<title>Recipes - Ellis Enchanted</title>
<meta property="og:title" content="Recipes" />
<meta name="description" content="a personal blog for all of the little things" />
<meta property="og:description" content="a personal blog for all of the little things" />
<link rel="canonical" href="http://localhost:4000/recipes/" />
<meta property="og:url" content="http://localhost:4000/recipes/" />
<meta property="og:site_name" content="Ellis Enchanted" />

        About Lauren
        |

        Archive
        |

        Categories
        |

        Projects
        |

        Recipes
        |

        Tags
        |

        Travel
        |

Recipes

				2 JAN 2017

			  •

				recipe

			  Guide to the perfect cheeseboard

One of our favorite things to do is have wine and a cheeseboard as a dinner alternative from time to time.
One of the local restaurants in Worcester does a beautiful spread that we love to recreate.

				20 JUN 2016

			  •

				recipe

			  Hello, Hello Fresh!

HELLLLLOOOOO! I am so excited to write about our first experience with Hello Fresh!

Today my box arrived and I was extremely impressed!

				9 JUN 2016

			  •

				food

				/

				recipe

			  Bourbon Bread Pudding

While briefly living in Raleigh, North Carolina, my husband and I had a few fantastic bread puddings. I know bread pudding isn't up
everyone's alley - but it is DEFINITELY up our alley. While having brunch at a french bistro we
had an amazing blue crab bread pudding. Unfortunately, they change their menu frequently and I never saw it again. Le sigh.
The other one that resonated with us was a good ol' southern bourbon bread pudding from a local microbrew in Durham near the UNC campus.
We've dreamt about both since, but I have only recreated the latter. Here we go!

|

        About Lauren
        |

        Archive
        |

        Categories
        |

        Projects
        |

        Recipes
        |

        Tags
        |

        Travel
        |

  © Ellis Enchanted 2017.


text:
<?php

namespace Propel\Bundle\PropelBundle\Form\Type;

use Propel\Bundle\PropelBundle\Form\EventListener\TranslationCollectionFormListener;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * form type for i18n-columns in propel.
 *
 * @author Patrick Kaufmann
 */
class TranslationCollectionType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (!isset($options['options']['data_class']) || null === $options['options']['data_class']) {
            throw new MissingOptionsException('data_class must be set');
        }
        if (!isset($options['options']['columns']) || null === $options['options']['columns']) {
            throw new MissingOptionsException('columns must be set');
        }

        $listener = new TranslationCollectionFormListener($options['languages'], $options['options']['data_class']);
        $builder->addEventSubscriber($listener);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'collection';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'propel1_translation_collection';
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setRequired(array(
            'languages',
        ));

        $resolver->setDefaults(array(
            'type' => 'propel1_translation',
            'allow_add' => false,
            'allow_delete' => false,
            'options' => array(
                'data_class' => null,
                'columns' => null,
            ),
        ));
    }
}


text:
<!doctype html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<title>reveal.js</title>

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/nabira.css">

		<link rel="stylesheet" href="lib/css/zenburn.css">

What is Linux?

Simple, Powerful and Opensource

Created by Jhalak Nabira

Student, 6th D

BGS NPS, Bangalore, India

Agenda

Why Systems automation?

What is Ansible?

Architecture

Use cases of Ansible

Customers

Questions and Answers

Once upon a time

 Datacenters were simple

 One server, one OS, one service

we had shell scripts

and ssh loops

Then it all got complicated

Today's IT brings complex deployments and complex challenges. You've got to deal with clustered applications, multiple datacenters, public, private and hybrid clouds and applications with complex dependencies. You need a tool that can orchestrate your complex tasks simply. You need Ansible.

This is what we all need

Install, Configure Apache through playbook

Install, Configure Apache Ad-Hoc

Install, Configure Apache Ad-Hoc

Welcome to Ansible

Zero to Prod in minutes !!!

Automation should not require any programming experience

It must be EASY

Automation for Everyone.

It works with

Unix

Linux

Windows

Docker Containers

Virtualization platforms

Network routers,switches,Firewalls,etc

Openstack Cloud,AWS, Azure, Google,Rackspace etc

 Most of the stuff you need is already built-in

Use Cases for Ansible

Provisioning

Configuration Management

Application deployment

Continuous Integration

 Orchestration

Security and Compliance

				### Security is hard !!!

				Application Security
				Network Security
				Penetration testing
				Forensics
				Fraud Detection and prevention
				Governance, Risk, Complaince

				Fix empty root password
				Change Password every 60 days
				Shell Shock vernerability Check
				Stop vernerable services
				Change kernel parameters and reboot
				Collect log files in central location
				Remove venerable packages and replace them with secure ones
				Keep check on directory for change

MySQL DB provisioning example

What all things you do after your Linux VM is provisioned

 Change OS parameters to suit DB

 Install database

 Change configuation file for DB

 Enable and start DB

 Setup Backup script for DB

 Setup cronjob for scheduling backup

 Get the list of users

 Get the list of databases

 Remove test DB

 Add new DB

MySQL DB provisioning example

 11. Setup new users

 12. Setup permissions for users on DB

 13. Disable remote login for DB

 14. Setup root password for DB

 15. Setup replication for DB

 16. Check master and slave status for DB

 17. Start replication

Automation for everyone

 Deploy Apps, manage systems, crush complexity

Ansible helps you build a strong foundation for DevOps.

Architecture

Application Deployment

Configuration Management

Continuous Integration

CI/CD

Integration with Windows

Gather facts on Windows hosts

Install and uninstall MSIs

Enable and disable Windows Features

Start, stop, and manage Windows services

Create and manage local users and groups

Manage Windows packages via the Chocolatey package manager

Manage and install Windows updates

Fetch files from remote sites

Push and execute any PowerShell scripts you write

Integrations

Integrations

Integrations

Integrations

Integrations

Integrations

Integrations

Customers

Competetion

Saltstack

Chef

Puppet

Microsoft SCCM

BMC Control M

CA Client Automation

Shell Scripts

 BMC Control M

 It's used for batch automation

 It can work with Mainframes, Unix, Linux, Windows, OpenVMS

 It's in leaders quadrant

 Can't work as Devops tool

 Proprietary

 Expensive

 Requires Agent

 CA Client Automation

 It's used for Client devices automation

 It can work with VDI solutions

 It gives you software inventory capabilities for desktops

 Mainly designed for desktop management

 Can't work as Devops tool

 Proprietary

 Expensive

Ansible Tower

https://ansible.com/tower

Centralize  control with a visual dashboard

Role-based access control

Job scheduling

Graphical inventory management.

Audit trails

Association of playbooks with particular  Job

Notifications of job completion

Ansible Tower 3

You've freed yourself

Now go & free others

Thank you.


text:
from itertools import product, repeat
import os
import sys
import pickle
from operator import itemgetter
from os.path import split,splitext
import glob

if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser(description="Create Regression jobs")
    parser.add_argument('jobf',type=str)
    parser.add_argument('--startline',type=int,default=1)
    parser.add_argument('--endline',type=int,default=None)
    parser.add_argument('--outf_idx',type=int,default=None, help="Out field idx")
    args = parser.parse_args()

# Read jobfile list
    with open(args.jobf) as fin:
        old_jobs = [line.strip() for line in fin]

    start = args.startline
    end = len(old_jobs) if not args.endline else args.endline

    old_jobs = [j for (idx,j) in enumerate(old_jobs) if idx+1 in range(start,end+1)]

    completed_jobs = []
    for old_job in old_jobs:
        outf = old_job.strip("()").split(",")[args.outf_idx].strip("'")
        if os.path.exists(outf):
            completed_jobs.append(old_job)

    missing_jobs = [j for j in old_jobs if j not in completed_jobs]
    for j in missing_jobs:
        print >>sys.stdout, j


text:
class Admin::SuppliersController < Admin::BaseController
  resource_controller

private
  def collection
    base_scope = end_of_association_chain

    @search = base_scope.searchlogic(params[:search])
    @search.order ||= "ascend_by_name"

    @collection = @search.paginate(:per_page  => 20,
                                   :page      => params[:page])

  end

end


text:
require 'sinatra'
require 'json'
require 'faraday'
require 'rack/parser'
require 'rack/ssl-enforcer'

# Required
set :project_name, ENV['PROJECT_NAME'] || raise("no PROJECT_NAME set")
set :branch_name, ENV['BRANCH_NAME'] || raise("no BRANCH_NAME set")
set :secret, ENV['SECRET'] || raise("no SECRET set")
set :session_secret, ENV['SESSION_SECRET'] || raise("no SESSION_SECRET set")
set :buildkite_access_token, ENV['BUILDKITE_ACCESS_TOKEN'] || raise("no BUILDKITE_ACCESS_TOKEN set")

# Optional
set :buildkite_api_host, ENV['BUILDKITE_API_HOST'] || 'https://api.buildkite.com'

# SSL redirecter - must be the first piece of middleware
use Rack::SslEnforcer unless development?

# JSON request body parsing
use Rack::Parser

# Basic auth
use(Rack::Auth::Basic, "Restricted Area") {|u, p| u == settings.secret and p == ''}

# CSRF protection
enable :sessions
set :protection, use: [:authenticity_token]

# State
unblockable_job = nil

helpers do
  def buildkite_api
    Faraday.new(url: settings.buildkite_api_host) do |faraday|
      faraday.authorization :Bearer, settings.buildkite_access_token
      faraday.request :url_encoded
      # faraday.response :logger
      faraday.adapter Faraday.default_adapter
      faraday.use Faraday::Response::RaiseError
    end
  end
end

post "/" do
  halt(401, 'Looks like you forgot to add ?secret=the-secret') if params[:secret].nil?
  halt(401, 'Secret is incorrect') if params[:secret] != settings.secret

  event = JSON.parse(request.body.read)
  puts event.inspect # helpful for inspecting incoming webhook requests

  is_matching_build_request =
    request.env["HTTP_X_BUILDKITE_EVENT"] == "build" &&
     event['build']['project']['name'] == settings.project_name &&
     event['build']['branch'] == settings.branch_name

  if is_matching_build_request
    unblockable_job = build['jobs'].find {|job| job['unblockable']}
  end

  status 200
end

get "/" do
  erb :button
end

# Is it unblockable?
get "/unblockable" do
  if unblockable_job
    200
  else
    412
  end
end

# Unblock the job
post "/unblock" do
  if unblockable_job
    buildkite_api.post unblockable_job['unblock_url']
    200
  else
    412
  end
end


text:
package com.byoutline.androidlivecodewarsawflickr.api;

import com.byoutline.androidlivecodewarsawflickr.BuildConfig;

/**
 * Created by Sebastian Kacprzak on 10.01.15.
 */
public class ApiConstants {
    private static final String REAL_HOST = "https://api.flickr.com/services/rest/";
    private static final String MOCK_HOST = "http://localhost:8099";
    public static final boolean MOCK_ENABLED = false;
    public static final String API_KEY = FlickrKey.SECRET;

    public static String getApiPath() {
        if(BuildConfig.DEBUG) {
            return MOCK_ENABLED ? MOCK_HOST : REAL_HOST;
        }
        return REAL_HOST;
    }
}


text:
using UnityEngine;

public class Controller2D : RaycastController
{
    public float fallingThroughPlatformResetTimer = 0.1f;
    private float maxClimbAngle = 0f;
    private float maxDescendAngle = 0f;

    public CollisionInfo collisions;
    [HideInInspector]
    public Vector2 playerInput;

    public override void Start()
    {

        base.Start();

        collisions.faceDir = 1;
    }

    public void Move(Vector2 moveAmount, bool standingOnPlatform = false)
    {
        Move(moveAmount, Vector2.zero, standingOnPlatform);
    }

    public void Move(Vector2 moveAmount, Vector2 input, bool standingOnPlatform = false)
    {
        UpdateRaycastOrigins();
        collisions.Reset();
        collisions.moveAmountOld = moveAmount;
        playerInput = input;

        if (moveAmount.x != 0)
        {
            collisions.faceDir = (int)Mathf.Sign(moveAmount.x);
        }

        if (moveAmount.y < 0)
        {
            DescendSlope(ref moveAmount);
        }

       HorizontalCollisions(ref moveAmount);

        if (moveAmount.y != 0)
        {
            VerticalCollisions(ref moveAmount);
        }

        transform.Translate(moveAmount);

        if (standingOnPlatform)
        {
            collisions.below = true;
        }

		}

    private void HorizontalCollisions(ref Vector2 moveAmount)
    {
        float directionX = collisions.faceDir;
        float rayLength = Mathf.Abs(moveAmount.x) + skinWidth;

        if (Mathf.Abs(moveAmount.x) < skinWidth)
        {
            rayLength = 2 * skinWidth;
        }

       for (int i = 0; i < horizontalRayCount; i++)
        {
            Vector2 rayOrigin = (directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight;
            rayOrigin += Vector2.up * (horizontalRaySpacing * i);
            RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask);

            Debug.DrawRay(rayOrigin, Vector2.right * directionX, Color.red);

            if (hit)
            {
                if (hit.distance == 0)
                {
                    continue;
                }

                float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);

                if (i == 0 && slopeAngle <= maxClimbAngle)
                {
                    if (collisions.descendingSlope)
                    {
                        collisions.descendingSlope = false;
                        moveAmount = collisions.moveAmountOld;
                    }
                    float distanceToSlopeStart = 0f;
                    if (slopeAngle != collisions.slopeAngleOld)
                    {
                        distanceToSlopeStart = hit.distance - skinWidth;
                        moveAmount.x -= distanceToSlopeStart * directionX;
                    }
                   ClimbSlope(ref moveAmount, slopeAngle);
                    moveAmount.x += distanceToSlopeStart * directionX;
                }

                if (!collisions.climbingSlope || slopeAngle > maxClimbAngle)
                {
                    moveAmount.x = (hit.distance - skinWidth) * directionX;
                    rayLength = hit.distance;

                    if (collisions.climbingSlope)
                    {
                        moveAmount.y = Mathf.Tan(collisions.slopeAngle * Mathf.Deg2Rad) * Mathf.Abs(moveAmount.x);
                    }

                    collisions.left = directionX == -1;
                    collisions.right = directionX == 1;
                }
            }
        }
    }

    private void ClimbSlope(ref Vector2 moveAmount, float slopeAngle)
    {
        float moveDistance = Mathf.Abs(moveAmount.x);
        float climbmoveAmountY = Mathf.Sin(slopeAngle * Mathf.Deg2Rad) * moveDistance;

        if (moveAmount.y <= climbmoveAmountY)
        {
            moveAmount.y = climbmoveAmountY;
            moveAmount.x = Mathf.Cos(slopeAngle * Mathf.Deg2Rad) * moveDistance * Mathf.Sign(moveAmount.x);
            collisions.below = true;
            collisions.climbingSlope = true;
            collisions.slopeAngle = slopeAngle;
        }

    }

    private void DescendSlope(ref Vector2 moveAmount)
    {
        float directionX = Mathf.Sign(moveAmount.x);
        Vector2 rayOrigin = (directionX == -1) ? raycastOrigins.bottomRight : raycastOrigins.bottomLeft;
        RaycastHit2D hit = Physics2D.Raycast(rayOrigin, -Vector2.up, Mathf.Infinity, collisionMask);

        if (hit)
        {
            float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);
            if (slopeAngle != 0 && slopeAngle <= maxDescendAngle)
            {
                if (Mathf.Sign(hit.normal.x) == directionX)
                {
                    if (hit.distance - skinWidth <= Mathf.Tan(slopeAngle * Mathf.Deg2Rad) * Mathf.Abs(moveAmount.x))
                    {
                        float moveDistance = Mathf.Abs(moveAmount.x);
                        float descendmoveAmountY = Mathf.Sin(slopeAngle * Mathf.Deg2Rad) * moveDistance;
                        moveAmount.x = Mathf.Cos(slopeAngle * Mathf.Deg2Rad) * moveDistance * Mathf.Sign(moveAmount.x);
                        moveAmount.y -= descendmoveAmountY;

                        collisions.slopeAngle = slopeAngle;
                        collisions.descendingSlope = true;
                        collisions.below = true;
                    }
                }
            }
        }
    }

    private void VerticalCollisions(ref Vector2 moveAmount)
    {
        float directionY = Mathf.Sign(moveAmount.y);
        float rayLength = Mathf.Abs(moveAmount.y) + skinWidth;

        for (int i = 0; i < verticalRayCount; i++)
        {
            Vector2 rayOrigin = (directionY == -1) ? raycastOrigins.bottomLeft : raycastOrigins.topLeft;
            rayOrigin += Vector2.right * (verticalRaySpacing * i + moveAmount.x);
            RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask);

            Debug.DrawRay(rayOrigin, Vector2.up * directionY, Color.red);

            if (hit)
            {
                if (hit.collider.tag == "Through")
                {
                    if (directionY == 1 || hit.distance == 0)
                    {
                        continue;
                    }
                    if (collisions.fallingThroughPlatform)
                    {
                        continue;
                    }
                    if (playerInput.y == -1)
                    {
                        collisions.fallingThroughPlatform = true;
                        Invoke("ResetFallingThroughPlatform", fallingThroughPlatformResetTimer);
                        continue;
                    }
                }
                moveAmount.y = (hit.distance - skinWidth) * directionY;
                rayLength = hit.distance;

                if (collisions.climbingSlope)
                {
                    moveAmount.x = moveAmount.y / Mathf.Tan(collisions.slopeAngle * Mathf.Deg2Rad) * Mathf.Sign(moveAmount.x);
                }

                collisions.below = directionY == -1;
                collisions.above = directionY == 1;
            }
        }

        if (collisions.climbingSlope)
        {
            float directionX = Mathf.Sign(moveAmount.x);
            rayLength = Mathf.Abs(moveAmount.x) + skinWidth;
            Vector2 rayOrigin = ((directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight) + Vector2.up * moveAmount.y;
            RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask);

            if (hit)
            {
                float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);
                if (slopeAngle != collisions.slopeAngle)
                {
                    moveAmount.x = (hit.distance * skinWidth) * directionX;
                    collisions.slopeAngle = slopeAngle;
                }
            }
        }
    }

    private void ResetFallingThroughPlatform()
    {
        collisions.fallingThroughPlatform = false;
    }

    public struct CollisionInfo
    {
        public bool above, below;
        public bool left, right;

        public bool climbingSlope;
        public bool descendingSlope;
        public float slopeAngle, slopeAngleOld;
        public Vector2 moveAmountOld;
        public int faceDir;
        public bool fallingThroughPlatform;

        public void Reset()
        {
            above = below = false;
            left = right = false;
            climbingSlope = false;
            descendingSlope = false;

            slopeAngleOld = slopeAngle;
            slopeAngle = 0f;
        }
    }
}


text: Blog pessoal, que tratará de assuntos relacionados a Tecnologia da Informação.


text:
package play.server;

import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelHandler;
import play.Play;
import play.Logger;
import java.util.Map;
import java.util.HashMap;

import static org.jboss.netty.channel.Channels.pipeline;

public class HttpServerPipelineFactory implements ChannelPipelineFactory {

    private String pipelineConfig = Play.configuration.getProperty("play.netty.pipeline", "play.server.FlashPolicyHandler,org.jboss.netty.handler.codec.http.HttpRequestDecoder,play.server.StreamChunkAggregator,org.jboss.netty.handler.codec.http.HttpResponseEncoder,org.jboss.netty.handler.stream.ChunkedWriteHandler,play.server.PlayHandler");

    protected static Map<String, Class> classes = new HashMap<>();

    @Override
    public ChannelPipeline getPipeline() throws Exception {

        ChannelPipeline pipeline = pipeline();

        String[] handlers = pipelineConfig.split(",");
        if(handlers.length <= 0){
            Logger.error("You must defined at least the playHandler in \"play.netty.pipeline\"");
            return pipeline;
        }

        // Create the play Handler (always the last one)
        String handler = handlers[handlers.length - 1];
        ChannelHandler instance = getInstance(handler);
        PlayHandler playHandler = (PlayHandler) instance;
        if (playHandler == null) {
            Logger.error("The last handler must be the playHandler in \"play.netty.pipeline\"");
            return pipeline;
        }

        // Get all the pipeline. Give the user the opportunity to add their own
        for (int i = 0; i < handlers.length - 1; i++) {
            handler = handlers[i];
            try {
                String name = getName(handler.trim());
                instance = getInstance(handler);
                if (instance != null) {
                    pipeline.addLast(name, instance);
                    playHandler.pipelines.put(name, instance);
                }
            } catch (Throwable e) {
                Logger.error(" error adding " + handler, e);
            }
        }

        if (playHandler != null) {
            pipeline.addLast("handler", playHandler);
            playHandler.pipelines.put("handler", playHandler);
        }

        return pipeline;
    }

    protected String getName(String name) {
        if (name.lastIndexOf(".") > 0)
            return name.substring(name.lastIndexOf(".") + 1);
        return name;
    }

    protected ChannelHandler getInstance(String name) throws Exception {

        Class clazz = classes.get(name);
        if (clazz == null) {
            clazz = Class.forName(name);
            classes.put(name, clazz);
        }
        if (ChannelHandler.class.isAssignableFrom(clazz))
            return (ChannelHandler)clazz.newInstance();
        return null;
    }
}


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Create an Ansible module for integrating your Google Calendar)
[#]: via: (https://opensource.com/article/20/10/ansible-module-go)
[#]: author: (Nicolas Leiva https://opensource.com/users/nicolas-leiva)

Create an Ansible module for integrating your Google Calendar
======
Learn how to write an Ansible module in Go to integrate Google Calendar
into your automation workflow.
![Business woman on laptop sitting in front of window][1]

In a [previous article][2], I explored how [Ansible][3] can integrate with Google Calendar for change management, but I didn't get into the details of the [Ansible module][4] that was built for this purpose. In this article, I will cover the nuts and bolts of it.

While most [Ansible modules][5]** **are written in [Python][6] (see [this example][7]), that's not the only option you have. You can use other programming languages if you prefer. And if you like [Go][8], this post is for you!

![Gopher illustration][9]

([Maria Letta's Free Gophers Pack][10], [Free Gophers License v1.0][11], modified with permission)

If you are new to Go, check out these [pointers to get started][12].

## Ansible and Go

There are at least four different ways that you can run a Go program from Ansible:

  1. Install Go and run your Go code with the `go run` command from Ansible.
  2. Cross-compile your Go code for different platforms before execution. Then call the proper binary from Ansible, based on the facts you collect from the host.
  3. Run your Go code or compiled binary from a container with the `containers.podman` [collection][13]. Something along the lines of: [code] - name: Run Go container
  podman_container:
    name: go_test_container
    image: golang
    command: go version
    rm: true
    log_options: "path={{ log_file }}"
```
  4. Create an [RPM][14] package of your Go code with something like [NFPM][15], and install it in the system of the target host. You can then call it with the Ansible modules [shell][16] or [command][17].

Running an RPM package or container is not Go-specific (cases 3 and 4), so I will focus on the first two options.

## Google Calendar API

You will need to interact with the [Google Calendar API][18], which provides code examples for different programming languages. The one for Go will be the base for your Ansible module.

The tricky part is [enabling the Calendar API][19] and downloading the credentials you generate in the [Google API Console][20] (`Credentials` > `+ CREATE CREDENTIALS` > `OAuth client ID` > `Desktop App`).

![Downloading credentials from Google API Console][21]

(Nicolas Leiva, [CC BY-SA 4.0][22])

The arrow shows where to download your OAuth 2.0 client credentials (JSON file) once you create them in [API Credentials][23].

## Calling the module from Ansible

The `calendar` module takes the `time` to validate as an argument. The example below provides the current time. You can typically get this from [Ansible facts][24] (`ansible_date_time`). The JSON output of the module is registered in a variable named `output` to be used in a subsequent task:
```

\- name: Check if timeslot is taken
  calendar:
    time: "{{ ansible_date_time.iso8601 }}"
  register: output

```
You might wonder where the `calendar` module code lives and how Ansible executes it. Please bear with me for a moment; I'll get to this after I cover other pieces of the puzzle.

## Employ the time logic

With the Calendar API nuances out of the way, you can proceed to interact with the API and build a Go function to capture the module logic. The `time` is taken from the input arguments—in the playbook above—as the initial time (`min`) of the time window to validate (I arbitrarily chose a one-hour duration):
```

func isItBusy(min string) (bool, error) {
        ...
        // max -> min.Add(1 * time.Hour)
        max, err := maxTime(min)
        // ...
        srv, err := calendar.New(client)
        // ...
        freebusyRequest := calendar.FreeBusyRequest{
                TimeMin: min,
                TimeMax: max,
                Items:   []*calendar.FreeBusyRequestItem{&cal},
        }
        // ...
        freebusyRequestResponse, err := freebusyRequestCall.Do()
        // ...
        if len(freebusyRequestResponse.Calendars[name].Busy) == 0 {
                return false, nil
        }
        return true, nil
}

```
It [sends a `FreeBusyRequest`][25] to Google Calendar with the time window's initial and finish time (`min` and `max`). It also creates a calendar [client][26] (`srv`) to authenticate the account correctly using the JSON file with the OAuth 2.0 client credentials. In return, you get a list of events during this time window.

If you get zero events, the function returns `busy=false`. However, if there is at least one event during this time window, it means `busy=true`. You can check out the [full code][27] in my GitHub repository.

## Process the input and creating a response

Now, how does the Go code read the inputs arguments from Ansible and, in turn, generate a response that Ansible can process? The answer to this depends on whether you are running the [Go CLI][28] (command-line interface) or just executing a pre-compiled Go program binary (i.e., options 1 and 2 above).

Both options have their pros and cons. If you use the Go CLI, you can pass the arguments the way you prefer. However, to make it consistent with how it works for binaries you run from Ansible, both alternatives will read a JSON file in the examples presented here.

### Reading the arguments

As shown in the Go code snippet below, an input file is processed, and Ansible provides a path to it when it calls a binary.

The content of the file is unmarshaled into an instance (`moduleArg`) of a previously defined struct (`ModuleArgs`). This is how you tell the Go code which data you expect to receive. This method enables you to gain access to the `time` specified in the playbook via `moduleArg.time`, which is then passed to the time logic function (`isItBusy`) for processing:
```

// ModuleArgs are the module inputs
type ModuleArgs struct {
        Time string
}

func main() {
        ...
        argsFile := os.Args[1]
        text, err := ioutil.ReadFile(argsFile)
        ...
        var moduleArgs ModuleArgs
        err = json.Unmarshal(text, &moduleArgs)
        ...
        busy, err := isItBusy(moduleArg.time)
        ...
}

```
### Generating a response

The values to return are assigned to an instance of a `Response` object. Ansible will need this response includes a couple of boolean flags (`Changed` and `Failed`). You can add any other field you need; in this case, a `Busy` boolean value is carried to signal the response of the time logic function.

The response is marshaled into a message that you print out and Ansible can read:
```

// Response are the values returned from the module
type Response struct {
        Msg     string `json:"msg"`
        Busy    bool   `json:"busy"`
        Changed bool   `json:"changed"`
        Failed  bool   `json:"failed"`
}

func returnResponse(r Response) {
  ...
        response, err = json.Marshal(r)
        ...
        fmt.Println(string(response))
        ...
}

```
You can check out the [full code][29] on GitHub.

## Execute a binary or Go code on the fly?

One of the cool things about Go is that you can cross-compile a Go program to run on different target operating systems and architectures. The binary files you compile can be executed in the target host without installing Go or any dependency.

This flexibility plays nicely with Ansible, which provides the target host details (`ansible_system` and `ansible_architecture`) via Ansible facts. In this example, the target architecture is fixed when compiling (`x86_64`), but binaries for macOS, Linux, and Windows are generated (via `make compile`). This produces the three files that are included in the [`library` folder][30] of the `go_role` role with the form of: `calendar_$system`:
```

⇨  tree roles/go_role/
roles/go_role/
├── library
│   ├── calendar_darwin
│   ├── calendar_linux
│   ├── calendar_windows
│   └── go_run
└── tasks
    ├── Darwin.yml
    ├── Go.yml
    ├── Linux.yml
    ├── main.yml
    └── Win32NT.yml

```
The [`go_role` role][31] that packages the `calendar`


text:
package com.vavi.thread;

public final class FalseSharing implements Runnable {
	public static int NUM_THREADS = 4; // change
	public final static long ITERATIONS = 500L * 1000L * 1000L;
	private final int arrayIndex;
	private static VolatileLong[] longs;

	public FalseSharing(final int arrayIndex) {
		this.arrayIndex = arrayIndex;
	}

	public static void main(final String[] args) throws Exception {
		Thread.sleep(10000);
		System.out.println("starting....");
		if (args.length == 1) {
			NUM_THREADS = Integer.parseInt(args[0]);
		}

		longs = new VolatileLong[NUM_THREADS];
		for (int i = 0; i < longs.length; i++) {
			longs[i] = new VolatileLong();
		}
		final long start = System.nanoTime();
		runTest();
		System.out.println("duration = " + (System.nanoTime() - start));
	}

	private static void runTest() throws InterruptedException {
		Thread[] threads = new Thread[NUM_THREADS];
		for (int i = 0; i < threads.length; i++) {
			threads[i] = new Thread(new FalseSharing(i));
		}
		for (Thread t : threads) {
			t.start();
		}
		for (Thread t : threads) {
			t.join();
		}
	}

	@Override
	public void run() {
		long i = ITERATIONS + 1;
		while (0 != --i) {
			longs[arrayIndex].value = i;
		}
	}

	public final static class VolatileLong {
		public volatile long value = 0L;
		public long p1, p2, p3, p4, p5, p6; // 注释
	}
}


text:
require 'rails_helper'

RSpec.describe NotifyCreatorsThatModerationIsDelayedJob, type: :job do
  let(:petition) { FactoryBot.create(:sponsored_petition, :overdue, sponsors_signed: true) }
  let(:signature) { petition.creator }
  let(:subject) { "Moderation of your petition is delayed" }
  let(:body) { "Sorry, but moderation of your petition is delayed for reasons." }

  let(:notify_creator_job) do
    {
      job: NotifyCreatorThatModerationIsDelayedJob,
      args: [
        { "_aj_globalid" => "gid://jpets/Signature/#{signature.id}" },
        "Moderation of your petition is delayed",
        "Sorry, but moderation of your petition is delayed for reasons."
      ],
      queue: "low_priority"
    }
  end

  before do
    expect(Petition).to receive_message_chain(:overdue_in_moderation, :find_each).and_yield(petition)
  end

  it "enqueues a job for every petition awaiting moderation" do
    expect {
      described_class.perform_now(subject, body)
    }.to change {
      enqueued_jobs
    }.from([]).to([notify_creator_job])
  end
end


text:
class CreateDrgs < ActiveRecord::Migration[5.2]
  def change
    create_table :drgs do |t|
      t.string :code
      t.string :version
      t.string :text_de
      t.string :text_fr
      t.string :text_it
      t.integer :mdc_id
      t.integer :partition_id
      t.integer :adrg_id
    end
  end
end


text:
from sklearn.metrics import precision_recall_fscore_support

import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import MinMaxScaler, normalize

df = pd.read_csv('../../Dataset/dataset.csv', delimiter='\t')

dataset = df.values

mask = np.random.rand(len(df)) < .80

train = df[mask]
test = df[~mask]

X = pd.DataFrame()
Y = pd.DataFrame()

X = train.ix[:, 2:len(train.columns) - 1]
Y = train.ix[:, len(train.columns) - 1: len(train.columns)]

X_Test = pd.DataFrame()
Y_Test = pd.DataFrame()

# After Normalising
X_standard = normalize(X)
print X_standard.shape

X_Test = test.ix[:, 2:len(test.columns) - 1]
Y_Test = test.ix[:, len(test.columns) - 1: len(test.columns)]

X_Test_standard = normalize(X_Test)
print X_Test_standard.shape

print "Training Data Set Size : ", str(len(X))
print "Testing Data Set Size : ", str(len(X_Test))

# tune parameters here.
rf = RandomForestClassifier(n_estimators=150, max_features=20)

rf.fit(X_standard, Y)
# predict
Y_Result = rf.predict(X_Test_standard)

print precision_recall_fscore_support(Y_Test, Y_Result, average='micro')


text:
/*!
 *  \file test_mkldnn.h
 *  \brief helper functions to test mkldnn.
 *  \author Alex Zai
 */

#ifndef TEST_MKLDNN_H_
#define TEST_MKLDNN_H_

#if MXNET_USE_MKLDNN == 1

#include <set>
#include <string>
#include <vector>
#include "../../../3rdparty/mkldnn/include/mkldnn_types.h"
#include "../../../3rdparty/googletest/googletest/include/gtest/gtest.h"
#include "../../../src/operator/nn/mkldnn/mkldnn_base-inl.h"

using namespace mxnet;

inline static mkldnn::memory::primitive_desc GetMemPD(const TShape s, int dtype,
                                               mkldnn::memory::format format) {
  mkldnn::memory::dims dims(s.ndim());
  for (size_t i = 0; i < dims.size(); i++)
    dims[i] = s[i];
  mkldnn::memory::desc desc{dims, get_mkldnn_type(dtype), format};
  return mkldnn::memory::primitive_desc(desc, CpuEngine::Get()->get_engine());
}

inline static mkldnn::memory::primitive_desc GetExpandedMemPD(
    mkldnn::memory::primitive_desc pd, float scale, int dim = 0) {
  CHECK(dim < pd.desc().data.ndims) << "dimension cannot be larger than total dimensions of input";
  nnvm::TShape s(pd.desc().data.ndims);
  for (size_t i = 0; i < pd.desc().data.ndims; i++)
    s[i] = pd.desc().data.dims[i];
  s[dim] = static_cast<int>(s[dim] * scale);
  return GetMemPD(s, mshadow::DataType<mshadow::default_real_t>::kFlag,
                  static_cast<mkldnn::memory::format>(pd.desc().data.format));
}

struct TestArrayShapes {
  std::vector<nnvm::TShape> shapes;
  std::vector<mkldnn::memory::primitive_desc> pds;
};

// Init arrays with the default layout.
inline static void InitDefaultArray(NDArray *arr, bool is_rand = false) {
  const TBlob &blob = arr->data();
  mshadow::default_real_t *data = blob.dptr<mshadow::default_real_t>();
  int size = blob.Size();

  for (int i = 0; i < size; i++)
    if (is_rand) {
      data[i] = (std::rand() % 100) - 50;
    } else {
      data[i] = i % 100 - 50;
    }
}

// Init arrays with the specified layout.
inline static void InitMKLDNNArray(NDArray *arr, const mkldnn::memory::primitive_desc &pd,
                            bool is_rand = false) {
  InitDefaultArray(arr, is_rand);
  arr->MKLDNNDataReorderAsync(pd);
  arr->WaitToRead();
}

inline static bool IsSameShape(mkldnn::memory::primitive_desc pd, TShape shape) {
  if (pd.desc().data.ndims != shape.ndim()) return false;
  for (size_t i = 0; i < shape.ndim(); i++)
    if (pd.desc().data.dims[i] != shape[i]) return false;
  return true;
}

// This function gets special MKLDNN formats without knowing the specific
// hardware configuration. Certainly, it potentially misses some format if
// it's specific for certain array shapes. It covers at least one special format
// for each of the formats: nchw, oihw, goihw.
// To test the logic of the code in NDArray, these formats should be enough.
inline static std::vector<mkldnn::memory::format> GetMKLDNNFormat(size_t num_dims, int dtype) {
  if (num_dims == 4) {
    mkldnn::memory::dims data_dims{1, 3, 224, 224};
    mkldnn::memory::desc data_md{data_dims, get_mkldnn_type(dtype),
                                 mkldnn::memory::format::any};
    mkldnn::memory::dims weight_dims{96, 3, 11, 11};
    mkldnn::memory::desc weight_md{weight_dims, get_mkldnn_type(dtype),
                                   mkldnn::memory::format::any};
    mkldnn::memory::dims output_dims{1, 96, 54, 54};
    mkldnn::memory::desc out_md{output_dims, get_mkldnn_type(dtype),
                                mkldnn::memory::format::any};
    mkldnn::memory::dims strides{4, 4};
    mkldnn::memory::dims padding{0, 0};

    mkldnn::convolution_forward::desc desc(mkldnn::prop_kind::forward_training,
                                           mkldnn::algorithm::convolution_direct,
                                           data_md, weight_md, out_md, strides,
                                           padding, padding, mkldnn::padding_kind::zero);
    mkldnn::convolution_forward::primitive_desc pd(desc, CpuEngine::Get()->get_engine());
    while (pd.dst_primitive_desc().get_size() != GetMemDescSize(out_md) ||
           pd.src_primitive_desc().get_size() != GetMemDescSize(data_md) ||
           pd.weights_primitive_desc().get_size() != GetMemDescSize(weight_md)) {
      CHECK(pd.next_impl()) << "No implementation";
    }

    std::vector<mkldnn::memory::format> ret(1);
    ret[0] = static_cast<mkldnn::memory::format>(pd.dst_primitive_desc().desc().data.format);
    printf("format: %d \n", ret[0]);
    return ret;
  } else if (num_dims == 5) {
    mkldnn::memory::dims data_dims{1, 32, 112, 112};
    mkldnn::memory::desc data_md{data_dims, get_mkldnn_type(dtype),
                                 mkldnn::memory::format::any};
    mkldnn::memory::dims weight_dims{32, 1, 1, 3, 3};
    mkldnn::memory::desc weight_md{weight_dims, get_mkldnn_type(dtype),
                                   mkldnn::memory::format::any};
    mkldnn::memory::dims output_dims{1, 32, 112, 112};
    mkldnn::memory::desc out_md{output_dims, get_mkldnn_type(dtype),
                                mkldnn::memory::format::any};
    mkldnn::memory::dims strides{1, 1};
    mkldnn::memory::dims padding{1, 1};

    mkldnn::convolution_forward::desc desc(mkldnn::prop_kind::forward_training,
                                           mkldnn::algorithm::convolution_direct,
                                           data_md, weight_md, out_md, strides,
                                           padding, padding, mkldnn::padding_kind::zero);
    mkldnn::convolution_forward::primitive_desc pd(desc, CpuEngine::Get()->get_engine());
    while (pd.dst_primitive_desc().get_size() != GetMemDescSize(out_md) ||
           pd.src_primitive_desc().get_size() != GetMemDescSize(data_md) ||
           pd.weights_primitive_desc().get_size() != GetMemDescSize(weight_md)) {
      CHECK(pd.next_impl()) << "No implementation";
    }

    std::vector<mkldnn::memory::format> ret(1);
    ret[0] = static_cast<mkldnn::memory::format>(pd.weights_primitive_desc().desc().data.format);
    printf("format: %d\n", ret[0]);
    return ret;
  } else {
    return std::vector<mkldnn::memory::format>();
  }
}

inline static TestArrayShapes GetTestArrayShapes(bool spatial_data_format = false) {
  int dtype = mshadow::DataType<mshadow::default_real_t>::kFlag;
  std::vector<TShape> shapes;
  std::vector<mkldnn::memory::primitive_desc> pds;
  {
    // 1D
    TShape s(1);
    s[0] = 279936;
    shapes.push_back(s);
    pds.push_back(GetMemPD(s, dtype, mkldnn::memory::format::x));
    s[0] = 34848;
    shapes.push_back(s);
    pds.push_back(GetMemPD(s, dtype, mkldnn::memory::format::x));
  }
  {
    // 2D
    TShape s(2);
    s[0] = 96;
    s[1] = 2916;
    shapes.push_back(s);
    pds.push_back(GetMemPD(s, dtype, mkldnn::memory::format::nc));
    s[0] = 96;
    s[1] = 363;
    shapes.push_back(s);
    pds.push_back(GetMemPD(s, dtype, mkldnn::memory::format::nc));
  }
  {
    // 4D
    TShape s1(4);
    s1[0] = 10; s1[1] = 96; s1[2] = 54; s1[3] = 54;
    shapes.push_back(s1);
    pds.push_back(GetMemPD(s1, dtype, mkldnn::memory::format::nchw));

    TShape s2(4);
    s2[0] = 96; s2[1] = 3; s2[2] = 11; s2[3] = 11;
    shapes.push_back(s2);
    pds.push_back(GetMemPD(s2, dtype, mkldnn::memory::format::oihw));

    std::vector<mkldnn::memory::format> formats = GetMKLDNNFormat(4, dtype);
    if (!spatial_data_format) {
      pds.push_back(GetMemPD(s1, dtype, formats[0]));
    }
  }
  {
    // 5D
    TShape s(5);
    s[0] = 96; s[1] = 1; s[2] = 3; s[3] = 11; s[4] = 11;
    shapes.push_back(s);
    pds.push_back(GetMemPD(s, dtype, mkldnn::memory::format::goihw));

    std::vector<mkldnn::memory::format> formats = GetMKLDNNFormat(5, dtype);
    if (!spatial_data_format) {
      pds.push_back(GetMemPD(s, dtype, formats[0]));
    }
  }

  TestArrayShapes ret;
  ret.shapes = shapes;
  ret.pds = pds;
  return ret;
}

struct NDArrayAttrs {
  NDArray arr;
  std::string desc;
  NDArrayAttrs(NDArray arr, std::string desc) : arr(arr), desc(desc) {}
};

struct OpAttrs {
  nnvm::NodeAttrs attrs;
  std::vector<DispatchMode> dispatches;
  std::set<OpReqType> requests;
  std::unordered_set<int> accept_dims;
  int num_inputs;
  int num_outputs;
  int input_types;
  int output_types;
};

enum ArrayTypes {
  Normal = 1,
  MKLDNN = 2,
  MKLDNNDiffShape = 4,
  MKLDNNDiffDim = 8,
  NormalReshaped = 16,
  MKLDNNReshaped = 32,
  MKLDNNReshapedDiffShape = 64,
  MKLDNNReshapedDiffDim = 128,
  NormalReused = 256,
  MKLDNNReused = 512,
  MKLDNNReusedDiffDim = 1024,
  NormalReshapedReused = 2048,
  NormalReusedDiffDtype = 4096,
  All = 8191,
};

inline NDArray CreateKernelNDArray(TShape kernel, int num_filters, TShape input,
    bool is_deconv = false) {
  CHECK_EQ(kernel.ndim(), 2) << "mkldnn only supports 2d filters on 4d inputs";
  TShape target_shape(4);
  target_shape[0] = is_deconv ? input[1] : num_filters;
  target_shape[1] = is_deconv ? num_filters : input[1];
  target_shape[2] = kernel[0];
  target_shape[3] = kernel[1];
  int dtype = mshadow::DataType<mshadow::default_real_t>::kFlag;
  NDArray arr(target_shape, Context());
  auto pd = GetMemPD(target_shape, dtype, mkldnn::memory::format::nchw);
  InitMKLDNNArray(&arr, pd);
  return arr;
}

inline NDArray CreateBiasNDArray(TShape target_shape) {
  int dtype = mshadow::DataType<mshadow::default_real_t>::kFlag;
  NDArray arr(target_shape, Context());
  auto pd = GetMemPD(target_shape, dtype, mkldnn::memory::format::x);
  InitMKLDNNArray(&arr, pd);
  return arr;
}

inline int CalculateWidthConvOutput(int width, int kernel, int padding, int stride) {
  return (width - kernel + 2 * padding) / stride  + 1;
}

inline int CalculateWidthDeconvOutput(int width, int kernel, int padding, int stride) {
  return stride * (width - 1) + kernel - 2 * padding;
}

inline std::string CreateShapeString(int value, int dim) {
  std::stringstream ss;
  ss << "(";
  for (int i = 0; i < dim; i++) {
    ss << value;
    if (i != dim - 1) ss << ",";
  }
  ss << ")";
  return ss.str();
}

inline void PrintVerifyMsg(const NDArrayAttrs &arr1, const NDArrayAttrs &arr2) {
  TShape t1 = arr1.arr.shape();
  TShape t2 = arr2.arr.shape();
  std::stringstream ss;
  std::cout << "Verifying: " << arr1.desc.c_str() << " " <<
            t1 << " with " << arr2.desc.c_str() << " " << t2 << "\n";
}

/*
 * We want to get a few types of NDArrays for testing:
 * 1. Normal NDArray
 * 2. Normal NDArray with MKLDNN layout (output from an MKLDNN operator)
 * 3. Normal NDArray with MKLDNN layout whose MKLDNN memory may have different
 *    dimensions from the NDArray (result of MKLDNNDataReorderAsync). However, this
 *    type of NDArrays only exists for weight arrays. I don't think we should
 *    pass them to all operators.
 *    In the inference mode, the MKLDNN memory in the weight array will be
 *    reordered to 5 dimensions.
 * 4. Reshaped/sliced NDArray
 * 5. Reshaped/sliced NDArray with MKLDNN layout (reshape/slice from Normal NDArray
 *    with MKLDNN layout)
 * 6. Reshaped/sliced NDArray with MKLDNN layout whose MKLDNN memory may have
 *    different dimensions from the NDArray (result of MKLDNNDataReorderAsync).
 *    However, this type of NDArrays only exists for weight arrays. I don't think
 *    we should pass them to all operators.
 *    In the inference mode, the MKLDNN memory in the weight array will be
 *    reordered to 5 dimensions.
 *
 *  num_inputs / dim arguments used to scale shape (used for concat backwards to enlarge input shapes)
 */
inline std::vector<NDArrayAttrs> GetTestInputArrays(
    int types = ArrayTypes::All, bool rand = false,
    std::vector<float> scale = {1}, bool spatial_data_format = false) {
  TestArrayShapes tas = GetTestArrayShapes(spatial_data_format);
  std::vector<nnvm::TShape> shapes = tas.shapes;
  std::vector<mkldnn::memory::primitive_desc> pds = tas.pds;

  std::vector<NDArrayAttrs> in_arrs;
  std::string desc;

  int slice_amount = scale[0];
  for (auto shape : shapes) {
    if (scale.size() > shape.ndim())
      continue;

    for (size_t dim = 0; dim < scale.size(); ++dim)
      shape[dim] = static_cast<int>(round(shape[dim] * scale[dim]));

    // Type 1.
    NDArray arr(shape, Context());
    if (types & ArrayTypes::Normal) {
      InitDefaultArray(&arr, rand);
      in_arrs.emplace_back(arr, "Normal NDArray");
    }

    // Type 4
    arr = NDArray(shape, Context());
    if (types & ArrayTypes::NormalReshaped) {
      InitDefaultArray(&arr, rand);
      in_arrs.emplace_back(arr.Slice(slice_amount, arr.shape()[0] - slice_amount),
                           "Reshaped Normal NDArray");
    }

    for (auto pd : pds) {
      for (size_t dim = 0; dim < scale.size(); ++dim) {
        // preserve if matching layout else just expand on 0 dim
        if (shape.ndim() == pd.desc().data.ndims)
          pd = GetExpandedMemPD(pd, scale[dim], dim);
        else
          pd = GetExpandedMemPD(pd, scale[dim]);
      }

      if (shape.Size() != pd.get_size() / sizeof(mshadow::default_real_t))
        continue;

      // Type 2, 3.
      arr = NDArray(shape, Context());
      if (shape.ndim() == pd.desc().data.ndims && IsSameShape(pd, shape)
          && types & ArrayTypes::MKLDNN) {
        desc = "MKLDNN NDArray";
        InitMKLDNNArray(&arr, pd, rand);
        in_arrs.emplace_back(arr, desc);
      } else if (shape.ndim() == pd.desc().data.ndims && !IsSameShape(pd, shape)
          && types & ArrayTypes::MKLDNNDiffShape) {
        desc = "MKLDNN NDArray with different shape";
        InitMKLDNNArray(&arr, pd, rand);
        in_arrs.emplace_back(arr, desc);
      } else if (shape.ndim() != pd.desc().data.ndims && types & ArrayTypes::MKLDNNDiffDim) {
        std::stringstream ss;
        ss << "MKLDNN NDArray with different dim " <<
           shape.ndim() << "/" << pd.desc().data.ndims;
        desc = ss.str();
        InitMKLDNNArray(&arr, pd, rand);
        in_arrs.emplace_back(arr, desc);
      }

      // Type 5, 6.
      arr = NDArray(shape, Context());
      if (shape.ndim() == pd.desc().data.ndims && IsSameShape(pd, shape)
          && types & ArrayTypes::MKLDNNReshaped) {
        desc = "Reshaped MKLDNN NDArray";
        InitMKLDNNArray(&arr, pd, rand);
        in_arrs.emplace_back(arr.Slice(slice_amount, arr.shape()[0] - slice_amount), desc);
      } else if (shape.ndim() == pd.desc().data.ndims && !IsSameShape(pd, shape)
          && types & ArrayTypes::MKLDNNReshapedDiffShape) {
        desc = "Reshaped MKLDNN NDArray with different shape";
        InitMKLDNNArray(&arr, pd, rand);
        in_arrs.emplace_back(arr.Slice(slice_amount, arr.shape()[0] - slice_amount), desc);
      } else if (shape.ndim() != pd.desc().data.ndims
          && types & ArrayTypes::MKLDNNReshapedDiffDim) {
        std::stringstream ss;
        ss << "MKLDNN NDArray with different dim " <<
           shape.ndim() << "/" << pd.desc().data.ndims;
        desc = ss.str();
        InitMKLDNNArray(&arr, pd, rand);
        in_arrs.emplace_back(arr.Slice(slice_amount, arr.shape()[0] - slice_amount), desc);
      }
    }
  }
  return in_arrs;
}

/*
 * We want to get a few types of NDArrays for testing:
 * 1. Normal NDArray
 * 2. Normal NDArray with MKLDNN layout (output from an MKLDNN operator)
 * 3. Normal NDArray with MKLDNN layout whose MKLDNN memory may have different
 *    dimensions from the NDArray (result of MKLDNNDataReorderAsync). However, this
 *    type of NDArrays only exists for weight arrays. I don't think we should
 *    pass them to all operators.
 *    In the inference mode, the MKLDNN memory in the weight array will be
 *    reordered to 5 dimensions.
 * 4. Reshaped/sliced NDArray
 * 5. Reused NDArray (this is created by the MXNet executor). This type of
 *    NDArrays can only be used as output arrays.
 * 6. Reused NDArray converted from an array with a different data type.
 * 7. Reused reshaped/sliced NDArray.
 * 8. Reused NDArray with MKLDNN layout.
 * 9. Reused NDArray with MKLDNN layout of different dimensions.
 *
 * Optional num_inputs / dim args can be passed to modify input shape (used for Concat test)
 */
inline std::vector<NDArrayAttrs> GetTestOutputArrays(
    const TShape &shp,
    const std::vector<mkldnn::memory::primitive_desc> &pds,
    std::vector<float>scale = {1}, bool rand = true, int types = ArrayTypes::All) {
  TShape shape = shp;

  for (int dim = 0; dim < scale.size(); dim++)
    shape[dim] = static_cast<int>(shape[dim] * scale[dim]);

  std::vector<NDArrayAttrs> in_arrs;
  std::string desc;
  // Type 1.
  NDArray arr(shape, Context());

  if (types & ArrayTypes::Normal) {
    in_arrs.emplace_back(arr, "Normal NDArray");
    InitDefaultArray(&in_arrs.back().arr, rand);
  }

  TShape tmp_shape = shape;
  if (types & ArrayTypes::NormalReshaped) {
    // Type 4.
    tmp_shape[0] = shape[0] * 2;
    NDArray arr0(tmp_shape, Context());
    InitDefaultArray(&arr0, rand);
    in_arrs.emplace_back(arr0.Slice(1, shape[0] + 1), "Reshaped NDArray");
  }

  nnvm::TShape s(1);
  if (types & ArrayTypes::NormalReused) {
    // Type 5.
    // Get a reused version.
    s[0] = shape.Size();
    NDArray arr1(s, Context());
    arr1 = arr1.AsArray(shape, arr1.dtype());
    InitDefaultArray(&arr1, rand);
    in_arrs.emplace_back(arr1, "Reused NDArray");
  }

  if (types & ArrayTypes::NormalReusedDiffDtype) {
    // Type 6.
    s[0] = shape.Size() * GetTypeSize(mshadow::default_type_flag);
    NDArray arr2(s, Context(), true, mshadow::kUint8);
    arr2 = arr2.AsArray(shape, mshadow::default_type_flag);
    InitDefaultArray(&arr2, rand);
    in_arrs.emplace_back(arr2, "Reused NDArray with diff data type");
  }

  if (types & ArrayTypes::NormalReshapedReused) {
    // Type 7
    s[0] = shape.Size() * GetTypeSize(mshadow::default_type_flag) * 2;
    NDArray arr3(s, Context(), true, mshadow::kUint8);
    tmp_shape[0] = shape[0] * 2;
    arr3 = arr3.AsArray(tmp_shape, mshadow::default_type_flag);
    InitDefaultArray(&arr3, rand);
    in_arrs.emplace_back(arr3.Slice(1, shape[0] + 1), "Reused+Reshaped NDArray");
  }

  for (auto pd : pds) {
    if (shape.Size() != pd.get_size() / sizeof(mshadow::default_real_t))
      continue;

    if (scale.size() > pd.desc().data.ndims)
      continue;

    for (int dim = 0; dim < scale.size(); dim++)
      pd = GetExpandedMemPD(pd, scale[dim]);

    // Type 2, 3.
    arr = NDArray(shape, Context());
    desc = "MKLDNN NDArray";
    if (shape.ndim() != pd.desc().data.ndims) {
      std::stringstream ss;
      ss << "MKLDNN NDArray with different memory layout "
         << shape.ndim() << "/" << pd.desc().data.ndims;
      desc = ss.str();
    }

    if ((types & ArrayTypes::MKLDNN && shape.ndim() == pd.desc().data.ndims) ||
        (types & ArrayTypes::MKLDNNDiffDim && shape.ndim() != pd.desc().data.ndims)) {
      in_arrs.emplace_back(arr, desc);
      InitMKLDNNArray(&in_arrs.back().arr, pd, rand);
    }

    // Type 8, 9.
    // Get a reused version.
    nnvm::TShape s(1);
    s[0] = shape.Size();
    NDArray arr = NDArray(s, Context());
    arr = arr.AsArray(shape, arr.dtype());
    InitMKLDNNArray(&arr, pd, rand);
    desc = "Reused MKLDNN NDArray";
    if (shape.ndim() != pd.desc().data.ndims) {
      std::stringstream ss;
      ss << "Reused MKLDNN NDArray with different memory layout "
         << shape.ndim() << "/" << pd.desc().data.ndims;
      desc = ss.str();
    }

    if ((types & ArrayTypes::MKLDNNReused && shape.ndim() == pd.desc().data.ndims) ||
        (types & ArrayTypes::MKLDNNReusedDiffDim && shape.ndim() != pd.desc().data.ndims)) {
      in_arrs.emplace_back(arr, desc);
    }
  }
  return in_arrs;
}

/*
 * Determines axis ndarrays are concatenated by
 * Used to verify concat/concat backwards operator
 */
inline int GetDim(TShape input_shape, TShape output_shape) {
  CHECK(input_shape.Size() != output_shape.Size());
  for (size_t i = 0; i < input_shape.ndim(); i++) {
    if (input_shape[i] != output_shape[i])
      return i;
  }
  return -1;
}

/*
 * Calculates the size of continuous block of array inside larger concatenated array
 * Used to verify concat/concat backwards operator
 */
inline int GetBlockSize(TShape shape, int dim) {
  int block_size = 1;
  for (int i = shape.ndim() - 1; i >= dim; i--)
    block_size *= shape[i];
  return block_size;
}

inline int CalculateWidthPoolOutput(int width, int kernel, int padding, int stride) {
  return (width - kernel + 2 * padding) / stride  + 1;
}

using VerifyFunc = std::function<void (const std::vector<NDArray *> &in_arrs,
                                       const std::vector<NDArray *> &out_arrs)>;

inline void VerifyAddRequest(const std::vector<NDArray*> &in_arrs,
                      const std::vector<NDArray*> &original_outputs,
                      const std::vector<NDArray*> &new_outputs,
                      VerifyFunc verify_fn) {
  CHECK(original_outputs.size() == new_outputs.size());
  std::vector<NDArray*> tmp_outputs;
  NDArray tmp;
  for (size_t i = 0; i < new_outputs.size(); i++) {
    tmp = new_outputs[i]->Reorder2Default() - original_outputs[i]->Reorder2Default();
    tmp_outputs.push_back(&tmp);
  }
  Engine::Get()->WaitForAll();
  verify_fn(in_arrs, tmp_outputs);
}

inline void VerifyCopyResult(const std::vector<NDArray *> &in_arrs,
                      const std::vector<NDArray *> &out_arrs) {
  NDArray tmp1 = in_arrs[0]->Reorder2Default();
  NDArray tmp2 = out_arrs[0]->Reorder2Default();
  EXPECT_EQ(tmp1.shape().Size(), tmp2.shape().Size());
  TBlob d1 = tmp1.data();
  TBlob d2 = tmp2.data();
  EXPECT_EQ(memcmp(d1.dptr_, d2.dptr_,
                   tmp1.shape().Size() * sizeof(mshadow::default_real_t)), 0);
}

inline void VerifySumResult(const std::vector<NDArray *> &in_arrs,
                     const std::vector<NDArray *> &out_arrs) {
  NDArray in1 = in_arrs[0]->Reorder2Default();
  NDArray in2 = in_arrs[1]->Reorder2Default();
  NDArray out = out_arrs[0]->Reorder2Default();
  EXPECT_EQ(in1.shape().Size(), in2.shape().Size());
  EXPECT_EQ(in1.shape().Size(), out.shape().Size());

  mshadow::default_real_t *d1 = in1.data().dptr<mshadow::default_real_t>();
  mshadow::default_real_t *d2 = in2.data().dptr<mshadow::default_real_t>();
  mshadow::default_real_t *o = out.data().dptr<mshadow::default_real_t>();
  for (size_t i = 0; i < in1.shape().Size(); i++)
    ASSERT_EQ(d1[i] + d2[i], o[i]);
}

#endif  // MXNET_USE_MKLDNN
#endif  // TEST_MKLDNN_H_


text:
<?php

namespace Google\Service\SecurityCommandCenter;

class Cve extends \Google\Collection
{
  protected $collection_key = 'references';
  protected $cvssv3Type = Cvssv3::class;
  protected $cvssv3DataType = '';
  /**
   * @var string
   */
  public $id;
  protected $referencesType = Reference::class;
  protected $referencesDataType = 'array';
  /**
   * @var bool
   */
  public $upstreamFixAvailable;

  /**
   * @param Cvssv3
   */
  public function setCvssv3(Cvssv3 $cvssv3)
  {
    $this->cvssv3 = $cvssv3;
  }
  /**
   * @return Cvssv3
   */
  public function getCvssv3()
  {
    return $this->cvssv3;
  }
  /**
   * @param string
   */
  public function setId($id)
  {
    $this->id = $id;
  }
  /**
   * @return string
   */
  public function getId()
  {
    return $this->id;
  }
  /**
   * @param Reference[]
   */
  public function setReferences($references)
  {
    $this->references = $references;
  }
  /**
   * @return Reference[]
   */
  public function getReferences()
  {
    return $this->references;
  }
  /**
   * @param bool
   */
  public function setUpstreamFixAvailable($upstreamFixAvailable)
  {
    $this->upstreamFixAvailable = $upstreamFixAvailable;
  }
  /**
   * @return bool
   */
  public function getUpstreamFixAvailable()
  {
    return $this->upstreamFixAvailable;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(Cve::class, 'Google_Service_SecurityCommandCenter_Cve');


text:
<?php

/**
 * Description of LoginFormFilter
 *
 * @author fragote
 */

namespace Dashboard\FormFilter;

use Zend\InputFilter\InputFilter;

class LoginFormFilter extends InputFilter
{

    public function __construct()
    {
        $input = new \Zend\InputFilter\Input('username');
        // Validadores
        $v = new \Zend\Validator\StringLength(array('min'=>3,'max'=>50));
        $v->setMin(3);
        $v->setMessage('El usuario ingresado es inválido', \Zend\Validator\StringLength::TOO_SHORT);
        $input->setRequired(true);
        $input->getValidatorChain()->attach($v);
        $this->add($input);

        $input = new \Zend\InputFilter\Input('password');
        // Validadores
        $v = new \Zend\Validator\StringLength(array('min'=>1,'max'=>50));
        $v->setMessage('La clave ingresada es inválida', \Zend\Validator\StringLength::TOO_SHORT);
        $input->setRequired(true);
        $input->getValidatorChain()->attach($v);
        $this->add($input);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="1dp"
                android:background="@drawable/first_anim_phone_inner_frame"
    >

    <TextView
        android:id="@+id/phone_frame_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:background="@color/guide_view_5_myself"
        android:gravity="center"
        android:keepScreenOn="true"
        android:textColor="@android:color/white"
        android:textSize="16sp"
        android:textStyle="bold"
        tools:text="Myself"
        />
</RelativeLayout>


text:
#ifndef _NETINET_ICMP_VAR_H_
#define _NETINET_ICMP_VAR_H_

/*
 * Variables related to this implementation
 * of the internet control message protocol.
 */
struct	icmpstat {
/* statistics related to icmp packets generated */
	u_long	icps_error;		/* # of calls to icmp_error */
	u_long	icps_oldshort;		/* no error 'cuz old ip too short */
	u_long	icps_oldicmp;		/* no error 'cuz old was icmp */
	u_long	icps_outhist[ICMP_MAXTYPE + 1];
/* statistics related to input messages processed */
	u_long	icps_badcode;		/* icmp_code out of range */
	u_long	icps_tooshort;		/* packet < ICMP_MINLEN */
	u_long	icps_checksum;		/* bad checksum */
	u_long	icps_badlen;		/* calculated bound mismatch */
	u_long	icps_reflect;		/* number of responses */
	u_long	icps_inhist[ICMP_MAXTYPE + 1];
	u_long	icps_bmcastecho;	/* b/mcast echo requests dropped */
	u_long	icps_bmcasttstamp;	/* b/mcast tstamp requests dropped */
	u_long	icps_badaddr;		/* bad return address */
	u_long	icps_noroute;		/* no route back */
};

#ifdef _KERNEL
#include <sys/counter.h>

VNET_PCPUSTAT_DECLARE(struct icmpstat, icmpstat);
/*
 * In-kernel consumers can use these accessor macros directly to update
 * stats.
 */
#define	ICMPSTAT_ADD(name, val)	\
    VNET_PCPUSTAT_ADD(struct icmpstat, icmpstat, name, (val))
#define	ICMPSTAT_INC(name)	ICMPSTAT_ADD(name, 1)

/*
 * Kernel module consumers must use this accessor macro.
 */
void	kmod_icmpstat_inc(int statnum);
#define	KMOD_ICMPSTAT_INC(name)						\
    kmod_icmpstat_inc(offsetof(struct icmpstat, name) / sizeof(uint64_t))
#endif

/*
 * Names for ICMP sysctl objects
 */
#define	ICMPCTL_MASKREPL	1	/* allow replies to netmask requests */
#define	ICMPCTL_STATS		2	/* statistics (read-only) */
#define ICMPCTL_ICMPLIM		3
#define ICMPCTL_MAXID		4

#ifdef _KERNEL
SYSCTL_DECL(_net_inet_icmp);

extern int badport_bandlim(int);
#define BANDLIM_UNLIMITED -1
#define BANDLIM_ICMP_UNREACH 0
#define BANDLIM_ICMP_ECHO 1
#define BANDLIM_ICMP_TSTAMP 2
#define BANDLIM_RST_CLOSEDPORT 3 /* No connection, and no listeners */
#define BANDLIM_RST_OPENPORT 4   /* No connection, listener */
#define BANDLIM_ICMP6_UNREACH 5
#define BANDLIM_SCTP_OOTB 6
#define BANDLIM_MAX 6
#endif

#endif


text:
package org.openqa.selenium;

/**
 * Represents rotation of the browser view for orientation-sensitive devices.
 *
 * When using this with a real device, the device should not be moved so that the built-in sensors
 * do not interfere.
 */
public interface Rotatable {

  /**
   * Changes the orientation of the browser window.
   *
   * @param orientation the desired screen orientation
   */
  void rotate(ScreenOrientation orientation);

  /**
   * @return the current screen orientation of the browser
   */
  ScreenOrientation getOrientation();
}


text: angular.module('todo', ['ngMaterial', 'todo.controllers']);


text:
#pragma once
#include "UEPyModule.h"

#if WITH_EDITOR

#if PLATFORM_LINUX
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wnull-dereference"
#endif
#endif

#include <fbxsdk.h>

struct ue_PyFbxPose
{
	PyObject_HEAD
		/* Type-specific fields go here. */
		FbxPose *fbx_pose;
};

void ue_python_init_fbx_pose(PyObject *);

PyObject *py_ue_new_fbx_pose(FbxPose *);

#endif


text:
namespace GerberParser.Commands
{
    public interface IContainsUnits
    {
        void MultiplyBy(decimal mul);

        void MoveBy(decimal offsetX, decimal offsetY);
    }
}


text:
package kikaha.core.cdi;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class CountDownApplication implements Application {

	volatile int number;

	@Override
	public void run() throws Exception {
		number--;
	}
}


text:
<bill session="115" type="h" number="2728" updated="2017-07-07T07:12:28Z">
  <state datetime="2017-05-25">REFERRED</state>
  <status>
    <introduced datetime="2017-05-25"/>
  </status>
  <introduced datetime="2017-05-25"/>
  <titles>
    <title type="short" as="introduced">Cleaning Product Labeling Act of 2017</title>
    <title type="short" as="introduced">Cleaning Product Labeling Act of 2017</title>
    <title type="official" as="introduced">To require labeling of ingredients of cleaning products, and for other purposes.</title>
    <title type="display">Cleaning Product Labeling Act of 2017</title>
  </titles>
  <sponsor bioguide_id="R000599"/>
  <cosponsors/>
  <actions>
    <action datetime="2017-05-25">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-05-25" state="REFERRED">
      <text>Referred to the Committee on Energy and Commerce, and in addition to the Committee on Education and the Workforce, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text>
    </action>
    <action datetime="2017-05-25">
      <text>Referred to House Energy and Commerce</text>
    </action>
    <action datetime="2017-05-25">
      <text>Referred to House Education and the Workforce</text>
    </action>
    <action datetime="2017-06-09">
      <text>Referred to the Subcommittee on Digital Commerce and Consumer Protection.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSIF" name="House Energy and Commerce" activity="Referral"/>
    <committee subcommittee="Commerce, Manufacturing, and Trade" code="HSIF17" name="House Energy and Commerce" activity="Referral"/>
    <committee subcommittee="" code="HSED" name="House Education and the Workforce" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Commerce"/>
  </subjects>
  <amendments/>
  <summary date="2017-05-25T04:00:00Z" status="Introduced in House">Cleaning Product Labeling Act of 2017

This bill requires chemically formulated cleaning products to bear a label with, and requires manufacturers to include on their Internet websites, a list of all of the product's ingredients (including individual ingredients in dyes, fragrances, and preservatives) in descending order of predominance by weight, except that ingredients that constitute less than 1% of the product can be listed at the end in any order. Product websites must include: (1) the CAS Registry Number of each ingredient, and (2) an explanation of each ingredient's purpose.

A product that is not in conformity with the labeling and website listing requirements shall be treated as: (1) a misbranded hazardous substance under the Federal Hazardous Substances Act if it is under the jurisdiction of the Consumer Product Safety Commission (CPSC), or (2) a violation of rules under the Occupational Safety and Health Act of 1970 if it is under the jurisdiction of the Occupational Safety and Health Administration (OSHA).

The CPSC and OSHA must issue regulations to enforce this bill.

A person may petition the CPSC or OSHA to investigate claims that a product does not satisfy these requirements.</summary>
  <committee-reports/>
</bill>


text:
package io.grpc;

import static io.grpc.ConnectivityState.CONNECTING;
import static io.grpc.ConnectivityState.IDLE;
import static io.grpc.ConnectivityState.TRANSIENT_FAILURE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotSame;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link ConnectivityStateInfo}. */
@RunWith(JUnit4.class)
public class ConnectivityStateInfoTest {
  @Test
  public void forNonError() {
    ConnectivityStateInfo info = ConnectivityStateInfo.forNonError(IDLE);
    assertEquals(IDLE, info.getState());
    assertEquals(Status.OK, info.getStatus());
  }

  @Test(expected = IllegalArgumentException.class)
  public void forNonErrorInvalid() {
    ConnectivityStateInfo.forNonError(TRANSIENT_FAILURE);
  }

  @Test
  public void forTransientFailure() {
    ConnectivityStateInfo info = ConnectivityStateInfo.forTransientFailure(Status.UNAVAILABLE);
    assertEquals(TRANSIENT_FAILURE, info.getState());
    assertEquals(Status.UNAVAILABLE, info.getStatus());
  }

  @Test(expected = IllegalArgumentException.class)
  public void forTransientFailureInvalid() {
    ConnectivityStateInfo.forTransientFailure(Status.OK);
  }

  @Test
  public void equality() {
    ConnectivityStateInfo info1 = ConnectivityStateInfo.forNonError(IDLE);
    ConnectivityStateInfo info2 = ConnectivityStateInfo.forNonError(CONNECTING);
    ConnectivityStateInfo info3 = ConnectivityStateInfo.forNonError(IDLE);
    ConnectivityStateInfo info4 = ConnectivityStateInfo.forTransientFailure(Status.UNAVAILABLE);
    ConnectivityStateInfo info5 = ConnectivityStateInfo.forTransientFailure(Status.INTERNAL);
    ConnectivityStateInfo info6 = ConnectivityStateInfo.forTransientFailure(Status.INTERNAL);

    assertEquals(info1, info3);
    assertNotSame(info1, info3);
    assertEquals(info1.hashCode(), info3.hashCode());
    assertEquals(info5, info6);
    assertEquals(info5.hashCode(), info6.hashCode());
    assertNotSame(info5, info6);

    assertNotEquals(info1, info2);
    assertNotEquals(info1, info4);
    assertNotEquals(info4, info6);

    assertFalse(info1.equals(null));
    // Extra cast to avoid ErrorProne EqualsIncompatibleType failure
    assertFalse(((Object) info1).equals(this));
  }
}


text:
import React from "react";
import NextHead from "next/head";

const Head = ({ title, description, image }) => (
  <NextHead>
    <meta charSet="utf-8" />

    <title>{title}</title>

    <link rel="dns-prefetch" href="//ajax.googleapis.com/" />
    <link rel="dns-prefetch" href="//fonts.googleapis.com/" />
    <link rel="dns-prefetch" href="//fonts.gstatic.com/" />
    <link rel="dns-prefetch" href="//www.google-analytics.com/" />

    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link
      rel="preconnect"
      href="https://fonts.gstatic.com"
      crossOrigin="crossorigin"
    />

    <meta name="description" content={description} />

    <link
      rel="alternate"
      type="application/rss+xml"
      title="drublic Blog"
      href="/feed"
    />

    <meta property="twitter:domain" content="drublic.de" />
    <meta name="twitter:site" content="@drublic" />
    <meta name="twitter:title" content={title} />
    <meta name="twitter:description" content={description} />

    <meta property="og:type" content="website" />
    <meta property="og:title" content={title} />
    <meta property="og:description" content={description} />
    {image ? (
      <>
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:image" content={image} />
        <meta property="og:image" content={image} />
      </>
    ) : (
      <>
        <meta name="twitter:card" content="summary" />
        <meta name="twitter:image" content="https://drublic.de/img/logo.png" />
        <meta property="og:image" content="https://drublic.de/img/logo.png" />
      </>
    )}

    <link type="text/plain" rel="author" href="/humans.txt" />
    <meta name="author" content="Hans Christian Reinl" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <meta name="application-name" content="drublic" />
    <meta name="theme-color" content="#316eae" />
    <link rel="manifest" href="/manifest.json" />
    <link rel="shortcut icon" href="/favicon.png" />

    <link
      rel="index"
      href="/"
      title="drublic - State of the Art Webdesign - HTML, CSS, JavaScript - Hans Christian Reinl"
    />
  </NextHead>
);

export default Head;


text:
#import "TiBase.h"
#import "TiEvaluator.h"
#import "KrollCallback.h"
#import "KrollObject.h"
#import <pthread.h>

@class KrollBridge;

//Common exceptions to throw when the function call was improper
extern NSString * const TiExceptionInvalidType;
extern NSString * const TiExceptionNotEnoughArguments;
extern NSString * const TiExceptionRangeError;

extern NSString * const TiExceptionOSError;

//This is when a normally allowed command is not allowed (Say, adding a row to a table when it already is added elsewhere)
extern NSString * const TiExceptionInternalInconsistency;

//Should be rare, but also useful if arguments are used improperly.
extern NSString * const TiExceptionInternalInconsistency;

//Rare exceptions to indicate a bug in the _testcleartop code (Eg, function that a subclass should have implemented)
extern NSString * const TiExceptionUnimplementedFunction;

@class TiHost;
@class TiProxy;

typedef enum {
	NativeBridge,
	WebBridge
} TiProxyBridgeType;

@protocol TiProxyDelegate<NSObject>

@required

-(void)propertyChanged:(NSString*)key oldValue:(id)oldValue newValue:(id)newValue proxy:(TiProxy*)proxy;

@optional

-(void)readProxyValuesWithKeys:(id<NSFastEnumeration>)keys;

-(void)listenerAdded:(NSString*)type count:(int)count;
-(void)listenerRemoved:(NSString*)type count:(int)count;

-(void)detachProxy;

@end

SEL SetterForKrollProperty(NSString * key);
SEL SetterWithObjectForKrollProperty(NSString * key);

void DoProxyDelegateChangedValuesWithProxy(UIView<TiProxyDelegate> * target, NSString * key, id oldValue, id newValue, TiProxy * proxy);
void DoProxyDelegateReadValuesWithKeysFromProxy(UIView<TiProxyDelegate> * target, id<NSFastEnumeration> keys, TiProxy * proxy);
//Why are these here? Because they can be commonly used between TiUIView and TiUITableViewCell.

@interface TiProxy : NSObject<KrollTargetable> {
@private
	NSMutableDictionary *listeners;
	BOOL destroyed;
	id<TiProxyDelegate> modelDelegate;
	NSURL *baseURL;
	NSString *krollDescription;
	pthread_rwlock_t listenerLock;
	BOOL reproxying;
@protected
	BOOL	ignoreValueChanged;	//This is done only at initialization where we know the dynprops were properly set by _initWithProperties.
	NSMutableDictionary *dynprops;
	pthread_rwlock_t dynpropsLock; // NOTE: You must respect the dynprops lock when accessing dynprops elsewhere!
	id<TiEvaluator> pageContext;
	id<TiEvaluator> executionContext;
}

@property(readonly,nonatomic)			id<TiEvaluator> pageContext;
@property(readonly,nonatomic)			id<TiEvaluator> executionContext;

@property(nonatomic,retain,readwrite)	id<TiProxyDelegate> modelDelegate;

#pragma mark Private

-(id)_initWithPageContext:(id<TiEvaluator>)context;
-(id)_initWithPageContext:(id<TiEvaluator>)context args:(NSArray*)args;
-(void)_initWithProperties:(NSDictionary*)properties;
-(BOOL)_hasListeners:(NSString*)type;
-(void)_fireEventToListener:(NSString*)type withObject:(id)obj listener:(KrollCallback*)listener thisObject:(TiProxy*)thisObject_;
-(id)_proxy:(TiProxyBridgeType)type;
-(void)_contextDestroyed;
-(void)contextWasShutdown:(id<TiEvaluator>)context;
-(TiHost*)_host;
-(NSURL*)_baseURL;
-(void)_setBaseURL:(NSURL*)url;
-(BOOL)_propertyInitRequiresUIThread;
-(void)_destroy;
-(void)_configure;
-(void)_dispatchWithObjectOnUIThread:(NSArray*)args;
-(void)didReceiveMemoryWarning:(NSNotification*)notification;
-(TiProxy*)currentWindow;
-(void)contextShutdown:(id)sender;
-(id)toString:(id)args;
-(BOOL)destroyed;
-(void)setReproxying:(BOOL)yn;
-(BOOL)inReproxy;

#pragma mark Public
-(id<NSFastEnumeration>)allKeys;
-(NSArray *)keySequence;

+(void)throwException:(NSString *) reason subreason:(NSString*)subreason location:(NSString *)location;
-(void)throwException:(NSString *) reason subreason:(NSString*)subreason location:(NSString *)location;
-(void)addEventListener:(NSArray*)args;
-(void)removeEventListener:(NSArray*)args;

-(void)fireEvent:(id)args;
-(void)fireEvent:(NSString*)type withObject:(id)obj;
-(void)fireEvent:(NSString*)type withObject:(id)obj withSource:(id)source;
-(void)fireEvent:(NSString*)type withObject:(id)obj withSource:(id)source propagate:(BOOL)yn;
-(void)fireEvent:(NSString*)type withObject:(id)obj propagate:(BOOL)yn;

-(NSDictionary*)allProperties;
-(void)replaceValue:(id)value forKey:(NSString*)key notification:(BOOL)notify;
-(void)deleteKey:(NSString*)key;

-(id)sanitizeURL:(id)value;

-(void)setExecutionContext:(id<TiEvaluator>)context;

@end


text:
nisteag.scripts package
=======================

Submodules
----------

.. toctree::

   nisteag.scripts.checkers

Module contents
---------------

.. automodule:: nisteag.scripts
    :members:
    :undoc-members:
    :show-inheritance:


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_marginBottom="10dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:layout_gravity="center"
        android:gravity="center">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="@string/faq1"
            android:id="@+id/faqQuestion1"
            android:textColor="@color/fontColor"
            android:layout_marginBottom="5dp"
            android:textSize="25sp"
            android:layout_marginTop="5dp"
            android:textStyle="bold"
            android:layout_marginLeft="5dp"
            android:layout_weight="0.1"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_menu_more"
            android:id="@+id/expandAnswerButton"
            android:layout_marginRight="2dp"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_menu_less"
            android:id="@+id/closeButton2"
            android:layout_marginRight="2dp"/>
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="#888"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:id="@+id/answerDetailsContainer">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/faq1"
            android:id="@+id/faqQuestion2"
            android:layout_marginTop="5dp"
            android:textColor="@color/fontColor"
            android:textStyle="bold"
            android:textSize="20sp"
            android:layout_marginLeft="5dp"/>
        <WebView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/faqAnswer"
            android:layout_marginTop="2dp"
            android:layout_marginLeft="9dp"
            android:layout_marginRight="7dp"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="9dp"
            android:textColor="#000"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="20dp"
            android:text="@string/clickForMoreInfo"
            android:id="@+id/moreInfo"/>
        <WebView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="9dp"
            android:layout_marginRight="7dp"
            android:id="@+id/detailsContent"/>
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="9dp"
            android:layout_marginRight="7dp"
            android:id="@+id/imageContent"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:src="@drawable/ic_menu_less"
            android:layout_marginRight="7dp"
            android:id="@+id/contractAnswerButton"/>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#555"/>
    </LinearLayout>
</LinearLayout>