text:
package org.esupportail.publisher.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.esupportail.publisher.domain.enums.ContextType;
import org.esupportail.publisher.domain.enums.ItemStatus;
import org.esupportail.publisher.domain.util.CstPropertiesLength;
import org.esupportail.publisher.domain.util.CustomEnumSerializer;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.validator.constraints.ScriptAssert;
import java.time.Instant;
import java.time.LocalDate;

/**
 * @author GIP RECIA - Julien Gribonvald 24 Juin 2014
 */
@Data
@EqualsAndHashCode(callSuper = false)
@ToString(callSuper = false)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
    @JsonSubTypes.Type(value = News.class, name = "NEWS"),
    @JsonSubTypes.Type(value = Media.class, name = "MEDIA"),
    @JsonSubTypes.Type(value = Resource.class, name = "RESOURCE"),
    @JsonSubTypes.Type(value = Flash.class, name = "FLASH"),
    @JsonSubTypes.Type(value = Attachment.class, name = "ATTACHMENT")
})
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "T_ITEM")
@DiscriminatorColumn(name = "type")
@ScriptAssert(lang = "javascript", script = "org.esupportail.publisher.domain.AbstractItem.complexeDateValidation(_this.redactor.optionalPublishTime, _this.startDate, _this.endDate, _this.redactor.nbDaysMaxDuration)"
    , message = "Not valid startDate that should be before endDate or with maximum number of days duration")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public abstract class AbstractItem extends AbstractAuditingEntity implements
    IContext, Serializable {

    /** */
    private static final long serialVersionUID = -5070583652062682913L;

    /** This field corresponds to the database column title. */
    @NotNull
    @Size(max = CstPropertiesLength.ITEM_TITLE)
    @Column(nullable = false, length = CstPropertiesLength.ITEM_TITLE)
    private String title;

    /** This field corresponds to the database column enclosure. */
    @Size(max = CstPropertiesLength.URL)
    @Column(length = CstPropertiesLength.URL)
    private String enclosure;

    @Column(name = "end_date")
    private LocalDate endDate;

    @NotNull
    @Column(name = "start_date", nullable = false)
    private LocalDate startDate;

    @ManyToOne
    @JoinColumn(name = "validated_by")
    private User validatedBy;

    @Column(name = "validated_date")
    private Instant validatedDate;

    /** This field corresponds to the database column status. */
    @NotNull
    @Column(length = 50, nullable = false)
    //@Convert(converter = ItemStatusConverter.class)
    @Enumerated(EnumType.STRING)
    //@JsonFormat(shape = JsonFormat.Shape.STRING)
    //@JsonDeserialize(using = ItemStatusDeserializer.class)
    @JsonSerialize(using = CustomEnumSerializer.class)
    private ItemStatus status;

    /** This field corresponds to the database column summary. */
    @NotNull
    @Size(min = 5, max = CstPropertiesLength.SUMMARY)
    @Column(nullable = false, length = CstPropertiesLength.SUMMARY)
    private String summary;

    /** This field corresponds to the database column rss_allowed. */
    @Column(length = 1, nullable = false, name = "rss_allowed")
    private boolean rssAllowed = false;

    @Column(length = 1, nullable = false)
    private boolean highlight = false;

    /** This field corresponds to the database column entity_id. */
    @NotNull
    @ManyToOne
    @JoinColumn(name = "entity_id", nullable = false)
    private Organization organization;
    /** This field corresponds to the database column publisher_id. */
    @NotNull
    @ManyToOne
    @JoinColumn(name = "redactor_id", nullable = false)
    private Redactor redactor;

    /**
     * Empty constructor of the object Item.java.
     */
    public AbstractItem() {
        super();
    }

    /**
     * Constructor of the object Item.java.
     *
     * @param title
     * @param enclosure
     * @param startDate
     * @param endDate
     * @param validatedDate
     * @param validatedBy
     * @param status
     * @param summary
     * @param rssAllowed
     * @param highlight
     * @param organization
     * @param redactor
     */
    public AbstractItem(final String title, final String enclosure,
                        final LocalDate startDate, final LocalDate endDate,
                        final Instant validatedDate, final User validatedBy,
                        final ItemStatus status, final String summary, final boolean rssAllowed,
                        final boolean highlight, final Organization organization, final Redactor redactor) {
        super();
        this.title = title;
        this.enclosure = enclosure;
        this.startDate = startDate;
        this.endDate = endDate;
        this.validatedDate = validatedDate;
        this.validatedBy = validatedBy;
        this.status = status;
        this.summary = summary;
        this.rssAllowed = rssAllowed;
        this.highlight = highlight;
        this.organization = organization;
        this.redactor = redactor;
    }

    public ItemStatus getStatus() {
        switch (status) {
            case PUBLISHED:
                if (this.startDate.isAfter(LocalDate.now())) {
                    status = ItemStatus.SCHEDULED;
                    return ItemStatus.SCHEDULED;
                } else if (this.endDate != null && this.endDate.isBefore(LocalDate.now())) {
                    status = ItemStatus.ARCHIVED;
                    return ItemStatus.ARCHIVED;
                }
                break;
            default:
                break;
        }
        return status;
    }

    @Override
    public ContextKey getContextKey() {
        if (getId() == null) return null;
        return new ContextKey(this.getId(), ContextType.ITEM);
    }

    @Override
    public String getDisplayName() {
        return this.title;
    }

    /** for scriptAssert validation. */
    public static boolean complexeDateValidation(final boolean isPeriodOptional, final LocalDate startDate, final LocalDate endDate, final int maxDuration) {
        if (!isPeriodOptional) {
            return  startDate != null &&  endDate != null && startDate.isBefore(endDate) && startDate.plusDays(maxDuration+1).isAfter(endDate);
        } else if (startDate != null &&  endDate != null) {
            return startDate.isBefore(endDate) && startDate.plusDays(maxDuration+1).isAfter(endDate);
        }
        return true;
    }
}


text:
package datakeyed

// xlOverlay_go/datakeyed/diskCacheI.go

import (
	xi "github.com/jddixon/xlNodeID_go"
)

type DiskCacheI interface {

	/** initializes (clears) the underlying Bloom filter */
	// Init ()

	/** badly named */
	GetPathToXLattice() string

	/** For testing, should be deprecated ASAP. */
	// GetThreadPool() *DiskIOThreadPool

	// BLOOM FILTER INTERFACE ///////////////////////////////////////
	/**
	 * The theoretical false positive rate is
	 *   (1 - e(-kN/M))^k
	 * where k is the number of key functions, N is the number
	 * of keys in the filter, and there are 2^M bits in the
	 * filter.
	 *
	 * @param  n number of keys in the filter
	 * @return an approximation to the false positive rate
	 */
	FalsePositives(n int) float64

	/**
	 * Add a key to the filter.
	 */
	Insert(id *xi.NodeID) error

	/**
	 * This method has a non-zero false positive rate.  The filter
	 * can normally be set up to make this a very small number.
	 *
	 * @return whether a key is in the filter
	 * @see #FalsePositives
	 */
	IsMember(id *xi.NodeID) bool

	/**
	 * Remove a key from the filter.
	 */
	Remove(id *xi.NodeID) error

	/**
	 * A counter is incremented and decremented whenever a key is
	 * inserted or removed.  The value of this counter is returned
	 * as a crude estimate of the number of keys in the filter.
	 *
	 * @return the approximate number of keys in the filter
	 */
	Size() uint

	// DISK I/O QUEUES //////////////////////////////////////////////
	AcceptReadJob(id *xi.NodeID) error

	AcceptWriteJob(id *xi.NodeID, data []byte) error
}

redpajama_set_name: RedPajamaGithub


text:
import gettext
import os
import subprocess

from setuptools import find_packages
from setuptools.command.sdist import sdist
from setuptools import setup

gettext.install('melange', unicode=1)

from melange.openstack.common.setup import parse_requirements
from melange.openstack.common.setup import parse_dependency_links
from melange.openstack.common.setup import write_requirements
from melange.openstack.common.setup import write_vcsversion
from melange.openstack.common.setup import write_git_changelog

from melange import version

class local_sdist(sdist):
    """Customized sdist hook - builds the ChangeLog file from VC first"""
    def run(self):
        write_git_changelog()
        sdist.run(self)
cmdclass = {'sdist': local_sdist}

try:
    from sphinx.setup_command import BuildDoc

    class local_BuildDoc(BuildDoc):
        def run(self):
            for builder in ['html', 'man']:
                self.builder = builder
                self.finalize_options()
                BuildDoc.run(self)
    cmdclass['build_sphinx'] = local_BuildDoc

except:
    pass

try:
    from babel.messages import frontend as babel
    cmdclass['compile_catalog'] = babel.compile_catalog
    cmdclass['extract_messages'] = babel.extract_messages
    cmdclass['init_catalog'] = babel.init_catalog
    cmdclass['update_catalog'] = babel.update_catalog
except:
    pass

requires = parse_requirements()
depend_links = parse_dependency_links()

write_requirements()
write_vcsversion('melange/vcsversion.py')

setup(name='melange',
      version=version.canonical_version_string(),
      description='IPAM mangement service for Openstack',
      author='OpenStack',
      author_email='openstack@lists.launchpad.net',
      url='http://www.openstack.org/',
      cmdclass=cmdclass,
      packages=find_packages(exclude=['bin']),
      include_package_data=True,
      install_requires=requires,
      dependency_links=depend_links,
      test_suite='nose.collector',
      classifiers=[
          'Development Status :: 4 - Beta',
          'License :: OSI Approved :: Apache Software License',
          'Operating System :: POSIX :: Linux',
          'Programming Language :: Python :: 2.6',
          'Environment :: No Input/Output (Daemon)',
      ],
      scripts=['bin/melange-server',
               'bin/melange-manage',
               'bin/melange-delete-deallocated-ips',
               ],
      py_modules=[],
      namespace_packages=['melange'],
    )


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Changed
- Solution redone as [Language Server](https://code.visualstudio.com/docs/extensions/example-language-server)

## 0.1.3

### Added
- Check on underscore in variables
### Changed
- Fixed a number of issues reported on GitHub.

## 0.1.2
- WARNING: You can not yet disable the new features.

### Added
- Added fields to the model with Hungarian Notation check.
- Check for using WITH statement in Tables and Pages.
- Warning if local and local variables have the same name.
- Text Constants throw warning if they have the old notation (TextXXX).
- Temporary Table Variables must have TEMP, BUFFER, ARGS or ARGUMENTS in the name.
- Check for reserved words, e.g. a function name called "Action" or a field called "SetRange".

### Changed
- First version of refactoring is implemented. The function is always called "foo" and does not yet check if the selection makes sense or depends on variables.
- Fixed issue with system variables Rec and xRec not being recognised as Hungarian Notation.
- Complex Type variables that are declared with object id instead of name give warning.
- Cleaned up the Type Script a bit here and there.

## 0.1.1

### Changed
- Implemented setting and fixed reported issues.

## 0.1.0
- First version


text:
import {expect} from 'chai';
import {MetricsActuatorServer} from '../../src/MetricsActuatorServer';
import {MetricsServerManager} from '../../src/MetricsServerManager';

describe('/test/unit/MetricsActuatorServer.test.ts', () => {

  it('init actuator server', () => {

    expect(() => {
      let server = new MetricsActuatorServer({
        logger: console,
        metricsManager: new MetricsServerManager()
      });
      expect(server.getMetricsManager()).to.exist;
    }).to.not.throw(TypeError);

  });
});


text:
#ifndef SERIAL_WRITE_HEX
#define SERIAL_WRITE_HEX

#include <types.h>

#ifdef __cplusplus
extern "C"
{
#endif

    /**
     * <!-- description -->
     *   @brief Writes a hexidecimal number "val" to the serial device.
     *
     * <!-- inputs/outputs -->
     *   @param val the hexidecimal number to write
     */
    void serial_write_hex(uint64_t const val) NOEXCEPT;

#ifdef __cplusplus
}
#endif

#endif


text:
var gulp = require('gulp');
var less = require('gulp-less');
var inline64 = require('gulp-inline-base64');
var requirejs = require('requirejs');
var rjsConfig = require('./tools/node-gulp-build.conf')();
var packageJson = require('./package.json');
var rework = require('gulp-rework');
var namespaceCss = require('rework-namespace-css');

var src = {
    'less': './src/less/**/*.less',
    'js': './src/**/*.js'
};

var dest = {
    'css': './dist/styles/',
    'js': './dist/'
};

gulp.task('less', function () {
    var prefix = '[data-lf-package="' + packageJson.name + '#' + packageJson.version + '"]';

    return gulp.src(src.less)
        .pipe(less({ paths: [ __dirname ] }))
        .pipe(inline64({baseDir: './lib/livefyre-bootstrap/src/', debug: true}))
        .pipe(rework(namespaceCss({selector: prefix, root: '.carousel-view'})))
        .pipe(gulp.dest(dest.css));
});

function compileJS(min) {
    min = min || false;

    if (min) {
        rjsConfig.out = dest.js + 'mosaic-component.min.js';
        rjsConfig.optimize = "uglify2";
    }
    else {
        rjsConfig.out = dest.js + 'mosaic-component.js';
        rjsConfig.optimize = "none";
    }

    return requirejs.optimize(rjsConfig, function (resp) {
        console.log((min ? 'Minified' : 'Unminified') + ' File Built');
        if (!min) {
            compileJS(true);
        }
    }, function (err) {});
}

gulp.task('rjs', ['less'], function () {
    return compileJS();
});

gulp.task('watch', function () {
    gulp.watch(src.less, ['less']);
});

gulp.task('default', ['less', 'watch']);
gulp.task('build', ['less', 'rjs']);


text:
from logging.handlers import RotatingFileHandler
import os

LOG_DIR = "log"
class MakeFileHandler(RotatingFileHandler):
  def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):
    try:
      os.makedirs(LOG_DIR)
    except OSError:
      if os.path.isdir(LOG_DIR):
          pass
      else: raise
    RotatingFileHandler.__init__(self, "%s/%s" % (LOG_DIR, filename), mode=mode, maxBytes=maxBytes, backupCount=backupCount, encoding=encoding, delay=delay)


text:
<?php

require_once('../vendor/j7mbo/twitter-api-php/TwitterAPIExchange.php');
require_once '../alchemyapi_php/alchemyapi.php';

class StackExchangeController extends BaseController {

    public function home()
    {
        return View::make('stackSearch');
    }

	public function search()
	{
        $validation = Validator::make(
            Input::all(), array(
                'stackExchangeSearch' => 'required | max:50',
            )
        );

        if ($validation->fails()) {
            return Redirect::back()->withInput()->withErrors($validation->messages());
        }

        $response = $this->getPosts(Input::get('stackExchangeSearch'), Input::get('count'));

        $alchemyapi = new AlchemyAPI();
        $postIntel = [];

        foreach($response->items as $post)
        {
            $textOptions = ['useMetadata' => 1];
            $textResponse = $alchemyapi->text('url', $post->link, $textOptions);

            $sentimentOptions = ['sentiment' => 1];
            $postSentiment = $this->doAlchemy('url', $post->link, $sentimentOptions, 'sentiment', 'docSentiment', $alchemyapi);

            //Dont use concepts
            //when loading stack url into concepts call, it just returns random unrelated stuff
            //when loading extracted text into concepts call, it returns empty every time

            $entityOptions = ['maxRetrieve' => 5, 'sentiment' => 1];
            $postEntities = $this->doAlchemy('text', $textResponse['text'], $entityOptions, 'entities', 'entities', $alchemyapi);

            $keywordOptions = ['sentiment' => 1, 'showSourceText' => 1, 'maxRetrieve' => 5];
            $postKeywords = $this->doAlchemy('text', $textResponse['text'], $keywordOptions, 'keywords', 'keywords', $alchemyapi);

            $tmp = ['link' => $post->link,
                    'title' => $post->title,
                    'answered' => $post->is_answered,
                    'sentiment' => $postSentiment,
                    'entities' => $postEntities,
                    'keywords' => $postKeywords];

            array_push($postIntel, $tmp);
        }

        return View::make('stackResults')->with('postIntel', $postIntel)->with('searchTerm', Input::get('stackExchangeSearch'));
	}

    private function doAlchemy($flavor, $data, $options, $call, $key, $alchemyapi)
    {
        $response = $alchemyapi->$call($flavor, $data, $options);
        if(array_key_exists($key, $response))
        {
            $intel = $response[$key];
        }
        else
        {
            $intel = null;
        }

        return $intel;
    }

    private function getPosts($searchTerm, $count)
    {
        function curl($url){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 30);
            curl_setopt($curl, CURLOPT_USERAGENT, 'cURL');
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_ENCODING , "gzip");

            $result = curl_exec($curl);
            curl_close($curl);

            return $result;
        }

        $searchURL = "http://api.stackexchange.com/2.2/search?pagesize=". $count . "&order=desc&sort=activity&intitle=". $searchTerm ."&site=stackoverflow";
        $response = json_decode(curl($searchURL));

        return $response;
    }
}


text:
require 'chef-dk/command/base'
require 'chef-dk/ui'
require 'chef-dk/policyfile_services/install'
require 'chef-dk/configurable'

module ChefDK
  module Command

    class Install < Base

      include Configurable

      banner(<<-E)
Usage: chef install [ POLICY_FILE ] [options]

`chef install` evaluates a `Policyfile.rb` to find a compatible set of
cookbooks for the policy's run_list and caches them locally. It emits a
Policyfile.lock.json describing the locked cookbook set. You can use the
lockfile to install the locked cookbooks on another machine. You can also push
the lockfile to a "policy group" on a Chef Server and apply that exact set of
cookbooks to nodes in your infrastructure.

See our detailed README for more information:

https://github.com/opscode/chef-dk/blob/master/POLICYFILE_README.md

Options:

E

      option :config_file,
        short:       "-c CONFIG_FILE",
        long:        "--config CONFIG_FILE",
        description: "Path to configuration file"

      option :debug,
        short:       "-D",
        long:        "--debug",
        description: "Enable stacktraces and other debug output",
        default:     false

      attr_reader :policyfile_relative_path

      attr_accessor :ui

      def initialize(*args)
        super
        @ui = UI.new

        @policyfile_relative_path = nil
        @installer = nil
      end

      def run(params = [])
        return 1 unless apply_params!(params)
        # Force config file to be loaded. We don't use the configuration
        # directly, but the user may have SSL configuration options that they
        # need to talk to a private supermarket (e.g., trusted_certs or
        # ssl_verify_mode)
        chef_config
        installer.run
        0
      rescue PolicyfileServiceError => e
        handle_error(e)
        1
      end

      def installer
        @installer ||= PolicyfileServices::Install.new(policyfile: policyfile_relative_path, ui: ui, root_dir: Dir.pwd)
      end

      def debug?
        !!config[:debug]
      end

      def config_path
        config[:config_file]
      end

      def handle_error(error)
        ui.err("Error: #{error.message}")
        if error.respond_to?(:reason)
          ui.err("Reason: #{error.reason}")
          ui.err("")
          ui.err(error.extended_error_info) if debug?
          ui.err(error.cause.backtrace.join("\n")) if debug?
        end
      end

      def apply_params!(params)
        remaining_args = parse_options(params)
        if remaining_args.size > 1
          ui.err(opt_parser)
          return false
        else
          @policyfile_relative_path = remaining_args.first
          true
        end
      end

    end
  end
end


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

namespace task_2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Ohjelma laskee N ensimmäistä lukua yhteen.");
            string userInput = Console.ReadLine();
            int number = int.Parse(userInput);
            int i = 1;
            int f = 1;
            int k = 1;

            if (number < 0)
            {
                k = -1;
            }
                do
                {
                    i = i + 1;
                    f = f + i;
                } while (i < number*k);
            Console.Write($"Syötit: {number}, Summa: {f*k}");
            Console.ReadLine();
        }
    }
}


text:
<?php

namespace Bolt\Provider;

use Bolt\Session\CookiePathRestrictionListener;
use Bolt\Session\Generator\RandomGenerator;
use Bolt\Session\Handler\FileHandler;
use Bolt\Session\Handler\RedisHandler;
use Bolt\Session\OptionsBag;
use Bolt\Session\Serializer\NativeSerializer;
use Bolt\Session\SessionListener;
use Bolt\Session\SessionStorage;
use GuzzleHttp\Url;
use Silex\Application;
use Silex\ServiceProviderInterface;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag;

/**
 * Because screw PHP core.
 *
 * @author Carson Full <carsonfull@gmail.com>
 */
class SessionServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $this->registerSessions($app);
        $this->registerListeners($app);
        $this->registerOptions($app);
        $this->registerHandlers($app);

        $app['session.storage.generator'] = $app->share(
            function () use ($app) {
                return new RandomGenerator($app['randomgenerator']);
            }
        );

        $app['session.storage.serializer'] = $app->share(
            function () {
                return new NativeSerializer();
            }
        );

        $app['session.bag.attribute'] = function () {
            return new AttributeBag();
        };

        $app['session.bag.flash'] = function () {
            return new FlashBag();
        };

        $app['session.bag.metadata'] = function () {
            return new MetadataBag();
        };

        $this->configure($app);
    }

    public function boot(Application $app)
    {
        $listeners = $app['sessions.listener'];
        foreach ($listeners->keys() as $name) {
            $app['dispatcher']->addSubscriber($listeners[$name]);
        }
        foreach ($app['sessions.options'] as $options) {
            /** @var $options OptionsBag */
            if ($options->getBoolean('cookie_restrict_path')) {
                $listener = $app['session.cookie_path_restriction_listener.factory']($options);
                $app['dispatcher']->addSubscriber($listener);
            }
        }
    }

    /**
     * This should be the only place in this class that is specific to bolt.
     *
     * @param Application $app
     */
    public function configure(Application $app)
    {
        $app['session.default_options'] = [
            'cookie_lifetime' => $app['config']->get('general/cookies_lifetime'),
            'cookie_path'     => $app['resources']->getUrl('root'),
            'cookie_domain'   => $app['config']->get('general/cookies_domain'),
            'cookie_secure'   => $app['config']->get('general/enforce_ssl'),
            'cookie_httponly' => true,
        ];
        $app['sessions.options'] = [
            'main' => [
                'name' => $app['token.session.name'],
            ],
            'csrf' => [
                'name'                 => $app['token.session.name'] . '_csrf',
                'cookie_restrict_path' => true,
                'cookie_lifetime'      => 0,
            ],
        ];
    }

    protected function registerSessions(Application $app)
    {
        $app['sessions'] = $app->share(
            function () use ($app) {
                $app['sessions.options.initializer']();

                $sessions = new \Pimple();
                foreach ($app['sessions.options'] as $name => $options) {
                    $sessions[$name] = $app->share(
                        function () use ($options, $app) {
                            return $app['session.factory']($options);
                        }
                    );
                }

                return $sessions;
            }
        );

        $app['session.factory'] = $app->protect(
            function ($options) use ($app) {
                return new Session(
                    $app['session.storage.factory']($options),
                    $app['session.bag.attribute'],
                    $app['session.bag.flash']
                );
            }
        );

        $app['session.storage.factory'] = $app->protect(
            function ($options) use ($app) {
                return new SessionStorage(
                    $options,
                    $app['session.storage.handler.factory']($options['save_handler'], $options),
                    $app['session.storage.generator'],
                    $app['session.storage.serializer']
                );
            }
        );

        $app['session'] = $app->share(
            function ($app) {
                // Sessions needs to be called first so sessions.default is initialized
                $sessions = $app['sessions'];

                return $sessions[$app['sessions.default']];
            }
        );
    }

    protected function registerListeners(Application $app)
    {
        $app['sessions.listener'] = $app->share(
            function () use ($app) {
                $app['sessions.options.initializer']();

                $listeners = new \Pimple();
                foreach ($app['sessions']->keys() as $name) {
                    $setToRequest = $name === $app['sessions.default'];
                    $listeners[$name] = $app->share(
                        function () use ($app, $name, $setToRequest) {
                            $session = $app['sessions'][$name];
                            $options = $app['sessions.options'][$name];

                            return $app['session.listener.factory']($session, $options, $setToRequest);
                        }
                    );
                }

                return $listeners;
            }
        );

        $app['session.listener.factory'] = $app->protect(
            function ($session, $options, $setToRequest = false) {
                return new SessionListener($session, $options, $setToRequest);
            }
        );

        $app['session.listener'] = $app->share(
            function ($app) {
                return $app['session.listeners'][$app['sessions.default']];
            }
        );

        $app['session.cookie_path_restriction_listener.factory'] = $app->protect(
            function ($options) {
                return new CookiePathRestrictionListener($options);
            }
        );
    }

    protected function registerOptions(Application $app)
    {
        $app['session.default_options'] = [];
        $app['session.options.import_from_ini'] = true;

        $app['sessions.options.initializer'] = $app->protect(
            function () use ($app) {
                static $initialized = false;

                if ($initialized) {
                    return;
                }
                $initialized = true;

                /*
                 * Ok this does several things.
                 * 1) Merges options together for each session. Precedence is as follows:
                 *    - Options from individual session
                 *    - Options from "session.default_options"
                 *    - Options from ini (if enabled with "session.options.import_from_ini")
                 *    - Options hardcoded below
                 * 2) Converts "session.options" shortcut to sessions.options['default']
                 * 3) Sets "sessions.default" value to first session key in "sessions.options"
                 * 4) Converts options for each session to an OptionsBag instance
                 */
                $actualDefaults = [
                    'save_handler'    => 'files',
                    'save_path'       => '/tmp',
                    'name'            => 'PHPSESSID',
                    //'auto_start' => false,
                    //'serialize_handler' => null,
                    'gc_probability'  => 1,
                    'gc_divisor'      => 1000,
                    'gc_maxlifetime'  => 1440,
                    //'referer_check' => '',
                    //'use_strict_mode' => false,
                    'cookie_lifetime' => 0,
                    'cookie_path'     => '/',
                    'cookie_domain'   => null,
                    'cookie_secure'   => false,
                    'cookie_httponly' => false,
                    // TODO Do started native sessions force "nocache" header in response?
                    // We don't have a way to force that, should we?
                    //'cache_limiter' => 'nocache',
                    //'cache_expire'  => 180,
                ];

                if (isset($app['session.options.import_from_ini']) && $app['session.options.import_from_ini']) {
                    foreach ($actualDefaults as $key => $value) {
                        $actualDefaults[$key] = ini_get('session.' . $key);
                    }
                }
                $app['session.default_options'] = array_replace($actualDefaults, $app['session.default_options']);

                // Maintain BC for "session.storage.options"
                if (isset($app['session.storage.options'])) {
                    $app['session.default_options'] = array_replace($app['session.default_options'], $app['session.storage.options']);
                }

                if (!isset($app['sessions.options'])) {
                    $app['sessions.options'] = [
                        'default' => isset($app['session.options']) ? $app['session.options'] : [],
                    ];
                }

                $options = [];
                foreach ($app['sessions.options'] as $name => $opts) {
                    if (!isset($app['sessions.default'])) {
                        $app['sessions.default'] = $name;
                    }
                    $opts = array_replace($app['session.default_options'], (array) $opts);
                    $options[$name] = new OptionsBag($opts);
                }
                $app['sessions.options'] = $options;
            }
        );
    }

    protected function registerHandlers(Application $app)
    {
        $app['session.storage.handler.factory'] = $app->protect(
            function ($handler, $options) use ($app) {
                $key = 'session.storage.handler.factory.' . $handler;
                if (isset($app[$key])) {
                    return $app[$key]($options);
                }
                throw new \RuntimeException("Unsupported handler type '$handler' specified");
            }
        );

        $app['session.storage.handler.factory.files'] = $app->protect(
            function ($options) use ($app) {
                return new FileHandler($options['save_path'], $app['logger.system']);
            }
        );

        $this->registerMemcacheHandler($app);
        $this->registerRedisHandler($app);
    }

    protected function registerMemcacheHandler(Application $app)
    {
        $app['session.storage.handler.factory.backing_memcache'] = $app->protect(
            function ($connections) {
                $memcache = new \Memcache();

                foreach ($connections as $conn) {
                    $memcache->addServer(
                        $conn['host'] ?: 'localhost',
                        $conn['port'] ?: 11211,
                        $conn['persistent'] ?: false,
                        $conn['weight'] ?: 0,
                        $conn['timeout'] ?: 1
                    );
                }

                return $memcache;
            }
        );

        $app['session.storage.handler.factory.memcache'] = $app->protect(
            function ($options, $key = 'memcache') use ($app) {
                $connections = $this->parseConnections($options, 'localhost', 11211);
                $memcache = $app['session.storage.handler.factory.backing_' . $key]($connections);

                $handlerOptions = [];
                if (isset($options['expiretime'])) {
                    $handlerOptions['expiretime'] = $options['expiretime'];
                }
                if (isset($options['prefix'])) {
                    $handlerOptions['prefix'] = $options['prefix'];
                }

                if ($key === 'memcache') {
                    return new MemcacheSessionHandler($memcache, $handlerOptions);
                } else {
                    return new MemcachedSessionHandler($memcache, $handlerOptions);
                }
            }
        );

        $app['session.storage.handler.factory.memcached'] = $app->protect(
            function ($options) use ($app) {
                return $app['session.storage.handler.factory.memcache']($options, 'memcached');
            }
        );
    }

    protected function registerRedisHandler(Application $app)
    {
        $app['session.storage.handler.factory.backing_redis'] = $app->protect(
            function ($connections) {
                if (class_exists('Redis')) {
                    $redis = new \Redis();
                    foreach ($connections as $conn) {
                        $params = [$conn['path'] ?: $conn['host'], $conn['port'], $conn['timeout'] ?: 0];
                        call_user_func_array([$redis, $conn['persistant'] ? 'pconnect' : 'connect'], $params);
                        if (!empty($conn['password'])) {
                            $redis->auth($conn['password']);
                        }
                        if ($conn['database'] > 0) {
                            $redis->select($conn['database']);
                        }
                        if (!empty($conn['prefix'])) {
                            $redis->setOption(\Redis::OPT_PREFIX, $conn['prefix']);
                        }
                    }
                } elseif (class_exists('Predis\Client')) {
                    $params = [];
                    $options = [];
                    foreach ($connections as $conn) {
                        $params[] = $conn;
                        if (!empty($conn['prefix'])) {
                            $options['prefix'] = $conn['prefix'];
                        }
                    }
                    $redis = new \Predis\Client($params, $options);
                } else {
                    throw new \RuntimeException('Neither Redis nor Predis\Client exist');
                }

                return $redis;
            }
        );

        $app['session.storage.handler.factory.redis'] = $app->protect(
            function ($options) use ($app) {
                $connections = $this->parseConnections($options, 'localhost', 6379);
                $redis = $app['session.storage.handler.factory.backing_redis']($connections);

                return new RedisHandler($redis, $options['gc_maxlifetime']);
            }
        );
    }

    protected function parseConnections($options, $defaultHost, $defaultPort)
    {
        if (isset($options['host']) || isset($options['port'])) {
            $options['connections'][] = $options;
        }

        /** @var Url[] $toParse */
        $toParse = [];
        if (isset($options['connections'])) {
            foreach ((array) $options['connections'] as $alias => $conn) {
                if (is_string($conn)) {
                    $conn = ['host' => $conn];
                }
                $scheme = isset($conn['scheme']) ? $conn['scheme'] : 'tcp';
                $host = isset($conn['host']) ? $conn['host'] : $defaultHost;
                $url = new Url($scheme, $host);
                $url->setPort(isset($conn['port']) ? $conn['port'] : $defaultPort);
                if (isset($conn['path'])) {
                    $url->setPath($conn['path']);
                }
                if (isset($conn['password'])) {
                    $url->setPassword($conn['password']);
                }
                $url->getQuery()->replace($conn);
                $toParse[] = $url;
            }
        } elseif (isset($options['save_path'])) {
            foreach (explode(',', $options['save_path']) as $conn) {
                $toParse[] = Url::fromString($conn);
            }
        }

        $connections = [];
        foreach ($toParse as $url) {
            $connections[] = [
                'scheme'     => $url->getScheme(),
                'host'       => $url->getHost(),
                'port'       => $url->getPort(),
                'path'       => $url->getPath(),
                'alias'      => $url->getQuery()->get('alias'),
                'prefix'     => $url->getQuery()->get('prefix'),
                'password'   => $url->getPassword(),
                'database'   => $url->getQuery()->get('database'),
                'persistent' => $url->getQuery()->get('persistent'),
                'weight'     => $url->getQuery()->get('weight'),
                'timeout'    => $url->getQuery()->get('timeout'),
            ];
        }

        return $connections;
    }
}


text:
![1.](./imgs/1.png)
## 2.
![2.](./imgs/2.png)
## 3.
![3.](./imgs/3.png)
## 4.
![4.](./imgs/4.png)
## 5.
![5.](./imgs/5.png)
## 6.
![6.](./imgs/6.png)
## 7.
![7.](./imgs/7.png)
## 8.
![8.](./imgs/7.png)
## 9.
![9.](./imgs/7.png)

How can you use Chrome's DevTools inspector to help you format or position
elements? How can you resize elements on the DOM using CSS? What are the
differences between Absolute, Fixed, Static, and Relative positioning? Which
did you find easiest to use? Which was most difficult? What are the
differences between Margin, Border, and Padding? What was your impression of
this challenge overall? (love, hate, and why?)

Chrome DevTools are really helpful because they give you a
visualization of the all of the display properties on the page, and a
sand box for rapidly experimenting with them. Its especially good for
positioning because you can make small changes and quickly see the
impact, and judge what changes to make based on the visual properties
of the element boxes on the page.

You can size elements by setting the height and/or width attributes to
a % value. This will resize the element when the parent element is
resized. If the parent element is the body, it should change when the
window size changes. You can also allow the user to resize an element
by setting the resize value of its CSS to both, vertical or
horizontal.

By default, all elements are set to static positioning. An element with static positioning is not affected by the left, right, bottom or top, properties. Static elements positions are determined by the flow of their placement in the HTML code. Relative positioned elements can be moved relative to their normal positioning. They can be moved with the right, left, top, and bottom attributes relative to the elements original placement. An element with fixed positioning is fixed to the viewport. Even when the window is resized or scrolled through, it will stay fixed in its position relative to the edge of the viewport.
An element with absolute positioning is placed relative to the nearest non-static ancestor. If it has no positioned(non-static) ancestors, it is positioned relative to document body, and behaves kind of like a fixed element.

I thought relative was the easiest to use, because its easy to see where you want an element to be moved to based on its current position, especially when using devTools. I think static and absolute are the hardest to use. Static is difficult to use because the only ability you have for positioning the element is where you place it within the HTML code. Absolute is hard because you must take into account what element is its nearest positioned ancestor, and move it based on that. That can be difficult especially if some things on the page are static, or move during scrolling or resizing.

Margin, border and padding are all aspects of the box model. The border is the size of the element box. Padding determines the amount of space between the border's inner edge and anything contained in the box. The margin is the amount of space between the outer edge of the border and any elements outside of the element's border.

I liked this challenge. I thought it was fun, and my partner was really great to work with. It didn't take to long and I thought we were able to complete everything pretty well in a collaborative fashion.


text:
"""Compare marked moles across rotomaps.

Controls:

    'left arrow' or 'right arrow' to change image in the left slot.
    'up arrow' or 'down arrow' to change rotomap in the left slot.
    'space' to swap left slot and right slot.
    'p' or 'n' to change the mole being examined in both slots.
    'a' to toggle crosshairs on/off.
    'c' to mark the moles as changed in the newest rotomap.
    'u' to mark the moles as unchanged in the newest rotomap.

    'l' to zoom and rotate the left slot to roughly align with the right slot.

    'z' to zoom in on the left slot.
    'x' to zoom out on the left slot.

    'j' to rotate left on the left slot.
    'k' to rotate right on the left slot.

    'q' to quit.
"""

import collections
import functools
import math
import os

import cv2
import numpy

import mel.lib.common
import mel.lib.datetime
import mel.lib.image
import mel.lib.math
import mel.lib.moleimaging
import mel.rotomap.display
import mel.rotomap.moles

_PosInfo = collections.namedtuple(
    "_PosInfo", "path pos ellipse_xpos uuid uuid_points"
)

def setup_parser(parser):
    parser.add_argument(
        "ROTOMAP",
        type=mel.rotomap.moles.make_argparse_rotomap_directory,
        nargs="+",
        help=(
            "A list of paths to rotomaps. The last rotomap is considered "
            "'the target', and only UUIDs from that one will be compared."
        ),
    )

def process_args(args):
    target_rotomap = args.ROTOMAP[-1]
    target_uuids = target_rotomap.calc_uuids()

    uuid_to_rotomaps_imagepos_list = collections.defaultdict(
        lambda: collections.defaultdict(list)
    )

    for rotomap in args.ROTOMAP:
        for frame in rotomap.yield_frames():
            if "ellipse" not in frame.metadata:
                raise Exception(
                    f"{frame} has no ellipse metadata, "
                    'try running "rotomap calc-space"'
                )
            ellipse = frame.metadata["ellipse"]
            elspace = mel.lib.ellipsespace.Transform(ellipse)
            for uuid_, point in frame.moledata.uuid_points.items():
                if uuid_ not in target_uuids:
                    continue
                posinfo = _PosInfo(
                    path=frame.path,
                    pos=point,
                    ellipse_xpos=elspace.to_space(point)[0],
                    uuid=uuid_,
                    uuid_points=frame.moledata.uuid_points,
                )
                uuid_to_rotomaps_imagepos_list[uuid_][rotomap.path].append(
                    posinfo
                )

    # We can't compare moles that are only in one rotomap, cull these.
    uuid_to_rotomaps_imagepos_list = {
        key: value
        for key, value in uuid_to_rotomaps_imagepos_list.items()
        if len(value) > 1
    }

    if not uuid_to_rotomaps_imagepos_list:
        raise Exception("Nothing to compare.")

    # Ensure we're not using a defaultdict, otherwise we might miss a KeyError.
    uuid_to_rotomaps_imagepos_list = dict(uuid_to_rotomaps_imagepos_list)

    def unchanged_status_keyfunc(uuid_):
        is_unchanged = is_lesion_unchanged(target_rotomap, uuid_)
        if is_unchanged is None:
            return 1
        if not is_unchanged:
            return 0
        return 2

    uuid_order = list(uuid_to_rotomaps_imagepos_list)
    uuid_order.sort(key=unchanged_status_keyfunc)
    uuid_ = uuid_order[0]

    # Import pygame as late as possible, to avoid displaying its
    # startup-text where it is not actually used.
    import pygame

    path_images_tuple = tuple(uuid_to_rotomaps_imagepos_list[uuid_].values())
    with mel.lib.common.timelogger_context("rotomap-compare") as logger:
        with mel.lib.fullscreenui.fullscreen_context() as screen:
            display = ImageCompareDisplay(
                logger, screen, path_images_tuple, uuid_
            )

            on_keydown = _make_on_keydown(
                display,
                uuid_order,
                target_rotomap,
                uuid_to_rotomaps_imagepos_list,
            )

            for event in mel.lib.fullscreenui.yield_events_until_quit(screen):
                if event.type == pygame.KEYDOWN:
                    on_keydown(event)

def _make_on_keydown(
    display, uuid_order, target_rotomap, uuid_to_rotomaps_imagepos_list
):
    # Import pygame as late as possible, to avoid displaying its
    # startup-text where it is not actually used.
    import pygame

    index = 0
    uuid_ = uuid_order[index]
    is_unchanged = is_lesion_unchanged(target_rotomap, uuid_)
    if is_unchanged is not None:
        display.indicate_changed(not is_unchanged)

    def on_keydown(event):
        key = event.key
        nonlocal index
        if key == pygame.K_RIGHT:
            display.next_image()
        elif key == pygame.K_LEFT:
            display.prev_image()
        elif key == pygame.K_UP:
            display.prev_rotomap()
        elif key == pygame.K_DOWN:
            display.next_rotomap()
        elif key == pygame.K_n:
            num_uuids = len(uuid_to_rotomaps_imagepos_list)
            index += 1
            index %= num_uuids
            uuid_ = uuid_order[index]
            path_images_tuple = tuple(
                uuid_to_rotomaps_imagepos_list[uuid_].values()
            )
            display.reset(path_images_tuple, uuid_)
            is_unchanged = is_lesion_unchanged(target_rotomap, uuid_)
            if is_unchanged is not None:
                display.indicate_changed(not is_unchanged)
        elif key == pygame.K_p:
            num_uuids = len(uuid_to_rotomaps_imagepos_list)
            index -= 1
            index %= num_uuids
            uuid_ = uuid_order[index]
            path_images_tuple = tuple(
                uuid_to_rotomaps_imagepos_list[uuid_].values()
            )
            display.reset(path_images_tuple, uuid_)
            is_unchanged = is_lesion_unchanged(target_rotomap, uuid_)
            if is_unchanged is not None:
                display.indicate_changed(not is_unchanged)
        elif key == pygame.K_SPACE:
            display.swap_images()
        elif key == pygame.K_a:
            display.toggle_crosshairs()
        elif key == pygame.K_c:
            is_unchanged = False
            uuid_ = uuid_order[index]
            mark_lesion(target_rotomap, uuid_, is_unchanged=False)
            display.indicate_changed()
        elif key == pygame.K_u:
            is_unchanged = True
            uuid_ = uuid_order[index]
            mark_lesion(target_rotomap, uuid_, is_unchanged=True)
            display.indicate_changed(False)
        elif key == pygame.K_z:
            display.adjust_zoom(1.025)
        elif key == pygame.K_x:
            display.adjust_zoom(1 / 1.025)
        elif key == pygame.K_l:
            display.auto_align_and_show()
        elif key == pygame.K_j:
            display.adjust_rotation(2)
        elif key == pygame.K_k:
            display.adjust_rotation(-2)

    return on_keydown

def is_lesion_unchanged(rotomap, uuid_):
    """Mark the provided uuid changed status in the lesions datafile."""
    for lesion in rotomap.lesions:
        if lesion["uuid"] == uuid_:
            return lesion[mel.rotomap.moles.KEY_IS_UNCHANGED]
    return None

def mark_lesion(rotomap, uuid_, *, is_unchanged):
    """Mark the provided uuid changed status in the lesions datafile."""
    target_lesion = None
    for lesion in rotomap.lesions:
        if lesion["uuid"] == uuid_:
            target_lesion = lesion
    if target_lesion is None:
        target_lesion = {"uuid": uuid_}
        rotomap.lesions.append(target_lesion)
    target_lesion[mel.rotomap.moles.KEY_IS_UNCHANGED] = is_unchanged
    mel.rotomap.moles.save_rotomap_dir_lesions_file(
        rotomap.path, rotomap.lesions
    )

class ImageCompareDisplay:
    """Display two images in a window, supply controls for comparing a list."""

    def __init__(self, logger, screen, path_images_tuple, uuid_):
        self._logger = logger
        self._image_path = None
        self._uuid = None
        self._should_draw_crosshairs = True
        self._display = screen
        self._melroot = mel.lib.fs.find_melroot()
        self.reset(path_images_tuple, uuid_)

    def _reset_logger(self):
        self._logger.reset(
            mode="compare",
            path=str(
                os.path.relpath(
                    os.path.abspath(self._image_path),
                    start=self._melroot,
                )
            )
            + ":"
            + self._uuid,
        )

    def reset(self, path_images_tuple, uuid_):
        if not path_images_tuple:
            raise ValueError(
                "path_images_tuple must be a tuple with at least one thing."
            )

        for group in path_images_tuple:
            if not group:
                raise ValueError("path_images_tuple not have empty groups.")

        self._uuid = uuid_
        self._rotomaps = path_images_tuple
        self._zooms = [1 for _ in path_images_tuple]
        self._rotations = [0 for _ in path_images_tuple]

        self._rotomap_cursors = [0] * len(self._rotomaps)
        for i, rotomap in enumerate(self._rotomaps):
            centre_index, _ = min(
                enumerate(self._rotomaps[i]),
                key=lambda x: x[1].ellipse_xpos * x[1].ellipse_xpos,
            )
            self._rotomap_cursors[i] = centre_index

        self._indices = [0, -1]

        self._should_indicate_changed = None

        self.auto_align_and_show()
        self._reset_logger()

    def next_image(self):
        ix = self._indices[0]
        num_images = len(self._rotomaps[ix])
        self._rotomap_cursors[ix] += 1
        self._rotomap_cursors[ix] %= num_images
        self.auto_align_and_show()

    def prev_image(self):
        ix = self._indices[0]
        num_images = len(self._rotomaps[ix])
        self._rotomap_cursors[ix] -= 1
        self._rotomap_cursors[ix] %= num_images
        self.auto_align_and_show()

    def next_rotomap(self):
        num_rotomaps = len(self._rotomaps)
        self._indices[0] += 1
        self._indices[0] %= num_rotomaps
        self.auto_align_and_show()

    def prev_rotomap(self):
        num_rotomaps = len(self._rotomaps)
        self._indices[0] -= 1
        self._indices[0] %= num_rotomaps
        self.auto_align_and_show()

    def swap_images(self):
        self._indices.reverse()
        self._show()

    def toggle_crosshairs(self):
        self._should_draw_crosshairs = not self._should_draw_crosshairs
        self._show()

    def indicate_changed(self, should_indicate_changed=True):
        self._should_indicate_changed = should_indicate_changed
        self._show()

    def adjust_zoom(self, zoom_multiplier):
        ix = self._indices[0]
        self._zooms[ix] *= zoom_multiplier
        self._show()

    def adjust_rotation(self, rotation_modifier):
        ix = self._indices[0]
        self._rotations[ix] += rotation_modifier
        self._show()

    def _posinfo(self, index):
        ix = self._indices[index]
        image_index = self._rotomap_cursors[ix]
        return self._rotomaps[ix][image_index]

    def auto_align_and_show(self):
        left_posinfo = self._posinfo(0)
        right_posinfo = self._posinfo(1)
        target_uuid = left_posinfo.uuid
        assert right_posinfo.uuid == target_uuid

        common_uuids = set(left_posinfo.uuid_points) & set(
            right_posinfo.uuid_points
        )
        common_uuids.remove(target_uuid)
        if not common_uuids:
            self._show()
            return

        left_target_pos = [
            pos
            for uuid_, pos in left_posinfo.uuid_points.items()
            if uuid_ == target_uuid
        ][0]

        nearest_common_uuid = min(
            common_uuids,
            key=lambda u: mel.lib.math.distance_sq_2d(
                left_posinfo.uuid_points[u], left_target_pos
            ),
        )

        left_dist = math.sqrt(
            mel.lib.math.distance_sq_2d(
                left_posinfo.uuid_points[nearest_common_uuid], left_target_pos
            )
        )

        right_target_pos = [
            pos
            for uuid_, pos in right_posinfo.uuid_points.items()
            if uuid_ == target_uuid
        ][0]

        right_dist = math.sqrt(
            mel.lib.math.distance_sq_2d(
                right_posinfo.uuid_points[nearest_common_uuid],
                right_target_pos,
            )
        )

        self._zooms[self._indices[0]] = right_dist / left_dist
        self._zooms[self._indices[1]] = 1.0

        left_angle = mel.lib.math.angle(
            left_posinfo.uuid_points[nearest_common_uuid] - left_target_pos
        )
        right_angle = mel.lib.math.angle(
            right_posinfo.uuid_points[nearest_common_uuid] - right_target_pos
        )

        self._rotations[self._indices[0]] = right_angle - left_angle
        self._rotations[self._indices[1]] = 1.0

        self._show()

    def _path_pos_zoom_rotation(self, index):
        image_index = self._rotomap_cursors[index]
        posinfo = self._rotomaps[index][image_index]
        zoom = self._zooms[index]
        rotation = self._rotations[index]
        return posinfo.path, posinfo.pos, zoom, rotation

    def _show(self):
        image_width = self._display.width // 2
        image_height = self._display.height
        image_size = numpy.array((image_width, image_height))
        border_colour = None
        if self._should_indicate_changed is not None:
            if self._should_indicate_changed:
                border_colour = (0, 0, 255)
            else:
                border_colour = (0, 255, 0)

        images = [
            captioned_mole_image(
                *self._path_pos_zoom_rotation(i),
                image_size,
                self._should_draw_crosshairs,
                border_colour,
            )
            for i in self._indices
        ]
        self._image_path = self._path_pos_zoom_rotation(self._indices[-1])[0]
        montage = mel.lib.image.montage_horizontal(10, *images)
        self._display.show_opencv_image(montage)

def captioned_mole_image(
    path,
    pos,
    zoom,
    rotation_degs,
    size,
    should_draw_crosshairs,
    border_colour=None,
):

    image, caption_shape = _cached_captioned_mole_image(
        str(path), tuple(pos), zoom, tuple(size), rotation_degs
    )

    if should_draw_crosshairs:
        image_crosshairs = image.copy()
        xpos = image.shape[1] // 2
        ypos = (image.shape[0] - caption_shape[0]) // 2

        mel.rotomap.display.draw_crosshair(image_crosshairs, xpos, ypos)
        image = cv2.addWeighted(image, 0.75, image_crosshairs, 0.25, 0.0)

    if border_colour is not None:
        cv2.rectangle(image, (0, 0), (image.shape[1], 10), border_colour, -1)

    return image

@functools.lru_cache()
def _cached_captioned_mole_image(path, pos, zoom, size, rotation_degs):
    image = mel.lib.image.load_image(path)
    image = mel.lib.image.scale_image(image, zoom)
    pos = tuple(int(v * zoom) for v in pos)
    size = numpy.array(size)
    max_size = 2 * max(size)
    max_size = numpy.array([max_size, max_size])
    max_size_2 = 2 * max_size
    image = mel.lib.image.centered_at(image, pos, max_size_2)
    image = mel.lib.image.rotated(image, rotation_degs)
    image = mel.lib.image.centered_at(image, max_size, size)
    caption = mel.lib.image.render_text_as_image(str(path))
    return (
        mel.lib.image.montage_vertical(10, image, caption),
        caption.shape,
    )

# -----------------------------------------------------------------------------
# Copyright (C) 2018-2021 Angelos Evripiotis.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------ END-OF-FILE ----------------------------------


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

<hibernate-mapping package="auxiliares">
	<class name="auxiliares.Carro" table="carros">
		<id name="id" type="long" column="id" >
            <generator class="identity" />
		</id>

		<property name="modelo">
			<column name="modelo" />
		</property>
		<property name="marca">
			<column name="marca" />
		</property>
		<property name="ano">
			<column name="ano" />
		</property>
		<property name="cor">
			<column name="cor" />
		</property>
	</class>
</hibernate-mapping>


text:
using System.Xml.Linq;
using Microsoft.Xrm.Portal.Runtime;
using Microsoft.Xrm.Sdk.Metadata;

namespace Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView
{
	public abstract class CellContainerTemplate : CrmEntityFormViewTemplate
	{
		protected CellContainerTemplate(XNode node, int languageCode, EntityMetadata entityMetadata, ICellTemplateFactory cellTemplateFactory)
			: base(node, languageCode, entityMetadata)
		{
			cellTemplateFactory.ThrowOnNull("cellTemplateFactory");

			CellTemplateFactory = cellTemplateFactory;
		}

		protected ICellTemplateFactory CellTemplateFactory { get; private set; }
	}
}


text:
WebClient provides a simple yet complete HTTP client implementation.

To view the documentation evaluate:

	HelpBrowser openOn: WebClientHelp.


text:
class DummyService < Service
  attr_accessor :responses, :sleep

  def initialize(config = {})
    self.responses = []
    self.sleep = 0
    super
  end

  def service_types_generated
    responses.collect {|r| ServiceTypeValue[ r["service_type_value"] ]}.compact.uniq
  end

  def handle(request)

    ::Kernel.sleep( self.sleep ) if self.sleep

    responses.each do |response|
      request.add_service_response( { :service => self }.merge(response.symbolize_keys ) )
    end

    return request.dispatched(self, true)
  end

end


text:
package ru.job4j.max;

import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
	Test program "Max".

	@author DmitriyBystranov (mailto: dbystranov@mail.ru)
	@version 1.0
	@since 30.05.2017
*/

public class MaxTest {

	/**
		Test add.
	*/

    @Test
    public void whenAddOnePlusOneThenTwo() {
        Max maxTest = new Max();
        int result = maxTest.max1(1, 2);
        int expected = 2;
        assertThat(result, is(expected));
	}
}


text:
package org.cactoos.io;

import java.io.IOException;
import org.hamcrest.core.IsNull;
import org.junit.jupiter.api.Test;
import org.llorllale.cactoos.matchers.Assertion;
import org.llorllale.cactoos.matchers.Throws;

/**
 * Test case for {@link CheckedOutput}.
 *
 * @since 0.31
 * @checkstyle JavadocMethodCheck (500 lines)
 */
final class CheckedOutputTest {

    @Test
    void runtimeExceptionIsNotWrapped() {
        new Assertion<>(
            "must not wrap runtime exception",
            new CheckedOutput<>(
                () -> {
                    throw new IllegalStateException("runtime1");
                },
                IOException::new
            )::stream,
            new Throws<>(IllegalStateException.class)
        ).affirm();
    }

    @Test
    void checkedExceptionIsWrapped() {
        new Assertion<>(
            "must wrap checked exception",
            new CheckedOutput<>(
                () -> {
                    throw new IOException("runtime2");
                },
                IOException::new
            )::stream,
            new Throws<>(IOException.class)
        ).affirm();
    }

    @Test
    void extraWrappingIgnored() {
        try {
            new CheckedOutput<>(
                () -> {
                    throw new IOException("runtime3");
                },
                IOException::new
            ).stream();
        } catch (final IOException exp) {
            new Assertion<>(
                "must not add extra wrapping of IOException",
                exp.getCause(),
                new IsNull<>()
            ).affirm();
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Asterotrema orbiculinum (Müll. Arg.) Müll. Arg.

### Remarks
null


text:
"""
Display DNS resolution success on a configured domain.

This module launch a simple query on each nameservers for the specified domain.
Nameservers are dynamically retrieved. The FQDN is the only one mandatory parameter.
It's also possible to add additional nameservers by appending them in nameservers list.

The default resolver can be overwritten with my_resolver.nameservers parameter.

Configuration parameters:
    - domain : domain name to check
    - lifetime : resolver lifetime
    - nameservers : comma separated list of reference DNS nameservers
    - resolvers : comma separated list of DNS resolvers to use

@author nawadanp
"""

import dns.resolver
import socket

class Py3status:
    """
    """
    # available configuration parameters
    domain = ''
    lifetime = 0.3
    nameservers = ''
    resolvers = ''

    def ns_checker(self, i3s_output_list, i3s_config):
        response = {'full_text': ''}
        counter = 0
        error = False
        nameservers = []

        # parse some configuration parameters
        if not isinstance(self.nameservers, list):
            self.nameservers = self.nameservers.split(',')
        if not isinstance(self.resolvers, list):
            self.resolvers = self.resolvers.split(',')

        my_resolver = dns.resolver.Resolver()
        my_resolver.lifetime = self.lifetime
        if self.resolvers:
            my_resolver.nameservers = self.resolvers

        my_ns = my_resolver.query(self.domain, 'NS')

        # Insert each NS ip address in nameservers
        for ns in my_ns:
            nameservers.append(str(socket.gethostbyname(str(ns))))
        for ns in self.nameservers:
            nameservers.append(str(ns))

        # Perform a simple DNS query, for each NS servers
        for ns in nameservers:
            my_resolver.nameservers = [ns]
            counter += 1
            try:
                my_resolver.query(self.domain, 'A')
            except:
                error = True

        if error:
            response['full_text'] = str(counter) + ' NS NOK'
            response['color'] = i3s_config['color_bad']
        else:
            response['full_text'] = str(counter) + ' NS OK'
            response['color'] = i3s_config['color_good']

        return response

if __name__ == "__main__":
    """
    Test this module by calling it directly.
    """
    from time import sleep
    x = Py3status()
    config = {
        'color_good': '#00FF00',
        'color_bad': '#FF0000',
    }
    while True:
        print(x.ns_checker([], config))
        sleep(1)


text:
/**
 * Name: Clone Graph
 * Number: 133
 * Tag: BFS
 * Main Points:
   pay attention to queue.offer(neighbor)
   we can't add sth to queue repeatedly, so we offer(neighbor) under the condition !map.containsKey(neighbor)
 * Time Complexity: O(E + V)
 * Space Complexity: O(V) (queue take up V, map take up V)
**/
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) return null;

        HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
        Queue<UndirectedGraphNode> queue = new LinkedList<>();

        queue.offer(node);

        while (!queue.isEmpty()) {
            UndirectedGraphNode cur = queue.poll();
            if (!map.containsKey(cur)) {
                map.put(cur, new UndirectedGraphNode(cur.label));
            }

            for (UndirectedGraphNode neighbor : cur.neighbors) {
                if (!map.containsKey(neighbor)) {
                    map.put(neighbor, new UndirectedGraphNode(neighbor.label));
                    queue.offer(neighbor);
                }
                map.get(cur).neighbors.add(map.get(neighbor));
            }
        }
        return map.get(node);
    }
}


text:
*MIT License - Copyright 2016 Hans Raaf - METATEXX GmbH*

Pre alpha WIP Nim Module for creating PHP extensions using native Zend (unsupported).

## Basic usage of NimZend

For development of NimZend modules you should enable `dl()` (loading of dynamic libraries) in you php.ini. This is the only thing which is not yet handled by the config script. Everything else should work just by calling the nim build tasks from the included config template.

After enabling `dl()` it should be as easy as changing into the `nimext` directory of the examples and running `nim build nimext.nim` followed by `nim tests nimext.nim`. If all works right your PHP cli will execute the code from the extension.

Code for you module can be as simple as:

File: `nimfun.nim`

```nim
import nimzend

proc nimFun(a: int, b: int): ZValArray {.phpfunc.} =
  result["add"] = a + b
  result["sub"] = a - b
  result["concat"] = $a & $b
  var arr = zvalArray()
  arr.add a
  arr.add b
  result["array"] = arr

finishExtension("nimfun.so", "0.1")
```

File: `config.nims`

```nim
# the extension name
var extensionName = "nimfun"

# include the configuration template
include "cfgtpl.nims"

# our tests
task tests, "runs a simple test":
  setCommand "nop"
  exec phpExe & """ test.php"""
```

File: `test.php`

```php
<?php
dl("nimfun.so");
print_r(nimFun(124, 111));
```

Building, installing and testing the extension is pretty easy

Shell:

```
> nim build nimfun
building ...
installing ...

> nim tests
Array
(
    [add] => 235
    [sub] => 13
    [concat] => 124111
    [array] => Array
        (
            [0] => 124
            [1] => 111
        )

)
```

*P.S.: The above code is [here](examples/nimfun)*

## What is supported?

This is not an auto translation but an manually written Nim interface to the Zend API. Which is itself driven by a huge amount of #define macros.

We only plan to support basic functionality and types for now.

The code support building of PHP 5.3 up to PHP 7.0 extensions with the same Nim source. While out first experiments are mainly for PHP 5.4 this will eventually shift to PHP 7.0. Maybe some day in the future we will remove the support for PHP < 7. After all PHP 5 will be deprecated in August 2016.

## Creating your own NimZend modules

To create your own modules you can use `nimble install` in the repository root to install nimzend as a local package. After this you can include both "nimzend.nim" and "cfgtpl.nims" in your modules. Simply copy one of the examples as stand alone directory and adjust the paths to the module to not be relative anymore.

P.S.: We do not support Windows and probably never will. PRs which are not to convoluted may be accepted though.

Have Fun!

*The Team of METATEXX GmbH*


text:
部署詳細

<?php echo form_open();?>

	部署ID
	<?php echo $group_row->get_id();?>

    部署名
    <?php echo htmlspecialchars($group_row->get_name(),ENT_QUOTES);?>

	<?php echo form_submit(['name'=>'cancel','class'=>'btn btn-primary','value'=>'一覧に戻る'])?>
	<?php echo form_submit(['name'=>'edit','class'=>'btn btn-default','value'=>'編集'])?>
<?php echo form_button(['data-target'=>'#deleteModal','data-toggle'=>'modal','class'=>'btn btn-danger','content'=>'削除'])?>

					<button type="button" class="close" data-dismiss="modal">×</button>

本当に削除してよろしいですか?

					<?php echo form_button(['data-dismiss'=>'modal','class'=>'btn btn-default','content'=>'Cancel'])?>
					<?php echo form_submit(['name'=>'delete','class'=>'btn btn-primary','value'=>'OK'])?>

<?php echo form_close();?>


text:
"""
Description

Runtime:
Space:

Example:

Input: [format]
[]

Output: [format]
[]
"""

def RemoveDups(input):
    return None


text:
/*
 ONOS GUI -- Settings View -- CSS file
 */

#ov-settings h2 {
    display: inline-block;
}

#ov-settings div.ctrl-btns {
    width: 45px;
}

#ov-settings div.summary-list td.notdef {
    color: #0071bd;
    font-weight: bold;
}

#settings-details-panel .container {
    padding: 0 30px;
    overflow-y: scroll;
}

#settings-details-panel .close-btn {
    position: absolute;
    right: 26px;
    top: 26px;
    cursor: pointer;
}

#settings-details-panel .top .settings-title-1 {
    width: 90%;
    height: 28px;
    font-size: 14pt;
    font-weight: lighter;
    overflow: hidden;
    white-space: nowrap;
    padding: 0 12px 0 2px;
    margin-top: 19px;
    margin-bottom: 5px;
}

#settings-details-panel .top .settings-title-2 {
    width: 90%;
    height: 52px;
    font-size: 20pt;
    font-weight: lighter;
    overflow: hidden;
    white-space: nowrap;
    padding: 0 6px 0 2px;
    margin-top: 5px;
    margin-bottom: 5px;
}

#settings-details-panel td.label {
    font-weight: bold;
    text-align: right;
    font-size: 12pt;
    padding-right: 6px;
    vertical-align: top;
    width: 120px;
}