text:
const homeOrTmp = require('home-or-tmp');
const path = require('path');

const _resolveCloneDir = (opts) => {
    return (opts && opts.clone_dir) ?
        opts.clone_dir : path.join(homeOrTmp, 'unity-npm-utils-packages');
}

module.exports = _resolveCloneDir;

redpajama_set_name: RedPajamaGithub


text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.serverlist.commands;

import io.github.nucleuspowered.nucleus.Nucleus;
import io.github.nucleuspowered.nucleus.Util;
import io.github.nucleuspowered.nucleus.argumentparsers.BoundedIntegerArgument;
import io.github.nucleuspowered.nucleus.internal.annotations.RunAsync;
import io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions;
import io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand;
import io.github.nucleuspowered.nucleus.internal.command.AbstractCommand;
import io.github.nucleuspowered.nucleus.internal.command.NucleusParameters;
import io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException;
import io.github.nucleuspowered.nucleus.modules.serverlist.datamodules.ServerListGeneralDataModule;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.util.annotation.NonnullByDefault;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Optional;

@Permissions(prefix = "serverlist")
@RunAsync
@RegisterCommand(value = { "message", "m" }, subcommandOf = ServerListCommand.class)
@NonnullByDefault
public class TemporaryMessageCommand extends AbstractCommand<CommandSource> {

    private final String line = "line";

    @Override public CommandElement[] getArguments() {
        return new CommandElement[] {
            GenericArguments.flags()
                .flag("r", "-remove")
                .valueFlag(new BoundedIntegerArgument(Text.of(this.line), 1, 2),"l", "-line")
                .valueFlag(NucleusParameters.DURATION, "t", "-time")
                .buildWith(NucleusParameters.OPTIONAL_MESSAGE)
        };
    }

    @Override protected CommandResult executeCommand(CommandSource src, CommandContext args, Cause cause) throws Exception {
        // Get the temporary message item.
        ServerListGeneralDataModule mod = Nucleus.getNucleus().getGeneralService().get(ServerListGeneralDataModule.class);

        if (args.hasAny("r")) {
            if (mod.getMessage().isPresent()) {
                // Remove
                mod.remove();

                // Send message.
                src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.serverlist.message.removed"));
                return CommandResult.success();
            }

            throw ReturnMessageException.fromKey("command.serverlist.message.noremoved");
        }

        // Which line?
        boolean linetwo = args.<Integer>getOne(this.line).map(x -> x == 2).orElse(false);

        Optional<String> onMessage = args.getOne(NucleusParameters.Keys.MESSAGE);

        if (!onMessage.isPresent()) {
            boolean isValid = mod.getExpiry().map(x -> x.isAfter(Instant.now())).orElse(false);
            if (!isValid) {
                throw ReturnMessageException.fromKey("command.serverlist.message.isempty");
            }

            if (linetwo) {
                mod.setLineTwo(null);
            } else {
                mod.setLineOne(null);
            }

            Optional<Text> newMessage = mod.getMessage();

            if (newMessage.isPresent()) {
                // Send message
                src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.serverlist.message.set"));
                src.sendMessage(newMessage.get());
            } else {
                src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.serverlist.message.empty"));
            }

            return CommandResult.success();
        }

        String nMessage = onMessage.get();

        // If the expiry is null or before now, and there is no timespan, then it's an hour.
        Instant endTime = args.<Long>getOne(NucleusParameters.Keys.DURATION).map(x -> Instant.now().plus(x, ChronoUnit.SECONDS))
                .orElseGet(() -> mod.getExpiry().map(x -> x.isBefore(Instant.now()) ? x.plusSeconds(3600) : x)
                .orElseGet(() -> Instant.now().plusSeconds(3600)));

        // Set the expiry.
        mod.setExpiry(endTime);
        if (linetwo) {
            mod.setLineTwo(nMessage);
        } else {
            mod.setLineOne(nMessage);
        }

        Optional<Text> newMessage = mod.getMessage();

        if (newMessage.isPresent()) {
            // Send message
            src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.serverlist.message.set"));
            src.sendMessage(newMessage.get());
            src.sendMessage(Nucleus.getNucleus().getMessageProvider()
                    .getTextMessageWithFormat("command.serverlist.message.expiry", Util.getTimeToNow(endTime)));
            return CommandResult.success();
        }

        throw ReturnMessageException.fromKey("command.serverlist.message.notset");
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lichen citrinus Hedw.

### Remarks
null


text:
'use strict';

const common = require('../common');
if (!common.hasCrypto)
  common.skip('missing crypto');
const assert = require('assert');
const http2 = require('http2');

const expectValue = 'meoww';

const server = http2.createServer(common.mustNotCall());

server.once('checkExpectation', common.mustCall((req, res) => {
  assert.strictEqual(req.headers.expect, expectValue);
  res.statusCode = 417;
  res.end();
}));

server.listen(0, common.mustCall(() => nextTest(2)));

function nextTest(testsToRun) {
  if (!testsToRun) {
    return server.close();
  }

  const port = server.address().port;
  const client = http2.connect(`http://localhost:${port}`);
  const req = client.request({
    ':path': '/',
    ':method': 'GET',
    ':scheme': 'http',
    ':authority': `localhost:${port}`,
    'expect': expectValue
  });

  req.on('response', common.mustCall((headers) => {
    assert.strictEqual(headers[':status'], 417);
    req.resume();
  }));

  req.on('end', common.mustCall(() => {
    client.close();
    nextTest(testsToRun - 1);
  }));
}


text:
// Author: Daniele Giardini - http://www.demigiant.com
// Created: 2015/03/11 18:21

using System;
using UnityEditor;
using UnityEngine;

namespace DG.DOTweenEditor.Core
{
    public class DelayedCall
    {
        public float delay;
        public Action callback;
        float _startupTime;

        public DelayedCall(float delay, Action callback)
        {
            this.delay = delay;
            this.callback = callback;
            _startupTime = Time.realtimeSinceStartup;
            EditorApplication.update += Update;
        }

        void Update()
        {
            if (Time.realtimeSinceStartup - _startupTime >= delay) {
                if (EditorApplication.update != null) EditorApplication.update -= Update;
                if (callback != null) callback();
            }
        }
    }
}


text:
@interface NSString (CSV)

- (NSArray *)vfe_csvComponents;

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<title>CURLOPT_LOCALPORT man page</title>
<meta name="generator" content="roffit">

NAME

CURLOPT_LOCALPORT - set local port number to use for socket
SYNOPSIS

#include <curl/curl.h>

CURLcode curl_easy_setopt(CURL *handle, CURLOPT_LOCALPORT, long port);
DESCRIPTION

Pass a long. This sets the local port number of the socket used for the connection. This can be used in combination with CURLOPT_INTERFACE and you are recommended to use CURLOPT_LOCALPORTRANGE as well when this option is set. Valid port numbers are 1 - 65535.
DEFAULT

0, disabled - use whatever the system thinks is fine
PROTOCOLS

All
EXAMPLE

TODO
AVAILABILITY

Added in 7.15.2
RETURN VALUE

Returns CURLE_OK
SEE ALSO

CURLOPT_LOCALPORTRANGE, CURLOPT_INTERFACE

 This HTML page was made with roffit.


text:
package soot.jimple.infoflow.test.android;

public class TelephonyManager {

	public static String getDeviceId(){
		return "I1t359-f";
	}

	public static int getIMEI() {
		return 123;
	}

	public static int getIMSI() {
		return 321;
	}

}


text:
from shutit_module import ShutItModule

class test3(ShutItModule):

	def build(self, shutit):
		s1=shutit.create_session()
		s1out=s1.send_and_get_output('echo $$')
		s2=shutit.create_session()
		s2out=s2.send_and_get_output('echo $$')
		assert s1out != s2out
		return True

def module():
		return test3(
			'bash_tests.test3.test3', 2010087968.00011256,
			description='',
			maintainer='',
			delivery_methods=['bash'],
			depends=['shutit.tk.setup']
		)


text:
<?php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Table(name="indent")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\IndentRepository")
 */
class Indent
{

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Cart", inversedBy="indent")
     * @ORM\JoinColumn(name="cart_id", referencedColumnName="id", nullable=true)
     */
    private $cart;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Product",inversedBy="indent")
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=true)
     */
    private $product;

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    private $quantity;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set quantity
     *
     * @param integer $quantity
     *
     * @return Indent
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;

        return $this;
    }

    /**
     * Get quantity
     *
     * @return integer
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * Set cart
     *
     * @param \AppBundle\Entity\Cart $cart
     *
     * @return Indent
     */
    public function setCart(\AppBundle\Entity\Cart $cart)
    {
        $this->cart = $cart;

        return $this;
    }

    /**
     * Get cart
     *
     * @return \AppBundle\Entity\Cart
     */
    public function getCart()
    {
        return $this->cart;
    }

    /**
     * Set product
     *
     * @param \AppBundle\Entity\Product $product
     *
     * @return Indent
     */
    public function setProduct(\AppBundle\Entity\Product $product)
    {
        $this->product = $product;

        return $this;
    }

    /**
     * Get product
     *
     * @return \AppBundle\Entity\Product
     */
    public function getProduct()
    {
        return $this->product;
    }
}


text:
function createFilterDeeperAny() {
    'use strict';
    var filterDeeperAny = function filterDeeperAny() {
        return {
            ok: true,
            next: filterDeeperAny
        };
    };
    filterDeeperAny.toString = function() {
        return 'filterDeeperAny()';
    };
    return filterDeeperAny;
}


text:
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
    name: 'date'
})

export class DatePipe implements PipeTransform {
    transform(date: any, type: string): any {
        if (!date) return;
        switch(type) {
            case 'sm': return moment(date).format('LT');
            case 'md': return moment(date).format('ll');
            case 'lg': return moment(date).format('lll');
            default: throw new Error(`Invalid date type specified: ${type}`);
        }
    }
}


text:
<?xml version="1.0"?>
<!DOCTYPE MODE SYSTEM "xmode.dtd">

<MODE>

    <PROPS>

        <PROPERTY NAME="commentStart" VALUE="/*"/>
        <PROPERTY NAME="commentEnd" VALUE="*/"/>

        <PROPERTY NAME="wordBreakChars" VALUE=",/+=*"/>
        <PROPERTY NAME="noWordSep" VALUE="-_:."/>

    </PROPS>

    <RULES IGNORE_CASE="TRUE" HIGHLIGHT_DIGITS="TRUE" NO_WORD_SEP="-_:."
        DIGIT_RE="([0-9])*\.?([0-9])+" DEFAULT="LITERAL3">

        <IMPORT DELEGATE="leading-comments"/>
        <IMPORT DELEGATE="strings"/>
        <IMPORT DELEGATE="variables"/>
        <IMPORT DELEGATE="templates"/>
        <IMPORT DELEGATE="statements"/>
        <IMPORT DELEGATE="xml-tags"/>
        <IMPORT DELEGATE="trailing-comments"/>
    </RULES>

    <RULES SET="leading-comments">

            <BEGIN>/*</BEGIN>
            <END>*/</END>

    </RULES>

    <RULES SET="trailing-comments">
        <SPAN_REGEXP TYPE="LITERAL3">
            <BEGIN>((;)|(\})|(\{)|(\)))(\s)*/\*</BEGIN>
            <END>*/</END>
        </SPAN_REGEXP>
    </RULES>

    <RULES SET="strings">

            <BEGIN>"</BEGIN>
            <END>"</END>

            <BEGIN>'</BEGIN>
            <END>'</END>

    </RULES>

    <RULES SET="xml-tags" DEFAULT="KEYWORD3">
        <SPAN_REGEXP TYPE="KEYWORD3" DELEGATE="inside-the-tag">
            <BEGIN><![CDATA[<([a-z]|[A-Z])]]></BEGIN>
            <END><![CDATA[>]]></END>
        </SPAN_REGEXP>
    </RULES>

    <RULES SET="inside-the-tag" DEFAULT="KEYWORD3">
        <SPAN_REGEXP TYPE="LITERAL3" DELEGATE="attribute">
            <BEGIN>(\s)+(?!>)</BEGIN>
            <END>=</END>
        </SPAN_REGEXP>
        <IMPORT DELEGATE="strings"/>
    </RULES>

    <RULES SET="attribute" DEFAULT="KEYWORD4">
    </RULES>

    <RULES SET="variables">
        <MARK_FOLLOWING TYPE="KEYWORD2">$</MARK_FOLLOWING>
    </RULES>

    <RULES SET="templates">
        <MARK_PREVIOUS TYPE="FUNCTION" MATCH_TYPE="LITERAL3">(</MARK_PREVIOUS>
    </RULES>

    <RULES SET="statements">
        <KEYWORDS>
            <KEYWORD1>if</KEYWORD1>
            <KEYWORD1>version</KEYWORD1>
            <KEYWORD1>ns</KEYWORD1>
            <KEYWORD1>param</KEYWORD1>
            <KEYWORD1>var</KEYWORD1>
            <KEYWORD1>template</KEYWORD1>
            <KEYWORD1>match</KEYWORD1>
            <KEYWORD1>else</KEYWORD1>
            <KEYWORD1>copy-of</KEYWORD1>
            <KEYWORD1>copy</KEYWORD1>
            <KEYWORD1>call</KEYWORD1>
            <KEYWORD1>apply-templates</KEYWORD1>
            <KEYWORD1>expr</KEYWORD1>
            <KEYWORD1>import</KEYWORD1>
            <KEYWORD1>input</KEYWORD1>
            <KEYWORD1>for-each</KEYWORD1>
            <KEYWORD1>mode</KEYWORD1>
            <KEYWORD1>priority</KEYWORD1>
            <KEYWORD1>extension</KEYWORD1>
            <KEYWORD1>preserve-space</KEYWORD1>
            <KEYWORD1>strip-space</KEYWORD1>
            <KEYWORD1>with</KEYWORD1>
        </KEYWORDS>
    </RULES>

</MODE>


text:
<?xml version="1.0" encoding="UTF-8"?>
<component xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/component/1.1.3"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/component/1.1.3 http://maven.apache.org/xsd/component-1.1.3.xsd">
    <files>
        <file>
            <source>${project.build.directory}/${project.artifactId}-${project.version}-tests.jar</source>
            <destName>${project.artifactId}-test.jar</destName>
        </file>
        <file>
            <source>${project.build.directory}/${project.artifactId}-${project.version}-test-javadoc.jar</source>
            <destName>${project.artifactId}-test-doc-api.zip</destName>
        </file>
        <file>
            <source>${project.build.directory}/${project.artifactId}-${project.version}-test-design-javadoc.jar</source>
            <destName>${project.artifactId}-test-doc-design.zip</destName>
        </file>
        <file>
            <source>${project.build.directory}/${project.artifactId}-${project.version}-test-sources.jar</source>
            <destName>${project.artifactId}-test-src.zip</destName>
        </file>
    </files>
</component>


text:
class TransactionsController < ApplicationController
  before_action :set_transaction, only: [:show, :edit, :update, :destroy]

  # GET /transactions
  # GET /transactions.json
  def index
    @transactions = Transaction.where delivered: nil
  end

  # GET /transactions/1
  # GET /transactions/1.json
  def show
  end

  # GET /transactions/new
  def new
    @transaction = Transaction.new
  end

  # GET /transactions/1/edit
  def edit
  end

  # POST /transactions
  # POST /transactions.json
  def create
    @prize = Prize.find(params[:prize_id])
    @transaction = @prize.transactions.build(transaction_params)
    @transaction.user = current_user
    @transaction.cost = @prize.cost

    respond_to do |format|
      if @transaction.save
        @transaction.user.pay_for(@prize)
        format.html { redirect_to prizes_path,
          notice: 'Order recieved.  We will deliever your prize as soon as possible' }
        format.json { render action: 'show', status: :created, location: @transaction }
      else
        format.html { render action: 'new' }
        format.json { render json: @transaction.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /transactions/1
  # PATCH/PUT /transactions/1.json
  def update
    respond_to do |format|
      if @transaction.update(transaction_params)
        format.html { redirect_to transactions_path, notice: 'Transaction was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @transaction.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /transactions/1
  # DELETE /transactions/1.json
  def destroy
    @transaction.user.refund(@transaction.prize)
    @transaction.destroy
    respond_to do |format|
      format.html { redirect_to transactions_url, notice: "Refunded" }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_transaction
      @transaction = Transaction.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def transaction_params
      params.require(:transaction).permit(:user_id, :prize_id, :cost, :delivered, :answer)
    end
end


text:
package org.lambda4j.consumer.tri.obj;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.DoubleFunction;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.LongFunction;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.lambda4j.Lambda;
import org.lambda4j.consumer.Consumer2;
import org.lambda4j.consumer.ShortConsumer;
import org.lambda4j.consumer.bi.BiShortConsumer;
import org.lambda4j.consumer.bi.obj.ObjShortConsumer;
import org.lambda4j.consumer.tri.TriBooleanConsumer;
import org.lambda4j.consumer.tri.TriByteConsumer;
import org.lambda4j.consumer.tri.TriCharConsumer;
import org.lambda4j.consumer.tri.TriConsumer;
import org.lambda4j.consumer.tri.TriDoubleConsumer;
import org.lambda4j.consumer.tri.TriFloatConsumer;
import org.lambda4j.consumer.tri.TriIntConsumer;
import org.lambda4j.consumer.tri.TriLongConsumer;
import org.lambda4j.consumer.tri.TriShortConsumer;
import org.lambda4j.function.BooleanFunction;
import org.lambda4j.function.ByteFunction;
import org.lambda4j.function.CharFunction;
import org.lambda4j.function.FloatFunction;
import org.lambda4j.function.ShortFunction;
import org.lambda4j.function.conversion.BooleanToShortFunction;
import org.lambda4j.function.conversion.ByteToShortFunction;
import org.lambda4j.function.conversion.CharToShortFunction;
import org.lambda4j.function.conversion.DoubleToShortFunction;
import org.lambda4j.function.conversion.FloatToShortFunction;
import org.lambda4j.function.conversion.IntToShortFunction;
import org.lambda4j.function.conversion.LongToShortFunction;
import org.lambda4j.function.to.ToShortFunction;
import org.lambda4j.operator.unary.ShortUnaryOperator;

/**
 * Represents an operation that accepts one object-valued and two {@code short}-valued input arguments and returns no
 * result. This is a (reference, short, short) specialization of {@link TriConsumer}. Unlike most other functional
 * interfaces, {@code ObjBiShortConsumer} is expected to operate via side-effects.
 *

 * This is a {@link FunctionalInterface} whose functional method is {@link #accept(Object, short, short)}.
 *
 * @param <T> The type of the first argument to the consumer
 * @see TriConsumer
 */
@SuppressWarnings("unused")
@FunctionalInterface
public interface ObjBiShortConsumer<T> extends Lambda {

    /**
     * Constructs a {@link ObjBiShortConsumer} based on a lambda expression or a method reference. Thereby the given
     * lambda expression or method reference is returned on an as-is basis to implicitly transform it to the desired
     * type. With this method, it is possible to ensure that correct type is used from lambda expression or method
     * reference.
     *
     * @param <T> The type of the first argument to the consumer
     * @param expression A lambda expression or (typically) a method reference, e.g. {@code this::method}
     * @return A {@code ObjBiShortConsumer} from given lambda expression or method reference.
     * @implNote This implementation allows the given argument to be {@code null}, but only if {@code null} given,
     * {@code null} will be returned.
     * @see Lambda
     * Expression
     * @see Method Reference
     */
    @CheckForNull
    @Nullable
    static <T> ObjBiShortConsumer<T> of(@Nullable ObjBiShortConsumer<T> expression) {
        return expression;
    }

    /**
     * Calls the given {@link ObjBiShortConsumer} with the given arguments and returns its result.
     *
     * @param <T> The type of the first argument to the consumer
     * @param consumer The consumer to be called
     * @param t The first argument to the consumer
     * @param value1 The second argument to the consumer
     * @param value2 The third argument to the consumer
     * @throws NullPointerException If given argument is {@code null}
     */
    static <T> void call(@Nonnull ObjBiShortConsumer<? super T> consumer, T t, short value1, short value2) {
        Objects.requireNonNull(consumer);
        consumer.accept(t, value1, value2);
    }

    /**
     * Creates a {@link ObjBiShortConsumer} which uses the {@code first} parameter of this one as argument for the given
     * {@link Consumer}.
     *
     * @param <T> The type of the first argument to the consumer
     * @param consumer The consumer which accepts the {@code first} parameter of this one
     * @return Creates a {@code ObjBiShortConsumer} which uses the {@code first} parameter of this one as argument for
     * the given {@code Consumer}.
     * @throws NullPointerException If given argument is {@code null}
     */
    @Nonnull
    static <T> ObjBiShortConsumer<T> onlyFirst(@Nonnull Consumer<? super T> consumer) {
        Objects.requireNonNull(consumer);
        return (t, value1, value2) -> consumer.accept(t);
    }

    /**
     * Creates a {@link ObjBiShortConsumer} which uses the {@code second} parameter of this one as argument for the
     * given {@link ShortConsumer}.
     *
     * @param <T> The type of the first argument to the consumer
     * @param consumer The consumer which accepts the {@code second} parameter of this one
     * @return Creates a {@code ObjBiShortConsumer} which uses the {@code second} parameter of this one as argument for
     * the given {@code ShortConsumer}.
     * @throws NullPointerException If given argument is {@code null}
     */
    @Nonnull
    static <T> ObjBiShortConsumer<T> onlySecond(@Nonnull ShortConsumer consumer) {
        Objects.requireNonNull(consumer);
        return (t, value1, value2) -> consumer.accept(value1);
    }

    /**
     * Creates a {@link ObjBiShortConsumer} which uses the {@code third} parameter of this one as argument for the given
     * {@link ShortConsumer}.
     *
     * @param <T> The type of the first argument to the consumer
     * @param consumer The consumer which accepts the {@code third} parameter of this one
     * @return Creates a {@code ObjBiShortConsumer} which uses the {@code third} parameter of this one as argument for
     * the given {@code ShortConsumer}.
     * @throws NullPointerException If given argument is {@code null}
     */
    @Nonnull
    static <T> ObjBiShortConsumer<T> onlyThird(@Nonnull ShortConsumer consumer) {
        Objects.requireNonNull(consumer);
        return (t, value1, value2) -> consumer.accept(value2);
    }

    /**
     * Applies this consumer to the given arguments.
     *
     * @param t The first argument to the consumer
     * @param value1 The second argument to the consumer
     * @param value2 The third argument to the consumer
     */
    void accept(T t, short value1, short value2);

    /**
     * Applies this consumer partially to some arguments of this one, producing a {@link BiShortConsumer} as result.
     *
     * @param t The first argument to this consumer used to partially apply this function
     * @return A {@code BiShortConsumer} that represents this consumer partially applied the some arguments.
     */
    @Nonnull
    default BiShortConsumer acceptPartially(T t) {
        return (value1, value2) -> accept(t, value1, value2);
    }

    /**
     * Applies this consumer partially to some arguments of this one, producing a {@link ShortConsumer} as result.
     *
     * @param t The first argument to this consumer used to partially apply this function
     * @param value1 The second argument to this consumer used to partially apply this function
     * @return A {@code ShortConsumer} that represents this consumer partially applied the some arguments.
     */
    @Nonnull
    default ShortConsumer acceptPartially(T t, short value1) {
        return value2 -> accept(t, value1, value2);
    }

    /**
     * Applies this consumer partially to some arguments of this one, producing a {@link ObjShortConsumer} as result.
     *
     * @param value1 The second argument to this consumer used to partially apply this function
     * @return A {@code ObjShortConsumer} that represents this consumer partially applied the some arguments.
     */
    @Nonnull
    default ObjShortConsumer<T> acceptPartially(short value1) {
        return (t, value2) -> accept(t, value1, value2);
    }

    /**
     * Applies this consumer partially to some arguments of this one, producing a {@link Consumer2} as result.
     *
     * @param value1 The second argument to this consumer used to partially apply this function
     * @param value2 The third argument to this consumer used to partially apply this function
     * @return A {@code Consumer2} that represents this consumer partially applied the some arguments.
     */
    @Nonnull
    default Consumer2<T> acceptPartially(short value1, short value2) {
        return t -> accept(t, value1, value2);
    }

    /**
     * Returns the number of arguments for this consumer.
     *
     * @return The number of arguments for this consumer.
     * @implSpec The default implementation always returns {@code 3}.
     */
    @Nonnegative
    default int arity() {
        return 3;
    }

    /**
     * Returns a composed {@link TriConsumer} that first applies the {@code before} functions to its input, and then
     * applies this consumer to the result. If evaluation of either operation throws an exception, it is relayed to the
     * caller of the composed operation.
     *
     * @param  The type of the argument to the first given function, and of composed consumer
     * @param  The type of the argument to the second given function, and of composed consumer
     * @param <C> The type of the argument to the third given function, and of composed consumer
     * @param before1 The first function to apply before this consumer is applied
     * @param before2 The second function to apply before this consumer is applied
     * @param before3 The third function to apply before this consumer is applied
     * @return A composed {@code TriConsumer} that first applies the {@code before} functions to its input, and then
     * applies this consumer to the result.
     * @throws NullPointerException If given argument is {@code null}
     * @implSpec The input argument of this method is able to handle every type.
     */
    @Nonnull
    default  TriConsumer compose(@Nonnull Function<? super A, ? extends T> before1,
            @Nonnull ToShortFunction<? super B> before2, @Nonnull ToShortFunction<? super C> before3) {
        Objects.requireNonNull(before1);
        Objects.requireNonNull(before2);
        Objects.requireNonNull(before3);
        return (a, b, c) -> accept(before1.apply(a), before2.applyAsShort(b), before3.applyAsShort(c));
    }

    /**
     * Returns a composed {@link TriBooleanConsumer} that first applies the {@code before} functions to its input, and
     * then applies this consumer to the result. If evaluation of either operation throws an exception, it is relayed to
     * the caller of the composed operation. This method is just convenience, to provide the ability to execute an
     * operation which accepts {@code boolean} input, before this primitive consumer is executed.
     *
     * @param before1 The first function to apply before this consumer is applied
     * @param before2 The second function to apply before this consumer is applied
     * @param before3 The third function to apply before this consumer is applied
     * @return A composed {@code TriBooleanConsumer} that first applies the {@code before} functions to its input, and
     * then applies this consumer to the result.
     * @throws NullPointerException If given argument is {@code null}
     * @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
     * boolean}.
     */
    @Nonnull
    default TriBooleanConsumer composeFromBoolean(@Nonnull BooleanFunction<? extends T> before1,
            @Nonnull BooleanToShortFunction before2, @Nonnull BooleanToShortFunction before3) {
        Objects.requireNonNull(before1);
        Objects.requireNonNull(before2);
        Objects.requireNonNull(before3);
        return (value1, value2, value3) -> accept(before1.apply(value1), before2.applyAsShort(value2),
                before3.applyAsShort(value3));
    }

    /**
     * Returns a composed {@link TriByteConsumer} that first applies the {@code before} functions to its input, and then
     * applies this consumer to the result. If evaluation of either operation throws an exception, it is relayed to the
     * caller of the composed operation. This method is just convenience, to provide the ability to execute an operation
     * which accepts {@code byte} input, before this primitive consumer is executed.
     *
     * @param before1 The first function to apply before this consumer is applied
     * @param before2 The second function to apply before this consumer is applied
     * @param before3 The third function to apply before this consumer is applied
     * @return A composed {@code TriByteConsumer} that first applies the {@code before} functions to its input, and then
     * applies this consumer to the result.
     * @throws NullPointerException If given argument is {@code null}
     * @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
     * byte}.
     */
    @Nonnull
    default TriByteConsumer composeFromByte(@Nonnull ByteFunction<? extends T> before1,
            @Nonnull ByteToShortFunction before2, @Nonnull ByteToShortFunction before3) {
        Objects.requireNonNull(before1);
        Objects.requireNonNull(before2);
        Objects.requireNonNull(before3);
        return (value1, value2, value3) -> accept(before1.apply(value1), before2.applyAsShort(value2),
                before3.applyAsShort(value3));
    }

    /**
     * Returns a composed {@link TriCharConsumer} that first applies the {@code before} functions to its input, and then
     * applies this consumer to the result. If evaluation of either operation throws an exception, it is relayed to the
     * caller of the composed operation. This method is just convenience, to provide the ability to execute an operation
     * which accepts {@code char} input, before this primitive consumer is executed.
     *
     * @param before1 The first function to apply before this consumer is applied
     * @param before2 The second function to apply before this consumer is applied
     * @param before3 The third function to apply before this consumer is applied
     * @return A composed {@code TriCharConsumer} that first applies the {@code before} functions to its input, and then
     * applies this consumer to the result.
     * @throws NullPointerException If given argument is {@code null}
     * @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
     * char}.
     */
    @Nonnull
    default TriCharConsumer composeFromChar(@Nonnull CharFunction<? extends T> before1,
            @Nonnull CharToShortFunction before2, @Nonnull CharToShortFunction before3) {
        Objects.requireNonNull(before1);
        Objects.requireNonNull(before2);
        Objects.requireNonNull(before3);
        return (value1, value2, value3) -> accept(before1.apply(value1), before2.applyAsShort(value2),
                before3.applyAsShort(value3));
    }

    /**
     * Returns a composed {@link TriDoubleConsumer} that first applies the {@code before} functions to its input, and
     * then applies this consumer to the result. If evaluation of either operation throws an exception, it is relayed to
     * the caller of the composed operation. This method is just convenience, to provide the ability to execute an
     * operation which accepts {@code double} input, before this primitive consumer is executed.
     *
     * @param before1 The first function to apply before this consumer is applied
     * @param before2 The second function to apply before this consumer is applied
     * @param before3 The third function to apply before this consumer is applied
     * @return A composed {@code TriDoubleConsumer} that first applies the {@code before} functions to its input, and
     * then applies this consumer to the result.
     * @throws NullPointerException If given argument is {@code null}
     * @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
     * double}.
     */
    @Nonnull
    default TriDoubleConsumer composeFromDouble(@Nonnull DoubleFunction<? extends T> before1,
            @Nonnull DoubleToShortFunction before2, @Nonnull DoubleToShortFunction before3) {
        Objects.requireNonNull(before1);
        Objects.requireNonNull(before2);
        Objects.requireNonNull(before3);
        return (value1, value2, value3) -> accept(before1.apply(value1), before2.applyAsShort(value2),
                before3.applyAsShort(value3));
    }

    /**
     * Returns a composed {@link TriFloatConsumer} that first applies the {@code before} functions to its input, and
     * then applies this consumer to the result. If evaluation of either operation throws an exception, it is relayed to
     * the caller of the composed operation. This method is just convenience, to provide the ability to execute an
     * operation which accepts {@code float} input, before this primitive consumer is executed.
     *
     * @param before1 The first function to apply before this consumer is applied
     * @param before2 The second function to apply before this consumer is applied
     * @param before3 The third function to apply before this consumer is applied
     * @return A composed {@code TriFloatConsumer} that first applies the {@code before} functions to its input, and
     * then applies this consumer to the result.
     * @throws NullPointerException If given argument is {@code null}
     * @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
     * float}.
     */
    @Nonnull
    default TriFloatConsumer composeFromFloat(@Nonnull FloatFunction<? extends T> before1,
            @Nonnull FloatToShortFunction before2, @Nonnull FloatToShortFunction before3) {
        Objects.requireNonNull(before1);
        Objects.requireNonNull(before2);
        Objects.requireNonNull(before3);
        return (value1, value2, value3) -> accept(before1.apply(value1), before2.applyAsShort(value2),
                before3.applyAsShort(value3));
    }

    /**
     * Returns a composed {@link TriIntConsumer} that first applies the {@code before} functions to its input, and then
     * applies this consumer to the result. If evaluation of either operation throws an exception, it is relayed to the
     * caller of the composed operation. This method is just convenience, to provide the ability to execute an operation
     * which accepts {@code int} input, before this primitive consumer is executed.
     *
     * @param before1 The first function to apply before this consumer is applied
     * @param before2 The second function to apply before this consumer is applied
     * @param before3 The third function to apply before this consumer is applied
     * @return A composed {@code TriIntConsumer} that first applies the {@code before} functions to its input, and then
     * applies this consumer to the result.
     * @throws NullPointerException If given argument is {@code null}
     * @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
     * int}.
     */
    @Nonnull
    default TriIntConsumer composeFromInt(@Nonnull IntFunction<? extends T> before1,
            @Nonnull IntToShortFunction before2, @Nonnull IntToShortFunction before3) {
        Objects.requireNonNull(before1);
        Objects.requireNonNull(before2);
        Objects.requireNonNull(before3);
        return (value1, value2, value3) -> accept(before1.apply(value1), before2.applyAsShort(value2),
                before3.applyAsShort(value3));
    }

    /**
     * Returns a composed {@link TriLongConsumer} that first applies the {@code before} functions to its input, and then
     * applies this consumer to the result. If evaluation of either operation throws an exception, it is relayed to the
     * caller of the composed operation. This method is just convenience, to provide the ability to execute an operation
     * which accepts {@code long} input, before this primitive consumer is executed.
     *
     * @param before1 The first function to apply before this consumer is applied
     * @param before2 The second function to apply before this consumer is applied
     * @param before3 The third function to apply before this consumer is applied
     * @return A composed {@code TriLongConsumer} that first applies the {@code before} functions to its input, and then
     * applies this consumer to the result.
     * @throws NullPointerException If given argument is {@code null}
     * @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
     * long}.
     */
    @Nonnull
    default TriLongConsumer composeFromLong(@Nonnull LongFunction<? extends T> before1,
            @Nonnull LongToShortFunction before2, @Nonnull LongToShortFunction before3) {
        Objects.requireNonNull(before1);
        Objects.requireNonNull(before2);
        Objects.requireNonNull(before3);
        return (value1, value2, value3) -> accept(before1.apply(value1), before2.applyAsShort(value2),
                before3.applyAsShort(value3));
    }

    /**
     * Returns a composed {@link TriShortConsumer} that first applies the {@code before} functions to its input, and
     * then applies this consumer to the result. If evaluation of either operation throws an exception, it is relayed to
     * the caller of the composed operation. This method is just convenience, to provide the ability to execute an
     * operation which accepts {@code short} input, before this primitive consumer is executed.
     *
     * @param before1 The first function to apply before this consumer is applied
     * @param before2 The second operator to apply before this consumer is applied
     * @param before3 The third operator to apply before this consumer is applied
     * @return A composed {@code TriShortConsumer} that first applies the {@code before} functions to its input, and
     * then applies this consumer to the result.
     * @throws NullPointerException If given argument is {@code null}
     * @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
     * short}.
     */
    @Nonnull
    default TriShortConsumer composeFromShort(@Nonnull ShortFunction<? extends T> before1,
            @Nonnull ShortUnaryOperator before2, @Nonnull ShortUnaryOperator before3) {
        Objects.requireNonNull(before1);
        Objects.requireNonNull(before2);
        Objects.requireNonNull(before3);
        return (value1, value2, value3) -> accept(before1.apply(value1), before2.applyAsShort(value2),
                before3.applyAsShort(value3));
    }

    /**
     * Returns a composed {@link ObjBiShortConsumer} that performs, in sequence, this consumer followed by the {@code
     * after} consumer. If evaluation of either operation throws an exception, it is relayed to the caller of the
     * composed operation. If performing this consumer throws an exception, the {@code after} consumer will not be
     * performed.
     *
     * @param after The consumer to apply after this consumer is applied
     * @return A composed {@link ObjBiShortConsumer} that performs, in sequence, this consumer followed by the {@code
     * after} consumer.
     * @throws NullPointerException If given argument is {@code null}
     */
    @Nonnull
    default ObjBiShortConsumer<T> andThen(@Nonnull ObjBiShortConsumer<? super T> after) {
        Objects.requireNonNull(after);
        return (t, value1, value2) -> {
            accept(t, value1, value2);
            after.accept(t, value1, value2);
        };
    }

    /**
     * Returns a composed {@link TriConsumer} which represents this {@link ObjBiShortConsumer}. Thereby the primitive
     * input argument for this consumer is autoboxed. This method provides the possibility to use this {@code
     * ObjBiShortConsumer} with methods provided by the {@code JDK}.
     *
     * @return A composed {@code TriConsumer} which represents this {@code ObjBiShortConsumer}.
     */
    @Nonnull
    default TriConsumer<T, Short, Short> boxed() {
        return this::accept;
    }
}


text:
Oslo.versions
=============

All things about `OpenStack`_ versions/releases.

* Free software: Apache license

.. _OpenStack: http://openstack.org/


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Eur. J. Protist. 33: 432-443 (1997)

#### Original name
Ordospora colligata J.I.R. Larsson, D. Ebert & J. Vavra

### Remarks
null


text:
import { wrapWithAbort } from './operators/withabort';
import { throwIfAborted } from '../aborterror';
import { OptionalFindOptions } from './findoptions';

/**
 * Returns a promise that represents how many elements in the specified async-iterable sequence satisfy a condition
 * otherwise, the number of items in the sequence.
 *
 * @template T The type of elements in the source collection.
 * @param {AsyncIterable<T>} source An async-iterable sequence that contains elements to be counted.
 * @param {OptionalFindOptions<T>} [options] The options for a predicate for filtering, thisArg for binding and AbortSignal for cancellation.
 * @returns {Promise<number>} The number of matching elements for the given condition if provided, otherwise
 * the number of elements in the sequence.
 */
export async function count<T>(
  source: AsyncIterable<T>,
  options?: OptionalFindOptions<T>
): Promise<number> {
  const { ['signal']: signal, ['thisArg']: thisArg, ['predicate']: predicate = async () => true } =
    options || {};
  throwIfAborted(signal);
  let i = 0;

  for await (const item of wrapWithAbort(source, signal)) {
    if (await predicate.call(thisArg, item, i, signal)) {
      i++;
    }
  }

  return i;
}


text:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

import { Transaction } from '../data/transaction';
import { SugardaddyService } from '../service/sugarservice';
import { PaymentRequest } from '../data/paymentrequest';
import { MemeRequest } from '../data/memerequest';

//RXJS imports
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'app-request',
  templateUrl: './request.component.html',
  styleUrls: ['./request.component.css']
})
export class RequestComponent implements OnInit {

  //@Input() transaction: Transaction;
  private paymentRequest;
  private url;
  private currentImage;
  private currentImageIndex = 0;
  private includeMeme = false;
  private shareUrl: string;
  private shareDesc: string;
  private currentMeme;

  private MEMES_BASE = [
    { id: '8279814', url: 'https://i.imgflip.com/4xgqu.jpg' },
    { id: '563423', url: 'https://i.imgflip.com/c2qn.jpg' },
    { id: '405658', url: 'https://i.imgflip.com/8p0a.jpg' },
    { id: '176908', url: 'https://i.imgflip.com/3si4.jpg' },
    { id: '5496396', url: 'https://i.imgflip.com/39t1o.jpg' },
    { id: '8072285', url: 'https://i.imgflip.com/4t0m5.jpg' },
    { id: '61556', url: 'https://i.imgflip.com/1bhw.jpg' },
    { id: '1367068', url: 'https://i.imgflip.com/tau4.jpg' }
  ];

  constructor(
    private service: SugardaddyService,
    private route: ActivatedRoute,
    private location: Location
  ) { }

  public ngOnInit() {

    this.route.params.subscribe((params) => {
      this.currentImage = this.MEMES_BASE[this.currentImageIndex];
      this.paymentRequest = new PaymentRequest(params['transactionId']);
      this.paymentRequest.memeRequest = new MemeRequest();
    });
  }

  private createPaymentRequest(): void {
    if (!this.includeMeme){
      this.paymentRequest.memeRequest = null;
    }
    else {
      this.paymentRequest.memeRequest = this.currentMeme;
    }

    this.service.createPaymentrequest(this.paymentRequest)
      .then((result) => {
        this.paymentRequest.id = result.paymentRequestId;
          this.shareUrl = 'localhost:3000/%23/payment/'+result.paymentRequestId;

          let encodedUrl = (<any>window).encodeURIComponent(this.paymentRequest.description);
          this.shareDesc = encodedUrl;
          console.log(this.shareUrl);
       });
  }

  private nextImage(): void {
    this.currentImageIndex++;
    this.currentImageIndex = this.currentImageIndex % 8;

    console.log(this.currentImageIndex);
    this.currentImage = this.MEMES_BASE[this.currentImageIndex];

    this.currentMeme.memeId = this.currentImage.id;
  }

  private prevImage(): void {
    this.currentImageIndex--;
    if(this.currentImageIndex<0)
    {
      this.currentImageIndex = 7;
    }
    this.currentImageIndex = this.currentImageIndex % 8;
    console.log(this.currentImageIndex);
    this.currentImage = this.MEMES_BASE[this.currentImageIndex];

    this.currentMeme.memeId = this.currentImage.id;
  }

  private toggleMeme() : void {
    console.log(this.includeMeme);
    this.includeMeme = !this.includeMeme;
    if (this.includeMeme) {
        this.currentMeme = new MemeRequest();
        this.currentMeme.memeId = this.currentImage.id;
    } else {
      this.currentMeme = null;
    }

  }

  // private getCorrespondingMeme(): void {
  //   if (this.paymentRequest.memeRequest) {
  //     this.service.getMemeUrl(this.paymentRequest.memeRequest)
  //       .then((returnedMeme) => {
  //         this.meme = returnedMeme;
  //         this.showMeme = true;
  //       })
  //       .catch((err) => this.meme = new MemeResponse());
  //   }
  // }

}


text:
package com.haskforce.parsing.srcExtsDatatypes;

/**
 * ActiveFrom   l Int
 */
public class ActiveFrom extends ActivationTopType {
    public SrcInfoSpan srcInfoSpan;
    public int anInt;

    @Override
    public String toString() {
        return "ActiveFrom{" +
                anInt +
                '}';
    }
}


text:
@interface ViewController2 : UIViewController

@end


text:
package org.codingmatters.poom.demo.domain;

import org.codingmatters.poom.apis.demo.api.types.LateRentalTask;
import org.codingmatters.poom.apis.demo.api.types.Rental;
import org.codingmatters.poom.apis.demo.api.types.laterentaltask.Report;
import org.codingmatters.poom.demo.domain.rentals.LateRentalProcessor;
import org.codingmatters.poom.demo.domain.spec.Store;
import org.codingmatters.poom.services.domain.property.query.PropertyQuery;
import org.codingmatters.poom.services.domain.repositories.Repository;
import org.codingmatters.poom.services.domain.repositories.inmemory.InMemoryRepositoryWithPropertyQuery;
import org.codingmatters.poom.services.support.date.UTC;
import org.codingmatters.poom.services.tests.Eventually;
import org.codingmatters.poom.servives.domain.entities.Entity;
import org.codingmatters.value.objects.values.ObjectValue;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;

import java.util.Optional;
import java.util.concurrent.Executors;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class LateRentalTaskCRUDTest {
    static private Eventually eventually = Eventually.defaults();

    private Repository<LateRentalTask, PropertyQuery> repository = InMemoryRepositoryWithPropertyQuery.validating(LateRentalTask.class);
    private Repository<Store, PropertyQuery> storeRepository = InMemoryRepositoryWithPropertyQuery.validating(Store.class);
    private Repository<Rental, PropertyQuery> rentalRepository = InMemoryRepositoryWithPropertyQuery.validating(Rental.class);

    private LateRentalTaskCRUD crud = new LateRentalTaskCRUD(
            new LateRentalProcessor(this.repository,this.storeRepository, store -> Optional.of(this.rentalRepository)),
            Executors.newSingleThreadExecutor()
    );

    @Test
    public void givenNoStore__whenCreatingTask__thenTaskEventuallyFinishes() throws Exception {
        Entity<LateRentalTask> entity = this.crud.createEntityFrom(ObjectValue.builder().build());

        eventually.assertThat(() -> this.repository.retrieve(entity.id()).value().status(), is(LateRentalTask.Status.DONE));
    }

    @Test
    public void givenAStoreExists_andARentalIsPassedDueDate__whenCreatingTask__thenTaskEventuallyFinishes_andRentalIsMarkedAsLate() throws Exception {
        this.storeRepository.create(Store.builder().name("netflix").build());
        Entity<Rental> rentalEntity = this.rentalRepository.create(Rental.builder().status(Rental.Status.OUT).dueDate(UTC.now().minusDays(1)).build());

        Entity<LateRentalTask> entity = this.crud.createEntityFrom(ObjectValue.builder().build());

        eventually.assertThat(() -> this.repository.retrieve(entity.id()).value().status(), is(LateRentalTask.Status.DONE));

        LateRentalTask task = this.repository.retrieve(entity.id()).value();
        assertThat(task.report(), is(Report.builder().accountProcessed(1L).lateRentalCount(1L).build()));

        Rental rental = this.rentalRepository.retrieve(rentalEntity.id()).value();
        assertThat(rental.status(), is(Rental.Status.LATE));
    }
}


text:
from __future__ import (unicode_literals, absolute_import,
                        division, print_function)
import logging

import reversion
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _

from snisi_core.models.common import pre_save_report, post_save_report
from snisi_core.models.Reporting import (PeriodicAggregatedReportInterface,
                                         PERIODICAL_SOURCE,
                                         PERIODICAL_AGGREGATED,
                                         SNISIReport)
from snisi_nutrition.models.Common import AbstractURENutritionR

logger = logging.getLogger(__name__)

class AbstractURENASNutritionR(AbstractURENutritionR):

    class Meta:
        app_label = 'snisi_nutrition'
        abstract = True

    IS_URENAS = True

    # 6-59 months
    u59o6_total_start_m = models.PositiveIntegerField(
        _("[6-59m] Start of Month Male"))
    u59o6_total_start_f = models.PositiveIntegerField(
        _("[6-59m] Start of Month Female"))

    u59o6_new_cases = models.PositiveIntegerField(
        _("[6-59m] New Cases"))
    u59o6_returned = models.PositiveIntegerField(
        _("[6-59m] Returned"))
    u59o6_total_in_m = models.PositiveIntegerField(
        _("[6-59m] Total Admitted Male"))
    u59o6_total_in_f = models.PositiveIntegerField(
        _("[6-59m] Total Admitted Female"))
    u59o6_transferred = models.PositiveIntegerField(
        _("[6-59m] Transferred from URENI"))

    u59o6_healed = models.PositiveIntegerField(
        _("[6-59m] Healed"))
    u59o6_deceased = models.PositiveIntegerField(
        _("[6-59m] Deceased"))
    u59o6_abandon = models.PositiveIntegerField(
        _("[6-59m] Abandon"))
    u59o6_not_responding = models.PositiveIntegerField(
        _("[6-59m] Not Responding"))
    u59o6_total_out_m = models.PositiveIntegerField(
        _("[6-59m] Total Out Male"))
    u59o6_total_out_f = models.PositiveIntegerField(
        _("[6-59m] Total Out Female"))

    u59o6_referred = models.PositiveIntegerField(
        _("[6-59m] Referred"))

    u59o6_total_end_m = models.PositiveIntegerField(
        _("[6-59m] End of Month Male"))
    u59o6_total_end_f = models.PositiveIntegerField(
        _("[6-59m] End of Month Female"))

    # Over 59 months
    o59_total_start_m = models.PositiveIntegerField(
        _("[59m+] Start of Month Male"))
    o59_total_start_f = models.PositiveIntegerField(
        _("[59m+] Start of Month Female"))

    o59_new_cases = models.PositiveIntegerField(
        _("[59m+] New Cases"))
    o59_returned = models.PositiveIntegerField(
        _("[59m+] Returned"))
    o59_total_in_m = models.PositiveIntegerField(
        _("[59m+] Total Admitted Male"))
    o59_total_in_f = models.PositiveIntegerField(
        _("[59m+] Total Admitted Female"))
    o59_transferred = models.PositiveIntegerField(
        _("[59m+] Transferred from URENI"))

    o59_healed = models.PositiveIntegerField(
        _("[59m+] Healed"))
    o59_deceased = models.PositiveIntegerField(
        _("[59m+] Deceased"))
    o59_abandon = models.PositiveIntegerField(
        _("[59m+] Abandon"))
    o59_not_responding = models.PositiveIntegerField(
        _("[59m+] Not Responding"))
    o59_total_out_m = models.PositiveIntegerField(
        _("[59m+] Total Out Male"))
    o59_total_out_f = models.PositiveIntegerField(
        _("[59m+] Total Out Female"))

    o59_referred = models.PositiveIntegerField(
        _("[59m+] Referred"))

    o59_total_end_m = models.PositiveIntegerField(
        _("[59m+] End of Month Male"))
    o59_total_end_f = models.PositiveIntegerField(
        _("[59m+] End of Month Female"))

    # 6-59 months
    @property
    def u59o6_total_start(self):
        return self.age_sum_for('u59o6', ['total_start_m', 'total_start_f'])

    @property
    def u59o6_total_in(self):
        return self.age_sum_for('u59o6', ['total_in_m', 'total_in_f'])

    @property
    def u59o6_grand_total_in(self):
        return self.age_sum_for('u59o6', ['total_in', 'transferred'])

    @property
    def u59o6_total_out(self):
        return self.age_sum_for('u59o6', ['total_out_m', 'total_out_f'])

    @property
    def u59o6_grand_total_out(self):
        return self.age_sum_for('u59o6', ['total_out', 'referred'])

    @property
    def u59o6_total_end(self):
        return self.age_sum_for('u59o6', ['total_end_m', 'total_end_f'])

    @property
    def u59o6_healed_rate(self):
        return self.performance_indicator_for('u59o6', 'healed')

    @property
    def u59o6_deceased_rate(self):
        return self.performance_indicator_for('u59o6', 'deceased')

    @property
    def u59o6_abandon_rate(self):
        return self.performance_indicator_for('u59o6', 'abandon')

    # Over 59 months
    @property
    def o59_total_start(self):
        return self.age_sum_for('o59', ['total_start_m', 'total_start_f'])

    @property
    def o59_total_in(self):
        return self.age_sum_for('o59', ['total_in_m', 'total_in_f'])

    @property
    def o59_grand_total_in(self):
        return self.age_sum_for('o59', ['total_in', 'transferred'])

    @property
    def o59_total_out(self):
        return self.age_sum_for('o59', ['total_out_m', 'total_out_f'])

    @property
    def o59_grand_total_out(self):
        return self.age_sum_for('o59', ['total_out', 'referred'])

    @property
    def o59_total_end(self):
        return self.age_sum_for('o59', ['total_end_m', 'total_end_f'])

    @property
    def o59_healed_rate(self):
        return self.performance_indicator_for('o59', 'healed')

    @property
    def o59_deceased_rate(self):
        return self.performance_indicator_for('o59', 'deceased')

    @property
    def o59_abandon_rate(self):
        return self.performance_indicator_for('o59', 'abandon')

    @classmethod
    def age_groups(cls):
        return ['u59o6', 'o59']

    @classmethod
    def comp_age_groups(cls):
        return ['u59o6']

class URENASNutritionR(AbstractURENASNutritionR):

    REPORTING_TYPE = PERIODICAL_SOURCE
    RECEIPT_FORMAT = "{period__year_short}{period__month}" \
                     "NAS-{dow}/{entity__slug}-{rand}"
    UNIQUE_TOGETHER = [('period', 'entity')]

    class Meta:
        app_label = 'snisi_nutrition'
        verbose_name = _("URENAS Report")
        verbose_name_plural = _("URENAS Reports")

receiver(pre_save, sender=URENASNutritionR)(pre_save_report)
receiver(post_save, sender=URENASNutritionR)(post_save_report)

reversion.register(URENASNutritionR)

class AggURENASNutritionR(AbstractURENASNutritionR,
                          PeriodicAggregatedReportInterface, SNISIReport):

    REPORTING_TYPE = PERIODICAL_AGGREGATED
    RECEIPT_FORMAT = "{period__year_short}{period__month}" \
                     "NASa-{dow}/{entity__slug}-{rand}"
    INDIVIDUAL_CLS = URENASNutritionR
    UNIQUE_TOGETHER = [('period', 'entity')]

    class Meta:
        app_label = 'snisi_nutrition'
        verbose_name = _("Aggregated URENAS Report")
        verbose_name_plural = _("Aggregated URENAS Reports")

    indiv_sources = models.ManyToManyField(
        INDIVIDUAL_CLS,
        verbose_name=_(u"Primary. Sources"),
        blank=True,
        related_name='source_agg_%(class)s_reports')

    direct_indiv_sources = models.ManyToManyField(
        INDIVIDUAL_CLS,
        verbose_name=_("Primary. Sources (direct)"),
        blank=True,
        related_name='direct_source_agg_%(class)s_reports')

    @classmethod
    def create_from(cls, period, entity, created_by,
                    indiv_sources=None, agg_sources=None):

        if indiv_sources is None:
            if entity.type.slug in ('health_center', 'health_district'):
                indiv_sources = cls.INDIVIDUAL_CLS.objects.filter(
                    period__start_on__gte=period.start_on,
                    period__end_on__lte=period.end_on) \
                    .filter(entity__in=entity.get_health_centers())
            else:
                indiv_sources = []

        if agg_sources is None and not len(indiv_sources):
            agg_sources = cls.objects.filter(
                period__start_on__gte=period.start_on,
                period__end_on__lte=period.end_on) \
                .filter(entity__in=entity.get_natural_children(
                    skip_slugs=['health_area']))

        return super(cls, cls).create_from(
            period=period,
            entity=entity,
            created_by=created_by,
            indiv_sources=indiv_sources,
            agg_sources=agg_sources)

    @classmethod
    def update_instance_with_indiv(cls, report, instance):
        for field in cls.data_fields():
            setattr(report, field,
                    getattr(report, field, 0) + getattr(instance, field, 0))

    @classmethod
    def update_instance_with_agg(cls, report, instance):
        for field in cls.data_fields():
            setattr(report, field,
                    getattr(report, field, 0) + getattr(instance, field, 0))

receiver(pre_save, sender=AggURENASNutritionR)(pre_save_report)
receiver(post_save, sender=AggURENASNutritionR)(post_save_report)

reversion.register(AggURENASNutritionR)


text:
package models

type Address struct {
	City            string `json:"city"`
	Country         string `json:"country"`
	PostalCode      string `json:"postalCode"`
	StateOrProvince string `json:"stateOrProvince"`
	Street          string `json:"street"`
	Street2         string `json:"street2"`
	Street3         string `json:"street3"`
	Street4         string `json:"street4"`
	Street5         string `json:"street5"`
	Street6         string `json:"street6"`
	Value           string `json:"value"`
	Id              string `json:"id"`
}


text:
;(() => {

	var CONFIG = require('config');
	var ldap = require('ldapjs');

	var rootSUFFIX = CONFIG.ldap.root;
	var SUFFIX = 'ou=user,dc=assureit,dc=org';
	var db = {};

	export var app = ldap.createServer();

	app.bind(rootSUFFIX, function(req, res, next) {
		res.end();
		return next();
	});

	app.bind(SUFFIX, function(req, res, next) {
		var dn = req.dn.toString();
		if (!db[dn]) {
			return next(new ldap.NoSuchObjectError(dn));
		}
		if (!db[dn].userpassword) {
			return next(new ldap.NoSuchAttributeError('userPassword'));
		}
		if (db[dn].userpassword[0] !== req.credentials) {
			return next(new ldap.InvalidCredentialsError());
		}
		res.end();
		return next();
	});

	app.add(SUFFIX, function(req, res, next) {
		var dn = req.dn.toString();
		if (db[dn]) {
			return next(new ldap.EntryAlreadyExistsError(dn));
		}
		db[dn] = req.toObject().attributes;
		res.end();
		return next();
	});

	app.del(SUFFIX, function(req, res, next) {
		var dn = req.dn.toString();
		if (!db[dn]) {
			return next(new ldap.NoSuchObjectError(dn));
		}
		delete db[dn];
		res.end();
		return next();
	});
})();


text:
package org.springframework.web.servlet.view;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.context.support.ContextExposingHttpServletRequest;
import org.springframework.web.util.WebUtils;

/**
 * Wrapper for a JSP or other resource within the same web application.
 * Exposes model objects as request attributes and forwards the request to
 * the specified resource URL using a {@link javax.servlet.RequestDispatcher}.
 *
 *
A URL for this view is supposed to specify a resource within the web
 * application, suitable for RequestDispatcher's forward or
 * include method.
 *
 *
If operating within an already included request or within a response that
 * has already been committed, this view will fall back to an include instead of
 * a forward. This can be enforced by calling response.flushBuffer()
 * (which will commit the response) before rendering the view.
 *
 *
Typical usage with {@link InternalResourceViewResolver} looks as follows,
 * from the perspective of the DispatcherServlet context definition:
 *
 *
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 *   <property name="prefix" value="/WEB-INF/jsp/"/>
 *   <property name="suffix" value=".jsp"/>
 * </bean>

 *
 * Every view name returned from a handler will be translated to a JSP
 * resource (for example: "myView" -> "/WEB-INF/jsp/myView.jsp"), using
 * this view class by default.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @see javax.servlet.RequestDispatcher#forward
 * @see javax.servlet.RequestDispatcher#include
 * @see javax.servlet.ServletResponse#flushBuffer
 * @see InternalResourceViewResolver
 * @see JstlView
 */
public class InternalResourceView extends AbstractUrlBasedView {

	private boolean alwaysInclude = false;

	private Boolean exposeForwardAttributes;

	private boolean exposeContextBeansAsAttributes = false;

	private Set exposedContextBeanNames;

	private boolean preventDispatchLoop = false;

	/**
	 * Constructor for use as a bean.
	 * @see #setUrl
	 * @see #setAlwaysInclude
	 */
	public InternalResourceView() {
	}

	/**
	 * Create a new InternalResourceView with the given URL.
	 * @param url the URL to forward to
	 * @see #setAlwaysInclude
	 */
	public InternalResourceView(String url) {
		super(url);
	}

	/**
	 * Create a new InternalResourceView with the given URL.
	 * @param url the URL to forward to
	 * @param alwaysInclude whether to always include the view rather than forward to it
	 */
	public InternalResourceView(String url, boolean alwaysInclude) {
		super(url);
		this.alwaysInclude = alwaysInclude;
	}

	/**
	 * Specify whether to always include the view rather than forward to it.
	 *
Default is "false". Switch this flag on to enforce the use of a
	 * Servlet include, even if a forward would be possible.
	 * @see javax.servlet.RequestDispatcher#forward
	 * @see javax.servlet.RequestDispatcher#include
	 * @see #useInclude(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	public void setAlwaysInclude(boolean alwaysInclude) {
		this.alwaysInclude = alwaysInclude;
	}

	/**
	 * Set whether to explictly expose the Servlet 2.4 forward request attributes
	 * when forwarding to the underlying view resource.
	 *
Default is "true" on Servlet containers up until 2.4, and "false" for
	 * Servlet 2.5 and above. Note that Servlet containers at 2.4 level and above
	 * should expose those attributes automatically! This InternalResourceView
	 * feature exists for Servlet 2.3 containers and misbehaving 2.4 containers.
	 */
	public void setExposeForwardAttributes(boolean exposeForwardAttributes) {
		this.exposeForwardAttributes = Boolean.valueOf(exposeForwardAttributes);
	}

	/**
	 * Set whether to make all Spring beans in the application context accessible
	 * as request attributes, through lazy checking once an attribute gets accessed.
	 *
This will make all such beans accessible in plain ${...}
	 * expressions in a JSP 2.0 page, as well as in JSTL's c:out
	 * value expressions.
	 *
Default is "false". Switch this flag on to transparently expose all
	 * Spring beans in the request attribute namespace.
	 *
NOTE: Context beans will override any custom request or session
	 * attributes of the same name that have been manually added. However, model
	 * attributes (as explicitly exposed to this view) of the same name will
	 * always override context beans.
	 * @see #getRequestToExpose
	 */
	public void setExposeContextBeansAsAttributes(boolean exposeContextBeansAsAttributes) {
		this.exposeContextBeansAsAttributes = exposeContextBeansAsAttributes;
	}

	/**
	 * Specify the names of beans in the context which are supposed to be exposed.
	 * If this is non-null, only the specified beans are eligible for exposure as
	 * attributes.
	 *
If you'd like to expose all Spring beans in the application context, switch
	 * the {@link #setExposeContextBeansAsAttributes "exposeContextBeansAsAttributes"}
	 * flag on but do not list specific bean names for this property.
	 */
	public void setExposedContextBeanNames(String[] exposedContextBeanNames) {
		this.exposedContextBeanNames = new HashSet(Arrays.asList(exposedContextBeanNames));
	}

	/**
	 * Set whether to explicitly prevent dispatching back to the
	 * current handler path.
	 *
Default is "false". Switch this to "true" for convention-based
	 * views where a dispatch back to the current handler path is a
	 * definitive error.
	 */
	public void setPreventDispatchLoop(boolean preventDispatchLoop) {
		this.preventDispatchLoop = preventDispatchLoop;
	}

	/**
	 * An ApplicationContext is not strictly required for InternalResourceView.
	 */
	protected boolean isContextRequired() {
		return false;
	}

	/**
	 * Checks whether we need explictly expose the Servlet 2.4 request attributes
	 * by default.
	 * @see #setExposeForwardAttributes
	 * @see #exposeForwardRequestAttributes(javax.servlet.http.HttpServletRequest)
	 */
	protected void initServletContext(ServletContext sc) {
		if (this.exposeForwardAttributes == null && sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {
			this.exposeForwardAttributes = Boolean.TRUE;
		}
	}

	/**
	 * Render the internal resource given the specified model.
	 * This includes setting the model as request attributes.
	 */
	protected void renderMergedOutputModel(
			Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {

		// Determine which request handle to expose to the RequestDispatcher.
		HttpServletRequest requestToExpose = getRequestToExpose(request);

		// Expose the model object as request attributes.
		exposeModelAsRequestAttributes(model, requestToExpose);

		// Expose helpers as request attributes, if any.
		exposeHelpers(requestToExpose);

		// Determine the path for the request dispatcher.
		String dispatcherPath = prepareForRendering(requestToExpose, response);

		// Obtain a RequestDispatcher for the target resource (typically a JSP).
		RequestDispatcher rd = requestToExpose.getRequestDispatcher(dispatcherPath);
		if (rd == null) {
			throw new ServletException(
					"Could not get RequestDispatcher for [" + getUrl() + "]: check that this file exists within your WAR");
		}

		// If already included or response already committed, perform include, else forward.
		if (useInclude(requestToExpose, response)) {
			response.setContentType(getContentType());
			if (logger.isDebugEnabled()) {
				logger.debug("Including resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'");
			}
			rd.include(requestToExpose, response);
		}

		else {
			// Note: The forwarded resource is supposed to determine the content type itself.
			exposeForwardRequestAttributes(requestToExpose);
			if (logger.isDebugEnabled()) {
				logger.debug("Forwarding to resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'");
			}
			rd.forward(requestToExpose, response);
		}
	}

	/**
	 * Expose helpers unique to each rendering operation. This is necessary so that
	 * different rendering operations can't overwrite each other's contexts etc.
	 *
Called by {@link #renderMergedOutputModel(Map, HttpServletRequest, HttpServletResponse)}.
	 * The default implementation is empty. This method can be overridden to add
	 * custom helpers as request attributes.
	 * @param request current HTTP request
	 * @throws Exception if there's a fatal error while we're adding attributes
	 * @see #renderMergedOutputModel
	 * @see JstlView#exposeHelpers
	 * @see org.springframework.web.servlet.view.tiles.TilesJstlView#exposeHelpers
	 */
	protected void exposeHelpers(HttpServletRequest request) throws Exception {
	}

	/**
	 * Prepare for rendering, and determine the request dispatcher path
	 * to forward to (or to include).
	 *
This implementation simply returns the configured URL.
	 * Subclasses can override this to determine a resource to render,
	 * typically interpreting the URL in a different manner.
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @return the request dispatcher path to use
	 * @throws Exception if preparations failed
	 * @see #getUrl()
	 * @see org.springframework.web.servlet.view.tiles.TilesView#prepareForRendering
	 */
	protected String prepareForRendering(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String path = getUrl();
		if (this.preventDispatchLoop) {
			String uri = request.getRequestURI();
			if (path.startsWith("/") ? uri.equals(path) : uri.equals(StringUtils.applyRelativePath(uri, path))) {
				throw new ServletException("Circular view path [" + path + "]: would dispatch back " +
						"to the current handler URL [" + uri + "] again. Check your ViewResolver setup! " +
						"(Hint: This may be the result of an unspecified view, due to default view name generation.)");
			}
		}
		return path;
	}

	/**
	 * Get the request handle to expose to the RequestDispatcher, i.e. to the view.
	 *
The default implementation wraps the original request for exposure of
	 * Spring beans as request attributes (if demanded).
	 * @param originalRequest the original servlet request as provided by the engine
	 * @return the wrapped request, or the original request if no wrapping is necessary
	 * @see #setExposeContextBeansAsAttributes
	 * @see org.springframework.web.context.support.ContextExposingHttpServletRequest
	 */
	protected HttpServletRequest getRequestToExpose(HttpServletRequest originalRequest) {
		if (this.exposeContextBeansAsAttributes || this.exposedContextBeanNames != null) {
			return new ContextExposingHttpServletRequest(
					originalRequest, getWebApplicationContext(), this.exposedContextBeanNames);
		}
		return originalRequest;
	}

	/**
	 * Determine whether to use RequestDispatcher's include or
	 * forward method.
	 *
Performs a check whether an include URI attribute is found in the request,
	 * indicating an include request, and whether the response has already been committed.
	 * In both cases, an include will be performed, as a forward is not possible anymore.
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @return true for include, false for forward
	 * @see javax.servlet.RequestDispatcher#forward
	 * @see javax.servlet.RequestDispatcher#include
	 * @see javax.servlet.ServletResponse#isCommitted
	 * @see org.springframework.web.util.WebUtils#isIncludeRequest
	 */
	protected boolean useInclude(HttpServletRequest request, HttpServletResponse response) {
		return (this.alwaysInclude || WebUtils.isIncludeRequest(request) || response.isCommitted());
	}

	/**
	 * Expose the current request URI and paths as {@link HttpServletRequest}
	 * attributes under the keys defined in the Servlet 2.4 specification,
	 * for Servlet 2.3 containers as well as misbehaving Servlet 2.4 containers
	 * (such as OC4J).
	 *
Does not expose the attributes on Servlet 2.5 or above, mainly for
	 * GlassFish compatibility (GlassFish gets confused by pre-exposed attributes).
	 * In any case, Servlet 2.5 containers should finally properly support
	 * Servlet 2.4 features, shouldn't they...
	 * @param request current HTTP request
	 * @see org.springframework.web.util.WebUtils#exposeForwardRequestAttributes
	 */
	protected void exposeForwardRequestAttributes(HttpServletRequest request) {
		if (this.exposeForwardAttributes != null && this.exposeForwardAttributes.booleanValue()) {
			WebUtils.exposeForwardRequestAttributes(request);
		}
	}

}


text:
namespace _05.Flatten_Dictionary
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class FlattenDictionary
    {
        public static void Main()
        {
            var flattenDict = new Dictionary<string, Dictionary<string, string>>();

            string inputLine = Console.ReadLine();

            while (inputLine != "end")
            {
                string[] tokens = inputLine
                    .Split(new char[] { ' ' },
                    StringSplitOptions.RemoveEmptyEntries);

                if (tokens.Length > 2)
                {
                    string type = tokens[0];
                    string mark = tokens[1];
                    string model = tokens[2];

                    if (!flattenDict.ContainsKey(type))
                    {
                        flattenDict[type] = new Dictionary<string, string>();
                    }
                    flattenDict[type][mark] = model;

                }
                else
                {
                    string type = tokens[1];

                    //flatten the key and the value and se it to key, and for the value set it to string.empty
                    flattenDict[type] = flattenDict[type]
                        .ToDictionary(k => k.Key + k.Value + "", v => string.Empty);

                }

                inputLine = Console.ReadLine();
            }

            //Order the first keys ---> type of the product
            flattenDict = flattenDict
                .OrderByDescending(k => k.Key.Length)
                .ToDictionary(k => k.Key, v => v.Value);

            foreach (var type in flattenDict)
            {
                Console.WriteLine(type.Key);

                var notFlatteValues = type.Value
                    .Where(v => v.Value != string.Empty)
                    .ToDictionary(k => k.Key, v => v.Value)
                    .OrderBy(k => k.Key.Length)
                    .ToDictionary(k => k.Key, v => v.Value);

                var flattenValues = type.Value
                    .Where(v => v.Value == string.Empty)
                    .ToDictionary(k => k.Key, v => v.Value);
                int index = 1;

                foreach (var mark in notFlatteValues)
                {

                    Console.WriteLine($"{index}. {mark.Key} - {mark.Value}");

                    index++;
                }

                foreach (var mark in flattenValues)
                {
                    Console.WriteLine($"{index}. {mark.Key}");
                    index++;
                }
            }
        }
    }
}


text:
import {h} from "@cycle/dom";
import todoListMain from "./todoList/main";
import todoFormMain from "./todoForm/main";

let todoMain = function(sources) {
  let todoList = todoListMain(sources);
  let todoForm = todoFormMain(sources, todoList.editTodo$);

  let view$ = todoList.DOM.combineLatest(todoForm.DOM, function(listView, formView) {
    return h("div", [formView, listView]);
  });

  let request$ = todoList.HTTP.merge(todoForm.HTTP);

  return {
    DOM: view$,
    HTTP: request$,
    preventDefault: todoForm.preventDefault,
    todos$: todoList.todos$
  };
};

export default todoMain;


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovieMakerClipDrag : MonoBehaviour
{
    [SerializeField]
    private SpriteRenderer SR;

    [SerializeField]
    private GameObject Shadow;

    [SerializeField]
    private float snapBackSpeed = 20f;

    private Vector3 initialPosition;
    private bool dragging = false;
    bool hasBeenDragged = false;

    private void Start()
    {
        initialPosition = transform.localPosition;
    }

    private void OnMouseDown()
    {
        SR.maskInteraction = 0;
        Shadow.SetActive(true);
        dragging = true;
    }

    private void OnMouseUp()
    {
        Shadow.SetActive(false);
        dragging = false;
    }

    private void Update()
    {
        if (dragging)
            hasBeenDragged = true;
        if (!hasBeenDragged)
        {
            initialPosition = transform.localPosition;
            return;
        }

        if (!dragging && tag == "MicrogameTag1")
            transform.moveTowardsLocal2D(initialPosition, snapBackSpeed);
    }

    void OnMouseDrag()
    {
        Vector3 NewPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
        transform.position = Camera.main.ScreenToWorldPoint(NewPos) + new Vector3 (0, 0, 10);
    }

}


text:
Demonstrate how to update out of the box seattle.master user expirience responsive without a need to modify the master page as such, but rather to take advantage of the AlternateCssUrl property in Web level. Responsive CSS design has been done by Heather Solomon and you can read more information about the CSS details from following blog post.

* Heather Solomon (SharePoint Experts, Inc) - [Making Seattle master responsive](http://blog.sharepointexperience.com/2015/03/making-seattle-master-responsive/)

To make sure the css is rendered correctly on hardware devices a viewport html meta tag needs to be added to the master page. This can be accomplied by using the Search Engine Optimization Settings. Again the master page doesn't need to be edited. More details on this are covered in the following blog post.

* Stefan Bauer (n8d) - [How to add viewport meta without editing the master page](http://www.n8d.at/blog/how-to-add-viewport-meta-without-editing-the-master-page/)

*Notice* - There's more fine tuned and polished responsive UI CSS included in the PnP Partner Pack, which can be accessed from http://aka.ms/OfficeDevPnPPartnerPack.

### Applies to ###
-  Office 365 Multi Tenant (MT)
-  Office 365 Dedicated (D)*
-  SharePoint 2013 on-premises*

Experience might be slightly different, but the same thinking and process applies to on-premises as well.

### Prerequisites ###
To add valid viewport settings to the master page the site collection feature "SharePoint Server Publishing Infrastructure" needs to be activated. No other publishing related feature needs to be activated.
Alternatively the viewport meta tag can be added through a custom action[https://github.com/OfficeDev/PnP/tree/master/Samples/Core.EmbedJavaScript](https://github.com/OfficeDev/PnP/tree/master/Samples/Core.EmbedJavaScript). This is currently not covered in this solution. The HTML element that needs to be added is:

```HTML
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
```

### Solution ###
Solution | Author(s)
---------|----------
Branding.InjectResponsiveCSS | Heather Solomon (**SharePoint Experts, Inc**)

Packaging and remote provisioning with AlternateCSSUrl approach done by Vesa Juvonen, Microsoft
Provisioning of viewport meta tag settings done by Stefan Bauer, n8d

### Version history ###
Version  | Date | Comments
---------| -----| --------
1.2  | November 19th 2015 | Small polishing on the code and adjustments in the documentation
1.1  | May 2nd 2015 | Viewport meta tag added
1.0  | April 26th 2015 | Initial release

### Disclaimer ###
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

----------

# Responsive Experience #
Please check Heather's blog post for detailed information on the CSS design at [http://blog.sharepointexperience.com/2015/03/making-seattle-master-responsive](http://blog.sharepointexperience.com/2015/03/making-seattle-master-responsive/)

Here's three pictures which are showing how the responsive CSS will behave when screen size is adjusted.

![](http://i.imgur.com/I0PR6Qj.png)

Notice how the left navigation is removed the search box has been relocated.

![](http://i.imgur.com/iyAHWFh.png)

Notice how the top navigation is rendered completely differently

![](http://i.imgur.com/u9yYn8V.png)

If navigation control is clicked, user is presented the same list of navigation options

![](http://i.imgur.com/BRtYm79.png)

# Attaching custom css to site #
Attaching the css to the site is two step process. We upload the CSS to some location where it can be used from and then we update the AlternateCssUrl property of the web to the right URL.

Here's the code for uploading css to the site assets library using *FileCreationInformation* object.

```C#
/// <summary>
/// Uploads used CSS and site logo to host web
/// </summary>
/// <param name="web"></param>
    private static void UploadAssetsToHostWeb(Web web)
    {
        // Ensure site asset library exists in case of a publishing web site
        web.Lists.EnsureSiteAssetsLibrary();

        // Instance to site assets
        List assetLibrary = web.Lists.GetByTitle("Site Assets");
        web.Context.Load(assetLibrary, l => l.RootFolder);

        // Get the path to the file which we are about to deploy
        string cssFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "resources/spe-seattle-responsive.css");

        // Use CSOM to upload the file in
        FileCreationInformation newFile = new FileCreationInformation
        {
            Content = System.IO.File.ReadAllBytes(cssFile),
            Url = "spe-seattle-responsive.css",
            Overwrite = true
        };
        Microsoft.SharePoint.Client.File uploadFile = assetLibrary.RootFolder.Files.Add(newFile);
        web.Context.Load(uploadFile);
        web.Context.ExecuteQuery();
    }

```

After the CSS is available, we can just set the AlternateCssUrl property, so that it's taken into use automatically by the site when browsers are accessing it.

```C#
web.AlternateCssUrl = ctx.Web.ServerRelativeUrl + "/SiteAssets/spe-seattle-responsive.css";
web.Update();
web.Context.ExecuteQuery();
```

After setting the CSS Url, the viewport meta tag will be added to the "Search Engine Optimization Settings". This makes sure that the CSS values will be shown correctly on any hardware device.

```C#
    if (allProperties.FieldValues.ContainsKey("seoincludecustommetatagpropertyname")) {
        allProperties["seoincludecustommetatagpropertyname"] = true.ToString();
    }
    // Add value of custom meta tag
    if (allProperties.FieldValues.ContainsKey("seocustommetatagpropertyname"))
    {
        allProperties["seocustommetatagpropertyname"] = "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\" />";
    }
```


text:
TMPREPO=/tmp/docs/klink

.PHONY: clean css docs serve pages dist

clean:
	- rm -rf build
	- rm -rf dist
	- rm -rf klink.egg-info

css:
	lessc --clean-css klink/less/klink.less klink/static/css/klink.css
	- cp klink/static/css/klink.css docs/build/html/_static/css/klink.css

docs: css
	$(MAKE) -C docs/ clean
	$(MAKE) -C docs/ html

serve:
	cd docs/build/html; \
	python -m SimpleHTTPServer 9090

pages:
	- rm -rf $(TMPREPO)
	git clone -b gh-pages git@github.com:pmorissette/klink.git $(TMPREPO)
	rm -rf $(TMPREPO)/*
	cp -r docs/build/html/* $(TMPREPO)
	cd $(TMPREPO); \
	git add -A ; \
	git commit -a -m 'auto-updating docs' ; \
	git push

dist:
	python setup.py sdist upload


text:
<?php echo $html_master_header; ?>

<?php echo $master_label; ?>

<?php echo $master_cabecalho; ?>

<?php echo $master_menu; ?>

<?php echo $master_corpo; ?>

<?php echo $master_rodape; ?>

<?php echo $html_master_footer; ?>


text:
<?php
/**
 * Model EventDatePicker.php
 * Permet d'obtenir la liste des events de la BDD en format JSON
 * pour les requêtes AJAX
 */
//Autoloader permettant de charger les classes automatiquement
require '../Autoloader.php';
Autoloader::register();
$Events = new Event();
$tabEventExt = $Events->getListeEventJson();

//On force le format JSON
header('Content-type: application/json');
echo $tabEventExt
;


text:
| [docs](..) / [getting-started](.) / 1-integrating.md |
|:---|

# Step 1. Integrating

The first step is to configure MyApp to work with Squirrel.Windows. This requires you to install the Squirrel.Windows NuGet Package into the `MyApp.sln`.

## Installing Squirrel.Windows

The easiest way to install the Squirrel.Windows is using the [Package Manager Console](https://docs.NuGet.org/consume/package-manager-console) in Visual Studio after loading the MyApp solution.

~~~powershell
PM> Install-Package Squirrel.Windows
~~~

### Squirrel.Windows References

The package will install a number of dependent packages as well as tools that will be used to prepare MyApp to be released. The References in the Solution Explorer of the MyApp project now looks like the following (as of Squirrel.Windows version 1.2.2):

![](images/1.1-post-package-install.png)

**Tip:** Alternatively, you can use the "Manage NuGet Packages" GUI to install Squirrel.Windows (right clicking on your project in the Solution Explorer of Visual Studio and select "Manage NuGet Packages...").

## Basic Updating

For the basic example we are going to have MyApp update from your local file system rather than distributing the files via the web.  See section [Packaging](2-packaging.md) for additional options related to the distributing the update files.

### Basic Squirrel.Windows Update Code
The following code is added to MyApp `Program.cs` to cause the application to check for, download, and install any new releases of MyApp in the background while you use the application.

**`Program.cs`**

~~~cs
using Squirrel;
~~~

**`static void Main()`**

~~~cs
using (var mgr = new UpdateManager("C:\\Projects\\MyApp\\Releases"))
{
    await mgr.UpdateApp();
}
~~~

The code above demonstrates the most basic update mechanism using the `UpdateApp()` method in an asynchronous task. The actions it takes will be discussed further in section [Updating](5-updating.md).

**Caution:** The path you provide the `UpdateManager` is the path to the directory where the `RELEASES` file is located (which is also named `Releases` by default), and not the actual `RELEASES` file.

**Tip:** By default, the files for updating MyApp will be placed in the same directory as your `MyApp.sln` file under a `Releases` directory (e.g., `C:\Projects\MyApp\Releases`).

**Tip:** In this example we simply put the code in the `Program.cs` file. For a production application, place the update code later in start-up process so as to avoid slowing down your program start.

**Tip:** If you attempt to debug the application via Visual Studio, you will get an exception of `Update.exe not found, not a Squirrel-installed app?`. You can resolve this by placing a copy of the Update.exe in your bin directory (see [Debugging Updates: Update.exe not found?](../using/debugging-updates.md) section for details).

---
| Previous: [Getting Started Guide](0-overview.md) | Next: [2. Packaging](2-packaging.md)|
|:---|:---|


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../節/index.html">
<meta http-equiv=refresh content="0; url='../節/index.html'">

Redirecting...

Click here if you are not redirected.


text:
package com.coreoz.plume.db.querydsl.crud;

public interface CrudEntity {

	void setId(Long id);

	Long getId();

}


text:
import os
import sys

if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
    sys.path.append(tools)
else:
    sys.exit("Please declare the environment variable 'SUMO_HOME'")
sumoBinary = "/usr/bin/sumo"
parent_dir = os.path.dirname(os.path.dirname(__file__))
sumoConfig = os.path.join(parent_dir, "data/bangalore.sumo.cfg")

import traci

def makeDetectors(lanes):
    with open(os.path.join(parent_dir, 'data/bangalore.det.xml'), 'w') as f:
        f.write("<additional>\n")
        for lane in lanes:
            if traci.lane.getLength(lane) > 20.0:
                f.write("\t<inductionLoop id='{}' lane='{}' pos='{}' freq='100' "
                        "file='{}'/>\n".format(lane + "loop", lane, -10, os.path.join(parent_dir, "data/resultsOfDetectors.xml")))
        f.write("</additional>")

def list_of_n_phases(TLIds):
    n_phases = []
    for light in TLIds:
        n_phases.append(int((len(traci.trafficlights.getRedYellowGreenState(light)) ** 0.5) * 2))
    return n_phases

def makemap(TLIds):
    maptlactions = []
    n_phases = list_of_n_phases(TLIds)
    for n_phase in n_phases:
        mapTemp = []
        if len(maptlactions) == 0:
            for i in range(n_phase):
                if i%2 == 0:
                    maptlactions.append([i])
        else:
            for state in maptlactions:
                for i in range(n_phase):
                    if i%2 == 0:
                        mapTemp.append(state+[i])
            maptlactions = mapTemp
    return maptlactions

if __name__ == "__main__":
    sumoCmd = [sumoBinary, "-c", sumoConfig, "--start"]
    traci.start(sumoCmd)
    lanes = traci.lane.getIDList()
    makeDetectors(lanes)
    # TLIds = traci.trafficlights.getIDList()
    # print makemap(TLIds)
    traci.close()


text:
package org.http4s
package client
package asynchttpclient

import cats.effect.{Effect, IO}

class AsyncHttpClientSpec
    extends ClientRouteTestBattery(
      "AsyncHttpClient",
      AsyncHttpClient()(Effect[IO], Http4sSpec.TestExecutionContext))


text:
import {ContentChild, Directive, EventEmitter, HostListener, Input, Output} from '@angular/core';

import {CheckboxComponent} from '@components/checkbox/checkbox.component';

@Directive({
  selector: '[selectItem]'
})

export class SelectItemDirective {
  @ContentChild(CheckboxComponent) host: CheckboxComponent;
  @Input() item: any;
  @Input() selected: any[];
  @Input() keyToPush: string;

  constructor() {}

  @HostListener('ngModelChange')
  modelChange(): void {

    const i: number = this.selected.indexOf(this.item[this.keyToPush]);

    if (i === -1 && this.host.checked) {
      this.selected.push(this.item[this.keyToPush]);
    }
    else {
      this.selected.splice(i, 1);
    }
  }
}


text:
<template name="about">

</template>


text:
Vues

🚧 Under active development.  Feedback is welcome. 🚧

> The quickest way to run [vuejs] client side (inspired by [next.js], [nuxt.js] and  [vbuild]).

## Introduction

## Quickstart

```
$ yarn global add vues
$ vues init project
$ cd project
$ yarn dev
```
Done!!!  You're now running [vuejs].

## Folder Structure

```javascript
projectDir/
|
|-- filters/
|
|-- layouts/
|
|-- stores/
|
|-- views/
```

  filters

Global vuejs filters.

  layouts

Wrap your views with layout.

  stores

Vuex namespaced stores.

  views

Application views.

## vues.config.js (click to toggle)

  title

Set the title for your application.

```javascript
{
  title: 'My App'
}
```

  titleTemplate

Sets the title dynamically based on the title option in your /views vue component.

`{{ title }}` will be replaced by the title in your `vues.config.js` and `{{ viewTitle }}` will be replaced by the `title` option in your `/views` `.vue` file.

```javascript
{
  titleTemplate: '{{ title }} | {{ viewTitle }}'
}
```

  srcDir

Specify the vues root folder.  This is the project root by default.

```javascript
import { resolve } from 'path'

{
  srcDir: resolve('./src')
}
```

  include

Files/folders to be compiled with babel-loader.

Some node modules may require the need to be processed by `babel-loader`.

```javascript
{
  include: ['some-node-module']
}
```

  envs

Compile selected process.env variables with webpack.

Vues will load environment variables from `.env` and `.env.[process.env.NODE_ENV]` files.  If you want access to them via `process.env` inside your [vuejs] project just and them to your envs array.

```javascript
{
  envs: ['PUBLIC_KEY']
}
```

You will now have access to `process.env.PUBLIC_KEY` inside your [vuejs] project.

  router

Customize the vue-router.

You can completely customize [vue-router] using any of the options available at https://router.vuejs.org/en/.  If you make the router option a function, you will be able to access the context of the router file.

```javascript
{
  router () {
    return {
      history: null, // cordova can't handle html5 browser history
      routes: [
        { name: 'index', path: '/', component: require('~/views/login') },
        // You have access to LoginView due to this being executed in the context of the router file.
        { name: 'logout', path: '/logout', component: LoginView }
      ],
      // You even have the option to use the routers beforeEach method.
      beforeEach (to, from, next) {
        // some code
      }
    }
  }
}
```

  store

Customize the vuex store.

Just like the [router] you can use this to completely customize [vuex].  It may also be turned into a function, which will the get executed in the context of the `store.js` file.

```javascript
{
  store: {
    plugins: [require('vuex-persistedstate')]
  }
}
```

  polyfills

Add selected polyfills to support older browsers.

We use [core-js] under the hood, the following are used by default:

```javascript
{
  polyfills: ['promise', 'array/includes', 'string/includes', 'object/entries']
}
```

  babel

Customize your applications babel config.

Default babel config used:

```javascript
{
  babel: {
    presets: ['vue-app']
  }
}
```

  meta

Inject meta tags into your index.html.

```javascript
{
  meta: [
    { name: 'mobile-web-app-capable', content: 'yes' }
  ]
}
```

[vuejs]: https://vuejs.org/
[vue-router]: https://router.vuejs.org/en/
[vuex]: https://vuex.vuejs.org/en/

[nuxt.js]: https://github.com/nuxt/nuxt.js
[next.js]: https://github.com/zeit/next.js
[vbuild]: https://github.com/egoist/vbuild
[core-js]: https://github.com/zloirock/core-js/

[router]: #config__router


text:
 {{ helptitle }}

The job attribute summary gives an overview of the parameters of the selected jobs and enables you to drill down to the jobs of interest. If there are other parameters that it would be useful to have summarized here, let us know.

The job list itself is expensive to build (for the server, network and your browser) and so is limited by the display_limit parameter that is included by default on the URL. You can remove the limit on jobs displayed (by removing display_limit in the URL), but be careful. The intent is that you drill down to a relatively small number of jobs (a few thousand at most), then you can list them if necessary. With JEDI, tasks are the main focus anyway, and you can drill down from tasks to their jobs.

Note that the number of records retrieved from each table of the database is limited for performance reasons. (Job data is spread across several tables depending on the state and age of the job). This means that if the search interval is 12 hours, you are probably not seeing all jobs from the last 12 hours, only the latest N from each table. As you drill down, narrowing your search to jobs of interest, the (unchanged) limit will encompass more jobs of interest to you. If you need to increase the limit, use &limit=N in the URL. Similarly you can specify &days=N on the URL, but use carefully, the load on the DB is heavy for days greater than 3.

If you know the jobsetid=N or taskid=N, jeditaskid=N of the jobs you're interested in, you can add these to the URL, and the search will not be time limited (because these IDs give the DB enough indexing info that it isn't stressful on the DB to exclude the time constraint).

Job data can be retrieved in json format with curl so that it can be used programmatically. Use this carefully, do not for example put scripts in crons that do heavy retrieval of job data this way. If you have systematic needs for PanDA job data, tell us what they are. Do not use web page scraping. An example curl command is as follows; it takes the same url parameters as the browser version.

curl -H 'Accept: application/json' -H 'Content-Type: application/json' "http://bigpanda.cern.ch/jobs/?transfertype=fax&hours=1"