text:
<?php

namespace JsonWorks\Tests\Constraint\Common;

class NotTest extends \JsonWorks\Tests\Base
{
    public function testData()
    {
        $schema = '{
            "not": {"type": "boolean"}
        }';

        $data = 'value';
        $this->assertTrue($this->validate($schema, $data), 'Valid');

        $data = true;
        $this->assertFalse($this->validate($schema, $data), 'Invalid');
    }
}


text:
package com.github.dannil.httpdownloader.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import com.github.dannil.httpdownloader.model.Download;
import com.github.dannil.httpdownloader.model.User;

/**
 * Interface for DownloadService.
 *
 * @author Daniel Nilsson (daniel.nilsson94 @ outlook.com)
 * @version 1.0.1-SNAPSHOT
 * @since 0.0.1-SNAPSHOT
 */
public interface IDownloadService {

    // Others, defined in DownloadRepository
    Download findById(long downloadId);

    List<Download> findByUser(User user);

    Download save(Download download);

    void delete(Download download);

    void delete(long downloadId);

    // Delegated to DownloadService
    /**
     * Initiate the specified download and save it to the disk.
     *
     * @param download
     *            the download to save
     *
     * @return the saved download
     */
    Download saveToDisk(Download download);

    /**
     * Display a download dialog to the user.
     *
     * @param context
     *            the current servlet context
     * @param response
     *            the response to serve the dialog to
     * @param download
     *            the download to serve
     *
     * @throws IOException
     *             if the download for some reason can't be found
     */
    void serveDownload(ServletContext context, HttpServletResponse response, Download download) throws IOException;

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sis.internal.jaxb.metadata;

import javax.xml.bind.annotation.XmlElementRef;
import org.opengis.metadata.lineage.Processing;
import org.apache.sis.metadata.iso.lineage.DefaultProcessing;
import org.apache.sis.internal.jaxb.gco.PropertyType;

/**
 * JAXB adapter mapping implementing class to the GeoAPI interface. See
 * package documentation for more information about JAXB and interface.
 *
 * @author  Cédric Briançon (Geomatys)
 * @author  Martin Desruisseaux (Geomatys)
 * @version 0.3
 * @since   0.3
 * @module
 */
public final class LE_Processing extends PropertyType<LE_Processing, Processing> {
    /**
     * Empty constructor for JAXB only.
     */
    public LE_Processing() {
    }

    /**
     * Returns the GeoAPI interface which is bound by this adapter.
     * This method is indirectly invoked by the private constructor
     * below, so it shall not depend on the state of this object.
     *
     * @return {@code Processing.class}
     */
    @Override
    protected Class<Processing> getBoundType() {
        return Processing.class;
    }

    /**
     * Constructor for the {@link #wrap} method only.
     */
    private LE_Processing(final Processing metadata) {
        super(metadata);
    }

    /**
     * Invoked by {@link PropertyType} at marshalling time for wrapping the given metadata value
     * in a {@code <gmi:LE_Processing>} XML element.
     *
     * @param  metadata  the metadata element to marshall.
     * @return a {@code PropertyType} wrapping the given the metadata element.
     */
    @Override
    protected LE_Processing wrap(final Processing metadata) {
        return new LE_Processing(metadata);
    }

    /**
     * Invoked by JAXB at marshalling time for getting the actual metadata to write
     * inside the {@code <gmi:LE_Processing>} XML element.
     * This is the value or a copy of the value given in argument to the {@code wrap} method.
     *
     * @return the metadata to be marshalled.
     */
    @XmlElementRef
    public DefaultProcessing getElement() {
        return DefaultProcessing.castOrCopy(metadata);
    }

    /**
     * Invoked by JAXB at unmarshalling time for storing the result temporarily.
     *
     * @param  metadata  the unmarshalled metadata.
     */
    public void setElement(final DefaultProcessing metadata) {
        this.metadata = metadata;
    }
}


text:
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return helper(0, 0, inorder.length-1, preorder, inorder);
    }

    private TreeNode helper(int prestart, int instart, int inend, int[] preorder, int[] inorder) {
        if (prestart>preorder.length-1 || instart>inend) return null;

        int rootval = preorder[prestart];
        TreeNode root = new TreeNode(rootval);
        int inrootidx = -1;
        for(int i=instart; i<=inend; i++) {
            if(inorder[i] == rootval) {
                inrootidx = i;
                break;
            }
        }
        root.left = helper(prestart+1, instart, inrootidx-1, preorder, inorder);
        root.right = helper(prestart+inrootidx-instart+1, inrootidx+1, inend, preorder, inorder);

        return root;
    }
}


text:
namespace SynologyClient
{
    public class AdvancedRights
    {
        public bool disable_download { get; set; }
        public bool disable_list { get; set; }
        public bool disable_modify { get; set; }
    }
}


text:
CREATE TABLE AbstractTimeseries
(
    ID INTEGER NOT NULL,
    PRIMARY KEY (ID)
);

-- --------------------------------------------------------------------
-- AtomicTimeseries
-- --------------------------------------------------------------------
CREATE TABLE AtomicTimeseries
(
    ID INTEGER NOT NULL,
    dynamicDataTVP TEXT,
    dynamicDataDR TEXT,
    observationData TEXT,
    PRIMARY KEY (ID)
);

-- --------------------------------------------------------------------
-- CityObject_dynamizer_ade_ADE
-- --------------------------------------------------------------------
CREATE TABLE CityObject_dynamizer_ade_ADE
(
    ID INTEGER NOT NULL,
    PRIMARY KEY (ID)
);

-- --------------------------------------------------------------------
-- CompositeTimeseries
-- --------------------------------------------------------------------
CREATE TABLE CompositeTimeseries
(
    ID INTEGER NOT NULL,
    PRIMARY KEY (ID)
);

-- --------------------------------------------------------------------
-- Dynamizer
-- --------------------------------------------------------------------
CREATE TABLE Dynamizer
(
    ID INTEGER NOT NULL,
    dynamicData_ID INTEGER,
    linkToSensor_ID INTEGER,
    Dyna_dyna_City_dyna_ade_ADE_ID INTEGER,
    startTime_frame VARCHAR(254),
    startTime_calendarEraName VARCHAR(254),
    startTime_indeterminatePositio VARCHAR(254),
    startTime VARCHAR(254),
    endTime_frame VARCHAR(254),
    endTime_calendarEraName VARCHAR(254),
    endTime_indeterminatePosition VARCHAR(254),
    endTime VARCHAR(254),
    attributeRef VARCHAR(254),
    PRIMARY KEY (ID)
);

-- --------------------------------------------------------------------
-- SensorConnection
-- --------------------------------------------------------------------
CREATE TABLE SensorConnection
(
    ID INTEGER NOT NULL,
    sensorLocation_ID INTEGER,
    sensorID VARCHAR(254),
    serviceType VARCHAR(254),
    linkToObservation VARCHAR(254),
    linkToSensorML VARCHAR(254),
    PRIMARY KEY (ID)
);

-- --------------------------------------------------------------------
-- TimeseriesComponent
-- --------------------------------------------------------------------
CREATE TABLE TimeseriesComponent
(
    ID INTEGER NOT NULL,
    timeseries_ID INTEGER,
    Timeserie_componen_Composit_ID INTEGER,
    repetitions INTEGER,
    additionalGap VARCHAR(254),
    PRIMARY KEY (ID)
);

-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- *********************************  Create foreign keys  ********************************
-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- --------------------------------------------------------------------
-- AtomicTimeseries
-- --------------------------------------------------------------------
ALTER TABLE AtomicTimeseries
    ADD CONSTRAINT AtomicTimeseries_FK FOREIGN KEY (ID) REFERENCES AbstractTimeseries (ID);

-- --------------------------------------------------------------------
-- CompositeTimeseries
-- --------------------------------------------------------------------
ALTER TABLE CompositeTimeseries
    ADD CONSTRAINT CompositeTimeseries_FK FOREIGN KEY (ID) REFERENCES AbstractTimeseries (ID);

-- --------------------------------------------------------------------
-- Dynamizer
-- --------------------------------------------------------------------
ALTER TABLE Dynamizer
    ADD CONSTRAINT Dynamizer_FK FOREIGN KEY (ID) REFERENCES cityobject (ID);

ALTER TABLE Dynamizer
    ADD CONSTRAINT Dynamizer_dynamicData_FK FOREIGN KEY (dynamicData_ID) REFERENCES AbstractTimeseries (ID);

ALTER TABLE Dynamizer
    ADD CONSTRAINT Dynamizer_linkToSensor_FK FOREIGN KEY (linkToSensor_ID) REFERENCES SensorConnection (ID);

ALTER TABLE Dynamizer
    ADD CONSTRAINT Dyna_dyna_City_dyna_ade_ADE_FK FOREIGN KEY (Dyna_dyna_City_dyna_ade_ADE_ID) REFERENCES CityObject_dynamizer_ade_ADE (ID);

-- --------------------------------------------------------------------
-- SensorConnection
-- --------------------------------------------------------------------
ALTER TABLE SensorConnection
    ADD CONSTRAINT SensorConnect_sensorLocatio_FK FOREIGN KEY (sensorLocation_ID) REFERENCES cityobject (ID);

-- --------------------------------------------------------------------
-- TimeseriesComponent
-- --------------------------------------------------------------------
ALTER TABLE TimeseriesComponent
    ADD CONSTRAINT TimeseriesCompon_timeseries_FK FOREIGN KEY (timeseries_ID) REFERENCES AbstractTimeseries (ID);

ALTER TABLE TimeseriesComponent
    ADD CONSTRAINT Timeserie_componen_Composit_FK FOREIGN KEY (Timeserie_componen_Composit_ID) REFERENCES CompositeTimeseries (ID);

-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- *********************************  Create Indexes  *************************************
-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- --------------------------------------------------------------------
-- Dynamizer
-- --------------------------------------------------------------------
CREATE INDEX Dynamizer_dynamicData_FKX ON Dynamizer
    USING btree
    (
      dynamicData_ID ASC NULLS LAST
    )   WITH (FILLFACTOR = 90);

CREATE INDEX Dynamizer_linkToSensor_FKX ON Dynamizer
    USING btree
    (
      linkToSensor_ID ASC NULLS LAST
    )   WITH (FILLFACTOR = 90);

CREATE INDEX Dyna_dyna_City_dyn_ade_ADE_FKX ON Dynamizer
    USING btree
    (
      Dyna_dyna_City_dyna_ade_ADE_ID ASC NULLS LAST
    )   WITH (FILLFACTOR = 90);

-- --------------------------------------------------------------------
-- SensorConnection
-- --------------------------------------------------------------------
CREATE INDEX SensorConnect_sensorLocati_FKX ON SensorConnection
    USING btree
    (
      sensorLocation_ID ASC NULLS LAST
    )   WITH (FILLFACTOR = 90);

-- --------------------------------------------------------------------
-- TimeseriesComponent
-- --------------------------------------------------------------------
CREATE INDEX TimeseriesCompo_timeseries_FKX ON TimeseriesComponent
    USING btree
    (
      timeseries_ID ASC NULLS LAST
    )   WITH (FILLFACTOR = 90);

CREATE INDEX Timeseri_componen_Composit_FKX ON TimeseriesComponent
    USING btree
    (
      Timeserie_componen_Composit_ID ASC NULLS LAST
    )   WITH (FILLFACTOR = 90);

-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- *********************************  Create Sequences  ***********************************
-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


text:
package com.sun.hotspot.igv.hierarchicallayout;

import com.sun.hotspot.igv.layout.Link;
import com.sun.hotspot.igv.layout.Port;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Thomas Wuerthinger
 */
public class ClusterIngoingConnection implements Link {

    private List<Point> controlPoints;
    private ClusterInputSlotNode inputSlotNode;
    private Link connection;
    private Port inputSlot;
    private Port outputSlot;

    public ClusterIngoingConnection(ClusterInputSlotNode inputSlotNode, Link c) {
        this.inputSlotNode = inputSlotNode;
        this.connection = c;
        this.controlPoints = new ArrayList<Point>();

        inputSlot = c.getTo();
        outputSlot = inputSlotNode.getOutputSlot();
    }

    public Link getConnection() {
        return connection;
    }

    public ClusterInputSlotNode getInputSlotNode() {
        return inputSlotNode;
    }

    public Port getTo() {
        return inputSlot;
    }

    public Port getFrom() {
        return outputSlot;
    }

    public void setControlPoints(List<Point> p) {
        this.controlPoints = p;
    }

    public List<Point> getControlPoints() {
        return controlPoints;
    }
}


text: })); // End of all modules


text:
package com.codepath.apps.restclienttemplate.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.codepath.apps.restclienttemplate.helper.TwitterApp;
import com.codepath.apps.restclienttemplate.helper.TwitterClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by praniti on 10/6/17.
 */

public class UserTimelineFragment extends TweetsListFragment {
    TwitterClient client;

    public static UserTimelineFragment newInstance(String screenName) {
        UserTimelineFragment userTimelineFragment = new UserTimelineFragment();
        Bundle args = new Bundle();
        args.putString("screen_name", screenName);
        userTimelineFragment.setArguments(args);
        return userTimelineFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        client = TwitterApp.getRestClient();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    protected void populateTimeline(int count, long maxId) {
        //comes from activity
        String screenName = getArguments().getString("screen_name");
        client.getUserTimeline(count, maxId, screenName, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d("TwitterClient", response.toString());
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                Log.d("TwitterClient", response.toString());

                //iterate through JSON array
                // for each entry, deserialize the JSON object
                addItems(response);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("TwitterClient", responseString);
                throwable.printStackTrace();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                Log.d("TwitterClient", errorResponse.toString());
                throwable.printStackTrace();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                Log.d("TwitterClient", errorResponse.toString());
                throwable.printStackTrace();
            }
        });

    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Lichen chrysophthalmus L.

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
        bootstrap="./Bootstrap.php"
        colors="true"
        stopOnFailure="false"
        syntaxCheck="true"
        >
    <testsuites>
        <testsuite name="Application test suite">
            <directory>./module/Application/src</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">../module/Application/src</directory>
        </whitelist>
        <blacklist>
            <directory>../test</directory>
        </blacklist>
    </filter>
    <logging>
        <log type="coverage-html" target="./coverage-report" charset="UTF-8"
             yui="true" highlight="true" lowUpperBound="50"
             highLowerBound="80"/>
    </logging>
</phpunit>


text:
                Buy Live Insects

                Who We Are

                Reptile-U

                Products

                Contact Us


text:
@implementation QKTestCase

@synthesize query = _query;
@synthesize identifierQuote = _identifierQuote;
@synthesize database = _database;

- (id)initWithInvocation:(NSInvocation *)invocation database:(QKQueryDatabase)database identifierQuote:(NSString *)quote
{
    if ((self = [super initWithInvocation:invocation])) {
		[self setDatabase:database];
		[self setIdentifierQuote:quote];
    }

    return self;
}

- (void)dealloc
{
	if (_query) [_query release], _query = nil;
	if (_identifierQuote) [_identifierQuote release], _identifierQuote = nil;

	[super dealloc];
}

@end


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.06.05 at 08:50:12 PM SAMT
//

package ru.fsrar.wegais.productref_v2;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Справка 1 к ТТН
 *
 *
Java class for InformF1Type complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="InformF1Type">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="RegId" type="{http://fsrar.ru/WEGAIS/Common}NoEmptyString50"/>
 *         <element name="MarkInfo" type="{http://fsrar.ru/WEGAIS/ProductRef_v2}MarkInfoType" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "InformF1Type", propOrder = {
    "regId",
    "markInfo"
})
public class InformF1Type {

    @XmlElement(name = "RegId", required = true)
    protected String regId;
    @XmlElement(name = "MarkInfo")
    protected MarkInfoType markInfo;

    /**
     * Gets the value of the regId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRegId() {
        return regId;
    }

    /**
     * Sets the value of the regId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRegId(String value) {
        this.regId = value;
    }

    /**
     * Gets the value of the markInfo property.
     *
     * @return
     *     possible object is
     *     {@link MarkInfoType }
     *
     */
    public MarkInfoType getMarkInfo() {
        return markInfo;
    }

    /**
     * Sets the value of the markInfo property.
     *
     * @param value
     *     allowed object is
     *     {@link MarkInfoType }
     *
     */
    public void setMarkInfo(MarkInfoType value) {
        this.markInfo = value;
    }

}


text:
MIT 6.033 Computer System Engineering
Hands-on Tracerouter
author: Ma Yesheng
---------------------

This hands-on is mainly about internet routers and measuring round trip times. First and foremost, you should install the utility traceroute.

0. Mesuring Round Trip Time with Ping
  Ping uses the ICMP protocol's mandatory `ECHO_REQUEST` datagram to elicit an ICMP `ECHO_RESPONSE` from a host or gateway.
  First part is round trip times.
  1. Send 10 packets of 56 bytes to following hosts. Indicate what percentage of packets sent resulted in a successful response.
  www.csail.mit.edu: rate 50%, min 500ms, max 512ms, avg 503.4ms
  www.berkeley.edu: rate 80%, min 333ms, max 340ms, avg 335.9ms
  www.unsw.edu.au: rate 100%, min 438ms, max 459ms, avg 450.3ms
  www.kyoto-u.ac.jp: rate 100%, min 251ms, max 286ms, avg 259.8ms
  2. Explain the differences in minimum round trip time to each of these hosts.
  The rtt is somewhat related with the distance between two locations.
  3. Now send pings with 56, 512, 1024, 2056 bytes to www.csail.mit.edu and www.kyoto-u.ac.jp
		|  56 | 512 | 1024 | 2056
  ------|-----|-----|------|------
    mit |426.5|435.5| 428.7| loss
  ------|-----|-----|------|------
   kyoto|261.5|254.9| 261.3| 261.2
  Generally, there is no much difference when package size increases. However, loss rate increses when size increases.
  Second part is unanswered pings.
  4. Send 100 packages of 56 bytes to the following websites and estimate the rate of successful response.
  www.wits.ac.za: no response.
  www.microsoft.com: 100% response.
  Reason for this may be the first website do not support ICMP protocol.

1. Understanding Internet routes using traceroute
  In this part, we will use traceroute which allows you to trace the entire route from your machine to a remote machine. E.g. `traceroute www.google.com`.
  First, Let's do some basic works.
  5. Explain how traceroute discovers a path to a remote host.
  It tracks the route packets from local machine to a given host. It uses TTL field of IP protocol and elicit an `ICMP TIME_EXCEED` response from each gateway to the host.
  Next, we will discuss routine asymmetries. You should be able to find the IP address of your machine using `ifconfig`
  6. Describe output of both directions.
  The routes taken by each direction is not necessarily the same.
  Finally, we will learn something about blackholes.
  7. Try `traceroute 18.31.1.200` and describle what happens to the output.
  It seems that there is no response after several routings.

2016/7/4


text:
package org.slc.sli.ingestion.landingzone.validation;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.slc.sli.ingestion.landingzone.FileEntryDescriptor;
import org.slc.sli.ingestion.landingzone.IngestionFileEntry;
import org.slc.sli.ingestion.validation.ErrorReport;

/**
 * Validates file's checksum using MD5 algorithm.
 *
 * @author okrook
 *
 */
public class ChecksumValidator extends IngestionFileValidator {

    private Logger log = LoggerFactory.getLogger(ChecksumValidator.class);

    @Override
    public boolean isValid(FileEntryDescriptor item, ErrorReport callback) {
        IngestionFileEntry fe = item.getFileItem();

        if (StringUtils.isBlank(fe.getChecksum())) {
            fail(callback, getFailureMessage("SL_ERR_MSG10", fe.getFileName()));

            return false;
        }

        String actualMd5Hex;

        try {
            // and the attributes match
            actualMd5Hex = item.getLandingZone().getMd5Hex(fe.getFile());
        } catch (IOException e) {
            actualMd5Hex = null;
        }

        if (!checksumsMatch(actualMd5Hex, fe.getChecksum())) {

            String[] args = { fe.getFileName(), actualMd5Hex, fe.getChecksum() };
            log.debug("File [{}] checksum ({}) does not match control file checksum ({}).", args);

            fail(callback, getFailureMessage("SL_ERR_MSG2", fe.getFileName()));

            return false;
        }

        return true;
    }

    protected boolean checksumsMatch(String actualMd5Hex, String recordedMd5Hex) {
        return !StringUtils.isBlank(actualMd5Hex) && actualMd5Hex.equalsIgnoreCase(recordedMd5Hex);
    }

}


text:
package org.ovirt.engine.core.common.businessentities;

import java.io.Serializable;

//C# TO JAVA CONVERTER TODO TASK: The interface type was changed to the closest equivalent Java type, but the methods implemented will need adjustment:
public class VmTemplateComparerByDiskSize implements
        java.util.Comparator<VmTemplate>, Serializable {
    private static final long serialVersionUID = -1620249078971769528L;

    @Override
    public int compare(VmTemplate x, VmTemplate y) {
        return Compare(x, y);
    }

    public int Compare(VmTemplate x, VmTemplate y) {
        return (int) (x.getActualDiskSize() - y.getActualDiskSize());
    }

    public VmTemplateComparerByDiskSize() {
    }
}


text:
package com.javarush.test.level13.lesson02.task09;

/* Наследование интерфейса
1. Создать интерфейс Movable с методом speed.
2. Метод speed возвращает значение типа Double и не принимает параметров.
3. Создать и унаследовать интерфейс Runable от интерфейса Movable.
4. Добавить в интерфейс Runable метод speed.
5. Метод speed возвращает значение типа Double и принимает один параметр типа Runable.
*/

public class Solution
{
    public static void main(String[] args) throws Exception
    {
    }
    public interface Movable {
        Double speed();
    }
    public interface Runable extends Movable {
        Double speed(Runable o);
    }
}


text:
static NSString *const DKStoryboardName = @"DKStoryboard";
static NSString *const DKTelpromptProtocol = @"telprompt://";
static NSString *const DKTelProtocol = @"tel://";
static NSString *const DKMailboxEmailKey = @"email";
static NSString *const DKEnabledPredicate = @"enabled = YES";

static NSInteger const DSMailboxesPerPage = 100;

@interface DKSession ()

@property (nonatomic, strong) NSString *contactUsToEmailAddress;
@property (nonatomic) NSOperationQueue *APICallbackQueue;
@property (nonatomic) NSURLSessionDataTask *listMailboxesTask;

@end

@implementation DKSession

+ (void)startWithHostname:(NSString *)hostname
                 APIToken:(NSString *)APIToken
{
    [DKSession sharedInstance];
    [[DKAPIManager sharedInstance] APIClientWithHostname:hostname
                                                APIToken:APIToken];
}

+ (instancetype)sharedInstance
{
    static DKSession *sharedInstance = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedInstance = [[DKSession alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _APICallbackQueue = [NSOperationQueue new];
    }
    return self;
}

+ (BOOL)isSessionStarted
{
    return [DKAPIManager sharedInstance].hasClient;
}

+ (UIStoryboard *)storyboard
{
    return [UIStoryboard storyboardWithName:DKStoryboardName bundle:[NSBundle bundleForClass:[self class]]];
}

+ (DKTopicsViewController *)newTopicsViewController
{
    return [[[self class] storyboard] instantiateViewControllerWithIdentifier:DKTopicsViewControllerId];
}

+ (DKArticlesViewController *)newArticlesViewController
{
    return [[[self class] storyboard] instantiateViewControllerWithIdentifier:DKArticlesViewControllerId];
}

+ (DKSearchResultsViewController *)newSearchResultsViewController
{
    return [[[self class] storyboard] instantiateViewControllerWithIdentifier:DKSearchResultsViewControllerId];
}

#pragma mark - Contact US

+ (UIAlertController *)newContactUsAlertControllerWithCallHandler:(void (^)(UIAlertAction *action))callHandler
                                                     emailHandler:(void (^)(UIAlertAction *action))emailHandler;
{
    UIAlertController *contactUsSheet = [UIAlertController alertControllerWithTitle:DKContactUs
                                                                            message:nil
                                                                     preferredStyle:UIAlertControllerStyleActionSheet];
    [[self class] addCancelButtonWithAlertController:contactUsSheet];
    [[self class] addCallUsButtonWithAlertController:contactUsSheet handler:callHandler];
    [[self class] addEmailUsButtonWithAlertController:contactUsSheet handler:emailHandler];
    return contactUsSheet;
}

+ (void)addCancelButtonWithAlertController:(UIAlertController *)controller
{
    [controller addAction:[UIAlertAction actionWithTitle:DKCancel
                                                   style:UIAlertActionStyleCancel
                                                 handler:nil]];
}

+ (void)addCallUsButtonWithAlertController:(UIAlertController *)controller handler:(void (^)(UIAlertAction *action))handler
{
    if ([DKSession sharedInstance].contactUsPhoneNumberURL) {
        [[self class] addCallUsActionWithAlertController:controller handler:handler];
    }
}

+ (UIAlertAction *)addCallUsActionWithAlertController:(UIAlertController *)controller handler:(void (^)(UIAlertAction *action))handler;
{
    UIAlertAction *callUsAction = [UIAlertAction actionWithTitle:DKCallUs
                                                           style:UIAlertActionStyleDefault
                                                         handler:handler];
    [controller addAction:callUsAction];
    return callUsAction;
}

+ (void)addEmailUsButtonWithAlertController:(UIAlertController *)controller handler:(void (^)(UIAlertAction *action))handler
{
    UIAlertAction *emailUsAction = [[self class] addEmailUsActionWithAlertController:controller handler:handler];
    emailUsAction.enabled = NO;
    [[DKSession sharedInstance] hasContactUsToEmailAddressWithCompletionHandler:^(BOOL hasContactUsToEmailAddress) {
        emailUsAction.enabled = hasContactUsToEmailAddress;
    }];
}

+ (UIAlertAction *)addEmailUsActionWithAlertController:(UIAlertController *)controller handler:(void (^)(UIAlertAction *action))handler
{
    UIAlertAction *emailUsAction = [UIAlertAction actionWithTitle:DKEmailUs
                                                            style:UIAlertActionStyleDefault
                                                          handler:handler];
    [controller addAction:emailUsAction];
    return emailUsAction;
}

- (DKContactUsViewController *)newContactUsViewController
{
    DKSettings *settings = [DKSettings sharedInstance];
    DKContactUsViewController *vc = [[[self class] storyboard] instantiateViewControllerWithIdentifier:DKContactUsViewControllerId];

    vc.showSubjectItem = settings.contactUsShowSubjectItem;
    vc.showAllOptionalItems = settings.contactUsShowAllOptionalItems;
    vc.showYourNameItem = settings.contactUsShowYourNameItem;
    vc.showYourEmailItem = settings.contactUsShowYourEmailItem;

    if (settings.hasContactUsSubject) {
        vc.subject = settings.contactUsSubject;
    }
    if (settings.hasContactUsStaticCustomFields) {
        vc.customFields = settings.contactUsStaticCustomFields;
    }

    return vc;
}

+ (DKArticleDetailViewController *)newArticleDetailViewController
{
    return [[[self class] storyboard] instantiateViewControllerWithIdentifier:DKArticleDetailViewControllerId];
}

#pragma mark - Phone

- (NSURL *)contactUsPhoneNumberURL
{
    if (![[self class] hasContactUsPhoneNumber]) {
        return nil;
    } else {
        NSURL *URL = [NSURL URLWithString:[DKTelpromptProtocol stringByAppendingString:[DKSettings sharedInstance].contactUsPhoneNumber]];
        // Add a check to ensure that the telprompt url can be opened. See this link for more info:
        // http://stackoverflow.com/questions/20072123/telprompt-vs-tel-and-app-approval
        BOOL canOpenURL = [[UIApplication sharedApplication] canOpenURL:URL];
        if (canOpenURL) {
            return URL;
        }
        URL = [NSURL URLWithString:[DKTelProtocol stringByAppendingString:[DKSettings sharedInstance].contactUsPhoneNumber]];
        canOpenURL = [[UIApplication sharedApplication] canOpenURL:URL];
        if (canOpenURL) {
            return URL;
        }
        return nil;
    }
}

+ (BOOL)hasContactUsPhoneNumber
{
    return [DKSettings sharedInstance].hasContactUsPhoneNumber;
}

#pragma mark - Email

- (void)fetchInboundMailboxesWithCompletionHandler:(void (^)(void))completionHandler
{
    [self.listMailboxesTask cancel];
    self.listMailboxesTask = [DSAPIMailbox listMailboxesOfType:DSAPIMailboxTypeInbound
                                                    parameters:@{ kPageKey : @1,
                                                                  kPerPageKey : @(DSMailboxesPerPage) }
                                                        client:[DKAPIManager sharedInstance].client
                                                         queue:self.APICallbackQueue
                                                       success:^(DSAPIPage *page) {
                                                           if ([page.totalEntries integerValue]) {
                                                               self.contactUsToEmailAddress = [self firstEnabledInboundEmailAddressFromPage:page];
                                                           }
                                                           if (completionHandler) {
                                                               dispatch_sync(dispatch_get_main_queue(), ^{
                                                                   completionHandler();
                                                               });
                                                           }
                                                       }
                                                       failure:^(NSHTTPURLResponse *response, NSError *error) {
                                                           if (completionHandler) {
                                                               dispatch_sync(dispatch_get_main_queue(), ^{
                                                                   completionHandler();
                                                               });
                                                           }
                                                       }];
}

- (void)hasContactUsToEmailAddressWithCompletionHandler:(void (^ __nonnull)(BOOL hasContactUsToEmailAddress))completionHandler
{
    if ([DKSettings sharedInstance].hasContactUsToEmailAddress) {
        self.contactUsToEmailAddress = [DKSettings sharedInstance].contactUsToEmailAddress;
    }

    if (self.contactUsToEmailAddress.length > 0) {
        completionHandler(YES);
    } else {
        [self fetchInboundMailboxesWithCompletionHandler:^{
            self.contactUsToEmailAddress.length > 0 ? completionHandler(YES) : completionHandler(NO);
        }];
    }
}

- (DSAPIMailbox *)firstEnabledInboundMailboxFromPage:(DSAPIPage *)page
{
    NSPredicate *enabledPredicate = [NSPredicate predicateWithFormat:DKEnabledPredicate];
    NSArray *enabledMailboxes = [page.entries filteredArrayUsingPredicate:enabledPredicate];
    return enabledMailboxes.firstObject;
}

- (NSString *)firstEnabledInboundEmailAddressFromPage:(DSAPIPage *)page
{
    return [[self firstEnabledInboundMailboxFromPage:page] valueForKey:DKMailboxEmailKey];
}

@end


text:
var Promise = require('bluebird');
var methodMap = {
  POST: 'create',
  GET: 'read',
  PUT: 'update',
  DELETE: 'delete'
};

var findRecords = require('sails/lib/hooks/blueprints/actions/find');
var wlFilter = require('waterline-criteria');

module.exports = {

  /**
   * Given an object, or a list of objects, return true if the list contains
   * objects not owned by the specified user.
   */
  hasForeignObjects: function(objects, user) {
    if (!_.isArray(objects)) {
      return PermissionService.isForeignObject(user.id)(objects);
    }
    return _.any(objects, PermissionService.isForeignObject(user.id));
  },

  /**
   * Return whether the specified object is NOT owned by the specified user.
   */
  isForeignObject: function(owner) {
    return function(object) {
      //sails.log.verbose('object', object);
      //sails.log.verbose('object.owner: ', object.owner, ', owner:', owner);
      return object.owner !== owner;
    };
  },

  /**
   * Find objects that some arbitrary action would be performed on, given the
   * same request.
   *
   * @param options.model
   * @param options.query
   *
   * TODO this will be less expensive when waterline supports a caching layer
   */
  findTargetObjects: function(req) {

    // handle add/remove routes that have :parentid as the primary key field
    var originalId;
    if (req.params.parentid) {
      originalId = req.params.id;
      req.params.id = req.params.parentid;
    }

    return new Promise(function(resolve, reject) {
        findRecords(req, {
          ok: resolve,
          serverError: reject,
          // this isn't perfect, since it returns a 500 error instead of a 404 error
          // but it is better than crashing the app when a record doesn't exist
          notFound: reject
        });
      })
      .then(function(result) {
        if (originalId !== undefined) {
          req.params.id = originalId;
        }
        return result;
      });
  },

  /**
   * Query Permissions that grant privileges to a role/user on an action for a
   * model.
   *
   * @param options.method
   * @param options.model
   * @param options.user
   */
  findModelPermissions: function(options) {
    var action = PermissionService.getMethod(options.method);
    var permissionCriteria = {
      model: options.model.id,
      action: action
    };

    return User.findOne(options.user.id)
      .populate('roles')
      .then(function(user) {
        return Permission.find({
          model: options.model.id,
          action: action,
          or: [{
            user: user.id
          }, {
            role: _.pluck(user.roles, 'id')
          }]
        }).populate('criteria');
      });
  },

  /**
   * Given a list of objects, determine if they all satisfy at least one permission's
   * where clause/attribute blacklist combination
   *
   * @param {Array of objects} objects - The result of the query, or if the action is create,
   * the body of the object to be created
   * @param {Array of Permission objects} permissions - An array of permission objects
   * that are relevant to this particular user query
   * @param {Object} attributes - The body of the request, in an update or create request.
   * The keys of this object are checked against the permissions blacklist
   * @returns boolean - True if there is at least one granted permission that allows the requested action,
   * otherwise false
   */
  hasPassingCriteria: function(objects, permissions, attributes, user) {
    // return success if there are no permissions or objects
    if (_.isEmpty(permissions) || _.isEmpty(objects)) return true;

    if (!_.isArray(objects)) {
      objects = [objects];
    }

    var criteria = permissions.reduce(function (memo, perm) {
      if (perm) {
        if (!perm.criteria || perm.criteria.length==0) {
          // If a permission has no criteria then it passes for all cases
          // (like the admin role)
          memo = memo.concat([{where:{}}]);
        }
        else {
            memo = memo.concat(perm.criteria);
        }
        if (perm.relation === 'owner') {
            perm.criteria.forEach(function (criteria) {
                criteria.owner = true;
            });
        }
        return memo;
      }
    }, []);

    if (!_.isArray(criteria)) {
      criteria = [criteria];
    }

    if (_.isEmpty(criteria)) {
      return true;
    }

    // every object must have at least one permission that has a passing criteria and a passing attribute check
    return objects.every(function(obj) {
      return criteria.some(function(criteria) {
        var match = wlFilter([obj], {
          where: criteria.where
        }).results;
        var hasUnpermittedAttributes = PermissionService.hasUnpermittedAttributes(attributes, criteria.blacklist);
        var hasOwnership = true; // edge case for scenario where a user has some permissions that are owner based and some that are role based
        if (criteria.owner) {
          hasOwnership = !PermissionService.isForeignObject(user)(obj);
        }
        return match.length === 1 && !hasUnpermittedAttributes && hasOwnership;
      });
    });

  },

  hasUnpermittedAttributes: function(attributes, blacklist) {
    if (_.isEmpty(attributes) || _.isEmpty(blacklist)) {
      return false;
    }
    return _.intersection(Object.keys(attributes), blacklist).length ? true : false;
  },

  /**
   * Return true if the specified model supports the ownership policy; false
   * otherwise.
   */
  hasOwnershipPolicy: function(model) {
    return model.autoCreatedBy;
  },

  /**
   * Build an error message
   */
  getErrorMessage: function(options) {
    return [
      'User', options.user.email, 'is not permitted to', options.method, options.model.globalId
    ].join(' ');
  },

  /**
   * Given an action, return the CRUD method it maps to.
   */
  getMethod: function(method) {
    return methodMap[method];
  },

  /**
   * create a new role
   * @param options
   * @param options.name {string} - role name
   * @param options.permissions {permission object, or array of permissions objects}
   * @param options.permissions.model {string} - the name of the model that the permission is associated with
   * @param options.permissions.criteria - optional criteria object
   * @param options.permissions.criteria.where - optional waterline query syntax object for specifying permissions
   * @param options.permissions.criteria.blacklist {string array} - optional attribute blacklist
   * @param options.users {array of user names} - optional array of user ids that have this role
   */
  createRole: function(options) {

    var ok = Promise.resolve();
    var permissions = options.permissions;

    if (!_.isArray(permissions)) {
      permissions = [permissions];
    }

    // look up the model id based on the model name for each permission, and change it to an id
    ok = ok.then(function() {
      return Promise.map(permissions, function(permission) {
        return Model.findOne({
            name: permission.model
          })
          .then(function(model) {
            permission.model = model.id;
            return permission;
          });
      });
    });

    // look up user ids based on usernames, and replace the names with ids
    ok = ok.then(function(permissions) {
      if (options.users) {
        return User.find({
            username: options.users
          })
          .then(function(users) {
            options.users = users;
          });
      }
    });

    ok = ok.then(function(users) {
      return Role.create(options);
    });

    return ok;
  },

  /**
   *
   * @param options {permission object, or array of permissions objects}
   * @param options.role {string} - the role name that the permission is associated with,
   *                                either this or user should be supplied, but not both
   * @param options.user {string} - the user than that the permission is associated with,
   *                                either this or role should be supplied, but not both
   * @param options.model {string} - the model name that the permission is associated with
   * @param options.action {string} - the http action that the permission allows
   * @param options.criteria - optional criteria object
   * @param options.criteria.where - optional waterline query syntax object for specifying permissions
   * @param options.criteria.blacklist {string array} - optional attribute blacklist
   */
  grant: function(permissions) {
    if (!_.isArray(permissions)) {
      permissions = [permissions];
    }

    // look up the models based on name, and replace them with ids
    var ok = Promise.map(permissions, function(permission) {
      var findRole = permission.role ? Role.findOne({
        name: permission.role
      }) : null;
      var findUser = permission.user ? User.findOne({
        username: permission.user
      }) : null;
      return Promise.all([findRole, findUser, Model.findOne({
          name: permission.model
        })])
        .spread(function(role, user, model) {
          permission.model = model.id;
          if (role && role.id) {
            permission.role = role.id;
          } else if (user && user.id) {
            permission.user = user.id;
          } else {
            return Promise.reject(new Error('no role or user specified'));
          }
        });
    });

    ok = ok.then(function() {
      return Permission.create(permissions);
    });

    return ok;
  },

  /**
   * add one or more users to a particular role
   * TODO should this work with multiple roles?
   * @param usernames {string or string array} - list of names of users
   * @param rolename {string} - the name of the role that the users should be added to
   */
  addUsersToRole: function(usernames, rolename) {
    if (_.isEmpty(usernames)) {
      return Promise.reject(new Error('One or more usernames must be provided'));
    }

    if (!_.isArray(usernames)) {
      usernames = [usernames];
    }

    return Role.findOne({
      name: rolename
    }).populate('users').then(function(role) {
      return User.find({
        username: usernames
      }).then(function(users) {
        role.users.add(_.pluck(users, 'id'));
        return role.save();
      });
    });
  },

  /**
   * remove one or more users from a particular role
   * TODO should this work with multiple roles
   * @params usernames {string or string array} - name or list of names of users
   * @params rolename {string} - the name of the role that the users should be removed from
   */
  removeUsersFromRole: function(usernames, rolename) {
    if (_.isEmpty(usernames)) {
      return Promise.reject(new Error('One or more usernames must be provided'));
    }

    if (!_.isArray(usernames)) {
      usernames = [usernames];
    }

    return Role.findOne({
        name: rolename
      })
      .populate('users')
      .then(function(role) {
        return User.find({
          username: usernames
        }, {
          select: ['id']
        }).then(function(users) {
          users.map(function(users) {
            role.users.remove(user.id);
          });
          return role.save();
        });
      });
  },

  /**
   * revoke permission from role
   * @param options
   * @param options.role {string} - the name of the role related to the permission.  This, or options.user should be set, but not both.
   * @param options.user {string} - the name of the user related to the permission.  This, or options.role should be set, but not both.
   * @param options.model {string} - the name of the model for the permission
   * @param options.action {string} - the name of the action for the permission
   * @param options.relation {string} - the type of the relation (owner or role)
   */
  revoke: function(options) {
    var findRole = options.role ? Role.findOne({
      name: options.role
    }) : null;
    var findUser = options.user ? User.findOne({
      username: options.user
    }) : null;
    var ok = Promise.all([findRole, findUser, Model.findOne({
      name: options.model
    })]);

    ok = ok.spread(function(role, user, model) {

      var query = {
        model: model.id,
        action: options.action,
        relation: options.relation
      };

      if (role && role.id) {
        query.role = role.id;
      } else if (user && user.id) {
        query.user = user.id;
      } else {
        return Promise.reject(new Error('You must provide either a user or role to revoke the permission from'));
      }

      return Permission.destroy(query);
    });

    return ok;
  },

  /**
   * Check if the user (out of role) is granted to perform action on given objects
   * @param objects
   * @param user
   * @param action
   * @param model
   * @param body
   * @returns {*}
   */
  isAllowedToPerformAction: function(objects, user, action, model, body) {
    if (!_.isArray(objects)) {
      return PermissionService.isAllowedToPerformSingle(user.id, action, model, body)(objects);
    }
    return new Promise.map(objects, PermissionService.isAllowedToPerformSingle(user.id, action, model, body))
        .then(function (allowedArray) {
            return allowedArray.every(function (allowed) {
                return allowed === true;
            });
        });
  },

  /**
   * Resolve if the user have the permission to perform this action
   * @param user
   * @param action
   * @param model
   * @param body
   * @returns {Function}
   */
  isAllowedToPerformSingle: function(user, action, model, body) {
    return function(obj) {
      return new Promise(function(resolve, reject) {
        Model.findOne({
          identity: model
        }).then(function(model) {
         return Permission.find({
            model: model.id,
            action: action,
            relation: 'user',
            user: user
          }).populate('criteria');
        }).then(function(permission) {
          if (permission.length > 0 && PermissionService.hasPassingCriteria(obj, permission, body)) {
            resolve(true);
          } else {
            resolve(false);
          }
        }).catch(reject);
      });
    };
  }
};


text:
/*--------------------------- Package Declaration ----------------------------*/

package com.github.jessemull.microflex.bigdecimalflex.io;

/*------------------------------- Dependencies -------------------------------*/

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.github.jessemull.microflex.bigdecimalflex.plate.WellBigDecimal;

/**
 * This is a wrapper class used to marshal/unmarshal an XML encoded well object.
 *
 * @author Jesse L. Mull
 * @update Updated Oct 17, 2016
 * @address http://www.jessemull.com
 * @email hello@jessemull.com
 */
@XmlRootElement
@XmlType (propOrder={"type", "index", "size", "values"})
public class WellXMLBigDecimal {

	/*---------------------------- Private Fields ----------------------------*/

    private String type;            // Data set numerical type
    private String index;           // The well index
    private int size;               // Size of the data set
    private BigDecimal[] values;    // Array holding the well values

    /*------------------------------ Constructors ----------------------------*/

    public WellXMLBigDecimal(){}

    /**
     * Creates a well XML object from a well integer object.
     * @param    WellBigDecimal    the well object
     */
    public WellXMLBigDecimal(WellBigDecimal well) {
        this.index = well.index();
        this.size = well.size();
        this.values = well.data().toArray(new BigDecimal[well.size()]);
        this.type = well.typeString();
    }

    /**
     * Creates a well XML object from a well integer object.
     * @param    WellBigDecimal    the well object
     */
    public WellXMLBigDecimal(String index, int size, BigDecimal[] values, String type) {
        this.index = index;
        this.size = size;
        this.values = values;
        this.type = type;;
    }

    /*-------------------------- Getters and setters -------------------------*/

    /**
     * Sets the index.
     * @param    String    the new index
     */
    @XmlElement
    public void setIndex(String newIndex) {
        this.index = newIndex;
    }

    /**
     * Sets the values array.
     * @param    int[]    the values array
     */
    @XmlElement(name="value")
    @XmlElementWrapper(name="values")
    public void setValues(BigDecimal[] newValues) {
        this.values = newValues;
    }

    /**
     * Sets the type.
     * @param   String    the numerical type
     */
    @XmlElement
    public void setType(String type) {
        this.type = type;
    }

    /**
     * Sets the size.
     * @param   String    the numerical type
     */
    @XmlElement
    public void setSize(int size) {
        this.size = size;
    }

    /**
     * Returns the index.
     * @return    the index
     */
    public String getIndex() {
        return this.index;
    }

    /**
     * Returns the values array.
     * @return    the array of values
     */
    public BigDecimal[] getValues() {
        return this.values;
    }

    /**
     * Returns the numerical type as a string.
     * @return    the numerical type
     */
    public String getType() {
        return this.type;
    }

    /**
     * Returns the size of the values array.
     * @return    the size of the values array
     */
    public int getSize() {
        return this.size;
    }

    /**
     * Returns a WellBigDecimal object.
     * @return    the well
     */
    public WellBigDecimal toWellObject() {
        return new WellBigDecimal(index, values);
    }
}


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/action_save_tags"
            app:showAsAction="always"
            android:icon="@drawable/ic_done"
            android:title="@string/action_save_tags"/>
</menu>


text:
from math import factorial

def ans():
    return sum(int(x) for x in str(factorial(100)))

if __name__ == '__main__':
    print(ans())


text: Programming problems.


text:
package edu.iu.grid.oim.model.db;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.db.record.MeshConfigGroupRecord;
import edu.iu.grid.oim.model.db.record.MeshConfigOIMMemberRecord;
import edu.iu.grid.oim.model.db.record.RecordBase;
import edu.iu.grid.oim.model.db.record.ResourceRecord;
import edu.iu.grid.oim.model.db.record.ServiceRecord;

public class MeshConfigOIMMemberModel extends SmallTableModelBase<MeshConfigOIMMemberRecord>
{
    static Logger log = Logger.getLogger(MeshConfigOIMMemberModel.class);

    public MeshConfigOIMMemberModel(UserContext context)
    {
    	super(context, "mesh_config_oim_member");
    }
    MeshConfigOIMMemberRecord createRecord() throws SQLException
	{
		return new MeshConfigOIMMemberRecord();
	}
    public String getName()
    {
    	return "Mesh Config OIM Group Members";
    }
	public String getHumanValue(String field_name, String value) throws NumberFormatException, SQLException
	{
		if(field_name.equals("group_id")) {
			MeshConfigGroupModel model = new MeshConfigGroupModel(context);
			MeshConfigGroupRecord rec = model.get(Integer.parseInt(value));
			return value + " (" + rec.name + ")";
		}
		if(field_name.equals("resource_id")) {
			ResourceModel model = new ResourceModel(context);
			ResourceRecord rec = model.get(Integer.parseInt(value));
			return value + " (" + rec.name + ")";
		}
		if(field_name.equals("service_id")) {
			ServiceModel model = new ServiceModel(context);
			ServiceRecord rec = model.get(Integer.parseInt(value));
			return value + " (" + rec.name + ")";
		}
		return value;
	}
	/*
	public MeshConfigMemberRecord get(int id) throws SQLException {
		MeshConfigMemberRecord keyrec = new MeshConfigMemberRecord();
		keyrec.id = id;
		return get(keyrec);
	}
	*/
	public Boolean hasLogAccess(XPath xpath, Document doc) throws XPathExpressionException
	{
		if(auth.allows("admin_meshconig")) {
			return true;
		}
		return false;
	}
	/*
	public boolean canEdit(int meshconfig_id)
	{
		if(auth.allows("admin")) return true;
		if(auth.allows("admin_meshconfig")) return true;
		return false;
	}
	*/
	public ArrayList<MeshConfigOIMMemberRecord> getAll() throws SQLException
	{
		ArrayList<MeshConfigOIMMemberRecord> list = new ArrayList<MeshConfigOIMMemberRecord>();
		for(RecordBase it : getCache()) {
			list.add((MeshConfigOIMMemberRecord)it);
		}
		return list;
	}
	public ArrayList<MeshConfigOIMMemberRecord> getByGroupID(Integer id) throws SQLException {
		ArrayList<MeshConfigOIMMemberRecord> list = new ArrayList<MeshConfigOIMMemberRecord>();
		for(RecordBase it : getCache()) {
			MeshConfigOIMMemberRecord rec = (MeshConfigOIMMemberRecord)it;
			if(rec.group_id.equals(id)) {
				list.add(rec);
			}
		}
		return list;
	}
}


text:
module Mogli
  class Page < Profile
    set_search_type

    define_properties :id, :name, :category, :username, :access_token, :namespace

    # General
    define_properties :likes, :link, :picture, :has_added_app, :website, :description, :can_post, :checkins, :general_info

    # Retail
    define_properties :founded, :products, :mission, :company_overview

    # Musicians
    define_properties :record_label, :hometown, :band_members, :genre

    # Restaurants
    define_properties :parking, :public_transit, :hours, :payment_options, :restaurant_services, :restaurant_specialties

    # As a like
    define_properties :created_time

    def client_for_page
      if access_token.nil? || access_token.empty?
        raise MissingAccessToken.new("You can only get a client for this page if an access_token has been provided. i.e. via /me/accounts")
      end
      Client.new(access_token)
    end

    def self.recognize?(hash)
      hash.has_key?("category")
    end

    class MissingAccessToken < StandardError
    end

  end

end


text:
import datetime
import os

import bpy
import bpy_extras
from bpy.app.handlers import persistent

import appleseed as asr
from . import path_util, osl_utils
from ..logger import get_logger
from ..properties.nodes import AppleseedOSLScriptNode

logger = get_logger()

image_extensions = ('jpg', 'png', 'tif', 'exr', 'bmp',
                    'tga', 'hdr', 'dpx', 'psd', 'gif', 'jp2')

def safe_register_class(cls):
    try:
        logger.debug("[appleseed] Registering class {0}...".format(cls))
        bpy.utils.register_class(cls)
    except Exception as e:
        logger.error("[appleseed] ERROR: Failed to register class {0}: {1}".format(cls, e))

def safe_unregister_class(cls):
    try:
        logger.debug("[appleseed] Unregistering class {0}...".format(cls))
        bpy.utils.unregister_class(cls)
    except Exception as e:
        logger.error("[appleseed] ERROR: Failed to unregister class {0}: {1}".format(cls, e))

# ------------------------------------
# Generic utilities and settings.
# ------------------------------------

def clamp_value(n, smallest, largest):
    return max(smallest, min(n, largest))

def filter_params(params):
    filter_list = list()
    for p in params:
        if p not in filter_list:
            filter_list.append(p)

    return filter_list

def realpath(path):
    """Resolve a relative Blender path to a real filesystem path"""

    if path.startswith('//'):
        path = bpy.path.abspath(path)
    else:
        path = os.path.realpath(path)

    path = path.replace('\\', '/')
    path = os.path.realpath(path)

    return path

def appleseed_popup_info(message="", title="appleseed Info", icon='INFO'):

    def draw(self, context):
        self.layout.label(text=message)

    bpy.context.window_manager.popup_menu(draw, title=title, icon=icon)

@persistent
def update_project(_):
    """
    This function automatically runs when a .blend file is opened.
    :param _:
    :return:
    """

    # Compile all OSL Script nodes
    stdosl_path = path_util.get_stdosl_paths()
    compiler = asr.ShaderCompiler(stdosl_path)
    q = asr.ShaderQuery()
    for script in bpy.data.texts:
        osl_bytecode = osl_utils.compile_osl_bytecode(compiler,
                                                      script)
        if osl_bytecode is not None:
            q.open_bytecode(osl_bytecode)

            node_data = osl_utils.parse_shader(q)

            node_name, node_category, node_classes = osl_utils.generate_node(node_data,
                                                                             AppleseedOSLScriptNode)

            for cls in node_classes:
                safe_register_class(cls)

        else:
            logger.debug(f"appleseed: Shader {script.name} did not compile")

# ------------------------------------
# Scene export utilities.
# ------------------------------------

def get_render_resolution(scene):
    scale = scene.render.resolution_percentage / 100.0
    width = int(scene.render.resolution_x * scale)
    height = int(scene.render.resolution_y * scale)
    return width, height

def calc_film_aspect_ratio(scene):
    render = scene.render
    scale = render.resolution_percentage / 100.0
    width = int(render.resolution_x * scale)
    height = int(render.resolution_y * scale)
    xratio = width * render.pixel_aspect_x
    yratio = height * render.pixel_aspect_y
    return xratio / yratio

def calc_film_dimensions(aspect_ratio, camera, zoom):
    """
    Fit types:
    Horizontal = Horizontal size manually set.  Vertical size derived from aspect ratio.

    Vertical = Vertical size manually set.  Horizontal size derived from aspect ratio.

    Auto = sensor_width bpy property sets the horizontal size when the aspect ratio is over 1 and
    the vertical size when it is below 1.  Other dimension is derived from aspect ratio.

    Much thanks to the Radeon ProRender plugin for clarifying this behavior
    :param aspect_ratio:
    :param camera:
    :param zoom:
    :return:
    """

    horizontal_fit = camera.sensor_fit == 'HORIZONTAL' or \
                     (camera.sensor_fit == 'AUTO' and aspect_ratio > 1)

    if camera.sensor_fit == 'VERTICAL':
        film_height = camera.sensor_height / 1000 * zoom
        film_width = film_height * aspect_ratio
    elif horizontal_fit:
        film_width = camera.sensor_width / 1000 * zoom
        film_height = film_width / aspect_ratio
    else:
        film_height = camera.sensor_width / 1000 * zoom
        film_width = film_height * aspect_ratio

    return film_width, film_height

def find_autofocus_point(scene):
    cam = scene.camera
    co = scene.cursor_location
    co_2d = bpy_extras.object_utils.world_to_camera_view(scene,
                                                         cam,
                                                         co)
    y = 1 - co_2d.y

    return co_2d.x, y

def get_focal_distance(camera):
    if camera.data.dof.focus_object is not None:
        cam_location = camera.matrix_world.to_translation()
        cam_target_location = bpy.data.objects[camera.data.dof.focus_object.name].matrix_world.to_translation()
        focal_distance = (cam_target_location - cam_location).magnitude
    else:
        focal_distance = camera.data.dof.focus_distance

    return focal_distance

# ------------------------------------
# Object / instance utilities.
# ------------------------------------

def is_object_deforming(ob):
    deforming_mods = {'ARMATURE', 'MESH_SEQUENCE_CACHE', 'CAST', 'CLOTH', 'CURVE', 'DISPLACE',
                      'HOOK', 'LATTICE', 'MESH_DEFORM', 'SHRINKWRAP', 'EXPLODE',
                      'SIMPLE_DEFORM', 'SMOOTH', 'WAVE', 'SOFT_BODY',
                      'SURFACE', 'MESH_CACHE', 'FLUID_SIMULATION',
                      'DYNAMIC_PAINT'}
    if ob.modifiers:
        for mod in ob.modifiers:
            if mod.type in deforming_mods:
                return True

    if ob.data and hasattr(ob.data, 'shape_keys') and ob.data.shape_keys:
        return True

    return False

# ------------------------------------
# Simple timer for profiling.
# ------------------------------------

class Timer(object):
    """
    Simple timer for profiling operations.
    """

    def __init__(self):
        self.start()

    def start(self):
        self.__start = datetime.datetime.now()

    def stop(self):
        self.__end = datetime.datetime.now()

    def elapsed(self):
        delta = self.__end - self.__start
        return delta.total_seconds()

# ------------------------------------
# Blender addon.
# ------------------------------------

def register():
    pass

def unregister():
    pass


text:
package org.zaproxy.zap.view;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import org.jdesktop.swingx.JXTable;
import org.parosproxy.paros.Constant;

/**
 * @author yhawke (2014)
 * @param <E> the type of the options
 */
public abstract class AbstractMultipleOptionsBaseTablePanel<E> extends MultipleOptionsTablePanel {

    protected static final long serialVersionUID = -7609757285865562636L;

    protected static final String ADD_BUTTON_LABEL =
            Constant.messages.getString("multiple.options.panel.add.button.label");
    protected static final String MODIFY_BUTTON_LABEL =
            Constant.messages.getString("multiple.options.panel.modify.button.label");
    protected static final String REMOVE_BUTTON_LABEL =
            Constant.messages.getString("multiple.options.panel.remove.button.label");
    protected static final String REMOVE_WO_CONFIRMATION_CHECKBOX_LABEL =
            Constant.messages.getString(
                    "multiple.options.panel.removeWithoutConfirmation.checkbox.label");

    protected JButton addButton;
    protected JButton modifyButton;
    protected JButton removeButton;

    protected AbstractMultipleOptionsBaseTableModel<E> model;
    protected GridBagConstraints gbcFooterPanel;
    protected JCheckBox removeWithoutConfirmationCheckBox;

    public AbstractMultipleOptionsBaseTablePanel(AbstractMultipleOptionsBaseTableModel<E> model) {
        this(model, true);
    }

    protected AbstractMultipleOptionsBaseTablePanel(
            AbstractMultipleOptionsBaseTableModel<E> model, boolean allowModification) {
        super(model);

        getFooterPanel().setLayout(new GridBagLayout());

        gbcFooterPanel = new GridBagConstraints();
        gbcFooterPanel.gridx = 0;
        gbcFooterPanel.weightx = 1.0D;
        gbcFooterPanel.weighty = 1.0D;
        gbcFooterPanel.anchor = GridBagConstraints.LINE_START;

        addFooterPanelComponent(getRemoveWithoutConfirmationCheckBox());

        this.model = model;

        addButton = new JButton(ADD_BUTTON_LABEL);
        addButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        E e = showAddDialogue();

                        if (e != null) {
                            getMultipleOptionsModel().addElement(e);
                        }
                    }
                });

        if (allowModification) {
            modifyButton = new JButton(MODIFY_BUTTON_LABEL);
            modifyButton.setEnabled(false);
            modifyButton.addActionListener(
                    new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent evt) {
                            modifyElement(getSelectedRow());
                        }
                    });
        }

        removeButton = new JButton(REMOVE_BUTTON_LABEL);
        removeButton.setEnabled(false);
        removeButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        int row = getSelectedRow();

                        if (!isRemoveWithoutConfirmation()) {
                            if (!showRemoveDialogue(getMultipleOptionsModel().getElement(row))) {
                                return;
                            }
                        }

                        getMultipleOptionsModel().removeElement(row);
                    }
                });

        addButton(addButton);
        if (allowModification) {
            addButton(modifyButton);
        }
        addButton(removeButton);

        getTable()
                .getSelectionModel()
                .addListSelectionListener(
                        new ListSelectionListener() {

                            @Override
                            public void valueChanged(ListSelectionEvent e) {
                                if (!e.getValueIsAdjusting()) {
                                    selectionChanged(
                                            getTable().getSelectionModel().getMinSelectionIndex()
                                                    >= 0);
                                }
                            }
                        });

        if (allowModification) {
            getTable()
                    .addMouseListener(
                            new MouseAdapter() {
                                @Override
                                public void mousePressed(MouseEvent me) {
                                    // Bring up the modify dialog if the user double clicks on a row
                                    if (me.getClickCount() == 2
                                            && modifyButton != null
                                            && modifyButton.isEnabled()) {
                                        JXTable table = (JXTable) me.getSource();
                                        Point p = me.getPoint();
                                        int row = table.rowAtPoint(p);
                                        if (row >= 0) {
                                            modifyElement(getTable().convertRowIndexToModel(row));
                                        }
                                    }
                                }
                            });
        }
    }

    private void modifyElement(int row) {
        E e = showModifyDialogue(getMultipleOptionsModel().getElement(row));
        if (e != null) {
            getMultipleOptionsModel().modifyElement(row, e);
        }
    }

    protected void selectionChanged(boolean entrySelected) {
        if (modifyButton != null) {
            modifyButton.setEnabled(entrySelected);
        }
        removeButton.setEnabled(entrySelected);
    }

    public AbstractMultipleOptionsBaseTablePanel(TableModel model) {
        super(model);
    }

    /**
     * {@inheritDoc}
     *
     * <p>Overridden to also enable/disable the added buttons ("add", "modify", "remove" and "remove
     * without confirmation").
     */
    @Override
    public void setComponentEnabled(boolean enabled) {
        super.setComponentEnabled(enabled);

        addButton.setEnabled(enabled);
        removeWithoutConfirmationCheckBox.setEnabled(enabled);

        boolean enable = enabled && getTable().getSelectionModel().getMinSelectionIndex() >= 0;
        if (modifyButton != null) {
            modifyButton.setEnabled(enable);
        }
        removeButton.setEnabled(enable);
    }

    public final void addFooterPanelComponent(JComponent component) {
        getFooterPanel().add(component, gbcFooterPanel);
    }

    public boolean isRemoveWithoutConfirmation() {
        return getRemoveWithoutConfirmationCheckBox().isSelected();
    }

    public void setRemoveWithoutConfirmation(boolean enabled) {
        getRemoveWithoutConfirmationCheckBox().setSelected(enabled);
    }

    protected String getRemoveWithoutConfirmationLabel() {
        return REMOVE_WO_CONFIRMATION_CHECKBOX_LABEL;
    }

    protected final JCheckBox getRemoveWithoutConfirmationCheckBox() {
        if (removeWithoutConfirmationCheckBox == null) {
            removeWithoutConfirmationCheckBox = new JCheckBox(getRemoveWithoutConfirmationLabel());
        }
        return removeWithoutConfirmationCheckBox;
    }

    protected int getSelectedRow() {
        int selectedRow = getTable().getSelectionModel().getMinSelectionIndex();
        if (selectedRow == -1) {
            return -1;
        }
        return getTable().convertRowIndexToModel(selectedRow);
    }

    protected AbstractMultipleOptionsBaseTableModel<E> getMultipleOptionsModel() {
        return model;
    }

    public abstract E showAddDialogue();

    public abstract E showModifyDialogue(E e);

    public abstract boolean showRemoveDialogue(E e);
}


text:
<!DOCTYPE html>

<meta charset="utf-8">

<title>class User - Rails Application Documentation</title>

<link href="./css/fonts.css" rel="stylesheet">
<link href="./css/rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Parent

ActiveRecord::Base

Methods

::omniauth

#add_role

#fullname

#has_role?

#remove_role

#update_from_gram

    class User

A User of the application

Attributes

          synced_with_gram[RW]

#synced_with_gram :
True if last sync with gram data succeed (false if not). false if object
never tried to sync at runtime. Auto sync performed at connection via CAS

Public Class Methods

          omniauth(auth_data, signed_in_resource=nil)

          click to toggle source

Return an User to login after Omniauth
authentification. This user is retrieve in database with hruid or created
on the fly from CAS data

# File app/models/user.rb, line 62
def self.omniauth(auth_data, signed_in_resource=nil)

  logger.debug "=================================="
  logger.debug "Connexion depuis le CAS uid : "+auth_data[:uid]
  logger.debug "Infos de connection :"
  logger.debug auth_data.inspect

  # auth_data : take a look on Users::OmniauthCallbacksController
  unless user = User.find_by_hruid(auth_data[:uid])
    user = User.new(
        email: auth_data[:info][:email],
        password: Devise.friendly_token[0,20],
        hruid: auth_data[:uid],
        firstname: auth_data[:extra][:firstname],
        lastname: auth_data[:extra][:lastname],
    )
    user.save!
  end

  begin
    user.update_from_gram
  rescue => e
    logger.error "Erreur de connexion au GrAM :\n #{YAML::dump e}"
  end

  user
end

Public Instance Methods

          add_role(role_name)

          click to toggle source

Add or change role

# File app/models/user.rb, line 34
def  add_role (role_name)
  self.update_attribute(:role_id,Role.find_by_name(role_namee).id)
end

          fullname()

          click to toggle source

Return user firstname and lastname

# File app/models/user.rb, line 92
def fullname
  firstname + " " + lastname
end

          has_role?(role_name)

          click to toggle source

Check current role

# File app/models/user.rb, line 27
def has_role? (role_name)
  self.role ? self.role.name==(role_name.to_s) : false
end

          remove_role(role_name=nil)

          click to toggle source

Delete current role if any

# File app/models/user.rb, line 40
def  remove_role (role_name=nil)
  self.update_attribute(:role_id,nil)
end

          update_from_gram()

          click to toggle source

Update local user data with data contained in GrAM

# File app/models/user.rb, line 46
def update_from_gram
  self.synced_with_gram = false
  gram_data=GramAccount.find(self.hruid)

  self.email=gram_data.email
  self.firstname=gram_data.firstname
  self.lastname=gram_data.lastname

  self.save
  self.synced_with_gram = true
  self
end

Validate

Generated by RDoc 4.2.0.

Based on Darkfish by Michael Granger.


text:
package fi.attemoisio.songbookapi.resource.mock;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import fi.attemoisio.songbookapi.errorhandling.ApiError;
import fi.attemoisio.songbookapi.exceptions.ApiException;
import fi.attemoisio.songbookapi.model.ExtraVerse;
import fi.attemoisio.songbookapi.model.ExtraVersePost;
import fi.attemoisio.songbookapi.repository.ExtraVerseRepository;

public class MockExtraVerseRepository implements ExtraVerseRepository {

	Map<String, HashMap<String, List<ExtraVerse>>> bookMap;

	private final AtomicInteger idSequence = new AtomicInteger(5);

	public MockExtraVerseRepository() {

			bookMap = new HashMap<String, HashMap<String, List<ExtraVerse>>>();

			for (int j = 0; j < 5; j++){
				String bookId = "book" + j;
				HashMap<String, List<ExtraVerse>> songMap = new HashMap<String, List<ExtraVerse>>();
				for (int i = 0; i < 5; i++) {
					String songId = "song" + i;

					List<ExtraVerse> verses = new ArrayList<ExtraVerse>();
					for (int k = 0; k < 5; k++) {
						ExtraVerse verse = new ExtraVerse();
						verse.setId(i);
						verse.setLyrics("lorem ipsum " + i);
						verses.add(verse);
					}
					songMap.put(songId, verses);
				}
				bookMap.put(bookId, songMap);
			}

	}

	@Override
	public Collection<ExtraVerse> getExtraVerses(String bookId, String songId) {
		Collection<ExtraVerse> verses = bookMap.get(bookId).get(songId);
		return verses;
	}

	@Override
	public ExtraVerse getExtraVerse(String bookId, String songId, Integer verseId) {
		Collection<ExtraVerse> verses = bookMap.get(bookId).get(songId);
		for (ExtraVerse verse : verses) {
			if (verse.getId().equals(verseId))
				return verse;
		}
		return null;
	}

	@Override
	public ExtraVerse postExtraVerse(String bookId, String songId, ExtraVersePost verse) {
		Collection<ExtraVerse> verses = bookMap.get(bookId).get(songId);
		ExtraVerse newVerse = new ExtraVerse();
		newVerse.setId(idSequence.getAndIncrement());
		newVerse.setLyrics(verse.getLyrics());
		verses.add(newVerse);
		return newVerse;
	}

	@Override
	public boolean deleteExtraVerse(String bookId, String songId, Integer verseId) {
		Collection<ExtraVerse> verses = bookMap.get(bookId).get(songId);

		for (ExtraVerse verse : verses) {
			if (verse.getId().equals(verseId)) {
				verses.remove(verse);
				return true;
			}
		}
		return false;
	}

	@Override
	public void patchExtraVerse(String bookId, String songId,
			ExtraVerse verse) {

		ExtraVerse existingVerse = getExtraVerse(bookId, songId, verse.getId());

		if (existingVerse == null) {
			throw new ApiException(ApiError.UPDATE_VERSE_NOT_FOUND);
		}

		existingVerse.setLyrics(verse.getLyrics());

	}

}


text:
kennygchevyrider-yahoo.com
==========================


text:
package net.awired.clients.teamcity;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Calendar;
import java.util.Date;
import net.awired.clients.teamcity.DateAdapter;
import org.junit.Test;

public class DateAdapterTest {

    @Test
    public void should_parse_date() {
        // 02/03/2011 17h19mn40 + 0300
        // equivaut a
        // 02/03/2011 15h19mn40
        Date date = DateAdapter.parseDate("20110302T171940+0300");

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        assertEquals(2011, cal.get(Calendar.YEAR));
        assertEquals(2, cal.get(Calendar.DAY_OF_MONTH));
        assertEquals(3, cal.get(Calendar.MONTH) + 1);
        assertTrue(15 == cal.get(Calendar.HOUR_OF_DAY) || 9 == cal.get(Calendar.HOUR_OF_DAY));
        assertEquals(19, cal.get(Calendar.MINUTE));
        assertEquals(40, cal.get(Calendar.SECOND));
    }

    @Test(expected = NullPointerException.class)
    public void cant_pass_null_as_parameter() {
        DateAdapter.parseDate(null);
    }

}