text:
package org.apache.jackrabbit.vault.packaging;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.jcr.RepositoryException;
import javax.jcr.Session;

import org.apache.jackrabbit.vault.fs.io.Archive;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.osgi.annotation.versioning.ProviderType;

/**
 * The package manager is used to deal with packages. the following operations
 * are defined:
 *
 *

 *
open

 *
read underlying data and validate them

 *
 *
close

 *
release underlying data. the package is unusable afterwards

 *
 *
upload

 *
import the package from a binary source to the system. for example
 * create a new jcr node structure or create a file.
 *

 *
 *
export

 *
export the package in binary format.
 *

 *
 *
unwrap

 *
extract the meta information of the binary data and store it in the
 * repository

 *
 *
assemble

 *
create a vault export of the repository using the package definition
 * and filter.

 *
 *
extract

 *
extract the packaged content to the repository.

 *
 *
install

 *
install the packaged content to the repository but create a snapshot if needed.

 *
 *
snapshot

 *
assemble snapshot information that can be used for a later uninstall. this
 * is done by assembling the content using the same filter definition.

 *
 *
uninstall

 *
revert changes to the repository of a previous installation.

 *
 *

 */
@ProviderType
public interface PackageManager {

    /**
     * Opens the given archive and creates a package
     * @param archive the archive
     * @return the package
     * @throws IOException if an error occurs
     */
    @NotNull VaultPackage open(@NotNull Archive archive) throws IOException;

    /**
     * Opens the given archive and creates a package
     * @param archive the archive
     * @param strict if {@code true} the import is more strict with regards to errors.
     * @return the package
     * @throws IOException if an error occurs
     */
    @NotNull VaultPackage open(@NotNull Archive archive, boolean strict) throws IOException;

    /**
     * Opens the given file and creates a package
     * @param file the file
     * @return the package
     * @throws IOException if an error occurs
     */
    @NotNull VaultPackage open(@NotNull File file) throws IOException;

    /**
     * Opens the given file and creates a package
     * @param file the file
     * @param strict if {@code true} the import is more strict with regards to errors.
     * @return the package
     * @throws IOException if an error occurs
     */
    @NotNull VaultPackage open(@NotNull File file, boolean strict) throws IOException;

    /**
     * Assembles a package using the given meta information and file to
     * store to. if file is {@code null} a temp file is generated.
     *
     * @param s the repository session
     * @param opts export options
     * @param file the file to write to
     * @return the newly created vault package
     *
     * @throws IOException if an I/O error occurs.
     * @throws RepositoryException if a repository error during building occurs.
     * @throws IllegalStateException if the package is not new.
     */
    @NotNull VaultPackage assemble(@NotNull Session s, @NotNull ExportOptions opts, @Nullable File file)
            throws IOException, RepositoryException;

    /**
     * Assembles a package using the given meta information. The package
     * is directly streamed to the given output stream.
     *
The specified stream is closed after this method returns.
     * @param s the repository session
     * @param opts the export options
     * @param out the output stream to write to
     * @throws IOException if an I/O error occurs.
     * @throws RepositoryException if a repository error during building occurs.
     * @throws IllegalStateException if the package is not new.
     */
    void assemble(@NotNull Session s, @NotNull ExportOptions opts, @NotNull OutputStream out)
            throws IOException, RepositoryException;

    /**
     * Re-wraps a package using the given meta information and file to
     * store to.
     *
     * @param opts export options
     * @param src source package
     * @param file the file to write to (may be {@code null}) to create a new temp file
     * @return the newly created vault package
     *
     * @throws IOException if an I/O error occurs.
     * @throws RepositoryException if a repository error during building occurs.
     * @throws IllegalStateException if the package is not new.
     */
    @NotNull VaultPackage rewrap(@NotNull ExportOptions opts, @NotNull VaultPackage src, @Nullable File file)
            throws IOException, RepositoryException;

    /**
     * Re-wraps the given package with the definition provided in the export
     * options.
     *
The specified stream is closed after this method returns.
     * @param opts export options
     * @param src source package
     * @param out destination output stream
     * @throws IOException if an I/O error occurs
     */
    void rewrap(@NotNull ExportOptions opts, @NotNull VaultPackage src, @NotNull OutputStream out)
            throws IOException;
}


text:
Downloading CodeIgniter
#######################

-  `CodeIgniter v4.0.0-dev (Upcoming version) <https://codeload.github.com/bcit-ci/CodeIgniter4/zip/develop>`_

******
GitHub
******

`Git <http://git-scm.com/about>`_ is a distributed version control system.

Public Git access is available at `GitHub <https://github.com/bcit-ci/CodeIgniter4>`_.
Please note that while every effort is made to keep this code base
functional, we cannot guarantee the functionality of code taken from
the develop branch.

Stable versions are also available via `GitHub Releases <https://github.com/bcit-ci/CodeIgniter4/releases>`_.

redpajama_set_name: RedPajamaGithub


text:
This is a quick-and-dirty tool for an alternative method of poker planning, usable by a distributed team.

## Setup
- `docker run crossbario/crossbar` from a VPS or server
- Update the `Config.es6` with the IP (default port 8080)
- Run `npm run build`
- Merge `master` into `gh-pages`

## Usage
Load this webpage in your favorite modern web browser.  No webserver is required - it can be loaded straight off
your filesystem if you like.

Create a new card by entering a story title in the textbox at the top of the screen.

Drag existing cards to whichever sizing you feel is appropriate.

Everyone who has this webpage open will see the same board.  When a card is changed, it'll briefly flash to let you know
that it was newly moved or created.

## Method for Story Sizing

### Phase 1 - Sizing
No discussion during the first phase of the sizing exercise.

All team members move cards around simultaneously.  Each team member simply puts a card in the column they think it
should be.  If you disagree with its placement, just move it!

If a card moves around a lot, move it to the '?' bucket.

Once the team stops moving cards around, proceed to Phase 2.

### Phase 2 - Resolve Questions
Discuss each card in the '?' bucket until the team understands enough to size the task.  After discussion, sizing can
be determined by whatever means you like - hidden voting (as in traditional poker planning) tends to work well for this.

## Caveats
Because this was a small PoC effort, in its current incarnation there are some warnings and a few important missing
features.  Caveat emptor.

* Cards can only be added - not deleted or updated.
* There's only a single channel for all users.  That means that there's no privacy or access control for the board.
  * If you want your own private board, you'll need to run your own [crossbar.io](http://crossbar.io) server, and update main.js's `_getRealm()` and `_getWebsocketURI()` functions accordingly.

> **IMPORTANT** - all state is saved in the clients' browsers!  When the last person closes their browser, the contents of
> the table will be lost!


text:
import jwt from 'jsonwebtoken';
import toastr from 'toastr';
import {
  SET_CURRENT_USER,
  GET_USER_INFORMATION,
  GET_USER_REQUEST
} from './types';
import instance from '../utils/axios';
import '../utils/toastrConfig';

/**
 * Action creator to set the current user in the store
 *
 * @param { object } user - The user object
 *
 * @returns { object } The action type and a user object
 */

export const setCurrentUser = (user) => {
  return {
    type: SET_CURRENT_USER,
    user,
    isLoading: false
  };
};

const getUserRequest = () => ({
  type: GET_USER_REQUEST,
  isLoading: true
});

/**
 * Action creator to set fetch the user in the store
 *
 * @param { object } user - The user object
 *
 * @returns { object } The action type and a user object
 */

export const getUserInformationActionCreator = (user) => {
  return {
    type: GET_USER_INFORMATION,
    user,
    isLoading: false
  };
};

/**
 * Action to set the current user in the store
 *
 * @param { object } user - The user object
 *
 * @returns { object } The action type and a user object
 */

export const getUserInformation = () => {
  return (dispatch) => {
    dispatch(getUserRequest());
    return instance
      .get('/users/get_user')
      .then((response) => {
        dispatch(getUserInformationActionCreator(response.data));
      })
      .catch(error => error);
  };
};

/**
 * Action to sign-in a user
 *
 * @param { object } userData - The user object
 *
 * @returns { object } The signed in user and a token
 */
export const signinRequest = userData => (dispatch) => {
  return instance
    .post('/users/signin', userData)
    .then((response) => {
      const { token } = response.data;
      localStorage.setItem('authToken', token);
      toastr.success('Login Successful.');
      dispatch(setCurrentUser(jwt.decode(token)));
    })
    .catch((error) => {
      toastr.error(error.response.data.message);
    });
};

/**
 * Action to log a user out of the application
 *
 * @returns { object } An empty object representing a signed out user
 */
export const logout = () => {
  return (dispatch) => {
    localStorage.removeItem('authToken');
    toastr.success('Logout Successful.');
    dispatch(setCurrentUser({}));
  };
};


text:
USE TSQL_Koans

EXEC tSQLt.NewTestClass 'AboutSets'
GO

/*
UNION
INTERSECT
EXCEPT
*/


text:
package com.gu.cas

import org.joda.time.{Days, Weeks}
import org.scalatest.{FlatSpec, Matchers}

class TokenPayloadTest extends FlatSpec with Matchers {

  val epoch = TokenPayload.epoch.toLocalDate
  val wrappedEpoch = epoch.plusDays(2048)
  val startOffset = 2040
  val testData = TokenPayload(Days.days(startOffset), Weeks.weeks(2), SevenDay)

  "Token Payload" should "return the end date on the issue date (with no wrapping)" in {

    testData.expiryDate(epoch.plusDays(startOffset)) should be(epoch.plusDays(startOffset + 14 + 1))

  }

  "Token Payload" should "return the expiry date on expiry date (with no wrapping)" in {

    testData.expiryDate(epoch.plusDays(startOffset + 14 + 1)) should be(epoch.plusDays(startOffset + 14 + 1))

  }

  "Token Payload" should "work on the day before the wrapped creation date (with no wrapping)" in {

    testData.expiryDate(wrappedEpoch.plusDays(startOffset - 1)) should be(epoch.plusDays(startOffset + 14 + 1))

  }

  "Token Payload" should "return the wrapped expiry date on the wrapped creation date" in {

    testData.expiryDate(wrappedEpoch.plusDays(startOffset)) should be(wrappedEpoch.plusDays(startOffset + 14 + 1))

  }

  "create token payload" should "be created if it's still in the first era" in {
    val payload = TokenPayload(epoch.plusDays(100))(Weeks.THREE, SevenDay)
    payload.creationDateOffset should be(Days.days(100))
  }

  "create token payload" should "be created if it's into the second era" in {
    val payload = TokenPayload(wrappedEpoch.plusDays(100))(Weeks.THREE, SevenDay)
    payload.creationDateOffset should be(Days.days(100))
  }

}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-lazy="false">

  <class name="org.olat.data.portfolio.artefact.AbstractArtefact" table="o_ep_artefact">
  	<!-- the default columns -->
    <id name="key" column="artefact_id" type="long" unsaved-value="null">
      <generator class="hilo"/>
    </id>
    <discriminator column="artefact_type" type="string"/>
    <version name="version" access="field" column="version" type="int"/>
		<property  name="creationDate" column="creationdate" type="timestamp" />

		<property  name="collectionDate" column="collection_date" type="timestamp" />

    <property name="title" column="title" type="string" length="512" not-null="false"/>
		<property name="description" column="description" type="string" length="4000" not-null="false"/>
		<property name="signature" column="signature" type="int"/>
		<property name="businessPath" column="businesspath" type="string" length="2048" not-null="false"/>
		<property name="fulltextContent" column="fulltextcontent" type="text" length="16384" not-null="false"/>
		<property name="reflexion" column="reflexion" type="text" length="16384" not-null="false"/>
		<property name="source" column="source" type="string" length="2048" not-null="false"/>

    <many-to-one name="author" column="fk_artefact_auth_id" class="org.olat.data.basesecurity.IdentityImpl"
    	fetch="join" unique="false" cascade="none"/>

  </class>

	<subclass name="org.olat.data.portfolio.artefact.FileArtefact"
		extends="org.olat.data.portfolio.artefact.AbstractArtefact" discriminator-value="bc">
		<property name="filename" column="add_prop1" type="string" length="2048" not-null="false"/>

		<!-- If you need some additional property, the alter sql create these three properties.
		     You can used them in your own subclass without extra update from the database
		<property name="myExtraProp" column="add_prop1" type="string" length="2048" not-null="false"/>
		<property name="myAddProp" column="add_prop2" type="string" length="2048" not-null="false"/>
		<property name="myUsefullProp" column="add_prop3" type="string" length="2048" not-null="false"/>
		-->
	</subclass>

	<subclass name="org.olat.data.portfolio.artefact.EPTextArtefact"
		extends="org.olat.data.portfolio.artefact.AbstractArtefact" discriminator-value="text">
	</subclass>

	<subclass name="org.olat.data.portfolio.artefact.EPStructureElementArtefact"
		extends="org.olat.data.portfolio.artefact.AbstractArtefact" discriminator-value="ep-structure-element">

		<many-to-one name="structureElement" column="fk_struct_el_id" class="org.olat.data.portfolio.structure.EPStructureElement"
			fetch="join" unique="false" cascade="none"/>
	</subclass>

</hibernate-mapping>


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

namespace HuntTheWumpus
{
    enum SpecialNode { None, Bats, Hole, Wumpus, PlayerSpawn, Arrow, Coin }

    class Node : CircleShape
    {
        public int Id;
        public List<Node> Neighbors = new List<Node>();
        public List<Node> Connections = new List<Node>();
        static Random r = new Random(DateTime.Now.Second);
        public SpecialNode Specialty = SpecialNode.None;
        bool enabled = false;
        bool active = false;
        ushort openConnections = 3;

        public Node(int id)
            : base(50)
        {
            Id = id;
            SetPointCount(6);
            Rotation = 90;
            Enabled = false;
            OutlineColor = Color.White;
        }

        public void AddConnection(Node n)
        {
            if (!Connections.Contains(n))
            {
                Connections.Add(n);
                openConnections--;
                n.AddConnection(this);
            }
        }

        public void GenerateRandomConnections()
        {
            while (Neighbors.Count > 0 && openConnections > 0)
            {
                var lookingAt = Neighbors[r.Next(0, Neighbors.Count - 1)];
                if (lookingAt.openConnections > 0)
                    AddConnection(lookingAt);
                Neighbors.Remove(lookingAt);
            }
        }

        public bool Enabled
        {
            get
            {
                return enabled;
            }

            set
            {
                enabled = value;
                if (value)
                    FillColor = Color.Green;
                else
                    FillColor = new Color(100, 100, 100);
            }
        }

        public bool Active
        {
            get
            {
                return active;
            }

            set
            {
                active = value;
                if (value)
                {
                    OutlineThickness = 2;
                    OutlineColor = Color.Blue;
                    Enabled = true;
                }
                else
                {
                    OutlineThickness = 0;
                    OutlineColor = Color.White;
                }
            }
        }
    }
}


text:
package com.amazonaws.services.opsworks.model.transform;

import java.util.Map;
import java.util.Map.Entry;

import com.amazonaws.services.opsworks.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * EnvironmentVariable JSON Unmarshaller
 */
public class EnvironmentVariableJsonUnmarshaller implements
        Unmarshaller<EnvironmentVariable, JsonUnmarshallerContext> {

    public EnvironmentVariable unmarshall(JsonUnmarshallerContext context)
            throws Exception {
        EnvironmentVariable environmentVariable = new EnvironmentVariable();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL)
            return null;

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Key", targetDepth)) {
                    context.nextToken();
                    environmentVariable.setKey(StringJsonUnmarshaller
                            .getInstance().unmarshall(context));
                }
                if (context.testExpression("Value", targetDepth)) {
                    context.nextToken();
                    environmentVariable.setValue(StringJsonUnmarshaller
                            .getInstance().unmarshall(context));
                }
                if (context.testExpression("Secure", targetDepth)) {
                    context.nextToken();
                    environmentVariable.setSecure(BooleanJsonUnmarshaller
                            .getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null
                        || context.getLastParsedParentElement().equals(
                                currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return environmentVariable;
    }

    private static EnvironmentVariableJsonUnmarshaller instance;

    public static EnvironmentVariableJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new EnvironmentVariableJsonUnmarshaller();
        return instance;
    }
}


text:
<?php $field instanceof GDO_Object; $id = 'gwfac_'.$field->name; ?>
<md-input-container
 ng-controller="GWFAutoCompleteCtrl"
 ng-init='init(<?php echo $field->initCompletionJSON(); ?>, "#<?php echo $id; ?>")'
 class="md-block md-float md-icon-left<?php echo $field->classError(); ?>"
 flex>
  <?php if ($field->tooltip) : ?>
  <md-tooltip md-direction="right"><?php echo htmlspecialchars($field->tooltip); ?></md-tooltip>
  <?php endif; ?>
  <?php echo $field->htmlIcon(); ?>
  <md-autocomplete
   md-clear-button="true"
   md-floating-label="<?php echo $field->displayLabel(); ?>"
   md-search-text="data.searchText"
   md-items="item in query(data.searchText)"
   md-item-text="item.text"
   md-selected-item="selectedItem"
   md-selected-item-change="objectSelected(selectedItem)"
   md-min-length="0"
   <?php echo $field->htmlRequired(); ?>
   <?php echo $field->htmlDisabled(); ?>>

    <md-item-template>

    </md-item-template>
    <md-not-found><?php l('no_match'); ?></md-not-found>
  </md-autocomplete>
  <input
   type="hidden"
   id="<?php echo $id; ?>"
   name="form[<?php echo $field->name; ?>]"
   value="<?php echo $field->displayFormValue(); ?>" />

<?php echo $field->displayError(); ?>

</md-input-container>


text:
package dk.ralu.springtutorial.bean;

import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RandomWordGenerator {

    private static final Logger LOGGER = LoggerFactory.getLogger(RandomWordGenerator.class);

    @PostConstruct
    private void postConstruct() {
        LOGGER.info("Created " + getClass().getCanonicalName());
    }

    String generateGreetingWord() {
        return Math.random() < 0.5 ? "Hi" : "Hello";
    }

    String generateLocationWord() {
        return Math.random() < 0.5 ? "World" : "Universe";
    }
}


text:
#!/usr/bin/php
<?php

define('Rabbit_PATH', 		realpath(dirname(__FILE__)).'/../../main/php/Rabbit');

$paths = array(	get_include_path(),
				Rabbit_PATH,
				realpath(dirname(__FILE__)).'/../../main/php',
				realpath(dirname(__FILE__)).'/../../../target/phpinc',
				'.');
set_include_path(implode(PATH_SEPARATOR, $paths));
define('ENVIRONMENT_UNIT_TEST', 'unit-test');
defined('APPLICATION_ENV')		or define('APPLICATION_ENV', 	ENVIRONMENT_UNIT_TEST);
defined('APPLICATION_PATH') 	or define('APPLICATION_PATH', 	realpath(dirname(__FILE__)).'/../../main/php/Rabbit');

require_once "Zend/Loader/Autoloader.php";
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('PHPUnit_');
$autoloader->registerNamespace('Zend_');
$autoloader->registerNamespace('Rabbit_');

$arrOptions = array(  "host"    => "localhost"
                   ,  "vhost"   => "/CANDDi"
                   ,  "port"    => 5672
                   ,  "username"=> "CANDDi"
                   ,  "password"=> "abc123");

$EXCHANGE 		  = 'WebAnalytics-fan1';
$msg_body       = isset($argv[1])?$argv[1]:"quit";
$ROUTING		    = isset($argv[2])?$argv[2]:null;

$rabbitConn     = new Rabbit_Connection($arrOptions);
$rabbitExchange = $rabbitConn->getExchange($EXCHANGE, Rabbit_Exchange::EXCHANGE_TYPE_FANOUT);

$msg            = new Rabbit_Message($msg_body, array('content_type' => 'text/plain'));
$rabbitExchange->publish($msg, $ROUTING);
$rabbitConn->close();


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Coverage Report</title>
<link title="Style" type="text/css" rel="stylesheet" href="css/main.css"/>

Coverage Report - au.gov.amsa.streams.Ob

  Classes in this File	  Line Coverage	  Branch Coverage	  Complexity

Ob

0%

0/2

N/A

N/A

	1.0;1

   1

 package au.gov.amsa.streams;

   2

   3

 import rx.Observable;

   4

   5	   0
 public class Ob {

   6

   7

         // TODO move this class to rxjava-extras

   8

   9

         public static <T> Observable<T> justOne(T t) {

   10	   0
                 return Observable.unsafeCreate(new OnSubscribeJustOneWithBackpressure<T>(t));

   11

         }

   12

   13

 }

Report generated by Cobertura 2.1.1 on 9/11/20 4:00 PM.


text:
"""
Plots and saves the 2D pressure field from a PetIBM simulation at saved
time-steps.
"""

from snake.petibm.simulation import PetIBMSimulation

simulation = PetIBMSimulation()
simulation.read_grid()

for time_step in simulation.get_time_steps():
  simulation.read_fields('pressure', time_step)
  simulation.plot_contour('pressure',
                          field_range=(-1.0, 0.5, 101),
                          filled_contour=True,
                          view=[-15.0, -15.0, 15.0, 15.0],
                          style='mesnardo',
                          cmap='viridis',
                          save_name='pressure',
                          width=8.0)


text:
<?php
    require_once __DIR__."/MessageKeys.php";
    require_once __DIR__."/../kdf/DerivedMessageSecrets.php";
    class ChainKey{

        const MESSAGE_KEY_SEED    = "\x01";
        const CHAIN_KEY_SEED      = "\x02";
        protected $kdf;
        protected $key;
        protected $index;
        public function ChainKey($kdf, $key, $index){
            $this->kdf = $kdf;
            $this->key = $key;
            $this->index = $index;
        }
        public function getKey(){
            return $this->key;
        }

        public function getIndex(){
            return $this->index;
        }
        public function getNextChainKey(){
            $nextKey = $this->getBaseMaterial(self::CHAIN_KEY_SEED);
            return new ChainKey($this->kdf, $nextKey, $this->index + 1);
        }
        public function getMessageKeys(){
            $inputKeyMaterial = $this->getBaseMaterial(self::MESSAGE_KEY_SEED);
            $keyMaterialBytes = $this->kdf->deriveSecrets($inputKeyMaterial, "WhisperMessageKeys", DerivedMessageSecrets::SIZE);
            $keyMaterial = new DerivedMessageSecrets($keyMaterialBytes);
            return new MessageKeys($keyMaterial->getCipherKey(), $keyMaterial->getMacKey(), $keyMaterial->getIv(), $this->index);
        }
        public function getBaseMaterial($seedBytes){
            $mac =  hash_init("sha256",HASH_HMAC,$this->key);
            hash_update($mac,$seedBytes);
            $data = hash_final($mac,true);
            return $data;
        }

    }

?>


text:
import { Action } from 'redux-actions';

import { ObjectHelper } from '../../Utility/Helpers';
import { IAppState } from '../../State/AppState';

const actionWrapper = <TState>(state: TState,
    action: Action<any>,
    func: (newState: TState, action: Action<any>) => void) => {

    const newState = ObjectHelper.deepClone(state);
    func(newState, action);
    return newState;
};

const reduxHelper = {
    actionWrapper
};

export {
    reduxHelper as ReduxHelper
}


text:
package com.intellij.util.ui;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * User: Vassiliy.Kudryashov
 */
public class TwoColorsIcon extends EmptyIcon {
  @NotNull private final Paint myColor1;
  @NotNull private final Paint myColor2;
  private static final int SQUARE_SIZE = 6;
  private static final BufferedImage CHESS_IMAGE = UIUtil.createImage(SQUARE_SIZE, SQUARE_SIZE, BufferedImage.TYPE_INT_RGB);
  static {
    Graphics2D graphics = CHESS_IMAGE.createGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    graphics.setColor(Color.LIGHT_GRAY);
    graphics.fillRect(0, 0, SQUARE_SIZE + 1, SQUARE_SIZE + 1);
    graphics.setColor(Color.GRAY);
    graphics.fillRect(0, 0, SQUARE_SIZE / 2, SQUARE_SIZE / 2);
    graphics.fillRect(SQUARE_SIZE / 2, SQUARE_SIZE / 2, SQUARE_SIZE / 2, SQUARE_SIZE / 2);
  }
  private TexturePaint CHESS = new TexturePaint(CHESS_IMAGE, new Rectangle(0, 0, SQUARE_SIZE, SQUARE_SIZE));

  public TwoColorsIcon(int size, @Nullable Color color1, @Nullable Color color2) {
    super(size, size);
    myColor1 = color1 != null ? color1 : CHESS;
    myColor2 = color2 != null ? color2 : CHESS;
  }

  @Override
  public void paintIcon(final Component component, final Graphics g, final int x, final int y) {
    Graphics2D g2d = (Graphics2D)g.create();
    try {
      final int w = getIconWidth();
      final int h = getIconHeight();
      GraphicsUtil.setupAAPainting(g2d);
      g2d.setPaint(myColor1);
      g2d.fillPolygon(new int[]{x, x + w, x}, new int[]{y, y, y + h}, 3);
      g2d.setPaint(myColor2);
      g2d.fillPolygon(new int[]{x + w, x + w, x}, new int[]{y, y + h, y + h}, 3);
    }
    catch (Exception e) {
      g2d.dispose();
    }
  }

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

    TwoColorsIcon icon = (TwoColorsIcon)o;

    if (getIconWidth() != icon.getIconWidth()) return false;
    if (getIconHeight() != icon.getIconHeight()) return false;
    if (!myColor1.equals(icon.myColor1)) return false;
    if (!myColor2.equals(icon.myColor2)) return false;
    return true;
  }

  @Override
  public int hashCode() {
    int result = super.hashCode();
    result = 31 * result + myColor1.hashCode();
    result = 31 * result + myColor2.hashCode();
    return result;
  }
}


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

    <TextView
            android:id="@android:id/text1"
            style="?android:attr/dropDownItemStyle"
            android:textAppearance="?android:attr/textAppearanceLargePopupMenu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="?attr/standardPadding"
            android:paddingLeft="?attr/standardPadding"
            android:paddingRight="?attr/standardPadding"
    />

    <TextView
            android:id="@android:id/text2"
            style="?android:attr/textAppearanceSmall"
            android:textAppearance="?android:attr/textAppearanceLargePopupMenu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="?attr/standardPadding"
            android:paddingRight="?attr/standardPadding"
            android:paddingBottom="?attr/standardPadding"
    />
</LinearLayout>


text:
function [inst_rate,t] = NWepanechnikovKernelRegrRaster(time,raster,pop,kwidth,Ts,flag_interp)

%  Nadaraya-Watson smoothing kernel regression of a rastergram using a Epanechnikov kernel

  if nargin < 6
    flag_interp = 0; % set this to 1 if you want to interpolate to the previous sampling frequency 1/(dsfact*dt)
  end

  if isempty(pop)
    pop = unique(raster(:,2));
  end

  cumSpikesPop_dt = zeros(size(time));
  for  iter_dt = 1:length(time)
    raster_dt = raster(raster(:,1)==time(iter_dt),:);
    cumSpikesPop_dt(iter_dt) = sum(ismember(raster_dt(:,2),pop));
  end
  interval = time(end)-time(1);
  ncells = length(pop);
  rate = sum(cumSpikesPop_dt)/interval/ncells;

  x = time;
  y = cumSpikesPop_dt;
  h = kwidth;
  % rcontrol = eksr(x,y,h);
  % rcontrol.fnorm = rcontrol.f/mean(rcontrol.f)*rate;

  % (down-)sampling spike times to Fs = 1/Ts (e.g. 1 kHz) because the kernel regression takes too long for small dt otherwise
  t = 0:Ts:max(time)+Ts;
  t = t(nearest(t,min(time))):Ts:t(nearest(t,max(time)));
  try
    dt = time(2)-time(1);
    cumSpikesPop_dt = resample(cumSpikesPop_dt,1,round(Ts/dt),2);
  catch
    time = double(time);
    dt = time(2)-time(1);
    cumSpikesPop_dt = resample(cumSpikesPop_dt,1,round(Ts/dt),2);
  end

%    if ~exist('t','var')
%      t = time;
%      flag_interp = 0;
%    end

  x = t;
  y = cumSpikesPop_dt;
  h = kwidth;
  r = eksr(x,y,h);
  r.fnorm = r.f/mean(r.f)*rate;
  % if min(r.fnorm) < 0
  %   r.fnorm = r.fnorm - min(r.fnorm);
  % end

  if ~exist('scalingFig','var')
    scalingFig = 2;
  end

  if flag_interp
    inst_rate = interp1(t,r.fnorm,time,'pchip');
    t = time;
  else
    inst_rate = r.fnorm;
    t = r.x;
  end

%    figure('color','none','visible','off')
%    hold on
%    set(gca,'layer','top','color','none')
%    plot(time,rcontrol.fnorm,'-','color',[0,0.6,1],'linewidth',1*scalingFig)
%    plot(t,r.fnorm,'-','color',[1,0.4,0.4],'linewidth',1*scalingFig)
%    title('Gaussian kernel regression','fontSize',16*scalingFig)
%    xlabel('Time (s)','fontSize',16*scalingFig)
%    ylabel('Instantaneous firing rate','fontSize',16*scalingFig)
%    set(gca,'fontSize',16*scalingFig,'LineWidth',1*scalingFig,'TickDir','out','Box','off')
%    plot2svg('gaussRegr.svg')
%
%    if flag_interp
%      figure('color','none','visible','off')
%      hold on
%      set(gca,'layer','top','color','none')
%      plot(time,inst_rate,'-','color',[0,0.6,1],'linewidth',1*scalingFig)
%      plot(t,r.fnorm,'-','color',[1,0.4,0.4],'linewidth',1*scalingFig)
%      title('Gaussian kernel regression vs interpolated curve','fontSize',16*scalingFig)
%      xlabel('Time (s)','fontSize',16*scalingFig)
%      ylabel('Instantaneous firing rate','fontSize',16*scalingFig)
%      set(gca,'fontSize',16*scalingFig,'LineWidth',1*scalingFig,'TickDir','out','Box','off')
%      plot2svg('gaussRegrVSinterpCurve.svg')
%
%      figure('color','none','visible','off')
%      hold on
%      set(gca,'layer','top','color','none')
%      plot(time,inst_rate-rcontrol.fnorm,'-','color',[1,0.4,0.4],'linewidth',1*scalingFig)
%      title('Diff Gaussian kernel regression','fontSize',16*scalingFig)
%      xlabel('Time (s)','fontSize',16*scalingFig)
%      ylabel('Instantaneous firing rate','fontSize',16*scalingFig)
%      set(gca,'fontSize',16*scalingFig,'LineWidth',1*scalingFig,'TickDir','out','Box','off')
%      plot2svg('diffGaussRegrVSinterpCurve.svg')
%    end
end


text:
#ifndef QEVENT_P_H
#define QEVENT_P_H

#include <QtCore/qglobal.h>
#include <QtCore/qurl.h>
#include <QtGui/qevent.h>

QT_BEGIN_NAMESPACE

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

class QTouchEventTouchPointPrivate
{
public:
    inline QTouchEventTouchPointPrivate(int id)
        : ref(1),
          id(id),
          state(Qt::TouchPointReleased),
          pressure(qreal(-1.))
    { }

    inline QTouchEventTouchPointPrivate *detach()
    {
        QTouchEventTouchPointPrivate *d = new QTouchEventTouchPointPrivate(*this);
        d->ref.store(1);
        if (!this->ref.deref())
            delete this;
        return d;
    }

    QAtomicInt ref;
    int id;
    Qt::TouchPointStates state;
    QRectF rect, sceneRect, screenRect;
    QPointF normalizedPos,
            startPos, startScenePos, startScreenPos, startNormalizedPos,
            lastPos, lastScenePos, lastScreenPos, lastNormalizedPos;
    qreal pressure;
    QVector2D velocity;
    QTouchEvent::TouchPoint::InfoFlags flags;
    QVector<QPointF> rawScreenPositions;
};

#ifndef QT_NO_TABLETEVENT
class QTabletEventPrivate
{
public:
    inline QTabletEventPrivate(Qt::MouseButton button, Qt::MouseButtons buttons)
        : b(button),
          buttonState(buttons)
    { }

    Qt::MouseButton b;
    Qt::MouseButtons buttonState;
};
#endif // QT_NO_TABLETEVENT

QT_END_NAMESPACE

#endif // QEVENT_P_H


text:
class ApplicationController < ActionController::Base
  include Slimmer::Template

  protect_from_forgery with: :exception

  rescue_from GdsApi::HTTPForbidden, with: :error_403
  rescue_from GdsApi::TimedOutException, with: :error_503

  slimmer_template "core_layout"

  before_action :set_cors_headers, if: :json_request?

  if ENV["BASIC_AUTH_USERNAME"]
    http_basic_authenticate_with(
      name: ENV.fetch("BASIC_AUTH_USERNAME"),
      password: ENV.fetch("BASIC_AUTH_PASSWORD"),
    )
  end

protected

  def error_403
    render status: :forbidden, plain: "403 forbidden"
  end

  def error_503(exception)
    GovukError.notify(exception) if exception && defined? GovukError
    render status: :service_unavailable, plain: "503 service unavailable"
  end

  def set_expiry(age = 60.minutes)
    expires_in age, public: true unless Rails.env.development?
  end

  def set_cors_headers
    # Calendars only does GET requests, so it's safe to allow CORS for all
    # requests.
    headers["Access-Control-Allow-Origin"] = "*"
  end

  def json_request?
    request.format.symbol == :json
  end
end


text:
using System.Windows;

namespace ChartsTest.Line_Examples
{
    public partial class BasicLine
    {
        public BasicLine()
        {
            InitializeComponent();
        }

        private void BasicLine_OnLoaded(object sender, RoutedEventArgs e)
        {
            //this is just to see animation everytime you click next
            Chart.ClearAndPlot();
        }
    }
}


text:
package net.trustyuri.rdf;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.rdf4j.model.BNode;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.rio.RDFHandler;
import org.eclipse.rdf4j.rio.RDFHandlerException;

public class HashAdder implements RDFHandler {

	private IRI baseURI;
	private String artifactCode;
	private RDFHandler handler;
	private Map<String,String> ns;
	private Map<IRI,IRI> transformMap;

	public HashAdder(IRI baseURI, String artifactCode, RDFHandler handler, Map<String,String> ns) {
		this.baseURI = baseURI;
		this.artifactCode = artifactCode;
		this.handler = handler;
		this.ns = ns;
		if (ns == null) {
			this.ns = new HashMap<String,String>();
		}
		transformMap = new HashMap<IRI,IRI>();
	}

	@Override
	public void startRDF() throws RDFHandlerException {
		handler.startRDF();
		if (ns.get("this") != null) handler.handleNamespace("this", ns.get("this"));
		if (ns.get("sub") != null) handler.handleNamespace("sub", ns.get("sub"));
		if (ns.get("node") != null) handler.handleNamespace("node", ns.get("node"));
	}

	@Override
	public void endRDF() throws RDFHandlerException {
		handler.endRDF();
	}

	@Override
	public void handleNamespace(String prefix, String uri) throws RDFHandlerException {
		if (baseURI != null && baseURI.toString().equals(uri)) {
			return;
		}
		handler.handleNamespace(prefix, uri);
	}

	@Override
	public void handleStatement(Statement st) throws RDFHandlerException {
		Resource context = transform(st.getContext());
		Resource subject = transform(st.getSubject());
		IRI predicate = transform(st.getPredicate());
		Value object = st.getObject();
		if (object instanceof Resource) {
			object = transform((Resource) object);
		}
		Statement n = SimpleValueFactory.getInstance().createStatement(subject, predicate, object, context);
		handler.handleStatement(n);
	}

	@Override
	public void handleComment(String comment) throws RDFHandlerException {
		handler.handleComment(comment);
	}

	private IRI transform(Resource r) {
		if (r == null) {
			return null;
		} else if (r instanceof BNode) {
			throw new RuntimeException("Unexpected blank node encountered");
		} else {
			IRI transformedURI = SimpleValueFactory.getInstance().createIRI(r.toString().replace(" ", artifactCode));
			transformMap.put((IRI) r, transformedURI);
			return transformedURI;
		}
	}

	public Map<IRI,IRI> getTransformMap() {
		return transformMap;
	}

}


text:
"""Program to take screenshot from a MS Word Document
"""

import os
import shutil
import win32com.client
import pythoncom
import wx
import win32con
import win32gui

def window_enumeration_handler(hwnd, top_windows):
  """Handles window enumeration
  """
  top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))

def take_screenshot():
  """Take screenshot from the MS word document
  """
  pythoncom.CoInitialize()
  root_path = os.path.dirname(os.getcwd())
  path_to_file = ".\\data\\sample.docx"
  if os.path.exists(path_to_file):
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = 1
    word.Documents.Open(os.path.abspath(path_to_file))
    top_windows = []
    win32gui.EnumWindows(window_enumeration_handler, top_windows)
    # Select the word document tab and bring it to foreground
    # also maximise the word document
    for window in top_windows:
      if " - Word" in window[1]:
        win32gui.ShowWindow(window[0], win32con.SW_MAXIMIZE)
        win32gui.SetForegroundWindow(window[0])
        break
    app = wx.App()
    screen = wx.ScreenDC()
    size = screen.GetSize()
    bmp = wx.Bitmap(size[0], size[1])
    mem = wx.MemoryDC(bmp)
    mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
    del mem  # Release bitmap
    bmp.SaveFile("screenshot.png", wx.BITMAP_TYPE_PNG)
    word.Quit()
    del word
    dest_path = ".\\output\\screenshot.png"
    shutil.move(".\\screenshot.png", dest_path)
    print("Action successfully executed")

if __name__ == "__main__":
  take_screenshot()


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module Text.RE.Types.LineNo where

-- | our line numbers are of the proper zero-based kind
newtype LineNo =
    ZeroBasedLineNo { getZeroBasedLineNo :: Int }
  deriving (Show,Enum)

-- | the first line in a file
firstLine :: LineNo
firstLine = ZeroBasedLineNo 0

-- | extract a conventional 1-based line number
getLineNo :: LineNo -> Int
getLineNo = succ . getZeroBasedLineNo

-- | inject a conventional 1-based line number
lineNo :: Int -> LineNo
lineNo = ZeroBasedLineNo . pred


text:
FOLDERS=`ls -d vendor/*/`
BRANCH="master"
REMOTE="origin"

for FILE in $FOLDERS
do
	echo "Process $FILE bundle"
	echo "================================================================"
	cd $FILE
	git fetch --all
	git checkout $BRANCH
	git pull $REMOTE $BRANCH
	cd ../..
done


text:
@extends('admin.template')

@section('title')
  {{ ucfirst($action) . ' ' . $repository->getSingular() }}
@endsection

@section('css')
@endsection

@section('js')
@endsection

@section('content')
  @if ($action == 'edit')

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

  @endif

          getIndexURL() }}">

            Back to index

{{ ucfirst($action) . ' ' . $repository->getSingular() }}

        @if ($action == 'edit')
          {!! Form::model($model) !!}
        @elseif ($action == 'add')
          {!! Form::open() !!}
        @endif
          @if ($action == 'edit')

Update Details

          @endif
          @php
            $cols = $repository->getCols();
          @endphp
          @include('admin.crud._cols', ['cols' => $cols])
          @if ($action == 'add')
            @include('admin.crud.users._password-info')
            has('password')) ? 'is-invalid-label' : '' }}">
              Password
              <input type="password" name="password" placeholder="Password" class="{{ ($errors->has('password')) ? 'is-invalid-input' : '' }}" required>
              @foreach ($errors->get('password') as $error)

                  {!! $error !!}

              @endforeach

              Confirm Password
              <input type="password" name="password_confirmation" placeholder="Confirm Password" required>

          @endif

              <button type="submit" class="button small">
                Save
              </button>

        {!! Form::close() !!}

        @if ($action == 'edit')
          <form action="{{ route('admin.users.edit.password', $model->hash) }}" method="POST" autocomplete="off">
            {{ csrf_field() }}

Update Password

              @include('admin.crud.users._password-info')
              has('password')) ? 'is-invalid-label' : '' }}">
                New Password
                <input type="password" name="password" placeholder="New Password" class="{{ ($errors->has('password')) ? 'is-invalid-input' : '' }}" required>
                @foreach ($errors->get('password') as $error)

                    {!! $error !!}

                @endforeach

                Confirm New Password
                <input type="password" name="password_confirmation" placeholder="Confirm New Password" required>

              <button type="submit" class="button small">
                Update Password
              </button>

          </form>
        @endif

          getIndexURL() }}">

            Back to index

@endsection


text:
<?php

namespace CityIndex\CIAPI\Test;
require_once 'CIAPIIntegrationTestCase.php';

use CityIndex\CIAPI\Core\CIAPIClient;
use CityIndex\CIAPI\Core\SessionException;
use CityIndex\CIAPI\DTO\AccountInformationResponseDTO;

class AccountInformationTest extends CIAPIIntegrationTestCase {
	static private $ctx;

	public static function setUpBeforeClass() {
		parent::initializeEnvironment();
		self::$ctx = new CIAPIClient(self::$endpoint, self::$appKey, self::$appVersion);
		self::$ctx->logIn(self::$userName, self::$password);
	}

	public static function tearDownAfterClass() {
		self::$ctx->logOut();
	}

	/**
	 * @test
	 */
	public function getAccountInformation() {
		$this->assertNotNull(self::$ctx->getSession());
		$response = self::$ctx->getAccountInformation();
		$this->assertInstanceOf('CityIndex\CIAPI\DTO\AccountInformationResponseDTO', $response);
		$this->assertNotEmpty($response->logonUserName);
		$this->assertNotEmpty($response->clientAccountId);
		$this->assertNotEmpty($response->clientAccountCurrency);
		$this->assertNotEmpty($response->accountOperatorId);
		foreach ($response->tradingAccounts as $tradingAccount) {
			$this->assertInstanceOf('CityIndex\CIAPI\DTO\ApiTradingAccountDTO', $tradingAccount);
			$this->assertNotEmpty($tradingAccount->tradingAccountId);
			$this->assertNotEmpty($tradingAccount->tradingAccountCode);
			$this->assertNotEmpty($tradingAccount->tradingAccountStatus);
			$this->assertNotEmpty($tradingAccount->tradingAccountType);
		}
	}
}


text:
/*
 * @test
 * @bug 8026213
 * @summary Reflection support for private methods in interfaces
 * @author  Robert Field
 * @run main TestPrivateInterfaceMethodReflect
 */

import java.lang.reflect.*;

import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.MethodVisitor;
import jdk.internal.org.objectweb.asm.Opcodes;

public class TestPrivateInterfaceMethodReflect {

    static final String INTERFACE_NAME = "PrivateInterfaceMethodReflectTest_Interface";
    static final String CLASS_NAME = "PrivateInterfaceMethodReflectTest_Class";
    static final int EXPECTED = 1234;

    static class TestClassLoader extends ClassLoader implements Opcodes {

        @Override
        public Class findClass(String name) throws ClassNotFoundException {
            byte[] b;
            try {
                b = loadClassData(name);
            } catch (Throwable th) {
                // th.printStackTrace();
                throw new ClassNotFoundException("Loading error", th);
            }
            return defineClass(name, b, 0, b.length);
        }

        private byte[] loadClassData(String name) throws Exception {
            ClassWriter cw = new ClassWriter(0);
            MethodVisitor mv;
            switch (name) {
                case INTERFACE_NAME:
                    cw.visit(V1_8, ACC_ABSTRACT | ACC_INTERFACE | ACC_PUBLIC, INTERFACE_NAME, null, "java/lang/Object", null);
                    {
                        mv = cw.visitMethod(ACC_PRIVATE, "privInstance", "()I", null, null);
                        mv.visitCode();
                        mv.visitLdcInsn(EXPECTED);
                        mv.visitInsn(IRETURN);
                        mv.visitMaxs(1, 1);
                        mv.visitEnd();
                    }
                    break;
                case CLASS_NAME:
                    cw.visit(52, ACC_SUPER | ACC_PUBLIC, CLASS_NAME, null, "java/lang/Object", new String[]{INTERFACE_NAME});
                    {
                        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
                        mv.visitCode();
                        mv.visitVarInsn(ALOAD, 0);
                        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
                        mv.visitInsn(RETURN);
                        mv.visitMaxs(1, 1);
                        mv.visitEnd();
                    }
                    break;
                default:
                    break;
            }
            cw.visitEnd();

            return cw.toByteArray();
        }
    }

    public static void main(String[] args) throws Exception {
        TestClassLoader tcl = new TestClassLoader();
        Class<?> itf = tcl.loadClass(INTERFACE_NAME);
        Class<?> k = tcl.loadClass(CLASS_NAME);
        Object inst = k.newInstance();
        Method[] meths = itf.getDeclaredMethods();
        if (meths.length != 1) {
            throw new Exception("Expected one method in " + INTERFACE_NAME + " instead " + meths.length);
        }

        Method m = meths[0];
        int mod = m.getModifiers();
        if ((mod & Modifier.PRIVATE) == 0) {
            throw new Exception("Expected " + m + " to be private");
        }
        if ((mod & Modifier.STATIC) != 0) {
            throw new Exception("Expected " + m + " to be instance method");
        }

        m.setAccessible(true);
        for (int i = 1; i < 200; i++) {
            if (!m.invoke(inst).equals(EXPECTED)) {
                throw new Exception("Expected " + EXPECTED + " from " + m);
            }
        }

        System.out.println("Passed.");
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Ozellestirilmis Progressbar</string>
    <string name="app_name">Ozellestirilmis Progressbar</string>
</resources>


text:
<?php

namespace Bolt\Twig\Runtime;

use Bolt\Users;
use Symfony\Component\VarDumper\Cloner\ClonerInterface;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
use Twig\Environment;
use Twig\Template;

/**
 * Twig Bridge's DumpExtension's runtime logic with custom enabled check.
 * Also, backtrace function.
 *
 * @author Carson Full <carsonfull@gmail.com>
 */
class DumpRuntime
{
    /** @var ClonerInterface */
    private $cloner;
    /** @var HtmlDumper */
    private $dumper;

    /** @var Users */
    private $users;
    /** @var bool */
    private $debugShowLoggedoff;

    /**
     * Constructor.
     *
     * @param ClonerInterface $cloner
     * @param HtmlDumper      $dumper
     * @param Users           $users
     * @param bool            $debugShowLoggedoff
     */
    public function __construct(ClonerInterface $cloner, HtmlDumper $dumper, Users $users, $debugShowLoggedoff)
    {
        $this->cloner = $cloner;
        $this->dumper = $dumper;
        $this->users = $users;
        $this->debugShowLoggedoff = $debugShowLoggedoff;
    }

    /**
     * @param Environment $env
     * @param mixed       $context
     *
     * @return bool|null|string
     */
    public function dump(Environment $env, $context)
    {
        if (!$this->isEnabled($env)) {
            return null;
        }

        if (func_num_args() === 2) {
            $vars = [];
            foreach ($context as $key => $value) {
                if (!$value instanceof Template) {
                    $vars[$key] = $value;
                }
            }

            $vars = [$vars];
        } else {
            $vars = func_get_args();
            unset($vars[0], $vars[1]);
        }

        $output = fopen('php://memory', 'r+b');
        $this->dumper->setCharset($env->getCharset());

        foreach ($vars as $value) {
            $this->dumper->dump($this->cloner->cloneVar($value), $output);
        }

        return stream_get_contents($output, -1, 0);
    }

    /**
     * Output pretty-printed backtrace.
     *
     * @param Environment $env
     * @param array       $context
     * @param int         $depth
     *
     * @return string|null
     */
    public function dumpBacktrace(Environment $env, $context, $depth)
    {
        if (!$this->isEnabled($env)) {
            return null;
        }

        return $this->dump($env, $context, debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, $depth));
    }

    /**
     * @param Environment $env
     *
     * @return bool
     */
    protected function isEnabled(Environment $env)
    {
        return $env->isDebug() && ($this->debugShowLoggedoff || $this->users->getCurrentUser() !== null);
    }
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S15.1.1.3_A2_T2;
 * @section: 15.1.1.3, 11.4.3;
 * @assertion: The undefined is not ReadOnly;
 * @description: Checking typeof Operator;
*/

// CHECK#1
undefined = true;
if (typeof(undefined) !== "boolean") {
	ERROR('#1: undefined = true; typeof(undefined) === "boolean". Actual: ' + (typeof(undefined)));
}


text:
module Nokogiri
  module XML
    ###
    # This class provides information about XML SyntaxErrors.  These
    # exceptions are typically stored on Nokogiri::XML::Document#errors.
    class SyntaxError < ::Nokogiri::SyntaxError
      ###
      # return true if this is a non error
      def none?
        level == 0
      end

      ###
      # return true if this is a warning
      def warning?
        level == 1
      end

      ###
      # return true if this is an error
      def error?
        level == 2
      end

      ###
      # return true if this error is fatal
      def fatal?
        level == 3
      end

      alias :to_s :message
    end
  end
end


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Lines;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input.Events;
using osu.Framework.Testing;
using osuTK;
using osuTK.Graphics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;

namespace osu.Framework.Tests.Visual.TestCaseUserInterface
{
    public class TestCaseDrawablePath : GridTestCase
    {
        public TestCaseDrawablePath()
            : base(3, 2)
        {
            const int width = 20;
            Texture gradientTexture = new Texture(width, 1, true);
            var image = new Image<Rgba32>(width, 1);

            for (int i = 0; i < width; ++i)
            {
                var brightnessByte = (byte)((float)i / (width - 1) * 255);
                image[i, 0] = new Rgba32(brightnessByte, brightnessByte, brightnessByte);
            }

            gradientTexture.SetData(new TextureUpload(image));

            Cell(0).AddRange(new[]
            {
                createLabel("Simple path"),
                new TexturedPath
                {
                    RelativeSizeAxes = Axes.Both,
                    Vertices = new List<Vector2> { Vector2.One * 50, Vector2.One * 100 },
                    Texture = gradientTexture,
                    Colour = Color4.Green,
                },
            });

            Cell(1).AddRange(new[]
            {
                createLabel("Curved path"),
                new TexturedPath
                {
                    RelativeSizeAxes = Axes.Both,
                    Vertices = new List<Vector2>
                    {
                        new Vector2(50, 50),
                        new Vector2(50, 150),
                        new Vector2(150, 150),
                        new Vector2(150, 50),
                        new Vector2(50, 50),
                    },
                    Texture = gradientTexture,
                    Colour = Color4.Blue,
                },
            });

            Cell(2).AddRange(new[]
            {
                createLabel("Self-overlapping path"),
                new TexturedPath
                {
                    RelativeSizeAxes = Axes.Both,
                    Vertices = new List<Vector2>
                    {
                        new Vector2(50, 50),
                        new Vector2(50, 150),
                        new Vector2(150, 150),
                        new Vector2(150, 100),
                        new Vector2(20, 100),
                    },
                    Texture = gradientTexture,
                    Colour = Color4.Red,
                },
            });

            Cell(3).AddRange(new[]
            {
                createLabel("Smoothed path"),
                new SmoothPath
                {
                    RelativeSizeAxes = Axes.Both,
                    PathWidth = 5,
                    Vertices = new List<Vector2>
                    {
                        new Vector2(50, 50),
                        new Vector2(125, 100),
                    },
                    Colour = Color4.White,
                }
            });

            Cell(4).AddRange(new[]
            {
                createLabel("un-smoothed path"),
                new Path
                {
                    RelativeSizeAxes = Axes.Both,
                    PathWidth = 5,
                    Vertices = new List<Vector2>
                    {
                        new Vector2(50, 50),
                        new Vector2(125, 100),
                    },
                    Colour = Color4.White,
                }
            });

            Cell(5).AddRange(new[]
            {
                createLabel("Draw something ;)"),
                new UserDrawnPath
                {
                    RelativeSizeAxes = Axes.Both,
                    Texture = gradientTexture,
                    Colour = Color4.White,
                },
            });
        }

        private Drawable createLabel(string text) => new SpriteText
        {
            Text = text,
            Font = new FontUsage(size: 20),
            Colour = Color4.White,
        };

        private class UserDrawnPath : TexturedPath
        {
            private Vector2 oldPos;

            protected override bool OnDragStart(DragStartEvent e)
            {
                AddVertex(e.MousePosition);
                oldPos = e.MousePosition;
                return true;
            }

            protected override bool OnDrag(DragEvent e)
            {
                Vector2 pos = e.MousePosition;
                if ((pos - oldPos).Length > 10)
                {
                    AddVertex(pos);
                    oldPos = pos;
                }

                return base.OnDrag(e);
            }
        }
    }
}


text:
#include "Gwen/ToolTip.h"
#include "Gwen/Utility.h"

using namespace Gwen;

#ifdef _MSC_VER
	#pragma warning(disable:4267)// conversion from 'size_t' to 'int', possible loss of data
#endif

#ifdef __MINGW32__
	#undef vswprintf
	#define vswprintf _vsnwprintf
#endif

UnicodeString Gwen::Utility::Format( const wchar_t* fmt, ... )
{
	wchar_t strOut[ 4096 ];

	va_list s;
	va_start( s, fmt );
	vswprintf( strOut, sizeof(strOut), fmt, s );
	va_end(s);

	UnicodeString str = strOut;
	return str;
}

void Gwen::Utility::Strings::Split( const Gwen::String& str, const Gwen::String& seperator, Strings::List& outbits, bool bLeave )
{
	int iOffset = 0;
	int iLength = str.length();
	int iSepLen = seperator.length();

	size_t i = str.find( seperator, 0 );
	while ( i != std::string::npos )
	{
		outbits.push_back( str.substr( iOffset, i-iOffset ) );
		iOffset = i + iSepLen;

		i = str.find( seperator, iOffset );
		if ( bLeave ) iOffset -= iSepLen;
	}

	outbits.push_back( str.substr( iOffset, iLength-iOffset ) );
}

void Gwen::Utility::Strings::Split( const Gwen::UnicodeString& str, const Gwen::UnicodeString& seperator, Strings::UnicodeList& outbits, bool bLeave )
{
	int iOffset = 0;
	int iLength = str.length();
	int iSepLen = seperator.length();

	size_t i = str.find( seperator, 0 );
	while ( i != std::wstring::npos )
	{
		outbits.push_back( str.substr( iOffset, i-iOffset ) );
		iOffset = i + iSepLen;

		i = str.find( seperator, iOffset );
		if ( bLeave ) iOffset -= iSepLen;
	}

	outbits.push_back( str.substr( iOffset, iLength-iOffset ) );
}

int Gwen::Utility::Strings::To::Int( const Gwen::String& str )
{
	if ( str == "" ) return 0;
	return atoi( str.c_str() );
}

float Gwen::Utility::Strings::To::Float( const Gwen::String& str )
{
	if ( str == "" ) return 0.0f;
	return (float)atof( str.c_str() );
}

float Gwen::Utility::Strings::To::Float( const Gwen::UnicodeString& str )
{
	return wcstod( str.c_str(), NULL);
}

bool Gwen::Utility::Strings::To::Bool( const Gwen::String& str )
{
	if ( str.size() == 0 ) return false;
	if ( str[0] == 'T' || str[0] == 't' || str[0] == 'y' || str[0] == 'Y' ) return true;
	if ( str[0] == 'F' || str[0] == 'f' || str[0] == 'n' || str[0] == 'N' ) return false;
	if ( str[0] == '0' ) return false;
	return true;
}

bool Gwen::Utility::Strings::To::Floats( const Gwen::String& str, float* f, size_t iCount )
{
	Strings::List lst;
	Strings::Split( str, " ", lst );
	if ( lst.size() != iCount ) return false;

	for ( size_t i=0; i<iCount; i++ )
	{
		f[i] = Strings::To::Float( lst[i] );
	}

	return true;
}

bool Gwen::Utility::Strings::Wildcard( const TextObject& strWildcard, const TextObject& strHaystack )
{
	const UnicodeString& W = strWildcard.GetUnicode();
	const UnicodeString& H = strHaystack.GetUnicode();

	if ( strWildcard == "*" ) return true;

	int iPos = W.find( L"*", 0 );
	if ( iPos == UnicodeString::npos ) return strWildcard == strHaystack;

	// First half matches
	if ( iPos > 0 && W.substr( 0, iPos ) != H.substr( 0, iPos ) )
		return false;

	// Second half matches
	if ( iPos != W.length()-1 )
	{
		UnicodeString strEnd = W.substr( iPos+1, W.length() );

		if ( strEnd != H.substr( H.length() - strEnd.length(), H.length() ) )
			return false;
	}

	return true;
}

void Gwen::Utility::Strings::ToUpper( Gwen::UnicodeString& str )
{
	transform( str.begin(), str.end(), str.begin(), towupper );
}

void Gwen::Utility::Strings::Strip( Gwen::UnicodeString& str, const Gwen::UnicodeString& chars )
{
	Gwen::UnicodeString Source = str;
	str = L"";

	for ( int i =0; i<Source.length(); i++ )
	{
		if ( chars.find( Source[i] ) != Gwen::UnicodeString::npos )
			continue;

		str += Source[i];
	}
}


text:
<?php

$loader = require dirname(__DIR__).'/vendor/.composer/autoload.php';
$loader->add('dflydev\\tests\\markdown', 'tests');


text:
using namespace llvm;

#define DEBUG_TYPE "dce"

STATISTIC(DIEEliminated, "Number of insts removed by DIE pass");
STATISTIC(DCEEliminated, "Number of insts removed");

namespace {
  //===--------------------------------------------------------------------===//
  // DeadInstElimination pass implementation
  //
  struct DeadInstElimination : public BasicBlockPass {
    static char ID; // Pass identification, replacement for typeid
    DeadInstElimination() : BasicBlockPass(ID) {
      initializeDeadInstEliminationPass(*PassRegistry::getPassRegistry());
    }
    bool runOnBasicBlock(BasicBlock &BB) override {
      if (skipOptnoneFunction(BB))
        return false;
      auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
      TargetLibraryInfo *TLI = TLIP ? &TLIP->getTLI() : nullptr;
      bool Changed = false;
      for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); ) {
        Instruction *Inst = DI++;
        if (isInstructionTriviallyDead(Inst, TLI)) {
          Inst->eraseFromParent();
          Changed = true;
          ++DIEEliminated;
        }
      }
      return Changed;
    }

    void getAnalysisUsage(AnalysisUsage &AU) const override {
      AU.setPreservesCFG();
    }
  };
}

char DeadInstElimination::ID = 0;
INITIALIZE_PASS(DeadInstElimination, "die",
                "Dead Instruction Elimination", false, false)

Pass *llvm::createDeadInstEliminationPass() {
  return new DeadInstElimination();
}

namespace {
  //===--------------------------------------------------------------------===//
  // DeadCodeElimination pass implementation
  //
  struct DCE : public FunctionPass {
    static char ID; // Pass identification, replacement for typeid
    DCE() : FunctionPass(ID) {
      initializeDCEPass(*PassRegistry::getPassRegistry());
    }

    bool runOnFunction(Function &F) override;

    void getAnalysisUsage(AnalysisUsage &AU) const override {
      AU.setPreservesCFG();
    }
 };
}

char DCE::ID = 0;
INITIALIZE_PASS(DCE, "dce", "Dead Code Elimination", false, false)

bool DCE::runOnFunction(Function &F) {
  if (skipOptnoneFunction(F))
    return false;

  auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  TargetLibraryInfo *TLI = TLIP ? &TLIP->getTLI() : nullptr;

  // Start out with all of the instructions in the worklist...
  std::vector<Instruction*> WorkList;
  for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
    WorkList.push_back(&*i);

  // Loop over the worklist finding instructions that are dead.  If they are
  // dead make them drop all of their uses, making other instructions
  // potentially dead, and work until the worklist is empty.
  //
  bool MadeChange = false;
  while (!WorkList.empty()) {
    Instruction *I = WorkList.back();
    WorkList.pop_back();

    if (isInstructionTriviallyDead(I, TLI)) { // If the instruction is dead.
      // Loop over all of the values that the instruction uses, if there are
      // instructions being used, add them to the worklist, because they might
      // go dead after this one is removed.
      //
      for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
        if (Instruction *Used = dyn_cast<Instruction>(*OI))
          WorkList.push_back(Used);

      // Remove the instruction.
      I->eraseFromParent();

      // Remove the instruction from the worklist if it still exists in it.
      WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
                     WorkList.end());

      MadeChange = true;
      ++DCEEliminated;
    }
  }
  return MadeChange;
}

FunctionPass *llvm::createDeadCodeEliminationPass() {
  return new DCE();
}


text:
package org.wso2.developerstudio.eclipse.artifact.analytics.execution.plan.validators;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.wso2.developerstudio.eclipse.artifact.analytics.execution.plan.model.ExecutionPlanModel;
import org.wso2.developerstudio.eclipse.artifact.analytics.execution.plan.utils.ExecutionPlanConstants;
import org.wso2.developerstudio.eclipse.artifact.analytics.utils.AnalyticsProjectArtifactCreator;
import org.wso2.developerstudio.eclipse.artifact.analytics.utils.AnalyticsArtifactModel;
import org.wso2.developerstudio.eclipse.platform.core.exception.FieldValidationException;
import org.wso2.developerstudio.eclipse.platform.core.model.AbstractFieldController;
import org.wso2.developerstudio.eclipse.platform.core.project.model.ProjectDataModel;
import org.wso2.developerstudio.eclipse.platform.ui.validator.CommonFieldValidator;

import java.util.List;

public class ExecutionPlanFieldController extends AbstractFieldController {

	public void validate(String modelProperty, Object value, ProjectDataModel model)
	        throws FieldValidationException {
		if (modelProperty.equals(ExecutionPlanConstants.WIZARD_OPTION_EXECUTIONPLAN_NAME)) {
		     CommonFieldValidator.validateArtifactName(value);
		     if (value != null) {
				String resource = value.toString();
				ExecutionPlanModel executionPlanModel = (ExecutionPlanModel) model;
				if (executionPlanModel != null) {
					IContainer resLocation = executionPlanModel.getExecution_planSaveLocation();
					if (resLocation != null) {
						IProject project = resLocation.getProject();
						AnalyticsProjectArtifactCreator analyticsProjectArtifact = new AnalyticsProjectArtifactCreator();
						try {
							analyticsProjectArtifact.fromFile(project.getFile("artifact.xml").getLocation().toFile());
							List<AnalyticsArtifactModel> allArtifacts = analyticsProjectArtifact.getAllAnalyticsArtifacts();
							for (AnalyticsArtifactModel artifact : allArtifacts) {
								if (resource.equals(artifact.getName())) {
									throw new FieldValidationException("");
								}
							}

						} catch (Exception e) {
							throw new FieldValidationException("Artifact name already exsits");
						}
					}
				}
			}
		} else if (modelProperty.equals(ExecutionPlanConstants.WIZARD_OPTION_EXECUTIONPLAN_IMPORT_LOCATION)) {
			 CommonFieldValidator.validateImportFile(value);
		}  else if (modelProperty.equals(ExecutionPlanConstants.WIZARD_OPTION_EXECUTIONPLAN_SAVE_LOCATION)) {
			IResource resource = (IResource)value;
			if(null== resource || !resource.exists())
				throw new FieldValidationException("Specified project or path doesn't exist");
		}

	}

	public boolean isReadOnlyField(String modelProperty, ProjectDataModel model) {
		boolean readOnlyField = super.isReadOnlyField(modelProperty, model);
		if (modelProperty.equals(ExecutionPlanConstants.WIZARD_OPTION_EXECUTIONPLAN_SAVE_LOCATION)) {
			readOnlyField = true;
		}
	    return readOnlyField;
	}

}


text:
"""A fast but lossy, totally generic object formatter."""

import os
import types

from google.net.proto import ProtocolBuffer

EASY_TYPES = (type(None), int, long, float, bool)
META_TYPES = (type, types.ClassType)
STRING_TYPES = (str, unicode)
CONTAINER_TYPES = {tuple: ('(', ')'),
                   list: ('[', ']'),
                   dict: ('{', '}'),
                   }
BUILTIN_TYPES = EASY_TYPES + STRING_TYPES + tuple(CONTAINER_TYPES)
INSTANCE_TYPE = types.InstanceType

def format_value(val, limit=100, level=10):
    """Wrapper around _format_value()."""
    return _format_value(val, limit, level)

def _format_value(val, limit, level, len=len, repr=repr):
  """Format an arbitrary value as a compact string.

  This is a variant on Python's built-in repr() function, also
  borrowing some ideas from the repr.py standard library module, but
  tuned for speed even in extreme cases (like very large longs or very
  long strings) and safety (it never invokes user code).

  For structured data types like lists and objects it calls itself
  recursively; recursion is strictly limited by level.

  Python's basic types (numbers, strings, lists, tuples, dicts, bool,
  and None) are represented using their familiar Python notations.
  Objects are represented as ClassName<attr1=val1, attr2=val2, ...>.
  Portions omitted due to the various limits are represented using
  three dots ('...').

  Args:
    val: An arbitrary value.
    limit: Limit on the output length.
    level: Recursion level countdown.
    len, repr: Not arguments; for optimization.

  Returns:
    A str instance.
  """

  if level <= 0:
    return '...'

  typ = type(val)

  if typ in EASY_TYPES:
    if typ is float:
      rep = str(val)
    elif typ is long:
      if val >= 10L**99:
        return '...L'
      elif val <= -10L**98:
        return '-...L'
      else:
        rep = repr(val)
    else:
      rep = repr(val)
    if typ is long and len(rep) > limit:
      n1 = (limit - 3) // 2
      n2 = (limit - 3) - n1
      rep = rep[:n1] + '...' + rep[-n2:]
    return rep

  if typ in META_TYPES:
    return val.__name__

  if typ in STRING_TYPES:
    n1 = (limit - 3) // 2
    if n1 < 1:
      n1 = 1
    n2 = (limit - 3) - n1
    if n2 < 1:
      n2 = 1
    if len(val) > limit:
      rep = repr(val[:n1] + val[-n2:])
    else:
      rep = repr(val)
      if len(rep) <= limit:
        return rep
    return rep[:n1] + '...' + rep[-n2:]

  if typ is types.MethodType:
    if val.im_self is None:
      fmt = '<unbound method %s of %s>'
    else:
      fmt = '<method %s of %s<>>'
    if val.im_class is not None:
      return fmt % (val.__name__, val.im_class.__name__)
    else:
      return fmt % (val.__name__, '?')

  if typ is types.FunctionType:
    nam = val.__name__
    if nam == '<lambda>':
      return nam
    else:
      return '<function %s>' % val.__name__

  if typ is types.BuiltinFunctionType:
    if val.__self__ is not None:
      return '<built-in method %s of %s<>>' % (val.__name__,
                                               type(val.__self__).__name__)
    else:
      return '<built-in function %s>' % val.__name__

  if typ is types.ModuleType:
    if hasattr(val, '__file__'):
      return '<module %s>' % val.__name__
    else:
      return '<built-in module %s>' % val.__name__

  if typ is types.CodeType:
    return '<code object %s>' % val.co_name

  if isinstance(val, ProtocolBuffer.ProtocolMessage):
    buf = [val.__class__.__name__, '<']
    limit -= len(buf[0]) + 2
    append = buf.append
    first = True

    dct = getattr(val, '__dict__', None)
    if dct:
      for k, v in sorted(dct.items()):
        if k.startswith('has_') or not k.endswith('_'):
          continue
        name = k[:-1]

        has_method = getattr(val, 'has_' + name, None)
        if has_method is not None:

          if type(has_method) is not types.MethodType or not has_method():
            continue

        size_method = getattr(val, name + '_size', None)
        if size_method is not None:

          if type(size_method) is not types.MethodType or not size_method():
            continue

        if has_method is None and size_method is None:
          continue

        if first:
          first = False
        else:
          append(', ')
        limit -= len(name) + 2
        if limit <= 0:
          append('...')
          break
        append(name)
        append('=')
        rep = _format_value(v, limit, level-1)
        limit -= len(rep)
        append(rep)
    append('>')
    return ''.join(buf)

  dct = getattr(val, '__dict__', None)
  if type(dct) is dict:
    if typ is INSTANCE_TYPE:
      typ = val.__class__
    typnam = typ.__name__
    priv = '_' + typnam + '__'
    buffer = [typnam, '<']
    limit -= len(buffer[0]) + 2
    if len(dct) <= limit//4:
      names = sorted(dct)
    else:
      names = list(dct)
    append = buffer.append
    first = True

    if issubclass(typ, BUILTIN_TYPES):

      for builtin_typ in BUILTIN_TYPES:
        if issubclass(typ, builtin_typ):
          try:
            val = builtin_typ(val)
            assert type(val) is builtin_typ
          except Exception:
            break
          else:
            append(_format_value(val, limit, level-1))
            first = False
            break

    for nam in names:
      if not isinstance(nam, basestring):
        continue
      if first:
        first = False
      else:
        append(', ')
      pnam = nam
      if pnam.startswith(priv):
        pnam = pnam[len(priv)-2:]
      limit -= len(pnam) + 2
      if limit <= 0:
        append('...')
        break
      append(pnam)
      append('=')
      rep = _format_value(dct[nam], limit, level-1)
      limit -= len(rep)
      append(rep)
    append('>')
    return ''.join(buffer)

  how = CONTAINER_TYPES.get(typ)
  if how:
    head, tail = how
    buffer = [head]
    append = buffer.append
    limit -= 2
    series = val
    isdict = typ is dict
    if isdict and len(val) <= limit//4:
      series = sorted(val)
    try:
      for elem in series:
        if limit <= 0:
          append('...')
          break
        rep = _format_value(elem, limit, level-1)
        limit -= len(rep) + 2
        append(rep)
        if isdict:
          rep = _format_value(val[elem], limit, level-1)
          limit -= len(rep)
          append(':')
          append(rep)
        append(', ')
      if buffer[-1] == ', ':
        if tail == ')' and len(val) == 1:
          buffer[-1] = ',)'
        else:
          buffer[-1] = tail
      else:
        append(tail)
      return ''.join(buffer)
    except (RuntimeError, KeyError):

      return head + tail + ' (Container modified during iteration)'

  if issubclass(typ, BUILTIN_TYPES):

    for builtin_typ in BUILTIN_TYPES:
      if issubclass(typ, builtin_typ):
        try:
          val = builtin_typ(val)
          assert type(val) is builtin_typ
        except Exception:
          break
        else:
          typnam = typ.__name__
          limit -= len(typnam) + 2
          return '%s<%s>' % (typnam, _format_value(val, limit, level-1))

  if (os.environ.get('APPENGINE_RUNTIME') == 'python27' and not
      os.environ.get('SERVER_SOFTWARE').startswith('Development')):
    from google.appengine._internal.proto1 import message
    if isinstance(val, message.Message):
      buffer = [typ.__name__, '<']
      limit -= len(buffer[0]) + 2
      append = buffer.append
      first = True
      fields = val.ListFields()

      for f, v in fields:
        if first:
          first = False
        else:
          append(', ')
        name = f.name
        limit -= len(name) + 2
        if limit <= 0:
          append('...')
          break
        append(name)
        append('=')
        if f.label == f.LABEL_REPEATED:
          limit -= 2
          append('[')
          first_sub = True
          for item in v:
            if first_sub:
              first_sub = False
            else:
              limit -= 2
              append(', ')
            if limit <= 0:
              append('...')
              break
            rep = _format_value(item, limit, level-1)
            limit -= len(rep)
            append(rep)
          append(']')
        else:
          rep = _format_value(v, limit, level-1)
          limit -= len(rep)
          append(rep)
      append('>')
      return ''.join(buffer)

  return typ.__name__ + '<>'


text:
import pytest
import os
import numpy as np
import logging
import matplotlib.pyplot as plt
import matplotlib as mpl

class Base:
    log = logging.getLogger('dip')

    def setup_method(self, method):
        print("\n{}:{}".format(self.__class__.__name__, method.__name__))
        # TODO support for fixtures (convert fixtures to strs)
        self._testMethodName = method.__name__

    def _plot_linpol(self, T, P, field, fixvminmax=True, ax=None):
        from dipole.plots import plot_linpol
        plot_linpol(T, P, field, fixvminmax=fixvminmax, ax=ax)

    def _plot_linpol_plane(self, X, Y, field, fixvminmax=True, ax=None):
        from dipole.plots import plot_linpol_plane
        plot_linpol_plane(X, Y, field=field, fixvminmax=fixvminmax, ax=ax)

    def _plot_surface(self, T, P, intens, ax=None):
        if ax is None:
            from mpl_toolkits.mplot3d import Axes3D
            fig = plt.figure()
            ax = fig.gca(projection='3d')

        intnorm = intens/intens.max()
        X = np.cos(P)*np.sin(T)*intnorm
        Y = np.sin(P)*np.sin(T)*intnorm
        Z = np.cos(T)*intnorm

        ax.plot_surface(X, Y, Z, facecolors=mpl.cm.rainbow(intnorm))
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_zlabel('z')

    def _plot_intens(self, T=None, P=None, field=None, intens=None, title=None, XY=None, ax=None):
        if intens is None:
            intens = np.sum(np.abs(field)**2, axis=2)
        if ax is None:
            fig, ax = plt.subplots()

        # ax.imshow(intens)
        if XY is not None:
            ax.pcolormesh(XY[0], XY[1], intens)
        else:
            ax.pcolormesh(np.degrees(T*np.cos(P)), np.degrees(T*np.sin(P)),
                          intens)
        # TODO improve limits (take code from paper_plotter.py)

        ax.set_aspect('equal')
        if title:
            ax.set_title(title)
        # ax.set_xlim(-25,25)
        # ax.set_ylim(-25,25)

        # cax.set_xticks([])
        # cax.set_yticks([])
        # cax.set_title('R_disk=%g lambda=%g, ndipoles=%d' % (scalefac, 2*np.pi/k,
                                                            # ndipoles))
        return ax

    def _plot_quiver_exy(self, field=None, title=None, XY=None, ax=None):
        Ex = field[:, :, 0].real
        Ey = field[:, :, 1].real

        if ax is None:
            fig, ax = plt.subplots()

        # ax.imshow(intens)
        if XY is not None:
            ax.quiver(XY[0], XY[1], Ex.real, Ey.real)
        ax.set_aspect('equal')
        if title:
            ax.set_title(title)
        ax.set_xlabel('X (plane)')
        ax.set_ylabel('Y (plane)')
        # ax.set_xlim(-25,25)
        # ax.set_ylim(-25,25)

        # cax.set_xticks([])
        # cax.set_yticks([])
        # cax.set_title('R_disk=%g lambda=%g, ndipoles=%d' % (scalefac, 2*np.pi/k,
                                                            # ndipoles))
        return ax

    def _plot_poynting(self, T=None, P=None, S=None, title=None, XY=None, ax=None):
        """s is either the magnitude of the poynting vector or a component of the
        poynting vector

        """
        if ax is None:
            fig, ax = plt.subplots()
        if XY is not None:
            C = ax.pcolormesh(XY[0], XY[1], S)
        else:
            C = ax.pcolormesh(np.degrees(T*np.cos(P)), np.degrees(T*np.sin(P)), S)
        if title:
            ax.set_title(title)
        ax.set_aspect('equal')

        plt.colorbar(C)

        return ax

    def gen_filename(self, postfix, extension):
        fname = "%s_%s%s.%s" % (self.__class__.__name__,
                                self._testMethodName,
                                "_%s" % postfix if postfix else "",
                                extension)
        logd = pytest.config.getvalue('logdir')
        fname = os.path.join(logd, fname)
        return fname

    def save_fig(self, postfix, fig, ext='png'):
        assert not postfix.endswith('.png')
        dest = self.gen_filename(postfix, ext)
        if not pytest.config.getvalue('log'):
            self.log.debug("do not save png %s (--log not set)", dest)
            return
        self.log.debug("saving mpl figure to '%s'", dest)
        if not os.path.exists(os.path.dirname(dest)):
            os.makedirs(os.path.dirname(dest))
        fig.savefig(dest)
        # TODO
        # self.created_files.append(dest)

    def show(self):
        if pytest.config.getvalue('interactive'):
            plt.show()