text:
// Type definitions for speakeasy 2.0
// Project: http://github.com/speakeasyjs/speakeasy
// Definitions by: Lucas Woo <https://github.com/legendecas>, Alexander Batukhtin <https://github.com/mrOlorin>, Aayush Kapoor <https://github.com/xeoneux>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/// <reference types="node" />

export type Encoding = 'ascii' | 'hex' | 'base32' | 'base64';
export type Algorithm = 'sha1' | 'sha256' | 'sha512';

export interface SharedOptions {
    /**
     * Key encoding, defaults to ascii
     */
    encoding?: Encoding;
    /**
     * Algorithm, defaults to sha1
     */
    algorithm?: Algorithm;
}

export interface GeneratedSecret {
    /**
     * ASCII representation of the secret
     */
    ascii: string;
    /**
     * Hex representation of the secret
     */
    hex: string;
    /**
     * Base32 representation of the secret
     */
    base32: string;
    /**
     * URL for the QR code for the ASCII secret.
     *
     * @deprecated use a separate QR code library
     */
    qr_code_ascii?: string;
    /**
     * URL for the QR code for the hex secret.
     *
     * @deprecated use a separate QR code library
     */
    qr_code_hex?: string;
    /**
     * URL for the QR code for the base32 secret.
     *
     * @deprecated use a separate QR code library
     */
    qr_code_base32?: string;
    /**
     * URL for the Google Authenticator otpauth
     * URL's QR code.
     *
     * @deprecated use a separate QR code library
     */
    google_auth_qr: string;
    /**
     * Google Authenticator-compatible otpauth URL.
     */
    otpauth_url?: string;
}
export interface GeneratedSecretWithOtpAuthUrl extends GeneratedSecret {
    /**
     * Google Authenticator-compatible otpauth URL.
     */
    otpauth_url: string;
}

export interface DigestOptions extends SharedOptions {
    secret: string;
    counter: number;
    /**
     * @deprecated use secret
     */
    key?: string;
}

export interface GenerateSecretOptions {
    /**
     * Length of the secret, defaults to 32
     */
    length?: number;
    /**
     * Whether to include symbols, defaults to false
     */
    symbols?: boolean;
    /**
     * The name to use with Google Authenticator, deaults to 'SecretKey'
     */
    name?: string;
    /**
     * Whether to output a Google Authenticator-compatible otpauth:// URL
     * (only returns otpauth:// URL, no QR code), defaults to false
     */
    otpauth_url?: boolean;
    /**
     * The provider or service with which the
     * secret key is associated, defaults to ''
     */
    issuer?: string;
    /**
     * Output QR code URLs for the token.
     *
     * @deprecated use your own QR code implementation to prevent
     *   leaking of secret to a third party.
     */
    qr_codes?: boolean;
    /**
     * Output a Google Authenticator otpauth:// QR code URL.
     *
     * @deprecated use your own QR code implementation to prevent
     *   leaking of secret to a third party.
     */
    google_auth_qr?: boolean;
}
export interface GenerateSecretWithOtpAuthUrlOptions extends GenerateSecretOptions {
    /**
     * Whether to output a Google Authenticator-compatible otpauth:// URL
     * (only returns otpauth:// URL, no QR code), defaults to false
     */
    otpauth_url: true;
}

export interface HotpOptions extends DigestOptions {
    /**
     * @deprecated use digits
     */
    length?: number;
    /**
     * The number of digits for the one-time passcode, defaults to 6
     */
    digits?: number;
    /**
     * The digest, automatically generated by default
     */
    digest?: Buffer;
}

export interface HotpVerifyOptions extends SharedOptions {
    /**
     * Shared secret key
     */
    secret: string;
    /**
     * Passcode to validate
     */
    token: string;
    /**
     * Counter value. This should be stored by
     * the application and must be incremented for each request.
     */
    counter: number;
    /**
     * The number of digits for the one-time passcode, defaults to 6
     */
    digits?: number;
    /**
     * The allowable margin for the counter.
     * The function will check "W" codes in the future against the provided
     * passcode, e.g. if W = 10, and C = 5, this function will check the
     * passcode against all One Time Passcodes between 5 and 15, inclusive,
     * defaults to 0
     */
    window?: number;
}

export interface TotpOptions extends SharedOptions {
    /**
     * Time in seconds with which to calculate
     * counter value, defaults to `Date.now() / 1000`.
     */
    time?: number;
    /**
     * Time step in seconds, defaults to 30
     */
    step?: number;
    /**
     * Initial time since the UNIX epoch from which to calculate the counter value,
     * defaults to 0 (no offset).
     */
    epoch?: number;
    /**
     * @deprecated use epoch
     */
    initial_time?: number;
    /**
     * The number of digits for the one-time passcode, defaults to 6
     */
    digits?: number;
    /**
     * @deprecated use digits
     */
    length?: number;
    /**
     * The digest, automatically generated by default
     */
    digest?: Buffer;
    /**
     * Shared secret key
     */
    secret: string;
    /**
     * @deprecated use secret
     */
    key?: string;
    /**
     * The counter value, calculated from time by default
     */
    counter?: number;
}

export interface TotpVerifyOptions extends SharedOptions {
    /**
     * Shared secret key
     */
    secret: string;
    /**
     * Passcode to validate
     */
    token: string;
    /**
     * Time in seconds with which to calculate
     * counter value, defaults to `Date.now() / 1000`.
     */
    time?: number;
    /**
     * Time step in seconds, defaults to 30
     */
    step?: number;
    /**
     * Initial time since the UNIX epoch from which to calculate the counter value,
     * defaults to 0 (no offset).
     */
    epoch?: number;
    /**
     * The number of digits for the one-time passcode, defaults to 6
     */
    digits?: number;
    /**
     * The allowable margin for the counter.
     * The function will check "W" codes in the future and the past against the
     * provided passcode, e.g. if W = 5, and C = 1000, this function will check
     * the passcode against all One Time Passcodes between 995 and 1005, inclusive
     * defaults to 0
     */
    window?: number;
    /**
     * The counter value, calculated from time by default
     */
    counter?: number;
}

export interface OtpauthURLOptions extends SharedOptions {
    /**
     * Shared secret key
     */
    secret: string;
    /**
     * Used to identify the account with which the secret key is associated,
     * e.g. the user's email address.
     */
    label: string;
    /**
     * Either 'hotp' or 'totp', defaults to 'totp'
     */
    type?: 'htop' | 'totp';
    /**
     * The initial counter value, required for HOTP.
     */
    counter?: number;
    /**
     * The provider or service with which the secret key is associated.
     */
    issuer?: string;
    /**
     * The number of digits for the one-time passcode. Currently ignored
     * by Google Authenticator, defaults to 6
     */
    digits?: number;
    /**
     * The length of time for which a TOTP code will be valid, in seconds.
     * Currently ignored by Google Authenticator, defaults to 30
     */
    period?: number;
}

export interface Delta {
    delta: number;
}

export interface Hotp {
    /**
     * Generate a counter-based one-time token. Specify the key and counter, and
     * receive the one-time password for that counter position as a string. You can
     * also specify a token length, as well as the encoding (ASCII, hexadecimal, or
     * base32) and the hashing algorithm to use (SHA1, SHA256, SHA512).
     *
     * @return The one-time passcode.
     */
    (options: HotpOptions): string;
    /**
     * Verify a counter-based one-time token against the secret and return the delta.
     * By default, it verifies the token at the given counter value, with no leeway
     * (no look-ahead or look-behind). A token validated at the current counter value
     * will have a delta of 0.
     *
     * You can specify a window to add more leeway to the verification process.
     * Setting the window param will check for the token at the given counter value
     * as well as `window` tokens ahead (one-sided window). See param for more info.
     *
     * `verifyDelta()` will return the delta between the counter value of the token
     * and the given counter value. For example, if given a counter 5 and a window
     * 10, `verifyDelta()` will look at tokens from 5 to 15, inclusive. If it finds
     * it at counter position 7, it will return `{ delta: 2 }`.
     *
     * @return On success, returns an object with the counter
     *   difference between the client and the server as the `delta` property (i.e.
     *   `{ delta: 0 }`).
     */
    verifyDelta: (options: HotpVerifyOptions) => undefined | Delta;
    /**
     * Verify a counter-based one-time token against the secret and return true if
     * it verifies. Helper function for `hotp.verifyDelta()`` that returns a boolean
     * instead of an object.
     *
     * @return Returns true if the token matches within the given window, false otherwise.
     */
    verify: (options: HotpVerifyOptions) => boolean;
}

export interface Totp {
    /**
     * Generate a time-based one-time token. Specify the key, and receive the
     * one-time password for that time as a string. By default, it uses the current
     * time and a time step of 30 seconds, so there is a new token every 30 seconds.
     * You may override the time step and epoch for custom timing. You can also
     * specify a token length, as well as the encoding (ASCII, hexadecimal, or
     * base32) and the hashing algorithm to use (SHA1, SHA256, SHA512).
     *
     * Under the hood, TOTP calculates the counter value by finding how many time
     * steps have passed since the epoch, and calls HOTP with that counter value.
     *
     * @return The one-time passcode.
     */
    (options: TotpOptions): string;
    /**
     * Verify a time-based one-time token against the secret and return the delta.
     * By default, it verifies the token at the current time window, with no leeway
     * (no look-ahead or look-behind). A token validated at the current time window
     * will have a delta of 0.
     *
     * You can specify a window to add more leeway to the verification process.
     * Setting the window param will check for the token at the given counter value
     * as well as `window` tokens ahead and `window` tokens behind (two-sided
     * window). See param for more info.
     *
     * `verifyDelta()` will return the delta between the counter value of the token
     * and the given counter value. For example, if given a time at counter 1000 and
     * a window of 5, `verifyDelta()` will look at tokens from 995 to 1005,
     * inclusive. In other words, if the time-step is 30 seconds, it will look at
     * tokens from 2.5 minutes ago to 2.5 minutes in the future, inclusive.
     * If it finds it at counter position 1002, it will return `{ delta: 2 }`.
     * If it finds it at counter position 997, it will return `{ delta: -3 }`.
     *
     * @return On success, returns an object with the time step
     *   difference between the client and the server as the `delta` property (e.g.
     *   `{ delta: 0 }`).
     */
    verifyDelta: (options: TotpVerifyOptions) => undefined | Delta;
    /**
     * Verify a time-based one-time token against the secret and return true if it
     * verifies. Helper function for verifyDelta() that returns a boolean instead of
     * an object.
     *
     * @return Returns true if the token matches within the given
     *   window, false otherwise.
     */
    verify: (options: TotpVerifyOptions) => boolean;
}

/**
 * Digest the one-time passcode options.
 *
 * @return The one-time passcode as a buffer.
 */
export function digest(options: DigestOptions): Buffer;

export const hotp: Hotp;
// Alias counter() for hotp()
export const counter: Hotp;

export const totp: Totp;
// Alias time() for totp()
export const time: Totp;

/**
 * Generates a random secret with the set A-Z a-z 0-9 and symbols, of any length
 * (default 32). Returns the secret key in ASCII, hexadecimal, and base32 format,
 * along with the URL used for the QR code for Google Authenticator (an otpauth
 * URL). Use a QR code library to generate a QR code based on the Google
 * Authenticator URL to obtain a QR code you can scan into the app.
 */
export function generateSecret(options: GenerateSecretWithOtpAuthUrlOptions): GeneratedSecretWithOtpAuthUrl;
/**
 * Generates a random secret with the set A-Z a-z 0-9 and symbols, of any length
 * (default 32). Returns the secret key in ASCII, hexadecimal, and base32 format,
 * along with the URL used for the QR code for Google Authenticator (an otpauth
 * URL). Use a QR code library to generate a QR code based on the Google
 * Authenticator URL to obtain a QR code you can scan into the app.
 */
export function generateSecret(options?: GenerateSecretOptions): GeneratedSecret;
/**
 * @deprecated use generateSecret
 */
export const generate_key: typeof generateSecret;

/**
 * Generates a key of a certain length (default 32) from A-Z, a-z, 0-9, and
 * symbols (if requested).
 *
 * @param  length  The length of the key, defaults to 32
 * @param  symbols Whether to include symbols in the key, defaults to false
 * @return The generated key.
 */
export function generateSecretASCII(
    length?: number,
    symbols?: boolean
): string;
/**
 * @deprecated use generateSecret
 */
export const generate_key_ascii: typeof generateSecretASCII;

/**
 * Generate a Google Authenticator-compatible otpauth:// URL for passing the
 * secret to a mobile device to install the secret.
 *
 * Authenticator considers TOTP codes valid for 30 seconds. Additionally,
 * the app presents 6 digits codes to the user. According to the
 * documentation, the period and number of digits are currently ignored by
 * the app.
 *
 * To generate a suitable QR Code, pass the generated URL to a QR Code
 * generator, such as the `qr-image` module.
 *
 * @return A URL suitable for use with the Google Authenticator.
 * @see https://github.com/google/google-authenticator/wiki/Key-Uri-Format
 */
export function otpauthURL(options: OtpauthURLOptions): string;


text:
<?php
namespace Codeception\Exception;

class TestParseException extends \Exception
{
    public function __construct($fileName, $errors = null, $line = null)
    {
        if ($line) {
            $this->message = "Couldn't parse test '$fileName' on line $line";
        } else {
            $this->message = "Couldn't parse test '$fileName'";
        }
        if ($errors) {
            $this->message .= "\n$errors";
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace SklepBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use SklepBundle\Entity\Review;
use SklepBundle\Form\ReviewType;

/**
 * Review controller.
 *
 * @Route("/review")
 */
class ReviewController extends Controller
{

    /**
     * Lists all Review entities.
     *
     * @Route("/", name="review")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('SklepBundle:Review')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Review entity.
     *
     * @Route("/", name="review_create")
     * @Method("POST")
     * @Template("SklepBundle:Review:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Review();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return new Response(json_encode(array('ok' => 1)));
        }

        return new Response(json_encode(array('ok' => 0)));
    }

    /**
     * Creates a form to create a Review entity.
     *
     * @param Review $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Review $entity)
    {
        $form = $this->createForm(new ReviewType(), $entity, array(
            'action' => $this->generateUrl('review_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Review entity.
     *
     * @Route("/new", name="review_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Review();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Pokazuje receznje do konkretnego filmu
     *
     * @Route("/{id}", name="review_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = new Review();
        // Ustawianie filmu
        $movie = $em->getRepository('SklepBundle:Movie')->find($id);
        $entity->setMovie($movie);

        $form   = $this->createCreateForm($entity);

        $entities = $em->getRepository('SklepBundle:Review')->findByMovie($id);
        //\Doctrine\Common\Util\Debug::dump($entity);

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
            'entities'      => $entities,
            'delete_form' => $deleteForm->createView(),
            'movie' => $movie
        );
    }

    /**
     * Displays a form to edit an existing Review entity.
     *
     * @Route("/{id}/edit", name="review_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('SklepBundle:Review')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Review entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Review entity.
    *
    * @param Review $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Review $entity)
    {
        $form = $this->createForm(new ReviewType(), $entity, array(
            'action' => $this->generateUrl('review_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Review entity.
     *
     * @Route("/{id}", name="review_update")
     * @Method("PUT")
     * @Template("SklepBundle:Review:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('SklepBundle:Review')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Review entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('review_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Review entity.
     *
     * @Route("/{id}", name="review_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('SklepBundle:Review')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Review entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('review'));
    }

    /**
     * Creates a form to delete a Review entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('review_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
package org.apache.commons.feedparser.locate;

import org.apache.commons.feedparser.FeedParserException;
import org.apache.commons.feedparser.locate.blogservice.BlogService;
import org.apache.commons.feedparser.locate.blogservice.Unknown;

/**
 * Determines what blog provider a given URI is using,
 * such as whether it is hosted on Blogspot, Radio Userland, etc.
 *
 * @author <a href="mailto:bkn3@columbia.edu">Brad Neuberg/a>
 */
public class BlogServiceDiscovery {

    public static BlogService discover( String resource )
                                            throws FeedParserException {
        return discover(resource, null);
    }

    public static BlogService discover( String resource,
                                        String content )
                                            throws FeedParserException {
        // Some services, such as AOL LiveJournal, are case sensitive
        // on their resource names; can't do a toLowerCase.
        // Brad Neuberg, bkn3@columbia.edu
        //resource = resource.toLowerCase();
        BlogService[] blogServices = BlogService.getBlogServices();

        for (int i = 0; i < blogServices.length; i++) {
            if (blogServices[i].isThisService(resource, content)) {
                return blogServices[i];
            }
        }

        return new Unknown();
    }
}


text:
layout: post
title: Real Brings Windows Media To Linux
date: 2006-08-16 12:51:12 +02:00
---
["RealNetworks will release open-source software this year that will let Linux computers play Windows Media files." - ZDNET](http://news.zdnet.com/2100-3513_22-6105970.html "Real to plug Windows media support into Linux | Tech News on ZDNet")

Well not completely true. The codecs itself will be closed source but Real will bundle it with the open source Helix player. Nonetheless, this is a good development in my opinion. It's another sign that Linux on the desktop is slowly being taken seriously by big companies. It also solves some legal issues for businesses and ethical users.

Obviously, RealNetworks isn't doing this for philantropic reasons. The answer is in the same ZDNet article linked to in the top of this blog post:

> "Duchmann added that RealNetworks also hopes to bring its music store technology to Linux." - ZDNet

Although this motive is being played down I think it's the #1 reason for this move.


text:
package viewer;

import java.io.File;

import javax.swing.filechooser.FileFilter;

public class DirFilter extends FileFilter {

	@Override
	public boolean accept(File f) {
		return f.isDirectory();
	}

	@Override
	public String getDescription() {
		return null;
	}

}


text:
JNDI_POOLED_CONFIG = { :adapter => 'jndi', :jndi => 'jdbc/PooledDerbyDB' }

unless ( ps = ENV['PREPARED_STATEMENTS'] || ENV['PS'] ).nil?
  JNDI_POOLED_CONFIG[:prepared_statements] = ps
end

# FS based JNDI impl borrowed from tomcat :
load 'test/jars/tomcat-juli.jar'
load 'test/jars/tomcat-catalina.jar'

java.lang.System.set_property(
    javax.naming.Context::INITIAL_CONTEXT_FACTORY,
    'org.apache.naming.java.javaURLContextFactory'
)
java.lang.System.set_property(
    javax.naming.Context::URL_PKG_PREFIXES,
    'org.apache.naming'
)

require 'jdbc/derby'
Jdbc::Derby.load_driver

data_source = org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource.new
data_source.database_name = "memory:PooledDerbyDB-JNDI"
data_source.create_database = "create"
data_source.user = "sa"
data_source.password = ""

init_context = javax.naming.InitialContext.new
begin
  init_context.create_subcontext 'jdbc'
rescue javax.naming.NameAlreadyBoundException
end

init_context.bind JNDI_POOLED_CONFIG[:jndi], data_source


text:
package griffon.core;

import griffon.util.RunnableWithArgs;
import groovy.lang.Closure;

import java.util.List;

/**
 * Base contract for classes that can publish events using their own
 * event bus.
 *
 * @author Andres Almiray
 * @since 0.9.3
 */
public interface EventPublisher {
    /**
     * Adds an event listener.

     * Accepted types are: Script, Map and Object.
     *
     * @param listener an event listener
     */
    void addEventListener(Object listener);

    /**
     * Adds a closure as an event listener.

     *
     * @param eventName the name of the event
     * @param listener  an event listener
     */
    void addEventListener(String eventName, Closure listener);

    /**
     * Adds a runnable as an event listener.

     *
     * @param eventName the name of the event
     * @param listener  an event listener
     */
    void addEventListener(String eventName, RunnableWithArgs listener);

    /**
     * Removes an event listener.

     * Accepted types are: Script, Map and Object.
     *
     * @param listener an event listener
     */
    void removeEventListener(Object listener);

    /**
     * Removes a closure as an event listener.

     *
     * @param eventName the name of the event
     * @param listener  an event listener
     */
    void removeEventListener(String eventName, Closure listener);

    /**
     * Removes a runnable as an event listener.

     *
     * @param eventName the name of the event
     * @param listener  an event listener
     */
    void removeEventListener(String eventName, RunnableWithArgs listener);

    /**
     * Publishes an event.

     * Listeners will be notified in the same thread as the publisher.
     *
     * @param eventName the name of the event
     */
    void publishEvent(String eventName);

    /**
     * Publishes an event.

     * Listeners will be notified in the same thread as the publisher.
     *
     * @param eventName the name of the event
     * @param args      event arguments sent to listeners
     */
    void publishEvent(String eventName, List args);

    /**
     * Publishes an event.

     * Listeners will be notified outside of the UI thread.
     *
     * @param eventName the name of the event
     */
    void publishEventOutside(String eventName);

    /**
     * Publishes an event.

     * Listeners will be notified outside of the UI thread.
     *
     * @param eventName the name of the event
     * @param args      event arguments sent to listeners
     */
    void publishEventOutside(String eventName, List args);

    /**
     * Publishes an event.

     * Listeners will be notified in a different thread.
     *
     * @param eventName the name of the event
     */
    void publishEventAsync(String eventName);

    /**
     * Publishes an event.

     * Listeners will be notified in a different thread.
     *
     * @param eventName the name of the event
     * @param args      event arguments sent to listeners
     */
    void publishEventAsync(String eventName, List args);
}


text:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        // Using class based composers...
        view()->composer(
            'player', 'App\Http\Composers\PlayerComposer'
        );

        // Using Closure based composers...
        view()->composer('player', function ($view) {

        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
from __future__ import unicode_literals

from django.db import IntegrityError
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.reverse import reverse
import six

from waldur_core.core.serializers import GenericRelatedField, AugmentedSerializerMixin
from waldur_core.cost_tracking import models
from waldur_core.structure import SupportedServices, models as structure_models
from waldur_core.structure.filters import ScopeTypeFilterBackend

class PriceEstimateSerializer(AugmentedSerializerMixin, serializers.HyperlinkedModelSerializer):
    scope = GenericRelatedField(related_models=models.PriceEstimate.get_estimated_models())
    scope_name = serializers.SerializerMethodField()
    scope_type = serializers.SerializerMethodField()
    resource_type = serializers.SerializerMethodField()
    consumption_details = serializers.SerializerMethodField(
        help_text=_('How much of each consumables were used by resource.'))

    def __init__(self, *args, **kwargs):
        depth = kwargs.get('context', {}).pop('depth', 0)  # allow to modify depth dynamically
        self.Meta.depth = depth
        super(PriceEstimateSerializer, self).__init__(*args, **kwargs)

    class Meta(object):
        model = models.PriceEstimate
        fields = ('url', 'uuid', 'scope', 'total', 'consumed', 'month', 'year',
                  'scope_name', 'scope_type', 'resource_type', 'consumption_details', 'children')
        extra_kwargs = {
            'url': {'lookup_field': 'uuid'},
        }

    def get_fields(self):
        display_children = self.Meta.depth > 0
        fields = super(PriceEstimateSerializer, self).get_fields()
        if not display_children:
            del fields['children']
        return fields

    def build_nested_field(self, field_name, relation_info, nested_depth):
        """ Use PriceEstimateSerializer to serialize estimate children """
        if field_name != 'children':
            return super(PriceEstimateSerializer, self).build_nested_field(field_name, relation_info, nested_depth)
        field_class = self.__class__
        field_kwargs = {'read_only': True, 'many': True, 'context': {'depth': nested_depth - 1}}
        return field_class, field_kwargs

    def get_scope_name(self, obj):
        if obj.scope:
            return getattr(obj.scope, 'name', six.text_type(obj.scope))
        if obj.details:
            return obj.details.get('scope_name')

    def get_scope_type(self, obj):
        return ScopeTypeFilterBackend.get_scope_type(obj.content_type.model_class())

    def get_resource_type(self, obj):
        if obj.is_resource_estimate():
            return SupportedServices.get_name_for_model(obj.content_type.model_class())

    def get_consumption_details(self, obj):
        try:
            consumption_details = obj.consumption_details
        except models.ConsumptionDetails.DoesNotExist:
            return
        consumed_in_month = consumption_details.consumed_in_month
        consumable_items = consumed_in_month.keys()
        pretty_names = models.DefaultPriceListItem.get_consumable_items_pretty_names(
            obj.content_type, consumable_items)
        return {pretty_names[item]: consumed_in_month[item] for item in consumable_items}

class YearMonthField(serializers.CharField):
    """ Field that support year-month representation in format YYYY.MM """

    def to_internal_value(self, value):
        try:
            year, month = [int(el) for el in value.split('.')]
        except ValueError:
            raise serializers.ValidationError(_('Value "%s" should be valid be in format YYYY.MM') % value)
        if not 0 < month < 13:
            raise serializers.ValidationError(_('Month has to be from 1 to 12.'))
        return year, month

class PriceEstimateDateFilterSerializer(serializers.Serializer):
    date_list = serializers.ListField(
        child=YearMonthField(),
        required=False
    )

class PriceEstimateDateRangeFilterSerializer(serializers.Serializer):
    start = YearMonthField(required=False)
    end = YearMonthField(required=False)

    def validate(self, data):
        if 'start' in data and 'end' in data and data['start'] >= data['end']:
            raise serializers.ValidationError(_('Start has to be earlier than end.'))
        return data

class PriceListItemSerializer(AugmentedSerializerMixin,
                              serializers.HyperlinkedModelSerializer):
    service = GenericRelatedField(related_models=structure_models.Service.get_all_models())
    default_price_list_item = serializers.HyperlinkedRelatedField(
        view_name='defaultpricelistitem-detail',
        lookup_field='uuid',
        queryset=models.DefaultPriceListItem.objects.all().select_related('resource_content_type'))

    class Meta:
        model = models.PriceListItem
        fields = ('url', 'uuid', 'units', 'value', 'service', 'default_price_list_item')
        extra_kwargs = {
            'url': {'lookup_field': 'uuid'},
            'default_price_list_item': {'lookup_field': 'uuid'}
        }
        protected_fields = ('service', 'default_price_list_item')

    def create(self, validated_data):
        try:
            return super(PriceListItemSerializer, self).create(validated_data)
        except IntegrityError:
            raise serializers.ValidationError(_('Price list item for service already exists.'))

class DefaultPriceListItemSerializer(serializers.HyperlinkedModelSerializer):
    value = serializers.FloatField()

    class Meta:
        model = models.DefaultPriceListItem
        fields = ('url', 'uuid', 'key', 'item_type', 'value', 'resource_type')
        extra_kwargs = {
            'url': {'lookup_field': 'uuid'},
        }

class MergedPriceListItemSerializer(serializers.HyperlinkedModelSerializer):
    value = serializers.SerializerMethodField()
    units = serializers.SerializerMethodField()
    is_manually_input = serializers.SerializerMethodField()
    service_price_list_item_url = serializers.SerializerMethodField()

    class Meta:
        model = models.DefaultPriceListItem
        fields = ('url', 'uuid', 'key', 'item_type', 'units', 'value',
                  'resource_type', 'is_manually_input', 'service_price_list_item_url')
        extra_kwargs = {
            'url': {'lookup_field': 'uuid'},
        }

    def get_value(self, obj):
        return getattr(obj, 'service_item', None) and float(obj.service_item[0].value) or float(obj.value)

    def get_units(self, obj):
        return getattr(obj, 'service_item', None) and obj.service_item[0].units or obj.units

    def get_is_manually_input(self, obj):
        return bool(getattr(obj, 'service_item', None))

    def get_service_price_list_item_url(self, obj):
        if not getattr(obj, 'service_item', None):
            return
        return reverse('pricelistitem-detail',
                       kwargs={'uuid': obj.service_item[0].uuid.hex},
                       request=self.context['request'])


text:
<?php include 'view/header.php'; ?>

Menu

Product Manager

Product Catalog

<?php include 'view/footer.php'; ?>


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

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * A complex type that contains the codes and full continent, country, and subdivision names for the specified
 * geolocation code.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GeoLocationDetails implements Serializable, Cloneable {

    /**
     *

     * The two-letter code for the continent.
     *

     */
    private String continentCode;
    /**
     *

     * The full name of the continent.
     *

     */
    private String continentName;
    /**
     *

     * The two-letter code for the country.
     *

     */
    private String countryCode;
    /**
     *

     * The name of the country.
     *

     */
    private String countryName;
    /**
     *

     * The code for the subdivision, for example, a state in the United States or a province in Canada.
     *

     */
    private String subdivisionCode;
    /**
     *

     * The full name of the subdivision, for example, a state in the United States or a province in Canada.
     *

     */
    private String subdivisionName;

    /**
     *

     * The two-letter code for the continent.
     *

     *
     * @param continentCode
     *        The two-letter code for the continent.
     */

    public void setContinentCode(String continentCode) {
        this.continentCode = continentCode;
    }

    /**
     *

     * The two-letter code for the continent.
     *

     *
     * @return The two-letter code for the continent.
     */

    public String getContinentCode() {
        return this.continentCode;
    }

    /**
     *

     * The two-letter code for the continent.
     *

     *
     * @param continentCode
     *        The two-letter code for the continent.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GeoLocationDetails withContinentCode(String continentCode) {
        setContinentCode(continentCode);
        return this;
    }

    /**
     *

     * The full name of the continent.
     *

     *
     * @param continentName
     *        The full name of the continent.
     */

    public void setContinentName(String continentName) {
        this.continentName = continentName;
    }

    /**
     *

     * The full name of the continent.
     *

     *
     * @return The full name of the continent.
     */

    public String getContinentName() {
        return this.continentName;
    }

    /**
     *

     * The full name of the continent.
     *

     *
     * @param continentName
     *        The full name of the continent.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GeoLocationDetails withContinentName(String continentName) {
        setContinentName(continentName);
        return this;
    }

    /**
     *

     * The two-letter code for the country.
     *

     *
     * @param countryCode
     *        The two-letter code for the country.
     */

    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }

    /**
     *

     * The two-letter code for the country.
     *

     *
     * @return The two-letter code for the country.
     */

    public String getCountryCode() {
        return this.countryCode;
    }

    /**
     *

     * The two-letter code for the country.
     *

     *
     * @param countryCode
     *        The two-letter code for the country.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GeoLocationDetails withCountryCode(String countryCode) {
        setCountryCode(countryCode);
        return this;
    }

    /**
     *

     * The name of the country.
     *

     *
     * @param countryName
     *        The name of the country.
     */

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    /**
     *

     * The name of the country.
     *

     *
     * @return The name of the country.
     */

    public String getCountryName() {
        return this.countryName;
    }

    /**
     *

     * The name of the country.
     *

     *
     * @param countryName
     *        The name of the country.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GeoLocationDetails withCountryName(String countryName) {
        setCountryName(countryName);
        return this;
    }

    /**
     *

     * The code for the subdivision, for example, a state in the United States or a province in Canada.
     *

     *
     * @param subdivisionCode
     *        The code for the subdivision, for example, a state in the United States or a province in Canada.
     */

    public void setSubdivisionCode(String subdivisionCode) {
        this.subdivisionCode = subdivisionCode;
    }

    /**
     *

     * The code for the subdivision, for example, a state in the United States or a province in Canada.
     *

     *
     * @return The code for the subdivision, for example, a state in the United States or a province in Canada.
     */

    public String getSubdivisionCode() {
        return this.subdivisionCode;
    }

    /**
     *

     * The code for the subdivision, for example, a state in the United States or a province in Canada.
     *

     *
     * @param subdivisionCode
     *        The code for the subdivision, for example, a state in the United States or a province in Canada.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GeoLocationDetails withSubdivisionCode(String subdivisionCode) {
        setSubdivisionCode(subdivisionCode);
        return this;
    }

    /**
     *

     * The full name of the subdivision, for example, a state in the United States or a province in Canada.
     *

     *
     * @param subdivisionName
     *        The full name of the subdivision, for example, a state in the United States or a province in Canada.
     */

    public void setSubdivisionName(String subdivisionName) {
        this.subdivisionName = subdivisionName;
    }

    /**
     *

     * The full name of the subdivision, for example, a state in the United States or a province in Canada.
     *

     *
     * @return The full name of the subdivision, for example, a state in the United States or a province in Canada.
     */

    public String getSubdivisionName() {
        return this.subdivisionName;
    }

    /**
     *

     * The full name of the subdivision, for example, a state in the United States or a province in Canada.
     *

     *
     * @param subdivisionName
     *        The full name of the subdivision, for example, a state in the United States or a province in Canada.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GeoLocationDetails withSubdivisionName(String subdivisionName) {
        setSubdivisionName(subdivisionName);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getContinentCode() != null)
            sb.append("ContinentCode: ").append(getContinentCode()).append(",");
        if (getContinentName() != null)
            sb.append("ContinentName: ").append(getContinentName()).append(",");
        if (getCountryCode() != null)
            sb.append("CountryCode: ").append(getCountryCode()).append(",");
        if (getCountryName() != null)
            sb.append("CountryName: ").append(getCountryName()).append(",");
        if (getSubdivisionCode() != null)
            sb.append("SubdivisionCode: ").append(getSubdivisionCode()).append(",");
        if (getSubdivisionName() != null)
            sb.append("SubdivisionName: ").append(getSubdivisionName());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GeoLocationDetails == false)
            return false;
        GeoLocationDetails other = (GeoLocationDetails) obj;
        if (other.getContinentCode() == null ^ this.getContinentCode() == null)
            return false;
        if (other.getContinentCode() != null && other.getContinentCode().equals(this.getContinentCode()) == false)
            return false;
        if (other.getContinentName() == null ^ this.getContinentName() == null)
            return false;
        if (other.getContinentName() != null && other.getContinentName().equals(this.getContinentName()) == false)
            return false;
        if (other.getCountryCode() == null ^ this.getCountryCode() == null)
            return false;
        if (other.getCountryCode() != null && other.getCountryCode().equals(this.getCountryCode()) == false)
            return false;
        if (other.getCountryName() == null ^ this.getCountryName() == null)
            return false;
        if (other.getCountryName() != null && other.getCountryName().equals(this.getCountryName()) == false)
            return false;
        if (other.getSubdivisionCode() == null ^ this.getSubdivisionCode() == null)
            return false;
        if (other.getSubdivisionCode() != null && other.getSubdivisionCode().equals(this.getSubdivisionCode()) == false)
            return false;
        if (other.getSubdivisionName() == null ^ this.getSubdivisionName() == null)
            return false;
        if (other.getSubdivisionName() != null && other.getSubdivisionName().equals(this.getSubdivisionName()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getContinentCode() == null) ? 0 : getContinentCode().hashCode());
        hashCode = prime * hashCode + ((getContinentName() == null) ? 0 : getContinentName().hashCode());
        hashCode = prime * hashCode + ((getCountryCode() == null) ? 0 : getCountryCode().hashCode());
        hashCode = prime * hashCode + ((getCountryName() == null) ? 0 : getCountryName().hashCode());
        hashCode = prime * hashCode + ((getSubdivisionCode() == null) ? 0 : getSubdivisionCode().hashCode());
        hashCode = prime * hashCode + ((getSubdivisionName() == null) ? 0 : getSubdivisionName().hashCode());
        return hashCode;
    }

    @Override
    public GeoLocationDetails clone() {
        try {
            return (GeoLocationDetails) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package controller;

import java.io.IOException;
import java.lang.reflect.Constructor;

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

import framework.BaseHelper;
import framework.Helper;

@SuppressWarnings("serial")
public class Controller extends HttpServlet {

    private static final boolean MAINTENANCE_MODE = false;

    public synchronized void init() throws ServletException {
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
	process(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
	process(request, response);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void process(HttpServletRequest request, HttpServletResponse response) {

	// authenticate with Google account
	String thisUrl = request.getRequestURI();
	if (request.getUserPrincipal() == null) {
	    try {
		response.getWriter().println("
Please sign in to continue.
");
	    } catch (IOException e1) {
		e1.printStackTrace();
	    }
	} else {

	    // String GoogleName = request.getUserPrincipal().getName();
	    String GoogleUserEmail = Helper.getSecurityhelper().getGoogleUserEmail();
	    if (!Helper.getSecurityhelper().hasGeneralAccess(GoogleUserEmail)) {
		try {
		    response.getWriter().println("
Development has been discontinued indefinitely." + " You can sign out.
");
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    } else {

		// maintenance mode
		if (MAINTENANCE_MODE) {
		    try {
			response.getWriter().println("
Bank of Dawgs is under maintenance. Please try again later." + " You can sign out.
");
		    } catch (IOException e) {
			e.printStackTrace();
		    }
		} else {

		    // if logged in as Google user, and has access.
		    request.setAttribute("GoogleUserEmail", GoogleUserEmail);
		    request.setAttribute("GoogleLogoutUrl", BaseHelper.getUserservice().createLogoutURL(thisUrl));
		    request.setAttribute("timestamp", BaseHelper.getTimesteamp());

		    String path = request.getServletPath();
		    String actionName = getActionName(path);
		    String nextPage = null;
		    Action action = null;
		    Class actionClass;
		    try {
			actionClass = Class.forName("action." + actionName + "Action");
			Constructor<? extends Action> actionConstructor = actionClass.getDeclaredConstructor();
			Object arglist[] = {};
			action = (Action) actionConstructor.newInstance(arglist);

		    } catch (Exception e) {
			// nextPage = "Home.do";
			nextPage = "noaccess.view";
			nextPage(request, response, nextPage);
			return;
		    }
		    nextPage = action.perform(request, response);
		    if (!response.isCommitted()) {
			nextPage(request, response, nextPage);
		    }
		}

	    }

	}

    }

    private String getActionName(String path) {
	int slash = path.lastIndexOf('/');
	int dot = path.indexOf(".", slash + 1);
	return path.substring(slash + 1, dot);
    }

    private void nextPage(HttpServletRequest request, HttpServletResponse response, String nextPage) {
	String path = "Home.do";
	if (nextPage != null && nextPage.contains(".do")) {
	    path = nextPage;
	} else if (nextPage != null && nextPage.contains(".view")) {
	    // path = "WEB-INF/20170309_expired/" + nextPage.replace(".view",
	    // ".jsp");
	    path = "WEB-INF/20170310/" + nextPage.replace(".view", ".jsp");
	}

	RequestDispatcher dispatch = request.getRequestDispatcher(path);
	try {
	    dispatch.forward(request, response);
	} catch (ServletException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}
    }
}


text:
package ru.job4j.threads;

import org.junit.Test;

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

/**
 * tests methods of class Tokenizer.
 * @author Dinis Saetgareev (dinis0086@mail.ru)
 * @since 17.05.2017
 * @version 1.0
 */
public class TokenizerTest {
    /**
     * testing method countWord().
     */
    @Test
    public void whenStringThenCountWords() {
        Tokenizer token = new Tokenizer("Hello! How are you?");

        assertThat(token.countWord(), is(4));
    }

    /**
     * testing method countSpaces().
     */
    @Test
    public void whenStringThenCountSpaces() {
        Tokenizer token = new Tokenizer("Hello! How are you?");

        assertThat(token.countSpaces(), is(3));
    }

}


text:
<!DOCTYPE html>

  <title>Vibrate outside click handler</title>

    <input id="button" type="button"
           value="Click here within 9 seconds of load" />

Log:


text:
package com.pacificmetrics.orca.utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HTMLUtil {

    private HTMLUtil() {
    }

    public static String getTextOfElement(String html, String elementid) {
        Document doc = Jsoup.parse(html);
        Element parentElement = doc.getElementById(elementid);
        return parentElement != null ? parentElement.text() : "";
    }

    public static String getWordOfElement(String html, String elementid,
            int wordno) {
        String text = getTextOfElement(html, elementid);
        return removePuncuation(StringUtils.isNotBlank(text) ? text.split(" ")[wordno - 1]
                : "");
    }

    public static String getCharacterSequenceOfElement(String html,
            String elementid, int startChar, int endChar) {
        String text = getTextOfElement(html, elementid);
        return StringUtils.isNotBlank(text) ? text.substring(startChar - 1,
                endChar - 1) : "";
    }

    public static String removePuncuation(String text) {
        if (StringUtils.isNotBlank(text) && text.matches("^.*\\p{P}$")) {
            return text.replaceAll("(?!\")\\p{P}$", "").replaceAll("\\.*$", "");
        }
        return text;
    }

    public static String sanitizeHtml(String html) {
        Document doc = Jsoup.parse(html);
        Elements links = doc.select("a[href]");
        Elements media = doc.select("[src]");
        Elements imports = doc.select("link[href]");

        if (CollectionUtils.isNotEmpty(media)) {
            for (Element src : media) {
                if ("img".equals(src.tagName())
                        && StringUtils.isNotBlank(src.attr("abs:src"))
                        && src.attr("abs:src").lastIndexOf("/") != -1) {
                    String url = src.attr("abs:src");
                    String file = url.substring(url.lastIndexOf("/") + 1);
                    src.attr("src", file);
                }
            }
        }

        if (CollectionUtils.isNotEmpty(links)) {
            for (Element link : links) {
                if (StringUtils.isNotBlank(link.attr("abs:href"))) {
                    link.attr("href", "");
                }
            }
        }

        return doc
                .body()
                .html()
                .replaceAll("<\\s*(img)+((\"[^\"]*\"|[^>/])*)(?<!/)\\s*>",
                        "<$1$2></$1>");
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/color"
        android:title="@string/menuItem_color"
        android:icon="@drawable/ic_palette_black_24dp"
        app:showAsAction="ifRoom"/>
    <item android:id="@+id/line_width"
        android:title="@string/menuItem_line_width"
        android:icon="@drawable/ic_brush_black_24dp"
        app:showAsAction="ifRoom"/>
    <item android:id="@+id/delete_drawing"
        android:title="@string/menuItem_delete"
        android:icon="@drawable/ic_delete_black_24dp"
        app:showAsAction="ifRoom"/>
    <item android:id="@+id/save"
        android:title="@string/menuItem_save"
        android:icon="@drawable/ic_save_black_24dp"
        app:showAsAction="ifRoom"/>
    <item android:id="@+id/print"
        android:title="@string/menuItem_print"
        android:icon="@drawable/ic_print_black_24dp"
        app:showAsAction="ifRoom"/>
</menu>


text:
class GeoController < ApplicationController

  skip_before_filter :verify_authenticity_token

  def geo_model
    throw NotImplementedError
  end

  def index
    client_srid = params[:srid].blank? ? geo_model.default_client_srid : params[:srid].to_i

    @features = geo_model.bbox_filter(params)
    @features = @features.user_filter(current_ability)
    respond_to do |format|
      # NOTE: return GeoJSON by default (OpenLayers.Protocol.HTTP PUT does not work with '.json' format selection)
      format.html {
        render :json => @features.json_filter.select_geojson_geom(client_srid).to_geojson
      }
      format.csv {
        send_csv_excel(@features.csv_filter)
      }
    end
  end

  def show
    client_srid = params[:srid].blank? ? geo_model.default_client_srid : params[:srid].to_i

    @feature = geo_model.user_filter(current_ability).json_filter.select_geojson_geom(client_srid).find(params[:id])
    render :json => [@feature].to_geojson
  end

  def create
    if params[:editv2]
      create_v2
    else
      create_v1
    end
  end

  def update
    if params[:editv2]
      update_v2
    else
      update_v1
    end
  end

  def destroy
    if params[:editv2]
      destroy_v2
    else
      destroy_v1
    end
  end

  def create_v2
    unless geo_model.can_edit?(current_ability)
      render :json => {
        :error => "Forbidden"
      }, :status => :forbidden
      return
    end

    geojson_data = request.raw_post
    begin
      feature_collection = geo_model.geojson_decode(geojson_data)
    rescue => err
      # JSON parse error
      render :json => {
        :error => "Invalid JSON: #{err.message}"
      }, :status => :bad_request
      return
    end
    error = geo_model.validate_feature_collection(feature_collection, geojson_data)
    unless error.nil?
      render :json => error, :status => :bad_request
      return
    end

    @features = []
    feature_collection.each do |feature|
      if feature.feature_id.is_a? Integer
        begin
          new_feature = geo_model.find(feature.feature_id)
        rescue ActiveRecord::RecordNotFound => err
          render :json => {
            :error => "Feature ID not found"
          }, :status => :not_found
          return
        end
      end
      if new_feature.nil?
        new_feature = geo_model.new
      end

      logger.info "#{geo_model.table_name}.update_attributes_from_feature: #{feature.inspect}"
      if new_feature.update_attributes_from_geojson_feature(feature, current_user)
        # transform geometry to SRID from GeoJSON feature
        client_srid = feature.geometry.nil? ? geo_model.default_client_srid : feature.geometry.srid
        new_feature = geo_model.json_filter.select_geojson_geom(client_srid).find(new_feature.id)

        @features << new_feature
      else
        render :json => {
          :error => "Feature validation failed",
          :validation_errors => new_feature.errors.full_messages
        }, :status => :unprocessable_entity
        return
      end
    end

    render :json => @features.to_geojson, :status => :created
  end

  def update_v2
    unless geo_model.can_edit?(current_ability)
      render :json => {
        :error => "Forbidden"
      }, :status => :forbidden
      return
    end

    geojson_data = request.raw_post
    begin
      feature = geo_model.geojson_decode(geojson_data)
    rescue => err
      # JSON parse error
      render :json => {
        :error => "Invalid JSON: #{err.message}"
      }, :status => :bad_request
      return
    end
    error = geo_model.validate_feature(feature, geojson_data)
    unless error.nil?
      render :json => error, :status => :bad_request
      return
    end

    if feature.feature_id.is_a? Integer
      begin
        # NOTE: user_filter may limit editable features; find raises RecordNotFound if feature cannot be found
        @feature = geo_model.user_filter(current_ability).find(feature.feature_id)
      rescue ActiveRecord::RecordNotFound => err
        render :json => {
          :error => "Feature ID not found"
        }, :status => :not_found
        return
      end
    end

    if @feature.update_attributes_from_geojson_feature(feature, current_user)
      # transform geometry to SRID from GeoJSON feature
      client_srid = feature.geometry.nil? ? geo_model.default_client_srid : feature.geometry.srid
      @feature = geo_model.json_filter.select_geojson_geom(client_srid).find(@feature.id)

      render :json => @feature.to_geojson, :status => :created
    else
      render :json => {
        :error => "Feature validation failed",
        :validation_errors => @feature.errors.full_messages
      }, :status => :unprocessable_entity
    end
  end

  def destroy_v2
    begin
      @feature = geo_model.user_filter(current_ability).find(params[:id])
    rescue ActiveRecord::RecordNotFound => err
      render :json => {
        :error => "Feature ID not found"
      }, :status => :not_found
      return
    end
    @feature.destroy
    render :json => {
      :message => "Feature removed"
    }
  end

  def create_v1
    @features = []
    feature_collection = geo_model.geojson_decode(request.raw_post)
    if feature_collection.nil? || !geo_model.can_edit?(current_ability)
      head :bad_request
      return
    end

    feature_collection.each do |feature|
      if feature.feature_id.is_a? Integer
        new_feature = geo_model.find(feature.feature_id)
      end
      if new_feature.nil?
        new_feature = geo_model.new
      end

      logger.info "#{geo_model.table_name}.update_attributes_from_feature: #{feature.inspect}"
      if new_feature.update_attributes_from_geojson_feature(feature, current_user)
        # transform geometry to SRID from GeoJSON feature
        client_srid = feature.geometry.nil? ? geo_model.default_client_srid : feature.geometry.srid
        new_feature = geo_model.json_filter.select_geojson_geom(client_srid).find(new_feature.id)

        @features << new_feature
      else
        head :unprocessable_entity
        return
      end
    end

    render :json => @features.to_geojson, :status => :created
  end

  def update_v1
    # NOTE: user_filter checks if model is editable
    feature = geo_model.user_filter(current_ability).geojson_decode(request.raw_post)
    if feature.nil?
      head :bad_request
      return
    end

    if feature.feature_id.is_a? Integer
      # NOTE: user_filter may limit editable features; find raises RecordNotFound if feature cannot be found
      @feature = geo_model.user_filter(current_ability).find(feature.feature_id)
    end

    if @feature.update_attributes_from_geojson_feature(feature, current_user)
      # transform geometry to SRID from GeoJSON feature
      client_srid = feature.geometry.nil? ? geo_model.default_client_srid : feature.geometry.srid
      @feature = geo_model.json_filter.select_geojson_geom(client_srid).find(@feature.id)

      render :json => @feature.to_geojson, :status => :created
    else
      head :unprocessable_entity
    end
  end

  def destroy_v1
    @feature = geo_model.user_filter(current_ability).find(params[:id])
    @feature.destroy
    head :no_content
  end

  private

  def send_csv_excel(features)
    require 'csv'

    # add byte order mark and use CRLF row breaks for Excel
    bom = "\xEF\xBB\xBF"
    csv_data = CSV.generate(bom, {:write_headers => true, :col_sep => ";", :row_sep => "\r\n"}) do |csv|
      csv << features.first.csv_header unless features.empty?
      features.each do |adresse|
        csv << adresse.csv_row
      end
    end

    send_data(csv_data, :filename => "features_#{geo_model.table_name}.csv", :type => 'text/csv; header=present')
  end

end


text:
package link.se7en.common.test;

import com.alibaba.fastjson.JSONObject;
import link.se7en.common.entity.BeanForTest;
import link.se7en.common.entity.CsvFieldBind;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;

import static link.se7en.common.utils.BeanUtil.csvToBean;
import static link.se7en.common.utils.BeanUtil.jsonToBean;

/**
 * Created by Link on 2017/3/29.
 */
public class TestBeanUtil {

    @Test
    public void csvTest() {
        CsvFieldBind bind = new CsvFieldBind();

        bind.bind(0,"s").bind(1,"i").bind(2,"l").bind(3,"f").bind(4,"d")
                .bind(5,"b").bind(6,"by").bind(7,"c");

        BeanForTest bean = csvToBean("abc,123,123123123,111.111,1231.123123123,true,1,a", ",", BeanForTest.class, bind);
        System.out.println(bean);// 在这里打断点,可以看到bean的属性已被注入!
    }

    @Test
    public void jsonTest() {
        JSONObject json = new JSONObject();
        json.put("s", RandomStringUtils.random(RandomUtils.nextInt(3,8),true,true));
        json.put("i", RandomUtils.nextInt(0,10000));
        json.put("l", RandomUtils.nextLong(0L,10000000L));
        json.put("f", RandomUtils.nextFloat(0.0f,10000.0f));
        json.put("d", RandomUtils.nextDouble(0.0d,10000000.0d));
        json.put("b", RandomUtils.nextInt(0,1) == 0);
        json.put("by", RandomUtils.nextBytes(1)[0]);
        json.put("c", RandomStringUtils.random(1).charAt(0));

        String jsonStr = json.toString();

        System.out.println(jsonStr);

        BeanForTest bean = jsonToBean(jsonStr,BeanForTest.class);
        System.out.println(bean);// 在这里打断点,可以看到bean的属性已被注入!
    }

    @Test
    public void jsonEntityTest() {
        BeanForTest bean = new BeanForTest();

        bean.setS(RandomStringUtils.random(RandomUtils.nextInt(3,8),true,true));
        bean.setI(RandomUtils.nextInt(0,10000));
        bean.setL(RandomUtils.nextLong(0L,10000000L));
        bean.setF(RandomUtils.nextFloat(0.0f,10000.0f));
        bean.setD(RandomUtils.nextDouble(0.0d,10000000.0d));
        bean.setB(RandomUtils.nextInt(0,1) == 0);
        bean.setBy(RandomUtils.nextBytes(1)[0]);
        bean.setC(RandomStringUtils.random(1).charAt(0));

        String jsonStr = bean.toJsonStr();

        System.out.println(jsonStr);

        BeanForTest newBean = jsonToBean(jsonStr,BeanForTest.class);
        System.out.println(newBean);// 在这里打断点,可以看到bean的属性已被注入!
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using MindTouch.Deki.Script.Expr;

namespace MindTouch.Deki.Script.Runtime {
    internal static class DekiScriptOutputBufferEx {

        //--- Extension Methods ---
        public static StringBuilder AppendLiteral(this StringBuilder builder, DekiScriptLiteral literal) {
            if(literal is DekiScriptString) {
                builder.Append(((DekiScriptString)literal).Value);
            } else {
                builder.Append(literal.ToString());
            }
            return builder;
        }
    }

    internal class DekiScriptOutputBuffer {

        //--- Constants ---
        public const int MAX_NODE_COUNT = 100000;

        //--- Types ---
        internal struct Range {

            //--- Class Fields ---
            public static readonly Range Empty = new Range(0, 0);

            //--- Fields ---
            public readonly int Start;
            public readonly int End;

            //--- Constructors ---
            public Range(int start, int end) {
                this.Start = start;
                this.End = end;
            }

            //--- Properties ---
            public int Count { get { return End - Start; } }
            public bool IsEmpty { get { return Start == End; } }
        }

        internal class XmlStart {

            //--- Fields ---
            public readonly string Prefix;
            public readonly string Name;
            public readonly Dictionary<string, string> Namespaces;
            public readonly List<Tuplet<string/*Prefix*/, string/*Name*/, string/*Value*/>> Attributes;

            //--- Constructors ---
            public XmlStart(string prefix, string name, Dictionary<string, string> namespaces, List<Tuplet<string, string, string>> attributes) {
                this.Prefix = prefix;
                this.Name = name;
                this.Namespaces = namespaces;
                this.Attributes = attributes;
            }

            //--- Methods ---
            public override string ToString() {
                var result = new StringBuilder();
                result.Append("<");
                result.Append(Name);
                if((Attributes != null) && (Attributes.Count > 0)) {
                    foreach(var attribute in Attributes) {
                        result.Append(" ");
                        result.Append(attribute.Item2);
                        result.Append("=");
                        result.Append(attribute.Item3.QuoteString());
                    }
                }
                result.Append(">");
                return result.ToString();
            }
        }

        internal class XmlEnd {

            //--- Class Fields ---
            public static readonly XmlEnd Value = new XmlEnd();

            //--- Constructors ---
            private XmlEnd() { }

            //--- Methods ---
            public override string ToString() {
                return "</>";
            }
        }

        //--- Fields ---
        private readonly List<object> _buffer = new List<object>();
        private readonly int _limit;

        //--- Constructors ---
        public DekiScriptOutputBuffer() {
            _limit = MAX_NODE_COUNT;
        }

        //--- Properties ---
        public object this[int index] { get { return _buffer[index]; } }
        public int Marker { get { return _buffer.Count; } }

        //--- Methods ---
        public DekiScriptLiteral Pop(Range range, bool safe) {

            // check if range is empty
            if(range.IsEmpty) {
                return DekiScriptNil.Value;
            }

            // make sure we're not trying to process elements in the middle of the buffer
            if(range.End != _buffer.Count) {
                throw new ArgumentException("range is not valid");
            }

            // optimize for the common case where we need the last added item
            if(range.Count == 1) {
                var result = (DekiScriptLiteral)_buffer[range.Start];
                _buffer.RemoveAt(range.Start);
                return result;
            }

            // process contents of output buffer
            return new DekiScriptOutputProcessor().Process(this, range.Start, safe);
        }

        public Range Since(int marker) {
            return new Range(marker, _buffer.Count);
        }

        public void Reset(int marker) {
            _buffer.RemoveRange(marker, _buffer.Count - marker);
        }

        public Range Push(DekiScriptLiteral literal) {
            if(literal.IsNil) {
                return Range.Empty;
            }

            // append element
            int start = _buffer.Count;
            CheckBufferLimits();
            _buffer.Add(literal);
            return new Range(start, _buffer.Count);
        }

        internal void PushXmlStart(string prefix, string name, Dictionary<string, string> namespaces, List<Tuplet<string, string, string>> attributes) {
            CheckBufferLimits();
            _buffer.Add(new XmlStart(prefix, name, namespaces, attributes));
        }

        internal void PushXmlEnd() {
            CheckBufferLimits();
            _buffer.Add(XmlEnd.Value);
        }

        private void CheckBufferLimits() {
            if(_buffer.Count >= _limit) {
                throw new DekiScriptDocumentTooLargeException(_buffer.Count);
            }
        }
    }
}


text:
var localTasks = require('../lib/localTasks');

module.exports = function(grunt) {
  var plugin = 'grunt-karma';

  localTasks.load(grunt, plugin);
};


text:
/* Debug Bar and Support Form */

div#debug-bar-tribe ul {
	list-style: none;
	margin: 0px;
	padding: 0px;
}

div#debug-bar-tribe li {
	padding: 0px;
	display: block;
	margin-bottom: 6px;
	background-color: #F4F4F4;
	border: #eee solid 1px;
}

div#debug-bar-tribe li div.tribe-debug-entry-title {
	font-weight: bold;
	padding: 10px;
	margin: 0;
	background-color: #eee;
}

div#debug-bar-tribe li div.tribe-debug-entry-data {
	padding: 10px;
}

div#debug-bar-tribe li.tribe-debug-log {
}

div#debug-bar-tribe li.tribe-debug-warning,
div#debug-bar-tribe li.tribe-debug-notice {
	background-color: #fffcee;
	border: #E6DB55 solid 1px;
}

div#debug-bar-tribe li.tribe-debug-warning div.tribe-debug-entry-title,
div#debug-bar-tribe li.tribe-debug-notice div.tribe-debug-entry-title {
	background-color: #E6DB55;
}

div#debug-bar-tribe li.tribe-debug-error {
	background-color: #fee;
	border: #D66 solid 1px;
}

div#debug-bar-tribe li.tribe-debug-error div.tribe-debug-entry-title {
	background-color: #D66;
}

div.tribe-support-form{
	width: 98%;
	border: #eee solid 1px;
	background-color: #efefef;
	padding: 10px;
}

div.tribe-support-form-description textarea {
	width: 100%;
	height: 200px;
}

div.tribe-support-form-submit input {
	margin-top: 10px;
	padding: 10px;
}

div#debug-bar-tribe li div.tribe-support-form {
	width: 100%;
	border: none;
	padding: 0;
	margin: 0;
	background: none;
}

div#debug-bar-tribe li div.tribe-support-form h3 {
	background-color: #eee;
	padding: 10px;
	margin: -10px;
	margin-bottom: 10px;
	font-weight: bold;
}


text:
//  (C) Copyright Edward Diener 2012
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).

#include "test_has_data.hpp"
#include <boost/mpl/assert.hpp>

int main()
  {

  // SomeStaticData does not exist at all

  BOOST_MPL_ASSERT((BOOST_TTI_HAS_DATA_GEN(SomeStaticData)<AnotherType,float>));

  return 0;

  }


text:
require 'rake'
require 'rake/tasklib'

module Lifeline
  ##
  # @private
  def get_processes_from_shell
     %x{ps ax -o pid,command}
  end

  ##
  # @private
  def get_process_list
    processes = get_processes_from_shell

    return nil if processes.nil?

    processes.split(/\n/).map do |p|
      if p =~ /^\s*(\d+)\s(.+)$/
        {:pid => $1.to_i, :command => $2.strip}
      end
    end.compact
  end

  ##
  # A method for executing a block of code only if there is no other process with the same command running. This is useful if you want
  # to have a perpetually running daemon that only executes once at a time. It uses the process name returned by ps ax to see if there is
  # a process with the same command name but a different PID already executing. If so, it terminates without running the block. NOTE: since it
  # uses the command name returned from <tt>ps ax</tt>, it us up to to you to name the process containing this code with a distinctly unique name. If two
  # separate Rails projects both have a <tt>rake lifeline</tt> task they WILL interfere with each other. I'd suggest prefixing with the project name (ie,
  # <tt>doc_viewer:lifeline</tt>) to be sure
  #
  # @param &block a block which is executed if there is not already a lifeline running.
  # @raise [ArgumentError] if you do not pass in a block argument
  def lifeline
    if !block_given?
      raise ArgumentError, "You must pass in a block to be the body of the run rake task"
    end

    my_pid = $$
    processes = get_process_list

    if processes.nil? || processes.empty?
      raise "No processes being returned by get_process_list. Aborting!"
    end

    myself = processes.detect {|p| p[:pid] == my_pid}
    if myself.nil?
      raise "Unable to find self (PID=#{my_pid}) in process list. This is bizarre to say the least. Exiting.\n#{processes.map {|p| p.inspect}.join("\n")}"
    end

    # there isn't already another process running with the same command
    if !processes.any? {|p| p[:pid] != my_pid && p[:command] == myself[:command]}
      yield
    end
  end

  # Define rake tasks for running, starting, and terminating
  class LifelineRakeTask < ::Rake::TaskLib
    # The namespace to define the tasks in
    # @return [String] the namespace for the tasks
    attr_accessor :namespace

    ##
    # Creates 3 new tasks for the lifeline in the namespace specified. These
    # tasks are
    # * run - a task for running the code provided in the block
    # * lifeline - a lifeline task for running the run task if it's not already running
    # * terminate - a task for terminating all lifelines.
    #
    # @param [String, Symbol] name the namespace of the rake tasks
    # @param [optional, Hash] opts Additional options for the method
    # @option opts [Array<String, Symbol>] :prereqs ([]) If there any any rake tasks that should be prerequisites of the :run task, specify them here (For Rails, you would do :prereqs => :environment)
    # @param a block that defines the body of the run task
    def initialize(namespace, opts={}, &block)
      if !block_given?
        raise ArgumentError, "You must pass in a block to be the body of the run rake task"
      end

      @namespace = namespace

      define_run_task(opts, &block)
      define_lifeline_task
      define_terminate_task
    end

    protected

    def run_task_name
      "#{namespace}:run"
    end

    def define_run_task(opts={}, &block)
      desc "Runs the #{namespace}:run task"

      task_arg = if opts[:prereqs]
        {run_task_name => opts[:prereqs]}
      else
        run_task_name
      end

      task(task_arg, &block)
    end

    def define_lifeline_task
      desc "A lifeline task for executing only one process of #{namespace}:run at a time"
      task("#{namespace}:lifeline") do
        lifeline do
          Rake::Task["#{namespace}:run"].invoke
        end
      end
    end

    def define_terminate_task
      desc "Terminates any running #{namespace}:lifeline tasks"
      task("#{namespace}:terminate") do
        unless (process = %x{ps aux | grep "#{namespace}:lifeline" | grep ruby | grep -v grep}.chomp).empty?
          runner_pid = process.gsub(/(\s+)/, ' ').split(' ')[1]
          puts %x{kill -9 #{runner_pid}}
        end
      end
    end
  end

  ##
  # A method that defines 3 rake tasks for doing lifelines:
  # * <tt>namespace:run</tt> runs the specified block
  # * <tt>namespace:lifeline</tt> a lifeline for executing only a single copy of <tt>namespace:run</tt> at a time
  # * <tt>namespace:terminate</tt> a task for terminating the lifelines
  #
  # @param [String,Symbol] namespace the namespace to define the 3 tasks in
  # @param &block a block which defines the body of the namespace:run method
  #
  # @raise [ArgumentError] if you do not pass in a block argument
  def define_lifeline_tasks(namespace, &block)
    LifelineRakeTask.new(namespace, &block)
  end
end


text:
section: events
lead: true
title: Developer meetings
authors:
- Tryggvi Björgvinsson
---
The first Thursday of every month we run a developer meeting for **everyone** hacking on [OpenSpending](http://openspending.org). These are a great way to get involved in the development (and thus the future) of the OpenSpending platform. We are very newcomer friendly so you can join the meeting and we *will* listen and value your input.

* **How**: Developer meetings are done **online** via text chat on IRC. (Details below.)
* **When**: 1st Thursday of each month at **4pm CET** (2pm GMT).
  * Also [Listed in Community Calendar]({{ site.baseurl }}/events/).
* **Who**: Anyone! All are welcome. Discussions might get technical but we also discuss things like documentation and management, etc.

## How to Participate in a Developer Meeting

Join the online chat channel:

* To join via your web browser, just [click on this link](http://webchat.freenode.net/?channels=openspending).
* If you are familiar with IRC, join #OpenSpending on Freenode using your favourite IRC client.


text:
package ru.job4j.io.filemanager;

import com.google.common.base.Joiner;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

import static ru.job4j.io.filemanager.ServerImpl.CURRENT_DIRECTORY_IS_SET_TO;
import static ru.job4j.io.filemanager.ServerImpl.SLASH;
import static ru.job4j.io.server.Server.EMPTY_LINE;
import static ru.job4j.io.server.Server.SPACE;

public class DispatchPattern {
    private ServerImpl server;
    private PrintWriter out;

    public DispatchPattern(ServerImpl server, PrintWriter out) {
        this.server = server;
        this.out = out;
    }

    /**
     * Contains destinations.
     */
    private final Map<Message.Type, Function<String, Boolean>> dispatch = new HashMap<>();

    public Function<String, Boolean> listFiles() {
        return s -> {
            Arrays.asList(Objects.requireNonNull(new File(this.server.getCurrentDirectory()).listFiles())).forEach(out::println);
            out.println(EMPTY_LINE);
            return true;
        };
    }

    public Function<String, Boolean> goToParentDirectory() {
        return s -> {
            this.server.setCurrentDirectory(new File(this.server.getCurrentDirectory()).getParent());
            out.println(Joiner.on(" ").join(CURRENT_DIRECTORY_IS_SET_TO, server.getCurrentDirectory()));
            out.println(EMPTY_LINE);
            return true;
        };
    }

    public Function<String, Boolean> goToSubDirectory() {
        return subDirectory -> {
            if (subDirectory != null) {
                server.setCurrentDirectory(Joiner.on(SLASH).join(server.getCurrentDirectory(), subDirectory));
                out.println(Joiner.on(SPACE).join(CURRENT_DIRECTORY_IS_SET_TO, server.getCurrentDirectory()));
                out.println(EMPTY_LINE);
            } else {
                out.println(EMPTY_LINE);
            }
            return true;
        };
    }

    public Function<String, Boolean> downloadFile() {
        return toDownload -> {
            try (FileInputStream fis = new FileInputStream(Joiner.on(SLASH).join(server.getCurrentDirectory(), toDownload))) {
                byte[] buffer = new byte[100000];
                int read = fis.read(buffer);
                while (read != -1) {
                    server.getSocket().getOutputStream().write(buffer, 0, read);
                    read = fis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        };
    }

    public Function<String, Boolean> uploadFile() {
        return toUpload -> {
        String[] split = toUpload.split(SLASH);
        String file = split[split.length - 1];
        try (FileOutputStream fos = new FileOutputStream(Joiner.on(SLASH).join(server.getCurrentDirectory(), file))) {
            byte[] buffer = new byte[100000];
            int read;
            do {
                read = server.getSocket().getInputStream().read(buffer);
                fos.write(buffer, 0, read);
            } while (read > 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
            return true;
        };
    }

    /**
     * Init's dispatch.
     *
     * @return current object.
     */
    public DispatchPattern init() {
        this.load(Message.Type.LS, this.listFiles());
        this.load(Message.Type.UP, this.goToParentDirectory());
        this.load(Message.Type.CD, this.goToSubDirectory());
        this.load(Message.Type.DOWNLOAD, this.downloadFile());
        this.load(Message.Type.UPLOAD, this.uploadFile());
        return this;
    }

    /**
     * Load handlers for destinations.
     *
     * @param type   Message type.
     * @param handle Handler.
     */
    public void load(Message.Type type, Function<String, Boolean> handle) {
        this.dispatch.put(type, handle);
    }

    public Function<String, Boolean> get(final Message msg) {
        return this.dispatch.get(msg.type());
    }
}


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

<title>project</title>
<meta name="date" content="2014-10-31">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

project

Classes

Arrayfiller

main

Word_search


text:
#ifndef __GSL_STATISTICS_LONG_DOUBLE_H__
#define __GSL_STATISTICS_LONG_DOUBLE_H__

#if !defined( GSL_FUN )
#  if !defined( GSL_DLL )
#    define GSL_FUN extern
#  elif defined( BUILD_GSL_DLL )
#    define GSL_FUN extern __declspec(dllexport)
#  else
#    define GSL_FUN extern __declspec(dllimport)
#  endif
#endif

#include <stddef.h>

#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif

__BEGIN_DECLS

GSL_FUN double gsl_stats_long_double_mean (const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_variance (const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_sd (const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_variance_with_fixed_mean (const long double data[], const size_t stride, const size_t n, const double mean);
GSL_FUN double gsl_stats_long_double_sd_with_fixed_mean (const long double data[], const size_t stride, const size_t n, const double mean);
GSL_FUN double gsl_stats_long_double_tss (const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_tss_m (const long double data[], const size_t stride, const size_t n, const double mean);

GSL_FUN double gsl_stats_long_double_absdev (const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_skew (const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_kurtosis (const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_lag1_autocorrelation (const long double data[], const size_t stride, const size_t n);

GSL_FUN double gsl_stats_long_double_covariance (const long double data1[], const size_t stride1,const long double data2[], const size_t stride2, const size_t n);
GSL_FUN double gsl_stats_long_double_correlation (const long double data1[], const size_t stride1,const long double data2[], const size_t stride2, const size_t n);

GSL_FUN double gsl_stats_long_double_variance_m (const long double data[], const size_t stride, const size_t n, const double mean);
GSL_FUN double gsl_stats_long_double_sd_m (const long double data[], const size_t stride, const size_t n, const double mean);
GSL_FUN double gsl_stats_long_double_absdev_m (const long double data[], const size_t stride, const size_t n, const double mean);
GSL_FUN double gsl_stats_long_double_skew_m_sd (const long double data[], const size_t stride, const size_t n, const double mean, const double sd);
GSL_FUN double gsl_stats_long_double_kurtosis_m_sd (const long double data[], const size_t stride, const size_t n, const double mean, const double sd);
GSL_FUN double gsl_stats_long_double_lag1_autocorrelation_m (const long double data[], const size_t stride, const size_t n, const double mean);

GSL_FUN double gsl_stats_long_double_covariance_m (const long double data1[], const size_t stride1,const long double data2[], const size_t stride2, const size_t n, const double mean1, const double mean2);

/* DEFINED FOR FLOATING POINT TYPES ONLY */

GSL_FUN double gsl_stats_long_double_wmean (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_wvariance (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_wsd (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_wvariance_with_fixed_mean (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double mean);
GSL_FUN double gsl_stats_long_double_wsd_with_fixed_mean (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double mean);
GSL_FUN double gsl_stats_long_double_wtss (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_wtss_m (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean);
GSL_FUN double gsl_stats_long_double_wabsdev (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_wskew (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);
GSL_FUN double gsl_stats_long_double_wkurtosis (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);

GSL_FUN double gsl_stats_long_double_wvariance_m (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean);
GSL_FUN double gsl_stats_long_double_wsd_m (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean);
GSL_FUN double gsl_stats_long_double_wabsdev_m (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean);
GSL_FUN double gsl_stats_long_double_wskew_m_sd (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean, const double wsd);
GSL_FUN double gsl_stats_long_double_wkurtosis_m_sd (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean, const double wsd);

/* END OF FLOATING POINT TYPES */

GSL_FUN double gsl_stats_long_double_pvariance (const long double data1[], const size_t stride1, const size_t n1, const long double data2[], const size_t stride2, const size_t n2);
GSL_FUN double gsl_stats_long_double_ttest (const long double data1[], const size_t stride1, const size_t n1, const long double data2[], const size_t stride2, const size_t n2);

GSL_FUN long double gsl_stats_long_double_max (const long double data[], const size_t stride, const size_t n);
GSL_FUN long double gsl_stats_long_double_min (const long double data[], const size_t stride, const size_t n);
GSL_FUN void gsl_stats_long_double_minmax (long double * min, long double * max, const long double data[], const size_t stride, const size_t n);

GSL_FUN size_t gsl_stats_long_double_max_index (const long double data[], const size_t stride, const size_t n);
GSL_FUN size_t gsl_stats_long_double_min_index (const long double data[], const size_t stride, const size_t n);
GSL_FUN void gsl_stats_long_double_minmax_index (size_t * min_index, size_t * max_index, const long double data[], const size_t stride, const size_t n);

GSL_FUN double gsl_stats_long_double_median_from_sorted_data (const long double sorted_data[], const size_t stride, const size_t n) ;
GSL_FUN double gsl_stats_long_double_quantile_from_sorted_data (const long double sorted_data[], const size_t stride, const size_t n, const double f) ;

__END_DECLS

#endif /* __GSL_STATISTICS_LONG_DOUBLE_H__ */


text:
@protocol LongSettingListViewControllerDelegate <NSObject>

- (void)updateSetting:(id<NSObject>)value
        forSettingKey:(NSString*)settingKey
      reloadTableData:(Boolean)reloadData;

@end


text:
from logging import debug

from gitlabform.configuration.core import ConfigurationCore

class ConfigurationGroups(ConfigurationCore):
    def __init__(self, config_path=None, config_string=None):
        super().__init__(config_path, config_string)

    def get_groups(self) -> list:
        """
        :return: sorted list of groups that are EXPLICITLY defined in the config
        """
        groups = []
        projects_and_groups = self.get("projects_and_groups")
        for element in projects_and_groups.keys():
            if element.endswith("/*"):
                # cut off that "/*"
                group_name = element[:-2]
                groups.append(group_name)
        return sorted(groups)

    def get_effective_config_for_group(self, group) -> dict:
        """
        :param group: "group_name"
        :return: merged configuration for this group, from common, group. Merging is additive.
        """

        common_config = self.get_common_config()
        debug("Common config: %s" % common_config)

        group_config = self.get_group_config(group)
        debug("Group config: %s" % group_config)

        if not group_config and not common_config:
            return {}

        return self.merge_configs(common_config, group_config)

    def get_effective_subgroup_config(self, subgroup):

        #
        # Goes through a subgroups hierarchy, from top to bottom
        #
        # "x/y/x" -> ["x", "x/y", "x/y/z"]
        #
        # ...and for each element after 1st generate effective config from previous effective one merged with current:
        #
        #              |     v       |
        #              \---> a       |
        #                    |       v
        #                    \------>b = effective config to return
        #
        # ..where a = merged_config("x", "x/y") and b = merged_config(a, "x/y/z")
        #

        effective_config = {}
        elements = subgroup.split("/")
        last_element = None
        for element in elements:
            if not last_element:
                effective_config = self.get_group_config(element)
                debug("First level config for '%s': %s" % (element, effective_config))
                last_element = element
            else:
                next_level_subgroup = last_element + "/" + element
                next_level_subgroup_config = self.get_group_config(next_level_subgroup)
                debug(
                    "Config for '%s': %s"
                    % (next_level_subgroup, next_level_subgroup_config)
                )
                effective_config = self.merge_configs(
                    effective_config, next_level_subgroup_config
                )
                debug(
                    "Merged previous level config for '%s' with config for '%s': %s"
                    % (last_element, next_level_subgroup, effective_config)
                )
                last_element = last_element + "/" + element

        return effective_config

class EmptyConfigException(Exception):
    pass


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

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>The Session UserAgent Storage Adapter - Zend Framework Manual</title>

                    The UserAgent Storage Interface

Zend_Http

                        Programmer's Reference Guide

Zend_InfoCard

The Session UserAgent Storage Adapter

Overview

            This storage adapter utilizes
            Zend_Session_Namespace for persisting discovered device
            capabilities for a given user session.

Quick Start

            This particular storage adapter is used by default with
            Zend_Http_UserAgent. As such, you will benefit from it from the
            outset without any real configuration necessary.

            You can alter the behavior slightly, however, by altering the namespace used, and the
            key (or member) in which data is written. You may do so by
            specifying the <var class="varname">browser_type</var> (mapped to namespace) and
            <var class="varname">member</var> options in your configuration.

resources.useragent.storage.adapter = "Session"

resources.useragent.storage.options.browser_type = "all"

resources.useragent.storage.options.member = "data"

            Typically, you will not pass the <var class="varname">browser_type</var> option, and instead let
            this be populated by the value discovered by the UserAgent class.

Configuration Options

Session Storage Options

browser_type

                        Provide this in order to hardcode the session namespace in which you wish to
                        store the User-Agent data. By default, the currently discovered browser type
                        will be used, or, if not provided, the value "Zend_Http_UserAgent".

member

                        This is the specific variable member within the session namespace in which
                        the data will be stored. By default, the value "storage" will be used.

Available Methods

                         __construct
                        (
                            <code_funcparams class="funcparams">$options = null</code_funcparams>
                         )

                        Accepts an array or object containing options. See the configuration options
                            section for details on the <var class="varname">$options</var> variable.

                         isEmpty

                        Used to determine whether or not the storage has been populated yet.

                         read

                        Retrieve previously stored data from the storage adapter.

                         write
                        (
                            <code_funcparams class="funcparams">$contents</code_funcparams>
                         )

                        Write data to the storage adapter for later retrieval.
                        <var class="varname">$contents</var> should be a string containing the serialized
                        UserAgent object.

                         clear

                        Clear the storage of any data.

                    The UserAgent Storage Interface

Zend_Http

                        Programmer's Reference Guide

Zend_InfoCard

Programmer's Reference Guide

Programmer's Reference Guide

Zend Framework Reference

Zend_Http

Einführung

Zend_Http_Client - Fortgeschrittende Nutzung

Zend_Http_Client - Verbindungsadapter

Zend_Http_Cookie und Zend_Http_CookieJar

Zend_Http_Response

Zend_Http_UserAgent

The UserAgent Device Interface

The UserAgent Features Adapter

The WURFL UserAgent Features Adapter

The DeviceAtlas UserAgent Features Adapter

The TeraWurfl UserAgent Features Adapter

The UserAgent Storage Interface

The Session UserAgent Storage Adapter