text:
#region Copyright

// Copyright 2017 Gigya Inc.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#endregion Copyright

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Orleans.Serialization;
using System;
using System.Linq;
using System.Collections.Generic;
using Gigya.Microdot.SharedLogic.Configurations;
using Gigya.Microdot.SharedLogic.Security;

// ReSharper disable AssignNullToNotNullAttribute

namespace Gigya.Microdot.Orleans.Hosting
{
    /// <summary>
    /// This class is called by the Orleans runtime to perform serialization for special types, and should not be called directly from your code.
    /// </summary>
    public class OrleansCustomSerialization : IExternalSerializer
    {
        protected readonly Dictionary<string,Type> _supportedTypes;

        public Func<JsonSerializerSettings> JsonSettingsFunc { get; set; }

        public OrleansCustomSerialization(IMicrodotTypePolicySerializationBinder serializationBinder)
        {
            _supportedTypes = new[]
            {
                typeof(JObject),
                typeof(JArray),
                typeof(JToken),
                typeof(JValue),
                typeof(JProperty),
                typeof(JConstructor)
            }.ToDictionary(t => t.FullName);

            JsonSettingsFunc = () => new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                NullValueHandling = NullValueHandling.Ignore,
                Formatting = Formatting.Indented,
                DateParseHandling = DateParseHandling.None,
                SerializationBinder = serializationBinder
        };
        }

        public virtual bool IsSupportedType(Type itemType)
        {
            if(itemType == null)
                throw new ArgumentNullException(nameof(itemType) + " can not be null");

            var result = _supportedTypes.ContainsKey(itemType.FullName);

            return result;
        }

        public virtual object DeepCopy(object source, ICopyContext context)
        {
            if (source is JToken token)
                return token.DeepClone();

            return source;
        }

        public virtual void Serialize(object item, ISerializationContext context, Type expectedType)
        {
            var serializedObject = JsonConvert.SerializeObject(item, expectedType, JsonSettingsFunc());
            SerializationManager.SerializeInner(serializedObject, context);
        }

        public virtual object Deserialize(Type expectedType, IDeserializationContext context)
        {
            var str = SerializationManager.DeserializeInner<string>(context);
            return JsonConvert.DeserializeObject(str, expectedType, JsonSettingsFunc());
        }

        public virtual void RegisterType(Type itemType)
        {
            if(itemType == null)
                throw new ArgumentNullException(nameof(itemType) + " can not be null");

            _supportedTypes[itemType.FullName] = itemType;
        }

        public virtual void UnRegisterType(Type itemType)
        {
            if(itemType == null)
                throw new ArgumentNullException(nameof(itemType) + " can not be null");

            _supportedTypes.Remove(itemType.FullName);
        }

        public virtual IEnumerable<Type> GetRegistered()
        {
            return _supportedTypes.Values;
        }
    }
}


text:
/* ###
 * IP: GHIDRA
 * REVIEWED: YES
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.framework.main.datatree;

import ghidra.framework.model.DomainFile;
import ghidra.framework.store.ItemCheckoutStatus;

import java.io.IOException;

class CheckoutInfo {
    private DomainFile file;

    private ItemCheckoutStatus status;

    CheckoutInfo(DomainFile file) throws IOException {
        this.file = file;
        this.status = file.getCheckoutStatus();
    }

    DomainFile getFile() {
        return file;
    }

    ItemCheckoutStatus getStatus() {
        return status;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Taskio\Entity;

abstract class AbstractEntity
{
    public $skipFill = [
        'id',
        'createdAt'
    ];

    /**
     * @param array $data
     * @return $this
     */
    public function fill(array $data = [])
    {
        foreach ($data as $key => $value) {
            if (!is_array($value) && !in_array($key, $this->skipFill)) {
                if (method_exists($this, 'set' . ucfirst($key))) {
                    $this->{'set' . ucfirst($key)}($value);
                } else {
                    throw new \InvalidArgumentException("Invalid key " . $key);
                }
            }
        }

        return $this;
    }
}


text:
/**
 * Utility for working with apis.
 */

import Config from './config'

const request = require('superagent');

export default class Api {
  constructor(config) {
    this.config = new Config(config, {
      'basePath': '/_grow/api/',
    })
    this.request = request
  }

  apiPath(path) {
    return `${this.config.get('basePath', '/')}${path}`
  }
}


text:
@component login-page {
  padding-top: 235px;
  background: url("../images/121.jpg") no-repeat center center fixed;
  background-size: 100% 100%;
}

@component login-form {
  width: 295px;
  background-color: #464646;
  margin: auto;
  margin-top: 60px;
  border-radius: 5px;
  padding: 30px 110px;
  border: 1px solid #000;
  margin-bottom: 30px;
  text-align:center;
  @descendent title {
    font-size: 28px;
    color: #fff;
    padding: 10px 0 20px 0;
  }
  @descendent list {
  }
}


text:
require 'rubygems'
require 'sinatra'
require 'slim'
require 'rest-client'
require 'json'
require_relative 'inc/levels'
require_relative 'inc/builddata'
require_relative 'inc/pagevars'
require_relative 'inc/Dataconn'
require_relative 'inc/api'

set :port, ENV['PORT'] || 8080
set :bind, ENV['IP'] || '0.0.0.0'

GIT_CLIENT_ID = ENV['GitHub_Client_ID']
GIT_CLIENT_SECRET = ENV['GitHub_Client_Secret']

RENV = ENV['RACK_ENV']

enable :sessions

helpers do
  def partial(template, locals = {})
    slim template, :layout => false, :locals => locals
  end
  def login?
    if session[:username].nil?
      return false
    else
      return true
    end
  end
  def devenv?
    if RENV == 'test'
      return true
    else
      return false
    end
  end
end

get '/' do
  if session[:username].nil?
    @TRAVISBUILDNUMBER = Pagevars.setVars("CIbuild")
    #@TRAVISBUILDNUMBER = 'dev (latest)'
    @PageTitle = 'Home'
    slim :accountSignup
  else
    @TRAVISBUILDNUMBER = Pagevars.setVars("CIbuild")
    #@TRAVISBUILDNUMBER = 'dev (latest)'
    @PageTitle = 'Home'
    @UserName = session[:username]
    @UserImg = session[:userimg]
    slim :home
  end
end
get '/contact' do
  slim :contact
end
post '/contact' do
  if session[:username].nil?
    redirect "/"
  else
    RestClient.post('https://api.github.com/repos/NETponents/code.me/issues',
                  {:params => {:access_token => session[:access_token],
                    :title => params[:title],
                    :body => "@" + params[:uname] + "(" + params[:name] + "): " + params[:message]}})
    slim :contact2
  end
end
get '/login/oauthcallback' do
  #session_code = request.env['rack.request.query_hash']['code']
  session_code = params[:code]
  result = RestClient.post('https://github.com/login/oauth/access_token',
                          {:client_id => GIT_CLIENT_ID,
                           :client_secret => GIT_CLIENT_SECRET,
                           :code => session_code},
                           :accept => :json)
  session[:access_token] = JSON.parse(result)['access_token']
  auth_result = JSON.parse(RestClient.get('https://api.github.com/user',
                                        {:params => {:access_token => session[:access_token]}}))
  session[:username] = auth_result['login']
  session[:userimg] = auth_result['avatar_url']
  redirect "/"
end
get '/account/login' do
  @TRAVISBUILDNUMBER = Pagevars.setVars("CIbuild")
    #@TRAVISBUILDNUMBER = 'dev (latest)'
  @PageTitle = 'Log in'
  @ClientId = GIT_CLIENT_ID
  slim :accountLoginInfo
end
get '/account/logout' do
  @TRAVISBUILDNUMBER = Pagevars.setVars("CIbuild")
  #@TRAVISBUILDNUMBER = 'dev (latest)'
  @PageTitle = 'Logged out'
  session[:username] = nil
  session[:userimg] = nil
  session[:access_token] = nil
  slim :accountLoggedOut
end

get '/api' do
  "#{API.a()}"
end
get '/api/notifications' do
  if login?
    "#{API.aNotifications(session[:username])}"
  elsif devenv?
    "#{API.aNotifications("ARMmaster17")}"
  else
    "401"
  end
end

#not_found do
#  slim :404
#end

get '/:userid/:projid' do
  # ProjExists() check
  @PageTitle = params[:userid] + '/' + params[:projid]
  @TRAVISBUILDNUMBER = Pagevars.setVars("CIbuild")
  if login?
    @UserName = session[:username]
    @UserImg = session[:userimg]
  elsif devenv?
    @UserName = 'TravisCIUser'
    @UserImg = 'https://avatars3.githubusercontent.com/u/4678601?v=3&s=460'
  else
    redirect "/"
  end
  @projName = params[:projid]
  @projDescription = 'A sample project that literally does nothing. Yep, nothing to see here.'
  @projOwner = params[:userid]
  @projContribNum = '1'
  @projCreateDate = 'June 1, 2015'
  @projCommitNum = 200
  @projLanguage = 'C++'
  slim :projProfile
end
get '/:userid' do
  @PageTitle = params[:userid]
  @TRAVISBUILDNUMBER = Pagevars.setVars("CIbuild")
  if login?
    @UserName = session[:username]
    @UserImg = session[:userimg]
  elsif devenv?
    @UserName = 'TravisCIUser'
    @UserImg = 'https://avatars3.githubusercontent.com/u/4678601?v=3&s=460'
  else
    redirect "/"
  end
  #Begin loading vars
  ustring = Dataconn.getUser(params[:userid])
  @userUserName = ustring.split(",")[0]
  @userPoints = ustring.split(",")[1]
  @userLevel = Levels.getLevelFromPoints(@userPoints)
  @levelName = Levels.getLevelName(@userLevel)
  @userImagePath = ustring.split(",")[2]
  @userFullName = ustring.split(",")[3]
  @userGeoLocation = ustring.split(",")[4]
  @userEmail = ustring.split(",")[5]
  slim :userProfile
end


text:
package org.apache.ignite.internal.processors.cache.persistence;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.ignite.Ignite;
import org.apache.ignite.cluster.ClusterState;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.failure.AbstractFailureHandler;
import org.apache.ignite.failure.FailureContext;
import org.apache.ignite.failure.FailureType;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.IgniteInterruptedCheckedException;
import org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointReadWriteLock;
import org.apache.ignite.internal.util.ReentrantReadWriteLockWithTracking;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.ListeningTestLogger;
import org.apache.ignite.testframework.LogListener;
import org.apache.ignite.testframework.junits.WithSystemProperty;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager.IGNITE_PDS_LOG_CP_READ_LOCK_HOLDERS;
import static org.apache.ignite.internal.util.ReentrantReadWriteLockWithTracking.LOCK_HOLD_MESSAGE;

/**
 * Tests critical failure handling on checkpoint read lock acquisition errors.
 */
public class CheckpointReadLockFailureTest extends GridCommonAbstractTest {
    /** */
    private ListeningTestLogger testLog;

    /** */
    private static final AbstractFailureHandler FAILURE_HND = new AbstractFailureHandler() {
        @Override protected boolean handle(Ignite ignite, FailureContext failureCtx) {
            if (failureCtx.type() != FailureType.SYSTEM_CRITICAL_OPERATION_TIMEOUT)
                return true;

            if (hndLatch != null)
                hndLatch.countDown();

            return false;
        }
    };

    /** */
    private static volatile CountDownLatch hndLatch;

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName)
            .setFailureHandler(FAILURE_HND)
            .setDataStorageConfiguration(new DataStorageConfiguration()
                .setDefaultDataRegionConfiguration(new DataRegionConfiguration()
                    .setPersistenceEnabled(true))
                .setCheckpointFrequency(Integer.MAX_VALUE)
                .setCheckpointReadLockTimeout(1));

        if (testLog != null) {
            cfg.setGridLogger(testLog);

            testLog = null;
        }

        return cfg;
    }

    /**
     *
     */
    @BeforeClass
    public static void beforeClass() {
        Set<FailureType> ignoredFailureTypes = new HashSet<>(FAILURE_HND.getIgnoredFailureTypes());
        ignoredFailureTypes.remove(FailureType.SYSTEM_CRITICAL_OPERATION_TIMEOUT);

        FAILURE_HND.setIgnoredFailureTypes(ignoredFailureTypes);
    }

    /**
     *
     */
    @Before
    public void before() throws Exception {
        cleanPersistenceDir();
    }

    /**
     *
     */
    @After
    public void after() throws Exception {
        cleanPersistenceDir();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testFailureTypeOnTimeout() throws Exception {
        hndLatch = new CountDownLatch(1);

        IgniteEx ig = startGrid(0);

        ig.cluster().state(ClusterState.ACTIVE);

        GridCacheDatabaseSharedManager db = (GridCacheDatabaseSharedManager)ig.context().cache().context().database();

        CheckpointReadWriteLock checkpointReadWriteLock = U.field(
            db.checkpointManager.checkpointTimeoutLock(), "checkpointReadWriteLock"
        );

        IgniteInternalFuture acquireWriteLock = GridTestUtils.runAsync(() -> {
            checkpointReadWriteLock.writeLock();

            try {
                doSleep(Long.MAX_VALUE);
            }
            finally {
                checkpointReadWriteLock.writeUnlock();
            }
        });

        IgniteInternalFuture acquireReadLock = GridTestUtils.runAsync(() -> {
            db.checkpointReadLock();
            db.checkpointReadUnlock();
        });

        assertTrue(hndLatch.await(5, TimeUnit.SECONDS));

        acquireWriteLock.cancel();

        acquireReadLock.get(5, TimeUnit.SECONDS);

        GridTestUtils.waitForCondition(acquireWriteLock::isCancelled, 5000);

        stopGrid(0);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    @WithSystemProperty(key = IGNITE_PDS_LOG_CP_READ_LOCK_HOLDERS, value = "true")
    public void testPrintCpRLockHolder() throws Exception {
        CountDownLatch canRelease = new CountDownLatch(1);

        testLog = new ListeningTestLogger(log);

        LogListener lsnr = LogListener.matches(LOCK_HOLD_MESSAGE).build();

        testLog.registerListener(lsnr);

        IgniteEx ig = startGrid(0);

        ig.cluster().state(ClusterState.ACTIVE);

        GridCacheDatabaseSharedManager db = (GridCacheDatabaseSharedManager)ig.context().cache().context().database();

        CheckpointReadWriteLock checkpointReadWriteLock = U.field(
            db.checkpointManager.checkpointTimeoutLock(), "checkpointReadWriteLock"
        );
        ReentrantReadWriteLockWithTracking tracker = U.field(checkpointReadWriteLock, "checkpointLock");

        GridTestUtils.runAsync(() -> {
            checkpointReadWriteLock.readLock();

            try {
                canRelease.await(tracker.lockWaitThreshold() + 500, TimeUnit.MILLISECONDS);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                checkpointReadWriteLock.readUnlock();
            }
        }, "async-runnable-runner-1");

        assertTrue(GridTestUtils.waitForCondition(lsnr::check, tracker.lockWaitThreshold() + 1000));

        stopGrid(0);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    @WithSystemProperty(key = IGNITE_PDS_LOG_CP_READ_LOCK_HOLDERS, value = "true")
    public void testReentrance() throws Exception {
        IgniteEx ig = startGrid(0);

        ig.cluster().state(ClusterState.ACTIVE);

        GridCacheDatabaseSharedManager db = (GridCacheDatabaseSharedManager)ig.context().cache().context().database();

        CheckpointReadWriteLock checkpointReadWriteLock = U.field(
            db.checkpointManager.checkpointTimeoutLock(), "checkpointReadWriteLock"
        );

        ReentrantReadWriteLockWithTracking rwLock = U.field(checkpointReadWriteLock, "checkpointLock");

        CountDownLatch waitFirstRLock = new CountDownLatch(1);

        CountDownLatch waitSecondRLock = new CountDownLatch(1);

        long timeout = 500L;

        IgniteInternalFuture f0 = GridTestUtils.runAsync(() -> {
            //noinspection LockAcquiredButNotSafelyReleased
            rwLock.readLock().lock();

            //noinspection LockAcquiredButNotSafelyReleased
            rwLock.readLock().lock();

            rwLock.readLock().unlock();

            waitFirstRLock.countDown();

            try {
                waitSecondRLock.await();
            }
            catch (InterruptedException e) {
                fail(e.toString());
            }

            rwLock.readLock().unlock();
        }, "async-runnable-runner-1");

        IgniteInternalFuture f1 = GridTestUtils.runAsync(() -> {
            try {
                waitFirstRLock.await();
            }
            catch (InterruptedException e) {
                fail(e.toString());
            }

            try {
                rwLock.writeLock().tryLock();

                assertFalse(GridTestUtils.waitForCondition(rwLock.writeLock()::isHeldByCurrentThread, timeout));
            }
            catch (IgniteInterruptedCheckedException e) {
                e.printStackTrace();
            }

            waitSecondRLock.countDown();

            try {
                rwLock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS);

                assertTrue(rwLock.writeLock().isHeldByCurrentThread());
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                rwLock.writeLock().unlock();
            }

        }, "async-runnable-runner-2");

        f1.get(4 * timeout);

        f0.get(4 * timeout);

        stopGrid(0);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    @WithSystemProperty(key = IGNITE_PDS_LOG_CP_READ_LOCK_HOLDERS, value = "true")
    public void testWriteLockedByCurrentThread() {
        ReentrantReadWriteLockWithTracking wrapped = new ReentrantReadWriteLockWithTracking(log, 1_000);

        wrapped.writeLock().lock();

        try {
            assertTrue(wrapped.isWriteLockedByCurrentThread());
        }
        finally {
            wrapped.writeLock().unlock();
        }
    }
}


text:
---
layout: post
title:  "Regex PHP : lookahead et lookbehind"
date:   2013-10-01
tags:
- regex
- php
description: >
  Bien le bonjour, amis regexophiles ! Aujourd'hui, je vous explique rapidement comment utiliser les lookahead et les lookbehind dans une regex en PHP.
---

## Le lookahead

Le lookahead, ou assertion avant, est un moyen de vérifier ce qui se trouve derrière votre groupe de capture, avant de décider si vous le capturez ou non.
Il existe deux type de lookahead :

* Le positive lookahead `(?=foo)` : capture le groupe s'il est suivi par…
* Le negative lookahead `(?!foo)` : capture le groupe s'il n'est pas suivi par…

Le symbole `$` est un lookahead bien connu, qui vérifie que le groupe de capture n'est suivi par rien d'autre.

## Le lookbehind

Le lookbehind, ou assertion arrière, est un moyen de vérifier ce qui se trouve devant votre groupe de capture, avant de décider si vous le capturez ou non.
Il existe deux type de lookbehind :

* Le positive lookbehind `(?<=foo)` : capture le groupe s'il est précédé par…
* Le negative lookbehind `(?<!foo)` : capture le groupe s'il n'est pas précédé par…

Le symbole `^` est un lookbehind bien connu, qui vérifie que le groupe de capture n'est précédé par rien d'autre.

## Exemples

Voici ci-dessous quelques exemples

```php
$url = array(
  'root/folder1/',
  'root/folder1/subfolder1/',
  'root/folder1/subfolder2/',
  'root/folder1/subfolder2/action1/',
  'root/folder1/subfolder2/action2/',
  'root/folder2/',
  'root/folder2/subfolder1/',
  'root/folder2/subfolder2/',
);
$reg = array(
  '#/folder1/(?=subfolder2)#', // folder1, suivi de subfolder2
  '#/folder1/(?!subfolder2)#', // folder1, non suivi de subfolder2
  '#(?<=folder1)/subfolder1#', // subfolder1, précédé de folder1
  '#(?<!folder1)/subfolder1#', // subfolder1, non précédé de folder1
);
foreach($reg as $r) {
  echo 'Regex : '.htmlentities($r).'
';
  foreach($url as $u) {
    echo preg_match($r, $u).' - '.$u.'
';
  }
  echo '-----------
';
}
/*
Regex : #/folder1/(?=subfolder2)#
0 - root/folder1/
0 - root/folder1/subfolder1/
1 - root/folder1/subfolder2/
1 - root/folder1/subfolder2/action1/
1 - root/folder1/subfolder2/action2/
0 - root/folder2/
0 - root/folder2/subfolder1/
0 - root/folder2/subfolder2/
-----------
Regex : #/folder1/(?!subfolder2)#
1 - root/folder1/
1 - root/folder1/subfolder1/
0 - root/folder1/subfolder2/
0 - root/folder1/subfolder2/action1/
0 - root/folder1/subfolder2/action2/
0 - root/folder2/
0 - root/folder2/subfolder1/
0 - root/folder2/subfolder2/
-----------
Regex : #(?<=folder1)/subfolder1#
0 - root/folder1/
1 - root/folder1/subfolder1/
0 - root/folder1/subfolder2/
0 - root/folder1/subfolder2/action1/
0 - root/folder1/subfolder2/action2/
0 - root/folder2/
0 - root/folder2/subfolder1/
0 - root/folder2/subfolder2/
-----------
Regex : #(?<!folder1)/subfolder1#
0 - root/folder1/
0 - root/folder1/subfolder1/
0 - root/folder1/subfolder2/
0 - root/folder1/subfolder2/action1/
0 - root/folder1/subfolder2/action2/
0 - root/folder2/
1 - root/folder2/subfolder1/
0 - root/folder2/subfolder2/
-----------
*/
```

## Applications

Les assertions peuvent être utilisées dans de nombreux cas, dont voici quelques exemples :

* Gérer des exceptions dans vos Regex (comme ci-dessus)
* Récupérer la dernière occurrence d'un mot :
  `foo(?!.*foo)`
* Valider le niveau de sécurité d'un mot de passe, ici, 8 caractères minimum, dont au moins une majuscule et un chiffre :
  `^(?=.*[A-Z])(?=.*\d)[\w]{8,}$`
* Récupérer les montants dans un texte (sans récupérer le symbole €) :
  `\d+(?:[.,]\d+)?(?=\s*€)`

## Limites

Si les assertions vous permettent une plus grande liberté dans l'utilisation de vos regex, il faut être conscient de leurs limites. Elles peuvent en effet devenir assez gourmandes si mal utilisées. Le lookbehind a de plus une particularité, due au fonctionnement des assertions et au déplacement du curseur d'avant en arrière : **il doit avoir une taille fixe**. Nous avons vu dans les exemples comment trouver la première occurrence d'un mot dans un texte. Si nous adaptions cette regex pour trouver la première occurrence, cela donnerait ce genre de code :

```
(?<!foo.*)foo
```

Malheureusement, notre lookbehind n'a pas ici une taille fixe, en résulte une erreur de compilation :

```
Warning: Compilation failed: lookbehind assertion is not fixed length
```

## Et en Javascript ?
Les lookahead sont aussi supportés en Javascript, mais pas les lookbehind. Il faudra donc parfois retravailler la capture pour supprimer les données inutiles.

## Liens
[Documentation PHP : PCRE, les assertions](https://www.php.net/manual/fr/regexp.reference.assertions.php)
[SO : Regex lookahead ordering, lien intéressant sur l'endroit où placer une assertion](https://stackoverflow.com/questions/2126137/regex-lookahead-ordering#2126755)


text:
libvorbis v1.3.7 bindings for Rust

```toml
[dependencies.vorbis-sys]
git = "https://github.com/tomaka/vorbis-sys"
```

## The libvorbis license

> Copyright (c) 2002-2008 Xiph.org Foundation
>
> Redistribution and use in source and binary forms, with or without
> modification, are permitted provided that the following conditions
> are met:
>
> - Redistributions of source code must retain the above copyright
> notice, this list of conditions and the following disclaimer.
>
> - Redistributions in binary form must reproduce the above copyright
> notice, this list of conditions and the following disclaimer in the
> documentation and/or other materials provided with the distribution.
>
> - Neither the name of the Xiph.org Foundation nor the names of its
> contributors may be used to endorse or promote products derived from
> this software without specific prior written permission.
>
> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
> ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
> LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
> A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION
> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
> SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
> LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
> DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
> THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
> (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


text:
var rtx5_impl =
[
    [ "Create an RTX5 Project", "cre_rtx_proj.html", [
      [ "Additional requirements for RTX on Cortex-A", "cre_rtx_proj.html#cre_rtx_cortexa", null ],
      [ "Using Interrupts on Cortex-M", "cre_rtx_proj.html#cre_UsingIRQs", null ],
      [ "Add support for RTX specific functions", "cre_rtx_proj.html#cre_rtx_proj_specifics", null ],
      [ "Add Event Recorder Visibility", "cre_rtx_proj.html#cre_rtx_proj_er", null ]
    ] ],
    [ "Theory of Operation", "theory_of_operation.html", [
      [ "System Startup", "theory_of_operation.html#SystemStartup", null ],
      [ "Scheduler", "theory_of_operation.html#Scheduler", null ],
      [ "Memory Allocation", "theory_of_operation.html#MemoryAllocation", [
        [ "Global Memory Pool", "theory_of_operation.html#GlobalMemoryPool", null ],
        [ "Object-specific Memory Pools", "theory_of_operation.html#ObjectMemoryPool", null ],
        [ "Static Object Memory", "theory_of_operation.html#StaticObjectMemory", null ]
      ] ],
      [ "Thread Stack Management", "theory_of_operation.html#ThreadStack", null ],
      [ "Low-Power Operation", "theory_of_operation.html#lowPower", null ],
      [ "RTX Kernel Timer Tick", "theory_of_operation.html#kernelTimer", [
        [ "Tick-less Low-Power Operation", "theory_of_operation.html#TickLess", null ]
      ] ],
      [ "RTX5 Header File", "theory_of_operation.html#rtx_os_h", null ],
      [ "Timeout Value", "theory_of_operation.html#CMSIS_RTOS_TimeOutValue", null ],
      [ "Calls from Interrupt Service Routines", "theory_of_operation.html#CMSIS_RTOS_ISR_Calls", null ],
      [ "SVC Functions", "theory_of_operation.html#CMSIS_RTOS_svcFunctions", null ]
    ] ],
    [ "Configure RTX v5", "config_rtx5.html", [
      [ "System Configuration", "config_rtx5.html#systemConfig", [
        [ "Global dynamic memory", "config_rtx5.html#systemConfig_glob_mem", null ],
        [ "Round-Robin Thread Switching", "config_rtx5.html#systemConfig_rr", null ],
        [ "ISR FIFO Queue", "config_rtx5.html#systemConfig_isr_fifo", null ],
        [ "Object Memory Usage Counters", "config_rtx5.html#systemConfig_usage_counters", null ]
      ] ],
      [ "Thread Configuration", "config_rtx5.html#threadConfig", [
        [ "Configuration of Thread Count and Stack Space", "config_rtx5.html#threadConfig_countstack", null ],
        [ "Stack Overflow Checking", "config_rtx5.html#threadConfig_ovfcheck", null ],
        [ "Stack Usage Watermark", "config_rtx5.html#threadConfig_watermark", null ],
        [ "Processor Mode for Thread Execution", "config_rtx5.html#threadConfig_procmode", null ]
      ] ],
      [ "Timer Configuration", "config_rtx5.html#timerConfig", [
        [ "Object-specific memory allocation", "config_rtx5.html#timerConfig_obj", null ],
        [ "User Timer Thread", "config_rtx5.html#timerConfig_user", null ]
      ] ],
      [ "Event Flags Configuration", "config_rtx5.html#eventFlagsConfig", [
        [ "Object-specific memory allocation", "config_rtx5.html#eventFlagsConfig_obj", null ]
      ] ],
      [ "Mutex Configuration", "config_rtx5.html#mutexConfig", [
        [ "Object-specific Memory Allocation", "config_rtx5.html#mutexConfig_obj", null ]
      ] ],
      [ "Semaphore Configuration", "config_rtx5.html#semaphoreConfig", [
        [ "Object-specific memory allocation", "config_rtx5.html#semaphoreConfig_obj", null ]
      ] ],
      [ "Memory Pool Configuration", "config_rtx5.html#memPoolConfig", [
        [ "Object-specific memory allocation", "config_rtx5.html#memPoolConfig_obj", null ]
      ] ],
      [ "Message Queue Configuration", "config_rtx5.html#msgQueueConfig", [
        [ "Object-specific memory allocation", "config_rtx5.html#msgQueueConfig_obj", null ]
      ] ],
      [ "Event Recorder Configuration", "config_rtx5.html#evtrecConfig", [
        [ "Global Configuration", "config_rtx5.html#evtrecConfigGlobIni", null ],
        [ "RTOS Event Generation", "config_rtx5.html#evtrecConfigEvtGen", null ],
        [ "Manual event configuration", "config_rtx5.html#systemConfig_event_recording", null ]
      ] ]
    ] ],
    [ "Building the RTX5 Library", "creating_RTX5_LIB.html", null ],
    [ "Technical Data", "technicalData5.html", "technicalData5" ],
    [ "MISRA C:2012 Compliance", "misraCompliance5.html", [
      [ "[MISRA Note 1]: Return statements for parameter checking", "misraCompliance5.html#MISRA_1", null ],
      [ "[MISRA Note 2]: Object identifiers are void pointers", "misraCompliance5.html#MISRA_2", null ],
      [ "[MISRA Note 3]: Conversion to unified object control blocks", "misraCompliance5.html#MISRA_3", null ],
      [ "[MISRA Note 4]: Conversion from unified object control blocks", "misraCompliance5.html#MISRA_4", null ],
      [ "[MISRA Note 5]: Conversion to object types", "misraCompliance5.html#MISRA_5", null ],
      [ "[MISRA Note 6]: Conversion from user provided storage", "misraCompliance5.html#MISRA_6", null ],
      [ "[MISRA Note 7]: Check for proper pointer alignment", "misraCompliance5.html#MISRA_7", null ],
      [ "[MISRA Note 8]: Memory allocation management", "misraCompliance5.html#MISRA_8", null ],
      [ "[MISRA Note 9]: Pointer conversions for register access", "misraCompliance5.html#MISRA_9", null ],
      [ "[MISRA Note 10]: SVC calls use function-like macros", "misraCompliance5.html#MISRA_10", null ],
      [ "[MISRA Note 11]: SVC calls use assembly code", "misraCompliance5.html#MISRA_11", null ],
      [ "[MISRA Note 12]: Usage of exclusive access instructions", "misraCompliance5.html#MISRA_12", null ],
      [ "[MISRA Note 13]: Usage of Event Recorder", "misraCompliance5.html#MISRA_13", null ]
    ] ]
];


text:
using System.Reflection;

[assembly: AssemblyVersion("1.1.0")]
[assembly: AssemblyFileVersion("1.1.0")]


text:
using Contrib.Taxonomies.Models;
using Orchard.ContentManagement.Drivers;

namespace Contrib.Taxonomies.Drivers {
    public class TermsPartDriver : ContentPartDriver<TermsPart> {
    }
}


text:
<?php

// OCPAppliBundle:Parc:show.html.twig
return array (
);


text:
package org.apache.ambari.server.api.resources;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.ambari.server.api.query.render.ClusterBlueprintRenderer;
import org.apache.ambari.server.api.query.render.Renderer;
import org.apache.ambari.server.controller.KerberosHelper;
import org.apache.ambari.server.controller.spi.Resource;

/**
 * Cluster resource definition.
 */
public class ClusterResourceDefinition extends BaseResourceDefinition {
  /**
   * Constructor.
   */
  public ClusterResourceDefinition() {
    super(Resource.Type.Cluster);
  }

  @Override
  public String getPluralName() {
    return "clusters";
  }

  @Override
  public String getSingularName() {
    return "cluster";
  }

  @Override
  public Renderer getRenderer(String name) {
    if (name != null && name.equals("blueprint")) {
      return new ClusterBlueprintRenderer();
    } else {
      return super.getRenderer(name);
    }
  }

  @Override
  public Set<SubResourceDefinition> getSubResourceDefinitions() {
    Set<SubResourceDefinition> setChildren = new HashSet<>();
    setChildren.add(new SubResourceDefinition(Resource.Type.Service));
    setChildren.add(new SubResourceDefinition(Resource.Type.Host));
    setChildren.add(new SubResourceDefinition(Resource.Type.Configuration));
    setChildren.add(new SubResourceDefinition(Resource.Type.ServiceConfigVersion));
    setChildren.add(new SubResourceDefinition(Resource.Type.Request));
    setChildren.add(new SubResourceDefinition(Resource.Type.Workflow));
    setChildren.add(new SubResourceDefinition(Resource.Type.ConfigGroup));
    setChildren.add(new SubResourceDefinition(Resource.Type.ClusterPrivilege));
    setChildren.add(new SubResourceDefinition(Resource.Type.AlertDefinition));
    setChildren.add(new SubResourceDefinition(Resource.Type.Alert));
    setChildren.add(new SubResourceDefinition(Resource.Type.ClusterStackVersion));
    setChildren.add(new SubResourceDefinition(Resource.Type.ClusterKerberosDescriptor));
    //todo: dynamic sub-resource definition
    setChildren.add(new SubResourceDefinition(Resource.Type.Artifact));

    return setChildren;
  }

  @Override
  public Collection<String> getUpdateDirectives() {
    Collection<String> directives = super.getUpdateDirectives();
    directives.add(KerberosHelper.DIRECTIVE_REGENERATE_KEYTABS);
    directives.add(KerberosHelper.DIRECTIVE_MANAGE_KERBEROS_IDENTITIES);
    directives.add(KerberosHelper.DIRECTIVE_FORCE_TOGGLE_KERBEROS);
    directives.add(KerberosHelper.DIRECTIVE_HOSTS);
    directives.add(KerberosHelper.DIRECTIVE_COMPONENTS);
    return directives;
  }

}


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

namespace _07.SumOf5Numbers
{
    class SumOf5Numbers
    {
        static void Main()
        {
            int input = 0;
            for (int i = 0; i < 5; i++)
            {
                input += Convert.ToInt32(Console.ReadLine());
            }

            Console.WriteLine(input);
        }
    }
}


text:
'use strict';

var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var grpc = require('..');
var testProto = grpc.load(__dirname + '/test.proto').grpc.testing;
var GoogleAuth = require('google-auth-library');

var assert = require('assert');

var AUTH_SCOPE = 'https://www.googleapis.com/auth/xapi.zoo';
var AUTH_SCOPE_RESPONSE = 'xapi.zoo';
var AUTH_USER = ('155450119199-vefjjaekcc6cmsd5914v6lqufunmh9ue' +
    '@developer.gserviceaccount.com');
var COMPUTE_ENGINE_USER = ('155450119199-r5aaqa2vqoa9g5mv2m6s3m1l293rlmel' +
    '@developer.gserviceaccount.com');

/**
 * Create a buffer filled with size zeroes
 * @param {number} size The length of the buffer
 * @return {Buffer} The new buffer
 */
function zeroBuffer(size) {
  var zeros = new Buffer(size);
  zeros.fill(0);
  return zeros;
}

/**
 * Run the empty_unary test
 * @param {Client} client The client to test against
 * @param {function} done Callback to call when the test is completed. Included
 *     primarily for use with mocha
 */
function emptyUnary(client, done) {
  client.emptyCall({}, function(err, resp) {
    assert.ifError(err);
    if (done) {
      done();
    }
  });
}

/**
 * Run the large_unary test
 * @param {Client} client The client to test against
 * @param {function} done Callback to call when the test is completed. Included
 *     primarily for use with mocha
 */
function largeUnary(client, done) {
  var arg = {
    response_type: 'COMPRESSABLE',
    response_size: 314159,
    payload: {
      body: zeroBuffer(271828)
    }
  };
  client.unaryCall(arg, function(err, resp) {
    assert.ifError(err);
    assert.strictEqual(resp.payload.type, 'COMPRESSABLE');
    assert.strictEqual(resp.payload.body.length, 314159);
    if (done) {
      done();
    }
  });
}

/**
 * Run the client_streaming test
 * @param {Client} client The client to test against
 * @param {function} done Callback to call when the test is completed. Included
 *     primarily for use with mocha
 */
function clientStreaming(client, done) {
  var call = client.streamingInputCall(function(err, resp) {
    assert.ifError(err);
    assert.strictEqual(resp.aggregated_payload_size, 74922);
    if (done) {
      done();
    }
  });
  var payload_sizes = [27182, 8, 1828, 45904];
  for (var i = 0; i < payload_sizes.length; i++) {
    call.write({payload: {body: zeroBuffer(payload_sizes[i])}});
  }
  call.end();
}

/**
 * Run the server_streaming test
 * @param {Client} client The client to test against
 * @param {function} done Callback to call when the test is completed. Included
 *     primarily for use with mocha
 */
function serverStreaming(client, done) {
  var arg = {
    response_type: 'COMPRESSABLE',
    response_parameters: [
      {size: 31415},
      {size: 9},
      {size: 2653},
      {size: 58979}
    ]
  };
  var call = client.streamingOutputCall(arg);
  var resp_index = 0;
  call.on('data', function(value) {
    assert(resp_index < 4);
    assert.strictEqual(value.payload.type, 'COMPRESSABLE');
    assert.strictEqual(value.payload.body.length,
                       arg.response_parameters[resp_index].size);
    resp_index += 1;
  });
  call.on('end', function() {
    assert.strictEqual(resp_index, 4);
    if (done) {
      done();
    }
  });
  call.on('status', function(status) {
    assert.strictEqual(status.code, grpc.status.OK);
  });
}

/**
 * Run the ping_pong test
 * @param {Client} client The client to test against
 * @param {function} done Callback to call when the test is completed. Included
 *     primarily for use with mocha
 */
function pingPong(client, done) {
  var payload_sizes = [27182, 8, 1828, 45904];
  var response_sizes = [31415, 9, 2653, 58979];
  var call = client.fullDuplexCall();
  call.on('status', function(status) {
    assert.strictEqual(status.code, grpc.status.OK);
    if (done) {
      done();
    }
  });
  var index = 0;
  call.write({
      response_type: 'COMPRESSABLE',
      response_parameters: [
        {size: response_sizes[index]}
      ],
      payload: {body: zeroBuffer(payload_sizes[index])}
  });
  call.on('data', function(response) {
    assert.strictEqual(response.payload.type, 'COMPRESSABLE');
    assert.equal(response.payload.body.length, response_sizes[index]);
    index += 1;
    if (index === 4) {
      call.end();
    } else {
      call.write({
        response_type: 'COMPRESSABLE',
        response_parameters: [
          {size: response_sizes[index]}
        ],
        payload: {body: zeroBuffer(payload_sizes[index])}
      });
    }
  });
}

/**
 * Run the empty_stream test.
 * @param {Client} client The client to test against
 * @param {function} done Callback to call when the test is completed. Included
 *     primarily for use with mocha
 */
function emptyStream(client, done) {
  var call = client.fullDuplexCall();
  call.on('status', function(status) {
    assert.strictEqual(status.code, grpc.status.OK);
    if (done) {
      done();
    }
  });
  call.on('data', function(value) {
    assert.fail(value, null, 'No data should have been received', '!==');
  });
  call.end();
}

/**
 * Run the cancel_after_begin test.
 * @param {Client} client The client to test against
 * @param {function} done Callback to call when the test is completed. Included
 *     primarily for use with mocha
 */
function cancelAfterBegin(client, done) {
  var call = client.streamingInputCall(function(err, resp) {
    assert.strictEqual(err.code, grpc.status.CANCELLED);
    done();
  });
  call.cancel();
}

/**
 * Run the cancel_after_first_response test.
 * @param {Client} client The client to test against
 * @param {function} done Callback to call when the test is completed. Included
 *     primarily for use with mocha
 */
function cancelAfterFirstResponse(client, done) {
  var call = client.fullDuplexCall();
  call.write({
      response_type: 'COMPRESSABLE',
      response_parameters: [
        {size: 31415}
      ],
      payload: {body: zeroBuffer(27182)}
  });
  call.on('data', function(data) {
    call.cancel();
  });
  call.on('error', function(error) {
    assert.strictEqual(error.code, grpc.status.CANCELLED);
    done();
  });
}

function timeoutOnSleepingServer(client, done) {
  var deadline = new Date();
  deadline.setMilliseconds(deadline.getMilliseconds() + 1);
  var call = client.fullDuplexCall(null, {deadline: deadline});
  call.write({
    payload: {body: zeroBuffer(27182)}
  });
  call.on('error', function(error) {

    assert(error.code === grpc.status.DEADLINE_EXCEEDED ||
        error.code === grpc.status.INTERNAL);
    done();
  });
}

/**
 * Run one of the authentication tests.
 * @param {string} expected_user The expected username in the response
 * @param {Client} client The client to test against
 * @param {?string} scope The scope to apply to the credentials
 * @param {function} done Callback to call when the test is completed. Included
 *     primarily for use with mocha
 */
function authTest(expected_user, scope, client, done) {
  (new GoogleAuth()).getApplicationDefault(function(err, credential) {
    assert.ifError(err);
    if (credential.createScopedRequired() && scope) {
      credential = credential.createScoped(scope);
    }
    client.$updateMetadata = grpc.getGoogleAuthDelegate(credential);
    var arg = {
      response_type: 'COMPRESSABLE',
      response_size: 314159,
      payload: {
        body: zeroBuffer(271828)
      },
      fill_username: true,
      fill_oauth_scope: true
    };
    client.unaryCall(arg, function(err, resp) {
      assert.ifError(err);
      assert.strictEqual(resp.payload.type, 'COMPRESSABLE');
      assert.strictEqual(resp.payload.body.length, 314159);
      assert.strictEqual(resp.username, expected_user);
      if (scope) {
        assert.strictEqual(resp.oauth_scope, AUTH_SCOPE_RESPONSE);
      }
      if (done) {
        done();
      }
    });
  });
}

function oauth2Test(expected_user, scope, per_rpc, client, done) {
  (new GoogleAuth()).getApplicationDefault(function(err, credential) {
    assert.ifError(err);
    var arg = {
      fill_username: true,
      fill_oauth_scope: true
    };
    credential = credential.createScoped(scope);
    credential.getAccessToken(function(err, token) {
      assert.ifError(err);
      var updateMetadata = function(authURI, metadata, callback) {
        metadata.add('authorization', 'Bearer ' + token);
        callback(null, metadata);
      };
      var makeTestCall = function(error, client_metadata) {
        assert.ifError(error);
        client.unaryCall(arg, function(err, resp) {
          assert.ifError(err);
          assert.strictEqual(resp.username, expected_user);
          assert.strictEqual(resp.oauth_scope, AUTH_SCOPE_RESPONSE);
          if (done) {
            done();
          }
        }, client_metadata);
      };
      if (per_rpc) {
        updateMetadata('', new grpc.Metadata(), makeTestCall);
      } else {
        client.$updateMetadata = updateMetadata;
        makeTestCall(null, new grpc.Metadata());
      }
    });
  });
}

/**
 * Map from test case names to test functions
 */
var test_cases = {
  empty_unary: emptyUnary,
  large_unary: largeUnary,
  client_streaming: clientStreaming,
  server_streaming: serverStreaming,
  ping_pong: pingPong,
  empty_stream: emptyStream,
  cancel_after_begin: cancelAfterBegin,
  cancel_after_first_response: cancelAfterFirstResponse,
  timeout_on_sleeping_server: timeoutOnSleepingServer,
  compute_engine_creds: _.partial(authTest, COMPUTE_ENGINE_USER, null),
  service_account_creds: _.partial(authTest, AUTH_USER, AUTH_SCOPE),
  jwt_token_creds: _.partial(authTest, AUTH_USER, null),
  oauth2_auth_token: _.partial(oauth2Test, AUTH_USER, AUTH_SCOPE, false),
  per_rpc_creds: _.partial(oauth2Test, AUTH_USER, AUTH_SCOPE, true)
};

/**
 * Execute a single test case.
 * @param {string} address The address of the server to connect to, in the
 *     format 'hostname:port'
 * @param {string} host_overrirde The hostname of the server to use as an SSL
 *     override
 * @param {string} test_case The name of the test case to run
 * @param {bool} tls Indicates that a secure channel should be used
 * @param {function} done Callback to call when the test is completed. Included
 *     primarily for use with mocha
 */
function runTest(address, host_override, test_case, tls, test_ca, done) {
  // TODO(mlumish): enable TLS functionality
  var options = {};
  var creds;
  if (tls) {
    var ca_path;
    if (test_ca) {
      ca_path = path.join(__dirname, '../test/data/ca.pem');
    } else {
      ca_path = process.env.SSL_CERT_FILE;
    }
    var ca_data = fs.readFileSync(ca_path);
    creds = grpc.Credentials.createSsl(ca_data);
    if (host_override) {
      options['grpc.ssl_target_name_override'] = host_override;
      options['grpc.default_authority'] = host_override;
    }
  } else {
    creds = grpc.Credentials.createInsecure();
  }
  var client = new testProto.TestService(address, creds, options);

  test_cases[test_case](client, done);
}

if (require.main === module) {
  var parseArgs = require('minimist');
  var argv = parseArgs(process.argv, {
    string: ['server_host', 'server_host_override', 'server_port', 'test_case',
             'use_tls', 'use_test_ca']
  });
  runTest(argv.server_host + ':' + argv.server_port, argv.server_host_override,
          argv.test_case, argv.use_tls === 'true', argv.use_test_ca === 'true',
          function () {
            console.log('OK:', argv.test_case);
          });
}

/**
 * See docs for runTest
 */
exports.runTest = runTest;


text:
<?php

namespace Molajo\User\Mocks;

use CommonApi\Fieldhandler\FieldhandlerInterface;

class MockFieldHandler implements FieldhandlerInterface
{
    public function validate($field_name, $field_value = null, $constraint, array $options = array())
    {
        return true;
    }

    public function sanitize($field_name, $field_value = null, $constraint, array $options = array())
    {
        return $field_value;
    }

    public function format($field_name, $field_value = null, $constraint, array $options = array())
    {
        return $field_value;
    }
}


text:
package seu.controller;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
import seu.service.LibraryService;
import seu.service.StudentService;

import java.text.SimpleDateFormat;

public class LibraryTestController {

    LibraryService libraryService=new LibraryService();

    StudentService studentService=new StudentService();
    @FXML
    private TableView<studentLibraryTable> borrowBookTable;

    @FXML
    private TableView<studentLibraryTable> studentBookTable;

    @FXML
    private TableColumn<studentLibraryTable, String> bookName, startDate, returnBook;

    @FXML
    private TableColumn<studentLibraryTable, Integer> bookID;

    @FXML
    private TableColumn<studentLibraryTable, String> bookNameBorrow,borrowConfirm;

    @FXML
    private TableColumn<studentLibraryTable, Integer> bookIDBorrow;

   private  ObservableList<studentLibraryTable> bookLists= FXCollections.observableArrayList();

    private  ObservableList<studentLibraryTable> borrowbookLists= FXCollections.observableArrayList();

    private int studentID;

    public ObservableList<studentLibraryTable> getBooksData() {
       System.out.print(this.studentID);
       System.out.print( libraryService.getAllBookList(this.studentID).size());
        for(int i=0;i< libraryService.getAllBookList(this.studentID).size();i++)
       {
             SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
             String date=sdf.format( libraryService.getAllBookList(this.studentID).get(i).getStartDate());
             studentLibraryTable stu = new studentLibraryTable( libraryService. getAllBookList(this.studentID).get(i).getBookName(),
                     libraryService.getAllBookList(this.studentID).get(i).getBookId(),date);

               bookLists.add(stu);

         }

        System.out.print(3);

        return bookLists;
    }

    public void showBooksTable(final ObservableList<studentLibraryTable> bookLists) {
        bookName.setCellValueFactory(new PropertyValueFactory<studentLibraryTable, String>("bookName"));
        bookID.setCellValueFactory(new PropertyValueFactory<studentLibraryTable, Integer>("bookID"));
        startDate.setCellValueFactory(new PropertyValueFactory<studentLibraryTable, String>("startDate"));
        returnBook.setCellValueFactory(new PropertyValueFactory<studentLibraryTable, String>("DUMMY"));

      Callback<TableColumn<studentLibraryTable, String>, TableCell<studentLibraryTable, String>> cellFactory
                = //
                new Callback<TableColumn<studentLibraryTable, String>, TableCell<studentLibraryTable, String>>() {
                    @Override
                    public TableCell call(final TableColumn<studentLibraryTable, String> param) {
                        final TableCell<studentLibraryTable, String> cell = new TableCell<studentLibraryTable, String>() {

                            final Button btn = new Button("确认还书");

                            @Override
                            public void updateItem(String item, boolean empty) {
                                super.updateItem(item, empty);
                                if (empty) {
                                    setGraphic(null);
                                    setText(null);
                                } else {
                                            btn.setOnAction(new EventHandler<ActionEvent>(){
                                        @Override
                                        public void handle(ActionEvent event) {
                                            System.out.println("Button clicked");
                                            System.out.println(getIndex());
                                            show(getIndex());
                                        }
                                    });

                                    setGraphic(btn);
                                    setText(null);
                                }
                            }
                        };
                        return cell;
                    }
                };

        returnBook.setCellFactory(cellFactory);

        studentBookTable.setItems(this.getBooksData());
    }

    public void returnTab(Event event) {
        bookLists= FXCollections.observableArrayList();
        this.showBooksTable(this.getBooksData());
        int end= libraryService.getAllBookList(this.studentID).size()*2-1;
       int start=libraryService.getAllBookList(this.studentID).size()-1;
       bookLists.remove(start,end);
        studentBookTable.refresh();
        System.out.print("图书馆");
    }

    public void getStudentID( int id)
    {
        this.studentID=id;
        bookLists= FXCollections.observableArrayList();
        this.showBooksTable(this.getBooksData());
        int end= libraryService.getAllBookList(this.studentID).size()*2-1;
        int start=libraryService.getAllBookList(this.studentID).size()-1;
        bookLists.remove(start,end);
        studentBookTable.refresh();
        System.out.print("图书馆");

    }
    public void show(int index)
    {
        bookLists.remove(index);
        studentBookTable.refresh();

       libraryService.returnBook(   libraryService.getAllBookList(studentID).get(index).getBookId());
    }

   public ObservableList<studentLibraryTable> getborrowBooksData() {
        System.out.print(this.studentID);
        System.out.print( libraryService.getAllAvailableBook().size());
        for(int i=0;i< libraryService.getAllAvailableBook().size();i++)
        {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            studentLibraryTable stu = new studentLibraryTable( libraryService.getAllAvailableBook().get(i).getBookName(),
                    libraryService.getAllAvailableBook().get(i).getBookId(),"1997.09.11");

            borrowbookLists.add(stu);

        }

        System.out.print(3);

        return  borrowbookLists;
    }

    public void showborrowBooksTable(final ObservableList<studentLibraryTable> borrowbookLists) {
        bookNameBorrow.setCellValueFactory(new PropertyValueFactory<studentLibraryTable, String>("bookName"));
        bookIDBorrow.setCellValueFactory(new PropertyValueFactory<studentLibraryTable, Integer>("bookID"));

       borrowConfirm.setCellValueFactory(new PropertyValueFactory<studentLibraryTable, String>("DUMMY"));

        Callback<TableColumn<studentLibraryTable, String>, TableCell<studentLibraryTable, String>> cellFactory
                = //
                new Callback<TableColumn<studentLibraryTable, String>, TableCell<studentLibraryTable, String>>() {
                    @Override
                    public TableCell call(final TableColumn<studentLibraryTable, String> param) {
                        final TableCell<studentLibraryTable, String> cell = new TableCell<studentLibraryTable, String>() {

                            final Button btn = new Button("借书");

                            @Override
                            public void updateItem(String item, boolean empty) {
                                super.updateItem(item, empty);
                                if (empty) {
                                    setGraphic(null);
                                    setText(null);
                                } else {
                                    btn.setOnAction(new EventHandler<ActionEvent>(){
                                        @Override
                                        public void handle(ActionEvent event) {
                                            System.out.println("Button clicked");
                                            System.out.println(getIndex());
                                            showBorrow(getIndex());
                                        }
                                    });

                                    setGraphic(btn);
                                    setText(null);
                                }
                            }
                        };
                        return cell;
                    }
                };

       borrowConfirm.setCellFactory(cellFactory);

        borrowBookTable.setItems(this.getborrowBooksData());
    }

    public void showBorrow(int index)
    {
        borrowbookLists.remove(index);
        borrowBookTable.refresh();
        libraryService.borrowBook(   this.studentID,libraryService.getAllAvailableBook().get(index).getBookId());
    }

    public void borrowTab(Event event) {
        borrowbookLists= FXCollections.observableArrayList();
        this.showborrowBooksTable(this.getborrowBooksData());
        int end= libraryService.getAllAvailableBook().size()*2-1;
        int start=libraryService.getAllAvailableBook().size()-1;
        borrowbookLists.remove(start,end);
        borrowBookTable.refresh();
        System.out.print("图书馆");
    }
}


text:
using DND.Core.DTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DND.Core.ViewModels
{
    public class BlogPostListViewModel
    {
        public int Page { get; set; }
        public int PageSize { get; set; }
        public IList<BlogPostDTO> Posts { get; set; }
        public int TotalPosts { get; set; }
        public CategoryDTO Category { get; set; }
        public TagDTO Tag { get; set; }
        public AuthorDTO Author { get; set; }
        public string Search { get; set; }
    }
}


text:
var FONT_SIZE = 12;

var sankey_text = function (node) {
	/** @this self */
	var self = this;

	/**
	 * Node data
	 * @member node
	 * @member text
	 * @member id
	 * @member direction
	 */
	self.node = node;
	self.text = node.name;
	self.value = typeof node.value == 'function' ? node.value() : node.value;

	/**
	 * Render attributes
	 * @member fontsize
	 * @member padding
	 * @member pos
	 * @member box
	 * @member def_elem
	 * @member use_elem
	 */
	self.fontsize = 12;
	self.padding = 5;
	self.pos = {'x': 0, 'y': 0};
	self.box = [0,0,0,0];
	self.direction = node.direction;
	self.def_elem;
	self.use_elem;

	self.printed_text = {'title': [], 'amount': ''};

	self.constr();
	return self;
};

// used as static members
sankey_text.prototype.defs = undefined;
sankey_text.prototype.elem = undefined;
sankey_text.prototype.trans_duration = 800;

/**
 * Pre-define text
 * @constructor
 */
sankey_text.prototype.constr = function () {

	this.direction = this.define_dir();
	this.padding = this.onode ? 10 : 5;

	this.define_text();
	return this;
};

sankey_text.prototype.text_anchor = function () {
	return this.direction ? 'start' : 'end';
}

/** Define text element for later use */
sankey_text.prototype.define_text = function () {
	var self = this;

	self.printed_text.title = self.text.split('\n');
	self.printed_text.amount = self.node.pvalue();

	var defid = self.link ? self.link.linktype+self.link.id : self.node.id;
	self.def_elem = self.defs.selectAll('#sdeftext'+defid).data([1]);
	self.def_elem.enter().append('text').attr({'class': 'stext', 'id': 'sdeftext'+defid});

	// create def element for later use.
	self.def_elem.attr({
		'font-size': self.fontsize+'px',
		'text-anchor': self.text_anchor()
	});

	var title = self.printed_text.title;
	var newline = title.length > 1 && title.slice(-1)[0] == '';

	var titlewidth = self.add_title(self.def_elem);
	var amountwidth = self.add_amount(self.def_elem);

	var width = (newline ? Math.max(amountwidth, titlewidth) : titlewidth + amountwidth) + 4;
	var height = title.length*self.fontsize + 4;

	self.box = [0,0,width+self.padding,height];

	return self;
};

sankey_text.prototype.add_title = function (target) {
	var self = this;

	var title = self.printed_text.title;
	var newline = title.length > 1 && title.slice(-1)[0] == '';
	var titlewidth = 0;

	var spans = target.selectAll('.stext_title').data(title);
	spans.enter().append('tspan').attr('class', 'stext_title');
	spans.exit().remove();
	spans.attr({
		'dy': function (d,i) { return i == 0 ? 0 : self.fontsize; },
		'x': 0
	})
	.text(function (d,i) { return title[i] + ((i == title.length-1 && !newline) ? ' ' : ''); })
	.each(function (d,i) { titlewidth = Math.max(titlewidth, this.getComputedTextLength()); });

	return titlewidth;
};

sankey_text.prototype.add_amount = function (target) {
	var self = this;

	var amount = self.printed_text.amount;
	var title = self.printed_text.title;
	var newline = title.length > 1 && title.slice(-1)[0] == '';

	var amountwidth = 0;

	var spans = target.selectAll('.stext_amount').data([amount]);
	spans.enter().append('tspan').attr('class', 'stext_amount');
	spans.exit().remove();
	spans.attr({
		'dy': newline ? self.fontsize : null,
		'x': newline ? 0 : null
	})
	.text(self.printed_text.amount)
	.each(function (d,i) { amountwidth = Math.max(amountwidth, this.getComputedTextLength()); });

	return amountwidth;
};

sankey_text.prototype.update_text = function () {
	var self = this;

	var obj = this.link || this.node;

	var direction = this.define_dir();
	if (direction != this.direction) {

		this.direction = direction;
		this.define_text()
		this.use_elem && this.use_elem.attr('text-anchor', this.text_anchor());
	}

	// update text
	if (this.printed_text.title.join('\n') != obj.name) {

		self.text = obj.name;
		self.printed_text.title = self.text.split('\n');
		self.add_title(self.def_elem);
		self.add_title(self.use_elem);
	}

	// update value
	if (this.printed_text.amount != obj.pvalue()) {

		self.printed_text.amount = self.node.pvalue();
		self.add_amount(self.def_elem);
		self.add_amount(self.use_elem);
	}

	return self;
};

sankey_text.prototype.define_dir = function () {

	var direction = !this.node.targets.length && this.node.id != 9 || this.node.id == 7;
	return direction;
};

/**Draw defined text element */
sankey_text.prototype.draw = function (dx,dy, scale) {
	var self = this;

	self.position(dx,dy,scale);

	var underflow = self.node.underflow && self.node.underflow.value > 0;

	var editable = self.node.editable && self.node.id != 10;

	self.use_elem = self.elem.selectAll('#susetext'+self.node.id).data([1]);
	self.use_elem.enter().append('text').attr({
		'class': 'stext' + (editable ? ' sedit' : ''),
		'id': 'susetext'+self.node.id,
		'transform': 'translate('+self.pos.x+','+self.pos.y+')',
		'font-size': self.fontsize+'px',
		'text-anchor': self.text_anchor()
		//'xlink:href': '#sdeftext'+self.node.id
	})
	.classed('.suf', underflow)
	.each(function (d,i) {

		self.add_title(d3.select(this));
		self.add_amount(d3.select(this));
	});

	self.use_elem
		.classed('suf', underflow)
		//.attr('xlink:href', '#sdeftext'+self.node.id)
		.transition().delay(400).duration(this.trans_duration)
		.attr('transform', 'translate('+self.pos.x+','+self.pos.y+')');

	return self;
};

sankey_text.prototype.remove = function () {
	var self = this;

	var defid = self.link ? self.link.linktype+self.link.id : self.node.id;
	self.defs.selectAll('#sdeftext'+defid).remove();
	self.elem.selectAll('#susetext'+self.node.id).remove();

	return self;
};

/** Define text position */
sankey_text.prototype.position = function (dx, dy, scale) {
	var self = this;

	var center = (self.node.svalue()*scale - self.box[3])/2;
	var x = self.node.pos.x * scale + dx;
	var y = self.node.pos.y * scale + dy + center + self.fontsize;
	x += self.direction ? self.node.width + self.padding : self.padding*-1;

	if (self.node.inode) y = self.node.pos.y * scale + dy + self.fontsize*.8;

	self.pos.x = x;
	self.pos.y = y;
	return self.pos;
};

sankey_text.prototype.coords = function (dx,dy,s) {
	var self = this;
	dx = dx || 0;
	dy = dy || 0;
	s = s || 1;

	var node = self.node,
		x1 = node.pos.x*s + dx,
		y1 = node.pos.y*s + dy,
		x2 = x1 + node.width,
		y2 = y1 + node.svalue();

	if (self.direction) x2 += self.box[2];
	else x1 -= self.box[2];

	var tbo = self.node.svalue()*s - self.box[3];
	if (tbo < 0) {
		y1 -= tbo/2;
		y2 += tbo/2;
	}

	return [x1,y1,x2,y2];
};


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

namespace Amazon.RDS.Model
{
    /// <summary>
    /// <para> Contains the result of a successful invocation of the DescribeReservedDBInstances action. </para>
    /// </summary>
    public class DescribeReservedDBInstancesResult
    {

        private string marker;
        private List<ReservedDBInstance> reservedDBInstances = new List<ReservedDBInstance>();

        /// <summary>
        /// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the
        /// marker, up to the value specified by <c>MaxRecords</c>.
        ///
        /// </summary>
        public string Marker
        {
            get { return this.marker; }
            set { this.marker = value; }
        }

        /// <summary>
        /// Sets the Marker property
        /// </summary>
        /// <param name="marker">The value to set for the Marker property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public DescribeReservedDBInstancesResult WithMarker(string marker)
        {
            this.marker = marker;
            return this;
        }

        // Check to see if Marker property is set
        internal bool IsSetMarker()
        {
            return this.marker != null;
        }

        /// <summary>
        /// A list of of reserved DB Instances.
        ///
        /// </summary>
        public List<ReservedDBInstance> ReservedDBInstances
        {
            get { return this.reservedDBInstances; }
            set { this.reservedDBInstances = value; }
        }
        /// <summary>
        /// Adds elements to the ReservedDBInstances collection
        /// </summary>
        /// <param name="reservedDBInstances">The values to add to the ReservedDBInstances collection </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public DescribeReservedDBInstancesResult WithReservedDBInstances(params ReservedDBInstance[] reservedDBInstances)
        {
            foreach (ReservedDBInstance element in reservedDBInstances)
            {
                this.reservedDBInstances.Add(element);
            }

            return this;
        }

        /// <summary>
        /// Adds elements to the ReservedDBInstances collection
        /// </summary>
        /// <param name="reservedDBInstances">The values to add to the ReservedDBInstances collection </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public DescribeReservedDBInstancesResult WithReservedDBInstances(IEnumerable<ReservedDBInstance> reservedDBInstances)
        {
            foreach (ReservedDBInstance element in reservedDBInstances)
            {
                this.reservedDBInstances.Add(element);
            }

            return this;
        }

        // Check to see if ReservedDBInstances property is set
        internal bool IsSetReservedDBInstances()
        {
            return this.reservedDBInstances.Count > 0;
        }
    }
}


text:
package contexts

import "context"

// upgradeViaDefaultingKey is used as the key in a context.Context.
// This variable doesn't really matter, so it can be a total random name.
// Setting this key indicates that default values for a resource should be
// updated to new values. This is used to ensure non breaking updates when
// a default value of a resource changes or when a field is removed.
type upgradeViaDefaultingKey struct{}

// WithUpgradeViaDefaulting sets the upgradeViaDefaultingKey on the context
// indicating that default values for a resource should be updated to new values.
func WithUpgradeViaDefaulting(ctx context.Context) context.Context {
	return context.WithValue(ctx, upgradeViaDefaultingKey{}, struct{}{})
}

// IsUpgradeViaDefaulting checks if the upgradeViaDefaultingKey is set on
// the context.
func IsUpgradeViaDefaulting(ctx context.Context) bool {
	return ctx.Value(upgradeViaDefaultingKey{}) != nil
}


text:
using System.Net.Http;
using System.Threading.Tasks;
using UltimateTeam.Toolkit.Constants;
using UltimateTeam.Toolkit.Exceptions;

namespace UltimateTeam.Toolkit.Requests
{
    internal class GiftRequest : FutRequestBase, IFutRequest<byte>
    {
        private readonly int _idGift;

        public GiftRequest(int idGift)
        {
            _idGift = idGift;
        }

        public async Task<byte> PerformRequestAsync()
        {
            if (AppVersion != AppVersion.WebApp)
            {
                throw new FutException($"Not implemented for {AppVersion}");
            }

            AddCommonHeaders(HttpMethod.Delete);
            var activeMessageRedeemResponseMessage = await HttpClient.PostAsync(
                string.Format(Resources.FutHome + Resources.ActiveMessageGet, _idGift),
                new StringContent(" ")).ConfigureAwait(false);

            activeMessageRedeemResponseMessage.EnsureSuccessStatusCode();

            return 0;
        }
    }
}


text:
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <!-- Meta, title, CSS, favicons, etc. -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="-1">
    <meta http-equiv="pragma" content="no-cache">
    <title>Thiết bị An Ninh | Astech Việt Nam</title>
    <link href="/web/images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <!-- Bootstrap -->

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<!--    <link href="https://colorlib.com/polygon/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">-->
    <!-- Font Awesome -->
    <link href="https://colorlib.com/polygon/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <!-- Custom Theme Style -->
    <link href="/css/custom.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <link href="/css/define.css" rel="stylesheet">
    <link href="/css/vxgplayer-1.7.44.min.css" rel="stylesheet">
    <link href="/css/bootstrap-switch.css" rel="stylesheet">
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

    <script src="http://vjs.zencdn.net/5.10/video.js"></script>
    <script src="/js/videojs-contrib-hls.js"></script>

    <script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
    <script src="/js/validator.js"></script>
    <script src="/js/multiselect.js"></script>
    <script src="/js/vxgplayer-1.7.44.min.js"></script>
    <script src="/js/bootstrap-switch.js"></script>
    <script src="/js/watch.js"></script>
    <link href="/images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <script>
        var lever = parseInt(<?= Yii::$app->user->identity->level;?>);
    </script>
	 <script type="text/javascript">
           var YII_CSRF_TOKEN = "<?php print Yii::$app->request->csrfToken; ?>";
      </script>
</head>


text:
import { FixtureList } from '../../renderer';
import { FixtureTreeNode } from '../shared/types';
import { createRawFixtureTree } from './createRawFixtureTree';

it('creates tree with fixture', () => {
  const fixtures: FixtureList = {
    'Dashboard.fixture.js': { type: 'single' },
  };
  const tree: FixtureTreeNode = {
    data: { type: 'fileDir' },
    children: {
      'Dashboard.fixture': {
        data: {
          type: 'fixture',
          fixtureId: { path: 'Dashboard.fixture.js' },
        },
      },
    },
  };
  expect(createRawFixtureTree(fixtures)).toEqual(tree);
});

it('creates nested tree with fixture', () => {
  const fixtures: FixtureList = {
    'ui/Dashboard.fixture.js': { type: 'single' },
  };
  const tree: FixtureTreeNode = {
    data: { type: 'fileDir' },
    children: {
      ui: {
        data: { type: 'fileDir' },
        children: {
          'Dashboard.fixture': {
            data: {
              type: 'fixture',
              fixtureId: { path: 'ui/Dashboard.fixture.js' },
            },
          },
        },
      },
    },
  };
  expect(createRawFixtureTree(fixtures)).toEqual(tree);
});

it('creates tree with multi fixture', () => {
  const fixtures: FixtureList = {
    'Button.fixture.js': {
      type: 'multi',
      fixtureNames: ['normal', 'disabled'],
    },
  };
  const tree: FixtureTreeNode = {
    data: { type: 'fileDir' },
    children: {
      'Button.fixture': {
        data: {
          type: 'multiFixture',
          fixtureIds: {
            normal: { path: 'Button.fixture.js', name: 'normal' },
            disabled: { path: 'Button.fixture.js', name: 'disabled' },
          },
        },
      },
    },
  };
  expect(createRawFixtureTree(fixtures)).toEqual(tree);
});

it('creates nested tree with multi fixture', () => {
  const fixtures: FixtureList = {
    'ui/Button.fixture.js': {
      type: 'multi',
      fixtureNames: ['normal', 'disabled'],
    },
  };
  const tree: FixtureTreeNode = {
    data: { type: 'fileDir' },
    children: {
      ui: {
        data: { type: 'fileDir' },
        children: {
          'Button.fixture': {
            data: {
              type: 'multiFixture',
              fixtureIds: {
                normal: { path: 'ui/Button.fixture.js', name: 'normal' },
                disabled: { path: 'ui/Button.fixture.js', name: 'disabled' },
              },
            },
          },
        },
      },
    },
  };
  expect(createRawFixtureTree(fixtures)).toEqual(tree);
});


text:
require File.expand_path(File.dirname(__FILE__)) + '/../helper'

class LensToolTest < Test::Unit::TestCase

  include Approximately

  def test_action_description
    assert_equal "Apply or remove lens distortion with the Syntheyes algorithm", Tracksperanto::Tool::LensDisto.action_description
  end

  def test_lens_bypasses_centerpoint
    receiver = flexmock
    receiver.should_receive(:start_export).once.with(1920, 1080)
    receiver.should_receive(:start_tracker_segment).once.with("Tracker")
    receiver.should_receive(:export_point).once.with(1, 1920 / 2.0, 1080.0 / 2.0, 0)
    receiver.should_receive(:end_tracker_segment).once
    receiver.should_receive(:end_export).once

    m = Tracksperanto::Tool::LensDisto.new(receiver, :k => 0.0168)
    m.start_export(1920, 1080)
    m.start_tracker_segment("Tracker")
    m.export_point(1, 1920 / 2.0, 1080.0 / 2.0, 0)
    m.end_tracker_segment
    m.end_export
  end

  def test_lens_distorted
    receiver = flexmock
    receiver.should_receive(:start_export).once.with(1920, 1080)
    receiver.should_receive(:start_tracker_segment).once.with("Tracker")
    receiver.should_receive(:export_point).once.with(1, approx(66.06), approx(43.99), approx(0))

    receiver.should_receive(:end_tracker_segment).once
    receiver.should_receive(:end_export).once

    m = Tracksperanto::Tool::LensDisto.new(receiver, :k => -0.0298, :kcube => 0.0078)
    m.start_export(1920, 1080)
    m.start_tracker_segment("Tracker")
    m.export_point(1, 12.0, 14.0, 0)
    m.end_tracker_segment
    m.end_export
  end

  def test_lens_undistorted
    receiver = flexmock
    receiver.should_receive(:start_export).once.with(1920, 1080)
    receiver.should_receive(:start_tracker_segment).once.with("Tracker")
    receiver.should_receive(:export_point).once.with(1, approx(11.96), approx(13.98), 0)
    receiver.should_receive(:end_tracker_segment).once
    receiver.should_receive(:end_export).once

    m = Tracksperanto::Tool::LensDisto.new(receiver, :k => -0.0298, :kcube => 0.0078, :remove => true)
    m.start_export(1920, 1080)
    m.start_tracker_segment("Tracker")
    m.export_point(1, 66.03001446825158, 43.978678913818925, 0)
    m.end_tracker_segment
    m.end_export
  end

  def test_roundtrip
    receiver = flexmock
    receiver.should_receive(:start_export).once.with(1920, 1080)
    receiver.should_receive(:start_tracker_segment).once.with("Tracker")
    receiver.should_receive(:export_point).once.with(1, approx(0.984), approx(0.991), 0)
    receiver.should_receive(:end_tracker_segment).once
    receiver.should_receive(:end_export).once

    apply = Tracksperanto::Tool::LensDisto.new(receiver, :k => -0.0298, :kcube => 0.2178)
    remove = Tracksperanto::Tool::LensDisto.new(apply, :k => -0.0298, :kcube => 0.2178, :remove => true)

    remove.start_export(1920, 1080)
    remove.start_tracker_segment("Tracker")
    remove.export_point(1, 1.0, 1.0, 0)
    remove.end_tracker_segment
    remove.end_export
  end
end


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CodeCracker.CSharp.Style
{
    [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PropertyPrivateSetCodeFixProvider)), Shared]
    public class PropertyPrivateSetCodeFixProvider : CodeFixProvider
    {
        private enum FixType { PrivateFix, ProtectedFix }

        public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(DiagnosticId.PropertyPrivateSet.ToDiagnosticId());

        public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;

        public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            context.RegisterCodeFix(CodeAction.Create("Change property to 'private set'", c => ChangePropertySetAsync(context.Document, diagnostic, c, FixType.PrivateFix), nameof(PropertyPrivateSetCodeFixProvider) + nameof(FixType.PrivateFix)), diagnostic);
            context.RegisterCodeFix(CodeAction.Create("Change property to 'protected set'", c => ChangePropertySetAsync(context.Document, diagnostic, c, FixType.ProtectedFix), nameof(PropertyPrivateSetCodeFixProvider) + nameof(FixType.ProtectedFix)), diagnostic);
            return Task.FromResult(0);
        }

        private async static Task<Document> ChangePropertySetAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken, FixType fixType)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var propertyStatement = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().First();
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken);

            var setAcessor = (propertyStatement.AccessorList.Accessors[0].Keyword.Text == "set") ? propertyStatement.AccessorList.Accessors[0] : propertyStatement.AccessorList.Accessors[1];
            var privateprotectedModifier = SyntaxFactory.Token(fixType == FixType.PrivateFix ? SyntaxKind.PrivateKeyword : SyntaxKind.ProtectedKeyword)
                    .WithTrailingTrivia(setAcessor.GetTrailingTrivia())
                    .WithLeadingTrivia(setAcessor.GetLeadingTrivia());

            var newSet = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAcessor.AttributeLists, SyntaxTokenList.Create(privateprotectedModifier), setAcessor.Body);
            if(setAcessor.Body == null) newSet = newSet.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            var newProperty = propertyStatement.ReplaceNode(setAcessor, newSet);

            var newRoot = root.ReplaceNode(propertyStatement, newProperty);
            var newDocument = document.WithSyntaxRoot(newRoot);
            return newDocument;
        }
    }
}


text:
$(document).ready(function() {
    try {
        function csrf_token() {
            return $("#csrf-token").attr("data-token");
        };

        $(".breed-select").select2({
            ajax: {
                url: "/api/breeds",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term
                    };
                },
                cache: true
            },
            minimumInputLength: 1,
            placeholder: "We love all kinds of puppies..."
        });

        $(".age-select").select2({
            placeholder: "How old is he?"
        });

        $('.ajax').magnificPopup({
            type: 'ajax'
        });

        //magnific popup
        var mfpImage = {
            tError: 'The image #%curr% could not be loaded.',
            titleSrc: function(item) {
                return '{1} '
                    .format(
                        item.el.attr('data-gallery-url'),
                        item.el.attr('title')
                    );
            }
        }

        $('.popup-gallery').not(".dog-can-do .popup-gallery").magnificPopup({
            delegate: 'a',
            type: 'image',
            tLoading: 'Loading image #%curr%, please wait...',
            mainClass: 'mfp-img-mobile',
            gallery: {
                enabled: true,
                navigateByImgClick: true,
                preload: [0,1]
            },
            image: mfpImage
        });

        $('.popup-image').magnificPopup({
            delegate: 'a',
            type: 'image',
            tLoading: 'Loading image #%curr%, please wait...',
            mainClass: 'mfp-img-mobile',
            image: mfpImage
        });

        var upload_targets = [];
        $('#direct_upload input[type="file"]')
            .cloudinary_fileupload({
                dropZone: '#direct_upload',
                start: function () {
                    var target = $('

');
                    upload_targets.push(target);
                    target.insertAfter($("#thumbnails").children().eq(0))
                    console.log('Starting direct upload...');
                },
                progress: function () {
                    console.log("uploading");
                },
            })
            .on('cloudinarydone', function (e, data) {
                $.post(this.form.action, $(this.form).serialize()).always(function (result, status, jqxhr) {
                    var target = upload_targets.pop();
                    target.replaceWith(result);
                });
            });

        //
        // dog can do
        //
        $(".dog-can-do").on('click', 'a.thumbnail', function(event) {
            var result = confirm("Do you want to choose this picture?");
            event.preventDefault();
            if (result != true) {
                return;
            }
            var picture_id = $(this).attr("data-picture-id");
            var form = $("#dog_can_do_form");
            form.find("input[name=picture_id]")[0].value = picture_id;
            form.submit();
        });

        //
        //editor
        //
        var editable = $("#post_body");
        var source = $('#id_body');

        editable.hallo({
            plugins: {
                'halloformat': {},
                'halloheadings': {},
                'hallolists': {},
                'hallojustify': {},
                'hallolink': {},
                'halloreundo': {}
            },
            toolbar: 'halloToolbarFixed'
        });

        editable.bind('hallomodified', function(event, data) {
            update_source(data.content);
        });

        editable.bind('halloactivated', function(event, data) {
            //select content
            var range = rangy.createRange();
            range.selectNodeContents(editable[0]);
            var sel = rangy.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        });

        function convert_to_markdown(content) {
            var html = content.split("\n").map($.trim).filter(function(line) {
                return line != "";
            }).join("\n");
            return toMarkdown(html);
        };

        function update_source(content) {
            var markdown = convert_to_markdown(content);
            if (source.get(0).value == markdown) {
                return;
            }
            source.get(0).value = markdown;
        };

        if(editable.length > 0) {
            update_source(editable.html());
        }

        //
        //Parsley
        //
        window.ParsleyConfig = {
            errorClass: 'has-error',
            successClass: 'has-success',
            classHandler: function(ParsleyField) {
                return ParsleyField.$element.parents('.form-group');
            },
            errorsContainer: function(ParsleyField) {
                return ParsleyField.$element.parents('.form-group');
            },
            errorsWrapper: '',
            errorTemplate: '

'
        };
    } catch(err) {
        Raven.captureException(err);
    }
});

String.prototype.format = function() {
    var s = this;
    var i = arguments.length;
    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};


text:
import json
import urllib

from cinder import context
from cinder import db
from cinder import exception
from cinder.tests.unit import fake_snapshot
from cinder.tests.unit import fake_volume
from cinder.tests.unit.volume.drivers.emc import scaleio
from cinder.tests.unit.volume.drivers.emc.scaleio import mocks

class TestCreateSnapShot(scaleio.TestScaleIODriver):
    """Test cases for ``ScaleIODriver.create_snapshot()``"""
    def return_fake_volume(self, ctx, id):
        return self.fake_volume

    def setUp(self):
        """Setup a test case environment.

        Creates fake volume and snapshot objects and sets up the required
        API responses.
        """
        super(TestCreateSnapShot, self).setUp()
        ctx = context.RequestContext('fake', 'fake', auth_token=True)

        self.fake_volume = fake_volume.fake_volume_obj(
            ctx, **{'provider_id': 'fake_pid'})

        self.snapshot = fake_snapshot.fake_snapshot_obj(
            ctx, **{'volume': self.fake_volume})

        self.mock_object(db, 'volume_get', self.return_fake_volume)

        self.volume_name_2x_enc = urllib.quote(
            urllib.quote(self.driver._id_to_base64(self.snapshot.volume_id))
        )
        self.snapshot_name_2x_enc = urllib.quote(
            urllib.quote(self.driver._id_to_base64(self.snapshot.id))
        )

        self.snapshot_reply = json.dumps(
            {
                'volumeIdList': ['cloned'],
                'snapshotGroupId': 'cloned_snapshot'
            }
        )

        self.HTTPS_MOCK_RESPONSES = {
            self.RESPONSE_MODE.Valid: {
                'types/Volume/instances/getByName::' +
                self.volume_name_2x_enc: '"{}"'.format(
                    self.snapshot.volume_id
                ),
                'instances/System/action/snapshotVolumes':
                    self.snapshot_reply,
                'types/Volume/instances/getByName::' +
                self.snapshot_name_2x_enc: self.snapshot.id,
            },
            self.RESPONSE_MODE.BadStatus: {
                'types/Volume/instances/getByName::' +
                self.volume_name_2x_enc: self.BAD_STATUS_RESPONSE,
                'types/Volume/instances/getByName::' +
                self.snapshot_name_2x_enc: self.BAD_STATUS_RESPONSE,
                'instances/System/action/snapshotVolumes':
                    self.BAD_STATUS_RESPONSE,
            },
            self.RESPONSE_MODE.Invalid: {
                'types/Volume/instances/getByName::' +
                self.volume_name_2x_enc: None,
                'instances/System/action/snapshotVolumes':
                    mocks.MockHTTPSResponse(
                        {
                            'errorCode': 400,
                            'message': 'Invalid Volume Snapshot Test'
                        }, 400
                    ),
            },
        }

    def test_bad_login(self):
        self.set_https_response_mode(self.RESPONSE_MODE.BadStatus)
        self.assertRaises(
            exception.VolumeBackendAPIException,
            self.driver.create_snapshot,
            self.snapshot
        )

    def test_invalid_volume(self):
        self.set_https_response_mode(self.RESPONSE_MODE.Invalid)
        self.assertRaises(
            exception.VolumeBackendAPIException,
            self.driver.create_snapshot,
            self.snapshot
        )

    def test_create_snapshot(self):
        self.set_https_response_mode(self.RESPONSE_MODE.Valid)
        self.driver.create_snapshot(self.snapshot)


text:
require 'chefspec'
require 'chefspec/policyfile'

# do a code coverage report at the end
RSpec.configure do |config|
  config.after(:all) do
		ChefSpec::Coverage.start!
  end
end

shared_examples 'converged machine' do |expected|
  # instance name
  it 'creates with the correct machine name' do
    expect(chef_run).to converge_machine(expected[:name])
  end

  # operating system
  it 'creates with correct instance os' do
    expect(chef_run.machine(expected[:name]).machine_options[:is_windows]).to eq(expected[:is_windows])
  end

  # vpc and subnet references
  it 'creates with correct vpc and subnet references' do
    expect(chef_run).to create_machine_in_vpc(expected[:name])
    expect(chef_run.aws_vpc_machine(expected[:name]).vpc_name).to eq(expected[:vpc_name])
    expect(chef_run.aws_vpc_machine(expected[:name]).subnet_name).to eq(expected[:subnet_name])
    expect(chef_run.aws_vpc_machine(expected[:name]).security_group_ids).to eq(expected[:security_group_ids])
  end

  # verify all bootstrap options
  %i{availability_zone security_groups subnet image_id instance_type key_name iam_instance_profile block_device_mappings}.each do |key|
    it ('creates with correct ' + key.to_s) do
      expect(chef_run.machine(expected[:name]).machine_options[:bootstrap_options][key]).to eq(expected[:bootstrap_options][key])
    end
  end

  it 'creates with correct chef policy' do
    expect(chef_run.aws_vpc_machine(expected[:name]).policy_group).to eq(expected[:policy_group])
    expect(chef_run.aws_vpc_machine(expected[:name]).policy_name).to eq(expected[:policy_name])
  end
end

shared_examples 'destroyed machine' do |expected|
  # vpc and subnet references
  it 'destroys with correct vpc and subnet references' do
    expect(chef_run).to destroy_machine_in_vpc(expected[:name])
    expect(chef_run).to destroy_machine(expected[:name])
    expect(chef_run.aws_vpc_machine(expected[:name]).vpc_name).to eq(expected[:vpc_name])
    expect(chef_run.aws_vpc_machine(expected[:name]).subnet_name).to eq(expected[:subnet_name])
    expect(chef_run.aws_vpc_machine(expected[:name]).security_group_ids).to eq(expected[:security_group_ids])
  end
end


text:
<?php

namespace BIT\GoogleBundle\Google;

use Google_Service_Exception;
use Google_Service_Urlshortener;
use Google_Service_Urlshortener_Url;

/**
 * Implements Google URl Shorter.
 */
class GoogleURLShorter
{
    private $googleClient;

    public function __construct(GoogleClient $googleClient)
    {
        $this->googleClient = $googleClient->getWithoutAuthorization();
    }

    public function short($url)
    {
        try {
            // create url
            $urlShortener = new Google_Service_Urlshortener_Url();
            $urlShortener->longUrl = $url;

            // create service
            $googleServiceUrlshortener = new Google_Service_Urlshortener($this->googleClient);

            // short it
            $shortUrl = $googleServiceUrlshortener->url->insert($urlShortener);
            if (array_key_exists('id', $shortUrl)) {
                return $shortUrl['id'];
            }
        } catch (Google_Service_Exception $e) {
            return $e->getMessage();
        }

        return null;
    }

    public function getClient()
    {
        return $this->googleClient;
    }
}


text:
<?php

namespace Rocketeer;

use Rocketeer\Traits\ContainerAwareTrait;

/**
 * Handles interaction between the User provided informations
 * and the various Rocketeer components.
 */
class Rocketeer
{
    use ContainerAwareTrait;

    /**
     * The specific commit built.
     */
    const COMMIT = '@commit@';

    /**
     * Global local mode.
     *
     * @var bool
     */
    protected $local = false;

    /**
     * Returns what stage Rocketeer thinks he's in.
     *
     * @param string      $application
     * @param string|null $path
     *
     * @return string|false
     */
    public static function getDetectedStage($application = 'application', $path = null)
    {
        $folderRegex = '[a-zA-Z0-9_-]+';

        $current = $path ?: realpath(__DIR__);
        $pattern = sprintf('/%s\/(%s)\/%s\/([0-9]{14})/', $application, $folderRegex, $folderRegex);
        preg_match($pattern, $current, $matches);

        return isset($matches[1]) ? $matches[1] : false;
    }

    //////////////////////////////////////////////////////////////////////
    /////////////////////////////// LOCAL ////////////////////////////////
    //////////////////////////////////////////////////////////////////////

    /**
     * @return bool
     */
    public function isLocal()
    {
        return $this->local;
    }

    /**
     * @param bool $local
     */
    public function setLocal($local)
    {
        $this->local = $local;
    }
}


text:
##workflow description

#First get picture by gimp -> xcf originals put it all in a folder
#run the programm from that folder
#xcf is converted to png original resolution png
#this png converted to png 1400 and png 600 for better handling
#for overview contact-sheet is build

#you need xcf_tools installed and imageMagick
# got only metatag to work with exiftool
#apt-get install libimage-exiftool-perl

#directorystructure
#project_name
#      |
#      |
#      |
#      |__png_full
#      |
#      |__png_1400
#      |
#      |__png_600
#      |__jpg_600
#
#You have to create a project-folder and put all xcf there.Then go there and run xcf_.sh The rest is created.
#
#      if you want to have a signiture in the right corner put a file with the signiture in the the directory of the programmfile. It must be a transparent file as png in the same directory your xcf_.sh file is

# recommend the tool contact to create contact-sheets.
# http://github.com/jmhobbs/helper-scripts

mkdir -p "./full_png"
mkdir -p "./png_1400"
mkdir -p "./png_600"
mkdir -p "./jpg_600"

###change this to your name
author="your name your www.adress"

for file in ./*
do
    if [ -f "$file" ]; then
        echo $file
        filename=${file##*/}
        filename="${filename%.*}.png"
        jpgfilename="${filename%.*}.jpg"
        echo "FILENAME ---->"
        echo $filename
        xcf2png -g "$file" -o "./full_png/$filename"
        ret=$?
        ##if this was ok (no color) then process the rest with greyscale params
        greyscale=""
        if [ $ret == 0 ]; then
        greyscale="-type Grayscale"
        fi
        if [ $ret == "103" ]; then
            xcf2png "$file" -o "./full_png/$filename"
        fi
          convert  "./full_png/$filename"  $greyscale -resize 1400x1400 "./png_1400/1400_$filename"
          convert  "./full_png/$filename"  $greyscale -resize 600x600 "./png_600/600_$filename"
          convert  "./full_png/$filename"  $greyscale -resize 600x600 "./jpg_600/600_$jpgfilename"
          ##put author in jpg
          exiftool -Comment="$author" ./jpg_600/600_$jpgfilename
          rm ./jpg_600/600_"$jpgfilename"_original
      fi
done