text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package JdbcManagment;

import common.data.Dbmanager;
import common.model.Cure;
import common.model.pline;
import common.model.preciption;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author helmi
 */
public class PreceptionDao {
    public static void addPreciption(preciption pre  ) throws SQLException{
        try (Connection con = Dbmanager.getConnection()) {
            PreparedStatement st = con.prepareStatement("select max(prescription_id) from prescription_line;");
            ResultSet rs = st.executeQuery();
            rs.next();
            int id = rs.getInt(1)+1;
            for (pline col : pre.lines) {
                st = con.prepareStatement("INSERT INTO `prescription_line` "
                        + "(`prescription_id`, `count`, `cure`, `note`, `amount`, `place`, `duration`, `Edis`)"
                        + " VALUES ('"+id+"', '"+col.count+"','"+col.cure+"','"+col.note+"','"+col.amount+"','"+col.place+"','"+col.duration+"','"+pre.dis.name+"');");
                st.executeUpdate();
                con.close();
            }
        }}
        public static List<preciption> getPreByDis(String name) throws SQLException{
            ResultSet rs;
        try (Connection con = Dbmanager.getConnection()) {
            PreparedStatement st = con.prepareStatement("select * from prescription_line where  Edis ='"+name+"' order by  prescription_id;");
            rs = st.executeQuery();
        }
     List<preciption> temp = new ArrayList<>();

     while(rs.next()){
       int item=rs.getInt(1);
       preciption ps = new preciption();
       while(item ==rs.getInt(1)){
       pline pl = new pline();
       pl.count= rs.getInt(2);
      pl.cure = rs.getString(3);
     pl.note = rs.getString(4);
     pl.amount = rs.getInt(5);
     pl.place = rs.getString(6);
     pl.duration = rs.getInt(7);
      ps.lines.add(pl);
   }
     temp.add(ps);
     }
        return temp;
        }
    }


text:
import _ from 'lodash';

let averageBarWidth = 30;
let debugSpacing = 2;

export default class Debug {
  constructor(opts = {}) {
    this.opts = {
      canvasId: opts.canvasId || 'debug-canvas',
      width: opts.width || 240,
      height: opts.height || 140
    };
    this.init();
  }

  init() {
    let canvas = document.getElementById(this.opts.canvasId);
    let debugCtx = canvas.getContext('2d');
    let gradient = debugCtx.createLinearGradient(0, 0, 0, 256);

    debugCtx.width = this.width;
    debugCtx.height = this.height;
    debugCtx.fillStyle = 'rgb(40, 40, 40)';
    debugCtx.lineWidth = 2;
    debugCtx.strokeStyle = 'rgb(255, 255, 255)';

    gradient.addColorStop(1, '#330000');
    gradient.addColorStop(0.75, '#aa0000');
    gradient.addColorStop(0.25, '#aaaa00');
    gradient.addColorStop(0, '#aaaaaa');

    this.debugCtx = debugCtx;
    this.gradient = gradient;
  }

  draw(soundData) {
    let {width, height} = this.opts;
    let {debugCtx, gradient} = this;
    let {levels, waveform, beatCutOff, isBeat, volume} = soundData;
    let bpmHeight = height - chartHeight;
    let chartHeight = height;
    let chartWidth = width - 40;

    debugCtx.clearRect(0, 0, width, height);

    // background
    debugCtx.fillStyle = '#000';
    debugCtx.fillRect(0, 0, width, height);

    // levels bar chart
    let barWidth = chartWidth / levels.length;
    debugCtx.fillStyle = gradient;
    _.times(levels.length, (i) => {
      debugCtx.fillRect(i * barWidth, chartHeight, barWidth - debugSpacing, levels[i] * chartHeight * -1);
    });

    // volume level + beat
    if (isBeat){
      debugCtx.fillStyle = '#ffffff';
    }
    debugCtx.fillRect(chartWidth, chartHeight, averageBarWidth, volume * chartHeight *-1);

    // beat cut off
    debugCtx.beginPath();
    debugCtx.moveTo(chartWidth , chartHeight - beatCutOff * chartHeight);
    debugCtx.lineTo(chartWidth + averageBarWidth, chartHeight - beatCutOff * chartHeight);
    debugCtx.stroke();

    // waveform
    debugCtx.beginPath();
    _.times(waveform.length, (i) => {
      debugCtx.lineTo(i / waveform.length * chartWidth, waveform[i] * chartHeight / 2 + chartHeight / 2);
    });
    debugCtx.stroke();

    // DRAW BPM
    // var bpmMaxSize = bpmHeight;
    // var size = bpmMaxSize - bpmTime * bpmMaxSize;
    // debugCtx.fillStyle="#020";
    // debugCtx.fillRect(0,chartHeight, bpmMaxSize, bpmMaxSize);
    // debugCtx.fillStyle="#0F0";
    // debugCtx.fillRect((bpmMaxSize - size)/2,chartHeight + (bpmMaxSize - size)/2, size, size);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.drupal.project.computing.exception;

/**
 * Some item is not found.
 */
public class DNotFoundException extends Exception {
    public DNotFoundException() {}

    public DNotFoundException(String s) {
        super(s);
    }
}


text:
<?php

namespace RBM\Datagrid\Data;

class Extractor
{
    /**
     * @param $source
     * @param $accessor
     * @return mixed
     */
    public static function extract($source, $accessor)
    {
        if (is_callable($accessor)) {
            return call_user_func($accessor, $source);
        }

        if (is_array($source) && isset($source[$accessor])) {
            return $source[$accessor];
        }

        if (is_object($source) && isset($source->{$accessor})) {
            return $source->{$accessor};
        }

        return "";
    }
}


text:
#include <inviwo/png/pngreader.h>

#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/raiiutils.h>

#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/datastructures/image/layerramprecision.h>

#include <png.h>

#include <sstream>

namespace inviwo {

PNGLayerReaderException::PNGLayerReaderException(const std::string& message,
                                                 ExceptionContext context)
    : DataReaderException(message, context) {}

PNGLayerReader::PNGLayerReader() : DataReaderType<Layer>() {
    addExtension(FileExtension("png", "Portable Network Graphics"));
}

PNGLayerReader* PNGLayerReader::clone() const { return new PNGLayerReader(*this); }

std::shared_ptr<inviwo::Layer> PNGLayerReader::readData(const std::string& filePath) {
    if (!filesystem::fileExists(filePath)) throw PNGLayerReaderException(filePath);

    auto* fp = fopen(filePath.c_str(), "rb");
    if (!fp) throw PNGLayerReaderException("Failed to open file for reading, " + filePath);
    util::OnScopeExit closeFile([fp]() { fclose(fp); });

    unsigned char header[8];
    const auto read = fread(header, 1, 8, fp);
    if (read != 8 || png_sig_cmp(header, 0, 8)) {
        throw PNGLayerReaderException("File is not a PNG, " + filePath);
    }

    auto png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!png_ptr) {
        throw PNGLayerReaderException("Internal PNG Error: Failed to create read struct");
    }
    util::OnScopeExit cleanup([&]() { png_destroy_read_struct(&png_ptr, NULL, NULL); });
    png_set_error_fn(
        png_ptr, NULL,
        [](png_structp, png_const_charp message) {
            throw PNGLayerReaderException(std::string("Error reading PNG: ") + message);
        },
        [](png_structp, png_const_charp message) { LogWarnCustom("PNGReader", message); });

    auto info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
        throw PNGLayerReaderException("Internal PNG Error: Failed to create info struct");
    }
    cleanup.setAction([&]() { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); });

    png_init_io(png_ptr, fp);
    png_set_sig_bytes(png_ptr, 8);
    png_read_info(png_ptr, info_ptr);

    auto width = png_get_image_width(png_ptr, info_ptr);
    auto height = png_get_image_height(png_ptr, info_ptr);
    auto color_type = png_get_color_type(png_ptr, info_ptr);
    auto bit_depth = png_get_bit_depth(png_ptr, info_ptr);

    SwizzleMask swizzleMask;
    size_t channels;
    switch (color_type) {
        case PNG_COLOR_TYPE_GRAY_ALPHA:
            swizzleMask = swizzlemasks::luminanceAlpha;
            channels = 2;
            break;
        case PNG_COLOR_TYPE_GRAY:
            swizzleMask = swizzlemasks::luminance;
            channels = 1;
            break;
        case PNG_COLOR_TYPE_PALETTE:
            [[fallthrough]];
        case PNG_COLOR_TYPE_RGB:
            swizzleMask = swizzlemasks::rgb;
            channels = 3;
            break;
        case PNG_COLOR_TYPE_RGBA:
            swizzleMask = swizzlemasks::rgba;
            channels = 4;
            break;
        default:
            throw PNGLayerReaderException("Unsupported color type");
            break;
    }

    if (color_type == PNG_COLOR_TYPE_PALETTE) {
        if (bit_depth <= 8) {
            png_set_expand(png_ptr);
            bit_depth = 8;
        } else {
            png_set_expand_16(png_ptr);
        }
    }
    if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
        png_set_expand_gray_1_2_4_to_8(png_ptr);
        bit_depth = 8;
    }
    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
        png_set_tRNS_to_alpha(png_ptr);
        channels++;
    }

    if (bit_depth == 16) {
        png_set_expand_16(png_ptr);
    }

    png_set_swap(png_ptr);

    png_set_interlace_handling(png_ptr);
    png_read_update_info(png_ptr, info_ptr);

    const DataFormatBase* df =
        DataFormatBase::get(inviwo::NumericType::UnsignedInteger, channels, bit_depth);

    auto layer = std::make_shared<Layer>(size2_t(width, height), df);

    layer->setSwizzleMask(swizzleMask);

    layer->getEditableRepresentation<LayerRAM>()->dispatch<void>([&](auto ram) {
        auto data = ram->getDataTyped();

        std::vector<png_bytep> rows(height);

        for (png_uint_32 rownum = 0; rownum < height; ++rownum) {
            // Need to flip images in Inviwo
            rows[height - rownum - 1] = (png_bytep)(data + rownum * width);
        }

        png_read_image(png_ptr, rows.data());
    });

    return layer;
}

}  // namespace inviwo


text:
package com.google.gapid.service.snippets;

import com.google.gapid.rpclib.binary.*;
import com.google.gapid.rpclib.schema.*;

import java.io.IOException;
import com.google.gapid.proto.service.snippets.SnippetsProtos.PartKind;

final class PartPath extends Pathway implements BinaryObject {

  @Override
  public String getSegmentString() {
    return "PartPath(" + myKind + ")";
  }

  //<<<Start:Java.ClassBody:1>>>
  private Pathway myBase;
  private PartKind myKind;

  // Constructs a default-initialized {@link PartPath}.
  public PartPath() {}

  public Pathway getBase() {
    return myBase;
  }

  public PartPath setBase(Pathway v) {
    myBase = v;
    return this;
  }

  public PartKind getKind() {
    return myKind;
  }

  public PartPath setKind(PartKind v) {
    myKind = v;
    return this;
  }

  @Override
  public BinaryClass klass() { return Klass.INSTANCE; }

  private static final Entity ENTITY = new Entity("snippets", "partPath", "", "");

  static {
    ENTITY.setFields(new Field[]{
      new Field("base", new Interface("Pathway")),
      new Field("kind", new Primitive("PartKind", Method.Int32)),
    });
    Namespace.register(Klass.INSTANCE);
  }
  public static void register() {}
  //<<<End:Java.ClassBody:1>>>

  public PartPath(Pathway base, PartKind kind) {
    myBase = base;
    myKind = kind;
  }

  @Override
  public Pathway base() {
    return getBase();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    PartPath partPath = (PartPath)o;

    if (myBase != null ? !myBase.equals(partPath.myBase) : partPath.myBase != null) return false;
    if (myKind != null ? !myKind.equals(partPath.myKind) : partPath.myKind != null) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = myBase != null ? myBase.hashCode() : 0;
    result = 31 * result + (myKind != null ? myKind.hashCode() : 0);
    return result;
  }

  public enum Klass implements BinaryClass {
    //<<<Start:Java.KlassBody:2>>>
    INSTANCE;

    @Override
    public Entity entity() { return ENTITY; }

    @Override
    public BinaryObject create() { return new PartPath(); }

    @Override
    public void encode(Encoder e, BinaryObject obj) throws IOException {
      PartPath o = (PartPath)obj;
      e.object(o.myBase == null ? null : o.myBase.unwrap());
      e.int32(o.myKind.getNumber());
    }

    @Override
    public void decode(Decoder d, BinaryObject obj) throws IOException {
      PartPath o = (PartPath)obj;
      o.myBase = Pathway.wrap(d.object());
      o.myKind = PartKind.valueOf(d.int32());
    }
    //<<<End:Java.KlassBody:2>>>
  }
}


text:
<?php

namespace Synful;

use Exception;
use Gestalt\Configuration;
use Spackle\Plugin;
use Synful\Data\Database;
use Synful\IO\IOFunctions;
use Synful\Framework\Route;
use Synful\Framework\Request;
use Synful\Framework\Response;
use Synful\Framework\RateLimit;
use Synful\Command\CommandLine;
use Synful\Serializers\URLSerializer;
use Synful\WebListener\WebListener;
use Synful\Framework\SynfulException;
use Synful\Serializers\HtmlSerializer;

use Spackle\TemplateParser as Template;

/**
 * Primary class for framework.
 */
class Synful
{
    /**
     * The config for the system pulled from './config/'.
     *
     * @var Configuration
     */
    public static $config;

    /**
     * All Routes registered in the system.
     *
     * @var array
     */
    public static $routes = [];

    /**
     * The result of the command line parsing.
     *
     * @var array
     */
    public static $command_results = [];

    /**
     * Initialize the Synful API instance.
     * @throws SynfulException
     * @throws Exception
     */
    public static function initialize()
    {
        // Load Global Functions
        self::loadGlobalFunctions();

        // Load the configuration into system
        if (! IOFunctions::loadConfig()) {
            exit();
        }

        // Enabele error reporting
        ini_set('display_errors', 0);
        ini_set('display_startup_errors', 0);
        error_reporting(E_ALL);
        if (sf_conf('system.display_errors')) {
            ini_set('display_errors', 1);
            ini_set('display_startup_errors', 1);
        }

        // Set error handler and shutdown hook
        set_error_handler('\\Synful\\IO\\IOFunctions::catchError', E_ALL);
        register_shutdown_function('\\Synful\\IO\\IOFunctions::onShutDown');

        // Check Cross Origin Resource Sharing
        if (sf_conf('system.cors_enabled')) {
            if (in_array('all', sf_conf('system.cors_domains'))) {
                header('Access-Control-Allow-Origin: *');
            } else {
                foreach (sf_conf('system.cors_domains') as $domain) {
                    if ($_SERVER['HTTP_ORIGIN'] == $domain) {
                        header('Access-Control-Allow-Origin: '.$domain);
                        break;
                    }
                }
            }
        }

        // Check global rate limiter
        if (sf_conf('rate.global')) {
            if (! RateLimit::global()->isUnlimited()) {
                if (RateLimit::global()->isLimited(self::getClientIP())) {
                    $response = (new SynfulException(500, 1028))->response;
                    sf_respond($response->code, $response->serialize());
                    exit;
                }
            }
        }

        // Load Template Plugins
        if (sf_conf('templating.enabled')) {
            self::loadTemplatePlugins();
        }

        // Initialize the Database Connections
        self::initializeDatabases();

        // Load routes
        self::loadRoutes();

        // Parse Command Line
        if (self::isCommandLineInterface()) {
            global $argv;
            $commandLine = new CommandLine();
            $results = $commandLine->parse($argv);

            // Output Results
            if ((array_key_exists('hc', $results) && ! $results['hc']) ||
                ! array_key_exists('hc', $results)) {
                if (array_key_exists('cl', $results)) {
                    $str = (sf_conf('system.color')) ? 'true' : 'false';
                    sf_note('CONFIG: Set console color to \''.$str.'\'.');
                }

                if (array_key_exists('o', $results)) {
                    sf_note('CONFIG: Set output level to \''.$results['o'].'\'.');
                }
            }

            if ((count($argv) < 2 || substr($argv[1], 0, 7) == '-output' ||
                 substr($argv[1], 0, 2) == '-o')) {
                $commandLine->printUsage();
                exit(3);
            }

            self::$command_results = $results;
        }

        // Initialize WebListener
        (new WebListener())->initialize();
    }

    /**
     * Initializes Database Connection.
     */
    public static function initializeDatabases()
    {
        if (sf_conf('databases.synful') != null) {
            Database::initialize(sf_conf('databases'));
        } else {
            trigger_error(
                'Missing Synful database definition. '.
                'Set \'synful\' in \'config/Databases.php\'. '.
                'Default Synful database is for storing API Keys.',
                E_USER_WARNING
            );
            exit();
        }
    }

    /**
     * Passes a JSON Request through the desired route, validates authentication
     * and request integrity and returns a response.
     *
     * @param Route $route
     * @param string $input
     * @param array $fields
     * @param string $ip
     *
     * @return Response
     * @throws SynfulException
     */
    public static function handleRequest(
        Route  $route,
        string $input,
        array  $fields,
        string $ip
    ) {
        // Check rate limit for Route
        if (sf_conf('rate.per_route')) {
            if (
                property_exists($route, 'rate_limit') &&
                is_array($route->rate_limit) &&
                isset($route->rate_limit['requests']) &&
                isset($route->rate_limit['per_seconds']) &&
                is_int($route->rate_limit['requests']) &&
                is_int($route->rate_limit['per_seconds'])
            ) {
                /** @noinspection PhpUndefinedFieldInspection */
                $rh_rl = new RateLimit(
                    'synful_route_'.$route->endpoint,
                    $route->rate_limit['requests'],
                    $route->rate_limit['per_seconds']
                );
                if (! $rh_rl->isUnlimited()) {
                    if ($rh_rl->isLimited(self::getClientIP())) {
                        $response = (new SynfulException(500, 1029))->response;
                        sf_respond($response->code, $response->serialize());
                        exit;
                    }
                }
            }
        }

        $serializer = sf_conf('system.serializer');
        $serializer = new $serializer;

        if (
            property_exists($route, 'serializer') &&
            class_exists($route->serializer)
        ) {
            $serializer = new $route->serializer;
        }

        if (! empty($input)) {
            try {
                if ($_SERVER['REQUEST_METHOD'] == 'GET') {
                    $data = (new URLSerializer)->deserialize($input);
                } else {
                    /** @noinspection PhpUndefinedMethodInspection */
                    $data = $serializer->deserialize($input);
                }
            } catch (Exception $e) {
                $response = (new SynfulException(500, -1, $e->getMessage()))->response;
                sf_respond($response->code, $response->serialize());
                exit;
            }
        } else {
            $data = [];
        }

        $request = new Request([
            'ip' => $ip,
            'headers' => sf_headers(),
            'data' => $data,
            'fields' => $fields,
            'method' => $_SERVER['REQUEST_METHOD'],
            'route' => $route,
        ]);

        try {
            $middlewares = [];

            if (! class_exists($route->controller)) {
                trigger_error(
                    'Unknown controller defined in route: Attempted '.
                    $route->controller,
                    E_USER_ERROR
                );
                exit;
            }

            if (! method_exists($route->controller, $route->call)) {
                trigger_error(
                    'Unknown controller call defined in route: Attempted '.
                    $route->controller.'@'.$route->call,
                    E_USER_ERROR
                );
                exit;
            }

            if (property_exists($route, 'middleware')) {
                if (! is_array($route->middleware)) {
                    throw new SynfulException(500, 1017);
                }

                $middlewares = $route->middleware;
            }

            foreach ($middlewares as $middleware) {
                $middleware = new $middleware;
                /** @noinspection PhpUndefinedMethodInspection */
                $middleware->before($request, $route);
            }

            $request->route = $route;
            $controller = $route->controller;
            $call = $route->call;
            $response = (new $controller)->{$call}($request);

            if (is_array($response)) {
                $response = sf_response(200, $response);
            }

            if (sf_conf('templating.enabled')) {
                if ($response instanceof Template)
                {
                    return sf_response(
                        200,
                        [
                            'html' => $response->parse()
                        ]
                    )->setSerializer(
                        new HtmlSerializer()
                    );
                }
            }

            if (! ($response instanceof Response)) {
                throw new SynfulException(500, 1016);
            }
        } catch (SynfulException $synfulException) {
            $response = $synfulException->response;
        }

        $response->request = $request;
        return $response;
    }

    /**
     * Load Template Plugins.
     * @throws Exception
     */
    public static function loadTemplatePlugins()
    {
        foreach (sf_conf('templating.plugins') as $plugin) {
            Plugin::add(
                new $plugin
            );
        }
    }

    /**
     * Retreives the client IP Address.
     *
     * @return string The ip of the remote client
     */
    public static function getClientIP()
    {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip_address = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip_address = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_X_FORWARDED')) {
            $ip_address = getenv('HTTP_X_FORWARDED');
        } elseif (getenv('HTTP_FORWARDED_FOR')) {
            $ip_address = getenv('HTTP_FORWARDED_FOR');
        } elseif (getenv('HTTP_FORWARDED')) {
            $ip_address = getenv('HTTP_FORWARDED');
        } elseif (getenv('REMOTE_ADDR')) {
            $ip_address = getenv('REMOTE_ADDR');
        } else {
            $ip_address = 'UNKNOWN';
        }

        return $ip_address;
    }

    /**
     * Check if this is a CLI instance.
     *
     * @return bool
     */
    public static function isCommandLineInterface()
    {
        return php_sapi_name() === 'cli';
    }

    /**
     * Retrieve the current version of the framework from git.
     *
     * @return string
     */
    public static function version()
    {
        if (! file_exists('.git')) {
            return '*no-git* (dirty)';
        }

        return preg_replace('/\s+/', '', shell_exec('git describe --tag'));
    }

    /**
     * Load all routes configured in routes.yaml.
     * @throws SynfulException
     */
    private static function loadRoutes()
    {
        $route_found = false;
        foreach (
            sf_conf('routes') as $path => $route_data
        ) {
            $route_found = true;
            self::$routes[$path] = Route::buildRoute($path, $route_data);
        }

        if (! $route_found) {
            trigger_error(
                'No routes have been configured. Check routes.yaml.',
                E_USER_ERROR
            );

            exit;
        }
    }

    /**
     * Automatically include all function libraries stored in Global Functions.
     * Note: This must use scandir as it is loaded before the configs.
     */
    public static function loadGlobalFunctions()
    {
        foreach (scandir('./src/Synful/Functions') as $func_lib) {
            if (substr($func_lib, 0, 1) !== '.') {
                /** @noinspection PhpIncludeInspection */
                include_once './src/Synful/Functions/'.$func_lib;
            }
        }

        foreach (scandir('./src/App/Functions') as $func_lib) {
            if (substr($func_lib, 0, 1) !== '.') {
                /** @noinspection PhpIncludeInspection */
                include_once './src/App/Functions/'.$func_lib;
            }
        }
    }
}


text:
// Copyright 2021 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 "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/signin_view_controller.h"
#include "chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"

class SigninViewControllerDelegateViewsBrowserTest
    : public InProcessBrowserTest {
 public:
  SigninViewControllerDelegateViewsBrowserTest() = default;
  ~SigninViewControllerDelegateViewsBrowserTest() override = default;

  // The delegate deletes itself when closed.
  SigninViewControllerDelegateViews* CreateDelegate(bool show_immediately) {
    return new SigninViewControllerDelegateViews(
        SigninViewControllerDelegateViews::CreateSyncConfirmationWebView(
            browser()),
        browser(), ui::MODAL_TYPE_WINDOW, /*wait_for_size=*/!show_immediately,
        false);
  }

  // Closes the dialog and checks that the web contents were not leaked.
  void CloseDialog(SigninViewControllerDelegateViews* delegate) {
    content::WebContentsDestroyedWatcher watcher(delegate->GetWebContents());
    delegate->CloseModalSignin();
    watcher.Wait();
    EXPECT_TRUE(watcher.IsDestroyed());
  }
};

// Opens and closes the dialog immediately. This is a basic test at the
// `SigninViewController` API level, but does not test all the edge cases.
// Regression test for https://crbug.com/1233030.
IN_PROC_BROWSER_TEST_F(SigninViewControllerDelegateViewsBrowserTest,
                       CloseImmediately) {
  SigninViewController* controller = browser()->signin_view_controller();
  controller->ShowModalSyncConfirmationDialog();
  content::WebContentsDestroyedWatcher watcher(
      controller->GetModalDialogWebContentsForTesting());
  // Close the dialog before it was displayed, this should not crash.
  controller->CloseModalSignin();
  // The web contents were destroyed.
  EXPECT_TRUE(watcher.IsDestroyed());
}

// Similar to SigninViewControllerDelegateViewsBrowserTest.CloseImmediately but
// specifically tests the case where the dialog is not shown at creation.
// Regression test for https://crbug.com/1233030.
IN_PROC_BROWSER_TEST_F(SigninViewControllerDelegateViewsBrowserTest,
                       CloseBeforeDisplay) {
  SigninViewControllerDelegateViews* delegate =
      CreateDelegate(/*show_immediately=*/false);
  // The dialog is not shown.
  EXPECT_FALSE(delegate->GetWidget());
  CloseDialog(delegate);
}

// Similar to SigninViewControllerDelegateViewsBrowserTest.CloseImmediately but
// specifically tests the case where the dialog is shown at creation.
// Regression test for https://crbug.com/1233030.
IN_PROC_BROWSER_TEST_F(SigninViewControllerDelegateViewsBrowserTest,
                       CloseAfterDisplay) {
  SigninViewControllerDelegateViews* delegate =
      CreateDelegate(/*show_immediately=*/true);
  // The dialog is shown.
  EXPECT_TRUE(delegate->GetWidget());
  CloseDialog(delegate);
}


text:
package org.jvnet.jaxb2_commons.plugin.elementwrapper;

import javax.xml.namespace.QName;

public class Customizations {

	public static String NAMESPACE_URI = "http://jaxb2-commons.dev.java.net/basic/elementWrapper";

	public static QName IGNORED_ELEMENT_NAME = new QName(NAMESPACE_URI,
			"ignored");

}


text:
namespace service_manager {

#if !defined(OS_NACL_NONSFI)
int SharedMemoryIPCSupport::MakeSharedMemorySegment(size_t length,
                                                    bool executable) {
  base::Pickle request;
  request.WriteInt(
      service_manager::SandboxLinux::METHOD_MAKE_SHARED_MEMORY_SEGMENT);
  request.WriteUInt32(length);
  request.WriteBool(executable);
  uint8_t reply_buf[10];
  int result_fd;
  ssize_t result = base::UnixDomainSocket::SendRecvMsg(
      GetSandboxFD(), reply_buf, sizeof(reply_buf), &result_fd, request);
  if (result == -1)
    return -1;
  return result_fd;
}
#endif

int GetSandboxFD() {
  return service_manager::kSandboxIPCChannel +
         base::GlobalDescriptors::kBaseDescriptor;
}

}  // namespace service_manager


text:
var template = require('lodash.template');

module.exports = function(tmpl, data){
  var fn = template(tmpl);

  var wrapped = function(o) {
    if (!o.file) throw new Error("Failed to provide the current file as 'file' to the template");
    return fn(o);
  };

  return (data ? wrapped(data) : wrapped);
};


text:
aicApp.config(['$stateProvider', '$urlRouterProvider',
	function($stateProvider, $urlRouterProvider) {
		$stateProvider
			.state('show', {
				url: '/show',
				abstract: true,
				views: {
					"content": {
						templateUrl: "templates/home.html"
					}
				}
			})
			.state('show.year', {
				url: "/list/:year",
				views: {
					"main" : {
						templateUrl: "templates/shows/index.html",
						controller: function($scope) {
							$scope.display = 'info';

							$scope.viewChange = function(type) {
								this.display = type;
							}
						}
					},
					"show-list@show.year" : {
						templateUrl: "templates/shows/table.partial.html",
						controller: function($log, $scope, shows) {
							$scope.shows = shows.items();
						},
						resolve: {
							shows: function($log, $stateParams, ShowFactory) {
								return ShowFactory.get({ year: $stateParams.year });
							}
						}
					}
				}
			})
			.state('show.details', {
				url: "/:showId",
				views: {
					"main" : {
						templateUrl: "templates/shows/details.html",
						controller: function($scope, show) {
							$scope.show = show;
						},
						resolve: {
							show: function(ShowFactory, $stateParams) {
								return ShowFactory.find($stateParams.showId);
							}
						}
					},
					"setlist@show.details" : {
						templateUrl: "templates/songs/setlist.partial.html",
						controller: function($scope, performances) {
							$scope.performances = performances.items();
						},
						resolve: {
							performances: function(SongPerformanceFactory, $stateParams) {
								return SongPerformanceFactory.get({ show: $stateParams.showId });
							}
						}
					}
				}
			});
		}]);


text:
<project>
	<modelVersion>4.0.0</modelVersion>
	<artifactId>chapter_004</artifactId>
	<version>2.0</version>
	<packaging>jar</packaging>
	<parent>
		<groupId>ru.istolbov</groupId>
		<artifactId>i_stolbov</artifactId>
		<version>2.0</version>
	</parent>
</project>


text:
package http_api

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	"github.com/julienschmidt/httprouter"
	"github.com/feixiao/nsq-0.3.7/internal/app"
)

// 函数对象定义:入参和出参都是APIHandler
// 功能是对函数的二次包装,就是在原来函数的基层上面增加处理
type Decorator func(APIHandler) APIHandler

// 函数对象定义
type APIHandler func(http.ResponseWriter, *http.Request, httprouter.Params) (interface{}, error)

type Err struct {
	Code int
	Text string
}

func (e Err) Error() string {
	return e.Text
}

func acceptVersion(req *http.Request) int {
	if req.Header.Get("accept") == "application/vnd.nsq; version=1.0" {
		return 1
	}

	return 0
}

//在f函数的基础之上增加了逻辑处理,返回新的函数
func PlainText(f APIHandler) APIHandler {
	return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
		code := 200
		data, err := f(w, req, ps)
		if err != nil {
			code = err.(Err).Code
			data = err.Error()
		}
		// 将错误码写入消息头,错误信息写入消息体
		switch d := data.(type) {
		case string:
			w.WriteHeader(code)
			io.WriteString(w, d)
		case []byte:
			w.WriteHeader(code)
			w.Write(d)
		default:
			panic(fmt.Sprintf("unknown response type %T", data))
		}
		return nil, nil
	}
}

func NegotiateVersion(f APIHandler) APIHandler {
	return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
		data, err := f(w, req, ps)
		if err != nil {
			if acceptVersion(req) == 1 {
				RespondV1(w, err.(Err).Code, err)
			} else {
				// this handler always returns 500 for backwards compatibility
				Respond(w, 500, err.Error(), nil)
			}
			return nil, nil
		}
		if acceptVersion(req) == 1 {
			RespondV1(w, 200, data)
		} else {
			Respond(w, 200, "OK", data)
		}
		return nil, nil
	}
}

func V1(f APIHandler) APIHandler {
	return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
		data, err := f(w, req, ps)
		if err != nil {
			RespondV1(w, err.(Err).Code, err)
			return nil, nil
		}
		RespondV1(w, 200, data)
		return nil, nil
	}
}

// 根据后面的三个参数生成回复并发送出去
func Respond(w http.ResponseWriter, statusCode int, statusTxt string, data interface{}) {
	var response []byte
	var err error

	// 根据数据类型的不同,创建不同的response对象
	switch data.(type) {
	case string:
		response = []byte(data.(string))
	case []byte:
		response = data.([]byte)
	default:
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		response, err = json.Marshal(struct {
			StatusCode int         `json:"status_code"`
			StatusTxt  string      `json:"status_txt"`
			Data       interface{} `json:"data"`
		}{
			statusCode,
			statusTxt,
			data,
		})
		if err != nil {
			response = []byte(fmt.Sprintf(`{"status_code":500, "status_txt":"%s", "data":null}`, err))
		}
	}

	w.WriteHeader(statusCode)
	w.Write(response)
}

func RespondV1(w http.ResponseWriter, code int, data interface{}) {
	var response []byte
	var err error
	var isJSON bool

	if code == 200 {
		switch data.(type) {
		case string:
			response = []byte(data.(string))
		case []byte:
			response = data.([]byte)
		case nil:
			response = []byte{}
		default:
			isJSON = true
			response, err = json.Marshal(data)
			if err != nil {
				code = 500
				data = err
			}
		}
	}

	if code != 200 {
		isJSON = true
		response = []byte(fmt.Sprintf(`{"message":"%s"}`, data))
	}

	if isJSON {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	}
	w.Header().Set("X-NSQ-Content-Type", "nsq; version=1.0")
	w.WriteHeader(code)
	w.Write(response)
}

// 以router.Handle("GET", "/ping", http_api.Decorate(s.pingHandler, log, http_api.PlainText))为例
func Decorate(f APIHandler, ds ...Decorator) httprouter.Handle {
	decorated := f
	// 将f函数封装到ds...内部,支持嵌套封装

	for _, decorate := range ds {
		decorated = decorate(decorated)
	}
	return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
		decorated(w, req, ps)
	}
}

// log输出
func Log(l app.Logger) Decorator {
	return func(f APIHandler) APIHandler {
		return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
			start := time.Now()
			response, err := f(w, req, ps)
			elapsed := time.Since(start)
			status := 200
			if e, ok := err.(Err); ok {
				status = e.Code
			}
			l.Output(2, fmt.Sprintf("%d %s %s (%s) %s",
				status, req.Method, req.URL.RequestURI(), req.RemoteAddr, elapsed))
			return response, err
		}
	}
}

func LogPanicHandler(l app.Logger) func(w http.ResponseWriter, req *http.Request, p interface{}) {
	return func(w http.ResponseWriter, req *http.Request, p interface{}) {
		l.Output(2, fmt.Sprintf("ERROR: panic in HTTP handler - %s", p))
		Decorate(func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
			return nil, Err{500, "INTERNAL_ERROR"}
		}, Log(l), V1)(w, req, nil)
	}
}

func LogNotFoundHandler(l app.Logger) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		Decorate(func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
			return nil, Err{404, "NOT_FOUND"}
		}, Log(l), V1)(w, req, nil)
	})
}

func LogMethodNotAllowedHandler(l app.Logger) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		Decorate(func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
			return nil, Err{405, "METHOD_NOT_ALLOWED"}
		}, Log(l), V1)(w, req, nil)
	})
}


text:
using NUnit.Framework;

namespace LanExchange.Plugin.Network
{
    [TestFixture]
    internal class SharePanelItemFactoryTest
    {
        [Test]
        public void TestFactory()
        {
            var factory = new ShareFactory();
            Assert.IsNotNull(factory.CreatePanelItem(null, null));
            Assert.IsNull(factory.CreateDefaultRoot());
        }
    }
}


text:
using System.Collections.Generic;
using WampSharp.Core.Message;

namespace WampSharp.Tests.Wampv2.IntegrationTests.MockBuilder
{
    public class MessageRecorder<TMessage> : IMessageRecorder<TMessage>
    {
        private readonly ICollection<WampMessage<TMessage>> mRecordedMessages =
            new List<WampMessage<TMessage>>();

        public MessageRecorder()
        {
        }

        public virtual void Record(WampMessage<TMessage> message)
        {
            mRecordedMessages.Add(message);
        }

        public IEnumerable<WampMessage<TMessage>> RecordedMessages
        {
            get { return mRecordedMessages; }
        }
    }
}


text:
namespace dart {

// Forward declarations.
class HandleVisitor;
class Heap;
class IsolateGroup;
class ObjectPointerVisitor;
class PageSpace;
template <bool sync>
class MarkingVisitorBase;
class Page;
class Thread;

// The class GCMarker is used to mark reachable old generation objects as part
// of the mark-sweep collection. The marking bit used is defined in RawObject.
// Instances have a lifetime that spans from the beginining of concurrent
// marking (or stop-the-world marking) until marking is complete. In particular,
// an instance may be created and destroyed on different threads if the isolate
// is exited during concurrent marking.
class GCMarker {
 public:
  GCMarker(IsolateGroup* isolate_group, Heap* heap);
  ~GCMarker();

  // Mark roots synchronously, then spawn tasks to concurrently drain the
  // marking queue. Only called when no marking or sweeping is in progress.
  // Marking must later be finalized by calling MarkObjects.
  void StartConcurrentMark(PageSpace* page_space);

  // Contribute to marking.
  void IncrementalMarkWithUnlimitedBudget(PageSpace* page_space);
  void IncrementalMarkWithSizeBudget(PageSpace* page_space, intptr_t size);
  void IncrementalMarkWithTimeBudget(PageSpace* page_space, int64_t deadline);

  // (Re)mark roots, drain the marking queue and finalize weak references.
  // Does not required StartConcurrentMark to have been previously called.
  void MarkObjects(PageSpace* page_space);

  intptr_t marked_words() const { return marked_bytes_ >> kWordSizeLog2; }
  intptr_t MarkedWordsPerMicro() const;

 private:
  void Prologue();
  void Epilogue();
  void ResetSlices();
  void IterateRoots(ObjectPointerVisitor* visitor);
  void IterateWeakRoots(Thread* thread);
  void ProcessWeakHandles(Thread* thread);
  void ProcessWeakTables(Thread* thread);
  void ProcessRememberedSet(Thread* thread);
  void ProcessObjectIdTable(Thread* thread);

  // Called by anyone: finalize and accumulate stats from 'visitor'.
  template <class MarkingVisitorType>
  void FinalizeResultsFrom(MarkingVisitorType* visitor);

  IsolateGroup* const isolate_group_;
  Heap* const heap_;
  MarkingStack marking_stack_;
  MarkingStack deferred_marking_stack_;
  GCLinkedLists global_list_;
  MarkingVisitorBase<true>** visitors_;

  Page* new_page_;
  Monitor root_slices_monitor_;
  RelaxedAtomic<intptr_t> root_slices_started_;
  intptr_t root_slices_finished_;
  intptr_t root_slices_count_;
  RelaxedAtomic<intptr_t> weak_slices_started_;

  uintptr_t marked_bytes_;
  int64_t marked_micros_;

  friend class ConcurrentMarkTask;
  friend class ParallelMarkTask;
  DISALLOW_IMPLICIT_CONSTRUCTORS(GCMarker);
};

}  // namespace dart

#endif  // RUNTIME_VM_HEAP_MARKER_H_


text:
__precompile__()

module Bio

include("IO.jl")
include("Ragel.jl")
include("StringFields.jl")
include("seq/Seq.jl")
include("intervals/Intervals.jl")
include("align/Align.jl")
include("util/tokenize.jl")
include("util/indexing.jl")
include("phylo/Phylo.jl")
include("structure/Structure.jl")
include("tools/Tools.jl")
include("util/windows.jl")
include("precompile.jl")

end  # module Bio


text:
<?php

namespace TorInfo\Support\Laravel;

use Illuminate\Support\ServiceProvider;
use TorInfo\Support\Laravel\Console\CacheTorIPs;

class TorInfoServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->publishes([__DIR__.'/config/torinfo.php' => config_path('torinfo.php')]);

        $this->registerCommands();
    }

    private function registerCommands()
    {
        // Clean command
        $this->app['command.tor.cache'] = $this->app->share(function ($app) {
            return new CacheTorIPs();
        });

        $this->commands(
            'command.tor.cache'
        );
    }
}


text:
package com.amazonaws.services.codegurureviewer.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum JobState {

    Completed("Completed"),
    Pending("Pending"),
    Failed("Failed"),
    Deleting("Deleting");

    private String value;

    private JobState(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return JobState corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static JobState fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (JobState enumEntry : JobState.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
* DONE: implement install() and handleInstall()
* DONE: implement getInformation()
* DONE: implement dispose()
* DONE: handle restore()
* DONE: Check Android app lifecycle, do we need specific code for cornercases?
* DONE: Fail fast for other product types than ENTTITLEMENT type.
* DONE: Refactor and cleanup.
* DONE: IN PROGRESSS Integrate publish.gradle to android project to be able to publish to a maven repo.
* DONE: test SNAPSHOT version
* DONE: integrate publish.gradle (support android library project).
* DONE: release new version.
* DONE: Describe com.badlogic.gdx.pay.PurchaseSystem#onAppRestarted on gdx-pay README

## Milestone 2
* Do agreed naming refactorings
* Verify purchase cancellation (is handled by Google Play, it no longer returns cancelled transactions?)
* Verify purchase authenticity (using the Google license Key)
* Handle purchase non-consumable product
* Support working with AndroidFragmentApplication
* DONE: Handle purchase consumable product
* Handle purchase subscription
* DONE: Set up CI (e.g. travis ci)
* update root README.md (update versions)
* Check for TODO's
* Move testdata (objectmothers) to a common place (gdx-pay-testdata?)
* Make ObjectMothers return Builder instances (if applicable).

## Refactorings to be discussed:

* Rename Information to Product (fits its name better)
* Should we rename Transaction to Purchase? At least matches better Google Play store naming.
* Rename com.badlogic.gdx.pay.Transaction.getIdentifier() to com.badlogic.gdx.pay.Transaction.getProductId();
* Rename gdx-pay submodule to gdx-pay-api
* create a -client and -server submodule
* gdx-pay-client: move classes in this project to com.badlogic.gdx.pay.client
* introduce gdx-pay-client-testdata module, put here in all ObjectMother classes.


text:
#define LOG_TAG "UsbDeviceJNI"

#include "utils/Log.h"

#include "jni.h"
#include "JNIHelp.h"
#include "core_jni_helpers.h"

#include <usbhost/usbhost.h>

using namespace android;

static jint
android_hardware_UsbDevice_get_device_id(JNIEnv *env, jobject clazz, jstring name)
{
    const char *nameStr = env->GetStringUTFChars(name, NULL);
    int id = usb_device_get_unique_id_from_name(nameStr);
    env->ReleaseStringUTFChars(name, nameStr);
    return id;
}

static jstring
android_hardware_UsbDevice_get_device_name(JNIEnv *env, jobject clazz, jint id)
{
    char* name = usb_device_get_name_from_unique_id(id);
    jstring result = env->NewStringUTF(name);
    free(name);
    return result;
}

static const JNINativeMethod method_table[] = {
    // static methods
    { "native_get_device_id", "(Ljava/lang/String;)I",
                                        (void*)android_hardware_UsbDevice_get_device_id },
    { "native_get_device_name", "(I)Ljava/lang/String;",
                                        (void*)android_hardware_UsbDevice_get_device_name },
};

int register_android_hardware_UsbDevice(JNIEnv *env)
{
    return RegisterMethodsOrDie(env, "android/hardware/usb/UsbDevice",
            method_table, NELEM(method_table));
}


text:
<?php

$php_value = phpversion();
if (version_compare($php_value, '5.3.0') == -1) {
    echo 'Currently installed PHP version (' . $php_value . ') is not supported. Minimal required PHP version is  5.3.0.';
    die();
}

define('AREA', 'A');
define('ACCOUNT_TYPE', 'admin');

try {
    require(dirname(__FILE__) . '/init.php');

    fn_dispatch();
} catch (Tygh\Exceptions\AException $e) {
    $e->output();
}


text:
package dungeonmart;

import dungeonmart.ref.v35.ClassesApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ClassesApplication.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class ClassesApplicationTests {

	@Test
	public void contextLoads() {
	}

}


text:
{% extends "bootstrap_responsive.html" %}
{% block body_content %}

    {% with messages = get_flashed_messages(with_categories = true) %}
    {% if messages %}
    {% for category, message in messages %}

        <button type="button" class="close" data-dismiss="alert">×</button>
        {{ message }}

    {% endfor %}
    {% endif %}
    {% endwith %}
    {% block content %}{% endblock %}

{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tausta">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:id="@+id/viestiKohde"
		android:textSize="24sp"
		android:textColor="#FFFFFF"/>

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textMultiLine"
                android:ems="10"
                android:id="@+id/tekstiruutu"
                android:layout_gravity="center_horizontal"
                android:hint="@string/viestiohje"/>

            <Button
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="@string/viesti_lahetys_nappi"
                android:id="@+id/viestiLahetysNappi"
                android:layout_gravity="center_horizontal"
                style="@style/Nappi" />
        </LinearLayout>

        </ScrollView>

</LinearLayout>


text:
WulinMaster.behaviors.disableSortingInitially = $.extend({}, WulinMaster.behaviors.BaseBehavior, {
  event: "onRendered",

  subscribe: function(target) {
    this.grid = target;
    var self = this;
    target[this.event].subscribe(function(){ self.handler(); });
  },

  unsubscribe: function() {

  },

  handler: function() {
    var columns = this.grid.getColumns();
    for(var i in columns) {
      // remember the column which is initially unsortable
      if(columns[i]['sortable'] === false) {
        columns[i]['origin_sortable'] = false;
      }
      columns[i]['sortable'] = false;
    }
  }

});

WulinMaster.BehaviorManager.register("disable_sorting_initially", WulinMaster.behaviors.disableSortingInitially);


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInitca8785c04f197d9ab91fffbccdb945c7::getLoader();


text:
package io.gravitee.repository.analytics.query;

import io.gravitee.repository.analytics.query.response.Response;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public interface Query<T extends Response> {

    Class<T> responseType();
}


text:
package com.hzn.easytransition;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hzn.lib.EasyTransition;

public class DetailActivity extends AppCompatActivity {

    private LinearLayout layoutAbout;
    private ImageView ivAdd;
    private boolean finishEnter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        // pre init some views and data
        initViews();

        // if re-initialized, do not play any anim
        long transitionDuration = 800;
        if (null != savedInstanceState)
            transitionDuration = 0;

        // transition enter
        finishEnter = false;
        EasyTransition.enter(
                this,
                transitionDuration,
                new DecelerateInterpolator(),
                new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        // init other views after transition anim
                        finishEnter = true;
                        initOtherViews();
                    }
                });
    }

    private void initViews() {
        TextView tvName = (TextView) findViewById(R.id.tv_name);
        tvName.setText(getIntent().getStringExtra("name"));
    }

    private void initOtherViews() {
        layoutAbout = (LinearLayout) findViewById(R.id.layout_about);
        layoutAbout.setVisibility(View.VISIBLE);
        layoutAbout.setAlpha(0);
        layoutAbout.setTranslationY(-30);
        layoutAbout.animate()
                .setDuration(300)
                .alpha(1)
                .translationY(0);

        ivAdd = (ImageView) findViewById(R.id.iv_add);
        ivAdd.setVisibility(View.VISIBLE);
        ivAdd.setScaleX(0);
        ivAdd.setScaleY(0);
        ivAdd.animate()
                .setDuration(200)
                .scaleX(1)
                .scaleY(1);
    }

    @Override
    public void onBackPressed() {
        if (finishEnter) {
            finishEnter = false;
            startBackAnim();
        }
    }

    private void startBackAnim() {
        // forbidden scrolling
        ScrollView sv = (ScrollView) findViewById(R.id.sv);
        sv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        // start our anim
        ivAdd.animate()
                .setDuration(200)
                .scaleX(0)
                .scaleY(0);

        layoutAbout.animate()
                .setDuration(300)
                .alpha(0)
                .translationY(-30)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        // transition exit after our anim
                        EasyTransition.exit(DetailActivity.this, 800, new DecelerateInterpolator());
                    }
                });
    }
}


text:
<?php
namespace Llama\Modules\Commands;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Illuminate\Console\Command;
use Llama\Modules\Module;

class MigrateRollbackCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:migrate-rollback';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rollback the module migrations.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $module = $this->argument('module');

        if (! empty($module)) {
            return $this->rollback($this->laravel['modules']->findOrFail($module));
        }

        foreach ($this->laravel['modules']->getOrdered() as $module) {
            $this->line('Running for module: <info>' . $module->getName() . '</info>');

            $this->rollback($module);
        }
    }

    /**
     * Rollback migration from the specified module.
     *
     * @param Module $module
     */
    public function rollback(Module $module)
    {
        $this->call('migrate:rollback', [
            '--database' => $this->option('database'),
            '--path' => str_replace(base_path(), '', $module->getMigrationPath()),
            '--step' => $this->option('step'),
            '--pretend' => $this->option('pretend'),
            '--force' => $this->option('force')
        ]);
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            [
                'module',
                InputArgument::OPTIONAL,
                'The name of module will be used.'
            ]
        ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            [
                'database',
                null,
                InputOption::VALUE_OPTIONAL,
                'The database connection to use.'
            ],
            [
                'force',
                null,
                InputOption::VALUE_NONE,
                'Force the operation to run when in production.'
            ],

            [
                'pretend',
                null,
                InputOption::VALUE_NONE,
                'Dump the SQL queries that would be run.'
            ],

            [
                'step',
                null,
                InputOption::VALUE_OPTIONAL,
                'The number of migrations to be reverted.'
            ]
        ];
    }
}


text:
<TITLE>Review for Noi vivi (1942)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Noi vivi (1942)

reviewed by
Mark R. Leeper

                                WE THE LIVING
                       A film review by Mark R. Leeper
                        Copyright 1988 Mark R. Leeper

          Capsule review:  The history of this film is more
     intriguing than its plot.  A melodrama based, without
     permission, on an Ayn Rand novel was first supported, then
     banned by the government of Il Duce.  Set in post-
     Revolutionary Russia, the film tells the story of young Kira
     and the men in her life.  Not much historic scope but a
     lavish film.  Rating: +1.

     In 1942 Italy was at war with the Allies in more ways than one.
Without permission or legal rights they thumbed their noses held by the
enemy.  They started writing their own FLASH GORDON comic strips, hiring for
the task two young unknown Italian cartoonists, one of whom was Federico
Fellini, who later was to have some association with the film industry.
Also without permission, and certainly in direct opposition to her
philosophy, the state appropriated film rights to Ayn Rand's semi-
autobiographical first novel, WE THE LIVING.  Goffredo Alessandrini adapted
the anti-Communist novel into a film.  NOI VIVI (WE THE LIVING) played for
about five months before a reportedly furious Mussolini decided the film was
an argument against any totalitarian government and had the film banned.  In
1968, after much effort, lawyers for Ayn Rand found a copy of the film in a
vault outside Rome.  Ms.~Rand, not happy with the original film, re-edited
it and redubbed parts.  WE THE LIVING is now having its first United States
release.

     It would be nice to report, as is usually the case when an old "lost
film" is discovered, that it is a wonderful classic that we are all
culturally poorer for for having been deprived of all these years.  It may
have been true of Gance's NAPOLEON; it is patently not true of WE THE
LIVING.  The re-released film is only a moderately enjoyable melodrama made
with some of the faulty conventions but also some of the cinematic artistry
of the period.  That means it's no CITIZEN KANE, but it stacks up really
well next to ALIEN NATION.

     In post-Revolutionary Russia, Kira's family of ex-aristocrats returns
to the city they will always call Petrograd and take up residence in a few
rooms of what used to be their house.  Young Kira (played by Alida Valli)
has no respect for anyone who works for the new Soviet government.  She
rebuffs the advances of her cousin Victor, a loyal Party member, and instead
has a monthly rendezvous with Leo (played by Rossano Brazzi), the son of a
famous counter-revolutionary.  The police are looking for Leo and Kira is
nearly pulled into trouble with him.  Yet unbidden, people in high places
seem to intervene in her behalf.  One of Kira's unbidden saviors is Andrei
(played by Fosco Giachetti), an inspector for the GPU security police, who
seems anxious to reunite the two lovers.  This is the beginning of a story
that spans several years in the lives of Kira, Leo, and Andrei, a story
involving politics and crime, love and death.

     WE THE LIVING was made at a time when great care was taken to compose
scenes visually.  A vast number of Soviet propaganda posters were somehow
obtained (or perhaps invented) for the filming.  Yet not everything makes
sense as it was filmed.  One wonders how in an economy of shortages, Kira is
always able to wear lipstick and eye makeup flawlessly applied.  In one
scene the characters come into a warm building from the snow, yet the snow
on their shoulders refuses to melt.

     Ayn Rand's stories always seem to be overblown melodramas, having
larger-than-life characters who refuse to capitulate to the demands of
society.  And the stories usually culminate in the hero making an
impassioned speech of Rand's personal philosophy that society tries to tear
down the individual as a sort of dubious benefit to an undeserving
multitude.  This version of WE THE LIVING is no exception, however the
speech seems to make little sense in the context of the film.  And the
speech scene is quite noticeably one of those scenes that were re-dubbed.
One wonders if in the original the speech was so noticeable a non sequitur.

     WE THE LIVING is diverting fare, but falls well short of being a
classic.  Still, it is valuable as an artifact of World War II history as
well as film history and a reminder of what films used to be.  Rate it a +1
on the -4 to +4 scale.

                                        Mark R. Leeper
                                        att!mtgzz!leeper
                                        leeper%mtgzz@att.arpa

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
:Author:
	Zain Memon

###################
jQuery in the Admin
###################

`Changeset r12297`_ dropped a bomb on everyone: a new file in the
``django/contrib/admin/media/js`` directory called ``jquery.js``. This change
ushers in a new era for the Django admin; an era of fancy new features, pretty
widgets, and better usability.

The case for jQuery
===================

Despite being discussed in the past, integration of jQuery into the admin
wasn't on the map until the GSoC `admin-ui proposal`_ this summer, which
suggested some UI-heavy features that would be difficult without the use of a
framework.

It's easy to see the need for a Javascript framework in the admin. Raw
Javascript in any decently sized project slowly approaches the size and
complexity of a framework. That process becomes a minefield of dealing with
cross-browser issues, workarounds, and normalization; a framework
short-circuits that pain and lets developers focus on building cool stuff. We
live in the future, and there's just no good reason to write Javascript
straight to the DOM APIs when we could be adding useful functionality (with
fewer bugs) instead.

It's also easy to see why jQuery is the framework of choice: jQuery has
`soundly won`_ the JS framework wars. Almost 30% of the sites tracked by
`builtwith.com`_ use jQuery. Picking something else would mean fewer
knowledgeable devs, less available code, and a smaller community of support.

This doesn't mean Django endorses jQuery
========================================

There's some concern in the community that the inclusion of jQuery appears to
be an endorsement of one framework over another -- that's not the case at all.

Django proper remains blissfully agnostic to toolkit choice. The admin is an
optional app designed for end-users, not other developers. Data entry clerks
are unaffected by the admin's tooling, and developers are not constrained by
it.

If you're modifying the Django admin, jQuery stays out of your way. For
example, the admin uses ``jQuery.noConflict()`` to make sure the ``$`` variable
isn't polluting your namespace, so you can use Prototype's ``$()`` in your own
widgets without any conflicts. Also, jQuery is only loaded on pages with
widgets that require it.

Your apps can still use whatever makes sense for you. For the Django admin,
including a well-tested, proven framework makes more sense than to add even
more undocumented, unvetted spaghetti Javascript.

This does mean Django's admin will grow much faster
===================================================

The front-end of the admin has stagnated a bit. A perfect storm is brewing for
some kick-ass new front-end features: jQuery, a newly (re)appointed `design
czar`_, and a general focus in the community on better usability.

Django 1.2 mainly focused on laying the groundwork for future admin-ui
improvements and most visible changes won't be felt until Django 1.3 and later.
However, a few things did make it in.

New features
============

One of the first jQuery features in the admin is the dynamic addition of new
inlines. For a demo of this functionality, check out this screencast:

.. raw:: html

	<video width="624" height="464" controls="controls" autobuffer="autobuffer">
		<source src="http://djangoadvent.s3.amazonaws.com/advent/002/inlines_624x464.mp4" type='video/mp4; codecs="avc1.42E01E"'>
		<source src="http://djangoadvent.s3.amazonaws.com/advent/002/inlines_624x464.ogv" type='video/ogg; codecs="theora"'>
		<object width="624" height="488" type="application/x-shockwave-flash" data="http://djangoadvent.s3.amazonaws.com/advent/002/player.swf?image=http://djangoadvent.s3.amazonaws.com/advent/002/inlines_poster.png&file=http://djangoadvent.s3.amazonaws.com/advent/002/inlines_624x464.mp4">
			<param name="movie" value="http://djangoadvent.s3.amazonaws.com/advent/002/player.swf?image=http://djangoadvent.s3.amazonaws.com/advent/002/inlines_poster.png&file=http://djangoadvent.s3.amazonaws.com/advent/002/inlines_624x464.mp4" />

		</object>
	</video>

	Download Video: MP4 | Theora (Ogg)

A lot of implemented features missed the cut for Django 1.2, like drag-and-drop
reordering of inlines for models with an ordering field, and an autocomplete
widget for Foreign Key and M2M relations to be used instead of the select
drop-down (or raw_id_fields). Those features (and others) will most likely land
in Django 1.3.

These are exciting times for the users of the Django admin. There's already
some admin hotness in 1.2, and it's only going to get better by the time 1.3
ships. jQuery it up!

.. _Changeset r12297: http://code.djangoproject.com/changeset/12297
.. _soundly won: http://www.google.com/trends?q=jquery,+mootools,+dojo,+prototype+js&ctab=0&geo=all&date=all&sort=0
.. _builtwith.com: http://trends.builtwith.com/javascript/JQuery
.. _`design czar`: http://groups.google.com/group/django-developers/browse_thread/thread/18bca037f10769e9/50fc65fe85746197
.. _`admin-ui proposal`: http://groups.google.com/group/django-developers/browse_thread/thread/1edf77c9c8b1101d/4ecda5e4c982c7e1


text:
'use strict'
module.exports = function closeServer (hub) {
  const server = hub.downstream
  const instances = hub.instances
  closeConnections(hub)
  for (let i = 0, len = instances && instances.length; i < len; i++) {
    closeConnections(instances[i])
  }
  server.httpServer.close()
}

function closeConnections (hub) {
  const clients = hub.clients
  const id = hub.id
  // 1000x double check this
  clients.each((client) => {
    if (client.upstream && client.upstream.compute() === id) {
      client.socket.close()
    }
  })
}


text:
const gulp = require('gulp')

module.exports = function (config) {
  gulp.task('default', function (cb) {
    const runSequence = require('run-sequence')
    global.watchMode = true
    runSequence(
      'clean',
      ['copy', 'stylus'],
      ['watch'],
      cb
    )
  })
}


text:
from setuptools import setup

# "import" __version__
__version__ = 'unknown'
for line in open('src/nbsphinx.py'):
    if line.startswith('__version__'):
        exec(line)
        break

setup(
    name='nbsphinx',
    version=__version__,
    package_dir={'': 'src'},
    py_modules=['nbsphinx'],
    python_requires='>=3.6',
    install_requires=[
        'docutils',
        'jinja2',
        'nbconvert!=5.4',
        'traitlets>=5',
        'nbformat',
        'sphinx>=1.8',
    ],
    author='Matthias Geier',
    author_email='Matthias.Geier@gmail.com',
    description='Jupyter Notebook Tools for Sphinx',
    long_description=open('README.rst').read(),
    license='MIT',
    keywords='Sphinx Jupyter notebook'.split(),
    url='https://nbsphinx.readthedocs.io/',
    project_urls={
        'Documentation': 'https://nbsphinx.readthedocs.io/',
        'Source Code': 'https://github.com/spatialaudio/nbsphinx/',
        'Bug Tracker': 'https://github.com/spatialaudio/nbsphinx/issues/',
    },
    platforms='any',
    classifiers=[
        'Framework :: Sphinx',
        'Framework :: Sphinx :: Extension',
        'Framework :: Jupyter',
        'Intended Audience :: Education',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Topic :: Documentation :: Sphinx',
    ],
    zip_safe=True,
)


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>InfoSec briefly</title>
    <meta name="description" content="Information Security news and how-tos in 200 words or less" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="//www.infosecbriefly.com/themes/Casper/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//www.infosecbriefly.com/themes/Casper/assets/css/screen.css?v=1.0.0" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="http://www.infosecbriefly.com" />
    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="InfoSec briefly" href="http://www.infosecbriefly.com/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

InfoSec briefly

Information Security news and how-tos in 200 words or less

    Scroll Down

        Page 1 of 1

What is: The Angler Exploit Kit

The Angler exploit kit is a pre-packaged toolkit sold on the dark web that criminals use to distribute malware. With an exploit kit, would-be attackers no »

             on Angler,  Exploit Kit,  Angler Exploit Kit,  dark web,  Ransomeware,  Torrentlocker,  CryptoWall,  What is Angler,  What is an exploit kit,  drive-by download
            <time class="post-date" datetime="2016-04-25">25 April 2016</time>

MIT launches experimental $10,000 bug bounty programme for students

The Massachusetts Institute of Technology hopes to up its online security and "foster a community for students to research research and test the limits of cyber »

             on MIT,  bug bounty,  Massachusetts Institute of Technology
            <time class="post-date" datetime="2016-04-23">23 April 2016</time>

How to: enable IPv6 routing on a Cisco router

Before you can get started with OSPFv3 (Open Shortest Path First), the IPv6 router must be configured to forward traffic. This is done with the ipv6 »

             on IPv6 routing,  IPv6,  OSPFv3,  ipv6 unicast-routing,  Cisco,  CCNA
            <time class="post-date" datetime="2016-04-09">09 April 2016</time>

Prankster bypasses Steam's quality control to release game where you watch paint dry

On Sunday an odd title appeared on Steam: 'Watch Paint Dry', the game where you, well, watch paint dry. Unlike other joke games about goats and »

             on Valve,  Steam,  Watch paint dry,  no time wasters fee,  games,  indie games
            <time class="post-date" datetime="2016-03-29">29 March 2016</time>

Hospitals hit by 'Locky' ransomware

The Methodist Hospital in Henderson, Kentucky, had to declare an internal state of emergency on Tuesday after the ransomeware 'Locky' got onto its network through an »

             on ransomeware,  locky,  Brian Krebs,  Bitcoins,  spam
            <time class="post-date" datetime="2016-03-24">24 March 2016</time>

Contact us

Got a tip? You can reach us on contact@infosecbriefly.com Find us on Facebook or Twitter. We’ve also got an RSS-feed. »

             on contact us,  tips,  Facebook,  Twitter
            <time class="post-date" datetime="2016-03-24">24 March 2016</time>

Uber launches $10,000 bug bounty program

Uber just launched a bug bountry program that will pay up to $10,000 for critical vulnerabilities that could affect their users. They are mainly interested »

             on Uber,  bug bounty,  bug bounties,  bugs,  vulnerabilities
            <time class="post-date" datetime="2016-03-23">23 March 2016</time>

Paris terrorists used burner phones to evade detection

The three teams behind November’s terror attacks in Paris relied on prepaid burner phones to dodge unwanted attention from the intelligence agencies. "They used »

             on Paris,  terrorism,  encryption,  Bataclan,  Salah Abdeslam,  burner phones,  news
            <time class="post-date" datetime="2016-03-23">23 March 2016</time>

Subgraph - a featherweight OS for non-technical users

The Debian-based Subgraph OS, first released in 2015, is a featherweight open-source solution that comes with all the security and privacy options pre-configured. Key features: Full »

             on Subgraph,  linux,  OS,  operating system,  Debian,  news
            <time class="post-date" datetime="2016-03-22">22 March 2016</time>

How to: set Message Of The Day (MOTD) on a Cisco router

In Global Configuraton Mode, type: banner motd the #message of the day# The first character after motd becomes the delimiter, which we use to set the »

             on Cisco,  motd,  message of the day,  CCNA
            <time class="post-date" datetime="2016-03-21">21 March 2016</time>

        Page 1 of 1

InfoSec briefly © 2016

Proudly published with HubPress


text:
MIN_NUM = float('-inf')
MAX_NUM = float('inf')

class PID(object):
    def __init__(self, kp, ki, kd, mn=MIN_NUM, mx=MAX_NUM):
        self.kp = kp
        self.ki = ki
        self.kd = kd
        self.min = mn
        self.max = mx

        self.int_val = self.last_error = 0.

    def reset(self):
        self.int_val = 0.0

    def step(self, error, sample_time):

        integral = self.int_val + error * sample_time;
        derivative = (error - self.last_error) / sample_time;

        val = self.kp * error + self.ki * integral + self.kd * derivative;

        if val > self.max:
            val = self.max
        elif val < self.min:
            val = self.min
        else:
            self.int_val = integral
        self.last_error = error

        return val


text:
namespace System {

class Dispatcher;

class Event {
public:
  Event();
  explicit Event(Dispatcher& dispatcher);
  Event(const Event&) = delete;
  Event(Event&& other);
  ~Event();
  Event& operator=(const Event&) = delete;
  Event& operator=(Event&& other);
  bool get() const;
  void clear();
  void set();
  void wait();

private:
  Dispatcher* dispatcher;
  bool state;
  void* first;
  void* last;
};

}


text:
package internal

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"time"

	"github.com/cloudfoundry-incubator/cf-test-helpers/generator"
	"github.com/cloudfoundry-incubator/cf-test-helpers/internal"
	"github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

type TestUser struct {
	username       string
	password       string
	cmdStarter     internal.Starter
	timeout        time.Duration
	shouldKeepUser bool
}

type UserConfig interface {
	GetUseExistingUser() bool
	GetExistingUser() string
	GetExistingUserPassword() string
	GetShouldKeepUser() bool
	GetConfigurableTestPassword() string
}

type userConfig interface {
	UserConfig

	GetScaledTimeout(time.Duration) time.Duration
	GetNamePrefix() string
}

type AdminUserConfig interface {
	GetAdminUser() string
	GetAdminPassword() string
}

type ClientConfig interface {
	GetExistingClient() string
	GetExistingClientSecret() string
}

type AdminClientConfig interface {
	GetAdminClient() string
	GetAdminClientSecret() string
}

func NewTestUser(config userConfig, cmdStarter internal.Starter) *TestUser {
	var regUser, regUserPass string

	if config.GetUseExistingUser() {
		regUser = config.GetExistingUser()
		regUserPass = config.GetExistingUserPassword()
	} else {
		regUser = generator.PrefixedRandomName(config.GetNamePrefix(), "USER")
		regUserPass = generatePassword()
	}

	if config.GetConfigurableTestPassword() != "" {
		regUserPass = config.GetConfigurableTestPassword()
	}

	return &TestUser{
		username:       regUser,
		password:       regUserPass,
		cmdStarter:     cmdStarter,
		timeout:        config.GetScaledTimeout(1 * time.Minute),
		shouldKeepUser: config.GetShouldKeepUser(),
	}
}

func NewAdminUser(config AdminUserConfig, cmdStarter internal.Starter) *TestUser {
	return &TestUser{
		username:   config.GetAdminUser(),
		password:   config.GetAdminPassword(),
		cmdStarter: cmdStarter,
	}
}

func NewAdminClient(config AdminClientConfig, cmdStarter internal.Starter) *TestUser {
	return &TestUser{
		username:   config.GetAdminClient(),
		password:   config.GetAdminClientSecret(),
		cmdStarter: cmdStarter,
	}
}

func NewTestClient(config ClientConfig, cmdStarter internal.Starter) *TestUser {
	return &TestUser{
		username:   config.GetExistingClient(),
		password:   config.GetExistingClientSecret(),
		cmdStarter: cmdStarter,
	}
}

func (user *TestUser) Create() {
	redactor := internal.NewRedactor(user.password)
	redactingReporter := internal.NewRedactingReporter(ginkgo.GinkgoWriter, redactor)

	session := internal.CfWithCustomReporter(user.cmdStarter, redactingReporter, "create-user", user.username, user.password)
	EventuallyWithOffset(1, session, user.timeout).Should(Exit())

	if session.ExitCode() != 0 {
		ExpectWithOffset(1, combineOutputAndRedact(session, redactor)).Should(Say("scim_resource_already_exists"))
	}
}

func (user *TestUser) Destroy() {
	session := internal.Cf(user.cmdStarter, "delete-user", "-f", user.username)
	EventuallyWithOffset(1, session, user.timeout).Should(Exit(0))
}

func (user *TestUser) Username() string {
	return user.username
}

func (user *TestUser) Password() string {
	return user.password
}

func (user *TestUser) ShouldRemain() bool {
	return user.shouldKeepUser
}

func combineOutputAndRedact(session *Session, redactor internal.Redactor) *Buffer {
	stdout := redactor.Redact(string(session.Out.Contents()))
	stderr := redactor.Redact(string(session.Err.Contents()))

	return BufferWithBytes(append([]byte(stdout), []byte(stderr)...))
}

// The key thing that makes a password secure is the _entropy_ that comes from a
// generator of true random numbers.  But many password rules require a mixure
// of cases, numbers and special characters.  Here we meet these rules by starting
// the password with the required upper/lower case, number and special.  Then we make
// it secure by adding truly random characters.
func generatePassword() string {
	const randomBytesLength = 16
	encoding := base64.RawURLEncoding

	randomBytes := make([]byte, encoding.DecodedLen(randomBytesLength))
	_, err := rand.Read(randomBytes)
	if err != nil {
		panic(fmt.Errorf("Could not generate random password: %s", err.Error()))
	}

	return "A0a!" + encoding.EncodeToString(randomBytes)
}


text:
#ifndef DISABLE_UNCOMMON

#include "ConvexShape.h"
#include "GjkConvexCast.h"

GjkConvexCast::GjkConvexCast(ConvexShape^ convexA, ConvexShape^ convexB, SimplexSolverInterface^ simplexSolver)
	: ConvexCast(new btGjkConvexCast((btConvexShape*)convexA->_native, (btConvexShape*)convexB->_native,
		simplexSolver->_native))
{
}

#endif


text:
from .column import MongoModel, String, Integer, \
    Column, or_, and_, ValidationError, Boolean, ObjectId, \
    Date
from .relationships import belongs_to, has_and_belongs_to
from .base import connections


text:
package org.apache.camel.spring.boot;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import javax.annotation.PreDestroy;

import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.main.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class CamelSpringBootApplicationController {

    private static final Logger LOG = LoggerFactory.getLogger(CamelSpringBootApplicationController.class);

    private final Main main;
    private final CountDownLatch latch = new CountDownLatch(1);

    public CamelSpringBootApplicationController(final ApplicationContext applicationContext, final CamelContext camelContext) {
        this.main = new Main() {
            @Override
            protected ProducerTemplate findOrCreateCamelTemplate() {
                return applicationContext.getBean(ProducerTemplate.class);
            }

            @Override
            protected Map<String, CamelContext> getCamelContextMap() {
                return Collections.singletonMap("camelContext", camelContext);
            }

            @Override
            protected void doStop() throws Exception {
                LOG.debug("Controller is shutting down CamelContext");
                try {
                    super.doStop();
                } finally {
                    // should use the latch on this instance
                    CamelSpringBootApplicationController.this.latch.countDown();
                }
            }
        };
    }

    /**
     * Runs the application and blocks the main thread and shutdown Camel graceful when the JVM is stopping.
     */
    public void run() {
        LOG.debug("Controller is starting and waiting for Spring-Boot to stop or JVM to terminate");
        try {
            main.run();
            // keep the daemon thread running
            LOG.debug("Waiting for CamelContext to complete shutdown");
            latch.await();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        LOG.debug("CamelContext shutdown complete.");
    }

    /**
     * @deprecated use {@link #run()}
     */
    @Deprecated
    public void blockMainThread() {
        run();
    }

    @PreDestroy
    private void destroy() {
        main.completed();
    }

}


text:
  Follow up for N-Queens problem.

  Now, instead outputting board configurations, return the total number of distinct solutions.

## Source:
[Leetcode](https://leetcode.com/problems/n-queens-ii/)


text:
package org.ovirt.engine.api.restapi.resource;

import static org.ovirt.engine.api.restapi.resource.BackendIscsiBondsResource.SUB_COLLECTIONS;

import org.ovirt.engine.api.model.IscsiBond;
import org.ovirt.engine.api.resource.IscsiBondResource;
import org.ovirt.engine.api.resource.NetworksResource;
import org.ovirt.engine.api.resource.StorageServerConnectionsResource;
import org.ovirt.engine.core.common.action.EditIscsiBondParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;

public class BackendIscsiBondResource extends AbstractBackendActionableResource<IscsiBond, org.ovirt.engine.core.common.businessentities.IscsiBond>
        implements IscsiBondResource {

    public  BackendIscsiBondResource(String id) {
        super(id, IscsiBond.class, org.ovirt.engine.core.common.businessentities.IscsiBond.class, SUB_COLLECTIONS);
    }

    @Override
    public IscsiBond get() {
        return performGet(VdcQueryType.GetIscsiBondById, new IdQueryParameters(guid));
    }

    @Override
    public IscsiBond update(IscsiBond iscsiBond) {
        return performUpdate(iscsiBond,
                new QueryIdResolver<Guid>(VdcQueryType.GetIscsiBondById, IdQueryParameters.class),
                VdcActionType.EditIscsiBond,
                new ParametersProvider<IscsiBond, org.ovirt.engine.core.common.businessentities.IscsiBond>() {
                    @Override
                    public VdcActionParametersBase getParameters(IscsiBond incoming, org.ovirt.engine.core.common.businessentities.IscsiBond entity) {
                        return new EditIscsiBondParameters(
                                getMapper(modelType, org.ovirt.engine.core.common.businessentities.IscsiBond.class).map(incoming, entity)
                        );
                    }
                });
    }

    @Override
    public NetworksResource getNetworksResource() {
        return inject(new BackendIscsiBondNetworksResource(id));
    }

    @Override
    public StorageServerConnectionsResource getStorageServerConnectionsResource() {
        return inject(new BackendIscsiBondStorageConnectionsResource(id));
    }

    @Override
    protected IscsiBond doPopulate(IscsiBond model, org.ovirt.engine.core.common.businessentities.IscsiBond entity) {
        return model;
    }
}


text:
package io.cloudslang.lang.runtime.steps;

import com.hp.oo.sdk.content.annotations.Param;
import io.cloudslang.lang.entities.AsyncLoopStatement;
import io.cloudslang.lang.entities.ResultNavigation;
import io.cloudslang.lang.entities.ScoreLangConstants;
import io.cloudslang.lang.entities.bindings.Output;
import io.cloudslang.lang.runtime.RuntimeConstants;
import io.cloudslang.lang.runtime.bindings.AsyncLoopBinding;
import io.cloudslang.lang.runtime.bindings.LoopsBinding;
import io.cloudslang.lang.runtime.bindings.OutputsBinding;
import io.cloudslang.lang.runtime.env.*;
import io.cloudslang.lang.runtime.events.LanguageEventData;
import org.apache.commons.lang.SerializationUtils;
import org.apache.log4j.Logger;
import io.cloudslang.score.api.EndBranchDataContainer;
import io.cloudslang.score.api.execution.ExecutionParametersConsts;
import io.cloudslang.score.lang.ExecutionRuntimeServices;
import org.python.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.apache.commons.lang3.tuple.Pair;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.cloudslang.score.api.execution.ExecutionParametersConsts.EXECUTION_RUNTIME_SERVICES;

/**
 * Date: 3/25/2015
 *
 * @author Bonczidai Levente
 */
@Component
public class AsyncLoopSteps extends AbstractSteps {

    @Autowired
    private AsyncLoopBinding asyncLoopBinding;

    @Autowired
    private LoopsBinding loopsBinding;

    @Autowired
    private OutputsBinding outputsBinding;

    private static final Logger logger = Logger.getLogger(AsyncLoopSteps.class);

    public void addBranches(@Param(ScoreLangConstants.ASYNC_LOOP_STATEMENT_KEY) AsyncLoopStatement asyncLoopStatement,
                            @Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv,
                            @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices,
                            @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName,
                            @Param(ExecutionParametersConsts.RUNNING_EXECUTION_PLAN_ID) Long RUNNING_EXECUTION_PLAN_ID,
                            @Param(ScoreLangConstants.NEXT_STEP_ID_KEY) Long nextStepId,
                            @Param(ScoreLangConstants.BRANCH_BEGIN_STEP_ID_KEY) Long branchBeginStep,
                            @Param(ScoreLangConstants.REF_ID) String refId) {

        try {
            Context flowContext = runEnv.getStack().popContext();

            List<Serializable> splitData = asyncLoopBinding.bindAsyncLoopList(asyncLoopStatement, flowContext, nodeName);

            fireEvent(
                    executionRuntimeServices,
                    ScoreLangConstants.EVENT_ASYNC_LOOP_EXPRESSION_END,
                    "async loop expression bound",
                    runEnv.getExecutionPath().getCurrentPathPeekForward(),
                    Pair.of(LanguageEventData.BOUND_ASYNC_LOOP_EXPRESSION, (Serializable) splitData),
                    Pair.of(LanguageEventData.levelName.TASK_NAME.name(), nodeName));

            runEnv.putNextStepPosition(nextStepId);

            for (Serializable splitItem : splitData) {
                RunEnvironment branchRuntimeEnvironment = (RunEnvironment) SerializationUtils.clone(runEnv);
                Context branchContext = (Context) SerializationUtils.clone(flowContext);
                branchContext.putVariable(asyncLoopStatement.getVarName(), splitItem);

                updateCallArgumentsAndPushContextToStack(branchRuntimeEnvironment, branchContext, new HashMap<String, Serializable>());

                createBranch(
                        branchRuntimeEnvironment,
                        executionRuntimeServices,
                        RUNNING_EXECUTION_PLAN_ID,
                        refId,
                        nextStepId,
                        branchBeginStep);

                fireEvent(
                        executionRuntimeServices,
                        ScoreLangConstants.EVENT_BRANCH_START,
                        "async loop branch created",
                        runEnv.getExecutionPath().getCurrentPathPeekForward(),
                        Pair.of(ScoreLangConstants.REF_ID, refId),
                        Pair.of(RuntimeConstants.SPLIT_ITEM_KEY, splitItem),
                        Pair.of(LanguageEventData.levelName.TASK_NAME.name(), nodeName));
            }

            updateCallArgumentsAndPushContextToStack(runEnv, flowContext, new HashMap<String, Serializable>());

            // forward after the branches are created because begin task method also calls forward
            runEnv.getExecutionPath().forward();
        } catch (RuntimeException e) {
            logger.error("There was an error running the add branches execution step of: \'" + nodeName + "\'. Error is: " + e.getMessage());
            throw new RuntimeException("Error running: " + nodeName + ": " + e.getMessage(), e);
        }

    }

    public void joinBranches(@Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv,
                             @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices,
                             @Param(ScoreLangConstants.TASK_AGGREGATE_KEY) List<Output> taskAggregateValues,
                             @Param(ScoreLangConstants.TASK_NAVIGATION_KEY) Map<String, ResultNavigation> taskNavigationValues,
                             @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName) {
        try {
            List<Map<String, Serializable>> branchesContext = Lists.newArrayList();
            Context flowContext = runEnv.getStack().popContext();
            Map<String, Serializable> contextBeforeSplit = flowContext.getImmutableViewOfVariables();
            List<String> branchesResult = Lists.newArrayList();

            collectBranchesData(runEnv, executionRuntimeServices, nodeName, branchesContext, branchesResult);

            Map<String, Serializable> publishValues =
                    bindAggregateOutputs(
                            runEnv,
                            executionRuntimeServices,
                            taskAggregateValues,
                            (Serializable) taskNavigationValues,
                            nodeName, (Serializable) branchesContext,
                            contextBeforeSplit
                    );

            flowContext.putVariables(publishValues);

            String asyncLoopResult = getAsyncLoopResult(branchesResult);

            handleNavigationAndReturnValues(runEnv, executionRuntimeServices, taskNavigationValues, nodeName, publishValues, asyncLoopResult);

            runEnv.getStack().pushContext(flowContext);
        } catch (RuntimeException e) {
            logger.error("There was an error running the end task execution step of: \'" + nodeName + "\'. Error is: " + e.getMessage());
            throw new RuntimeException("Error running: \'" + nodeName + "\': " + e.getMessage(), e);
        }
    }

    private void handleNavigationAndReturnValues(
            RunEnvironment runEnv,
            ExecutionRuntimeServices executionRuntimeServices,
            Map<String, ResultNavigation> taskNavigationValues,
            String nodeName,
            Map<String, Serializable> publishValues,
            String asyncLoopResult) {
        // set the position of the next step - for the use of the navigation
        // find in the navigation values the correct next step position, according to the async loop result, and set it
        ResultNavigation navigation = taskNavigationValues.get(asyncLoopResult);
        if (navigation == null) {
            // should always have the executable response mapped to a navigation by the task, if not, it is an error
            throw new RuntimeException("Task: " + nodeName + " has no matching navigation for the async loop result: " + asyncLoopResult);
        }
        Long nextStepPosition = navigation.getNextStepId();
        String presetResult = navigation.getPresetResult();

        HashMap<String, Serializable> outputs = new HashMap<>(publishValues);
        ReturnValues returnValues = new ReturnValues(outputs, presetResult != null ? presetResult : asyncLoopResult);

        fireEvent(
                executionRuntimeServices,
                runEnv,
                ScoreLangConstants.EVENT_ASYNC_LOOP_OUTPUT_END,
                "Async loop output binding finished",
                Pair.of(LanguageEventData.OUTPUTS, (Serializable) publishValues),
                Pair.of(LanguageEventData.RESULT, returnValues.getResult()),
                Pair.of(LanguageEventData.NEXT_STEP_POSITION, nextStepPosition),
                Pair.of(LanguageEventData.levelName.TASK_NAME.name(), nodeName));

        runEnv.putReturnValues(returnValues);
        runEnv.putNextStepPosition(nextStepPosition);
    }

    private String getAsyncLoopResult(List<String> branchesResult) {
        // if one of the branches failed then return with FAILURE, otherwise return with SUCCESS
        String asyncLoopResult = ScoreLangConstants.SUCCESS_RESULT;
        for (String branchResult : branchesResult) {
            if (branchResult.equals(ScoreLangConstants.FAILURE_RESULT)) {
                asyncLoopResult = ScoreLangConstants.FAILURE_RESULT;
                break;
            }
        }
        return asyncLoopResult;
    }

    private Map<String, Serializable> bindAggregateOutputs(
            RunEnvironment runEnv,
            ExecutionRuntimeServices executionRuntimeServices,
            List<Output> taskAggregateValues,
            Serializable taskNavigationValues,
            String nodeName, Serializable branchesContext,
            Map<String, Serializable> contextBeforeSplit) {

        Map<String, Serializable> aggregateContext = new HashMap<>();
        aggregateContext.put(RuntimeConstants.BRANCHES_CONTEXT_KEY, branchesContext);

        fireEvent(
                executionRuntimeServices,
                runEnv,
                ScoreLangConstants.EVENT_ASYNC_LOOP_OUTPUT_START,
                "Async loop output binding started",
                Pair.of(ScoreLangConstants.TASK_AGGREGATE_KEY, (Serializable) taskAggregateValues),
                Pair.of(ScoreLangConstants.TASK_NAVIGATION_KEY, taskNavigationValues),
                Pair.of(LanguageEventData.levelName.TASK_NAME.name(), nodeName));

        return outputsBinding.bindOutputs(contextBeforeSplit, aggregateContext, taskAggregateValues);
    }

    private void collectBranchesData(
            RunEnvironment runEnv,
            ExecutionRuntimeServices executionRuntimeServices,
            String nodeName,
            List<Map<String, Serializable>> branchesContext,
            List<String> branchesResult) {

        List<EndBranchDataContainer> branches = executionRuntimeServices.getFinishedChildBranchesData();
        for (EndBranchDataContainer branch : branches) {
            Map<String, Serializable> branchContext = branch.getContexts();

            RunEnvironment branchRuntimeEnvironment = (RunEnvironment) branchContext.get(ScoreLangConstants.RUN_ENV);

            branchesContext.add(branchRuntimeEnvironment.getStack().popContext().getImmutableViewOfVariables());

            ReturnValues executableReturnValues = branchRuntimeEnvironment.removeReturnValues();
            branchesResult.add(executableReturnValues.getResult());

            fireEvent(
                    executionRuntimeServices,
                    runEnv,
                    ScoreLangConstants.EVENT_BRANCH_END,
                    "async loop branch ended",
                    Pair.of(RuntimeConstants.BRANCH_RETURN_VALUES_KEY, executableReturnValues),
                    Pair.of(LanguageEventData.levelName.TASK_NAME.name(), nodeName)
            );
        }
    }

    private void createBranch(RunEnvironment runEnv,
                              ExecutionRuntimeServices executionRuntimeServices,
                              Long RUNNING_EXECUTION_PLAN_ID,
                              String refId,
                              Long nextStepId,
                              Long branchBeginStep) {
        pushParentFlowDataOnStack(runEnv, RUNNING_EXECUTION_PLAN_ID, nextStepId);

        Map<String, Serializable> branchContext = new HashMap<>();
        branchContext.put(ScoreLangConstants.RUN_ENV, runEnv);
        executionRuntimeServices.addBranch(branchBeginStep, refId, branchContext);
    }
}