text:
<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Silex\Application;
use Drivegal\GalleryInfo;
use Drivegal\GalleryService;
use Drivegal\Authenticator;
use Drivegal\Exception\AlbumNotFoundException;
use Drivegal\Exception\ServiceAuthException;
use Drivegal\Exception\ServiceException;
use JasonGrimes\Paginator;

//Request::setTrustedProxies(array('127.0.0.1'));

/** @var Application $app */
global $app;

//
// Helper function to convert a route parameter into a gallery.
//
$galleryProvider = function($galleryInfo, Request $request) use ($app) {
    if ($slug = $request->attributes->get('gallery_slug')) {
        $galleryInfo = $app['gallery.info.mapper']->findBySlug($slug);
    } elseif ($id = $request->attributes->get('google_user_id')) {
        $galleryInfo = $app['gallery.info.mapper']->findByGoogleUserId($id);
    }
    if (!$galleryInfo instanceof GalleryInfo) {
        throw new NotFoundHttpException('Gallery "' . ($slug ?: $id) . '" not found.');
    }

    return $galleryInfo;
};

//
// Error handlers
//
$app->error(function(ServiceAuthException $e, $code) use ($app) {
    return new Response($app['twig']->render('errors/gallery-auth-failed.twig'));
});
$app->error(function (\Exception $e, $code) use ($app) {
    if ($app['debug']) {
        return;
    }

    $message = '';
    switch (get_class($e)) {
        case 'Drivegal\Exception\ServiceException':
            $code = 503;
            $message = 'The Google Drive server returned an error.';
            break;
    }

    // 404.html, or 40x.html, or 4xx.html, or error.html
    $templates = array(
        'errors/'.$code.'.html',
        'errors/'.substr($code, 0, 2).'x.html',
        'errors/'.substr($code, 0, 1).'xx.html',
        'errors/default.html',
    );

    return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code, 'message' => $message)), $code);
});

//
// Controller: Home page.
//
$app->get('/', function () use ($app) {
    return $app['twig']->render('index.twig', array());
})
->bind('homepage')
;

//
// Controller: Connect to a Google Drive account (to set up a gallery)
//
$app->get('/setup', function() use ($app) {
    return $app['twig']->render('setup.twig', array('auth_url' => $app['authenticator']->getAuthUrl()));
})
->bind('setup')
;

//
// Controller: Handle OAuth redirects from Google to authorize a gallery.
//
$app->get('/oauth', function(Application $app, Request $request) {
    if ($error_code = $request->query->get('error')) {
        if ($error_code == 'access_denied') { // The user refused to grant access.
            $error = 'The connection attempt was canceled.';
        } else {
            $error = 'Connection failed with the following error: "' . $error_code . '"';
        }
        $app['session']->getFlashBag()->add('error', $error);

        return $app->redirect($app['url_generator']->generate('setup'));
    }

    $auth_result = $app['authenticator']->authorizeGallery($request->query->get('code'));
    if ($auth_result['success']) {
        $app['session']->getFlashBag()->add('just-connected', true);
        // $app['session']->getFlashBag()->add('success', 'Successfully connected to your Google Drive account.');

        return $app->redirect($app['url_generator']->generate('settings'));
    } else {
        $app['session']->getFlashBag()->add('error', $auth_result['error']);

        return $app->redirect($app['url_generator']->generate('setup'));
    }
});

//
// Controller: Deactivate gallery
//
$app->get('/deactivate', function(Application $app) {
    if (!$app['user']) {
        $app['session']->getFlashBag()->add('error', 'Please log in to find your gallery.');

        return $app->redirect($app['url_generator']->generate('login'));
    }

    $galleryInfo = $app['gallery.info.mapper']->findByGoogleUserId($app['user']->getCustomField('googleUserId'));
    if (!$galleryInfo) {
        $app['session']->getFlashBag()->add('error', 'You haven\'t set up a gallery for this Google account yet.');

        return $app->redirect($app['url_generator']->generate('setup'));
    }

    if ($app['gallery']->deactivateGallery($galleryInfo)) {
        $app['session']->getFlashBag()->add('success', 'Disconnected from your Google Drive account and deactivated your gallery.');

        return $app->redirect($app['url_generator']->generate('setup'));
    } else {
        $app['session']->getFlashBag()->add('error', 'Error disconnecting from your Google Drive account.');

        return $app->redirect($app['url_generator']->generate('settings'));
    }

})
->bind('deactivate');

//
// Controller: Manage settings for a gallery.
//
$app->match('/settings', function(Application $app, Request $request) {
    if (!$app['user']) {
        $app['session']->getFlashBag()->add('error', 'You must sign in to edit your settings.');
        return $app->redirect($app['url_generator']->generate('login'));
    }

    /** @var GalleryInfo $galleryInfo */
    $galleryInfo = $app['gallery.info.mapper']->findByGoogleUserId($app['user']->getCustomField('googleUserId'));
    if (!$galleryInfo) {
        $app['session']->getFlashBag()->add('error', 'You don\'t have a gallery set up yet. You can set one up below.');
        return $app->redirect($app['url_generator']->generate('setup'));
    }
    if (!$galleryInfo->getIsActive()) {
        $app['session']->getFlashBag()->add('error', 'Your gallery was deactivated. You can reactivate it by connecting to your Google Drive below.');
        return $app->redirect($app['url_generator']->generate('setup'));
    }

    // Process form submissions.
    if ($request->isMethod('POST')) {
        $galleryInfo->setSlug($request->request->get('slug'));
        $galleryInfo->setGalleryName($request->request->get('galleryName'));

        $errors = $app['gallery']->validateGalleryInfo($galleryInfo);
        if (count($errors) > 0) {
            foreach ($errors as $error) {
                $app['session']->getFlashBag()->add('error', $error);
            }
        } else {
            // Save the gallery info
            $app['gallery.info.mapper']->save($galleryInfo);
            $app['session']->getFlashBag()->add('success', 'Saved gallery info.');

            return $app->redirect($app['url_generator']->generate('my-gallery'));
        }
    }

    return $app['twig']->render('edit.twig', array(
        'galleryInfo' => $galleryInfo,
        'galleryUrl' => 'http://drivegal.com/' . $galleryInfo->getSlug(),
    ));
})
->bind('settings')
;

//
// Controller: View the top-level album list.
//
$app->get('/{gallery_slug}/album/', function(Application $app, GalleryInfo $galleryInfo) {
    $albumContents = $app['gallery']->getAlbumContents($galleryInfo, '');
    return $app['twig']->render('album.twig', array(
        'galleryName' => $galleryInfo->getGalleryName(),
        'albumTitle' => 'Album list',
        'subAlbums' => $albumContents->getSubAlbums(),
        'files' => '',
        'breadcrumbs' => $albumContents->getBreadcrumbs(),
        'albumUrl' => $app['url_generator']->generate('album-list', array('gallery_slug' => $galleryInfo->getSlug())),
        'streamUrl' => $app['url_generator']->generate('gallery', array('gallery_slug' => $galleryInfo->getSlug())),
        'nextUrl' => '',
        'prevUrl' => '',
        'showLightboxPhoto' => '',
        'gallerySlug' => $galleryInfo->getSlug(),
    ));
})
->assert('gallery_slug', '^[^_][^/]+') // slug can't start with an underscore or contain a slash (we have to specify that manually since we override the default regex).
->convert('galleryInfo', $galleryProvider)
->bind('album-list')
;

//
// Controller: View an album in a gallery
//
$app->get('/{gallery_slug}/album/{album_path}/', function(Application $app, GalleryInfo $galleryInfo, $album_path) {
    try {
        /** @var \Drivegal\AlbumContents $albumContents */
        $albumContents = $app['gallery']->getAlbumContents($galleryInfo, $album_path);
    } catch (AlbumNotFoundException $e) {
        $app['session']->getFlashBag()->add('error', 'Album "' . $album_path . '" not found.');
        return $app->redirect($app['url_generator']->generate('gallery', array('gallery_slug' => $galleryInfo->getSlug())));
    }

    return $app['twig']->render('album.twig', array(
        'galleryName' => $galleryInfo->getGalleryName(),
        'albumTitle' => $albumContents->getTitle(),
        'files' => $albumContents->getFiles(),
        'subAlbums' => $albumContents->getSubAlbums(),
        'breadcrumbs' => $albumContents->getBreadcrumbs(),
        'albumUrl' => $app['url_generator']->generate('album-list', array('gallery_slug' => $galleryInfo->getSlug())),
        'streamUrl' => $app['url_generator']->generate('gallery', array('gallery_slug' => $galleryInfo->getSlug())),
        'showLightboxPhoto' => '',
        'gallerySlug' => $galleryInfo->getSlug(),
    ));
})
->assert('gallery_slug', '^[^_][^/]+') // slug can't start with an underscore or contain a slash (we have to specify that manually since we override the default regex).
->assert('album_path', '.*') // album path *can* contain slashes.
->convert('galleryInfo', $galleryProvider)
->value('album_path', '')
->bind('album')
;

//
// Middleware: Determine the current user.
//
$app->before(function (Symfony\Component\HttpFoundation\Request $request) use ($app) {
    $token = $app['security']->getToken();
    // echo '<pre>' . print_r($token, true);
    $app['user'] = null;

    if ($token && !$app['security.trust_resolver']->isAnonymous($token)) {
        $app['user'] = $token->getUser();
    }
});

//
// Controller: Login
//
$app->get('/login', function () use ($app) {
    $services = array_keys($app['oauth.services']);

    return $app['twig']->render('login.twig', array(
        'login_paths' => array_map(function ($service) use ($app) {
            return $app['url_generator']->generate('_auth_service', array(
                'service' => $service,
                '_csrf_token' => $app['form.csrf_provider']->generateCsrfToken('oauth')
            ));
        }, array_combine($services, $services)),
        'logout_path' => $app['url_generator']->generate('logout', array(
                '_csrf_token' => $app['form.csrf_provider']->generateCsrfToken('logout')
            ))
    ));
})
->bind('login');

//
// Controller: Logout
//
$app->match('/logout', function () {})->bind('logout');

//
// Controller: View my gallery
//
$app->get('/my-gallery', function(Application $app) {
    if (!$app['user']) {
        $app['session']->getFlashBag()->add('error', 'Please log in to find your gallery.');

        return $app->redirect($app['url_generator']->generate('login'));
    }

    $galleryInfo = $app['gallery.info.mapper']->findByGoogleUserId($app['user']->getCustomField('googleUserId'));
    if (!$galleryInfo) {
        $app['session']->getFlashBag()->add('error', 'You haven\'t set up a gallery for this Google account yet.');

        return $app->redirect($app['url_generator']->generate('setup'));
    }

    return $app->redirect($app['url_generator']->generate('gallery', array('gallery_slug' => $galleryInfo->getSlug())));
})
->bind('my-gallery');

//
// Controller: View a gallery's photo stream
//
$app->get('/{gallery_slug}/{pagestr}', function(Application $app, Request $request, GalleryInfo $galleryInfo, $pagestr) {
    $pg = substr($pagestr, 4); // Strip out the leading "page" string.
    $photoStream = $app['gallery']->getPhotoStream($galleryInfo); /** @var \Drivegal\PhotoStream $photoStream */
    $photoStream->setPerPage(60);
    $page = $photoStream->getPage($pg);
    $paginator = new Paginator(
        $photoStream->count(),
        $photoStream->getPerPage(),
        $pg,
        $app['url_generator']->generate('gallery', array('gallery_slug' => $galleryInfo->getSlug())) . '/page(:num)'
    );

    return $app['twig']->render('stream.twig', array(
        'galleryName' => $galleryInfo->getGalleryName(),
        'gallerySlug' => $galleryInfo->getSlug(),
        'files' => $page->getFiles(),
        'paginator' => $paginator,
        'showLightboxPhoto' => $request->query->get('show'),
    ));
})
->assert('gallery_slug', '^[^_][^/]+') // slug can't start with an underscore or contain a slash.
->assert('pagestr', '^page\d+')
->convert('galleryInfo', $galleryProvider)
->value('pagestr', 'page1')
->bind('gallery')
;


text:
'use babel';
var fManager = require('./function-manager');
var path = require('path');
var fileManager = require('./file-manager');
var parser = require('./parser');
var _ = require('lodash');

function get() {

}

function linterUnusedVariables(textEditor) {
  linterRet = [];
  unusedVariables = fileManager.checkUnusedVariable();
  _.forEach(unusedVariables, function (value) {
    var regStr = '\\s'+value+'[\\s+=]';
    var range = [[0, 0], [20, 20]];
    textEditor.scanInBufferRange(new RegExp(regStr, 'g'), range, function (iterator) {
      linterRet.push({type: 'Warning', text: 'Unused Variable', range: iterator.range, filePath: fPath});
    });
  });
  return linterRet;
}

function linterUnDeclaredVariables(textEditor) {
  linterRet = [];
  usedVariables = fileManager.getUsedVariables();
  var usedVariablesName = _.keys(usedVariables);
  variables = fileManager.getVariables();
  var variablesName = _.keys(variables);
  var undeclaredVariables = _.difference(usedVariablesName, variablesName);
  _.forEach(undeclaredVariables, function (value) {
    var regStr = '\\s'+value+'[\\s+=;]';
    var range = [[0, 0], [20, 20]];
    textEditor.scanInBufferRange(new RegExp(regStr, 'g'), range, function (iterator) {
      linterRet.push({type: 'Error', text: 'Undeclared Variable', range: iterator.range, filePath: fPath});
    });
  });
  return linterRet;
}

function linterCallFunction(textEditor) {
  var linterRet = [];
  var functions = fManager.getFunctions();
  var functionsKey = _.keys(functions);
  var usedFunctions = fileManager.getUsedFunctions();
  var usedFunctionsKey = _.keys(usedFunctions);
  var inexistentFunctions = _.difference(usedFunctionsKey, functionsKey);
  _.forEach(inexistentFunctions, function (value) {
    var regStr = value + '\\(';
    var range = [[0, 0], [20, 20]];
    textEditor.scanInBufferRange(new RegExp(regStr, 'g'), range, function (iterator) {
      linterRet.push({type: 'Error', text: 'Inexistent Function', range: iterator.range, filePath: fPath});
    });
  });
  return linterRet;
}

function getProvider() {
  const provider = {
    name: 'pg-dev',
    grammarScopes: ['source.pgsql'],
    scope: 'file',
    lintOnFly: true,
    lint: function(textEditor) {
      fPath = textEditor.getPath();
      text = textEditor.getText();
      fileManager.loadCurrentFile(text);
      return new Promise(function(resolve, reject) {
        allLinterRet = [];
        unusedVariablesLinter = linterUnusedVariables(textEditor);
        usedUnDeclaredVariablesLinter = linterUnDeclaredVariables(textEditor);
        calledFunctions = linterCallFunction(textEditor);
        allLinterRet = _.concat([], unusedVariablesLinter, usedUnDeclaredVariablesLinter, calledFunctions);
        resolve(allLinterRet);
      });
    }
  }
  return provider;
}

export default {
  getProvider: getProvider
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "sandbox/linux/services/broker_process.h"

#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <vector>

#if defined(OS_ANDROID)
#include "base/android/path_utils.h"
#endif
#include "base/files/file_path.h"
#include "base/logging.h"
#include "sandbox/linux/tests/unit_tests.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace sandbox {

#if defined(OS_ANDROID)
  #define DISABLE_ON_ANDROID(function) DISABLED_##function
#else
  #define DISABLE_ON_ANDROID(function) function
#endif

TEST(BrokerProcess, CreateAndDestroy) {
  std::vector<std::string> read_whitelist;
  read_whitelist.push_back("/proc/cpuinfo");

  BrokerProcess* open_broker = new BrokerProcess(read_whitelist,
                                                 std::vector<std::string>());
  ASSERT_TRUE(open_broker->Init(NULL));
  pid_t broker_pid = open_broker->broker_pid();
  delete(open_broker);

  // Now we check that the broker has exited properly.
  int status = 0;
  ASSERT_EQ(waitpid(broker_pid, &status, 0), broker_pid);
  ASSERT_TRUE(WIFEXITED(status));
  ASSERT_EQ(WEXITSTATUS(status), 0);
}

TEST(BrokerProcess, TestOpenAccessNull) {
  const std::vector<std::string> empty;
  BrokerProcess open_broker(empty, empty);
  ASSERT_TRUE(open_broker.Init(NULL));

  int fd = open_broker.Open(NULL, O_RDONLY);
  ASSERT_EQ(fd, -EFAULT);

  int ret = open_broker.Access(NULL, F_OK);
  ASSERT_EQ(ret, -EFAULT);
}

void TestOpenFilePerms(bool fast_check_in_client) {
  const char kR_WhiteListed[] = "/proc/DOESNOTEXIST1";
  // We can't debug the init process, and shouldn't be able to access
  // its auxv file.
  const char kR_WhiteListedButDenied[] = "/proc/1/auxv";
  const char kW_WhiteListed[] = "/proc/DOESNOTEXIST2";
  const char kRW_WhiteListed[] = "/proc/DOESNOTEXIST3";
  const char k_NotWhitelisted[] = "/proc/DOESNOTEXIST4";

  std::vector<std::string> read_whitelist;
  read_whitelist.push_back(kR_WhiteListed);
  read_whitelist.push_back(kR_WhiteListedButDenied);
  read_whitelist.push_back(kRW_WhiteListed);

  std::vector<std::string> write_whitelist;
  write_whitelist.push_back(kW_WhiteListed);
  write_whitelist.push_back(kRW_WhiteListed);

  BrokerProcess open_broker(read_whitelist,
                            write_whitelist,
                            fast_check_in_client);
  ASSERT_TRUE(open_broker.Init(NULL));

  int fd = -1;
  fd = open_broker.Open(kR_WhiteListed, O_RDONLY);
  ASSERT_EQ(fd, -ENOENT);
  fd = open_broker.Open(kR_WhiteListed, O_WRONLY);
  ASSERT_EQ(fd, -EPERM);
  fd = open_broker.Open(kR_WhiteListed, O_RDWR);
  ASSERT_EQ(fd, -EPERM);
  int ret = -1;
  ret = open_broker.Access(kR_WhiteListed, F_OK);
  ASSERT_EQ(ret, -ENOENT);
  ret = open_broker.Access(kR_WhiteListed, R_OK);
  ASSERT_EQ(ret, -ENOENT);
  ret = open_broker.Access(kR_WhiteListed, W_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(kR_WhiteListed, R_OK | W_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(kR_WhiteListed, X_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(kR_WhiteListed, R_OK | X_OK);
  ASSERT_EQ(ret, -EPERM);

  fd = open_broker.Open(kR_WhiteListedButDenied, O_RDONLY);
  // The broker process will allow this, but the normal permission system
  // won't.
  ASSERT_EQ(fd, -EACCES);
  fd = open_broker.Open(kR_WhiteListedButDenied, O_WRONLY);
  ASSERT_EQ(fd, -EPERM);
  fd = open_broker.Open(kR_WhiteListedButDenied, O_RDWR);
  ASSERT_EQ(fd, -EPERM);
  ret = open_broker.Access(kR_WhiteListedButDenied, F_OK);
  // The normal permission system will let us check that the file exist.
  ASSERT_EQ(ret, 0);
  ret = open_broker.Access(kR_WhiteListedButDenied, R_OK);
  ASSERT_EQ(ret, -EACCES);
  ret = open_broker.Access(kR_WhiteListedButDenied, W_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(kR_WhiteListedButDenied, R_OK | W_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(kR_WhiteListedButDenied, X_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(kR_WhiteListedButDenied, R_OK | X_OK);
  ASSERT_EQ(ret, -EPERM);

  fd = open_broker.Open(kW_WhiteListed, O_RDONLY);
  ASSERT_EQ(fd, -EPERM);
  fd = open_broker.Open(kW_WhiteListed, O_WRONLY);
  ASSERT_EQ(fd, -ENOENT);
  fd = open_broker.Open(kW_WhiteListed, O_RDWR);
  ASSERT_EQ(fd, -EPERM);
  ret = open_broker.Access(kW_WhiteListed, F_OK);
  ASSERT_EQ(ret, -ENOENT);
  ret = open_broker.Access(kW_WhiteListed, R_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(kW_WhiteListed, W_OK);
  ASSERT_EQ(ret, -ENOENT);
  ret = open_broker.Access(kW_WhiteListed, R_OK | W_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(kW_WhiteListed, X_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(kW_WhiteListed, R_OK | X_OK);
  ASSERT_EQ(ret, -EPERM);

  fd = open_broker.Open(kRW_WhiteListed, O_RDONLY);
  ASSERT_EQ(fd, -ENOENT);
  fd = open_broker.Open(kRW_WhiteListed, O_WRONLY);
  ASSERT_EQ(fd, -ENOENT);
  fd = open_broker.Open(kRW_WhiteListed, O_RDWR);
  ASSERT_EQ(fd, -ENOENT);
  ret = open_broker.Access(kRW_WhiteListed, F_OK);
  ASSERT_EQ(ret, -ENOENT);
  ret = open_broker.Access(kRW_WhiteListed, R_OK);
  ASSERT_EQ(ret, -ENOENT);
  ret = open_broker.Access(kRW_WhiteListed, W_OK);
  ASSERT_EQ(ret, -ENOENT);
  ret = open_broker.Access(kRW_WhiteListed, R_OK | W_OK);
  ASSERT_EQ(ret, -ENOENT);
  ret = open_broker.Access(kRW_WhiteListed, X_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(kRW_WhiteListed, R_OK | X_OK);
  ASSERT_EQ(ret, -EPERM);

  fd = open_broker.Open(k_NotWhitelisted, O_RDONLY);
  ASSERT_EQ(fd, -EPERM);
  fd = open_broker.Open(k_NotWhitelisted, O_WRONLY);
  ASSERT_EQ(fd, -EPERM);
  fd = open_broker.Open(k_NotWhitelisted, O_RDWR);
  ASSERT_EQ(fd, -EPERM);
  ret = open_broker.Access(k_NotWhitelisted, F_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(k_NotWhitelisted, R_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(k_NotWhitelisted, W_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(k_NotWhitelisted, R_OK | W_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(k_NotWhitelisted, X_OK);
  ASSERT_EQ(ret, -EPERM);
  ret = open_broker.Access(k_NotWhitelisted, R_OK | X_OK);
  ASSERT_EQ(ret, -EPERM);

  // We have some extra sanity check for clearly wrong values.
  fd = open_broker.Open(kRW_WhiteListed, O_RDONLY|O_WRONLY|O_RDWR);
  ASSERT_EQ(fd, -EPERM);

  // It makes no sense to allow O_CREAT in a 2-parameters open. Ensure this
  // is denied.
  fd = open_broker.Open(kRW_WhiteListed, O_RDWR|O_CREAT);
  ASSERT_EQ(fd, -EPERM);
}

// Run the same thing twice. The second time, we make sure that no security
// check is performed on the client.
TEST(BrokerProcess, OpenFilePermsWithClientCheck) {
  TestOpenFilePerms(true /* fast_check_in_client */);
  // Don't do anything here, so that ASSERT works in the subfunction as
  // expected.
}

TEST(BrokerProcess, OpenOpenFilePermsNoClientCheck) {
  TestOpenFilePerms(false /* fast_check_in_client */);
  // Don't do anything here, so that ASSERT works in the subfunction as
  // expected.
}

void TestOpenCpuinfo(bool fast_check_in_client) {
  const char kFileCpuInfo[] = "/proc/cpuinfo";
  std::vector<std::string> read_whitelist;
  read_whitelist.push_back(kFileCpuInfo);

  BrokerProcess* open_broker = new BrokerProcess(read_whitelist,
                                                 std::vector<std::string>(),
                                                 fast_check_in_client);
  ASSERT_TRUE(open_broker->Init(NULL));
  pid_t broker_pid = open_broker->broker_pid();

  int fd = -1;
  fd = open_broker->Open(kFileCpuInfo, O_RDWR);
  ASSERT_EQ(fd, -EPERM);

  // Check we can read /proc/cpuinfo.
  int can_access = open_broker->Access(kFileCpuInfo, R_OK);
  ASSERT_EQ(can_access, 0);
  can_access = open_broker->Access(kFileCpuInfo, W_OK);
  ASSERT_EQ(can_access, -EPERM);
  // Check we can not write /proc/cpuinfo.

  // Open cpuinfo via the broker.
  int cpuinfo_fd = open_broker->Open(kFileCpuInfo, O_RDONLY);
  ASSERT_GE(cpuinfo_fd, 0);
  char buf[3];
  memset(buf, 0, sizeof(buf));
  int read_len1 = read(cpuinfo_fd, buf, sizeof(buf));
  ASSERT_GT(read_len1, 0);

  // Open cpuinfo directly.
  int cpuinfo_fd2 = open(kFileCpuInfo, O_RDONLY);
  ASSERT_GE(cpuinfo_fd2, 0);
  char buf2[3];
  memset(buf2, 1, sizeof(buf2));
  int read_len2 = read(cpuinfo_fd2, buf2, sizeof(buf2));
  ASSERT_GT(read_len1, 0);

  // The following is not guaranteed true, but will be in practice.
  ASSERT_EQ(read_len1, read_len2);
  // Compare the cpuinfo as returned by the broker with the one we opened
  // ourselves.
  ASSERT_EQ(memcmp(buf, buf2, read_len1), 0);

  if (fd >= 0)
    close(fd);
  if (cpuinfo_fd >= 0)
    close(cpuinfo_fd);
  if (cpuinfo_fd2 >= 0)
    close(cpuinfo_fd);

  delete(open_broker);

  // Now we check that the broker has exited properly.
  int status = 0;
  ASSERT_EQ(waitpid(broker_pid, &status, 0), broker_pid);
  ASSERT_TRUE(WIFEXITED(status));
  ASSERT_EQ(WEXITSTATUS(status), 0);
}

// Run the same thing twice. The second time, we make sure that no security
// check is performed on the client.
TEST(BrokerProcess, OpenCpuinfoWithClientCheck) {
  TestOpenCpuinfo(true /* fast_check_in_client */);
  // Don't do anything here, so that ASSERT works in the subfunction as
  // expected.
}

TEST(BrokerProcess, OpenCpuinfoNoClientCheck) {
  TestOpenCpuinfo(false /* fast_check_in_client */);
  // Don't do anything here, so that ASSERT works in the subfunction as
  // expected.
}

TEST(BrokerProcess, OpenFileRW) {
  const char basename[] = "BrokerProcessXXXXXX";
  char template_name[2048];
  // On Android, this file will end up in
  // /data/local/tmp/BrokerProcessXXXXXX, which is OK.
  strncpy(template_name, basename, sizeof(basename) - 1);
  template_name[sizeof(basename) - 1] = '\0';
  int tempfile = mkstemp(template_name);
  ASSERT_GE(tempfile, 0);
  char tempfile_name[2048];
  int written = snprintf(tempfile_name, sizeof(tempfile_name),
                         "/proc/self/fd/%d", tempfile);
  ASSERT_LT(written, static_cast<int>(sizeof(tempfile_name)));

  std::vector<std::string> whitelist;
  whitelist.push_back(tempfile_name);

  BrokerProcess open_broker(whitelist, whitelist);
  ASSERT_TRUE(open_broker.Init(NULL));

  // Check we can access that file with read or write.
  int can_access = open_broker.Access(tempfile_name, R_OK | W_OK);
  ASSERT_EQ(can_access, 0);

  int tempfile2 = -1;
  tempfile2 = open_broker.Open(tempfile_name, O_RDWR);
  ASSERT_GE(tempfile2, 0);

  // Write to the descriptor opened by the broker.
  char test_text[] = "TESTTESTTEST";
  ssize_t len = write(tempfile2, test_text, sizeof(test_text));
  ASSERT_EQ(len, static_cast<ssize_t>(sizeof(test_text)));

  // Read back from the original file descriptor what we wrote through
  // the descriptor provided by the broker.
  char buf[1024];
  len = read(tempfile, buf, sizeof(buf));

  ASSERT_EQ(len, static_cast<ssize_t>(sizeof(test_text)));
  ASSERT_EQ(memcmp(test_text, buf, sizeof(test_text)), 0);

  // Cleanup the temporary file.
  char tempfile_full_path[2048];
  // Make sure tempfile_full_path will terminate with a 0.
  memset(tempfile_full_path, 0, sizeof(tempfile_full_path));
  ssize_t ret = readlink(tempfile_name, tempfile_full_path,
                         sizeof(tempfile_full_path));
  ASSERT_GT(ret, 0);
  // Make sure we still have a trailing zero in tempfile_full_path.
  ASSERT_LT(ret, static_cast<ssize_t>(sizeof(tempfile_full_path)));
  ASSERT_EQ(unlink(tempfile_full_path), 0);

  ASSERT_EQ(close(tempfile), 0);
  ASSERT_EQ(close(tempfile2), 0);
}

// Sandbox test because we could get a SIGPIPE.
SANDBOX_TEST(BrokerProcess, BrokerDied) {
  std::vector<std::string> read_whitelist;
  read_whitelist.push_back("/proc/cpuinfo");

  BrokerProcess open_broker(read_whitelist,
                            std::vector<std::string>(),
                            true /* fast_check_in_client */,
                            true /* quiet_failures_for_tests */);
  SANDBOX_ASSERT(open_broker.Init(NULL));
  pid_t broker_pid = open_broker.broker_pid();
  SANDBOX_ASSERT(kill(broker_pid, SIGKILL) == 0);

  // Now we check that the broker has exited properly.
  int status = 0;
  SANDBOX_ASSERT(waitpid(broker_pid, &status, 0) == broker_pid);
  SANDBOX_ASSERT(WIFSIGNALED(status));
  SANDBOX_ASSERT(WTERMSIG(status) == SIGKILL);
  // Hopefully doing Open with a dead broker won't SIGPIPE us.
  SANDBOX_ASSERT(open_broker.Open("/proc/cpuinfo", O_RDONLY) == -ENOMEM);
  SANDBOX_ASSERT(open_broker.Access("/proc/cpuinfo", O_RDONLY) == -ENOMEM);
}

void TestOpenComplexFlags(bool fast_check_in_client) {
  const char kCpuInfo[] = "/proc/cpuinfo";
  std::vector<std::string> whitelist;
  whitelist.push_back(kCpuInfo);

  BrokerProcess open_broker(whitelist,
                            whitelist,
                            fast_check_in_client);
  ASSERT_TRUE(open_broker.Init(NULL));
  // Test that we do the right thing for O_CLOEXEC and O_NONBLOCK.
  int fd = -1;
  int ret = 0;
  fd = open_broker.Open(kCpuInfo, O_RDONLY);
  ASSERT_GE(fd, 0);
  ret = fcntl(fd, F_GETFL);
  ASSERT_NE(-1, ret);
  // The descriptor shouldn't have the O_CLOEXEC attribute, nor O_NONBLOCK.
  ASSERT_EQ(0, ret & (O_CLOEXEC | O_NONBLOCK));
  ASSERT_EQ(0, close(fd));

  fd = open_broker.Open(kCpuInfo, O_RDONLY | O_CLOEXEC);
  ASSERT_GE(fd, 0);
  ret = fcntl(fd, F_GETFD);
  ASSERT_NE(-1, ret);
  // Important: use F_GETFD, not F_GETFL. The O_CLOEXEC flag in F_GETFL
  // is actually not used by the kernel.
  ASSERT_TRUE(FD_CLOEXEC & ret);
  ASSERT_EQ(0, close(fd));

  fd = open_broker.Open(kCpuInfo, O_RDONLY | O_NONBLOCK);
  ASSERT_GE(fd, 0);
  ret = fcntl(fd, F_GETFL);
  ASSERT_NE(-1, ret);
  ASSERT_TRUE(O_NONBLOCK & ret);
  ASSERT_EQ(0, close(fd));
}

TEST(BrokerProcess, OpenComplexFlagsWithClientCheck) {
  TestOpenComplexFlags(true /* fast_check_in_client */);
  // Don't do anything here, so that ASSERT works in the subfunction as
  // expected.
}

TEST(BrokerProcess, OpenComplexFlagsNoClientCheck) {
  TestOpenComplexFlags(false /* fast_check_in_client */);
  // Don't do anything here, so that ASSERT works in the subfunction as
  // expected.
}

}  // namespace sandbox


text:
layout: post
title: Brunette fucking two old dude outdoor
titleinfo: pornvd
desc: Watch Brunette fucking two old dude outdoor. Pornhub is the ultimate xxx porn and sex site.
---

Brunette fucking two old dude outdoor

Watch Brunette fucking two old dude outdoor. Pornhub is the ultimate xxx porn and sex site.


text:
class TIntermNode;

void SeparateDeclarations(TIntermNode *root);

#endif  // COMPILER_TRANSLATOR_SEPARATEDECLARATIONS_H_


text:
namespace DD4T.ContentModel
{
    using System.Collections.Generic;
    using System;

    public interface IComponent : IRepositoryLocal, IViewable
    {
        [Obsolete]
        IList<ICategory> Categories { get; }
        ComponentType ComponentType { get; }
        IFieldSet Fields { get; }
        //IDictionary<string,IField> Fields { get; }
        IOrganizationalItem Folder { get; }
        IFieldSet MetadataFields { get; }
        //IDictionary<string, IField> MetadataFields { get; }
        IMultimedia Multimedia { get; }
        ISchema Schema { get; }
        //string ResolvedUrl { get; set; }
        int Version { get; }
        DateTime LastPublishedDate { get; }
        DateTime RevisionDate { get; }
        string EclId { get; }
    }
}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "KismetCompiler.h"

//////////////////////////////////////////////////////////////////////////
// FKCHandler_CallFunction

class FKCHandler_CallFunction : public FNodeHandlingFunctor
{
public:
	FKCHandler_CallFunction(FKismetCompilerContext& InCompilerContext)
		: FNodeHandlingFunctor(InCompilerContext)
	{
	}

	/**
	 * Searches for the function referenced by a graph node in the CallingContext class's list of functions,
	 * validates that the wiring matches up correctly, and creates an execution statement.
	 */
	void CreateFunctionCallStatement(FKismetFunctionContext& Context, UEdGraphNode* Node, UEdGraphPin* SelfPin);

	bool IsCalledFunctionPure(UEdGraphNode* Node)
	{
		if(UK2Node_CallFunction* CallFunctionNode = Cast<UK2Node_CallFunction>(Node))
		{
			return CallFunctionNode->bIsPureFunc;
		}
		return false;
	}

	bool IsCalledFunctionFinal(UEdGraphNode* Node)
	{
		if(UK2Node_CallFunction* CallFunctionNode = Cast<UK2Node_CallFunction>(Node))
		{
			return CallFunctionNode->bIsFinalFunction;
		}
		return false;
	}

	bool IsCalledFunctionFromInterface(UEdGraphNode* Node)
	{
		if(UK2Node_CallFunction* CallFunctionNode = Cast<UK2Node_CallFunction>(Node))
		{
			return CallFunctionNode->bIsInterfaceCall;
		}
		return false;
	}

private:
	// Get the name of the function to call from the node
	virtual FString GetFunctionNameFromNode(UEdGraphNode* Node) const;
	UClass* GetCallingContext(FKismetFunctionContext& Context, UEdGraphNode* Node);
	UClass* GetTrueCallingClass(FKismetFunctionContext& Context, UEdGraphPin* SelfPin);

public:

	virtual void RegisterNets(FKismetFunctionContext& Context, UEdGraphNode* Node) override;
	virtual void RegisterNet(FKismetFunctionContext& Context, UEdGraphPin* Net) override;
	virtual UFunction* FindFunction(FKismetFunctionContext& Context, UEdGraphNode* Node);
	virtual void Transform(FKismetFunctionContext& Context, UEdGraphNode* Node) override;
	virtual void Compile(FKismetFunctionContext& Context, UEdGraphNode* Node) override;
	virtual void CheckIfFunctionIsCallable(UFunction* Function, FKismetFunctionContext& Context, UEdGraphNode* Node);
	virtual void AdditionalCompiledStatementHandling(FKismetFunctionContext& Context, UEdGraphNode* Node, FBlueprintCompiledStatement& Statement) {}

protected:
	TMap<UEdGraphPin*, FBPTerminal*> InterfaceTermMap;
};


text:
media-textfield
===============

A textfield that auto-generates previews from pasted URLs.

Or at least that was the plan. It's not currently possible to do this without an
external service of some kind, since there's no way to lift the same-origin policy.

Instead this is just a field that scans for URLs in it, and appends them to another container.


text:
url
( service in module ng
 )

Description

This method is getter / setter.

Return url (e.g.  /path?a=b#hash ) when called without any parameter.

Change path, search and hash, when called with parameter and return  $location .

Parameters

url(optional) – {string=} –

New url without base prefix (e.g.  /path?a=b#hash )

Returns

{string}
–
url


text:
namespace base {

class FilePath;
struct TestResult;

// Generates an XML output file. Format is very close to GTest, but has
// extensions needed by the test launcher.
class XmlUnitTestResultPrinter : public testing::EmptyTestEventListener {
 public:
  XmlUnitTestResultPrinter();
  virtual ~XmlUnitTestResultPrinter();

  // Must be called before adding as a listener. Returns true on success.
  bool Initialize(const FilePath& output_file_path) WARN_UNUSED_RESULT;

 private:
  // testing::EmptyTestEventListener:
  virtual void OnTestCaseStart(const testing::TestCase& test_case) override;
  virtual void OnTestStart(const testing::TestInfo& test_info) override;
  virtual void OnTestEnd(const testing::TestInfo& test_info) override;
  virtual void OnTestCaseEnd(const testing::TestCase& test_case) override;

  FILE* output_file_;

  DISALLOW_COPY_AND_ASSIGN(XmlUnitTestResultPrinter);
};

// Produces a vector of test results based on GTest output file.
// Returns true iff the output file exists and has been successfully parsed.
// On successful return |crashed| is set to true if the test results
// are valid but incomplete.
bool ProcessGTestOutput(const base::FilePath& output_file,
                        std::vector<TestResult>* results,
                        bool* crashed) WARN_UNUSED_RESULT;

}  // namespace base

#endif  // BASE_TEST_GTEST_XML_UTIL_H_


text:
using System.Collections.Generic;
namespace Pickaxe.Sdk
{
    public abstract class AstNode
    {
        protected AstNode()
        {
            Children = new ChildCollection(this);
        }

        public LineInfo Line { get; set; }
        public AstNode Parent { get; set; }
        public ChildCollection Children { get; private set; }
        public abstract void Accept(IAstVisitor visitor);

        public IList<TValue> Descendants<TValue>() where TValue : AstNode
        {
            var list = new List<TValue>();
            Descendants(list);
            return list;
        }

        private void Descendants<TValue>(IList<TValue> matches) where TValue : AstNode
        {
            if (typeof(TValue) == this.GetType())
                matches.Add(this as TValue);

            foreach (var child in Children)
                child.Descendants(matches);
        }
    }
}


text:
django-health-check
==================

This project checks a number of backends, if they are able to connect and do a simple action, e.g. check out the django ORM backend:

```python

class DjangoDatabaseBackend(BaseHealthCheckBackend):

    def check_status(self):
        try:
            obj = TestModel.objects.create(title="test")
            obj.title = "newtest"
            obj.save()
            obj.delete()
            return True
        except IntegrityError:
            raise ServiceReturnedUnexpectedResult("Integrity Error")
        except DatabaseError:
            raise ServiceUnavailable("Database error")

```

The project is made using some of the same codes, that the django admin site uses - so when you have sucessfully written a new plugin, you register it to the pool, e.g.

```python
plugin_dir.register(DjangoDatabaseBackend)
```

Install
=======

Add this to urls.py

```python
url(r'^ht/', include('health_check.urls'))
```

Add required apps:

```python
    'health_check',
    'health_check_celery',
    'health_check_db',
    'health_check_cache',
    'health_check_storage',
```
(remember to add dependencies, e.g. djcelery - however you should have that already, if you have celery running).
You'll also have to make sure that you have a
`result backend <http://celery.readthedocs.org/en/latest/configuration.html?highlight=result_backend#std:setting-CELERY_RESULT_BACKEND>`_
configured.
If you are using celery 3, use ``health_check_celery3`` instead of ``health_check_celery``.

Set up monitoring
=================

E.g. add to pingdom - django-health-check will return HTTP 200 if everything is OK and HTTP 500 if *anything* is not working.

Profit
======

![Screenshot of django-health-check](http://c.kristian.io/image/3C2s1Z3X071S/Screen%20Shot%202013-03-18%20at%2018.40.52.png)

Our mascot
==========
![django-health-check is the most interresting project in the world](http://c.kristian.io/image/1J3x031Q0S3B/36347774.jpg)

Dependencies
============

Python 2.7+ (Yes, thats right, we have **Python 3 support**)

Django 1.2+


text:
//  Copyright (c) 2021 Alachisoft
//
//  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

using Alachisoft.NCache.Common.DataStructures;
using System;

namespace Alachisoft.NCache.Client
{
    internal class RequestLogger
    {
        XrefDictionary _requestTable;
        long _lastAcknowledgedReferenceId = -1;
        long _lastAcknowledgedRequestId = -1;

        object _syncLock = new object();

        public RequestLogger()
        {
            _requestTable = new XrefDictionary();
        }

        /// <summary>
        /// Adds a new request to the table and returns the last removed request id.
        /// </summary>
        /// <param name="requestId"></param>
        /// <returns>Last remove request Id</returns>
        public long LogNewRequest(long requestId)
        {
            lock (_syncLock)
            {
                XReference sourceReferenceId = new XReference(requestId);
                _requestTable.AddSource(sourceReferenceId);

                long smallestRequestId;
                long smallestReferenceId = _requestTable.GetFirstReferenceId(_lastAcknowledgedReferenceId, out smallestRequestId);

                _lastAcknowledgedRequestId = smallestRequestId - 1;
                _lastAcknowledgedReferenceId = smallestReferenceId - 1;
            }

            return _lastAcknowledgedRequestId;
        }

        /// <summary>
        /// Removes the request with specified Id.
        /// </summary>
        /// <param name="requestId"></param>
        /// <returns></returns>
        public bool RemoveRequest(long requestId)
        {
            lock (_syncLock)
            {
                XReference sourceReferenceId = new XReference(requestId);
                long referenceId = _requestTable.RemoveSource(sourceReferenceId);
                if (referenceId != -1)
                {
                    if (_lastAcknowledgedReferenceId + 1 == referenceId)
                        _lastAcknowledgedReferenceId = referenceId;
                }
            }

            return true;
        }

        /// <summary>
        /// Expires the old requests
        /// </summary>
        /// <param name="expirationInterval">expiration interval in seconds</param>
        public void Expire(long expirationInterval)
        {
            XReference[] loggedRequests = new XReference[_requestTable.SourceIds.Count];

            lock (_syncLock)
            {
                _requestTable.SourceIds.CopyTo(loggedRequests, 0);
            }

            foreach (XReference refernce in loggedRequests)
            {
                if (refernce != null && refernce.CreationTime.AddSeconds(expirationInterval) < DateTime.Now)
                    RemoveRequest(refernce.SourceId);
            }
        }
    }
}


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

namespace WzComparerR2.Animation
{
    public struct KeyFrame
    {
        public int Length { get; set; }
        public bool Animated { get; set; }
    }
}


text:
<!DOCTYPE html>

	   <title>Welcome</title>

                BootLTE Spring Boot + AdminLTE

                         Level

Here

Bem vindo!

                BootLTE é o resultado da integração do Spring Boot (utilizando o template engine Thymeleaf) com o tema AdminLTE.
                O propósito deste projeto é ser utilizado como ponto de partida para outros projetos utilizando o tema AdminLTE.
                Visite os links abaixo para mais informações.

                    Spring Boot 1.4.1

                    Thymeleaf 2.1.5

                    Thymeleaf Layout Dialect 1.4.0

                    AdminLTE 2.3.6


text:
'use strict';

angular.module('cloudworkerApp')
    .config(function ($stateProvider) {
        $stateProvider
            .state('settings', {
                parent: 'account',
                url: '/settings',
                data: {
                    authorities: ['ROLE_USER', 'ROLE_NODE'],
                    pageTitle: 'Settings'
                },
                views: {
                    'content@': {
                        templateUrl: 'scripts/app/account/settings/settings.html',
                        controller: 'SettingsController'
                    }
                },
                resolve: {

                }
            });
    });


text:
using System;
using System.Collections.Generic;
using Cosmos.Logging.Exceptions.Core;
using Cosmos.Logging.Exceptions.Destructurers;
using MySql.Data.MySqlClient;

namespace Cosmos.Logging.Extensions.Exceptions.Destructurers {
    /// <summary>
    /// MySql exception destructurer
    /// </summary>
    public class MySqlExceptionDestructurer : ExceptionDestructurer<MySqlException> {
        /// <inheritdoc />
        protected override void DestructureException(
            MySqlException exception,
            IExceptionPropertyBag propertyBag,
            Func<Exception, IReadOnlyDictionary<string, object>> destructureExceptionHandle) {
            propertyBag.AddProperty(nameof(MySqlException.Number), exception.Number);
            propertyBag.AddProperty(nameof(MySqlException.SqlState), exception.SqlState);
            propertyBag.AddProperty(nameof(MySqlException.ErrorCode), exception.ErrorCode);
        }
    }
}


text:
$.ajax({
        type: "POST",
        url: "/TournamentController/jsonPersonen",
        dataType: 'json',
        data: {},
        success: function(data) {
            personen = document.getElementById('personen');
            personen.options.length = 0;
            $.each(data, function(index, element) {
            personen.options[personen.options.length] = new Option(element.Nickname , element.Google_ID);
            personenSelect.bootstrapDualListbox('refresh');
        });
        }
        });
function select() {
    personen = document.getElementById('personen');
    if (personen.value) {
        $("#button").prop('disabled', false);
    }
    else {
        $("#button").prop('disabled', true);
    }
}


text:
\hypertarget{_computer_evaluator_8cpp}{}\section{Mastermind\+C\+P\+P\+D\+L\+L/\+Computer\+Evaluator.cpp File Reference}
\label{_computer_evaluator_8cpp}\index{Mastermind\+C\+P\+P\+D\+L\+L/\+Computer\+Evaluator.\+cpp@{Mastermind\+C\+P\+P\+D\+L\+L/\+Computer\+Evaluator.\+cpp}}
{\ttfamily \#include \char`\"{}stdafx.\+h\char`\"{}}\newline
{\ttfamily \#include \char`\"{}Computer\+Evaluator.\+h\char`\"{}}\newline
\subsection*{Namespaces}
\begin{DoxyCompactItemize}
\item
 \hyperlink{namespacemastermind}{mastermind}
\item
 \hyperlink{namespacemastermind_1_1logic}{mastermind\+::logic}
\end{DoxyCompactItemize}


text:
import { Actor } from './Actor';

const children = new Map<string, Actor>();

let sessionIdIndex = 0;

export interface Registry {
  bookId(): string;
  register(id: string, actor: Actor): string;
  get(id: string): Actor | undefined;
  free(id: string): void;
}

export const registry: Registry = {
  bookId() {
    return `x:${sessionIdIndex++}`;
  },
  register(id, actor) {
    children.set(id, actor);
    return id;
  },
  get(id) {
    return children.get(id);
  },
  free(id) {
    children.delete(id);
  }
};


text:
import wx
import os
import glob
import threading
import serial
import tivuGUI
import bitimage
import pclparse

#----------------------------------------------------------------------
# Create an own event type, so that GUI updates can be delegated
# this is required as on some platforms only the main thread can
# access the GUI without crashing. wxMutexGuiEnter/wxMutexGuiLeave
# could be used too, but an event is more elegant.

SERIALRX = wx.NewEventType()
# bind to serial data receive events
EVT_SERIALRX = wx.PyEventBinder(SERIALRX, 0)

class SerialRxEvent(wx.PyCommandEvent):
    eventType = SERIALRX
    def __init__(self, windowID, data):
        wx.PyCommandEvent.__init__(self, self.eventType, windowID)
        self.data = data

    def Clone(self):
        self.__class__(self.GetId(), self.data)

class TivuFrame(tivuGUI.MainFrame):

    nufRows = 276

    def __init__(self, *args, **kwds):
        tivuGUI.MainFrame.__init__(self, *args, **kwds)
        self.ser = None
        self.speed = 9600

        self.pcl = pclparse.pclparse()
        self.streaming = False

        ## Thread specific variables
        self.thread = None
        self.alive = threading.Event()

        ## Bind residual events
        self.Bind(EVT_SERIALRX, self.OnSerialRead)
        self.Bind(wx.EVT_CLOSE, self.OnQuit)

        self.gauge = 0
        self.gaugemeter = None

    def OnNew(self, event):
        self.BitWindow.SetData([])

    def OnOpen(self, event):
        dlg = wx.FileDialog(None, 'Select file to read in')
        modal = dlg.ShowModal()
        filename = dlg.GetPath()
        dlg.Destroy()
        if modal != wx.ID_OK:
            return

        ## Create a parser and run the file thru it
        pcl = pclparse.pclparse()
        fd = open(filename, 'rb')
        while True:
            data = fd.read(100)
            if len(data) == 0:
                break
            pcl.parse(data)
        fd.close()

        ## Blit the parsed data to the bit window
        self.BitWindow.SetData(pcl.data)

    defaultFile = 'Image'
    wildcards = 'PNG (*.png)|*.png|JPEG (*.jpg)|*.jpg|BMP (*.bmp)|*.bmp|TIFF (*.tiff)|*.tiff'

    def OnSaveAs(self, event):
        dlg = wx.FileDialog(None, 'Select file name of file to save to',
                            defaultDir  = os.getcwd(),
                            defaultFile = self.defaultFile,
                            wildcard = self.wildcards,
                            style = wx.FD_SAVE | wx.FD_CHANGE_DIR)
        modal = dlg.ShowModal()
        filename = dlg.GetPath()
        filteridx = dlg.GetFilterIndex()
        dlg.Destroy()
        if modal != wx.ID_OK:
            return

        if filteridx == 0:
            filepostfix = '.png'
            bitmaptype = wx.BITMAP_TYPE_PNG
        elif filteridx == 1:
            filepostfix = '.jpg'
            bitmaptype = wx.BITMAP_TYPE_JPEG
        elif filteridx == 2:
            filepostfix = '.bmp'
            bitmaptype = wx.BITMAP_TYPE_BMP
        elif filteridx == 3:
            filepostfix = '.tiff'
            bitmaptype = wx.BITMAP_TYPE_TIF
        else:
            filepostfix = '.bmp'
            bitmaptype = wx.BITMAP_TYPE_BMP

        ## If postfix of filename is already there we don't add it
        filepostfixlen = len(filepostfix)
        if filename[-filepostfixlen:] == filepostfix:
            completefilename = filename
        else:
            completefilename = filename + filepostfix

        image = wx.ImageFromBitmap(self.BitWindow.buffer)
        image.SaveFile(completefilename, bitmaptype)

    def OnSerialPort(self, event):
        ## Calculate all ports available on per OS level
        if os.name == 'nt':
            allports = range(256)
        elif os.name == 'posix':
            allports = glob.glob('/dev/tty[A-Z]*')
            ## allports = range(1024)
            ## = ['/dev/ttyS0', '/dev/ttyS1', '/dev/ttyS2', '/dev/ttyS3',
            ##   '/dev/ttyS4', '/dev/ttyS5', '/dev/ttyS6', '/dev/ttyS7',
            ##   '/dev/ttyUSB0', '/dev/ttyUSB1', '/dev/ttyUSB2', '/dev/ttyUSB3',
            ##   '/dev/ttyUSB4', '/dev/ttyUSB5', '/dev/ttyUSB6', '/dev/ttyUSB7',
            ##   '/dev/ttyACM0', '/dev/ttyACM1', '/dev/ttyACM2', '/dev/ttyACM3',
            ##   '/dev/ttyACM4', '/dev/ttyACM5', '/dev/ttyACM6', '/dev/ttyACM7',
            ##   ]

        else:
            #print 'Unknown OS'
            os.exit()

        ## Search for all available ports, ie possible to open
        available = []
        for dev in allports:
            try:
                s = serial.Serial(dev)
                available.append((dev, s.portstr))
                s.close()   #explicit close 'cause of delayed GC in java
            except serial.SerialException:
                pass

        ## Build port list and open port selection list window
        if available == []:
            portnames = ["No comport"]
        else:
            # Pick out only the names, not indices
            portnames = [i[1] for i in available]

        dlg = wx.SingleChoiceDialog(None, "Select com port", "Com port",
                                    portnames)
        modal = dlg.ShowModal()
        serialport = dlg.GetStringSelection()
        dlg.Destroy()

        if modal == wx.ID_OK:
            # If serial port is open we must close it and make sure serial
            # receiving thread is stopped.
            if self.ser and self.ser.isOpen():
                self.StopThread()
                self.ser.close()
                self.ser = None
                self.statusbar.SetStatusText('No Comport', 1)

            ## Open serial port with requested speed
            try:
                self.ser = serial.Serial(serialport, self.speed, timeout = 1)
            except:
                wx.MessageBox("Serial port %s is not available" % serialport,
                              "Open serial port",
                              style = wx.OK | wx.ICON_ERROR)
                return

            ## Check if we managed to open port. At least in Linux it seems
            ## that sometimes serial.Serial does not generate an exception
            ## despite port is not opened.
            if not self.ser or not self.ser.isOpen():
                wx.MessageBox("Serial port %s failed to open" % serialport,
                              "Open serial port",
                              style = wx.OK | wx.ICON_ERROR)
                return

            ## Update statusbar
            self.statusbar.SetStatusText('%s' % serialport, 1)

            ## Start receiving thread
            self.StartThread()

    def OnSerialPortSpeed(self, event):
        dlg = wx.SingleChoiceDialog(None, "Select Speed", "Speed",
                                    ['300','600','1200','2400','4800','9600',
                                     '19200','38400','57600'])
        modal = dlg.ShowModal()
        speedstring = dlg.GetStringSelection()
        dlg.Destroy()

        if modal == wx.ID_OK:
            self.speed = int(speedstring)
            if self.ser and self.ser.isOpen():
                port = self.ser.port
                self.StopThread()
                self.ser.close()
                self.ser = serial.Serial(port, self.speed, timeout = 1)
                self.StartThread()
            self.statusbar.SetStatusText('%d' % self.speed, 2)

    def OnSerialRead(self, event):
        data = event.data
        self.pcl.parse(data)

        # Found start of graphical block
        if self.streaming == False and self.pcl.state != 'STATE_IDLE':
            self.streaming = True
            self.gauge = 0
            self.gaugemeter = wx.ProgressDialog('Receiving Data',
                                                'Receiving data from instrument...',
                                                maximum = self.nufRows,
                                                style = wx.PD_AUTO_HIDE |
                                                        wx.PD_CAN_ABORT)

        # Receiving graphical datablock
        if self.streaming and len(self.pcl.data) > self.gauge:
            self.gauge = len(self.pcl.data)
            (cont, skip) = self.gaugemeter.Update(self.gauge)
            wx.SafeYield()
            if not cont:
                self.pcl.state = 'STATE_IDLE'
                self.streaming = False
                self.pcl.data = []
                self.gaugemeter.Destroy()
                self.gaugemeter = None

        # Found end of graphical block
        if self.streaming and self.pcl.state == 'STATE_IDLE':
            self.streaming = False
            self.BitWindow.SetData(self.pcl.data)
            self.pcl.data = []
            wx.MilliSleep(100)
            self.gaugemeter.Destroy()
            self.gaugemeter = None

    def StartThread(self):
        """Start the receiver thread"""
        self.thread = threading.Thread(target = self.ComPortThread)
        self.thread.setDaemon(1)
        self.alive.set()
        self.thread.start()

    def StopThread(self):
        """Stop the receiver thread, wait util it's finished."""
        if self.thread is not None:
            self.alive.clear()          #clear alive event for thread
            self.thread.join()          #wait until thread has finished
            self.thread = None

    def ComPortThread(self):
        """Thread that handles the incoming traffic. Generates an
           SerialRxEvent"""
        while self.alive.isSet():               #loop while alive event is true
            text = self.ser.read(1)          #read one, with timeout
            if text:                            #check if not timeout
                n = self.ser.inWaiting()     #look if there is more to read
                if n:
                    text = text + self.ser.read(n) #get it
                event = SerialRxEvent(self.GetId(), text)
                self.GetEventHandler().AddPendingEvent(event)

    def OnAbout(self, event):
        description = """tivu acts as a printer connected to a testinstrument. It is mainly developed for HP E8285A, but can probably be used for other instruments using PCL printer output. When the program is started it waits silently for user to press "screen shot" button on the test instrument. tivu can currently save image as png, jpg, bmp and tiff.
"""

        licence = """Copyright (c) 2010-2012, Ciellt/Stefan Petersen (spe@ciellt.se)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. 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.

3. Neither the name of the author nor the names of any 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
COPYRIGHT OWNER 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.
"""

        info = wx.AboutDialogInfo()

        info.SetIcon(wx.Icon('tivu.png', wx.BITMAP_TYPE_PNG))
        info.SetName('Test Instrument Viewer')
        info.SetVersion('1.0')
        info.SetDescription(description)
        info.SetCopyright('(C) 2010 - 2012 Ciellt/Stefan Petersen')
        info.SetWebSite('http://www.ciellt.se/')
        info.SetLicence(licence)
        info.AddDeveloper('Stefan Petersen')
        #info.AddDocWriter('')
        #info.AddArtist('')
        #info.AddTranslator('')

        wx.AboutBox(info)

    def OnQuit(self, event):
        self.StopThread()
        self.Destroy()


text:
sudo yum -y install xinetd openssl-devel gcc

sudo mkdir ~/tmp
sudo cp -rf /apps/apps/infra/etc/nagios/files/* ~/tmp
sudo yum -y install xinetd openssl-devel gcc
sudo useradd -d /usr/local/nagios/ -M nagios
sudo chown nagios:nagios /usr/local/nagios/

cd ~/tmp/
sudo tar -xzf nagios-4.0.7.tar.gz
sudo tar -xzf nagios-plugins-2.0.2.tar.gz
sudo tar -xzf nrpe-2.15.tar.gz

# nagios install
cd ~/tmp/nagios-4.0.7
sudo  ./configure --with-nagios-user=nagios --with-nagios-group=nagios -prefix /usr/local/nagios
sudo make all
sudo make install
sudo make install-init
sudo make install-config
sudo make install-commandmode
sudo make install-webconf
sudo cp -R contrib/eventhandlers/ /usr/local/nagios/libexec/
sudo chown -R nagios:nagios /usr/local/app/nagios/libexec/eventhandlers
sudo /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg

#nagios plugin install
cd ~/tmp/
cd ~/tmp/nagios-plugins-2.0.2
sudo ./configure && sudo make
sudo make install

# nrpe install
cd ~/tmp/
tar -xzf nrpe-2.15.tar.gz
cd ~/tmp/nrpe-2.15
sudo ./configure && sudo make && sudo make install

sudo cp -rf /apps/apps/infra/etc/nagios/libexec/check_mem.pl /usr/local/nagios/libexec/
sudo chmod +x /usr/local/nagios/libexec/check_mem.pl
sudo echo "nrpe 5666/tcp # NRPE" >> /etc/services
sudo cp /apps/apps/infra/etc/nrpe/nrpe.cfg /usr/local/app/nagios/etc/
sudo chown nagios:nagios /usr/local/nagios/etc/nrpe.cfg
sudo cp /apps/apps/infra/etc/nrpe/nrpe /etc/xinetd.d/nrpe
sudo /etc/rc.d/init.d/xinetd start

sudo rm -rf ~/tmp


text:
package com.box.l10n.mojito.smartling.response;

public class ContextUploadResponse extends Response<ContextUpload> {}


text:
jQuery(document).ready(function($){
	$('body').on('click','#upload-btn',function(e) {
		var clicked_incentive = parseInt( $( this ).attr( 'data-attr-position' ) );
		e.preventDefault();
		var image = wp.media({
			title: 'Upload Image',
			// mutiple: true if you want to upload multiple files at once
			multiple: false
		}).open()
		.on('select', function(e){
			// This will return the selected image from the Media Uploader, the result is an object
			var uploaded_image = image.state().get('selection').first();
			// We convert uploaded_image to a JSON object to make accessing it easier
			// Output to the console uploaded_image
			var image_url = uploaded_image.toJSON().url;
			if( uploaded_image.toJSON().hasOwnProperty( 'sizes' ) ) {
				if( uploaded_image.toJSON().sizes.medium ) {
					var size = uploaded_image.toJSON().sizes.medium.width;
				} else if( uploaded_image.toJSON().sizes.full ) {
					var size = uploaded_image.toJSON().sizes.full.width;
				} else {
					var size = '';
				}
			}
			// Let's assign the url value to the input field
			$( 'input[data-attr-position="'+clicked_incentive+'"]' ).prev().val( image_url );
			populate_file_container( image_url, clicked_incentive );
			// adjust file container size
			$( 'a[data-attr-position="'+clicked_incentive+'"]' ).next().attr( 'width' , size+'px' ).css({ 'max-width' : size+'px', 'width' : '100%' });
			$( 'a[data-attr-position="'+clicked_incentive+'"]' ).parents( '.file-container' ).show()
		});
	});
});

function populate_file_container( image_url, clicked_incentive ) {
	var extension = image_url.substr( ( image_url.lastIndexOf('.') +1) );
	switch(extension) {
		case 'jpg':
		case 'png':
		case 'gif':
			var file_container = '';  // There's was a typo in the example where
		break;                         // the alert ended with pdf instead of gif.
		case 'zip':
		case 'rar':
			var file_container = '';  // There's was a typo in the example where
		break;
		case 'pdf':
			var file_container = '';  // There's was a typo in the example where
		break;
		case 'mp3':
		case 'wav':
		case 'wma':
			var file_container = '';  // There's was a typo in the example where
		break;
		case 'mp4':
		case 'avi':
		case 'mpg':
		case 'mov':
		case 'qt':
		case 'mpeg':
		case '3gp':
		case 'ogm':
		case 'ogg':
			var file_container = '';  // There's was a typo in the example where
		break;
		default:
			alert('who knows');
	}
	jQuery( 'a[data-attr-position="'+clicked_incentive+'"]' ).parent( '.file-remove-wrapper' ).find( 'img.incentive-image-preview' ).remove()
	jQuery( 'a[data-attr-position="'+clicked_incentive+'"]' ).parent( '.file-remove-wrapper' ).append( file_container ).find( 'a' );
}


text:
<?php namespace Fisharebest\Localization\Script;

class ScriptDeva extends AbstractScript implements ScriptInterface {
	public function code() {
		return 'Deva';
	}

	public function numerals() {
		return array('०', '१', '२', '३', '४', '५', '६', '७', '८', '९');
	}

	public function number() {
		return '315';
	}

	public function unicodeName() {
		return 'Devanagari';
	}
}


text:
<?xml version='1.0' encoding='utf-8'?>
<plugin id="cordova-plugin-empatica-device" version="1.0.0" xmlns="http://apache.org/cordova/ns/plugins/1.0"
        xmlns:android="http://schemas.android.com/apk/res/android">
    <name>Empatica</name>
    <js-module name="Empatica" src="www/Empatica.js">
        <clobbers target="Empatica"/>
    </js-module>
    <platform name="android">
        <config-file parent="/*" target="res/xml/config.xml">
            <feature name="Empatica">
                <param name="android-package" value="au.edu.sydney.poscomp.Empatica"/>
            </feature>
        </config-file>
        <config-file parent="/*" target="AndroidManifest.xml">
            <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        </config-file>
        <source-file src="src/android/Empatica.java" target-dir="src/au/edu/sydney/poscomp/"/>
        <framework custom="true" src="src/android/Empatica.gradle" type="gradleReference"/>
        <source-file src="src/android/empalink-2.1.aar" target-dir="libs/"/>
    </platform>
    <platform name="ios">
        <config-file parent="/*" target="config.xml">
            <feature name="Empatica">
                <param name="ios-package" value="Empatica"/>
            </feature>
        </config-file>
        <header-file src="src/ios/Empatica.h" />
        <source-file src="src/ios/Empatica.m"/>
        <framework src="ExternalAccessory.framework" />
        <framework src="libz.dylib" />
        <framework src="CoreBluetooth.framework" />
        <framework src="CoreMotion.framework" />
        <framework src="CFNetwork.framework" />
        <framework src="MessageUI.framework" />
        <framework src="Security.framework" />
        <framework src="Accelerate.framework" />
        <framework src="src/ios/EmpaLink-ios-0.7-full.framework" custom="true" />

        <preference name="BLUETOOTH_USAGE_DESC" default="We need bluetooth access to connect to your device." />
        <config-file target="*-Info.plist" parent="NSBluetoothPeripheralUsageDescription">
            <string>$BLUETOOTH_USAGE_DESC</string>
        </config-file>
        <config-file parent="UIBackgroundModes" target="*-Info.plist">
            <array>
                <string>bluetooth-central</string>
            </array>
        </config-file>
    </platform>
</plugin>


text:
module ShardedModel

  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods

    # needed to tell User.using that it is a model_shard
    attr_accessor :SHARDED
    attr_accessor :MODEL_SHARD

    def get_vbucket(id)
      Digest::MD5.hexdigest(id).gsub(/[a-z]/i) { |s| s.ord.to_s }.to_i % Afterburner.VBUCKET_COUNT
    end

    def using_vb(vbucket, *options)
      begin
        shard_name = ''
        raise "incompatible setting for SHARDED variable in class or instance #{self.inspect}" if (REF == vbucket and self.SHARDED == true) or (REF != vbucket and self.SHARDED.nil?)
        shard_name = get_shard_name(vbucket)
        return self.using(shard_name).send(*options)
      rescue Exception => e
        if self.class.name == "Asset"
          Octopus.using(:master) do
            return self.first
          end
        end
        raise e
      end
    end

    def all_shards_helper(type, *options)
      # this is operation on all shards
      result = []
      # brute force for now .... optimize later
      shard_name = ''
      shard_count = Afterburner.SHARDS_CONFIG['db']['generic']['shards_count']
      if self.MODEL_SHARD == true
        shard_name = self.name.underscore+'_'
        shard_count = Afterburner.SHARDS_CONFIG['db'][self.name.underscore]['shards_count']
      end
      shard_count.times do |s|
        if type == :each
          result << self.using("shard_#{shard_name+s.to_s}_#{::Rails.env}".to_sym).send(*options)
        else
          temp_var = self.using("shard_#{shard_name+s.to_s}_#{::Rails.env}".to_sym).send(*options)
          if !temp_var.instance_of?(Array)
            result += [self.using("shard_#{shard_name+s.to_s}_#{::Rails.env}".to_sym).send(*options)]
          else
            result += self.using("shard_#{shard_name+s.to_s}_#{::Rails.env}".to_sym).send(*options)
          end
        end
      end
      # we have an array or arrays
      result
    end

    def in_each_shard(*options)
      all_shards_helper(:each, *options)
    end

    def in_all_shards(*options)
      all_shards_helper(:all, *options)
    end

    def in_each_db(*options)
      result = {}
      result['master'] = self.using(get_shard_name(REF)).send(*options)
      Afterburner.SHARDS_CONFIG['db'].keys.each do |key|
        next if key == 'master'
        result[key] = {}
        Afterburner.SHARDS_CONFIG['db'][key]['shards_count'].times do |c|
          shard_name = key == 'generic' ? c.to_s : "#{key}_#{c}"
          result[key][c] = self.using("shard_#{shard_name}_#{::Rails.env}".to_sym).send(*options)
        end
      end
      result
    end

    def get_shard_name(vbucket)
      return :master if ENV['SINGLE_SHARD'].to_s == 'true'
      shard_count = Afterburner.SHARDS_CONFIG['db']['generic']['shards_count']
      if vbucket != REF
        shard_id = ''
        if self.class == Class.class
          # in class method =>
          if self.MODEL_SHARD
            shard_id = self.name.underscore
            shard_count = Afterburner.SHARDS_CONFIG['db'][shard_id]['shards_count']
            shard_id = "#{shard_id}_"
          end
        else
          # in instance method
          if self.class.MODEL_SHARD
            shard_id = self.class.name.underscore
            shard_count = Afterburner.SHARDS_CONFIG['db'][shard_id]['shards_count']
            shard_id = "#{shard_id}_"
          end
        end
        shard_name = "#{shard_id}#{vbucket%shard_count}"
        return "shard_#{shard_name}_#{::Rails.env}".to_sym
      else
        return :master
      end
    end
  end

  def check_vbucket
    unless self.vbucket
      self.vbucket = self.class.get_vbucket(self.class.name == User.name ? "FB_#{self.facebook_id}" : self.user_id)
    end
  end

  def my_vbucket
    self.class.SHARDED == true ? self.vbucket : REF
  end

end


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.udit.shangri_la">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:name=".ShangriLaApplication">
        <activity android:name=".splash.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".home.HomeActivity" />
    </application>
</manifest>


text:
import React from "react";
import {connect} from "react-redux";
import {Breadcrumb, BreadcrumbItem} from "react-bootstrap";
import {navigateHome, navigateViewCourtCase} from "../store/actions/NavigationActions";

const EditCourtCaseEvents = ({caseNumber, party, navigateHome, navigateViewCourtCase, activeBreadcrumbText}) =>
    <Breadcrumb>
        <BreadcrumbItem id="breadcrumb-home" onClick={navigateHome}>Home</BreadcrumbItem>
        <BreadcrumbItem id="breadcrumb-case" onClick={navigateViewCourtCase}>Case Number {caseNumber} ({party})</BreadcrumbItem>
        <BreadcrumbItem id="breadcrumb-active" active>{activeBreadcrumbText}</BreadcrumbItem>
    </Breadcrumb>;

EditCourtCaseEvents.displayName = "EditCourtCaseEvents";

EditCourtCaseEvents.propTypes = {
    caseId: React.PropTypes.string.isRequired,
    caseNumber: React.PropTypes.string.isRequired,
    party: React.PropTypes.string.isRequired,
    navigateHome: React.PropTypes.func.isRequired,
    navigateViewCourtCase: React.PropTypes.func.isRequired,
    activeBreadcrumbText: React.PropTypes.string.isRequired
};

const mapDispatchToProps = (dispatch, {caseId}) => ({
    navigateHome: () => dispatch(navigateHome()),
    navigateViewCourtCase: () => dispatch(navigateViewCourtCase(caseId))
});

export default connect(undefined, mapDispatchToProps)(EditCourtCaseEvents);


text:
<?php

namespace SmoothPHP\Framework\Templates\Compiler;

use Exception;

class TemplateCompileException extends Exception {
}


text:
var Shov3Prefs = {
  endpoint: 's3.amazonaws.com'
};

var Shov3 = function(options, $) {
  var params = {};
  var defaultParams = {
    bucket: null,
    key: null,
    acl: 'public-read',
    aws_key: null,
    secret: null,
    redirect: null,
    folder: ''
  };

  $.extend(true, params, defaultParams);
  $.extend(true, params, options);

  var that = {};

  // Generates S3 access policy string
  // @params name: Name of object to access
  // @params contentType: MIME Type of object to access

  that.policy = function(name, contentType) {
    var POLICY_JSON = {
      "expiration": "2013-12-31T12:00:00.000Z", // @TODO nicer date string
      "conditions": [
        ["eq", "$bucket", params.bucket],
        ["starts-with", "$key", params.folder + name],
        {"acl": params.acl},
        {"success_action_redirect": params.redirect},
        {"x-amz-meta-filename": name},
        ["starts-with", "$Content-Type", contentType]
      ]
    };
    return Base64.encode(JSON.stringify(POLICY_JSON));
  };

  // Generates S3 access signature
  // @params name: Name of object to access
  // @params contentType: MIME Type of object to access

  that.signature = function(name, contentType) {
    return b64_hmac_sha1(params.secret, that.policy(name, contentType));
  };

  // Turn Base64 string into Uint8Array
  // @params b64Str: Base64 string

  that.getBin = function(b64Str) {
    var bin = window.atob(b64Str);
    return that.getAB(bin);
  };

  // Turn binary string into Uint8Array
  // @params bin: Binary string

  that.getAB = function(bin) {
    var ab = new ArrayBuffer(bin.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < bin.length; i++) {
        ia[i] = bin.charCodeAt(i);
    }

    return ia;
  };

  // Send XHR request to S3-compatible store
  // @params bin: Binary content to send
  // @params name: Name of object to send
  // @params contentType: MIME Type of object to send
  // @params callback: Triggered on success
  // @params progressCallback: Triggered on progress update

  that.sendXHR = function(bin, name, contentType, callback, progressCallback) {
    var fd = new FormData();

    fd.append('key', params.folder + name);
    fd.append('acl', params.acl);
    fd.append('Content-Type', contentType);
    fd.append('AWSAccessKeyId', params.aws_key);
    fd.append('success_action_redirect', params.redirect);
    fd.append('x-amz-meta-filename', name);
    fd.append('Policy', that.policy(name, contentType));
    fd.append('Signature', that.signature(name, contentType));

    var binBlob = new Blob([bin], {type: contentType});
    fd.append('file', binBlob);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", 'http://' + params.bucket + '.' + Shov3Prefs.endpoint);

    xhr.onload = function() {
    };

    xhr.upload.addEventListener('progress', function(e) {
      if (!!progressCallback && $.isFunction(progressCallback)) {
        progressCallback(e);
      }
    }, false);

    xhr.onreadystatechange = function() {
      if (xhr.readyState != 4)  { return; }

      xhr = new XMLHttpRequest();
      xhr.open("GET", params.redirect + "?key=" + params.folder + name, false);
      xhr.send(null);

      callback([
        params.bucket,
        params.folder + name,
        ''
      ]);
    };

    xhr.send(fd);
  };

  // List directory
  // @params callback: Triggered on success

  that.listDir = function(callback) {
    $.ajax({
      url: 'http://' + params.bucket + '.' + Shov3Prefs.endpoint,
      data: {
        'prefix': params.folder
      },
      headers: {
      },
      dataType: 'xml',
      beforeSend: function(xhr) {
      },
      success: function(data, textStatus, jqXHR) {
        callback(data);
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
      }
    });
  };

  return that;
};


text:
class CreateClicks < ActiveRecord::Migration
  def change
    create_table :clicks do |t|
      t.json :data
      t.belongs_to :site
      t.timestamps
    end
  end
end


text:
title: 'AncesTrim - a tool for trimming complex pedigrees'
tags:
  - genealogy
  - Python
  - genetics
authors:
 - name: Julia Niskanen
   orcid: 0000-0002-2871-6890
   affiliation: 1, 2, 3
 - name: Elina Salmela
   orcid: 0000-0003-1326-4462
   affiliation: 1, 2, 3, 4
 - name: Hannes Lohi
   orcid: 0000-0003-1087-5532
   affiliation: 1, 2, 3
affiliations:
 - name: Department of Veterinary Biosciences, University of Helsinki, Helsinki, Finland
   index: 1
 - name: Research Programs Unit, Molecular Neurology, University of Helsinki, Helsinki, Finland
   index: 2
 - name: The Folkhälsan Institute of Genetics, Helsinki, Finland
   index: 3
 - name: Department of Biosciences, University of Helsinki, Helsinki, Finland
   index: 4
date: 3 January 2017
bibliography: paper.bib
---

# Summary

AncesTrim [@AncesTrim] is a Python tool for trimming complex pedigrees. Some pedigree data
can have an inherently complicated structure with a high level of inbreeding, which makes
visualization of such data difficult. AncesTrim reduces the complexity of pedigrees while
preserving critical relatedness structures, allowing the pedigree to be displayed in a more
efficient way.

# References


text:
class EmptyWidget :
    public IWidget
{
public:
    EmptyWidget(const std::string& name);

    virtual void draw() override;

private:
    std::string name_;
};

#endif // FLOATING_EYE_EMPTYWIDGET_H


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
description: >
    An AssignmentRestElement may not follow another AssignmentRestElement in an
    AssignmentElementList.
es6id: 12.14.5
negative: SyntaxError
---*/

var x, y;

[...x, ...y] = [];


text:
Dex
=========

[Developers Guide](non-server/DEVELOPERS-GUIDE.md)
[Style](non-server/STYLE.md)
[Repository Guide](non-server/REPO-GUIDE.md)

Dex is a small and simple CMS designed for small- to medium-sized websites. It aims for high usability and intuitivity for users, while remaining robust and modular for webmasters.

### Properties
1. Fast
 - Makes use of server and browser caching
 - Concatenates JS and CSS to one file to reduce requests
 - Minifies HTML output
2. Modular
 - Adding themes, modules and templates is as easy as uploading the files
 - Using callbacks modules can hook onto certain actions to add functionality
3. Portable
 - All data is being stored in one folder
 - No need to setup a database, since it uses SQLite3
 - No references to the URL or directory, so it is truly portable
4. Usable
 - Stripped-down admin panel for editors
 - Simple editor and asset management
5. Strict
 - Themes do not contain logic or HTML
 - Page content is true WYSIWYG, edit you page in-place

### Note
Dex is _not_ suited for blogs, forums or large sites. The CMS is simply underdeveloped at this point of time and is in the first place not build for very large or dynamic sites.

The CMS relies on modern but common used software. This includes the use of Sqlite3, HTML5 and CSS3. It is not hold back by legacy but doesn't use experimental software either.

### Comparison to Wordpress
The project was initiated after heavy use of Wordpress for sites. Where Wordpress is officially a blog platform, I noticed how users dislike the large admin panel which is mostly for webmasters anyways. Dex tries to minimize the options editors have, they edit pages and manage assets. Period.

Wordpress, while modular, is not ideal to build themes for. Build a theme for Wordpress from the start and notice how many blog related elements need to be hidden. Dex is very modular too, but is more strict with themes. Themes do not contain logic or HTML, which clears the line between logic and presentation. Dex sets a basic HTML structure and modules can expand on that, themes do not.

Another downside of Wordpress is its size. The output HTML is large, CSS and JS files are imported plenty (WP Total Cache solves a lot but is complex and clumsy). Dex automatically concatenates CSS and JS files and minifies output HTML.

Installation
------------

Use git clone or download the zipfile from Git and extract. Move the files onto your webserver and access it with your browser. The setup page will show and a (SQLite) database is created containing all site-specific data. The non-server/ directory does not have to be uploaded.

Accessing the admin panel is done by appending admin/ to the base site URL. Removing *.db will reinitiate the setup process.

Make sure that the following Apache modules are enabled:
- mod_rewrite (essential)
- mod_deflate
- mod_expires
- mod_filter
- mod_headers

And these PHP extensions:
- php_sqlite3 (essential)
- php_curl (or allow_url_fopen = 1)

### Installing modules, themes and templates

Move the module, theme or template folder into modules/, themes/ or templates/ respectively. The next time you load a page in the admin panel the new module will be installed. Deleting the module, theme or template folder will uninstall.

### Setting up a site

After setup you can add content using the admin panel. Create pages and upload assets. Make sure to make pages visible in the menu module so the pages can be navigated to.


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
        <title>Agency - Start Bootstrap Theme</title>

        <link href="css/bootstrap.min.css" rel="stylesheet">

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

        <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
        <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                    </button>
                    TrendyMan

                            How It Works

                            Portfolio

                            Team

                            Our Brands

                            Contact

LET US DO YOUR SHOPPING!

Our stylistes select for you clothes and you do deliver home free.

                    Tell Me More

How It Works

REFER

to your stylist your tastes, your desires and your budget.

GET

home in a nice box, a selection of clothes.

TRY

your clothes within 7 days and keep what you like.

NO PURCHASE NECESSARY

FREE DELIVERY AND RETURN

NO SUBSCRIPTION

SAME PRICE AS RETAIL STORE

Portfolio

Click and Find Your Own Personal Style In Our Lookbook.

Casual Chic

Classic

Business

Contemporain

Rock

Dandy

NO PURCHASE NECESSARY

FREE DELIVERY AND RETURN

NO SUBSCRIPTION

SAME PRICE AS RETAIL STORE

Our Amazing Stylistes

CHOOSE YOUR PERSONAL STYLIST

Marion

Alex

Karolina

A STYLIST AT YOUR SERVICE

"Every client is different ... All our selections are unique and increasingly accurate over our relationship."

Our Brands

We select the best brands of menswear. The unavoidable, but also our findings, for all styles.

Contact Us

Call us for being put in touch with a stylist!

You have questions ? We are there to respond. Feel free to visit our FAQ for read answers to questions most frequently ask.

CONTACT US AT

08 40 18 10 25

Monday to Thursday (9h-20h)
and Friday (9h-18h)

OR BY MAIL TO THE ADDRESS

customer-service@trendyman.com

<form name="sentMessage" id="contactForm" novalidate>

                <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

            <button type="submit" class="btn btn-xl">Send Message</button>

</form>

About

Career

FAQ

Contact

Copyright

GTCS

TrendyMan

What is TrendyMan?

TrendyMan is a personalized styling service for men: we propose a new solution to men who want to be well dressed without having to do shopping.Frankly, for most of us, shopping is often a chore, either online or in stores. It's thinking about the uses and the specific needs of men than we imagined TrendyMan.At your request, your stylist composes a personalized selection of clothing from the brands you love and makes it delivered to your door. You have 7 days to try the clothes, without any obligation to purchase.You pay only the clothes you keep, we get the rest. Shipping and returns are free.

TrendyMan is for men who want to wear quality clothes of the best brands, but do not have time or do not like shopping, online or in stores. The service is particularly relevant for those of us who do not have an urgent need to buy clothes or who are not looking for a specific piece for personalized composition.

Career

JOIN US

TrendyMan is a young company that wants to reconcile men with fashion.
We are reinventing the way to distribute ready-to-wear and offer our customers an exceptional shopping experience,
based on customization and high quality service.

To apply to current offers, please send your application to recrutement@trendyman.com.
simply send your CV and a short email explaining your motivations to join us.

Current Offers

JOB DESCRIPTION

You are at the center of the organization. You are responsible for the animation of your customer:
You participate in the acquisition of customers in the sales and marketing operations and build your customer portfolio (prospection: email, phone ...)
During your phone conversation, you greet and qualify customer contacts and help build customer database
You analyze in detail with his needs and desires.
You select the clothes to send him among supply TrendyMan and compose a personalized selection.
You accompany the client throughout his experience (feedback after receiving the trunk, operational monitoring) and maintain a relationship of trust with him, your goal loyalty.

WHAT WE LOOK

You have experience in sales, (ideally in menswear) and are (on) vendor (se) performer (s) willing to work in a rapidly changing environment. You are recognized (e) for your sense of service, your professional and personalized advice. We often notice your listening skills and the quality of your relationships, even with demanding customers. Your motivation: customer satisfaction and taste for challenge. You are an enterprising person who wants to create and animate its customer portfolio. You are force proposal, do bring solutions and take initiative. You have strong organizational skills, time management and know your priorities.

WHAT YOU WILL FIND IN TrendyMan

A full shift, original and fast moving with society. Turned to selling, consulting and managing a portfolio of clients. Which allows you to learn quickly, while acting. Where you can feel with your added value. A young and friendly staff, a dynamic start-ups and even adventure in its infancy.

FAQ

Frequently Asked Questions

What is TrendyMan?

TrendyMan is a personalized styling service for men: we propose a new solution to men who want to be well dressed without having to do shopping.Frankly, for most of us, shopping is often a chore, either online or in stores. It's thinking about the uses and the specific needs of men than we imagined TrendyMan.At your request, your stylist composes a personalized selection of clothing from the brands you love and makes it delivered to your door. You have 7 days to try the clothes, without any obligation to purchase.You pay only the clothes you keep, we get the rest. Shipping and returns are free.

How to use the TrendyMan service?

To start using ChicTypes, simply send us a mail or call us directly. Once this step done, you tell to your stylist your tastes, your desires and your budget to determine what you expect from your first trunk. Please visit the "How it works" for details.

What kind of clothes do you suggest?

 We focus on premium brands and offer only casual clothes: a careful selection of jackets, pants, tops, knits and shoes of the best brands. No costumes at the moment, but you will find shirts and street shoes. Imagine the best of the brands you like, specifically selected for you. Visit the page "portofolio" for more details.

About Us

What is TrendyMan?

TrendyMan is a personalized styling service for men: we propose a new solution to men who want to be well dressed without having to do shopping.Frankly, for most of us, shopping is often a chore, either online or in stores. It's thinking about the uses and the specific needs of men than we imagined TrendyMan.At your request, your stylist composes a personalized selection of clothing from the brands you love and makes it delivered to your door. You have 7 days to try the clothes, without any obligation to purchase.You pay only the clothes you keep, we get the rest. Shipping and returns are free.

Who are the users of TrendyMan?

TrendyMan is for men who want to wear quality clothes of the best brands, but do not have time or do not like shopping, online or in stores. The service is particularly relevant for those of us who do not have an urgent need to buy clothes or who are not looking for a specific piece for personalized composition.

And for women?

Sorry, we do not offer clothing for women. But we are convinced that we can  reconciling men with their shopping. You will have more time for them, and you will appreciate their elegance.

Deliveries and Returns

How to use the TrendyMan service?

To start using ChicTypes, simply send us a mail or call us directly. Once this step done, you tell to your stylist your tastes, your desires and your budget to determine what you expect from your first trunk. Please visit the "How it works" for details.

How to use the TrendyMan service?

To start using ChicTypes, simply send us a mail or call us directly. Once this step done, you tell to your stylist your tastes, your desires and your budget to determine what you expect from your first trunk. Please visit the "How it works" for details.

How to use the TrendyMan service?

To start using ChicTypes, simply send us a mail or call us directly. Once this step done, you tell to your stylist your tastes, your desires and your budget to determine what you expect from your first trunk. Please visit the "How it works" for details.

Contact Us

Call us for being put in touch with a stylist!

You have questions ? We are there to respond.
Feel free to visit our FAQ for read answers to questions most frequently ask.

CONTACT US AT

08 40 18 10 25

Monday to Thursday (9h-20h)

and Friday (9h-18h)

OR BY MAIL TO THE ADDRESS

customer-service@trendyman.com

<form name="sentMessage" id="contactForm" novalidate>

                <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

            <button type="submit" class="btn btn-xl">Send Message</button>

</form>

Copyright

This Project is a fake project created during an exercice in a class to learn how to code. I found all the images in several websites.

General terms and conditions of sale

Object

These general conditions of sale apply without restriction or reservation to all sales offered online by the company Andromatic www.trendyman.com on the website (hereinafter: the "Site"). The site is an ecommerce platform that allows users (hereinafter: the "Buyers") to acquire clothing and / or accessories (hereinafter: the "Products"), as part of sales test, as described in Article 5.
The Site and the Products are only available to individuals and are not intended to professionals, understood as all natural or legal persons in paid employment than occasionally in all sectors of industry and commerce, including especially the fashion and accessories sector.
These general conditions are intended to determine the terms and conditions of these sales testing and delivery of the products and to define the rights and obligations of the parties in this context.
They are accessible and printable at any time by a direct link on the Site.
They may be supplemented if necessary by special conditions of use for certain products or services, which complement the present general conditions and, in case of conflict, prevail over the latter.

Intellectual Property

Systems, software, structures, infrastructures, databases and content of any kind (text, images, video, music, logos, trademarks, database, etc.) operated by ChicTypes within the Site are protected by rights of all or intellectual property rights of producers of existing databases. All disassembly, decompilation, decryption, extractions, reuses, copies and more generally, any act of reproduction, distribution and use of any of these elements, in whole or part without permission is strictly prohibited and ChicTypes may be subject to prosecution.

Responsability

TrendyMan undertakes to conduct regular checks to verify the functioning and accessibility of the site. As such, ChicTypes reserves the right to temporarily interrupt access to the site for maintenance reasons. Similarly, ChicTypes can not be held responsible for difficulties or impossibilities temporary access to the Site which would originally circumstances that are external, force majeure, or which would be due to disruptions in telecommunication networks.
The connection of any person to the website is fully responsible. It is up to the Purchaser to take all appropriate measures to protect their data and / or software stored on his computer equipment and against any attack.
Moreover, TrendyMan can not be held responsible for failure or delay in the execution of the sales contract due to a force majeure or disruption or total or partial strike of postal services and means of transportation or communications.

LEGAL CAPACITY AND ACCEPTANCE OF TERMS

The Buyer declares, prior to his order, he has full legal capacity, enabling it to engage under these terms.

Acceptance thereof is represented by a check box in the order form. This acceptance can only be full. Any acceptance subject is considered null and void. Buyer who does not accept to be bound by these terms and conditions shall not perform control on the Site.


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

    <string name="app_name">ActiWatch</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_login">LoginActivity</string>
    <string name="hello_world">Hello world!</string>
    <string name="prompt">Please fill in your name and select the desired activity. No action is required on the watch.</string>
    <string name="copyright">© 2014 Fordham University WISDM Lab.</string>
</resources>


text:
<?php

namespace MusicBrainz\Value\Property;

use MusicBrainz\Helper\ArrayAccess;
use MusicBrainz\Value\AnnotationText;

/**
 * Provides a getter for the annotation text.
 */
trait AnnotationTextTrait
{
    /**
     * The annotation text
     *
     * @var AnnotationText
     */
    private AnnotationText $annotationText;

    /**
     * Returns the annotation text.
     *
     * @return AnnotationText
     */
    public function getAnnotationText(): AnnotationText
    {
        return $this->annotationText;
    }

    /**
     * Sets the annotation text by extracting it from a given input array.
     *
     * @param array $input An array returned by the webservice
     *
     * @return void
     */
    private function setAnnotationTextFromArray(array $input): void
    {
        $this->annotationText = is_null($annotationText = ArrayAccess::getString($input, 'text'))
            ? new AnnotationText()
            : new AnnotationText($annotationText);
    }
}


text:
Test for PHP-543: Mongo::connect() should return a bool value.
--SKIPIF--
<?php require dirname( __FILE__ ) . "/skipif.inc" ?>
--FILE--
<?php
require dirname( __FILE__ ) . "/../utils.inc";

$m = mongo(null, true, true, array( 'connect' => false ) );
var_dump($m->connect());

try
{
	$m = new Mongo("mongodb://totallynonsense/", array( 'connect' => false ) );
	var_dump($m->connect());
}
catch ( Exception $e )
{
	echo $e->getMessage(), "\n";
}
?>
--EXPECTF--
bool(true)
Failed to connect to: %s:%d: %s