text:
'use strict';

const {
  verifySelectorsVisible,
} = require('../../../build-system/tasks/visual-diff/verifiers');

module.exports = {
  'dark theme - shopping CTA UI should display': async (page, name) => {
    const pageID = 'inline-dark-theme';
    const url = await page.url();
    await page.goto(`${url}#page=${pageID}`);
    await page.waitForSelector(
      `amp-story-page#${pageID}[active][distance="0"]`
    );
    await verifySelectorsVisible(page, name, [
      '.i-amphtml-story-page-open-attachment[active]',
    ]);
  },
  'displays shopping PLP (product list page)': async (page, name) => {
    const pageID = 'inline-light-theme';
    const url = await page.url();
    await page.goto(`${url}#page=${pageID}`);
    await page.waitForSelector(
      `amp-story-page#${pageID}[active][distance="0"]`
    );
    await page.tap(
      `amp-story-page#${pageID} .i-amphtml-story-inline-page-attachment-chip`
    );
    await page.waitForSelector('.i-amphtml-story-draggable-drawer-open');
    await verifySelectorsVisible(page, name, [
      '.i-amphtml-story-draggable-drawer-open',
    ]);
  },
  'dark theme - displays shopping PLP (product list page)': async (
    page,
    name
  ) => {
    const pageID = 'inline-dark-theme';
    const url = await page.url();
    await page.goto(`${url}#page=${pageID}`);
    await page.waitForSelector(
      `amp-story-page#${pageID}[active][distance="0"]`
    );
    await page.tap(
      `amp-story-page#${pageID} .i-amphtml-story-inline-page-attachment-chip`
    );
    await page.waitForSelector('.i-amphtml-story-draggable-drawer-open');
    await verifySelectorsVisible(page, name, [
      '.i-amphtml-story-draggable-drawer-open',
    ]);
  },
  'displays shopping PDP (product description page) with carousel': async (
    page,
    name
  ) => {
    const pageID = 'inline-light-theme';
    const url = await page.url();
    await page.goto(`${url}#page=${pageID}`);
    await page.waitForSelector(
      `amp-story-page#${pageID}[active][distance="0"]`
    );
    await page.tap(
      `amp-story-page#${pageID} .i-amphtml-story-inline-page-attachment-chip`
    );
    await verifySelectorsVisible(page, name, [
      '.i-amphtml-story-draggable-drawer-open',
    ]);
    await page.tap(
      `amp-story-page#${pageID} .i-amphtml-amp-story-shopping-plp-card`
    );
    await page.waitForSelector('.i-amphtml-amp-story-shopping-pdp');
  },
  'displays shopping PDP (product description page) without carousel': async (
    page,
    name
  ) => {
    const pageID = 'inline-light-theme';
    const url = await page.url();
    await page.goto(`${url}#page=${pageID}`);
    await page.waitForSelector(
      `amp-story-page#${pageID}[active][distance="0"]`
    );
    await page.tap(
      `amp-story-page#${pageID} .i-amphtml-story-inline-page-attachment-chip`
    );
    await verifySelectorsVisible(page, name, [
      '.i-amphtml-story-draggable-drawer-open',
    ]);
    await page.tap(
      `amp-story-page#${pageID} .i-amphtml-amp-story-shopping-plp-card:nth-child(2)`
    );
    await page.waitForSelector('.i-amphtml-amp-story-shopping-pdp');
  },
};


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Baz</title>
    <link rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../../assets/validation.css">

pagination

          «

          ‹

 1

          2

 3

 4

 5

 6

          ›

          »

pagination-justified

          «

          ‹

 1

          2

 3

 4

 5

 6

          ›

          »

paginate

          ← Prev

 1

          2

 3

 4

 5

 6

          Next →

    bar

    baz

    index

    quux

    foo

    index

                First

                ← Previous

 1

                2

 3

 4

 5

 6

                Next →

                Last

Sanity Check

                3
                Total Categories

                4
                Total Tags

{{relative}} helper

                  Page title: Baz

 Bar

                    Baz

 Category Index

 Quux

 Foo Foo

 Home

{{rel}} helper

                  Page title: Baz

 Bar

                    Baz

 Category Index

 Quux

 Foo Foo

 Home

Tags

Related pages for: bbb

 Bar

Related pages for: one

 Foo Foo

 Home

Related pages for: three

 Category Index

 Home

Related pages for: two

 Quux

Categories

Related pages for: nested

 Quux

Related pages for: yyy

                      Baz

Related pages for: zzz

                      Baz

Baz

Suprising discovery! Contrary to popular belief, ice in the arctic tundra was found to be below freezing temperatures.

          Ullamco elit non id amet ex ut ea dolor ipsum. Adipisicing deserunt non reprehenderit anim deserunt in nisi voluptate laborum labore fugiat et fugiat cillum. Est anim ea ea amet eu sit ut dolor in.

deserunt minim labore qui consequat

Laboris reprehenderit commodo sit mollit magna occaecat id qui tempor do irure adipisicing eu amet culpa. Quis enim ut fugiat ea est fugiat excepteur eiusmod exercitation do. Occaecat excepteur consectetur nisi et et aliqua fugiat sunt laborum
            magna commodo amet consequat. Cupidatat dolore nisi qui pariatur excepteur occaecat elit ut nulla. Culpa aute ipsum magna consequat minim ullamco cupidatat magna labore amet est laboris enim nisi. Qui et officia enim qui voluptate reprehenderit
            nostrud veniam veniam in exercitation do excepteur id. Veniam sint qui amet deserunt sint aliqua adipisicing labore deserunt do non adipisicing do ex non reprehenderit voluptate.

Veniam dolor Lorem eu Lorem cillum in do pariatur eu ipsum ipsum labore nostrud ex tempor pariatur cillum. Eiusmod id velit laboris excepteur laborum minim nostrud do culpa sint ullamco commodo ipsum adipisicing sint ipsum. Ad exercitation do
            Lorem enim dolore non quis Lorem anim ex minim ex anim amet. Proident minim esse magna fugiat in incididunt dolore amet do consectetur exercitation excepteur dolor consequat cillum adipisicing ea.

Non officia proident sit quis laboris Lorem fugiat commodo et excepteur cupidatat tempor nostrud non sunt amet cillum sint. Et tempor deserunt nulla proident ad eu id culpa amet sunt esse nulla quis velit culpa qui id. Veniam cupidatat excepteur
            Lorem est proident laboris pariatur fugiat ipsum voluptate magna labore labore ea sint ut. Elit eu exercitation est occaecat est pariatur tempor voluptate sit esse laborum non ut eu nostrud pariatur quis aliquip. Velit ut ex adipisicing do
            occaecat officia excepteur exercitation quis duis mollit sit veniam deserunt quis reprehenderit tempor.

Ipsum amet exercitation excepteur anim enim occaecat culpa ex id sit ipsum anim velit minim. Veniam elit enim in ipsum nisi irure et minim mollit voluptate non fugiat laboris. Fugiat commodo Lorem dolore mollit commodo voluptate amet deserunt
          in anim nostrud do.

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
in Sturm, Deutschl. Fl. , 3 Abt. (Pilze Deutschl. ) [7](19-20): 35 (1841)

#### Original name
Ceratogaster Corda

### Remarks
null


text:
package training

import (
	"fmt"
	"strings"

	"github.com/kubeflow/arena/pkg/apis/types"
	"github.com/kubeflow/arena/pkg/argsbuilder"
)

type VolcanoJobBuilder struct {
	args      *types.SubmitVolcanoJobArgs
	argValues map[string]interface{}
	argsbuilder.ArgsBuilder
}

func NewVolcanoJobBuilder() *VolcanoJobBuilder {
	args := &types.SubmitVolcanoJobArgs{
		MinAvailable:  1,
		Queue:         "default",
		SchedulerName: "volcano",
		TaskName:      "task",
		TaskImages:    []string{"ubuntu", "nginx", "busybox"},
		TaskReplicas:  1,
		TaskCPU:       "250m",
		TaskMemory:    "128Mi",
		TaskPort:      2222,
	}
	return &VolcanoJobBuilder{
		args:        args,
		argValues:   map[string]interface{}{},
		ArgsBuilder: argsbuilder.NewSubmitVolcanoJobArgsBuilder(args),
	}
}

// Name is used to set job name,match option --name
func (b *VolcanoJobBuilder) Name(name string) *VolcanoJobBuilder {
	if name != "" {
		b.args.Name = name
	}
	return b
}

// Command is used to set job command
func (b *VolcanoJobBuilder) Command(args []string) *VolcanoJobBuilder {
	b.args.Command = strings.Join(args, " ")
	return b
}

func (b *VolcanoJobBuilder) MinAvailable(minAvailable int) *VolcanoJobBuilder {
	if minAvailable > 0 {
		b.args.MinAvailable = minAvailable
	}
	return b
}

func (b *VolcanoJobBuilder) Queue(queue string) *VolcanoJobBuilder {
	if queue != "" {
		b.args.Queue = queue
	}
	return b
}

func (b *VolcanoJobBuilder) SchedulerName(name string) *VolcanoJobBuilder {
	if name != "" {
		b.args.SchedulerName = name
	}
	return b
}

func (b *VolcanoJobBuilder) TaskImages(images []string) *VolcanoJobBuilder {
	if len(images) != 0 {
		b.args.TaskImages = images
	}
	return b
}

func (b *VolcanoJobBuilder) TaskName(name string) *VolcanoJobBuilder {
	if name != "" {
		b.args.TaskName = name
	}
	return b
}

func (b *VolcanoJobBuilder) TaskReplicas(replicas int) *VolcanoJobBuilder {
	if replicas > 0 {
		b.args.TaskReplicas = replicas
	}
	return b
}

func (b *VolcanoJobBuilder) TaskCPU(cpu string) *VolcanoJobBuilder {
	if cpu != "" {
		b.args.TaskCPU = cpu
	}
	return b
}

func (b *VolcanoJobBuilder) TaskMemory(mem string) *VolcanoJobBuilder {
	if mem != "" {
		b.args.TaskMemory = mem
	}
	return b
}

func (b *VolcanoJobBuilder) TaskPort(port int) *VolcanoJobBuilder {
	if port > 0 {
		b.args.TaskPort = port
	}
	return b
}

func (b *VolcanoJobBuilder) Labels(labels map[string]string) *VolcanoJobBuilder {
	if labels != nil && len(labels) != 0 {
		s := []string{}
		for key, value := range labels {
			s = append(s, fmt.Sprintf("%v=%v", key, value))
		}
		b.argValues["label"] = &s
	}
	return b
}

func (b *VolcanoJobBuilder) Annotations(annotations map[string]string) *VolcanoJobBuilder {
	if annotations != nil && len(annotations) != 0 {
		s := []string{}
		for key, value := range annotations {
			s = append(s, fmt.Sprintf("%v=%v", key, value))
		}
		b.argValues["annotation"] = &s
	}
	return b
}

// Build is used to build the job
func (b *VolcanoJobBuilder) Build() (*Job, error) {
	for key, value := range b.argValues {
		b.AddArgValue(key, value)
	}
	if err := b.PreBuild(); err != nil {
		return nil, err
	}
	if err := b.ArgsBuilder.Build(); err != nil {
		return nil, err
	}
	return NewJob(b.args.Name, types.VolcanoTrainingJob, b.args), nil
}


text:
This contains test resources for the unit tests. Files in this folder include pre-made cryptographic signatures.

## Directory structure

* `valid_signature.json`: Extracted using packet extract from an actual authentication
* `incorrect_nonce.json`: Different nonce token simulating that the server expected a different token than signed
* `incorrect_salt.json`: Salt sent is different to the content signed by the signature (changed salt field)
* `incorrect_signature.json`: Changed signature

## File content

* `nonce`: Server generated nonce token
* `salt`: Client generated random token that will be signed
* `signature`: Nonce and salt signed using the client key from `valid_public_key.json`


text:
/* This is an empty file to satisfy the "$(srcdir)/*.[ch]" in libgasnet_dependencies.
 * The actual sources reside in the vapi-conduit directory.
 */
#error "nothing should #include this file"


text:
/**
 *
 */
package org.gdg.util;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * @author DeadCode
 *
 */
public class PubsubJSONSerializer<T> {

	public String POJOSerializer(T ser)
	{

	ObjectMapper mapper = new ObjectMapper();

		try {

			// convert user object to json string,
			String jsonString = mapper.writeValueAsString(ser);

			// display to console

			return jsonString;

		} catch (JsonGenerationException e) {

			e.printStackTrace();

		} catch (JsonMappingException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		return "";
	}

}


text:
FROM alpine:3.3

RUN apk add --update bash curl unzip openjdk7 && \
    rm /var/cache/apk/*

# epubcheck
ENV EPUBCHECK epubcheck-4.0.1

RUN curl -L -o "/tmp/$EPUBCHECK.zip" "https://github.com/IDPF/epubcheck/releases/download/v${EPUBCHECK#*-}/$EPUBCHECK.zip" \
 && unzip "/tmp/$EPUBCHECK.zip" -d /app \
 && rm "/tmp/$EPUBCHECK.zip" \
 && ( cd /app; ln -s "$EPUBCHECK" epubcheck )
ADD app /app/

VOLUME ["/app/data"]
WORKDIR /app

ENTRYPOINT ["/app/bin/epubcheck"]


text:
package ch.marc.jumpguy.entities;

import java.awt.image.BufferedImage;

public class WorldBlock {
	private int x, y;
	public int yOffset = 0;
	public boolean deadly, win;

	public BufferedImage sprite;

	public int width, height = 64;

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}
}


text:
<?php

namespace IgetMaster\TokenAuth;

use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Auth\GuardHelpers;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Carbon\Carbon;
use Cache;

class TokenGuard implements Guard
{
    use GuardHelpers;

    /**
     * The current authorization token.
     *
     * @var string|null
     */
    public $token;

    /**
     * The request instance.
     *
     * @var \Illuminate\Http\Request
     */
    protected $request;

    /**
     * Indicates if the logout method has been called.
     *
     * @var bool
     */
    protected $loggedOut = false;

    /**
     * TokenGuard constructor.
     * @param $createUserProvider
     */
    public function __construct(UserProvider $provider, Request $request)
    {
        $this->request = $request;
        $this->provider = $provider;
    }

    /**
     * Get the currently authenticated user.
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function user() {
        if ($this->loggedOut) {
            return;
        }

        // If we've already retrieved the user for the current request we can just
        // return it back immediately. We do not want to fetch the user data on
        // every call to this method because that would be tremendously slow.
        if (! is_null($this->user)) {
            return $this->user;
        }

        $user = null;

        $this->token =  $this->getAuthorizationToken();

        if (! empty($this->token)) {
            $authorization = Cache::get('auth:' . $this->token);

            if ($authorization) {
                $user = $this->provider->retrieveById($authorization['user_id']);
            }
        }

        return $this->user = $user;
    }

    /**
     * Validate a user's credentials.
     *
     * @param  array  $credentials
     * @return bool
     */
    public function validate(array $credentials = [])
    {
        return $this->attempt($credentials, false, false);
    }

    /**
     * Attempt to authenticate a user using the given credentials.
     *
     * @param  array  $credentials
     * @param  bool   $login
     * @return bool
     */
    public function attempt(array $credentials = [], $login = true)
    {
        $this->fireAttemptEvent($credentials, $login);

        $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);

        // If an implementation of UserInterface was returned, we'll ask the provider
        // to validate the user against the given credentials, and if they are in
        // fact valid we'll log the users into the application and return true.
        if ($this->hasValidCredentials($user, $credentials)) {
            if ($login) {
                $this->login($user);
            }

            return true;
        }

        return false;
    }

    /**
     * Log a user into the application.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @return void
     */
    public function login(AuthenticatableContract $user)
    {
        $lifetime = config('session.lifetime');

        $user_id = $user->getAuthIdentifier();
        $expires_on = Carbon::now()->addMinutes($lifetime);
        $this->token = $this->generateAuthorizationToken();

        Cache::put('auth:' . $this->token, compact('user_id', 'expires_on'), $lifetime);

        // If we have an event dispatcher instance set we will fire an event so that
        // any listeners will hook into the authentication events and run actions
        // based on the login and logout events fired from the guard instances.
        $this->fireLoginEvent($user);

        $this->setUser($user);
    }

    /**
     * Log the user out of the application.
     *
     * @return void
     */
    public function logout()
    {
        Cache::forget('auth:' . $this->getAuthorizationToken());

        if (isset($this->events)) {
            $this->events->fire(new Events\Logout($this->user));
        }

        // Once we have fired the logout event we will clear the users out of memory
        // so they are no longer available as the user is no longer considered as
        // being signed into this application and should not be available here.
        $this->user = null;

        $this->loggedOut = true;
    }

    /**
     * Reset user to allow testing
     */
    public function resetUser()
    {
        $this->user = null;
    }

    /**
     * @return null|string
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * Get the expiration datetime for the current authorization token
     *
     * @return \Carbon\Carbon|null
     */
    public function getExpiration()
    {
        $authentication = Cache::get('auth:' . $this->token);

        return $authentication ? $authentication['expires_on'] : null;
    }

    /**
     * Set the current request instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return $this
     */
    public function setRequest(Request $request)
    {
        $this->request = $request;

        return $this;
    }

    /**
     * @return string|null
     */
    protected function getAuthorizationToken()
    {
        return $this->request->header('Authorization');
    }

    /**
     * Fire the attempt event with the arguments.
     *
     * @param  array  $credentials
     * @param  bool  $login
     * @return void
     */
    protected function fireAttemptEvent(array $credentials, $login)
    {
        if (isset($this->events)) {
            $this->events->fire(new Events\Attempting(
                $credentials, false, $login
            ));
        }
    }

    /**
     * Fire the login event if the dispatcher is set.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @return void
     */
    protected function fireLoginEvent($user)
    {
        if (isset($this->events)) {
            $this->events->fire(new Events\Login($user, false));
        }
    }

    /**
     * Generate a random unique authorization token
     *
     * @param $user_id
     * @return string
     */
    protected function generateAuthorizationToken()
    {
        do {
            $token = str_random();
        } while (Cache::has("auth:${token}"));
        return $token;
    }

    /**
     * Determine if the user matches the credentials.
     *
     * @param  mixed  $user
     * @param  array  $credentials
     * @return bool
     */
    protected function hasValidCredentials($user, $credentials)
    {
        return ! is_null($user) && $this->provider->validateCredentials($user, $credentials);
    }
}


text:
package domain

import (
	"net/url"
)

type Page struct {
	Url    *url.URL
	Links  []*Link
	Assets []*url.URL
}

type Link struct {
	Source *url.URL
	Target *url.URL
}


text:
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;

namespace System.Security.Cryptography.X509Certificates
{
    public sealed class X509Certificate2Enumerator : IEnumerator
    {
        // This is a mutable struct enumerator, so don't mark it as readonly.
        private List<X509Certificate>.Enumerator _enumerator;

        internal X509Certificate2Enumerator(X509Certificate2Collection collection)
        {
            Debug.Assert(collection != null);

            collection.GetEnumerator(out _enumerator);
        }

        public X509Certificate2 Current
        {
            // Call the struct enumerator's IEnumerator.Current implementation, which has the
            // behavior we want of throwing InvalidOperationException when the enumerator
            // hasn't been started or has ended, without boxing.
            get { return (X509Certificate2)(EnumeratorHelper.GetCurrent(ref _enumerator)); }
        }

        object IEnumerator.Current
        {
            get { return Current; }
        }

        public bool MoveNext()
        {
            return _enumerator.MoveNext();
        }

        bool IEnumerator.MoveNext()
        {
            return MoveNext();
        }

        public void Reset()
        {
            // Call Reset on the struct enumerator without boxing.
            EnumeratorHelper.Reset(ref _enumerator);
        }

        void IEnumerator.Reset()
        {
            Reset();
        }
    }
}


text:
namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace distance
{

template <typename Linear, typename Areal, typename Strategy>
struct linear_to_areal
{
    typedef typename strategy::distance::services::return_type
        <
            Strategy,
            typename point_type<Linear>::type,
            typename point_type<Areal>::type
        >::type return_type;

    static inline return_type apply(Linear const& linear,
                                    Areal const& areal,
                                    Strategy const& strategy)
    {
        if ( geometry::intersects(linear, areal) )
        {
            return 0;
        }

        return linear_to_linear
            <
                Linear, Areal, Strategy
            >::apply(linear, areal, strategy, false);
    }

    static inline return_type apply(Areal const& areal,
                                    Linear const& linear,
                                    Strategy const& strategy)
    {
        return apply(linear, areal, strategy);
    }
};

template <typename Areal1, typename Areal2, typename Strategy>
struct areal_to_areal
{
    typedef typename strategy::distance::services::return_type
        <
            Strategy,
            typename point_type<Areal1>::type,
            typename point_type<Areal2>::type
        >::type return_type;

    static inline return_type apply(Areal1 const& areal1,
                                    Areal2 const& areal2,
                                    Strategy const& strategy)
    {
        if ( geometry::intersects(areal1, areal2) )
        {
            return 0;
        }

        return linear_to_linear
            <
                Areal1, Areal2, Strategy
            >::apply(areal1, areal2, strategy, false);
    }
};

}} // namespace detail::distance
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template <typename Linear, typename Areal, typename Strategy>
struct distance
    <
        Linear, Areal, Strategy,
        linear_tag, areal_tag,
        strategy_tag_distance_point_segment, false
    >
    : detail::distance::linear_to_areal
        <
            Linear, Areal, Strategy
        >
{};

template <typename Areal, typename Linear, typename Strategy>
struct distance
    <
        Areal, Linear, Strategy,
        areal_tag, linear_tag,
        strategy_tag_distance_point_segment, false
    >
    : detail::distance::linear_to_areal
        <
            Linear, Areal, Strategy
        >
{};

template <typename Areal1, typename Areal2, typename Strategy>
struct distance
    <
        Areal1, Areal2, Strategy,
        areal_tag, areal_tag,
        strategy_tag_distance_point_segment, false
    >
    : detail::distance::areal_to_areal
        <
            Areal1, Areal2, Strategy
        >
{};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_LINEAR_OR_AREAL_TO_AREAL_HPP


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <!-- "Mark Favorite", should appear as action button if possible -->
    <item
        android:id="@+id/action_save"
        android:title="action_save"
        android:icon="@drawable/save"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_cancel"
        android:title="action_cancel"
        android:icon="@drawable/cancel"
        app:showAsAction="ifRoom"/>

</menu>


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var DataFactory = function () {
  function DataFactory() {
    _classCallCheck(this, DataFactory);
  }

  _createClass(DataFactory, [{
    key: 'createDatasource',
    value: function createDatasource(url, pagesize, callback) {
      console.log('agtable data ajax run this...........');
      var datasource = {
        pageSize: pagesize,
        getRows: function getRows(params) {
          // const URL = `${}?size=${pagesize}&page=${params.endRow / pagesize}`
          fetch(URL).then(function (response) {
            if (response.status !== 200) {
              console.error('error');
              return;
            }
            return response.json();
          }).then(function (json) {
            if (json) {
              return json.body;
            }
          }).then(function (data) {
            if (data) {
              var rowsThisPage = data.items;
              var lastRow = -1;
              lastRow = data.pageInfo.total;
              callback(data.pageInfo.total, data.pageInfo.pages);
              document.querySelector('#current').onfocus = function (e) {
                var currentVal = e.target.value;
                var reg = /^\+?[1-9][0-9]*$/;
                e.target.onblur = function (e) {
                  if (!reg.test(e.target.value)) {
                    e.target.value = currentVal;
                  }
                };
              };
              params.successCallback(rowsThisPage, lastRow);
            }
          }).catch(function (err) {
            console.error(err);
            params.failCallback();
          });
        }
      };

      return datasource;
    }
  }]);

  return DataFactory;
}();

exports.default = DataFactory;


text:
	Main Concepts
	Forms - FormControl and FormGroup

		In this sample, we are using a formControl directive in our input field

		This control is bound to the detailsControl property in our component (typed FormControl)

		Controls are typically used to check that a field is valid and do something when it is not

		Controls also add these properties to fields:

				The element itself and so its value

				The valid (!invalid) attribute which is
				false if a validator has failed

				The pristine (!dirty) attribute which is true if
				the field has not been modified

				touched (!untouched) :
				if the input field has been focused

		When a property is true, a corresponding css class is added:
		ng-touched, ng-untouched
		ng-dirty, ng-pristine
		ng-valid, ng-invalid

<editor [ng2]="true" [plunker]="true" description="Using forms">
    <editortab title="app/app.component.ts" fileType="js" ngNonBindable>
import {Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MyFormCmp} from 'app/my-form.component';

@Component({
    selector: 'app',
    template: '<my-form-cmp></my-form-cmp>'
})
export class App {}

export const ModuleDefs= {
	bootstrap: [App],
	imports: [BrowserModule, FormsModule, ReactiveFormsModule],
	declarations: [App, MyFormCmp]
}
    </editortab>
    <editortab title="app/my-form.component.ts" fileType="js">
import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

enum TodoCategory{PRIVATE, PERSO};

class TodoModel{
	constructor(public category: TodoCategory, public details: string){}
}

@Component({
	selector:'my-form-cmp',
	templateUrl:'app/my-form.html'
})
export class MyFormCmp{
	categories: string[]= Object.keys(TodoCategory).filter(v => isNaN(parseInt(v, 10)));
	model: TodoModel= new TodoModel();

	detailsControl= new FormControl('', Validators.required);

	isSubmit: false;

	onSubmit(m){
	  	this.m = m;
		this.isSubmit= true;
	}
}
	</editortab>
    <editortab title="app/my-form.html" fileType="html" ngNonBindable>
<h1>Add an element to your todo list</h1>

<form (ngSubmit)="onSubmit(catForm.value)" #catForm="ngForm" >
	<p>
	    <label for="category">
			Category
		</label>
		<select name="category" [(ngModel)]="model.category" id="category" required>
			<option *ngFor="let category of categories" [value]="category">{{category}}</option>
		</select>
	</p>
	<p>
	    <label for="todoDetails">Content</label>
	    <input
	      name="details"
	      [(ngModel)]="model.details"
	      [formControl]="detailsControl"
	      #currentElt
	    >
	    <span *ngIf="!detailsControl.valid">Miss data here</span>
	</p>
	<button type="submit">Submit</button>
</form>

<p>
  {{currentElt.classList}}
</p>

<p *ngIf="isSubmit">
	Form submited <br/>
	Model {{model.category}} : {{model.details}} <br/>
	Model from ngSubmit {{m.category}} : {{m.details}}
</p>

<p *ngIf="!isSubmit">
	Model {{model.category}} : {{model.details}}
</p>
    </editortab>
</editor>


text:
<?php

namespace App\Http\Controllers;

use App\Task;
use Illuminate\Http\Request;
use App\Transformers\TaskTransformer;

class TaskController extends Controller
{
    protected $transformer;

    public function __construct(TaskTransformer $transformer)
    {
        $this->transformer = $transformer;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return fractal(Task::all(), $this->transformer)->respond();
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string',
            'description' => 'required'
        ]);

        $task = Task::create($request->only('name', 'description', 'completed_flag'));

        return fractal($task, $this->transformer)->respond(201);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Task  $task
     * @return \Illuminate\Http\Response
     */
    public function show(Task $task)
    {
        return fractal($task, $this->transformer)->respond();
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Task  $task
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Task $task)
    {
        $this->validate($request, [
            'name' => 'required|string',
            'description' => 'required'
        ]);

        $task->update($request->only('name', 'description', 'completed_flag'));

        return fractal($task, $this->transformer)->respond();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Task  $task
     * @return \Illuminate\Http\Response
     */
    public function destroy(Task $task)
    {
        $task->delete();

        return fractal($task, $this->transformer)->respond();
    }
}


text:
%% MASSEF.execute
% Run MASSEF using input mixtures and separators.
%
%% Syntax
%
%   massef.execute(mixtures,separators)
%   massef.execute(mixtures)
%
% |massef.execute(mixtures,separators)| runs the multichannel audio source
% separation evaluation framework (MASSEF) using the <help_MASSEF.html
% MASSEF> instance |massef|, the array of <matlab:doc('iosr.bss.mixture')
% |iosr.bss.mixture|> objects |mixtures| and the array (or cell array) of
% instances of separation algorithms contained in |separators|. Separation
% is performed for all combinations of separators and mixtures. The
% separation algorithm instances contained in |separators| should conform
% to the <help_Separators.html required format>.
%
% The |execute| method performs evaluations of the algorithm according to
% the data returned by the algorithm, and the options provided to
% <help_MASSEF.html MASSEF>.
%
% If the separation algorithm returns a signal, then |MASSEF.execute|
% evaluates:
%
% * signal-to-noise ratio (SNR);
% * signal-to-ideal-noise ratio (SINR) (the SNR with respect to the signal
% reconstructed using the ideal binary and ratio masks).
%
% In addition, if |evalPEASS| is true, then PEASS and BSSeval evaluation is
% performed. If |evalSTOI| is true, then STOI evaluation is performed.
%
% If the separation algorithm returns a mask, and if the ideal mask
% dimensions match the estimated mask dimensions, then |MASSEF.execute|
% evaluates:
%
% * ideal mask ratio (IMR) with respect to the ideal binary and ratio
% masks.
%
% If the separation algorithm returns a mask but no signals, then MASSEF
% attempts to calculate the estimate signal in order to calculate the
% signal-related metrics mentioned above.
%
% The |execute| method also calculates and evaluates the ideal binary and
% ratio masks using the signal-related metrics utilised for the algorithm
% evaluation. The masks are calculated using the settings that are local to
% each <matlab:doc('iosr.bss.mixture') |iosr.bss.mixture|> object.
%
% Lastly, the framework captures the estimated azimuth and elevation of the
% targets and interferer(s), if they are returned.
%
% Once the evaluation is complete, the <help_MASSEF.html MASSEF> object,
% which contains the results data in |MASSEF.results| as a
% <help_MASSEFresults.html MASSEFresults> object, is saved to the file
% given by |MASSEF.results_filename|. The separation and mixture objects
% are also saved.
%
% |massef.execute(mixtures)| evaluates only the ideal masks.
%
%% See also
% <help_MASSEF.html MASSEF>, <help_MASSEF_evaluate.html MASSEF.evaluate>,
% <help_MASSEFresults.html MASSEFresults>,
% <matlab:doc('iosr.bss.generateMixtures') iosr.bss.generateMixtures>,
% <matlab:doc('iosr.bss.resynthesise') iosr.bss.resynthesise>.
%
%
%

%
Copyright © 2017 University of Surrey

% Institute of Sound Recording, University of Surrey, UK

%


text:
package de.espend.idea.php.annotation.util;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.jetbrains.php.lang.psi.PhpPsiElementFactory;
import com.jetbrains.php.lang.psi.elements.PhpUseList;
import com.jetbrains.php.util.PhpContractUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 */
public class PhpPsiElementFactoryCompatible {

    @NotNull
    public static PhpUseList createUseStatementWithKeyword(@NotNull Project project, @Nullable String keyword, @NotNull String fqn, @Nullable String alias) {

        PhpContractUtil.assertFqn(fqn);
        PhpContractUtil.assertNoQualifier(alias);

        StringBuilder builder = new StringBuilder("<?php\nuse ");
        if (StringUtil.isNotEmpty(keyword)) {
            builder.append(keyword).append(" ");
        }
        builder.append(StringUtil.trimStart(fqn, "\\"));
        if (StringUtil.isNotEmpty(alias)) {
            builder.append(" as ").append(alias);
        }
        builder.append(";\n");

        return PhpPsiElementFactory.createFromText(project, PhpUseList.class, builder.toString());

    }

}


text:
package org.estatio.dom.budget;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

import org.apache.isis.applib.query.Query;
import org.apache.isis.core.commons.matchers.IsisMatchers;

import org.estatio.dom.FinderInteraction;
import org.estatio.dom.asset.Property;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

/**
 * Created by jodo on 30/04/15.
 */
public class BudgetKeytablesTest {

    FinderInteraction finderInteraction;

    BudgetKeyTables budgetKeyTables;

    @Before
    public void setup() {
        budgetKeyTables = new BudgetKeyTables() {

            @Override
            protected <T> T firstMatch(Query<T> query) {
                finderInteraction = new FinderInteraction(query, FinderInteraction.FinderMethod.FIRST_MATCH);
                return null;
            }

            @Override
            protected List<BudgetKeyTable> allInstances() {
                finderInteraction = new FinderInteraction(null, FinderInteraction.FinderMethod.ALL_INSTANCES);
                return null;
            }

            @Override
            protected <T> List<T> allMatches(Query<T> query) {
                finderInteraction = new FinderInteraction(query, FinderInteraction.FinderMethod.ALL_MATCHES);
                return null;
            }
        };
    }

    public static class findBudgetKeyTableByName extends BudgetKeytablesTest {

        @Test
        public void happyCase() {

            budgetKeyTables.findBudgetKeyTableByName("name");

            assertThat(finderInteraction.getFinderMethod(), is(FinderInteraction.FinderMethod.FIRST_MATCH));
            assertThat(finderInteraction.getResultType(), IsisMatchers.classEqualTo(BudgetKeyTable.class));
            assertThat(finderInteraction.getQueryName(), is("findBudgetKeyTableByName"));
            assertThat(finderInteraction.getArgumentsByParameterName().get("name"), is((Object) "name"));
            assertThat(finderInteraction.getArgumentsByParameterName().size(), is(1));
        }

        @Test
         public void anotherHappyCase() {

            Property property = new PropertyForTesting();
            budgetKeyTables.findBudgetKeyTableByProperty(property);

            assertThat(finderInteraction.getFinderMethod(), is(FinderInteraction.FinderMethod.ALL_MATCHES));
            assertThat(finderInteraction.getResultType(), IsisMatchers.classEqualTo(BudgetKeyTable.class));
            assertThat(finderInteraction.getQueryName(), is("findByProperty"));
            assertThat(finderInteraction.getArgumentsByParameterName().get("property"), is((Object) property));
            assertThat(finderInteraction.getArgumentsByParameterName().size(), is(1));
        }

    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using LinqToDB.Mapping;

namespace WebAddressbookTests
{
    [Table(Name = "addressbook")]
    public class ContactData : IEquatable<ContactData>, IComparable<ContactData>
    {
        private string allPhones;
        private string allInformation;
        private string allEmails;

        public ContactData()
        {
        }

        public ContactData(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }

        public bool Equals(ContactData other)
        {
            if (Object.ReferenceEquals(other, null))
            {
                return false;
            }
            if (Object.ReferenceEquals(this, other))
            {
                return true;
            }
            return FirstName == other.FirstName && LastName == other.LastName;
        }

        public override int GetHashCode()
        {
            return FirstName.GetHashCode() + LastName.GetHashCode();
        }

        public override string ToString()
        {
            return "FirstName = " + FirstName + "\nLastName = " + LastName;
        }

        public int CompareTo(ContactData other)
        {
            if (Object.ReferenceEquals(other, null))
            {
                return 1;
            }
            var fullNameThis = LastName + FirstName;
            var fullNameOther = other.LastName + other.FirstName;

            return fullNameThis.CompareTo(fullNameOther);
        }

        [Column(Name = "firstname")]
        public string FirstName { get; set; }

        [Column(Name = "lastname")]
        public string LastName { get; set; }

        public string Address { get; set; }

        public string HomePhone { get; set; }

        public string MobilePhone { get; set; }

        public string WorkPhone { get; set; }

        public string Email { get; set; }

        public string Email2 { get; set; }

        public string Email3 { get; set; }

        [Column(Name = "id"), PrimaryKey, Identity]
        public string Id { get; set; }

        [Column(Name = "deprecated")]
        public string Deprecated { get; set; }

        public static List<ContactData> GetAll()
        {
            using (AddressBookDB db = new AddressBookDB())
            {
                List<ContactData> list = new List<ContactData>();
                list = (from g in db.Contacts
                        where g.Deprecated == "0000-00-00 00:00:00"
                        select g).ToList();
                return list;
            }
        }

        public string AllPhones
        {
            get
            {
                if (allPhones != null)
                {
                    return allPhones;
                }
                else
                {
                    return (CleanUp(HomePhone) + CleanUp(MobilePhone) + CleanUp(WorkPhone)).Trim();
                }
            }
            set
            {
                allPhones = value;
            }
        }

        public string AllInformation
        {
            get
            {
                if (allInformation != null)
                {
                    return allInformation;
                }
                else
                {
                    var name = FirstName + " " + LastName + "\r\n";

                    string address = null;
                    if (Address != "")
                    {
                        address += Address + "\r\n";
                    }
                    address += "\r\n";

                    var phones = PhonesForProperties();
                    var emails = EmailsForProperties();

                    var contact = (name + address + phones + emails).Trim();
                    return contact;
                }
            }
            set
            {
                allInformation = value;
            }
        }

        public string AllEmails
        {
            get
            {
                if (allEmails != null)
                {
                    return allEmails;
                }
                else
                {
                    var emails = "";
                    emails = Email + Email2 + Email2;
                    return emails;
                }
            }
            set
            {
                allEmails = value;
            }
        }

        private string CleanUp(string phone)
        {
            if (phone == null || phone == "")
            {
                return "";
            }
            return Regex.Replace(phone, "[() -]", "") + "\r\n";
        }

        public string EmailsForProperties()
        {
            string emails = null;
            if (Email != "")
            {
                emails += Email + "\r\n";
            }
            if (Email2 != "")
            {
                emails += Email2 + "\r\n";
            }
            if (Email3 != "")
            {
                emails += Email3 + "\r\n";
            }
            return emails;
        }

        public string PhonesForProperties()
        {
            string phones = null;
            if (HomePhone == "" && MobilePhone == "" && WorkPhone == "")
            {
                return phones;
            }

            if (HomePhone != "")
            {
                phones += "H: " + HomePhone + "\r\n";
            }
            if (MobilePhone != "")
            {
                phones += "M: " + MobilePhone + "\r\n";
            }
            if (WorkPhone != "")
            {
                phones += "W: " + WorkPhone + "\r\n";
            }
            return phones + "\r\n";
        }

        public List<GroupData> GetGroups()
        {
            using (AddressBookDB db = new AddressBookDB())
            {
                return (from c in db.Groups
                        from gcr in db.GCR.Where(p => p.ContactId == Id && p.GroupId == c.Id)
                        select c).Distinct().ToList();
            }
        }
    }
}


text: a = b <selection>+ func()</selection>


text:
<?php

namespace app\models\b2b2c\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\b2b2c\ReturnApply;

/**
 * ReturnApplySearch represents the model behind the search form about `app\models\b2b2c\ReturnApply`.
 */
class ReturnApplySearch extends ReturnApply
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'sheet_type_id', 'vip_id', 'order_id', 'status'], 'integer'],
            [['apply_date', 'reason', 'code'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ReturnApply::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            //'pagination' => ['pagesize' => '15',],

        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'sheet_type_id' => $this->sheet_type_id,
            'apply_date' => $this->apply_date,
            'vip_id' => $this->vip_id,
            'order_id' => $this->order_id,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'reason', $this->reason])
            ->andFilterWhere(['like', 'code', $this->code]);

        return $dataProvider;
    }
}


text:
using llvm::raw_ostream;
using llvm::Record;
using llvm::RecordKeeper;
using llvm::StringRef;
using mlir::tblgen::StructAttr;

static void
emitStructClass(const Record &structDef, StringRef structName,
                llvm::ArrayRef<mlir::tblgen::StructFieldAttr> fields,
                StringRef description, raw_ostream &os) {
  const char *structInfo = R"(
// {0}
class {1} : public mlir::DictionaryAttr)";
  const char *structInfoEnd = R"( {
public:
  using DictionaryAttr::DictionaryAttr;
  static bool classof(mlir::Attribute attr);
)";
  os << formatv(structInfo, description, structName) << structInfoEnd;

  // Declares a constructor function for the tablegen structure.
  //   TblgenStruct::get(MLIRContext context, Type1 Field1, Type2 Field2, ...);
  const char *getInfoDecl = "  static {0} get(\n";
  const char *getInfoDeclArg = "      {0} {1},\n";
  const char *getInfoDeclEnd = "      mlir::MLIRContext* context);\n\n";

  os << llvm::formatv(getInfoDecl, structName);

  for (auto field : fields) {
    auto name = field.getName();
    auto type = field.getType();
    auto storage = type.getStorageType();
    os << llvm::formatv(getInfoDeclArg, storage, name);
  }
  os << getInfoDeclEnd;

  // Declares an accessor for the fields owned by the tablegen structure.
  //   namespace::storage TblgenStruct::field1() const;
  const char *fieldInfo = R"(  {0} {1}() const;
)";
  for (const auto field : fields) {
    auto name = field.getName();
    auto type = field.getType();
    auto storage = type.getStorageType();
    os << formatv(fieldInfo, storage, name);
  }

  os << "};\n\n";
}

static void emitStructDecl(const Record &structDef, raw_ostream &os) {
  StructAttr structAttr(&structDef);
  StringRef structName = structAttr.getStructClassName();
  StringRef cppNamespace = structAttr.getCppNamespace();
  StringRef description = structAttr.getDescription();
  auto fields = structAttr.getAllFields();

  // Wrap in the appropriate namespace.
  llvm::SmallVector<StringRef, 2> namespaces;
  llvm::SplitString(cppNamespace, namespaces, "::");

  for (auto ns : namespaces)
    os << "namespace " << ns << " {\n";

  // Emit the struct class definition
  emitStructClass(structDef, structName, fields, description, os);

  // Close the declared namespace.
  for (auto ns : namespaces)
    os << "} // namespace " << ns << "\n";
}

static bool emitStructDecls(const RecordKeeper &recordKeeper, raw_ostream &os) {
  llvm::emitSourceFileHeader("Struct Utility Declarations", os);

  auto defs = recordKeeper.getAllDerivedDefinitions("StructAttr");
  for (const auto *def : defs) {
    emitStructDecl(*def, os);
  }

  return false;
}

static void emitFactoryDef(llvm::StringRef structName,
                           llvm::ArrayRef<mlir::tblgen::StructFieldAttr> fields,
                           raw_ostream &os) {
  const char *getInfoDecl = "{0} {0}::get(\n";
  const char *getInfoDeclArg = "    {0} {1},\n";
  const char *getInfoDeclEnd = "    mlir::MLIRContext* context) {";

  os << llvm::formatv(getInfoDecl, structName);

  for (auto field : fields) {
    auto name = field.getName();
    auto type = field.getType();
    auto storage = type.getStorageType();
    os << llvm::formatv(getInfoDeclArg, storage, name);
  }
  os << getInfoDeclEnd;

  const char *fieldStart = R"(
  llvm::SmallVector<mlir::NamedAttribute, {0}> fields;
)";
  os << llvm::formatv(fieldStart, fields.size());

  const char *getFieldInfo = R"(
  assert({0});
  auto {0}_id = mlir::Identifier::get("{0}", context);
  fields.emplace_back({0}_id, {0});
)";

  for (auto field : fields) {
    os << llvm::formatv(getFieldInfo, field.getName());
  }

  const char *getEndInfo = R"(
  Attribute dict = mlir::DictionaryAttr::get(fields, context);
  return dict.dyn_cast<{0}>();
}
)";
  os << llvm::formatv(getEndInfo, structName);
}

static void emitClassofDef(llvm::StringRef structName,
                           llvm::ArrayRef<mlir::tblgen::StructFieldAttr> fields,
                           raw_ostream &os) {
  const char *classofInfo = R"(
bool {0}::classof(mlir::Attribute attr))";

  const char *classofInfoHeader = R"(
   auto derived = attr.dyn_cast<mlir::DictionaryAttr>();
   if (!derived)
     return false;
   if (derived.size() != {0})
     return false;
)";

  os << llvm::formatv(classofInfo, structName) << " {";
  os << llvm::formatv(classofInfoHeader, fields.size());

  const char *classofArgInfo = R"(
  auto {0} = derived.get("{0}");
  if (!{0} || !{0}.isa<{1}>())
    return false;
)";
  for (auto field : fields) {
    auto name = field.getName();
    auto type = field.getType();
    auto storage = type.getStorageType();
    os << llvm::formatv(classofArgInfo, name, storage);
  }

  const char *classofEndInfo = R"(
  return true;
}
)";
  os << classofEndInfo;
}

static void
emitAccessorDef(llvm::StringRef structName,
                llvm::ArrayRef<mlir::tblgen::StructFieldAttr> fields,
                raw_ostream &os) {
  const char *fieldInfo = R"(
{0} {2}::{1}() const {
  auto derived = this->cast<mlir::DictionaryAttr>();
  auto {1} = derived.get("{1}");
  assert({1} && "attribute not found.");
  assert({1}.isa<{0}>() && "incorrect Attribute type found.");
  return {1}.cast<{0}>();
}
)";
  for (auto field : fields) {
    auto name = field.getName();
    auto type = field.getType();
    auto storage = type.getStorageType();
    os << llvm::formatv(fieldInfo, storage, name, structName);
  }
}

static void emitStructDef(const Record &structDef, raw_ostream &os) {
  StructAttr structAttr(&structDef);
  StringRef cppNamespace = structAttr.getCppNamespace();
  StringRef structName = structAttr.getStructClassName();
  mlir::tblgen::FmtContext ctx;
  auto fields = structAttr.getAllFields();

  llvm::SmallVector<StringRef, 2> namespaces;
  llvm::SplitString(cppNamespace, namespaces, "::");

  for (auto ns : namespaces)
    os << "namespace " << ns << " {\n";

  emitFactoryDef(structName, fields, os);
  emitClassofDef(structName, fields, os);
  emitAccessorDef(structName, fields, os);

  for (auto ns : llvm::reverse(namespaces))
    os << "} // namespace " << ns << "\n";
}

static bool emitStructDefs(const RecordKeeper &recordKeeper, raw_ostream &os) {
  llvm::emitSourceFileHeader("Struct Utility Definitions", os);

  auto defs = recordKeeper.getAllDerivedDefinitions("StructAttr");
  for (const auto *def : defs)
    emitStructDef(*def, os);

  return false;
}

// Registers the struct utility generator to mlir-tblgen.
static mlir::GenRegistration
    genStructDecls("gen-struct-attr-decls",
                   "Generate struct utility declarations",
                   [](const RecordKeeper &records, raw_ostream &os) {
                     return emitStructDecls(records, os);
                   });

// Registers the struct utility generator to mlir-tblgen.
static mlir::GenRegistration
    genStructDefs("gen-struct-attr-defs", "Generate struct utility definitions",
                  [](const RecordKeeper &records, raw_ostream &os) {
                    return emitStructDefs(records, os);
                  });


text:
#include <config.h>

#include "seq.h"

#include <stdbool.h>

#include "hash.h"
#include "hmap.h"
#include "latch.h"
#include "list.h"
#include "ovs-thread.h"
#include "poll-loop.h"

/* A sequence number object. */
struct seq {
    uint64_t value OVS_GUARDED;
    struct hmap waiters OVS_GUARDED; /* Contains 'struct seq_waiter's. */
};

/* A thread waiting on a particular seq. */
struct seq_waiter {
    struct seq *seq OVS_GUARDED;            /* Seq being waited for. */
    struct hmap_node hmap_node OVS_GUARDED; /* In 'seq->waiters'. */
    unsigned int ovsthread_id OVS_GUARDED;  /* Key in 'waiters' hmap. */

    struct seq_thread *thread OVS_GUARDED; /* Thread preparing to wait. */
    struct list list_node OVS_GUARDED;     /* In 'thread->waiters'. */

    uint64_t value OVS_GUARDED; /* seq->value we're waiting to change. */
};

/* A thread that might be waiting on one or more seqs. */
struct seq_thread {
    struct list waiters OVS_GUARDED; /* Contains 'struct seq_waiter's. */
    struct latch latch OVS_GUARDED;  /* Wakeup latch for this thread. */
    bool waiting OVS_GUARDED;        /* True if latch_wait() already called. */
};

static struct ovs_mutex seq_mutex = OVS_MUTEX_INITIALIZER;

static uint64_t seq_next OVS_GUARDED_BY(seq_mutex) = 1;

static pthread_key_t seq_thread_key;

static void seq_init(void);
static struct seq_thread *seq_thread_get(void) OVS_REQUIRES(seq_mutex);
static void seq_thread_exit(void *thread_) OVS_EXCLUDED(seq_mutex);
static void seq_thread_woke(struct seq_thread *) OVS_REQUIRES(seq_mutex);
static void seq_waiter_destroy(struct seq_waiter *) OVS_REQUIRES(seq_mutex);
static void seq_wake_waiters(struct seq *) OVS_REQUIRES(seq_mutex);

/* Creates and returns a new 'seq' object. */
struct seq * OVS_EXCLUDED(seq_mutex)
seq_create(void)
{
    struct seq *seq;

    seq_init();

    seq = xmalloc(sizeof *seq);
    ovs_mutex_lock(&seq_mutex);
    seq->value = seq_next++;
    hmap_init(&seq->waiters);
    ovs_mutex_unlock(&seq_mutex);

    return seq;
}

/* Destroys 'seq', waking up threads that were waiting on it, if any. */
void
seq_destroy(struct seq *seq)
     OVS_EXCLUDED(seq_mutex)
{
    ovs_mutex_lock(&seq_mutex);
    seq_wake_waiters(seq);
    hmap_destroy(&seq->waiters);
    free(seq);
    ovs_mutex_unlock(&seq_mutex);
}

/* Increments 'seq''s sequence number, waking up any threads that are waiting
 * on 'seq'. */
void
seq_change(struct seq *seq)
    OVS_EXCLUDED(seq_mutex)
{
    ovs_mutex_lock(&seq_mutex);
    seq->value = seq_next++;
    seq_wake_waiters(seq);
    ovs_mutex_unlock(&seq_mutex);
}

/* Returns 'seq''s current sequence number (which could change immediately).
 *
 * seq_read() and seq_wait() can be used together to yield a race-free wakeup
 * when an object changes, even without an ability to lock the object.  See
 * Usage in seq.h for details. */
uint64_t
seq_read(const struct seq *seq)
    OVS_EXCLUDED(seq_mutex)
{
    uint64_t value;

    ovs_mutex_lock(&seq_mutex);
    value = seq->value;
    ovs_mutex_unlock(&seq_mutex);

    return value;
}

static void
seq_wait__(struct seq *seq, uint64_t value)
    OVS_REQUIRES(seq_mutex)
{
    unsigned int id = ovsthread_id_self();
    uint32_t hash = hash_int(id, 0);
    struct seq_waiter *waiter;

    HMAP_FOR_EACH_IN_BUCKET (waiter, hmap_node, hash, &seq->waiters) {
        if (waiter->ovsthread_id == id) {
            if (waiter->value != value) {
                /* The current value is different from the value we've already
                 * waited for, */
                poll_immediate_wake();
            } else {
                /* Already waiting on 'value', nothing more to do. */
            }
            return;
        }
    }

    waiter = xmalloc(sizeof *waiter);
    waiter->seq = seq;
    hmap_insert(&seq->waiters, &waiter->hmap_node, hash);
    waiter->ovsthread_id = id;
    waiter->value = value;
    waiter->thread = seq_thread_get();
    list_push_back(&waiter->thread->waiters, &waiter->list_node);

    if (!waiter->thread->waiting) {
        latch_wait(&waiter->thread->latch);
        waiter->thread->waiting = true;
    }
}

/* Causes the following poll_block() to wake up when 'seq''s sequence number
 * changes from 'value'.  (If 'seq''s sequence number isn't 'value', then
 * poll_block() won't block at all.)
 *
 * seq_read() and seq_wait() can be used together to yield a race-free wakeup
 * when an object changes, even without an ability to lock the object.  See
 * Usage in seq.h for details. */
void
seq_wait(const struct seq *seq_, uint64_t value)
    OVS_EXCLUDED(seq_mutex)
{
    struct seq *seq = CONST_CAST(struct seq *, seq_);

    ovs_mutex_lock(&seq_mutex);
    if (value == seq->value) {
        seq_wait__(seq, value);
    } else {
        poll_immediate_wake();
    }
    ovs_mutex_unlock(&seq_mutex);
}

/* Called by poll_block() just before it returns, this function destroys any
 * seq_waiter objects associated with the current thread. */
void
seq_woke(void)
    OVS_EXCLUDED(seq_mutex)
{
    struct seq_thread *thread;

    seq_init();

    thread = pthread_getspecific(seq_thread_key);
    if (thread) {
        ovs_mutex_lock(&seq_mutex);
        seq_thread_woke(thread);
        thread->waiting = false;
        ovs_mutex_unlock(&seq_mutex);
    }
}

static void
seq_init(void)
{
    static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;

    if (ovsthread_once_start(&once)) {
        xpthread_key_create(&seq_thread_key, seq_thread_exit);
        ovsthread_once_done(&once);
    }
}

static struct seq_thread *
seq_thread_get(void)
    OVS_REQUIRES(seq_mutex)
{
    struct seq_thread *thread = pthread_getspecific(seq_thread_key);
    if (!thread) {
        thread = xmalloc(sizeof *thread);
        list_init(&thread->waiters);
        latch_init(&thread->latch);
        thread->waiting = false;

        xpthread_setspecific(seq_thread_key, thread);
    }
    return thread;
}

static void
seq_thread_exit(void *thread_)
    OVS_EXCLUDED(seq_mutex)
{
    struct seq_thread *thread = thread_;

    ovs_mutex_lock(&seq_mutex);
    seq_thread_woke(thread);
    latch_destroy(&thread->latch);
    free(thread);
    ovs_mutex_unlock(&seq_mutex);
}

static void
seq_thread_woke(struct seq_thread *thread)
    OVS_REQUIRES(seq_mutex)
{
    struct seq_waiter *waiter, *next_waiter;

    LIST_FOR_EACH_SAFE (waiter, next_waiter, list_node, &thread->waiters) {
        ovs_assert(waiter->thread == thread);
        seq_waiter_destroy(waiter);
    }
    latch_poll(&thread->latch);
}

static void
seq_waiter_destroy(struct seq_waiter *waiter)
    OVS_REQUIRES(seq_mutex)
{
    hmap_remove(&waiter->seq->waiters, &waiter->hmap_node);
    list_remove(&waiter->list_node);
    free(waiter);
}

static void
seq_wake_waiters(struct seq *seq)
    OVS_REQUIRES(seq_mutex)
{
    struct seq_waiter *waiter, *next_waiter;

    HMAP_FOR_EACH_SAFE (waiter, next_waiter, hmap_node, &seq->waiters) {
        latch_set(&waiter->thread->latch);
        seq_waiter_destroy(waiter);
    }
}


text:
package com.bernardomg.tabletop.dreadball.model.persistence.player;

import java.io.Serializable;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;

/**
 * Root for the basic features all the Dreadball players have, no matter if they
 * come from Dreadball Original (DBO) or Dreadball Xtreme (DBX).
 * <p>
 * This is a persistent JPA-Based implementation.
 *
 * @author Bernardo Martínez Garrido
 */
@Entity(name = "Player")
@DiscriminatorValue("simple")
@Table(name = "SIMPLE_PLAYERS")
public class PersistentTeamPlayer extends AbstractPersistentTeamPlayer
        implements Serializable {

    /**
     * Serialization ID.
     */
    private static final long serialVersionUID = -6317901977987115397L;

    /**
     * Default constructor.
     */
    public PersistentTeamPlayer() {
        super();
    }

}


text:
var ffmpeg = require('../index');

// make sure you set the correct path to your video file
var proc = new ffmpeg({ source: '/path/to/your_movie.avi', nolog: true })
  // set video bitrate
  .withVideoBitrate(1024)
  // set target codec
  .withVideoCodec('divx')
  // set aspect ratio
  .withAspect('16:9')
  // set size in percent
  .withSize('50%')
  // set fps
  .withFps(24)
  // set audio bitrate
  .withAudioBitrate('128k')
  // set audio codec
  .withAudioCodec('libmp3lame')
  // set number of audio channels
  .withAudioChannels(2)
  // set custom option
  .addOption('-vtag', 'DIVX')
  // set output format to force
  .toFormat('avi')
  // save to file
  .saveToFile('/path/to/your_target.avi', function(retcode, error){
    console.log('file has been converted succesfully');
  });


text:
using namespace igloo;

class NullTestResultsOutput : public TestResultsOutput
{
    public:
      void PrintResult(const TestResults&) const
      {
      }
};

class FakeTestListener : public TestListener
{
  public:
    void TestRunStarting()
    {
      callLog += "TestRunStarting\n";
    }

    void TestRunEnded(const TestResults& results)
    {
      std::stringstream stm;
      stm << "TestRunEnded called with " << results.NumberOfTestsRun() << " tests run" << std::endl;
      callLog += stm.str();
    }

    void ContextRunStarting(const ContextBase& context)
    {
      std::stringstream stm;
      stm << "ContextRunStarting called for context '" << context.Name() << "'" << std::endl;
      stm << "ContextRunStarting called with attribute '" << context.GetAttribute("attribute name") << "'" << std::endl;
      callLog += stm.str();
    }

    void ContextRunEnded(const ContextBase& context)
    {
      std::stringstream stm;
      stm << "ContextRunEnded called for context '" << context.Name() << "'" << std::endl;
      stm << "ContextRunEnded called with attribute '" << context.GetAttribute("attribute name") << "'" << std::endl;
      callLog += stm.str();
    }

    void SpecRunStarting(const ContextBase& context, const std::string& name)
    {
      std::stringstream stm;
      stm << "SpecRunStarting called for context '" << context.Name() << "' and spec '" << name << "'" << std::endl;
      callLog += stm.str();
    }

    void SpecSucceeded(const ContextBase& context, const std::string& name)
    {
      std::stringstream stm;
      stm << "SpecSucceeded called for context '" << context.Name() << "' and spec '" << name << "'" << std::endl;
      callLog += stm.str();
    }

    void SpecFailed(const ContextBase& context, const std::string& name)
    {
      std::stringstream stm;
      stm << "SpecFailed called for context '" << context.Name() << "' and spec '" << name << "'" << std::endl;
      callLog += stm.str();
    }

    std::string callLog;
};

class FakeContextRunner : public BaseContextRunner
{
  public:
    FakeContextRunner() : BaseContextRunner("ContextName") {}
    virtual void RunContext(TestResults& results, TestListener&) const
    {
      TestResultFactory factory(ContextName(), "SpecName");
      results.AddResult(factory.CreateSuccessful());
    }
};

Context(registering_a_test_listener)
{
  NullTestResultsOutput nullOutput;
  std::auto_ptr<TestRunner> runner;
  TestRunner::ContextRunners contextRunners;
  FakeTestListener listener;
  FakeContextRunner contextRunner;

  void SetUp()
  {
    runner = std::auto_ptr<TestRunner>(new TestRunner(nullOutput));
    runner->AddListener(&listener);

    contextRunners.push_back(&contextRunner);
  }

  Spec(a_callback_is_made_when_the_test_run_starts)
  {
    runner->Run(contextRunners);

    AssertThat(listener.callLog, Has().Exactly(1).EqualTo("TestRunStarting"));
  }

  Spec(a_callback_is_made_when_the_test_run_ends)
  {
    runner->Run(contextRunners);

    AssertThat(listener.callLog, Has().Exactly(1).EqualTo("TestRunEnded called with 1 tests run"));
  }
};

Context(a_registered_context)
{
  struct ContextToRun : public ContextProvider<ContextToRun, ContextWithAttribute<void> >
  {
    ContextAttribute("attribute name", "attribute value")

    Spec(SucceedingSpec)
    {
      Assert::That(true);
    }

    Spec(FailingSpec)
    {
      Assert::That(false);
    }
  };

  void SetUp()
  {
    ContextRegistry<ContextToRun>::RegisterSpec("SucceedingSpec", &ContextToRun::SucceedingSpec);
    ContextRegistry<ContextToRun>::Run<ContextToRun>("ContextToRun", testResults, testListener);
  }

  void TearDown()
  {
    ContextRegistry<ContextToRun>::ClearRegisteredSpecs();
  }

  Spec(ContextRunStarting_is_called)
  {
    AssertThat(testListener.callLog, Has().Exactly(1).EqualTo("ContextRunStarting called for context 'ContextToRun'"));
  }

  Spec(ContextRunStarting_is_called_with_attribute)
  {
    AssertThat(testListener.callLog, Has().Exactly(1).EqualTo("ContextRunStarting called with attribute 'attribute value'"));
  }

  Spec(ContextRunEnded_is_called)
  {
    AssertThat(testListener.callLog, Has().Exactly(1).EqualTo("ContextRunEnded called for context 'ContextToRun'"));
  }

  Spec(ContextRunEnded_is_called_with_attribute)
  {
    AssertThat(testListener.callLog, Has().Exactly(1).EqualTo("ContextRunEnded called with attribute 'attribute value'"));
  }

  Spec(SpecRunStarting_is_called)
  {
    AssertThat(testListener.callLog, Has().Exactly(1).EqualTo("SpecRunStarting called for context 'ContextToRun' and spec 'SucceedingSpec'"));
    AssertThat(testListener.callLog, Has().Exactly(1).EqualTo("SpecRunStarting called for context 'ContextToRun' and spec 'FailingSpec'"));
  }

  Spec(SpecSucceeded_is_called)
  {
    AssertThat(testListener.callLog, Has().Exactly(1).EqualTo("SpecSucceeded called for context 'ContextToRun' and spec 'SucceedingSpec'"));
  }

  Spec(SpecFailed_is_called)
  {
    AssertThat(testListener.callLog, Has().Exactly(1).EqualTo("SpecFailed called for context 'ContextToRun' and spec 'FailingSpec'"));
  }

  FakeTestListener testListener;
  TestResults testResults;
};


text:
FROM y12docker/elasticsearch

ADD logstash.conf $LS_CONF
ADD logstash.sh $LS_SRV
RUN chmod +x $LS_SRV

ADD collectd.conf $CTD_CONF
ADD collectd.sh $CTD_SRV
RUN chmod +x $CTD_SRV

CMD ["/sbin/my_init"]


text:
module System.MIDI.Sync
  ( Beats, BPM, openSourceWithSync
  )
  where

--------------------------------------------------------------------------------

import Control.Monad
import Control.Concurrent
import Control.Concurrent.MVar

import System.MIDI

--------------------------------------------------------------------------------

-- | Song position measured in beats (that is, quarter notes), starting from zero.
-- So with 120 BPM, you will have song position 120 after one minute.
type Beats = Double

-- | Estimated BPM
type BPM = Double

oneTwentyFourth = 1/24 :: Double
lambda          = 0.05 :: Double  -- ad-hoc speed of bpm adjustement

-- | Opens a midi source with the possibility to sync to it.
--
-- The user callback gets the the song position in /beats/,
-- and also we return functions to query to song position and
-- the estimated BPM. You may want to round the BPM to the nearest
-- integer if that is appropriate. Song position is Nothing when
-- the playback is stopped.
--
-- Note that when first used, it may need some time to calibrate
-- the bpm correctly, so start your MIDI host, press play, and
-- wait a few second. Afterwards, it should be reasonably ok.
-- Also if you do fast realtime BPM changes,
-- it will be a tiny little bit behind.
--
-- Note that we forward all messages (including clock messages) to
-- the user, so you can implement your own handling of transport
-- (start/stop/continue) or send messages on clock if you want.
--
openSourceWithSync
  :: Source                                     -- ^ midi source
  -> (Maybe Beats -> MidiEvent -> IO ())        -- ^ user callback
  -> IO (Connection, IO (Maybe Beats), IO BPM)  -- ^ (connection, song_position, estimated_bpm)
openSourceWithSync src userCallback = do

  theLastPos   <- newMVar 0       :: IO (MVar Beats)      -- last song position
  theBpmEst    <- newMVar 120     :: IO (MVar BPM)        -- last bpm estimation
  thePlayFlag  <- newMVar False   :: IO (MVar Bool)       -- whether we are playing or stopped
  theLastClock <- newMVar 0       :: IO (MVar TimeStamp)  -- timestamp of last clock signal
  theLastQuery <- newMVar 0       :: IO (MVar Beats)      -- last queried pos

  let queryPos tstamp = do
        b <- readMVar thePlayFlag
        if b
          then do
            lastpos   <- readMVar theLastPos    -- song position at the last clock/start message
            bpm       <- readMVar theBpmEst     -- estimated bpm
            lastclock <- readMVar theLastClock  -- time of the last clock/start message
            let tdiff = fromIntegral (tstamp - lastclock) / 60000.0 :: Double   -- in minutes
            let newpos0 = lastpos + tdiff * bpm  -- extrapolate since last clock signal
            lastquery <- takeMVar theLastQuery
            let newpos = max lastquery newpos0   -- make it monotone in time (!)
            putMVar theLastQuery newpos
            return (Just newpos)
          else return Nothing

  let queryBPM = readMVar theBpmEst

  let handle (MidiEvent tstamp msg) = case msg of

        SongPosition midibeats -> do
          let pos = fromIntegral midibeats / 6
          replaceMVar theLastPos   pos
          replaceMVar theLastQuery pos

        SRTStart -> do
          replaceMVar theLastPos   0
          replaceMVar theLastQuery 0
          replaceMVar theLastClock tstamp
          replaceMVar thePlayFlag  True

        SRTStop     -> replaceMVar thePlayFlag False

        SRTContinue	-> do
          replaceMVar theLastClock tstamp
          replaceMVar thePlayFlag  True

        Reset -> do
          replaceMVar theLastPos   0
          replaceMVar theLastQuery 0
          replaceMVar thePlayFlag  False
          replaceMVar theBpmEst    120

        SRTClock -> do
          lastclock <- takeMVar theLastClock
          bpm       <- takeMVar theBpmEst
          lastpos   <- takeMVar theLastPos
          let lastpos' = lastpos + oneTwentyFourth
          let tdiff = fromIntegral (tstamp - lastclock) / 60000.0 :: Double   -- in minutes
          let bpm' = (1-lambda)*bpm + lambda*(oneTwentyFourth/tdiff)
          putMVar theLastClock tstamp
          putMVar theLastPos lastpos'
          putMVar theBpmEst  bpm'
          print (bpm',tdiff,1/24/tdiff)

        _ -> return ()

  let syncCallback event@(MidiEvent tstamp _) = do
        handle event
        mbpos <- queryPos tstamp
        userCallback mbpos event

  conn <- openSource src (Just syncCallback)
  return (conn, currentTime conn >>= queryPos, queryBPM)

--------------------------------------------------------------------------------

replaceMVar :: MVar a -> a -> IO ()
replaceMVar mv x = do
  _ <- tryTakeMVar mv
  putMVar mv x

--------------------------------------------------------------------------------


text:
package com.nvapp.mupdf;

public class OutlineItem {
	public final int    level;
	public final String title;
	public final int    page;

	OutlineItem(int _level, String _title, int _page) {
		level = _level;
		title = _title;
		page  = _page;
	}

}


text:
require 'rails_helper'

describe TeamRoom, "#index" do
  describe "when guest enters the team room" do
    it "raises Unauthenticated exception" do
      lambda do
        perform_request
      end.should raise_error(Merb::Controller::Unauthenticated)
    end
  end

  describe "when not a team member enters the team room" do
    it "raises Unauthorized exception" do
      lambda do
        user = create_user
        @response = perform_request :as_user => user, :skip_authentication => true
      end.should raise_error(Merb::Controller::Unauthorized)
    end
  end

  describe "when a team member or captain enters the dashboard" do
    before :each do
      user = create_user
      create_team :captain => user
      @response = perform_request :as_user => user, :skip_authentication => true
    end

    it "should respond successfully" do
      @response.should be_successful
    end
  end

  def perform_request(opts={})
    dispatch_to TeamRoom, :index do |controller|
      controller.session.stub!(:authenticated?).and_return(opts[:skip_authentication])
      controller.session.stub!(:user).and_return(opts[:as_user])
    end
  end
end


text:
<!DOCTYPE html>

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

  <meta name="author" content="Gerges Dib">

  <meta name="description" content="Building sensor systems for reliable detection of fatigue cracks in multilayered aircraft fuselage.">

  <link rel="alternate" hreflang="en-us" href="https://dibgerge.github.io/project/gmr/">

  <meta name="theme-color" content="#ba68c8">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha256-+N4/V/SbAFiW1MPBCXnfnP9QSN3+Keu+NlB+0ev/YKQ=" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/styles/atom-one-light.min.css" crossorigin="anonymous" title="hl-light">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/styles/atom-one-light.min.css" crossorigin="anonymous" title="hl-dark" disabled>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css" integrity="sha256-SHMGCYmST46SoyGgo4YR/9AlK1vf3ff84Aq9yK4hdqM=" crossorigin="anonymous">

  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,700%7CRoboto:400,400italic,700%7CRoboto+Mono&display=swap">

  <link rel="stylesheet" href="/css/academic.css">

  <link rel="manifest" href="/index.webmanifest">
  <link rel="icon" type="image/png" href="/images/icon_hufb0bba0b24038dd6774d907c032416d0_44829_32x32_fill_lanczos_center_2.png">
  <link rel="apple-touch-icon" type="image/png" href="/images/icon_hufb0bba0b24038dd6774d907c032416d0_44829_192x192_fill_lanczos_center_2.png">

  <link rel="canonical" href="https://dibgerge.github.io/project/gmr/">

  <meta property="twitter:card" content="summary_large_image">

  <meta property="og:site_name" content="Ge[o]rges Dib">
  <meta property="og:url" content="https://dibgerge.github.io/project/gmr/">
  <meta property="og:title" content="Giant Magnetoresistance Sensors for Aircraft Inspection | Ge[o]rges Dib">
  <meta property="og:description" content="Building sensor systems for reliable detection of fatigue cracks in multilayered aircraft fuselage."><meta property="og:image" content="https://dibgerge.github.io/project/gmr/featured.gif">
  <meta property="twitter:image" content="https://dibgerge.github.io/project/gmr/featured.gif"><meta property="og:locale" content="en-us">

      <meta property="article:published_time" content="2014-07-01T00:00:00-07:00">

    <meta property="article:modified_time" content="2014-07-01T00:00:00-07:00">

  <title>Giant Magnetoresistance Sensors for Aircraft Inspection | Ge[o]rges Dib</title>

Search

        <input name="q" id="search-query" placeholder="Search..." autocapitalize="off"
        autocomplete="off" autocorrect="off" spellcheck="false" type="search">

    <button type="button" class="navbar-toggler" data-toggle="collapse"
            data-target="#navbar-content" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home

          #Projects

          #Publications

          Blog

Giant Magnetoresistance Sensors for Aircraft Inspection

    Jul 1, 2014

Nondestructive inspection of multi-layered airframe geometries is a significant challenge largely due to complexity of test geometry and deep lying defects. Structural geometry of interest includes different configurations of aircraft skins, stringers, doublers, wing-splice with fasteners and deep lying cracks and corrosion. Inspection of these complex geometries requires dealing with a large number of variables which affect damage detection performance (material, size, thickness, edges, air gaps, etc.), experimental sensor system (frequency, waveform shape, harmonics, sampling intervals, circuit design etc.), and defect variables (length, width, volume, shape, distribution, orientation, etc.). Combination of these classes of variables encountered in any inspection makes the interpretation of the signals very challenging.

The purpose of this project was to design, fabricate and test a novel transducer and inspection technique for detecting cracks near fastener sites in aircrafts with high efficiency and sensitivity. The transducer uses Giant Megnetoresistance (GMR) sensor arrays for increasing sensitivity and reducing required aircraft scan times. Also, a rotating coil excitation is used, which allows the probe to be uniformly sensitive to cracks oriented in arbitrary direction. This is a significant advancement over the previous state-of-the-art, where probes were only sensitive to cracks oriented parallel to the direction of coil current flow. A finite element model (FEM) was also developed for simulating the designed probes. FEM simulations were then used for optimizing the probe design, including GMR sensor placement, excitation coil parameters, and signal processing methods.

  NDE

  signal processing

Gerges Dib

Applied Scientist

Develop machine learning solutions

Related

Eddy Current Inspection Autoanalysis of Steam Generator Tubes in Nuclear Power Plants

Advanced Signal Processing Algorithms in Structural Integrity Monitoring

A Wireless Sensor Node for Structural Health Monitoring using Guided Wave Testing

Novel Mode Decomposition Algorithms for Lamb Wave Signal Analysis in Online Monitoring of Structures

Sensor-tilt invariance analysis for eddy current signals

Publications

      Rotating field EC-GMR sensor for crack detection at fastener site in layered structures

      Eddy current-based techniques have been investigated for the inspection of embedded cracks under fastener heads in riveted structures. …

  Guang Yang, Gerges Dib, Lalita Udpa, Antonello Tamburrino, Satish S Udpa

  PDF

    Project

  DOI

      EC-GMR array with rotating current excitation for multilayered riveted structures inspection

      The challenge in detecting crack under fastener heads (CUF) in a multi-layered aircraft structure poses the need for advanced NDE …

  Gerges Dib, Guang Yang, Chaofeng Ye, Antonello Tamburrino, Lalita Udpa, Satish S Udpa

  PDF

    Project

  DOI

      Image processing algorithms for automated analysis of GMR data from inspection of multilayer structures

      Eddy current probes (EC) with Giant Magnetoresistive (GMR) sensors have recently emerged as a promising tool for rapid scanning of …

  Oleksii Karpenko, Seyed Safdernejad, Gerges Dib, Lalita Udpa, Satish Udpa, Antonello Tamburrino

  PDF

    Project

  DOI

      Sensor-tilt invariance analysis for eddy current signals

      In the application of electromagnetic nondestructive evaluation (NDE), the measured signals received by sensors are decided by the flaw …

  Guang Yang, Zhiwei Zeng, Yiming Deng, Xin Liu, Gerges Dib, Lalita Udpa

  PDF

    Project

  DOI

    Powered by the
    Academic theme for
    Hugo.

Cite

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

           Copy

           Download


text:
package examples.clients

import java.time.LocalDate

import com.twitter.finagle.http.Method.Get
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Http, Service}
import com.twitter.util.Await
import io.fintrospect.RouteSpec
import io.fintrospect.formats.PlainText.ResponseBuilder._
import io.fintrospect.parameters._
import io.fintrospect.testing.TestHttpServer
import io.fintrospect.util.HttpRequestResponseUtil.{headersFrom, statusAndContentFrom}

/**
  * Simple example of how to define client endpoints using the same techniques as the server routes.
  * Note that the client will automatically reject (with a 400) any unknown or missing parameters, as per the
  * specified route. The response is also decorated with the anonymised route, allowing for collection of
  * metrics about timing and number of requests going to the downsteam systems.
  *
  * This example also shows how you can re-use the RouteSpec across client and servers, thus allowing really simple
  * stub/fake implementations of remote systems to be created.
  */
object ClientSideAndSharedRouteSpecExample extends App {

  val theDate = Path.localDate("date")
  val theWeather = Query.optional.string("weather")
  val theUser = Header.required.string("user")
  val gender = FormField.optional.string("gender")
  val body = Body.form(gender)

  val sharedRouteSpec = RouteSpec()
    .taking(theUser)
    .taking(theWeather)
    .body(body)
    .at(Get) / "firstSection" / theDate

  val fakeServerRoute = sharedRouteSpec bindTo (dateFromPath => Service.mk[Request, Response] {
    request: Request => {
      println("URL was " + request.uri)
      println("Headers were " + headersFrom(request))
      println("Form sent was " + (body <-- request))
      println("Date send was " + dateFromPath.toString)
      Ok(dateFromPath.toString)
    }
  })

  Await.result(new TestHttpServer(10000, fakeServerRoute).start())

  val client = sharedRouteSpec bindToClient Http.newService("localhost:10000")

  val theCall = client(theWeather --> Option("sunny"), body --> Form(gender --> "male"), theDate --> LocalDate.of(2015, 1, 1), theUser --> System.getenv("USER"))

  val response = Await.result(theCall)

  println("Response headers: " + headersFrom(response))
  println("Response: " + statusAndContentFrom(response))
}


text:
<?php

namespace Application\Model\Entities;

use \Luckie\Model\BasicObject;
use Doctrine\ORM\Mapping as ORM;

/**
 * Recovery
 *
 * @ORM\Table(name="recovery")
 * @ORM\Entity
 */
class Recovery extends BasicObject {

    function __construct()
    {
        $this->isActive = 1;
    }

    /**
     * @var string
     *
     * @ORM\Column(name="hash", type="string", length=255, nullable=false)
     */
    private $hash;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date", type="datetime", nullable=false)
     */
    private $date;

    /**
     * @var boolean
     *
     * @ORM\Column(name="is_active", type="boolean", nullable=false)
     */
    private $isActive;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \Application\Model\Entities\User
     *
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     * })
     */
    private $user;

    /**
     * Set hash
     *
     * @param string $hash
     * @return Recovery
     */
    public function setHash($hash)
    {
        $this->hash = $hash;

        return $this;
    }

    /**
     * Get hash
     *
     * @return string
     */
    public function getHash()
    {
        return $this->hash;
    }

    /**
     * Set date
     *
     * @param \DateTime $date
     * @return Recovery
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

    /**
     * Get date
     *
     * @return \DateTime
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     * @return Recovery
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set user
     *
     * @param \Application\Model\Entities\User $user
     * @return Recovery
     */
    public function setUser(\Application\Model\Entities\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \Application\Model\Entities\User
     */
    public function getUser()
    {
        return $this->user;
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.ListItem = exports.List = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _styledComponents = require('styled-components');

var _styledComponents2 = _interopRequireDefault(_styledComponents);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Avatar = require('../Avatar/Avatar');

var _Avatar2 = _interopRequireDefault(_Avatar);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var List = exports.List = _styledComponents2.default.div.attrs({
	className: 'List item__list'
}).withConfig({
	displayName: 'List',
	componentId: 's15prkdz-0'
})(['', ';word-wrap:break-word;overflow-wrap:break-word;word-break:break-word;'], function (props) {
	return props.pile ? 'padding-bottom: 1.25em' : void 0;
});

var ListItemWrapper = _styledComponents2.default.div.attrs({
	className: function className(_ref) {
		var _className = _ref.className,
		    online = _ref.online;
		return (_className || '') + ' ListItemWrapper item__list__item ' + (online ? '' : 'offline');
	}
}).withConfig({
	displayName: 'List__ListItemWrapper',
	componentId: 's15prkdz-1'
})(['display:flex;', ';', ';'], function (props) {
	return props.alignItems ? 'align-items: ' + props.alignItems : 'align-items: center;';
}, function (props) {
	return props.online ? '' : 'opacity: .4;';
});

var ItemAvatar = _styledComponents2.default.div.attrs({
	className: 'ItemAvatar avatar__outer__wrapper'
}).withConfig({
	displayName: 'List__ItemAvatar',
	componentId: 's15prkdz-2'
})(['position:relative;margin:0 10px 0 0;border-radius:50%;', ';'], function (props) {
	return props.alignItems ? 'align-items: ' + props.alignItems : 'align-items: center;';
});

var ItemDetail = _styledComponents2.default.div.attrs({
	className: 'ItemDetail item__details'
}).withConfig({
	displayName: 'List__ItemDetail',
	componentId: 's15prkdz-3'
})(['flex-grow:1;']);

var ItemRightContent = _styledComponents2.default.div.attrs({
	className: 'ItemRightContent content__right'
}).withConfig({
	displayName: 'List__ItemRightContent',
	componentId: 's15prkdz-4'
})(['text-align:right;display:flex;align-items:flex-end;']);

var ItemTitle = _styledComponents2.default.div.attrs({
	className: 'ItemTitle title'
}).withConfig({
	displayName: 'List__ItemTitle',
	componentId: 's15prkdz-5'
})(['', ';'], function (props) {
	return props.weight ? 'font-weight: ' + props.weight : 'font-weight: 500;';
});

var ItemSubTitle = _styledComponents2.default.div.attrs({
	className: 'ItemSubTitle sub__title'
}).withConfig({
	displayName: 'List__ItemSubTitle',
	componentId: 's15prkdz-6'
})(['font-size:0.75em;']);

var ListItem = exports.ListItem = function (_Component) {
	_inherits(ListItem, _Component);

	function ListItem() {
		_classCallCheck(this, ListItem);

		return _possibleConstructorReturn(this, (ListItem.__proto__ || Object.getPrototypeOf(ListItem)).apply(this, arguments));
	}

	_createClass(ListItem, [{
		key: 'render',
		value: function render() {
			var _props = this.props,
			    className = _props.className,
			    children = _props.children,
			    title = _props.title,
			    subtitle = _props.subtitle,
			    rightInput = _props.rightInput,
			    rightTitle = _props.rightTitle,
			    rightSubtitle = _props.rightSubtitle,
			    online = _props.online,
			    avatar = _props.avatar,
			    showOnlineIndicator = _props.showOnlineIndicator,
			    alignItems = _props.alignItems,
			    props = _objectWithoutProperties(_props, ['className', 'children', 'title', 'subtitle', 'rightInput', 'rightTitle', 'rightSubtitle', 'online', 'avatar', 'showOnlineIndicator', 'alignItems']);

			// build children

			children = children || [];
			if (!Array.isArray(children)) {
				children = [children];
			}

			// setup title/subtitle
			if (subtitle) {
				children.unshift(_react2.default.createElement(
					ItemSubTitle,
					{ key: 'subtitle' },
					subtitle
				));
			}

			if (title) {
				children.unshift(_react2.default.createElement(
					ItemTitle,
					{ key: 'title' },
					title
				));
			}

			return _react2.default.createElement(
				ListItemWrapper,
				this.props,
				avatar && _react2.default.createElement(
					ItemAvatar,
					{ alignItems: alignItems },
					avatar === true ? _react2.default.createElement(_Avatar2.default, {
						online: online,
						showOnlineIndicator: showOnlineIndicator
					}) : _react2.default.createElement(_Avatar2.default, {
						online: online,
						image: avatar,
						showOnlineIndicator: showOnlineIndicator
					})
				),
				children && _react2.default.createElement(
					ItemDetail,
					null,
					children
				),
				(rightTitle || rightSubtitle || rightInput) && _react2.default.createElement(
					ItemRightContent,
					{ alignItems: alignItems },
					rightInput && rightInput,
					rightTitle && _react2.default.createElement(
						ItemTitle,
						{ weight: 400 },
						rightTitle
					),
					rightSubtitle && _react2.default.createElement(
						ItemSubTitle,
						null,
						rightSubtitle
					)
				)
			);
		}
	}]);

	return ListItem;
}(_react.Component);

ListItem.propTypes = {
	friend: _propTypes2.default.object,
	title: _propTypes2.default.string,
	subtitle: _propTypes2.default.string,
	rightInput: _propTypes2.default.any,
	rightTitle: _propTypes2.default.any,
	rightSubtitle: _propTypes2.default.any,
	online: _propTypes2.default.bool,
	avatar: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.bool]),
	showOnlineIndicator: _propTypes2.default.bool,
	alignItems: _propTypes2.default.string
};

ListItem.defaultProps = {
	online: true,
	showOnlineIndicator: true
};


text:
package tianma.ss.spider.http;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;

import tianma.ss.spider.util.TLog;

/**
 * This is a proxy of  {@link HttpClients}
 * @author Tianma
 *
 */
public class HttpClientsProxy {

	private HttpClientsProxy() {

	}

	/**
	 * Creates builder object for construction of custom
	 * {@link CloseableHttpClient} instances.
	 */
	public static HttpClientBuilder custom() {
		return HttpClients.custom();
	}

	/**
	 * Creates {@link CloseableHttpClient} instance with default configuration.
	 */
	public static CloseableHttpClient createDefault() {
		return HttpClients.createDefault();
	}

	/**
	 * Creates {@link CloseableHttpClient} instance with default configuration
	 * based on ssytem properties.
	 */
	public static CloseableHttpClient createSystem() {
		return HttpClients.createSystem();
	}

	/**
	 * Creates {@link CloseableHttpClient} instance that implements the most
	 * basic HTTP protocol support.
	 */
	public static CloseableHttpClient createMinimal() {
		return HttpClients.createMinimal();
	}

	/**
	 * Creates {@link CloseableHttpClient} instance that implements the most
	 * basic HTTP protocol support.
	 */
	public static CloseableHttpClient createMinimal(final HttpClientConnectionManager connManager) {
		return HttpClients.createMinimal(connManager);
	}

	/**
	 * 创建支持Https请求的HttpClient
	 *
	 * @return
	 */
	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			TLog.e(e);
		} catch (NoSuchAlgorithmException e) {
			TLog.e(e);
		} catch (KeyStoreException e) {
			TLog.e(e);
		}
		return HttpClients.createDefault();
	}

}