text:
<?php
    session_start();
    header('Access-Control-Allow-Origin: *');
    ini_set('display_startup_errors', 1);
    ini_set('display_errors', 1);
    error_reporting(-1);
    $conn = new PDO('mysql:host=localhost;dbname=1998294_db', 'root', '1234');
    //$conn = new PDO('mysql:host=localhost;dbname=1183032', '1183032', 'Steinmetzstr9');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if(isset($_POST['action']) && $_POST['action'] == 'load')
    {
        $fc_shapes = load_fc_shapes();
        $fc_arrows = load_fc_arrows();
        $re = array('fcShapes' => $fc_shapes, 'fcArrows' => $fc_arrows);
        echo json_encode($re, JSON_NUMERIC_CHECK);
    }
    else if(isset($_POST['action']) && $_POST['action'] == 'save')
    {
        $pap = json_decode($_POST['flowchart'], true);
        save_fc_shapes($pap['shapes']);
        save_fc_arrows($pap['arrows']);
    }

function get_user_id($name, $password)
{
    global $conn;
    $statement = $conn->prepare('
        select id
        from user
        where name = :name
          and password = :password
        limit 1');
    $statement->bindParam(':name', $name);
    $statement->bindParam(':password', $password);
    $result = $statement->execute();
    $result = $statement->setFetchMode(PDO::FETCH_ASSOC);
    $rows = $statement->fetchAll();
    if(count($rows) === 1)
    {
        return $rows[0]['id'];
    }
    return -1;
}

function does_user_exist($name)
{
    global $conn;
    $statement = $conn->prepare('
        select id
        from user
        where name = :name
        limit 1');
    $statement->bindParam(':name', $name);
    $result = $statement->execute();
    $result = $statement->setFetchMode(PDO::FETCH_ASSOC);
    $rows = $statement->fetchAll();
    return (count($rows) >= 1);
}

function create_user($name, $password, $email)
{
    global $conn;
    if(does_user_exist($name))
    {
        return false;
    }
    $statement = $conn->prepare('
        insert into user (name, password, email) values(:name, :password, :email)');
    $statement->bindParam(':name', $name);
    $statement->bindParam(':password', $password);
    $statement->bindParam(':email', $email);
    $statement->execute();
    return true;
}

function load_fc_shapes()
{
    global $conn;
    $statement = $conn->prepare('
        select fc_shape.id as id, x, y, fc_shape_type.name as shapeType, title, text
        from fc_shape
        join book
          on fc_shape.book_id = book.id
        join fc_shape_type
          on fc_shape.fc_shape_type_id = fc_shape_type.id
        where
          book_id = (select max(book.id)
                     from book
                     where book.name = :book_name
                     and book.user_id = :user_id)');
    $statement->bindParam(':user_id', $_SESSION['user_id']);
    $statement->bindParam(':book_name', $_SESSION['book_name']);
    $result = $statement->execute();
    $result = $statement->setFetchMode(PDO::FETCH_ASSOC);
    $rows = $statement->fetchAll();
    return $rows;
}

function load_fc_arrows()
{
    global $conn;
    $statement = $conn->prepare('
        select fc_arrow.id
             , fc_arrow.source_id
             , fc_arrow.destination_id
             , fc_arrow.source_offset_x
             , fc_arrow.source_offset_y
             , fc_arrow.destination_offset_x
             , fc_arrow.destination_offset_y
             , fc_arrow.title
        from fc_arrow
        join book
          on fc_arrow.book_id = book.id
        where
          fc_arrow.book_id = (select max(book.id)
                              from book
                              where book.name = :book_name
                              and book.user_id = :user_id)');
    $statement->bindParam(':user_id', $_SESSION['user_id']);
    $statement->bindParam(':book_name', $_SESSION['book_name']);
    $result = $statement->execute();
    $result = $statement->setFetchMode(PDO::FETCH_ASSOC);
    $rows = $statement->fetchAll();
    return $rows;
}

function save_fc_shapes($fc_shapes)
{
    global $conn;

    $statement = $conn->prepare('select max(id) as max_book_id from book');
    $result = $statement->execute();
    $result = $statement->setFetchMode(PDO::FETCH_ASSOC);
    $rows = $statement->fetchAll();
    $nextBookId = ((count($rows) === 0) ? 1 : ($rows[0]['max_book_id'] + 1));

    $statement = $conn->prepare('
        insert into book(id, user_id, name, creation_date) values(:next_book_id, :user_id, :book_name, now())');
    $statement->bindParam(':next_book_id', $nextBookId);
    $statement->bindParam(':user_id', $_SESSION['user_id']);
    $statement->bindParam(':book_name', $_SESSION['book_name']);
    $statement->execute();
    if(is_null($fc_shapes))
    {
        return;
    }
    foreach($fc_shapes as $fc_shape)
    {
        $statement = $conn->prepare('
            insert into fc_shape
              (id, book_id, x, y, fc_shape_type_id, title, text)
            values (:id, :max_book_id, :x, :y, (select id from fc_shape_type where fc_shape_type.name = :type), :title, :text)');
        $statement->bindParam(':id', $fc_shape['id']);
        $statement->bindParam(':max_book_id', $nextBookId);
        $statement->bindParam(':x', $fc_shape['x']);
        $statement->bindParam(':y', $fc_shape['y']);
        $statement->bindParam(':type', $fc_shape['shapeType']);
        $statement->bindParam(':title', $fc_shape['title']);
        $statement->bindParam(':text', $fc_shape['text']);
        $result = $statement->execute();
    }
}
function save_fc_arrows($fc_arrows)
{
    global $conn;
    if(is_null($fc_arrows))
    {
        return;
    }
    foreach($fc_arrows as $fc_arrow)
    {
        $statement = $conn->prepare('
            insert into fc_arrow
              (id, source_id, destination_id, book_id, source_offset_x, source_offset_y, destination_offset_x, destination_offset_y, title)
            values (:id, :source_id, :destination_id, (select max(book.id) from book where book.name = :book_name and book.user_id = :user_id), :source_offset_x, :source_offset_y, :destination_offset_x, :destination_offset_y, :title)');
        $statement->bindParam(':id', $fc_arrow['id']);
        $statement->bindParam(':source_id', $fc_arrow['source_id']);
        $statement->bindParam(':destination_id', $fc_arrow['destination_id']);
        $statement->bindParam(':book_name', $_SESSION['book_name']);
        $statement->bindParam(':user_id', $_SESSION['user_id']);
        $statement->bindParam(':source_offset_x', $fc_arrow['source_offset_x']);
        $statement->bindParam(':source_offset_y', $fc_arrow['source_offset_y']);
        $statement->bindParam(':destination_offset_x', $fc_arrow['destination_offset_x']);
        $statement->bindParam(':destination_offset_y', $fc_arrow['destination_offset_y']);
        $statement->bindParam(':title', $fc_arrow['title']);
        $result = $statement->execute();
    }
}

function getBooks($user_id)
{
    global $conn;
    $statement = $conn->prepare('
        select book.name
        from book
        join user on book.user_id = user.id
        where user.id = :user_id
        group by book.name');
    $statement->bindParam(':user_id', $user_id);
    $result = $statement->execute();
    $result = $statement->setFetchMode(PDO::FETCH_ASSOC);
    $rows = $statement->fetchAll();
    return $rows;
}
function doesBookExist($user_id, $bookName)
{
    global $conn;
    $statement = $conn->prepare('
        select book.id
        from book
        join user
          on book.user_id = user.id
        where book.name = :book_name
          and user.id = :user_id
        limit 1');
    $statement->bindParam(':book_name', $bookName);
    $statement->bindParam(':user_id', $user_id);
    $result = $statement->execute();
    $result = $statement->setFetchMode(PDO::FETCH_ASSOC);
    $rows = $statement->fetchAll();
    return count($rows) > 0;
}

function createNewBook($user_id, $bookName)
{
    if(doesBookExist($user_id, $bookName))
    {
        return false;
    }
    global $conn;
    $statement = $conn->prepare('
        insert into book(user_id, name, creation_date) values(:user_id, :book_name, now())');
    $statement->bindParam(':user_id', $user_id);
    $statement->bindParam(':book_name', $bookName);
    $statement->execute();
    $statement = $conn->prepare('
        insert into fc_shape(id, book_id, fc_shape_type_id, x, y, title, text) values(1, (select max(id) from book where name = :book_name and user_id = :user_id), 1, 100, 100, "Title", "Texte")');
    $statement->bindParam(':book_name', $bookName);
    $statement->bindParam(':user_id', $user_id);
    $statement->execute();
    return true;
}
function createNewUser($user, $password)
{
    global $conn;
    $statement = $conn->prepare('
        insert into user(name, password) values(:user, :password)');
    $statement->bindParam(':user', $user);
    $statement->bindParam(':password', $password);
    $statement->execute();
}
?>


text:
#ifndef __OPENCV_XFEATURES2D_FEATURES_2D_HPP__
#define __OPENCV_XFEATURES2D_FEATURES_2D_HPP__

#include "opencv2/features2d.hpp"

namespace cv
{
namespace xfeatures2d
{

//! @addtogroup xfeatures2d_nonfree
//! @{

/** @brief Class for extracting keypoints and computing descriptors using the Scale Invariant Feature Transform
(SIFT) algorithm by D. Lowe @cite Lowe04 .
 */
class CV_EXPORTS_W SIFT : public Feature2D
{
public:
    /**
    @param nfeatures The number of best features to retain. The features are ranked by their scores
    (measured in SIFT algorithm as the local contrast)

    @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The
    number of octaves is computed automatically from the image resolution.

    @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform
    (low-contrast) regions. The larger the threshold, the less features are produced by the detector.

    @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning
    is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are
    filtered out (more features are retained).

    @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image
    is captured with a weak camera with soft lenses, you might want to reduce the number.
     */
    CV_WRAP static Ptr<SIFT> create( int nfeatures = 0, int nOctaveLayers = 3,
                                    double contrastThreshold = 0.04, double edgeThreshold = 10,
                                    double sigma = 1.6);
};

typedef SIFT SiftFeatureDetector;
typedef SIFT SiftDescriptorExtractor;

/** @brief Class for extracting Speeded Up Robust Features from an image @cite Bay06 .

The algorithm parameters:
-   member int extended
    -   0 means that the basic descriptors (64 elements each) shall be computed
    -   1 means that the extended descriptors (128 elements each) shall be computed
-   member int upright
    -   0 means that detector computes orientation of each feature.
    -   1 means that the orientation is not computed (which is much, much faster). For example,
if you match images from a stereo pair, or do image stitching, the matched features
likely have very similar angles, and you can speed up feature extraction by setting
upright=1.
-   member double hessianThreshold
Threshold for the keypoint detector. Only features, whose hessian is larger than
hessianThreshold are retained by the detector. Therefore, the larger the value, the less
keypoints you will get. A good default value could be from 300 to 500, depending from the
image contrast.
-   member int nOctaves
The number of a gaussian pyramid octaves that the detector uses. It is set to 4 by default.
If you want to get very large features, use the larger value. If you want just small
features, decrease it.
-   member int nOctaveLayers
The number of images within each octave of a gaussian pyramid. It is set to 2 by default.
@note
   -   An example using the SURF feature detector can be found at
        opencv_source_code/samples/cpp/generic_descriptor_match.cpp
    -   Another example using the SURF feature detector, extractor and matcher can be found at
        opencv_source_code/samples/cpp/matcher_simple.cpp
 */
class CV_EXPORTS_W SURF : public Feature2D
{
public:
    /**
    @param hessianThreshold Threshold for hessian keypoint detector used in SURF.
    @param nOctaves Number of pyramid octaves the keypoint detector will use.
    @param nOctaveLayers Number of octave layers within each octave.
    @param extended Extended descriptor flag (true - use extended 128-element descriptors; false - use
    64-element descriptors).
    @param upright Up-right or rotated features flag (true - do not compute orientation of features;
    false - compute orientation).
     */
    CV_WRAP static Ptr<SURF> create(double hessianThreshold=100,
                  int nOctaves = 4, int nOctaveLayers = 3,
                  bool extended = false, bool upright = false);

    CV_WRAP virtual void setHessianThreshold(double hessianThreshold) = 0;
    CV_WRAP virtual double getHessianThreshold() const = 0;

    CV_WRAP virtual void setNOctaves(int nOctaves) = 0;
    CV_WRAP virtual int getNOctaves() const = 0;

    CV_WRAP virtual void setNOctaveLayers(int nOctaveLayers) = 0;
    CV_WRAP virtual int getNOctaveLayers() const = 0;

    CV_WRAP virtual void setExtended(bool extended) = 0;
    CV_WRAP virtual bool getExtended() const = 0;

    CV_WRAP virtual void setUpright(bool upright) = 0;
    CV_WRAP virtual bool getUpright() const = 0;
};

typedef SURF SurfFeatureDetector;
typedef SURF SurfDescriptorExtractor;

//! @}

}
} /* namespace cv */

#endif

redpajama_set_name: RedPajamaGithub


text:
c:\nuget\nuget.exe pack .\ExpectThat.Pavlov.nuspec
md c:\nuget\ExpectThat.Pavlov\
copy .\*.nupkg c:\nuget\ExpectThat.Pavlov\ /Y
pause


text:
#ifndef CHOOSETEMPLATESDIALOG_H
#define CHOOSETEMPLATESDIALOG_H

#include <QDialog>
#include <QDialogButtonBox>

namespace Ui {
class ChooseTemplatesDialog;
}

namespace BuildingEditor {

class BuildingTemplate;

class ChooseTemplatesDialog : public QDialog
{
    Q_OBJECT

public:
    explicit ChooseTemplatesDialog(const QList<BuildingTemplate*> &templates,
                                   const QString &prompt,
                                   QWidget *parent = 0);
    ~ChooseTemplatesDialog();

    void setButtons(QDialogButtonBox::StandardButtons buttons);

    QList<BuildingTemplate*> chosenTemplates() const;

private slots:
    void checkAll();
    void uncheckAll();

private:
    void setList();

private:
    Ui::ChooseTemplatesDialog *ui;

    QList<BuildingTemplate*> mTemplates;
};

} // namespace BuildingEditor

#endif // CHOOSETEMPLATESDIALOG_H


text:
const router = require('../router')

describe('Company router', () => {
  it('should define company routes', () => {
    const paths = router.stack.filter((r) => r.route).map((r) => r.route.path)
    expect(paths).to.deep.equal([
      '/export',
      '/:companyId/archive',
      '/:companyId/unarchive',
      '/:companyId',
      '/:companyId/details',
      '/:companyId/business-details',
      '/:companyId/hierarchies/ghq/search',
      '/:companyId/hierarchies/ghq/:globalHqId/add',
      '/:companyId/hierarchies/ghq/remove',
      '/:companyId/hierarchies/subsidiaries/search',
      '/:companyId/hierarchies/subsidiaries/:subsidiaryCompanyId/add',
      '/:companyId/contacts',
      '/:companyId/orders',
      '/:companyId/documents',
      '/:companyId/manage-company-list',
      '/:companyId/subsidiaries',
      '/:companyId/subsidiaries/link',
    ])
  })
})


text:
const expect = require('expect');
const path = require('path');
const { skipPrettierHelpers: helpers } = require('../utils/utils');
const { OAUTH2 } = require('../../jdl/jhipster/authentication-types');

describe('JHipster angular generator', () => {
  describe('microfrontend', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(path.join(__dirname, '../../generators/client'))
        .withOptions({
          skipInstall: true,
          auth: OAUTH2,
          microfrontend: true,
          enableTranslation: true,
          nativeLanguage: 'en',
          languages: ['fr', 'en'],
        })
        .run();
    });
    it('should match generated files snapshot', () => {
      expect(runResult.getStateSnapshot()).toMatchSnapshot();
    });
  });
});


text:
#include <iostream>

template <typename T>
class StackheapPtr
/*
  Class that is just as unsafe as a normal pointer,
  meaning that you must not forget to call delete (if the class was default-initialized [with nullptr]).

  But the pointer can refer to memory on the heap (allocated with new) -- this is if it was default-initialized [with nullptr]
  .      -> in this case delete1() will delete
  Or  the pointer can refer to memory passed in from the outside (typically on the stack)
  .      -> in this case delete1() will not delete (since the memory has to be handled from the outside)
 */
{
public:
  using type = T;

  StackheapPtr(T *p = nullptr)
    : ptr{p}, is_heap{false}
  {
    if (ptr == nullptr) {
      ptr = new T{};
      is_heap = true;
    }
  }

  StackheapPtr(const StackheapPtr<T> &rhs)
    : ptr{rhs.ptr}, is_heap{rhs.is_heap}
  {
  }

  StackheapPtr<T> &operator=(const StackheapPtr<T> &rhs)
  {
    ptr     = rhs.ptr;
    is_heap = rhs.is_heap;
    return *this;
  }

  virtual ~StackheapPtr()
  {
  }

  void delete1()
  {
    if (is_heap)
      delete ptr;
  }

  T       &operator*()       { return *ptr; }
  const T &operator*() const { return *ptr; }

  T       *operator->()       { return ptr; }
  const T *operator->() const { return ptr; }

private:
  T   *ptr;
  bool is_heap;
};

class RefCount {
public:
  using cnt_t = size_t;
  RefCount(const std::string &name_, cnt_t *cnt = nullptr) :
    name{name_}, cnt_p{cnt}
  {
    *cnt_p = 1U;
  }

  RefCount(const RefCount &rhs)
    : name{rhs.name}, cnt_p{rhs.cnt_p}
  {
    ++*cnt_p;
  }

  RefCount &operator=(const RefCount &rhs)
  {
    if (get_shared_cnt_ptr() == rhs.get_shared_cnt_ptr())
      return *this;

    name = rhs.name;
    decrease_cnt_check_del();
    cnt_p = rhs.cnt_p;
    ++*cnt_p;

    return *this;
  }

  virtual ~RefCount()
  {
    decrease_cnt_check_del();
  }

  const cnt_t      *get_shared_cnt_ptr()  const { return &*cnt_p;}
  std::string       get_name()            const { return name; }

protected:
  StackheapPtr<cnt_t> cnt_p;
  std::string      name;  /* name could also be held on heap
                             (in which case objects with same value could point to a single name instance;
                             instead of each holding their own name, as is currently the case */

private:
  void decrease_cnt_check_del() {
    if (--*cnt_p == 0) {
      cnt_p.delete1();
    }
  }
};

class BaseWrapper : public RefCount {
  // Class used for monitoring constructor and destructor behaviour.
  // Other classes just need to derive from this class!
public:
  BaseWrapper(const std::string &name_, RefCount::cnt_t *cnt = new RefCount::cnt_t)
    : RefCount{name_, cnt}
  {
    std::cout << "#constructor      \t cnt_p " << get_shared_cnt_ptr() << "  " << name << " (" << *get_shared_cnt_ptr() << ')' << std::endl;
  }

  BaseWrapper(const BaseWrapper &rhs)
    : RefCount{rhs}
  {
    std::cout << "#copy-constructor \t cnt_p " << get_shared_cnt_ptr() << "  " << name << " (" << *get_shared_cnt_ptr() << ')' << std::endl;
  }

  BaseWrapper &operator=(const BaseWrapper &rhs)
  {
    std::cout << "#operator=        \t cnt_p " << get_shared_cnt_ptr() << "  " << name << " (" << *get_shared_cnt_ptr() << ')';
    if (get_shared_cnt_ptr() == rhs.get_shared_cnt_ptr()) {
      std::cout << "\t already_holding_same_value" << std::endl;
        return *this;
    }

    RefCount::operator=(rhs);
    std::cout << "\t ==>  cnt_p " << get_shared_cnt_ptr() << "  " << name << " (" << *get_shared_cnt_ptr() << ')' << std::endl;
    return *this;
  }

  ~BaseWrapper()
  {
    std::cout << "#destructor       \t cnt_p " << get_shared_cnt_ptr() << "  " << name << " (" << *get_shared_cnt_ptr() << ')' << std::endl;
  }

};

int main()
{
  StackheapPtr<int> s1;

  int i;
  StackheapPtr<int> s2{&i};

  BaseWrapper br{"br"};
  return 0;
}


text:
<?php
namespace Bricks\UserBundle\Security\Core\User;

use Symfony\Component\Security\Core\User\UserInterface;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\Exception\AccountNotLinkedException;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;

class FOSUBUserProvider extends BaseClass
{
    /**
     * {@inheritDoc}
     */
    public function connect(UserInterface $user, UserResponseInterface $response)
    {
        $property = $this->getProperty($response);
        $username = $response->getUsername();

        //on connect - get the access token and the user ID
        $service = $response->getResourceOwner()->getName();

        $setter = 'set'.ucfirst($service);
        $setter_id = $setter.'Id';
        $setter_token = $setter.'AccessToken';

        //we "disconnect" previously connected users
        if (null !== $previousUser = $this->userManager->findUserBy(array($property => $username))) {
            $previousUser->$setter_id(null);
            $previousUser->$setter_token(null);
            $this->userManager->updateUser($previousUser);
        }

        //we connect current user
        $user->$setter_id($username);
        $user->$setter_token($response->getAccessToken());

        $this->userManager->updateUser($user);
    }

    /**
     * {@inheritdoc}
     */
    public function loadUserByOAuthUserResponse(UserResponseInterface $response)
    {
        /*
         * Load user by connector field
         *
         * eg: $user = $this->userManager->findUserBy(array('githubId' => '375734252'));
         */
        try {
            //if user exists - go with the HWIOAuth way
            $user = parent::loadUserByOAuthUserResponse($response);

            $serviceName = $response->getResourceOwner()->getName();
            $setter = 'set' . ucfirst($serviceName) . 'AccessToken';

            //update access token
            $user->$setter($response->getAccessToken());

            return $user;

        } catch (AccountNotLinkedException $e) {
            /*
             * User is registrating
             */
            $service = $response->getResourceOwner()->getName();
            $setter = 'set'.ucfirst($service);
            $setter_id = $setter.'Id';
            $setter_token = $setter.'AccessToken';

            // create new user here
            $user = $this->userManager->createUser();
            $user->$setter_id($response->getUsername());
            $user->$setter_token($response->getAccessToken());

            // set username
            $user->setUsername($response->getNickname());
            for ($i = 2; $i < 500; $i++) {
                if ($this->userManager->findUserByUsername($user->getUsername()) !== null) {
                    $user->setUsername($response->getNickname().$i);
                } else {
                    break;
                }
            }

            /*
             * set email
             *
             * email is set random. see comment below
             */
            $user->setEmail("generated_".uniqid("", true));

            /**
             * This should be an invalid password
             */
            $user->setPassword("?".uniqid(true));

            $user->setEnabled(true);

            $this->userManager->updateUser($user);
            return $user;
        }

        /*
         * Load user by email
         *
         * INSECURE: a user could set an arbitrary email in eg. github, then logging
         * automatically in with it
         */
        /*
        if ($response->getEmail() != '') {
            return $this->userManager->findUserByEmail($response->getEmail());
        }
        */

        throw new \Exception("User could not be neither retrieved nor created.");
    }
}


text:
import pyglet

class SysFonts:

    name = "System Font Loader"

    def __init__(self,kernel):
        self.kernel = kernel
        self.fs = self.kernel.get_service('fs')

        pyglet.font.add_directory(self.fs.expand('{home}/sys/font/'))

APPLICATION = []
SERVICE     = {'sysfonts':SysFonts}


text:
package it.polimi.modaclouds.cpimlibrary.sqlservice;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * This class allows to use the SQL service on the Windows Azure platform,
 * through the {@link java.sql.Connection} interface.
 *
 */
class AzureSqlService extends CloudSqlService {

	private String connectionString = null;

	public AzureSqlService(String connectionString) {
		this.connectionString = connectionString;
	}

	/**
	 * Connects to a SQL database on the Windows Azure platform and returns the
	 * {@link java.sql.Connection} interface.
	 *
	 * @param connectionString
	 * @return a {@link java.sql.Connection} interface
	 * @see java.sql.Connection
	 */
	public Connection getConnection() {
		// String connectionstr2 =
		// "jdbc:sqlserver://127.0.0.1:1433;databaseName=micdb;user=root;password=mic";
		Connection c = null;
		try {

			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			c = (Connection) DriverManager.getConnection(connectionString);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return c;
	}
}


text:
import { QuickInputButtons } from 'vscode';
import type { Container } from '../../container';
import { GitBranchReference, GitReference, Repository } from '../../git/models';
import { QuickPickItemOfT } from '../../quickpicks/items/common';
import { FlagsQuickPickItem } from '../../quickpicks/items/flags';
import { pluralize } from '../../system/string';
import { ViewsWithRepositoryFolders } from '../../views/viewBase';
import {
	appendReposToTitle,
	AsyncStepResultGenerator,
	inputBranchNameStep,
	PartialStepState,
	pickBranchesStep,
	pickBranchOrTagStep,
	pickBranchStep,
	pickRepositoryStep,
	QuickCommand,
	QuickPickStep,
	StepGenerator,
	StepResult,
	StepResultGenerator,
	StepSelection,
	StepState,
} from '../quickCommand';

interface Context {
	repos: Repository[];
	associatedView: ViewsWithRepositoryFolders;
	showTags: boolean;
	title: string;
}

type CreateFlags = '--switch';

interface CreateState {
	subcommand: 'create';
	repo: string | Repository;
	reference: GitReference;
	name: string;
	flags: CreateFlags[];
}

type DeleteFlags = '--force' | '--remotes';

interface DeleteState {
	subcommand: 'delete';
	repo: string | Repository;
	references: GitBranchReference | GitBranchReference[];
	flags: DeleteFlags[];
}

type RenameFlags = '-m';

interface RenameState {
	subcommand: 'rename';
	repo: string | Repository;
	reference: GitBranchReference;
	name: string;
	flags: RenameFlags[];
}

type State = CreateState | DeleteState | RenameState;
type BranchStepState<T extends State> = SomeNonNullable<StepState<T>, 'subcommand'>;

type CreateStepState<T extends CreateState = CreateState> = BranchStepState<ExcludeSome<T, 'repo', string>>;
function assertStateStepCreate(state: PartialStepState<State>): asserts state is CreateStepState {
	if (state.repo instanceof Repository && state.subcommand === 'create') return;

	debugger;
	throw new Error('Missing repository');
}

type DeleteStepState<T extends DeleteState = DeleteState> = BranchStepState<ExcludeSome<T, 'repo', string>>;
function assertStateStepDelete(state: PartialStepState<State>): asserts state is DeleteStepState {
	if (state.repo instanceof Repository && state.subcommand === 'delete') return;

	debugger;
	throw new Error('Missing repository');
}

type RenameStepState<T extends RenameState = RenameState> = BranchStepState<ExcludeSome<T, 'repo', string>>;
function assertStateStepRename(state: PartialStepState<State>): asserts state is RenameStepState {
	if (state.repo instanceof Repository && state.subcommand === 'rename') return;

	debugger;
	throw new Error('Missing repository');
}

function assertStateStepDeleteBranches(
	state: DeleteStepState,
): asserts state is ExcludeSome<typeof state, 'references', GitBranchReference> {
	if (Array.isArray(state.references)) return;

	debugger;
	throw new Error('Missing branches');
}

const subcommandToTitleMap = new Map<State['subcommand'], string>([
	['create', 'Create'],
	['delete', 'Delete'],
	['rename', 'Rename'],
]);
function getTitle(title: string, subcommand: State['subcommand'] | undefined) {
	return subcommand == null ? title : `${subcommandToTitleMap.get(subcommand)} ${title}`;
}

export interface BranchGitCommandArgs {
	readonly command: 'branch';
	confirm?: boolean;
	state?: Partial<State>;
}

export class BranchGitCommand extends QuickCommand<State> {
	private subcommand: State['subcommand'] | undefined;

	constructor(container: Container, args?: BranchGitCommandArgs) {
		super(container, 'branch', 'branch', 'Branch', {
			description: 'create, rename, or delete branches',
		});

		let counter = 0;
		if (args?.state?.subcommand != null) {
			counter++;

			switch (args?.state.subcommand) {
				case 'create':
					if (args.state.reference != null) {
						counter++;
					}

					if (args.state.name != null) {
						counter++;
					}

					break;
				case 'delete':
					if (
						args.state.references != null &&
						(!Array.isArray(args.state.references) || args.state.references.length !== 0)
					) {
						counter++;
					}

					break;
				case 'rename':
					if (args.state.reference != null) {
						counter++;
					}

					if (args.state.name != null) {
						counter++;
					}

					break;
			}
		}

		if (args?.state?.repo != null) {
			counter++;
		}

		this.initialState = {
			counter: counter,
			confirm: args?.confirm,
			...args?.state,
		};
	}

	override get canConfirm(): boolean {
		return this.subcommand != null;
	}

	override get canSkipConfirm(): boolean {
		return this.subcommand === 'delete' || this.subcommand === 'rename' ? false : super.canSkipConfirm;
	}

	override get skipConfirmKey() {
		return `${this.key}${this.subcommand == null ? '' : `-${this.subcommand}`}:${this.pickedVia}`;
	}

	protected async *steps(state: PartialStepState<State>): StepGenerator {
		const context: Context = {
			associatedView: this.container.branchesView,
			repos: this.container.git.openRepositories,
			showTags: false,
			title: this.title,
		};

		let skippedStepTwo = false;

		while (this.canStepsContinue(state)) {
			context.title = this.title;

			if (state.counter < 1 || state.subcommand == null) {
				this.subcommand = undefined;

				const result = yield* this.pickSubcommandStep(state);
				// Always break on the first step (so we will go back)
				if (result === StepResult.Break) break;

				state.subcommand = result;
			}

			this.subcommand = state.subcommand;

			context.title = getTitle(state.subcommand === 'delete' ? 'Branches' : this.title, state.subcommand);

			if (state.counter < 2 || state.repo == null || typeof state.repo === 'string') {
				skippedStepTwo = false;
				if (context.repos.length === 1) {
					skippedStepTwo = true;
					state.counter++;

					state.repo = context.repos[0];
				} else {
					const result = yield* pickRepositoryStep(state, context);
					if (result === StepResult.Break) continue;

					state.repo = result;
				}
			}

			switch (state.subcommand) {
				case 'create':
					assertStateStepCreate(state);
					yield* this.createCommandSteps(state, context);
					// Clear any chosen name, since we are exiting this subcommand
					state.name = undefined!;
					break;
				case 'delete':
					assertStateStepDelete(state);
					yield* this.deleteCommandSteps(state, context);
					break;
				case 'rename':
					assertStateStepRename(state);
					yield* this.renameCommandSteps(state, context);
					// Clear any chosen name, since we are exiting this subcommand
					state.name = undefined!;
					break;
				default:
					QuickCommand.endSteps(state);
					break;
			}

			// If we skipped the previous step, make sure we back up past it
			if (skippedStepTwo) {
				state.counter--;
			}
		}

		return state.counter < 0 ? StepResult.Break : undefined;
	}

	private *pickSubcommandStep(state: PartialStepState<State>): StepResultGenerator<State['subcommand']> {
		const step = QuickCommand.createPickStep<QuickPickItemOfT<State['subcommand']>>({
			title: this.title,
			placeholder: `Choose a ${this.label} command`,
			items: [
				{
					label: 'create',
					description: 'creates a new branch',
					picked: state.subcommand === 'create',
					item: 'create',
				},
				{
					label: 'delete',
					description: 'deletes the specified branches',
					picked: state.subcommand === 'delete',
					item: 'delete',
				},
				{
					label: 'rename',
					description: 'renames the specified branch',
					picked: state.subcommand === 'rename',
					item: 'rename',
				},
			],
			buttons: [QuickInputButtons.Back],
		});
		const selection: StepSelection<typeof step> = yield step;
		return QuickCommand.canPickStepContinue(step, state, selection) ? selection[0].item : StepResult.Break;
	}

	private async *createCommandSteps(state: CreateStepState, context: Context): AsyncStepResultGenerator<void> {
		if (state.flags == null) {
			state.flags = [];
		}

		while (this.canStepsContinue(state)) {
			if (state.counter < 3 || state.reference == null) {
				const result = yield* pickBranchOrTagStep(state, context, {
					placeholder: context =>
						`Choose a branch${context.showTags ? ' or tag' : ''} to create the new branch from`,
					picked: state.reference?.ref ?? (await state.repo.getBranch())?.ref,
					titleContext: ' from',
					value: GitReference.isRevision(state.reference) ? state.reference.ref : undefined,
				});
				// Always break on the first step (so we will go back)
				if (result === StepResult.Break) break;

				state.reference = result;
			}

			if (state.counter < 4 || state.name == null) {
				const result = yield* inputBranchNameStep(state, context, {
					placeholder: 'Please provide a name for the new branch',
					titleContext: ` from ${GitReference.toString(state.reference, {
						capitalize: true,
						icon: false,
						label: state.reference.refType !== 'branch',
					})}`,
					value: state.name ?? GitReference.getNameWithoutRemote(state.reference),
				});
				if (result === StepResult.Break) continue;

				state.name = result;
			}

			if (this.confirm(state.confirm)) {
				const result = yield* this.createCommandConfirmStep(state, context);
				if (result === StepResult.Break) continue;

				state.flags = result;
			}

			QuickCommand.endSteps(state);
			if (state.flags.includes('--switch')) {
				void (await state.repo.switch(state.reference.ref, { createBranch: state.name }));
			} else {
				void state.repo.branch(...state.flags, state.name, state.reference.ref);
			}
		}
	}

	private *createCommandConfirmStep(
		state: CreateStepState<CreateState>,
		context: Context,
	): StepResultGenerator<CreateFlags[]> {
		const step: QuickPickStep<FlagsQuickPickItem<CreateFlags>> = QuickCommand.createConfirmStep(
			appendReposToTitle(`Confirm ${context.title}`, state, context),
			[
				FlagsQuickPickItem.create<CreateFlags>(state.flags, [], {
					label: context.title,
					detail: `Will create a new branch named ${state.name} from ${GitReference.toString(
						state.reference,
					)}`,
				}),
				FlagsQuickPickItem.create<CreateFlags>(state.flags, ['--switch'], {
					label: `${context.title} and Switch`,
					description: '--switch',
					detail: `Will create and switch to a new branch named ${state.name} from ${GitReference.toString(
						state.reference,
					)}`,
				}),
			],
			context,
		);
		const selection: StepSelection<typeof step> = yield step;
		return QuickCommand.canPickStepContinue(step, state, selection) ? selection[0].item : StepResult.Break;
	}

	private async *deleteCommandSteps(state: DeleteStepState, context: Context): AsyncStepResultGenerator<void> {
		if (state.flags == null) {
			state.flags = [];
		}

		while (this.canStepsContinue(state)) {
			if (state.references != null && !Array.isArray(state.references)) {
				state.references = [state.references];
			}

			if (
				state.counter < 3 ||
				state.references == null ||
				(Array.isArray(state.references) && state.references.length === 0)
			) {
				context.title = getTitle('Branches', state.subcommand);

				const result = yield* pickBranchesStep(state, context, {
					filter: b => !b.current,
					picked: state.references?.map(r => r.ref),
					placeholder: 'Choose branches to delete',
					sort: { current: false, missingUpstream: true },
				});
				// Always break on the first step (so we will go back)
				if (result === StepResult.Break) break;

				state.references = result;
			}

			context.title = getTitle(
				pluralize('Branch', state.references.length, { only: true, plural: 'Branches' }),
				state.subcommand,
			);

			assertStateStepDeleteBranches(state);
			const result = yield* this.deleteCommandConfirmStep(state, context);
			if (result === StepResult.Break) continue;

			state.flags = result;

			QuickCommand.endSteps(state);
			void state.repo.branchDelete(state.references, {
				force: state.flags.includes('--force'),
				remote: state.flags.includes('--remotes'),
			});
		}
	}

	private *deleteCommandConfirmStep(
		state: DeleteStepState<ExcludeSome<DeleteState, 'references', GitBranchReference>>,
		context: Context,
	): StepResultGenerator<DeleteFlags[]> {
		const confirmations: FlagsQuickPickItem<DeleteFlags>[] = [
			FlagsQuickPickItem.create<DeleteFlags>(state.flags, [], {
				label: context.title,
				detail: `Will delete ${GitReference.toString(state.references)}`,
			}),
		];
		if (!state.references.every(b => b.remote)) {
			confirmations.push(
				FlagsQuickPickItem.create<DeleteFlags>(state.flags, ['--force'], {
					label: `Force ${context.title}`,
					description: '--force',
					detail: `Will forcibly delete ${GitReference.toString(state.references)}`,
				}),
			);

			if (state.references.some(b => b.upstream != null)) {
				confirmations.push(
					FlagsQuickPickItem.create<DeleteFlags>(state.flags, ['--remotes'], {
						label: `${context.title} & Remote${
							state.references.filter(b => !b.remote).length > 1 ? 's' : ''
						}`,
						description: '--remotes',
						detail: `Will delete ${GitReference.toString(
							state.references,
						)} and any remote tracking branches`,
					}),
					FlagsQuickPickItem.create<DeleteFlags>(state.flags, ['--force', '--remotes'], {
						label: `Force ${context.title} & Remote${
							state.references.filter(b => !b.remote).length > 1 ? 's' : ''
						}`,
						description: '--force --remotes',
						detail: `Will forcibly delete ${GitReference.toString(
							state.references,
						)} and any remote tracking branches`,
					}),
				);
			}
		}

		const step: QuickPickStep<FlagsQuickPickItem<DeleteFlags>> = QuickCommand.createConfirmStep(
			appendReposToTitle(`Confirm ${context.title}`, state, context),
			confirmations,
			context,
		);
		const selection: StepSelection<typeof step> = yield step;
		return QuickCommand.canPickStepContinue(step, state, selection) ? selection[0].item : StepResult.Break;
	}

	private async *renameCommandSteps(state: RenameStepState, context: Context): AsyncStepResultGenerator<void> {
		if (state.flags == null) {
			state.flags = [];
		}

		while (this.canStepsContinue(state)) {
			if (state.counter < 3 || state.reference == null) {
				const result = yield* pickBranchStep(state, context, {
					filter: b => !b.remote,
					picked: state.reference?.ref,
					placeholder: 'Choose a branch to rename',
				});
				// Always break on the first step (so we will go back)
				if (result === StepResult.Break) break;

				state.reference = result;
			}

			if (state.counter < 4 || state.name == null) {
				const result = yield* inputBranchNameStep(state, context, {
					placeholder: `Please provide a new name for ${GitReference.toString(state.reference, {
						icon: false,
					})}`,
					titleContext: ` ${GitReference.toString(state.reference, false)}`,
					value: state.name ?? state.reference.name,
				});
				if (result === StepResult.Break) continue;

				state.name = result;
			}

			const result = yield* this.renameCommandConfirmStep(state, context);
			if (result === StepResult.Break) continue;

			state.flags = result;

			QuickCommand.endSteps(state);
			void state.repo.branch(...state.flags, state.reference.ref, state.name);
		}
	}

	private *renameCommandConfirmStep(
		state: RenameStepState<RenameState>,
		context: Context,
	): StepResultGenerator<RenameFlags[]> {
		const step: QuickPickStep<FlagsQuickPickItem<RenameFlags>> = QuickCommand.createConfirmStep(
			appendReposToTitle(`Confirm ${context.title}`, state, context),
			[
				FlagsQuickPickItem.create<RenameFlags>(state.flags, ['-m'], {
					label: context.title,
					detail: `Will rename ${GitReference.toString(state.reference)} to ${state.name}`,
				}),
			],
			context,
		);
		const selection: StepSelection<typeof step> = yield step;
		return QuickCommand.canPickStepContinue(step, state, selection) ? selection[0].item : StepResult.Break;
	}
}


text:
from distutils.core import setup
import py2exe

setup(console=['Dotannoy.py'])


text:
class LanguagesController < ApplicationController
  # GET /languages
  # GET /languages.xml
  def index
    @languages = Language.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @languages }
    end
  end

  # GET /languages/1
  # GET /languages/1.xml
  def show
    @language = Language.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @language }
    end
  end

  # GET /languages/new
  # GET /languages/new.xml
  def new
    @language = Language.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @language }
    end
  end

  # GET /languages/1/edit
  def edit
    @language = Language.find(params[:id])
  end

  # POST /languages
  # POST /languages.xml
  def create
    @language = Language.new(params[:language])

    respond_to do |format|
      if @language.save
        flash[:notice] = 'Language was successfully created.'
        format.html { redirect_to(@language) }
        format.xml  { render :xml => @language, :status => :created, :location => @language }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @language.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /languages/1
  # PUT /languages/1.xml
  def update
    @language = Language.find(params[:id])

    respond_to do |format|
      if @language.update_attributes(params[:language])
        flash[:notice] = 'Language was successfully updated.'
        format.html { redirect_to(@language) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @language.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /languages/1
  # DELETE /languages/1.xml
  def destroy
    @language = Language.find(params[:id])
    @language.destroy

    respond_to do |format|
      format.html { redirect_to(languages_url) }
      format.xml  { head :ok }
    end
  end
end


text:
package com.ignissoft.avalanche.results;

import java.util.HashMap;

import jsystem.utils.XmlUtils;

import org.w3c.dom.Element;

import com.ignissoft.trafficGenerator.TrafficException;

/**
 * @author shmir
 */
public class AvalancheClusterStats {

	private Element clientElement;

	private HashMap<String, AvalancheResultsBlock> blocks = new HashMap<String, AvalancheResultsBlock>();

	public AvalancheClusterStats(Element resultsElement) {
		clientElement = XmlUtils.getElement((this instanceof AvalancheClientStats) ? "ClientStatistics" : "ServerStatistics", 0, resultsElement);
	}

	public AvalancheResultsBlock block(String name) throws TrafficException {
		if (blocks.get(name) == null) {
			Element blocElement = XmlUtils.getChildElementWithName("Block", name, clientElement);
			if (blocElement == null) {
				return null;
			}
			blocks.put(name, new AvalancheResultsBlock(blocElement));
		}
		return blocks.get(name);

	}

	/*
	 * Standard Getters and Setters.
	 */

}


text:
package edu.mit.media.socialmetadatademo;

import android.os.Bundle;
import android.app.Activity;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import edu.mit.media.bandicootopenpdsdemo.R;

public class TermsAndConditionsActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_terms_and_conditions);
		setResult(RESULT_CANCELED);
		TextView tv = ((TextView) findViewById(R.id.share_button_title));
		tv.setMovementMethod(new ScrollingMovementMethod());
		findViewById(R.id.terms_agree_button).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(AnonymousLoginActivity.AGREED_TO_TERMS_RESULT_CODE);
				finish();
			}
		});
	}
}


text:
require 'chefspec'

describe 'http_request::post' do
  let(:chef_run) { ChefSpec::SoloRunner.converge(described_recipe) }

  it 'posts a http_request with an explicit action' do
    expect(chef_run).to post_http_request('explicit_action')
    expect(chef_run).to_not post_http_request('not_explicit_action')
  end

  it 'posts a http_request with attributes' do
    expect(chef_run).to post_http_request('with_attributes').with(url: 'http://my.url')
    expect(chef_run).to_not post_http_request('with_attributes').with(url: 'http://my.other.url')
  end

  it 'posts a http_request when specifying the identity attribute' do
    expect(chef_run).to post_http_request('identity_attribute')
  end
end


text:
{{adminCtrl.adminMessage}}

return to the  homepage

<uib-tabset active="activeForm">

  <uib-tab index="0" heading="create a bike brand">
    <create-mfr></create-mfr>

  </uib-tab>
  <uib-tab index="1" heading="add a bike to a brand">

bike brands

    <display-mfr
    ng-repeat="mfr in adminCtrl.mfrs"
    set-current-mfr="adminCtrl.setCurrentMfr(mfr)"
    fetch-mfr-bikes="adminCtrl.fetchMfrBikes()"
    brand="mfr"
    current-mfr="adminCtrl.currentMfr"
    all-bikes="adminCtrl.bikes"
    current-bike="adminCtrl.currentBike"
    set-current-bike="adminCtrl.setCurrentBike(newBike)"
    ></display-mfr>

  </uib-tab>

  <uib-tab index="2" heading="add a new bike size">
    <create-geo></create-geo>
    <display-geo fetch-all-geos="adminCtrl.fetchAllGeos()" geos="adminCtrl.geos"></display-geo>
  </uib-tab>

  <uib-tab index="3" heading="admin users">
    <users></users>
  </uib-tab>

</uib-tabset>


text:
// Copyright 2019 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.
package org.chromium.chrome.browser.feed.library.sharedstream.scroll;

import androidx.annotation.Nullable;

import org.chromium.chrome.browser.feed.library.common.concurrent.CancelableTask;
import org.chromium.chrome.browser.feed.library.common.concurrent.MainThreadRunner;
import org.chromium.chrome.browser.feed.library.common.time.Clock;

/**
 * Helper which is able to track a Scroll and aggregate them before sending the scroll events
 * events.
 */
public abstract class ScrollTracker {
    private static final String TAG = "ScrollTracker";
    // onScroll events are very noisy, so we collate them together to avoid over-reporting scrolls.
    private static final long SCROLL_EVENT_COLLATE_MILLIS = 200L;

    private final MainThreadRunner mMainThreadRunner;
    private final Clock mClock;

    @Nullable
    protected ScrollNotifier mScrollNotifier;
    @Nullable
    protected CancelableTask mTask;

    public ScrollTracker(MainThreadRunner mainThreadRunner, Clock clock) {
        this.mMainThreadRunner = mainThreadRunner;
        this.mClock = clock;
    }

    public void onUnbind() {
        ScrollTracker.ScrollNotifier localScrollNotifier = mScrollNotifier;
        if (localScrollNotifier != null) {
            if (mTask != null) {
                mTask.cancel();
            }
            localScrollNotifier.run();
        }
    }

    protected void trackScroll(int dx, int dy) {
        boolean positiveScroll;
        int amount;
        if (dy == 0) {
            return;
        }
        positiveScroll = dy > 0;
        amount = dy;

        int previousTotalScroll = 0;
        ScrollNotifier previousScrollNotifier = mScrollNotifier;
        if (previousScrollNotifier != null && !(mTask != null && mTask.canceled())) {
            if (previousScrollNotifier.mPositiveScroll == positiveScroll) {
                // Same direction, so merge the existing scroll with the new one.
                previousTotalScroll = previousScrollNotifier.mScrollAmount;
                if (mTask != null) {
                    mTask.cancel();
                }
            }
        }

        amount += previousTotalScroll;
        mScrollNotifier = new ScrollNotifier(positiveScroll, amount, mClock.currentTimeMillis());
        mTask = mMainThreadRunner.executeWithDelay(
                TAG, mScrollNotifier, SCROLL_EVENT_COLLATE_MILLIS);
    }

    protected abstract void onScrollEvent(int scrollAmount, long timestamp);

    private class ScrollNotifier implements Runnable {
        final boolean mPositiveScroll;
        final int mScrollAmount;
        final long mTimestamp;

        public ScrollNotifier(boolean positiveScroll, int scrollAmount, long timestamp) {
            this.mPositiveScroll = positiveScroll;
            this.mScrollAmount = scrollAmount;
            this.mTimestamp = timestamp;
        }

        @Override
        public void run() {
            onScrollEvent(mScrollAmount, mTimestamp);
            if (mScrollNotifier == this) {
                mScrollNotifier = null;
                if (mTask != null) {
                    mTask.cancel();
                }
            }
        }
    }
}


text:
from actionkit.models import CoreUser
from datetime import datetime
from django import forms
from django.contrib.localflavor.us import forms as usforms
from django.utils.translation import ugettext_lazy as _

class EventForm(forms.Form):
    title = forms.CharField(label=_("Title"), required=False)
    date = forms.DateField(label=_("Date"), required=False)
    time = forms.TimeField(label=_("Time"), required=False)

    venue = forms.CharField(label=_("Venue"), required=True)
    address = forms.CharField(label=_("Address"), required=True)
    city = forms.CharField(label=_("City"), required=True)
    state = usforms.USStateField(label=_("State"), required=True)
    zip = usforms.USZipCodeField(label=_("ZIP"), required=True)

    max_attendees = forms.IntegerField(label=_("Max Attendees"), required=True)
    host = forms.EmailField(label=_("Host's Email Address"), required=True)

    public_description = forms.CharField(label=_("Description"), required=False, widget=forms.Textarea())
    directions = forms.CharField(label=_("Directions"), required=False, widget=forms.Textarea())

    def clean_host(self):
        host = self.cleaned_data['host']
        try:
            user = CoreUser.objects.using("ak").get(email=host)
        except CoreUser.DoesNotExist:
            raise forms.ValidationError(_("No core_user exists with email %(email)s") % {'email': host})
        return user

    def clean(self):
        try:
            data = self.build_event_struct()
        except:
            pass
        else:
            self.event_struct = data
        return self.cleaned_data

    def build_event_struct(self):
        data = {}
        for key in "title venue city state zip max_attendees".split():
            data[key] = self.cleaned_data.get(key)
        for key in "directions public_description".split():
            if key in self.cleaned_data and self.cleaned_data.get(key).strip():
                data[key] = self.cleaned_data.get(key)
        data['creator_id'] = self.cleaned_data['host'].id
        data['address1'] = self.cleaned_data['address']
        data['starts_at'] = datetime.combine(self.cleaned_data['date'], self.cleaned_data['time'])
        return data


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

    <application
        android:allowBackup="true"
        android:fullBackupContent="false"
        android:icon="@android:color/transparent"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar">

        <activity android:name=".AppActivity">

            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:host="miguelgaeta.com"
                      android:scheme="http"/>
            </intent-filter>
        </activity>
    </application>
</manifest>


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

<form class="form-inline" ng-submit="addUserSkills()" method="post">

          <input type="checkbox" checklist-model="user.skills" checklist-value="skill"> {[skill]} </input>

    No skills to be submited

    <button class="btn btn-sm btn-primary" type="button" ng-click="addUserSkills()"> Submit skills </button>

{[user]}


text:
using System.Collections.Generic;

namespace Abp.Web.Security.AntiForgery
{
    /// <summary>
    /// Common configuration shared between ASP.NET MVC and ASP.NET Web API.
    /// </summary>
    public interface IAbpAntiForgeryWebConfiguration
    {
        /// <summary>
        /// Used to enable/disable Anti Forgery token security mechanism of ABP.
        /// Default: true (enabled).
        /// </summary>
        bool IsEnabled { get; set; }

        /// <summary>
        /// A list of ignored HTTP verbs for Anti Forgery token validation.
        /// Default list: Get, Head, Options, Trace.
        /// </summary>
        HashSet<HttpVerb> IgnoredHttpVerbs { get; }
    }
}


text:
'use strict';

angular.module('esri-map-docs')
    .service('browserDetectionService', function() {
        return {
            isMobile: function() {
                return /Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini|IEMobile/i.test(navigator.userAgent);
            }
        };
    });


text:
'use strict';
/**
 * An object wrapper for easier use of registry api
 */
class Key {
    constructor (pHKeyOrPredefined, path, accessLevel) {
        var isPredefined = false;
        this._registry = require('./registry');
        this._windef = require('./windef');
        for (var k in this._windef.HKEY) {
            if (this._windef.HKEY[k] === pHKeyOrPredefined) {
                isPredefined = true;
                break;
            }
        }

        // this is a predefined key
        if (isPredefined) {
            return this._registry.openKeyFromPredefined(pHKeyOrPredefined, path, accessLevel);
        }

        this.handle = pHKeyOrPredefined;
        this.path = path;
    }

    /**
    * Closes this Key, releasing the native OS handle
    * all the containers matching the query. Automatically closes current key
    */
    close () {
        this._registry.closeKey(this);
    }

    deleteKey () {
        this._registry.deleteKey(this);
    }

    /**
     * Deletes a value from a key
     */
    deleteValue (value) {
        this._registry.deleteValue(this, value);
    }

    /**
    * Sets a value for a value name on this key
    * all the containers matching the query.
    * @param  {DS.Record Container} selectedContainer - The container to be selected
    */
    setValue (valueName, valueType, value) {
        this._registry.setValueForKeyObject(this, valueName, valueType, value);
    }

    getValue (valueName) {
        return this._registry.queryValueForKeyObject(this, valueName);
    }

    /**
    * Returns a new Key object given a subkeyName
    * @param  {string} subKeyName - The container to be selected
    * @param  {string} accessLevel - The container to be selected
    * @return {Key}
    */
    openSubKey (subKeyName, accessLevel) {
        var key = this._registry.openKeyFromKeyObject(this, subKeyName, accessLevel);
        return key;
    }

    createSubKey (subKeyName, accessLevel) {
        this._registry.createKey(this, subKeyName, accessLevel);

        return new Key(this.handle, subKeyName, accessLevel);
    }

    /**
     * Returns the string representing this Key
     */
    toString () {
        return this.path;
    }
}

module.exports = Key;


text:
"use strict";

exports.foo7 = foo7;
var foo = exports.foo = 1;
var foo = exports.foo = 1;
var bar = exports.bar = 2;
var foo2 = exports.foo2 = function () {};
var foo3 = exports.foo3 = undefined;
var foo4 = exports.foo4 = 2;
var foo5 = exports.foo5 = undefined;
var foo6 = exports.foo6 = 3;
function foo7() {}
var foo8 = exports.foo8 = function foo8() {};

exports.__esModule = true;


text:
module HealthSeven::V2_5
class Al1 < ::HealthSeven::Segment
  # Set ID - AL1
  attribute :set_id_al1, Si, position: "AL1.1", require: true
  # Allergen Type Code
  attribute :allergen_type_code, Ce, position: "AL1.2"
  # Allergen Code/Mnemonic/Description
  attribute :allergen_code_mnemonic_description, Ce, position: "AL1.3", require: true
  # Allergy Severity Code
  attribute :allergy_severity_code, Ce, position: "AL1.4"
  # Allergy Reaction Code
  attribute :allergy_reaction_codes, Array[St], position: "AL1.5", multiple: true
  # Identification Date
  attribute :identification_date, Dt, position: "AL1.6"
end
end


text:
<?php

namespace UthandoSessionManagerTest\Controller;

use UthandoSessionManagerTest\Framework\ApplicationTestCase;

class SessionManagerControllerTest extends ApplicationTestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->setApplicationConfig(
            include __DIR__ . '/../../config/TestRouteListenerConfig.php'
        );
    }

    public function testIndexAction()
    {

    }
}


text:
<?php
/**
 * @group slow
 * @group Kwc_Trl
 * @group Kwc_Trl_ImageEnlarge
 * @group Image
 *
 * Was wo angezeigt werden soll siehe Kwc_Trl_ImageEnlarge_Master
 *
ansicht frontend:
http://fnprofile.markus.vivid/kwf/kwctest/Kwc_Trl_ImageEnlarge_Root/de/test1 (...2,3,4,5,6)
http://fnprofile.markus.vivid/kwf/kwctest/Kwc_Trl_ImageEnlarge_Root/en/test1 (...2,3,4,5,6)

backend
http://kwf.kwf.niko.vivid/kwf/componentedittest/Kwc_Trl_ImageEnlarge_Root/Kwc_Trl_ImageEnlarge_ImageEnlarge_Component/Index?componentId=root-master_test1
http://kwf.kwf.niko.vivid/kwf/componentedittest/Kwc_Trl_ImageEnlarge_Root/Kwc_Trl_ImageEnlarge_ImageEnlarge_Trl_Component.Kwc_Trl_ImageEnlarge_ImageEnlarge_Component/Index?componentId=root-en_test1
 */
class Kwc_Trl_ImageEnlarge_Test extends Kwc_TestAbstract
{
    public function setUp()
    {
        parent::setUp('Kwc_Trl_ImageEnlarge_Root');

        //master image
        Kwf_Model_Abstract::getInstance('Kwc_Trl_ImageEnlarge_ImageEnlarge_TestModel')
            ->getProxyModel()->setData(array(
                array('component_id'=>'root-master_test1', 'kwf_upload_id'=>'1'),
                array('component_id'=>'root-master_test2', 'kwf_upload_id'=>'1'),
                array('component_id'=>'root-master_test3', 'kwf_upload_id'=>'1'),
                array('component_id'=>'root-master_test4', 'kwf_upload_id'=>'1'),
                array('component_id'=>'root-master_test5', 'kwf_upload_id'=>'1'),
                array('component_id'=>'root-master_test6', 'kwf_upload_id'=>'1'),
                array('component_id'=>'root-master_test7', 'kwf_upload_id'=>'1'),
            ));

        //image trl
        Kwf_Model_Abstract::getInstance('Kwc_Trl_ImageEnlarge_ImageEnlarge_Trl_TestModel')
            ->getProxyModel()->setData(array(
                array('component_id'=>'root-en_test1', 'own_image'=>0),
                array('component_id'=>'root-en_test2', 'own_image'=>0),
                array('component_id'=>'root-en_test3', 'own_image'=>1),
                array('component_id'=>'root-en_test4', 'own_image'=>1),
                array('component_id'=>'root-en_test5', 'own_image'=>1),
                array('component_id'=>'root-en_test6', 'own_image'=>0),
                array('component_id'=>'root-en_test7', 'own_image'=>0),
            ));

        //image trl own image
        Kwf_Model_Abstract::getInstance('Kwc_Trl_ImageEnlarge_ImageEnlarge_Trl_Image_TestModel')
            ->getProxyModel()->setData(array(
                array('component_id'=>'root-en_test1-image', 'kwf_upload_id'=>null),
                array('component_id'=>'root-en_test2-image', 'kwf_upload_id'=>null),
                array('component_id'=>'root-en_test3-image', 'kwf_upload_id'=>'6'),
                array('component_id'=>'root-en_test4-image', 'kwf_upload_id'=>'6'),
                array('component_id'=>'root-en_test5-image', 'kwf_upload_id'=>'6'),
                array('component_id'=>'root-en_test6-image', 'kwf_upload_id'=>null),
                array('component_id'=>'root-en_test7-image', 'kwf_upload_id'=>'3'),
                array('component_id'=>'root-en_test7-image', 'kwf_upload_id'=>'3'),
            ));

        //master enlarge tag
        Kwf_Model_Abstract::getInstance('Kwc_Trl_ImageEnlarge_ImageEnlarge_EnlargeTag_TestModel')
            ->getProxyModel()->setData(array(
                array('component_id'=>'root-master_test1-linkTag'),
                array('component_id'=>'root-master_test2-linkTag'),
                array('component_id'=>'root-master_test3-linkTag'),
                array('component_id'=>'root-master_test4-linkTag'),
                array('component_id'=>'root-master_test5-linkTag'),
                array('component_id'=>'root-master_test6-linkTag'),
                array('component_id'=>'root-master_test7-linkTag'),
            ));

        //enlarge tag trl
        Kwf_Model_Abstract::getInstance('Kwc_Trl_ImageEnlarge_ImageEnlarge_EnlargeTag_Trl_TestModel')
            ->getProxyModel()->setData(array(
                array('component_id'=>'root-en_test1-linkTag'),
                array('component_id'=>'root-en_test2-linkTag'),
                array('component_id'=>'root-en_test3-linkTag'),
                array('component_id'=>'root-en_test4-linkTag'),
                array('component_id'=>'root-en_test5-linkTag'),
                array('component_id'=>'root-en_test6-linkTag'),
                array('component_id'=>'root-en_test7-linkTag'),
            ));

        //enlarge tag trl own image
        Kwf_Model_Abstract::getInstance('Kwc_Trl_ImageEnlarge_ImageEnlarge_EnlargeTag_Trl_Image_TestModel')
            ->getProxyModel()->setData(array(
                array('component_id'=>'root-en_test1-linkTag-image'),
                array('component_id'=>'root-en_test2-linkTag-image'),
                array('component_id'=>'root-en_test3-linkTag-image'),
                array('component_id'=>'root-en_test4-linkTag-image'),
                array('component_id'=>'root-en_test5-linkTag-image'),
                array('component_id'=>'root-en_test6-linkTag-image'),
                array('component_id'=>'root-en_test7-linkTag-image'),
            ));
    }

    public function testDe()
    {
        $c = $this->_root->getComponentById('root-master_test1');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);

        $c = $this->_root->getComponentById('root-master_test2');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);

        $c = $this->_root->getComponentById('root-master_test3');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);

        $c = $this->_root->getComponentById('root-master_test4');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);

        $c = $this->_root->getComponentById('root-master_test5');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);

        $c = $this->_root->getComponentById('root-master_test6');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);
    }

    public function testEn()
    {
        $c = $this->_root->getComponentById('root-en_test1');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);

        $c = $this->_root->getComponentById('root-en_test2');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);

        $c = $this->_root->getComponentById('root-en_test3');
        $this->_checkTheSizes($c->render(), 6, 180, 330, 6, 65, 120);

        $c = $this->_root->getComponentById('root-en_test4');
        $this->_checkTheSizes($c->render(), 6, 180, 330, 6, 65, 120);

        $c = $this->_root->getComponentById('root-en_test5');
        $this->_checkTheSizes($c->render(), 6, 180, 330, 6, 65, 120);

        $c = $this->_root->getComponentById('root-en_test6');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);
    }

    public function testDeImageEnlargeDimensions()
    {
        $c = $this->_root->getComponentById('root-master_test2-linkTag');
        $dim = $c->getComponent()->getImageDimensions();
        $this->assertEquals(560, $dim['width']);
        $this->assertEquals(560, $dim['height']);
    }

    public function testEnClearCacheAddOwnImage()
    {
        $c = $this->_root->getComponentById('root-en_test1');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);

        $row = $c->getComponent()->getRow();
        $row->own_image = 1;
        $row->save();
        $row = $c->getChildComponent('-image')->getComponent()->getRow(); //own preview image in en
        $row->kwf_upload_id = '6';
        $row->save();
        $this->_process();
        $this->_checkTheSizes($c->render(), 6, 180, 330, 6, 65, 120);

        $row = $c->getComponent()->getRow();
        $row->own_image = 0;
        $row->save();
        $this->_process();
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);
    }

    public function testEnClearCacheChangeMasterImage()
    {
        $c = $this->_root->getComponentById('root-en_test1');
        $this->_checkTheSizes($c->render(), 1, 560, 560, 1, 120, 120);

        $row = $this->_root->getComponentById('root-master_test1')->getComponent()->getRow();
        $row->kwf_upload_id = '6';
        $row->save();
        $this->_process();
        $this->_checkTheSizes($c->render(), 6, 180, 330, 6, 65, 120);
    }

    private function _getImageFromHtml($html)
    {
        preg_match_all('#/media/([^/]+)/([^/]+)/([^/]+)#', $html, $matches);
        foreach ($matches[0] as $key => $m) {
            if (substr($matches[3][$key], 0, 10) == 'dh-{width}') continue;
            return Kwf_Media::getOutput($matches[1][$key], $matches[2][$key], $matches[3][$key]);
        }
        return null;
    }

    public function testDeChangeImageMedia_CacheOfEnlargeTagTrlDeletedWithSameWidth()
    {
        $imageEnlargeTrlComponent = $this->_root->getComponentById('root-en_test1');
        $c = $imageEnlargeTrlComponent
                ->getChildComponent('-linkTag')
                ->getChildComponent('_imagePage');
        $imageWithNumber1 = $this->_getImageFromHtml($c->render());

        // Gets row of Master-Component, changes images
        $row = $imageEnlargeTrlComponent->chained->getComponent()->getRow();
        $row->kwf_upload_id = 3;
        $row->save();
        $this->_process();
        $imageWithNumber3 = $this->_getImageFromHtml($c->render());

        $image1 = new Imagick($imageWithNumber1['file']);
        $image3 = new Imagick($imageWithNumber3['file']);

        $this->assertEquals(560, $image1->getImageWidth());
        $this->assertEquals(320, $image3->getImageHeight());
    }

    public function testDeChangeImageMedia_CacheOfEnlargeTagTrlDeletedWithSameWidth2()
    {
        $imageEnlargeTrlComponent = $this->_root->getComponentById('root-en_test1');
        $c = $imageEnlargeTrlComponent
                ->getChildComponent('-linkTag')
                ->getChildComponent('_imagePage');
        $imageWithNumber1 = $this->_getImageFromHtml($c->render());

        $row = $imageEnlargeTrlComponent->getComponent()->getRow();
        $row->own_image = 1;
        $row->save();
        $row = $imageEnlargeTrlComponent->getChildComponent('-image')->getComponent()->getRow(); //own preview image in en
        $row->kwf_upload_id = '3';
        $row->save();
        $this->_process();
        $imageWithNumber3FromTrl = $this->_getImageFromHtml($c->render());

        $image1 = new Imagick($imageWithNumber1['file']);
        $image3 = new Imagick($imageWithNumber3FromTrl['file']);

        $this->assertEquals(560, $image1->getImageWidth());
        $this->assertEquals(560, $image3->getImageWidth());
        $this->assertEquals(320, $image3->getImageHeight());
    }

    public function testEnChangeOwnImageMedia_CacheOfEnlargeTagTrlDeletedWhenSameWidth()
    {
        $imageEnlargeTrlComponent = $this->_root->getComponentById('root-en_test7');
        $c = $imageEnlargeTrlComponent
                ->getChildComponent('-linkTag')
                ->getChildComponent('_imagePage');
        $imageWithNumber1 = $this->_getImageFromHtml($c->render());

        // Gets row of trl-component, adds image
        $row = $imageEnlargeTrlComponent->getComponent()->getRow();
        $row->own_image = 1;
        $row->save();
        $this->_process();
        $imageWithNumber3 = $this->_getImageFromHtml($c->render());

        $image1 = new Imagick($imageWithNumber1['file']);
        $image3 = new Imagick($imageWithNumber3['file']);
        $this->assertEquals($image1->getImageWidth(), 560);
        $this->assertEquals($image1->getImageHeight(), 560);
        $this->assertEquals($image3->getImageWidth(), 560);
        $this->assertEquals($image3->getImageHeight(), 320);
    }

    public function testEnChangeOwnImageMedia_CacheOfEnlargeTagTrlDeletedWhenSameWidth2()
    {
        $imageEnlargeTrlComponent = $this->_root->getComponentById('root-en_test3');
        $c = $imageEnlargeTrlComponent
                ->getChildComponent('-linkTag')
                ->getChildComponent('_imagePage');
        $imageWithNumber6 = $this->_getImageFromHtml($c->render());

        // Gets row of trl-component, adds image
        $row = $imageEnlargeTrlComponent->getComponent()->getRow();
        $row->own_image = 0;
        $row->save();
        $this->_process();
        $imageWithNumber1 = $this->_getImageFromHtml($c->render());

        $image6 = new Imagick($imageWithNumber6['file']);
        $image1 = new Imagick($imageWithNumber1['file']);
        $this->assertEquals($image6->getImageWidth(), 180);
        $this->assertEquals($image6->getImageHeight(), 330);
        $this->assertEquals($image1->getImageWidth(), 560);
        $this->assertEquals($image1->getImageHeight(), 560);
    }

    public function testEnChangeOwnImageAndSetUploadMedia_CacheOfEnlargeTagTrlDeletedWhenSameWidth()
    {
        $imageEnlargeTrlComponent = $this->_root->getComponentById('root-en_test1');
        $c = $imageEnlargeTrlComponent
                ->getChildComponent('-linkTag')
                ->getChildComponent('_imagePage');
        $imageWithNumber1 = $this->_getImageFromHtml($c->render());

        // Gets row of trl-component, adds image
        $row = $imageEnlargeTrlComponent->getComponent()->getRow();
        $row->own_image = 1;
        $row->save();
        $row = $imageEnlargeTrlComponent->getChildComponent('-image')->getComponent()->getRow(); //own preview image in en
        $row->kwf_upload_id = '3';
        $row->save();
        $this->_process();
        $imageWithNumber3 = $this->_getImageFromHtml($c->render());

        $image1 = new Imagick($imageWithNumber1['file']);
        $image3 = new Imagick($imageWithNumber3['file']);
        $this->assertNotEquals($image1->getImageHeight(), $image3->getImageHeight());
        $this->assertEquals($image1->getImageWidth(), 560);
        $this->assertEquals($image1->getImageHeight(), 560);
        $this->assertEquals($image3->getImageWidth(), 560);
        $this->assertEquals($image3->getImageHeight(), 320);
    }

    private function _checkTheSizes($html, $largeImageNum, $largeWidth, $largeHeight, $smallImageNum, $smallWidth, $smallHeight)
    {
        // getMediaOutput aufrufen, damit Cache-Meta geschrieben wird (wegen d0cf3812b20fa19c40617ac5b08ed08a18ff808d)
        // muss so gemacht werden, weil der request über getimagesize weiter unten
        // nicht das FnF-Cache Model dieses Request schreiben kann
        preg_match_all('#/media/([^/]+)/([^/]+)/([^/]+)#', $html, $matches);
        foreach ($matches[0] as $key => $m) {
            if (substr($matches[3][$key], 0, 10) == 'dh-{width}') continue;
            Kwf_Media::getOutput($matches[1][$key], $matches[2][$key], $matches[3][$key]);
        }
        preg_match('#^.*?<a.+?"width":(\d+),"height":(\d+).+?<img.+?src=".+?(\d+)\.jpg.+width="(\d+)".+height="(\d+)".+$#ms', $html, $matches);
        $this->assertEquals($matches[1], $largeWidth);
        $this->assertEquals($matches[2], $largeHeight);
        $this->assertEquals($matches[3], $smallImageNum);
        $this->assertEquals($matches[4], $smallWidth);
        $this->assertEquals($matches[5], $smallHeight);

        preg_match('#href="(.+?)".*? src="(.+?)"#ms', $html, $matches);
        $smallSrcSize = getimagesize('http://'.Kwf_Registry::get('testDomain').$matches[2]);
        $this->assertEquals($smallWidth, $smallSrcSize[0]);
        $this->assertEquals($smallHeight, $smallSrcSize[1]);

        $c = Kwf_Component_Data_Root::getInstance()
            ->getPageByUrl('http://'.Kwf_Registry::get('testDomain').str_replace('/kwf/kwctest/'.Kwf_Component_Data_Root::getComponentClass(), '', $matches[1]), '');
        $c->render(true, true); //first render in-process so we find the cache entry when doing a clear-cache

        //then render "real" thru http
        $largeHtml = file_get_contents('http://'.Kwf_Registry::get('testDomain').$matches[1]);
        preg_match('#class="lightboxBody.*?<img .*?src="(.*?)"#s', $largeHtml, $matches);
        $this->assertRegExp('#'.$largeImageNum.'\.jpg#', $matches[1]);
        $largeSrcSize = getimagesize('http://'.Kwf_Registry::get('testDomain').$matches[1]);
        $this->assertEquals($largeWidth, $largeSrcSize[0]);
        $this->assertEquals($largeHeight, $largeSrcSize[1]);
    }
}


text:
const url = require('url');
const config = require('../config');

module.exports = {
  'Load homepage': (client) => {
    const home = client.page.timetable();

    home
      .navigate()
      .waitForElementVisible('.main-container', config.timeout)
      .assert.elementPresent('.page-container')
      // Logo
      .assert.elementPresent('a[href="/"]');
  },

  'Add module': (client) => {
    const home = client.page.timetable();

    home
      .click('@addModuleBtn')
      .sendKeys('@addModuleInput', ['CS1010S'])
      .sendKeys('@addModuleInput', [client.Keys.RETURN]);

    client.pause(100);

    home
      .sendKeys('@addModuleInput', [client.Keys.ESCAPE])
      .waitForElementVisible('@timetableLessons', config.timeout)
      .assert.containsText('@timetableLessons', 'CS1010S')
      .assert.containsText('@moduleTable', 'CS1010S');
  },

  'Exam calendar': (client) => {
    const home = client.page.timetable();

    home
      .click('@examCalendarBtn')
      .waitForElementVisible('@examCalendar', 500)
      .assert.containsText('@examCalendar', 'CS1010S');

    client.end();
  },

  'Load module page': (client) => {
    client
      .url(url.resolve(client.launch_url, '/modules/CS1010S'))
      .waitForElementVisible('.page-container h1', config.timeout)
      .assert.containsText('.page-container h1', 'Programming Methodology');
  },

  'Load venue page': (client) => {
    client
      .url(url.resolve(client.launch_url, '/venues/COM1-0120'))
      .waitForElementVisible('.page-container', config.timeout)
      .assert.containsText('h1', 'COM1-0120')
      .end();
  },
  // STOP! Are you adding another test? Make sure the test has .end() at the end
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Myxosporium fumosum Ellis & Everh.

### Remarks
null


text:
class TokyoMetro::Factory::Convert::Customize::Api::StationFacility::RailwayLineNameInPlatformTransferInfos::Info < TokyoMetro::Factory::Convert::Common::Api::MetaClass::Fundamental::Normal

  include ::TokyoMetro::ClassNameLibrary::Api::StationFacility

  def process
    replacing_dictionary = ::TokyoMetro::Factory::Convert::Customize::Api::StationFacility::RailwayLineNameInPlatformTransferInfos.replacing_railway_lines
    ignored_dictionary = nil

    @object.platform_infos.each do | platform_info |
      if platform_info.transfer_infos.present?
        ary = self.class.platform_transfer_list_class.new

        platform_info.transfer_infos.each do | transfer_info |
          ::TokyoMetro::Factory::Convert::Customize::Api::StationFacility::RailwayLineNameInPlatformTransferInfos::Info::EachTransferInfo.process( transfer_info , ary , replacing_dictionary , ignored_dictionary , @object.same_as )
        end

        platform_info.instance_eval do
          @transfer_infos = ary
        end

      end
    end
  end

end


text:
#include "pool.h"

/*  TODO: The dummy implementation of a thread pool. As for now there's only
    one worker thread created. */

int grid_pool_init (struct grid_pool *self)
{
    return grid_worker_init (&self->worker);
}

void grid_pool_term (struct grid_pool *self)
{
    grid_worker_term (&self->worker);
}

struct grid_worker *grid_pool_choose_worker (struct grid_pool *self)
{
    return &self->worker;
}


text:
// Type: Highsoft.Web.Mvc.Stocks.PlotOptionsSeriesStep

namespace Highsoft.Web.Mvc.Stocks
{
    public enum PlotOptionsSeriesStep
    {
        False,
        Left,
        Center,
        Right,
    }
}


text:
<component name="ArtifactManager">
  <artifact type="war" name="sample-webapp:war">
    <output-path>$PROJECT_DIR$/../target</output-path>
    <root id="archive" name="servlet-example.war">
      <element id="artifact" artifact-name="sample-webapp:war exploded" />
    </root>
  </artifact>
</component>


text:
suite('rb/reviewRequestPage/views/ReviewReplyEditorView', function() {
    let reviewReply;
    let editor;
    let view;

    beforeEach(function() {
        const $container = $('
').appendTo($testsScratch);

        reviewReply = new RB.ReviewReply({
            id: 121
        });

        /* Some tests will invoke this, so just pretend it works. */
        spyOn(reviewReply, 'discardIfEmpty').and.callFake(
            (options, context) => options.success.call(context));

        editor = new RB.ReviewRequestPage.ReviewReplyEditor({
            anchorPrefix: 'header-reply',
            replyObject: reviewReply,
            review: new RB.Review({
                id: 42,
                parentObject: new RB.ReviewRequest(),
            }),
            reviewReply: reviewReply,
            contextType: 'rcbt',
            contextID: '100',
        });

        view = new RB.ReviewRequestPage.ReviewReplyEditorView({
            model: editor,
            el: $testsScratch,
        });

        /* Necessary to do pre-render so we can use makeCommentElement. */
        view._$commentsList = $('
');

        $container
            .append(view._$commentsList)
            .append($('New Comment'));
    });

    describe('Construction', function() {
        it('Populate from draft comment', function() {
            const commentText = 'Test comment';
            const now = moment();
            const $el = view._makeCommentElement({
                commentID: 16,
                now: now,
                text: commentText,
            });

            view.render();

            expect(editor.get('commentID')).toBe(16);
            expect(editor.get('text')).toBe(commentText);
            expect(editor.get('hasDraft')).toBe(true);
            expect(editor.get('timestamp').valueOf())
                .toBe(now.milliseconds(0).valueOf());
            expect(view._$draftComment[0]).toBe($el[0]);
            expect(view._$addCommentLink.is(':visible')).toBe(false);
        });
    });

    describe('Actions', function() {
        it('Add comment link', function() {
            view.render();

            expect(view._$addCommentLink.is(':visible')).toBe(true);
            view._$addCommentLink.click();

            expect(view._$addCommentLink.is(':visible')).toBe(false);
            expect(view._$draftComment).not.toBe(null);
            expect(view._$draftComment.hasClass('draft')).toBe(true);
        });
    });

    describe('Event handling', function() {
        it('Comment discarded', function() {
            view._makeCommentElement({
                text: 'Test comment',
            });

            view.render();

            let $el = view.$('.reply-comments li');
            expect($el.length).toBe(1);

            reviewReply.trigger('destroyed');

            $el = view.$('.reply-comments li');
            expect($el.length).toBe(0);
            expect(view._$draftComment).toBe(null);
        });

        it('Comment published', function() {
            const $draftEl = view._makeCommentElement({
                commentID: 16,
            });

            spyOn($.fn, 'user_infobox').and.callThrough();
            spyOn($.fn, 'timesince').and.callThrough();

            view.render();
            editor.set('text', 'Test **comment**');
            reviewReply.trigger('published');

            const $el = view.$('.reply-comments li');

            expect($el.length).toBe(1);
            expect($draftEl).not.toBe($el);
            expect($el.hasClass('draft')).toBe(false);
            expect($el.data('comment-id')).toBe(16);
            expect(view._$draftComment).toBe(null);
            expect($.fn.user_infobox).toHaveBeenCalled();
            expect($.fn.timesince).toHaveBeenCalled();

            const $anchor = $el.children('.comment-anchor');
            expect($anchor.length).toBe(1);
            expect($anchor.attr('name')).toBe('header-reply121');

            const $floatingAnchor = $el.find('> .floating-anchor > a');
            expect($floatingAnchor.length).toBe(1);
            expect($floatingAnchor.attr('href')).toBe('#header-reply121');
            expect($floatingAnchor.hasClass('fa fa-link fa-flip-horizontal'))
                .toBe(true);
        });
    });

    describe('Methods', function() {
        it('openCommentEditor', function() {
            view.render();

            expect(view._$addCommentLink.is(':visible')).toBe(true);
            expect(view._$draftComment).toBe(null);

            view.openCommentEditor();

            expect(view._$addCommentLink.is(':visible')).toBe(false);
            expect(view._$draftComment).not.toBe(null);
            expect(view._$draftComment.hasClass('draft')).toBe(true);
        });
    });

    describe('Text rendering', function() {
        function testRendering(richText, expectedHTML) {
            view.render();

            const $comment = view._makeCommentElement({
                text: '
Test &lt;
',
                richText: richText,
            });

            const $reviewText = $comment.find('.reviewtext');
            expect($reviewText.length).toBe(1);
            expect($reviewText.hasClass('rich-text')).toBe(richText);
            expect($reviewText.html()).toBe(expectedHTML);
        }

        it('richText=true', function() {
            testRendering(true, '
Test &lt;
');
        });

        it('richText=false', function() {
            testRendering(false,
                          '<p><strong>Test</strong> ' +
                          '&amp;lt;</p>');
        });
    });
});


text:
								#################
								### CONSTANTS ###
								#################

"""
	"Breakout" is an arcade game developed and published by Atari, Inc.
It was conceptualized by Nolan Bushnell and Steve Bristow, influenced
by the 1972 Atari arcade game Pong, and built by Steve Wozniak aided
by Steve Jobs.

	In the game, a layer of bricks lines the top third of the screen. A
ball travels across the screen, bouncing off the top and side walls of the
screen. When a brick is hit, the ball bounces away and the brick is destroyed.
The player loses a turn when the ball touches the bottom of the screen. To
prevent this from happening, the player has a movable paddle to bounce the
ball upward, keeping it in play.

	This is the firt part of the game where you can find all Constant variables
used for the game. We choose those values without any specific purposes and most
of them are just a result of design preferences. You can check the alternative
design option just by changing their values.

	Pygame module is the most important part of this project. Before running
the project make sure that you have installed that module. You can download
the module from this website: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame
Installing the module is easy and does not require any specific knowledge.
"""

import sys
import math
import pygame

# Constant for determining the screen size.

SIZE_OF_THE_SCREEN = 640, 480

# Dimensions of the Object

HEIGHT_OF_BRICK  = 15
WIDTH_OF_BRICK   = 60

HEIGH_OF_PADDLE = 12
PADDLE_WIDTH  = 60

BALL_DIAMETER = 16
BALL_RADIUS   = BALL_DIAMETER // 2

# X coordinate for Paddle
MAX_PADDLE_X = SIZE_OF_THE_SCREEN[0] - PADDLE_WIDTH

MAX_BALL_X   = SIZE_OF_THE_SCREEN[0] - BALL_DIAMETER
MAX_BALL_Y   = SIZE_OF_THE_SCREEN[1] - BALL_DIAMETER

# Y coordinate for Paddle
PADDLE_Y = SIZE_OF_THE_SCREEN[1] - HEIGH_OF_PADDLE - 10

# Color constants
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE  = (0, 0, 255)
COLOR_OF_BRICK = (255, 0, 0)

# State constants
STATE_BALL_IN_PADDLE = 0
STATE_PLAYING = 1
STATE_WON = 2
STATE_GAME_OVER = 3


text:
module Rusic
  class Deployer
    attr_reader :files

    def initialize(files)
      @files = Array(files).map { |file| ThemeFile.new(file) }
    end

    def upload_files(options = {})
      files.each do |file|
        file.uploader.upload_file(options)
      end
    rescue RestClient::Unauthorized
      puts
      puts '401 Unauthorized. Ensure your API Key is set correctly.'
      exit(1)
    rescue RestClient::ResourceNotFound
      puts
      puts '404 Not Found. Ensure you are have permission to access the given theme'
      exit(1)
    end
  end
end


text:
import { Directive, ElementRef, Input, OnDestroy, OnInit } from '@angular/core';
import { InputNumber } from 'ngx-weui/core';
import { Observable } from 'rxjs';

/**
 * 获取验证码
 */
@Directive({
  selector: '[weui-vcode]',
  exportAs: 'weuiVcode',
  host: {
    '(click)': '_onClick()',
    '[disabled]': '_disabled',
  },
})
export class VCodeDirective implements OnInit, OnDestroy {
  /**
   * 发送事件
   */
  @Input('weui-vcode') onSend: () => Observable<boolean>;

  /**
   * 时长(单位:秒),默认:`60`
   */
  @Input('weui-seconds') @InputNumber() seconds: number = 60;

  /**
   * 倒计时模板,使用 `${num}` 表示当前秒数
   */
  // tslint:disable-next-line: no-invalid-template-strings
  @Input('weui-tpl') tpl: string = '${num} 秒';

  /**
   * 重新发送提醒文本
   */
  @Input('weui-error') error: string = '重新发送';

  _disabled: boolean = false;
  private _cur: string;
  private _t: any;

  constructor(private el: ElementRef) {}

  ngOnInit(): void {
    if (typeof this.onSend !== 'function') {
      console.error('weui-vcode必须传递一个返回值为 `Observable<boolean>` 函数');
    }
    this._cur = this.el.nativeElement.innerHTML;
  }

  _onClick(): void {
    this._disabled = true;
    this.onSend().subscribe(res => {
      res ? this.tick() : this.err();
    });
  }

  private err(): void {
    this._disabled = false;
    this.el.nativeElement.innerHTML = this.error;
  }

  private tick(): void {
    let count = this.seconds < 1 ? 1 : this.seconds;
    this.setText(count);
    this._t = setInterval(() => {
      if (--count <= 0) {
        this._disabled = false;
        this.el.nativeElement.innerHTML = this._cur;
        this.destroy();
      } else {
        this.setText(count);
      }
    }, 1000);
  }

  private setText(num: number): void {
    this.el.nativeElement.innerHTML = this.tpl.replace(/\${num}/, num.toString());
  }

  private destroy(): void {
    if (this._t) {
      clearInterval(this._t);
      this._t = null;
    }
  }

  ngOnDestroy(): void {
    this.destroy();
  }
}