text:
from dashboards.models import Dashboard, DashboardWidget
from exceptions import InvalidDashboardParametersException, InvalidWidgetParametersException

class DashboardValidator(object):
    @staticmethod
    def validate(query_params):
        DashboardValidator.__validate_name_from(query_params)
        DashboardValidator.__validate_description_from(query_params)
        DashboardValidator.__validate_template_from(query_params)
        return query_params

    @staticmethod
    def validate_params_for_update(query_params):
        DashboardValidator.__validate_uuid_from(query_params)
        DashboardValidator.__validate_name_from(query_params)
        DashboardValidator.__validate_description_from(query_params)
        return query_params

    @staticmethod
    def __validate_uuid_from(query_params):
        if 'uuid' not in query_params.keys() or not query_params['uuid']:
            raise InvalidDashboardParametersException("Parameter <uuid> should should not be null or empty")

    @staticmethod
    def __validate_name_from(query_params):
        if 'name' not in query_params.keys() or not query_params['name']:
            raise InvalidDashboardParametersException("Parameter <name> should not be null or empty")

    @staticmethod
    def __validate_description_from(query_params):
        pass

    @staticmethod
    def __validate_template_from(query_params):
        if 'template' not in query_params.keys() or not query_params['template']:
            raise InvalidDashboardParametersException("Parameter <template> should not be null or empty")
        elif query_params['template'] not in Dashboard.TEMPLATES.keys():
            raise InvalidDashboardParametersException(
                    "Parameter <template> should be one of those:" + str(Dashboard.TEMPLATES.keys()))

    @staticmethod
    def __validate_monitored_object_uuid_from(query_params):
        if 'monitored-object-uuid' not in query_params.keys() or not query_params['monitored-object-uuid']:
            raise InvalidDashboardParametersException(
                    "Parameter <monitored-object-uuid> should should not be null or empty")

    @staticmethod
    def __validate_transmitter_uuid_from(query_params):
        if 'transmitter-uuid' not in query_params.keys() or not query_params['transmitter-uuid']:
            raise InvalidDashboardParametersException("Parameter <transmitter-uuid> should should not be null or empty")

class WidgetValidator(object):
    WIDGET_SIZE_LOWER_BOUND = 2
    WIDGET_SIZE_UPPER_BOUND = 11

    @staticmethod
    def validate_params_for_creation(query_params):
        WidgetValidator.__validate_name_from(query_params)
        WidgetValidator.__validate_description_from(query_params)
        WidgetValidator.__validate_type_from(query_params)
        WidgetValidator.__validate_measure_units_from(query_params)
        WidgetValidator.__validate_width_from(query_params)
        WidgetValidator.__validate_dashboard_from(query_params)
        WidgetValidator.__validate_sensor_from(query_params)
        WidgetValidator.__validate_sensor_measure_from(query_params)
        WidgetValidator.__validate_refresh_rate_from(query_params)
        return query_params

    @staticmethod
    def validate_params_for_update(query_params):
        pass

    @staticmethod
    def __validate_name_from(query_params):
        if 'name' not in query_params.keys() or not query_params['name']:
            raise InvalidWidgetParametersException("Parameter <name> should not be null or empty")

    @staticmethod
    def __validate_description_from(query_params):
        pass

    @staticmethod
    def __validate_type_from(query_params):
        if 'type' not in query_params.keys() or not query_params['type']:
            raise InvalidWidgetParametersException("Parameter <type> should not be null or empty")
        elif query_params['type'] not in DashboardWidget.TYPES.keys():
            raise InvalidWidgetParametersException(
                    "Parameter <type> should be one of those:" + str(DashboardWidget.TYPES.keys()))

    @staticmethod
    def __validate_measure_units_from(query_params):
        if 'measure-units' not in query_params.keys() or not query_params['measure-units']:
            raise InvalidWidgetParametersException("Parameter <measure-units> should not be null or empty")
        elif query_params['measure-units'] not in DashboardWidget.MEASURE_UNITS.keys():
            raise InvalidWidgetParametersException(
                    "Parameter <measure-units> should be one of those:" + str(DashboardWidget.MEASURE_UNITS.keys()))

    @staticmethod
    def __validate_width_from(query_params):
        if 'width' not in query_params.keys() or not query_params['width']:
            raise InvalidWidgetParametersException("Parameter <width> should not be null or empty")
        elif int(query_params['width']) < WidgetValidator.WIDGET_SIZE_LOWER_BOUND or int(
                query_params['width']) > WidgetValidator.WIDGET_SIZE_UPPER_BOUND:
            raise InvalidWidgetParametersException(
                    "Parameter <width> should be in range:" + str(WidgetValidator.WIDGET_SIZE_LOWER_BOUND) + "-" + str(
                            WidgetValidator.WIDGET_SIZE_UPPER_BOUND))

    @staticmethod
    def __validate_dashboard_from(query_params):
        if 'dashboard-uuid' not in query_params.keys() or not query_params['dashboard-uuid']:
            raise InvalidWidgetParametersException("Parameter <dashboard-uuid> should not be null or empty")

    @staticmethod
    def __validate_sensor_from(query_params):
        if 'sensor' not in query_params.keys() or not query_params['sensor']:
            raise InvalidWidgetParametersException("Parameter <sensor> should not be null or empty")

    @staticmethod
    def __validate_sensor_measure_from(query_params):
        if 'sensor-measure' not in query_params.keys() or not query_params['sensor-measure']:
            raise InvalidWidgetParametersException("Parameter <sensor-measure> should not be null or empty")

    @staticmethod
    def __validate_refresh_rate_from(query_params):
        if 'refresh-rate' not in query_params.keys() or not query_params['refresh-rate']:
            raise InvalidWidgetParametersException("Parameter <refresh-rate> should not be null or empty")


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Saroj Rout</title>
    <link>https://sarojios.github.io/tags/about/index.xml</link>
    <description>Recent content on Saroj Rout</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-US</language>
    <atom:link href="https://sarojios.github.io/tags/about/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>About</title>
      <link>https://sarojios.github.io/about/</link>
      <pubDate>Sun, 02 Oct 2016 22:55:05 -0400</pubDate>

      <guid>https://sarojios.github.io/about/</guid>
      <description>
Works as a Sr. Software Developer and have around more than 6 years of experience in Mobile Technologies like iOS, Android and Hybrid Apps using Angular JS, Angular 2 and jQuery Mobile.
I have developed more than 20 AppStore and Enterprise apps using Objective-C, Swift, Java, Angular JS, Angular 2 and other javascript frameworks. I have been working on iOS technology since 2010 and a passionate iOS developer who loves creating elegant apps using Objective-C and Swift.
I have developed apps for iPhone, iPad, watchOS and tvOS. I always like to keep up with latest technologies and learning new skills to develop a better Mobile app using the latest available features.
In the free time i like to read new technologies, spending time with my friends and traveling to new places where i can enjoy the beauty of nature.

</description>
    </item>

  </channel>
</rss>

redpajama_set_name: RedPajamaGithub


text:
comments: true
date: 2011-04-17 15:28:00+00:00
layout: post
title: A Very Long Journey
wordpress_id: 787
image: http://c4.staticflickr.com/2/1705/26673254115_a3b67a501d_q.jpg
locations:
  - Vietnam
  - Hanoi
redirect_from:
  - /vietnam/hanoi/vietnam-2011/a-very-long-journey/
---

Our latest journey started at the relatively late hour of 6am. We headed out to Heathrow for the
first leg toKuala Lumpur. The 12½ hour flight was fairly uneventful, but neither of us managed to
get much sleep so we were both a bit tired on arrival in Malaysia. We had a three hour stop over and
after enquiring we found that we wouldn't have enough time to actually visit KL. This was a little
disappointing, but the airport had an outdoor courtyard area so we visited that instead.

{% flickr_photoset 72157665304546884 %}

Our next leg was three more hours up to Hanoi by which point most people were feeling a little worse
for wear. We picked up 3 million Vietnamese Dong (about 90 quid) and met up with our Exodus guide,
Hai. We transferred straight to the hotel for about 2 hours sleep, then after a quick shower and
change we headed out into Hanoi to visit the Old Quarter and get some food. We ate in a quaint
little place called Little Hanoi. The service was friendly and very quick and the food was
excellent! We had a selection of local specialities and drinks and paid a little over £6 for the two
of us. Bargain!

On the way back to the hotel we took a stroll through one of the night markets but most of us were
too tired to really be that interested so just made our way back to the hotel for some proper sleep
following our very long journey to Vietnam.

{% flickr_photoset 72157667460755432 %}


text:
package rpc

import (
	"testing"

	"github.com/cockroachdb/cockroach/security"
	"github.com/cockroachdb/cockroach/security/securitytest"
	"github.com/cockroachdb/cockroach/testutils"
	"github.com/cockroachdb/cockroach/util/hlc"
	"github.com/cockroachdb/cockroach/util/leaktest"
	"github.com/cockroachdb/cockroach/util/stop"
)

// NewNodeTestContext returns a rpc.Context for testing.
// It is meant to be used by nodes.
func NewNodeTestContext(clock *hlc.Clock, stopper *stop.Stopper) *Context {
	if clock == nil {
		clock = hlc.NewClock(hlc.UnixNano)
	}
	return NewContext(testutils.NewNodeTestBaseContext(), clock, stopper)
}

func init() {
	security.SetReadFileFn(securitytest.Asset)
}

//go:generate ../util/leaktest/add-leaktest.sh *_test.go

func TestMain(m *testing.M) {
	leaktest.TestMainWithLeakCheck(m)
}


text:
<?php

declare(strict_types = 1);

namespace SportTrackerConnector\Core\Workout\Dumper;

use SportTrackerConnector\Core\Workout\Workout;

/**
 * Interface for workout dumpers.
 */
interface DumperInterface
{
    /**
     * Dump a workout to string.
     *
     * @param Workout $workout The workout to dump.
     * @return string
     */
    public function dump(Workout $workout): string;
}


text:
package net.catchpole.B9.devices.compass;

import net.catchpole.B9.spacial.Heading;

public interface HeadingFilter {
    Heading filter(Heading heading);
}


text:
Quickstart
==========

.. module:: terminal

Eager to get started? This page gives a good introduction in how to get started
with Terminal. This assumes you already have Terminal installed. If you do not,
head over to the :doc:`install` section.

First, make sure that:

* Terminal is :doc:`installed <install>`

Let's get started with some simple examples.

Play with colors
----------------

Terminal would be better if it is colorful.

Begin by importing the Terminal module::

    >>> import terminal

Now, let's play with the colors::

    >>> print(terminal.red('red color'))
    >>> print(terminal.green_bg('green background'))

Available colors::

    black, red, green, yellow, blue, magenta, cyan, white

Available styles::

    bold, faint, italic, underline, blink, overline, inverse
    conceal, strike

.. warning::

    But don't count on these styles, your terminal may be not able to
    show all of them.

Verbose logging
---------------

Terminal programs need a simple and beautiful logging system. If it has a
verbose feature, it could help a lot::

    >>> from terminal import log

Now, let's play with the verbose log::

    >>> log.info('play with the log')
    >>> log.verbose.info('a verbose log will not show')
    >>> log.config(verbose=True)
    >>> log.verbose.info('a verbose log will show')

We can also control the logging level::

    >>> log.config(quiet=True)
    >>> log.info('info log will not show')
    >>> log.warn('but warn and error messages will show')

Prompt communication
--------------------

Many terminal programs will communicate with the users, this could be easy
with :func:`prompt`.

Let's create a prompt to ask the user's name::

    import terminal

    username = terminal.prompt('what is your name')

We could set a default name for the user::

    username = terminal.prompt('what is your name', 'Kate')

It is not a good idea to get a password with :func:`prompt`, instead,
terminal provided a :func:`password` for you::

    password = terminal.password('what is your password')

Want more on prompt?

We have :func:`terminal.confirm` and :func:`terminal.choose`.

Command line
------------

This is a replacement for **argparse** (or optparse).

Create a simple command parser with :class:`Command`::

    program = Command('foo', 'a description')

Add some options::

    program.option('-f, --force', 'force to process')
    program.option('-o, --output [output]', 'the output directory')

Let's make it work::

    program.parse()

    if program.output:
       print program.output

Save the code in a file (for example :file:`foo.py`), play in the terminal::

    $ python foo.py -h
    $ python foo.py -o src
    $ python foo.py --output=src
    $ python foo.py --output src

However, when creating a terminal tool, a subcommand is usually needed, we can
add subcommands via :meth:`Command.action`::

    program = Command('foo', 'a description')
    program.option('-v, --verbose', 'show more logs')

    subcommand = Command('build', 'build the site')
    subcommand.option('-o, --output [output]', 'the output directory')

    program.action(subcommand)

    program.parse()

    if program.verbose:
        terminal.log.config(verbose=True)

Let's play with the more complex one::

    $ python foo.py -h
    $ python foo.py build -h

-----------------------------

Ready for more? Check out the :doc:`advanced` section.


text:
using System.Web;

namespace MvcDI
{
    /// <summary>
    /// JavaScriptファイルの論理パスと物理パスのマッピング
    /// </summary>
    public class ScriptFileHandler : IHttpHandler
    {
        /// <summary>
        /// 論理パス
        /// </summary>
        readonly string virtualPath;

        #region constructor
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="path"></param>
        public ScriptFileHandler(string path)
        {
            virtualPath = path;
        }
        #endregion

        #region IHttpHandler メンバ
        /// <summary>
        /// 別の要求で IHttpHandler インスタンスを使用できるかどうかを示す値を取得します。
        /// </summary>
        bool IHttpHandler.IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// IHttpHandler インターフェイスを実装するカスタム HttpHandler によって、HTTP Web 要求の処理を有効にします。
        /// </summary>
        /// <param name="context">HTTP 要求を処理するために使用する、組み込みのサーバー オブジェクト (Request、Response、Session、Server など) への参照を提供する HttpContext オブジェクト。</param>
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            var path = context.Server.MapPath(virtualPath);

            context.Response.ContentType = "text/javascript";
            context.Response.TransmitFile(path);
        }

        #endregion
    }
}


text:
import { isServer, useRefreshQuery } from 'core/utils';

import Layout from 'modules/layout';
import PlaceList from 'modules/place-list';

export default function FrontPage() {
  const [{ data, fetching, error }] = useRefreshQuery({
    query: `
    {
      places {
        name
        cuid
        lastSnapshot {
          cuid
          date
          temperature
          image
          placeName
        }
      }
    }
  `,
    pause: isServer,
  });

  if (!data || fetching) {
    return <Layout loading title="Værhøna" />;
  }

  if (error) {
    return 'Oh no.';
  }

  if (!data.places) {
    return 'no places';
  }

  return (
    <Layout title="Værhøna" scroll>
      <PlaceList places={data.places} />
    </Layout>
  );
}


text:
package fxlog

import (
	"reflect"
	"sync"

	"go.uber.org/fx/fxevent"
)

// Events is a list of events captured by fxlog.Spy.
type Events []fxevent.Event

// Len returns the number of events in this list.
func (es Events) Len() int { return len(es) }

// SelectByTypeName returns a new list with only events matching the specified
// type.
func (es Events) SelectByTypeName(name string) Events {
	var out Events
	for _, e := range es {
		if reflect.TypeOf(e).Elem().Name() == name {
			out = append(out, e)
		}
	}
	return out
}

// Spy is an Fx event logger that captures emitted events and/or logged
// statements. It may be used in tests of Fx logs.
type Spy struct {
	mu     sync.RWMutex
	events Events
}

var _ fxevent.Logger = &Spy{}

// LogEvent appends an Event.
func (s *Spy) LogEvent(event fxevent.Event) {
	s.mu.Lock()
	s.events = append(s.events, event)
	s.mu.Unlock()
}

// Events returns all captured events.
func (s *Spy) Events() Events {
	s.mu.RLock()
	defer s.mu.RUnlock()

	events := make(Events, len(s.events))
	copy(events, s.events)
	return events
}

// EventTypes returns all captured event types.
func (s *Spy) EventTypes() []string {
	s.mu.RLock()
	defer s.mu.RUnlock()

	types := make([]string, len(s.events))
	for i, e := range s.events {
		types[i] = reflect.TypeOf(e).Elem().Name()
	}
	return types
}

// Reset clears all messages and events from the Spy.
func (s *Spy) Reset() {
	s.mu.Lock()
	s.events = s.events[:0]
	s.mu.Unlock()
}


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.DataFactories;
using Microsoft.Azure.Management.DataFactories.Models;

namespace Microsoft.Azure.Management.DataFactories
{
    public static partial class EncryptionCertificateOperationsExtensions
    {
        /// <summary>
        /// Gets the certificate to use for encryption.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.DataFactories.IEncryptionCertificateOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. The resource group name of the data factory.
        /// </param>
        /// <param name='dataFactoryName'>
        /// Required. A unique data factory instance name.
        /// </param>
        /// <returns>
        /// The Get encryption certificate operation response.
        /// </returns>
        public static EncryptionCertificateGetResponse Get(this IEncryptionCertificateOperations operations, string resourceGroupName, string dataFactoryName)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IEncryptionCertificateOperations)s).GetAsync(resourceGroupName, dataFactoryName);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// Gets the certificate to use for encryption.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.DataFactories.IEncryptionCertificateOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. The resource group name of the data factory.
        /// </param>
        /// <param name='dataFactoryName'>
        /// Required. A unique data factory instance name.
        /// </param>
        /// <returns>
        /// The Get encryption certificate operation response.
        /// </returns>
        public static Task<EncryptionCertificateGetResponse> GetAsync(this IEncryptionCertificateOperations operations, string resourceGroupName, string dataFactoryName)
        {
            return operations.GetAsync(resourceGroupName, dataFactoryName, CancellationToken.None);
        }
    }
}


text:
package com.loren.textlibrary.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * Java utils 实现的Zip工具
 *
 * @author once
 */
public class ZipUtil{
    private static final int BUFF_SIZE = 1024 * 1024; // 1M Byte
    private static boolean stopZipFlag;

    public static boolean isStopZipFlag() {
		return stopZipFlag;
	}

	public static void setStopZipFlag(boolean stopZipFlag) {
		ZipUtil.stopZipFlag = stopZipFlag;
	}

	/**
     * 批量压缩文件(夹)
     *
     * @param resFileList 要压缩的文件(夹)列表
     * @param zipFile 生成的压缩文件
     * @param zipListener     zipListener
     */
    public static void zipFiles(Collection<File> resFileList, File zipFile,ZipListener zipListener)  {

        ZipOutputStream zipout = null;
        try {
            zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(
                    zipFile), BUFF_SIZE));
            for (File resFile : resFileList) {
                if(stopZipFlag){
                    break;
                }
                zipFile(resFile, zipout, "",zipListener);
            }
            zipout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量压缩文件(夹)
     *
     * @param resFileList 要压缩的文件(夹)列表
     * @param zipFile 生成的压缩文件
     * @param comment 压缩文件的注释
     * @param zipListener    zipListener
     */
    public static void zipFiles(Collection<File> resFileList, File zipFile, String comment,ZipListener zipListener)
           {
               ZipOutputStream zipout = null;
               try {
                   zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
                   for (File resFile : resFileList) {
                       zipFile(resFile, zipout, "",zipListener);
                   }
                   zipout.setComment(comment);
                   zipout.close();
               } catch (Exception e) {
                   e.printStackTrace();
               }
    }

    /**
     * 解压缩一个文件
     *
     * @param zipFile 压缩文件
     * @param folderPath 解压缩的目标目录
     */
    public static void upZipFile(File zipFile, String folderPath) {
        File desDir = new File(folderPath);
        if (!desDir.exists()) {
            desDir.mkdirs();
        }
        ZipFile zf = null;
        try {
            zf = new ZipFile(zipFile);
            for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
                ZipEntry entry = ((ZipEntry)entries.nextElement());
                InputStream in = zf.getInputStream(entry);
                String str = folderPath + File.separator + entry.getName();
                str = new String(str.getBytes("8859_1"), "GB2312");
                File desFile = new File(str);
                if (!desFile.exists()) {
                    File fileParentDir = desFile.getParentFile();
                    if (!fileParentDir.exists()) {
                        fileParentDir.mkdirs();
                    }
                    desFile.createNewFile();
                }
                OutputStream out = new FileOutputStream(desFile);
                byte buffer[] = new byte[BUFF_SIZE];
                int realLength;
                while ((realLength = in.read(buffer)) > 0) {
                    out.write(buffer, 0, realLength);
                }
                in.close();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 解压文件名包含传入文字的文件
     *
     * @param zipFile 压缩文件
     * @param folderPath 目标文件夹
     * @param nameContains 传入的文件匹配名
     * @return   返回的集合
     */
    public static ArrayList<File> upZipSelectedFile(File zipFile, String folderPath,
            String nameContains) {

        ArrayList<File> fileList = new ArrayList<File>();

        File desDir = new File(folderPath);
        if (!desDir.exists()) {
            desDir.mkdir();
        }

        ZipFile zf = null;
        try {
            zf = new ZipFile(zipFile);
            for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
                ZipEntry entry = ((ZipEntry)entries.nextElement());
                if (entry.getName().contains(nameContains)) {
                    InputStream in = zf.getInputStream(entry);
                    String str = folderPath + File.separator + entry.getName();
                    str = new String(str.getBytes("8859_1"), "GB2312");
                    // str.getBytes("GB2312"),"8859_1" 输出
                    // str.getBytes("8859_1"),"GB2312" 输入
                    File desFile = new File(str);
                    if (!desFile.exists()) {
                        File fileParentDir = desFile.getParentFile();
                        if (!fileParentDir.exists()) {
                            fileParentDir.mkdirs();
                        }
                        desFile.createNewFile();
                    }
                    OutputStream out = new FileOutputStream(desFile);
                    byte buffer[] = new byte[BUFF_SIZE];
                    int realLength;
                    while ((realLength = in.read(buffer)) > 0) {
                        out.write(buffer, 0, realLength);
                    }
                    in.close();
                    out.close();
                    fileList.add(desFile);
                }
            }
            return fileList;
        } catch (Exception e) {
            e.printStackTrace();
        }
            return null;
    }

    /**
     * 获得压缩文件内文件列表
     *
     * @param zipFile 压缩文件
     * @return 压缩文件内文件名称
     */
    public static ArrayList<String> getEntriesNames(File zipFile) {

        ArrayList<String> entryNames = new ArrayList<String>();
        Enumeration<?> entries = null;
        try {
            entries = getEntriesEnumeration(zipFile);
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry)entries.nextElement());
                entryNames.add(new String(getEntryName(entry).getBytes("GB2312"), "8859_1"));
            }
            return entryNames;
        } catch (IOException e) {
            e.printStackTrace();
        }
            return null;
    }

    /**
     * 获得压缩文件内压缩文件对象以取得其属性
     *
     * @param zipFile 压缩文件
     * @return 返回一个压缩文件列表
     */
    public static Enumeration<?> getEntriesEnumeration(File zipFile) {
        ZipFile zf = null;
        try {
            zf = new ZipFile(zipFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return zf.entries();

    }

    /**
     * 取得压缩文件对象的注释
     *
     * @param entry 压缩文件对象
     * @return 压缩文件对象的注释
     */
    public static String getEntryComment(ZipEntry entry)  {
        try {
            return new String(entry.getComment().getBytes("GB2312"), "8859_1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 取得压缩文件对象的名称
     *
     * @param entry 压缩文件对象
     * @return 压缩文件对象的名称
     */
    public static String getEntryName(ZipEntry entry)  {
        try {
            return new String(entry.getName().getBytes("GB2312"), "8859_1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 压缩文件
     *
     * @param resFile 需要压缩的文件(夹)
     * @param zipout 压缩的目的文件
     * @param rootpath 压缩的文件路径
     */
    private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath,ZipListener zipListener)
          {
        try {
            rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator)
                    + resFile.getName();
            rootpath = new String(rootpath.getBytes("8859_1"), "GB2312");
            if (resFile.isDirectory()) {
                File[] fileList = resFile.listFiles();
                int length=fileList.length;
                // Log.e("zipprogress", (int)((1 / (float) (length+1))*100)+"%");
                zipListener.zipProgress((int)((1 / (float) (length+1))*100));
                for (int i=0;i<length;i++) {
                    if(stopZipFlag){
                        break;
                    }
                    File file=fileList[i];
                    zipFile(file, zipout, rootpath,zipListener);
                    // Log.e("zipprogress", (int)(((i+2) / (float) (length+1))*100)+"%");
                    zipListener.zipProgress((int)(((i+2) / (float) (length+1))*100));
                }
            } else {
                byte buffer[] = new byte[BUFF_SIZE];
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile),
                        BUFF_SIZE);
                zipout.putNextEntry(new ZipEntry(rootpath));
                int realLength;
                while ((realLength = in.read(buffer)) != -1) {
                    if(stopZipFlag){
                        break;
                    }
                    zipout.write(buffer, 0, realLength);
                }
                in.close();
                zipout.flush();
                zipout.closeEntry();
            }
        }catch (Exception e){

        }

    }
    public interface ZipListener{
    	void zipProgress(int zipProgress);
    }
}


text:
#include <stdlib.h>
#include <topaz/topaz.h>
#include <topaz/transport_ata.h>
#include <topaz/security.h>
#include <topaz/discovery.h>
#include <topaz/swg_core.h>

/**
 * \brief Open Drive / Trusted Peripheral (TPer)
 *
 * Opens a hard drive for use with topaz
 *
 * \param[in] path Path to target device
 * \return Pointer to allocated handle, or NULL on error
 */
tp_handle_t *tp_open(char const *path)
{
  tp_handle_t *handle = NULL;
  tp_errno_t rc = 0;

  /* alloc some memory for new handle */
  if ((handle = calloc(1, sizeof(tp_handle_t))) == NULL)
  {
    tp_errno = TP_ERR_ALLOC;
    return NULL;
  }

  /* Default assumptions about TPer(drive), until it tell us better.
   * NOTE that these are from SWG core spec */
  handle->lba_align = 1;
  handle->max_com_pkt_size = 1024;
  handle->max_token_size = 968;

  /* open ATA device */
  if ((handle->ata = tp_ata_open(path)) == NULL)
  {
    rc = tp_errno;
  }

  /* check for TPM */
  else if (tp_ata_probe_tpm(handle->ata) != 0)
  {
    rc = tp_errno;
  }

  /* check for TPM security protocols */
  else if (tp_probe_security(handle) != 0)
  {
    rc = tp_errno;
  }

  /* check for supported SSC's and SWG features */
  else if (tp_probe_discovery(handle) != 0)
  {
    rc = tp_errno;
  }

  /* reset the SSC's ComID, if possible */
  else if ((handle->has_reset) &&
	   (tp_security_comid_reset(handle, handle->com_id) != 0))
  {
    rc = tp_errno;
  }

  /* perform host properties handshake */
  else if (tp_swg_do_properties(handle))
  {
    rc = tp_errno;
  }

  /* otherwise everything's ok */
  else
  {
    tp_errno = TP_ERR_SUCCESS;
    return handle;
  }

  /* cleanup */
  tp_close(handle);
  tp_errno = rc;
  return NULL;
}

/**
 * \brief Close Drive / Trusted Peripheral (TPer)
 *
 * Closes & cleans up topaz device handle
 *
 * \param[in] path Path to target device
 * \return 0 on success, error code indicating failure
 */
tp_errno_t tp_close(tp_handle_t *handle)
{
  /* sanity check */
  if (handle != NULL)
  {
    /* close ATA device */
    if (handle->ata != NULL)
    {
      tp_swg_session_end(handle);
      tp_ata_close(handle->ata);
      handle->ata = NULL;
    }

    /* clear mem */
    free(handle);
    handle = NULL;
  }

  /* always return success for now .. */
  return tp_errno = TP_ERR_SUCCESS;
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.03.27 at 03:31:23 PM GMT
//

package org.apache.wss4j.binding.wssc13;

import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.wss4j.binding.wss10.SecurityTokenReferenceType;
import org.apache.wss4j.binding.wssc.AbstractDerivedKeyTokenType;

/**
 *
Java class for DerivedKeyTokenType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="DerivedKeyTokenType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}SecurityTokenReference" minOccurs="0"/>
 *         <element name="Properties" type="{http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512}PropertiesType" minOccurs="0"/>
 *         <sequence minOccurs="0">
 *           <choice>
 *             <element name="Generation" type="{http://www.w3.org/2001/XMLSchema}unsignedLong"/>
 *             <element name="Offset" type="{http://www.w3.org/2001/XMLSchema}unsignedLong"/>
 *           </choice>
 *           <element name="Length" type="{http://www.w3.org/2001/XMLSchema}unsignedLong" minOccurs="0"/>
 *         </sequence>
 *         <element ref="{http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512}Label" minOccurs="0"/>
 *         <element ref="{http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512}Nonce" minOccurs="0"/>
 *       </sequence>
 *       <attribute ref="{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Id"/>
 *       <attribute name="Algorithm" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DerivedKeyTokenType", propOrder = {
    "securityTokenReference",
    "properties",
    "generation",
    "offset",
    "length",
    "label",
    "nonce"
})
public class DerivedKeyTokenType
    extends AbstractDerivedKeyTokenType
{

    @XmlElement(name = "SecurityTokenReference", namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")
    private SecurityTokenReferenceType securityTokenReference;
    @XmlElement(name = "Properties")
    private PropertiesType properties;
    @XmlElement(name = "Generation")
    @XmlSchemaType(name = "unsignedLong")
    private BigInteger generation;
    @XmlElement(name = "Offset")
    @XmlSchemaType(name = "unsignedLong")
    private BigInteger offset;
    @XmlElement(name = "Length")
    @XmlSchemaType(name = "unsignedLong")
    private BigInteger length;
    @XmlElement(name = "Label")
    private String label;
    @XmlElement(name = "Nonce")
    private byte[] nonce;
    @XmlAttribute(name = "Id", namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    @XmlSchemaType(name = "ID")
    private String id;
    @XmlAttribute(name = "Algorithm")
    @XmlSchemaType(name = "anyURI")
    private String algorithm;

    /**
     * Gets the value of the securityTokenReference property.
     *
     * @return
     *     possible object is
     *     {@link SecurityTokenReferenceType }
     *
     */
    public SecurityTokenReferenceType getSecurityTokenReference() {
        return securityTokenReference;
    }

    /**
     * Sets the value of the securityTokenReference property.
     *
     * @param value
     *     allowed object is
     *     {@link SecurityTokenReferenceType }
     *
     */
    public void setSecurityTokenReference(SecurityTokenReferenceType value) {
        this.securityTokenReference = value;
    }

    /**
     * Gets the value of the properties property.
     *
     * @return
     *     possible object is
     *     {@link PropertiesType }
     *
     */
    public PropertiesType getProperties() {
        return properties;
    }

    /**
     * Sets the value of the properties property.
     *
     * @param value
     *     allowed object is
     *     {@link PropertiesType }
     *
     */
    public void setProperties(PropertiesType value) {
        this.properties = value;
    }

    /**
     * Gets the value of the generation property.
     *
     * @return
     *     possible object is
     *     {@link BigInteger }
     *
     */
    public BigInteger getGeneration() {
        return generation;
    }

    /**
     * Sets the value of the generation property.
     *
     * @param value
     *     allowed object is
     *     {@link BigInteger }
     *
     */
    public void setGeneration(BigInteger value) {
        this.generation = value;
    }

    /**
     * Gets the value of the offset property.
     *
     * @return
     *     possible object is
     *     {@link BigInteger }
     *
     */
    public BigInteger getOffset() {
        return offset;
    }

    /**
     * Sets the value of the offset property.
     *
     * @param value
     *     allowed object is
     *     {@link BigInteger }
     *
     */
    public void setOffset(BigInteger value) {
        this.offset = value;
    }

    /**
     * Gets the value of the length property.
     *
     * @return
     *     possible object is
     *     {@link BigInteger }
     *
     */
    public BigInteger getLength() {
        return length;
    }

    /**
     * Sets the value of the length property.
     *
     * @param value
     *     allowed object is
     *     {@link BigInteger }
     *
     */
    public void setLength(BigInteger value) {
        this.length = value;
    }

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

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

    /**
     * Gets the value of the nonce property.
     *
     * @return
     *     possible object is
     *     byte[]
     */
    public byte[] getNonce() {
        return nonce;
    }

    /**
     * Sets the value of the nonce property.
     *
     * @param value
     *     allowed object is
     *     byte[]
     */
    public void setNonce(byte[] value) {
        this.nonce = value;
    }

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

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

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

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

}


text:
public class UnsortedDLLPQ<E extends Comparable<E>> implements MyPriorityQueue<E> {

	private ListNode2 queueHead;
	private int objectCount;

	public UnsortedDLLPQ()
	{
		queueHead = null;
		objectCount = 0;
	}

	public void add(E obj)
	{

	}

	public E removeMin()
	{

	}

	public E peek()
	{

	}

	public boolean isEmpty()
	{

	}

	public int size()
	{

	}

	public String toString()
	{
		StringBuffer stringbuf = new StringBuffer ("[ ");
		for (ListNode2 node = queueHead; node != null; node = node.getNext())
		{
			stringbuf.append(node.getValue()+" ");

		}
		stringbuf.append("]");
		return stringbuf.toString();
	}
}


text:
<?php

namespace Nours\RestAdminBundle\Tests\FixtureBundle\Controller;

use Nours\RestAdminBundle\Tests\FixtureBundle\Entity\Comment;
use Nours\RestAdminBundle\Tests\FixtureBundle\Entity\Post;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class FragmentController.
 *
 * The controller methods render templates which render rest actions as fragments.
 *
 * @author David Coudrier <david.coudrier@gmail.com>
 */
class FragmentController extends AbstractController
{
    /**
     * The template renders a post create action
     *
     * @return Response
     */
    public function createPost(): Response
    {
        return $this->render('fragment/post_create.html.twig');
    }

    /**
     * The template renders a comment create action, using the post from main request attributes
     *
     * @param Post $parent
     * @return Response
     */
    public function createPostComment(Post $parent): Response
    {
        return $this->render('fragment/post_comment_create.html.twig', array(
            'post' => $parent
        ));
    }

    /**
     * The template forwards to current resource's create action : the main request
     * attributes are used to discover everything.
     *
     * @return Response
     */
    public function create(): Response
    {
        return $this->render('fragment/create.html.twig');
    }

    /**
     *
     * @param Comment $data
     * @return Response
     */
    public function editPostComment(Comment $data): Response
    {
        return $this->render('fragment/post_comment_edit.html.twig', array(
            'comment' => $data
        ));
    }

    /**
     *
     * @return Response
     */
    public function edit(): Response
    {
        return $this->render('fragment/edit.html.twig');
    }
}


text:
using FluentAssertions;
using Marten.Integration.Tests.TestsInfrastructure;
using Xunit;

namespace Marten.Integration.Tests.EventStore.Aggregate
{
    public record IssueCreated(
        Guid IssueId,
        string Description
    );

    public record IssueUpdated(
        Guid IssueId,
        string Description
    );

    namespace OldVersion
    {
        public class Issue
        {
            public Guid Id { get; set; }

            public string Description { get; set; } = default!;

            public void Apply(IssueCreated @event)
            {
                Id = @event.IssueId;
                Description = @event.Description;
            }

            public void Apply(IssueUpdated @event)
            {
                Description = @event.Description;
            }
        }
    }

    namespace NewVersion
    {
        public class Issue
        {
            public Guid Id { get; set; }

            public string Description { get; set; } = default!;

            public void Apply(IssueCreated @event)
            {
                Id = @event.IssueId;
                Description = $"New Logic: {@event.Description}";
            }

            public void Apply(IssueUpdated @event)
            {
                Description = $"New Logic: {@event.Description}";
            }
        }
    }

    public class Reaggregation: MartenTest
    {
        public Reaggregation() : base(false)
        {
        }

        public IDocumentSession CreateSessionWithInlineAggregationFor<TIssue>() where TIssue : class, new()
        {
            return base.CreateSession(options =>
            {
                options.Events.AddEventTypes(new[] { typeof(IssueCreated), typeof(IssueUpdated) });
                //It's needed to manualy set that inline aggegation should be applied
                options.Projections.SelfAggregate<TIssue>();
            });
        }

        [Fact]
        public void Given_When_Then()
        {
            var taskId = Guid.NewGuid();

            var events = new object[]
            {
                new IssueCreated(taskId, "Issue 1"),
                new IssueUpdated(taskId, "Issue 1 Updated"),
            };

            OldVersion.Issue issueFromV1InlineAggregation;
            OldVersion.Issue issueFromV1OnlineAggregation;

            using (var session = CreateSessionWithInlineAggregationFor<OldVersion.Issue>())
            {
                //1. Publish events
                session.Events.StartStream<OldVersion.Issue>(taskId, events);

                session.SaveChanges();

                issueFromV1InlineAggregation = session.Load<OldVersion.Issue>(taskId)!;
                issueFromV1OnlineAggregation = session.Events.AggregateStream<OldVersion.Issue>(taskId)!;
            }

            //2. Both inline and online aggregation for the same type should be the same
            issueFromV1InlineAggregation.Description.Should().Be("Issue 1 Updated");
            issueFromV1InlineAggregation.Description.Should().Be(issueFromV1OnlineAggregation.Description);

            //3. Simulate change to aggregation logic
            NewVersion.Issue issueFromV2InlineAggregation;
            NewVersion.Issue issueFromV2OnlineAggregation;

            using (var session = CreateSessionWithInlineAggregationFor<NewVersion.Issue>())
            {
                issueFromV2InlineAggregation = session.Load<NewVersion.Issue>(taskId)!;
                issueFromV2OnlineAggregation = session.Events.AggregateStream<NewVersion.Issue>(taskId)!;
            }

            //4. Inline aggregated snapshot won't change automatically
            issueFromV2InlineAggregation.Description.Should().Be(issueFromV1InlineAggregation.Description);
            issueFromV2InlineAggregation.Description.Should().NotBe("New Logic: Issue 1 Updated");

            //5. But online aggregation is being applied automatically
            issueFromV2OnlineAggregation.Description.Should().NotBe(issueFromV1OnlineAggregation.Description);
            issueFromV2OnlineAggregation.Description.Should().Be("New Logic: Issue 1 Updated");

            //6. Reagregation
            using (var session = CreateSessionWithInlineAggregationFor<NewVersion.Issue>())
            {
                //7. Get online aggregation
                //8. Store manually online aggregation as inline aggregation
                session.Store(issueFromV2OnlineAggregation);
                session.SaveChanges();

                var taskFromV2AfterReaggregation = session.Load<NewVersion.Issue>(taskId)!;

                taskFromV2AfterReaggregation.Description.Should().NotBe(issueFromV1OnlineAggregation.Description);
                taskFromV2AfterReaggregation.Description.Should().Be(issueFromV2OnlineAggregation.Description);
                taskFromV2AfterReaggregation.Description.Should().Be("New Logic: Issue 1 Updated");

                //9. Check if next event would be properly applied to inline aggregation
                session.Events.Append(taskId, new IssueUpdated(taskId, "Completely New text"));
                session.SaveChanges();
            }

            using (var session = CreateSessionWithInlineAggregationFor<NewVersion.Issue>())
            {
                var taskFromV2NewInlineAggregation = session.Load<NewVersion.Issue>(taskId)!;
                taskFromV2NewInlineAggregation.Description.Should().Be("New Logic: Completely New text");
            }
        }
    }
}


text:
package com.superscholar.android.activity;

import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.superscholar.android.R;
import com.superscholar.android.control.BaseActivity;

public class WebActivity extends BaseActivity {

    private WebView webView;

    private void initWebView(){
        String url=getIntent().getStringExtra("url");
        webView=(WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(url);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        initWebView();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); //goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}


text:
package com.gurkensalat.osm.mosques;

import com.gurkensalat.osm.mosques.entity.OsmMosquePlace;
import com.gurkensalat.osm.mosques.repository.OsmMosquePlaceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@EnableAutoConfiguration
public class OsmController
{
    private final static Logger LOGGER = LoggerFactory.getLogger(OsmController.class);

    private final static String REQUEST_ROOT = "/osm";

    @Autowired
    private OsmMosquePlaceRepository osmMosquePlaceRepository;

    @RequestMapping(value = REQUEST_ROOT + "/list", method = RequestMethod.GET)
    public String osmList(Model model)
    {
        LOGGER.info("osmMosquePlaceRepository is {}", osmMosquePlaceRepository);

        model.addAttribute("repository", osmMosquePlaceRepository);

        Iterable<OsmMosquePlace> places = osmMosquePlaceRepository.findAll();
        model.addAttribute("places", places);

        return "osm-list";
    }
}


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
---

# batterystatus

Событие возникает, когда есть изменения в состояние батареи.

    window.addEventListener("batterystatus", yourCallbackFunction, false);

## Подробная информация

Это событие возникает при изменении процент заряда батареи по крайней мере на 1%, или если устройство подключен или отключен от сети.

Обработчик статуса батареи передается объект, содержащий два свойства:

*   **уровень**: процент заряда батареи (0-100). *(Число)*

*   **isPlugged**: логическое значение, указывающее, является ли устройство подключено дюйма *(Boolean)*

Приложения обычно должны использовать `window.addEventListener` прикрепить прослушиватель событий после `deviceready` пожаров события.

## Поддерживаемые платформы

*   iOS
*   Андроид
*   WebWorks ежевики (OS 5.0 и выше)
*   Windows Phone 7 и 8
*   Tizen

## Windows Phone 7 и 8 причуды

Windows Phone 7 не обеспечивает родной API, чтобы определить уровень заряда батареи, так что `level` свойство недоступно. `isPlugged`Параметр *это* поддерживает.

## Быстрый пример

    window.addEventListener("batterystatus", onBatteryStatus, false);

    function onBatteryStatus(info) {
        // Handle the online event
        console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
    }

## Полный пример

    <!DOCTYPE html>
    <html>
      <head>
        <title>Device Ready Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for device API libraries to load
        //
        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }

        // device APIs are available
        //
        function onDeviceReady() {
            window.addEventListener("batterystatus", onBatteryStatus, false);
        }

        // Handle the batterystatus event
        //
        function onBatteryStatus(info) {
            console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
        }

        </script>
      </head>
      <body onload="onLoad()">
      </body>
    </html>


text:
{% for error in form.identity.errors %}

{{ error }}

{% endfor %}

{% if created %}

Account created, please check your email!

{% endif %}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.cosmos.benchmark.linkedin.data;

import com.google.common.base.MoreObjects;
import java.util.Objects;

/**
 * Data struct to ensure the unique-ness constraint for id + partitioningKey for
 * any CosmosDBRecord is preserved when we generate the data
 */
public class Key {

    private final String _id;
    private final String _partitioningKey;

    public Key(final String id, final String partitioningKey) {
        _id = id;
        _partitioningKey = partitioningKey;
    }

    public String getId() {
        return _id;
    }

    public String getPartitioningKey() {
        return _partitioningKey;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Key that = (Key) o;
        return Objects.equals(_id, that._id)
            && Objects.equals(_partitioningKey, that._partitioningKey);
    }

    @Override
    public int hashCode() {
        return Objects.hash(_id, _partitioningKey);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .omitNullValues()
                .add("id", getId())
                .add("partitioningKey", getPartitioningKey())
                .toString();
        }
    }


text:
'use strict'

const {toBooleanConfig} = require('./utils')

module.exports = {
  debug: toBooleanConfig(process.env.DEBUG),
  dburl: process.env.DATABASE_URL,
  urlpath: process.env.URL_PATH,
  port: process.env.PORT
}


text:
Implement a clock that handles times without dates.

Create a clock that is independent of date.

You should be able to add and subtract minutes to it.

Two clocks that represent the same time should be equal to each other.

## Running the tests

To run the tests run the command `go test` from within the exercise directory.

If the test suite contains benchmarks, you can run these with the `-bench`
flag:

    go test -bench .

Keep in mind that each reviewer will run benchmarks on a different machine, with
different specs, so the results from these benchmark tests may vary.

## Further information

For more detailed information about the Go track, including how to get help if
you're having trouble, please visit the exercism.io [Go language page](http://exercism.io/languages/go/about).

## Source

Pairing session with Erin Drummond [https://twitter.com/ebdrummond](https://twitter.com/ebdrummond)

## Submitting Incomplete Problems
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
<!DOCTYPE html>

{% include head-tag.snippet %}

  {% if page.no_header != true %}

      {% include header.snippet %}

  {% endif %}

  {% if page.layout_keyword == 'one_column' or page.layout_keyword == 'partner_feature_onecol' %}

    {% if page.hero_image != null %}

        {% include hero.snippet %}

    {% endif %}

        {{ content }}

  {% endif %}

  {% if page.layout_keyword == 'basic_info' %}

      {% include hero.snippet %}

          {{ content }}

          {% include info-right-col.snippet %}

  {% endif %}

  {% if page.layout_keyword == 'knowledge_base' %}

      {% include hero.snippet %}

          {{ content }}

          {% include info-right-col.snippet %}

  {% endif %}

  {% if page.layout_keyword == 'knowledge_base_page' %}

      {% include hero.snippet %}

        {% include user_help_videos.snippet %}

          {% if page.tags == 'basic_user_pages' %}{% include basic_user_nav.snippet %}{% endif %}
          {% if page.tags == 'group_admin_pages' %}{% include admin_user_nav.snippet %}{% endif %}

          {{ content }}

  {% endif %}

  {% if page.layout_keyword == 'knowledge_base_video' %}

      {% include hero.snippet %}

        <video id="media-player" src="{{ page.video_url }}"></video>

  {% endif %}

  {% if page.layout_keyword == 'feature' %}

      {% include hero.snippet %}

          {% include feature-nav.snippet %}

          {{ content }}

  {% endif %}
  {% if page.no_header != true %}
    {% include demo.snippet %}

      {% include footer.snippet %}

  {% else %}

  {% endif %}

  {% if page.analytics %}
    {% include {{page.analytics}} %}
  {% else %}
    {% include analytics.snippet %}
  {% endif %}


text:
echo -n "Enter your kerberos username > "
read username

echo -n "Enter your kerberos password > "
read password

echo $password | kinit $username

echo -n "Enter the database hostname > "
read database_hostname

echo -n "Enter the HDFS directory from where export the data > "
read hdfs_egress_path

echo -n "Enter the egress RMBS table (where to put data) > "
read rdbms_egress_path

hadoop dfs -mkdir /user/mtazi/samples_result_less2digit_hdfs_dataset
sqoop export --connect jdbc:postgresql://$database_hostname/samples_database --username admin -P --table $rdbms_egress_path --export-dir $hdfs_egress_path --direct --where "result <40"


text:
require 'rails_helper'

RSpec.describe "items/edit", :type => :view do
  before(:each) do
    @item = assign(:item, Item.create!(
      :name => "MyString",
      :image => "MyString",
      :price => 1.5,
      :description => "MyText",
      :category => "MyString",
      :rating => 1
    ))
  end

  it "renders the edit item form" do
    render

    assert_select "form[action=?][method=?]", item_path(@item), "post" do

      assert_select "input#item_name[name=?]", "item[name]"

      assert_select "input#item_image[name=?]", "item[image]"

      assert_select "input#item_price[name=?]", "item[price]"

      assert_select "textarea#item_description[name=?]", "item[description]"

      assert_select "input#item_category[name=?]", "item[category]"

      assert_select "input#item_rating[name=?]", "item[rating]"
    end
  end
end


text:
<?php

namespace Anavel\Crud\Contracts\Abstractor;

interface ModelFactory
{
    /**
     * @return Model
     */
    public function getBySlug($slug, $id = null);

    /**
     * @return Model
     */
    public function getByName($name, $id = null);

    /**
     * @return Model
     */
    public function getByClassName($classname, array $config, $id = null);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Semver;
using Umbraco.Core.Configuration;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Services;

namespace Umbraco.Core.Persistence.Migrations.Initial
{
    public class DatabaseSchemaResult
    {
        public DatabaseSchemaResult()
        {
            Errors = new List<Tuple<string, string>>();
            TableDefinitions = new List<TableDefinition>();
            ValidTables = new List<string>();
            ValidColumns = new List<string>();
            ValidConstraints = new List<string>();
            ValidIndexes = new List<string>();
        }

        public List<Tuple<string, string>> Errors { get; set; }

        public List<TableDefinition> TableDefinitions { get; set; }

        public List<string> ValidTables { get; set; }

        public List<string> ValidColumns { get; set; }

        public List<string> ValidConstraints { get; set; }

        public List<string> ValidIndexes { get; set; }

        internal IEnumerable<DbIndexDefinition> DbIndexDefinitions { get; set; }

        /// <summary>
        /// Checks in the db which version is installed based on the migrations that have been run
        /// </summary>
        /// <param name="migrationEntryService"></param>
        /// <returns></returns>
        public SemVersion DetermineInstalledVersionByMigrations(IMigrationEntryService migrationEntryService)
        {
            SemVersion mostrecent = null;

            if (ValidTables.Any(x => x.InvariantEquals("umbracoMigration")))
            {
                var allMigrations = migrationEntryService.GetAll(GlobalSettings.UmbracoMigrationName);
                 mostrecent = allMigrations.OrderByDescending(x => x.Version).Select(x => x.Version).FirstOrDefault();
            }

            return mostrecent ?? new SemVersion(new Version(0, 0, 0));
        }

        /// <summary>
        /// Determines the version of the currently installed database by detecting the current database structure
        /// </summary>
        /// <returns>
        /// A <see cref="Version"/> with Major and Minor values for
        /// non-empty database, otherwise "0.0.0" for empty databases.
        /// </returns>
        public Version DetermineInstalledVersion()
        {
            //If (ValidTables.Count == 0) database is empty and we return -> new Version(0, 0, 0);
            if (ValidTables.Count == 0)
                return new Version(0, 0, 0);

            //If Errors is empty or if TableDefinitions tables + columns correspond to valid tables + columns then we're at current version
            if (Errors.Any() == false ||
                (TableDefinitions.All(x => ValidTables.Contains(x.Name))
                 && TableDefinitions.SelectMany(definition => definition.Columns).All(x => ValidColumns.Contains(x.Name))))
                return UmbracoVersion.Current;

            //If Errors contains umbracoApp or umbracoAppTree its pre-6.0.0 -> new Version(4, 10, 0);
            if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoApp") || x.Item2.InvariantEquals("umbracoAppTree"))))
            {
                //If Errors contains umbracoUser2app or umbracoAppTree foreignkey to umbracoApp exists its pre-4.8.0 -> new Version(4, 7, 0);
                if (Errors.Any(x =>
                               x.Item1.Equals("Constraint")
                               && (x.Item2.InvariantContains("umbracoUser2app_umbracoApp")
                                   || x.Item2.InvariantContains("umbracoAppTree_umbracoApp"))))
                {
                    return new Version(4, 7, 0);
                }

                return new Version(4, 8, 0);
            }

            //if the error is for umbracoServer
            if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoServer"))))
            {
                return new Version(6, 0, 0);
            }

            //if the error indicates a problem with the column cmsMacroProperty.macroPropertyType then it is not version 7
            // since these columns get removed in v7
            if (Errors.Any(x => x.Item1.Equals("Column") && (x.Item2.InvariantEquals("cmsMacroProperty,macroPropertyType"))))
            {
                //if the error is for this IX_umbracoNodeTrashed which is added in 6.2 AND in 7.1 but we do not have the above columns
                // then it must mean that we aren't on 6.2 so must be 6.1
                if (Errors.Any(x => x.Item1.Equals("Index") && (x.Item2.InvariantEquals("IX_umbracoNodeTrashed"))))
                {
                    return new Version(6, 1, 0);
                }
                else
                {
                    //if there are no errors for that index, then the person must have 6.2 installed
                    return new Version(6, 2, 0);
                }
            }

            //if the error indicates a problem with the constraint FK_cmsContent_cmsContentType_nodeId then it is not version 7.2
            // since this gets added in 7.2.0 so it must be the previous version
            if (Errors.Any(x => x.Item1.Equals("Constraint") && (x.Item2.InvariantEquals("FK_cmsContent_cmsContentType_nodeId"))))
            {
                return new Version(7, 0, 0);
            }

            //if the error is for umbracoAccess it must be the previous version to 7.3 since that is when it is added
            if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoAccess"))))
            {
                return new Version(7, 2, 0);
            }

            //if the error is for umbracoDeployChecksum it must be the previous version to 7.4 since that is when it is added
            if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoDeployChecksum"))))
            {
                return new Version(7, 3, 0);
            }

            //if the error is for umbracoRedirectUrl it must be the previous version to 7.5 since that is when it is added
            if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoRedirectUrl"))))
            {
                return new Version(7, 4, 0);
            }

            return UmbracoVersion.Current;
        }

        /// <summary>
        /// Gets a summary of the schema validation result
        /// </summary>
        /// <returns>A string containing a human readable string with a summary message</returns>
        public string GetSummary()
        {
            var sb = new StringBuilder();
            if (Errors.Any() == false)
            {
                sb.AppendLine("The database schema validation didn't find any errors.");
                return sb.ToString();
            }

            //Table error summary
            if (Errors.Any(x => x.Item1.Equals("Table")))
            {
                sb.AppendLine("The following tables were found in the database, but are not in the current schema:");
                sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Table")).Select(x => x.Item2)));
                sb.AppendLine(" ");
            }
            //Column error summary
            if (Errors.Any(x => x.Item1.Equals("Column")))
            {
                sb.AppendLine("The following columns were found in the database, but are not in the current schema:");
                sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Column")).Select(x => x.Item2)));
                sb.AppendLine(" ");
            }
            //Constraint error summary
            if (Errors.Any(x => x.Item1.Equals("Constraint")))
            {
                sb.AppendLine("The following constraints (Primary Keys, Foreign Keys and Indexes) were found in the database, but are not in the current schema:");
                sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Constraint")).Select(x => x.Item2)));
                sb.AppendLine(" ");
            }
            //Index error summary
            if (Errors.Any(x => x.Item1.Equals("Index")))
            {
                sb.AppendLine("The following indexes were found in the database, but are not in the current schema:");
                sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Index")).Select(x => x.Item2)));
                sb.AppendLine(" ");
            }
            //Unknown constraint error summary
            if (Errors.Any(x => x.Item1.Equals("Unknown")))
            {
                sb.AppendLine("The following unknown constraints (Primary Keys, Foreign Keys and Indexes) were found in the database, but are not in the current schema:");
                sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Unknown")).Select(x => x.Item2)));
                sb.AppendLine(" ");
            }

            if (SqlSyntaxContext.SqlSyntaxProvider is MySqlSyntaxProvider)
            {
                sb.AppendLine("Please note that the constraints could not be validated because the current dataprovider is MySql.");
            }

            return sb.ToString();
        }
    }
}


text:
package com.hyunjae.xdcc.parser;

import com.google.gson.annotations.SerializedName;

public class Pack {

    @SerializedName("b")
    private String botName;
    @SerializedName("n")
    private String packNumber;
    @SerializedName("f")
    private String fileName;
    @SerializedName("s")
    private String fileSize;

    public Pack() {

    }

    public Pack(String botName, String packNumber, String fileName, String fileSize) {
        this.botName = botName;
        this.packNumber = packNumber;
        this.fileName = fileName;
        this.fileSize = fileSize;
    }

    public String getBotName() {
        return botName;
    }

    public void setBotName(String botName) {
        this.botName = botName;
    }

    public String getPackNumber() {
        return packNumber;
    }

    public void setPackNumber(String packNumber) {
        this.packNumber = packNumber;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileSize() {
        return fileSize;
    }

    public void setFileSize(String fileSize) {
        this.fileSize = fileSize;
    }

}


text:
    <form name="form" novalidate enctype="multipart/form-data">

Error: cannot create

Created

                <button type="submit" class="btn btn-success" ng-disabled="form.$invalid || progressBar" ng-click="save(form.eventImage.files)">Create</button>
                <button type="button" class="btn btn-default" ng-click="clear()">Clear</button>
                <button type="button" class="btn btn-default" ng-click="cancel()">Cancel</button>

                    Name
                    <input type="text" name="eventName" required ng-pattern="/^[0-9a-zA-ZА-Яа-яЁё\s\-\,\.\+!;\?\(\)]*$/"
                           class="form-control" ng-model="event.name">

                    Impossible symbols

                    Required

                    City
                    <select class="form-control" ng-model="event.city">
                        <option ng-repeat="city in cityList">{{city}}</option>
                    </select>

                    Description
                    <input type="text" name="eventDescription" class="form-control" ng-pattern="/^[0-9a-zA-ZА-Яа-яЁё\s\-\,\.\+!;\?\(\)]*$/" ng-model="event.description">

                    Impossible symbols

                    About
                    <textarea type="text" name="eventAbout" class="form-control" ng-pattern="/^[0-9a-zA-ZА-Яа-яЁё\s\-\,\.\+!;\?\(\)]*$/"
                           required ng-model="event.about" style="max-width: 100%;"></textarea>

                    Impossible symbols

                    Required

                    Start Time
                    <input type="text" name="eventStartTime" class="form-control" ng-pattern="/^[0-9a-zA-ZА-Яа-яЁё\s\-\,\.\+!;:\?\(\)]*$/" ng-model="event.startTime">

                    Impossible symbols

                    Finish Time
                    <input type="text" name="eventFinishTime" class="form-control" ng-pattern="/^[0-9a-zA-ZА-Яа-яЁё\s\-\,\.\+!;:\?\(\)]*$/" ng-model="event.finishTime">

                    Impossible symbols

                <button type="button" ng-show="imageChanged" class="btn btn-danger item-offset" ng-click="removeImage()">Remove image</button>
                <input type="file" name="eventImage" class="btn btn-primary" onchange="angular.element(this).scope().uploadImage(this.files)" accept="image/jpeg, image/png">

    </form>


text:
"""
Verify that the xcode-ninja GYP_GENERATOR runs and builds correctly.
"""

import TestGyp

import os
import sys

if sys.platform == 'darwin':
  test = TestGyp.TestGyp(formats=['xcode'])

  # Run ninja and xcode-ninja
  test.formats = ['ninja', 'xcode-ninja']
  test.run_gyp('test.gyp', chdir='app-bundle')

  # If it builds the target, it works.
  test.build('test.ninja.gyp', chdir='app-bundle')
  test.pass_test()


text:
<?xml version="1.0"?>
<!--
  ~ Copyright (c) 2010-2017 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<name>midPoint Task Manager - Quartz impl</name>
	<groupId>com.evolveum.midpoint.repo</groupId>
	<artifactId>task-quartz-impl</artifactId>
	<packaging>jar</packaging>
	<parent>
		<artifactId>repo</artifactId>
		<groupId>com.evolveum.midpoint</groupId>
		<version>3.7-SNAPSHOT</version>
	</parent>
    <scm>
        <connection>https://github.com/Evolveum/midpoint.git</connection>
        <developerConnection>git@github.com:Evolveum/midpoint.git</developerConnection>
        <url>https://fisheye.evolveum.com/browse/midPoint</url>
    </scm>
	<dependencies>
		<dependency>
			<groupId>com.evolveum.midpoint.infra</groupId>
			<artifactId>util</artifactId>
			<version>3.7-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>com.evolveum.midpoint.infra</groupId>
			<artifactId>prism</artifactId>
			<version>3.7-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>com.evolveum.midpoint.infra</groupId>
			<artifactId>schema</artifactId>
			<version>3.7-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>com.evolveum.midpoint.infra</groupId>
			<artifactId>common</artifactId>
			<version>3.7-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>com.evolveum.midpoint.repo</groupId>
			<artifactId>repo-api</artifactId>
			<version>3.7-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>com.evolveum.midpoint.repo</groupId>
			<artifactId>task-api</artifactId>
			<version>3.7-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>com.evolveum.midpoint.repo</groupId>
			<artifactId>security-api</artifactId>
			<version>3.7-SNAPSHOT</version>
		</dependency>
        <dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-configuration</groupId>
			<artifactId>commons-configuration</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
    		<groupId>org.quartz-scheduler</groupId>
    		<artifactId>quartz</artifactId>
		</dependency>
		<dependency>
			<groupId>org.jetbrains</groupId>
			<artifactId>annotations-java5</artifactId>
		</dependency>
        <!-- this one is needed to get SQL configuration from the repository -->
        <dependency>
            <groupId>com.evolveum.midpoint.repo</groupId>
            <artifactId>repo-sql-impl</artifactId>
            <version>3.7-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>

        <!--  Testing dependencies  -->
        <dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.evolveum.midpoint.tools</groupId>
			<artifactId>test-ng</artifactId>
			<version>3.7-SNAPSHOT</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.evolveum.midpoint.infra</groupId>
			<artifactId>test-util</artifactId>
			<version>3.7-SNAPSHOT</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<scope>test</scope>
		</dependency>
        <dependency>
            <groupId>com.evolveum.midpoint.repo</groupId>
            <artifactId>audit-impl</artifactId>
            <version>3.7-SNAPSHOT</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.evolveum.midpoint.repo</groupId>
            <artifactId>security-impl</artifactId>
            <version>3.7-SNAPSHOT</version>
            <scope>test</scope>
        </dependency>
        <dependency> <!-- needed as runtime dependency otherwise spring won't start -->
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<scope>test</scope>
		</dependency>
        <dependency> <!-- needed as runtime dependency otherwise spring won't start -->
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<scope>test</scope>
		</dependency>

        <dependency>
			<groupId>com.evolveum.midpoint.repo</groupId>
			<artifactId>repo-test-util</artifactId>
			<version>3.7-SNAPSHOT</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.forgerock.opendj</groupId>
			<artifactId>opendj</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.evolveum.midpoint.repo</groupId>
			<artifactId>system-init</artifactId>
			<version>3.7-SNAPSHOT</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.evolveum.midpoint.repo</groupId>
			<artifactId>repo-sql-impl-test</artifactId>
			<version>3.7-SNAPSHOT</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>log4j-over-slf4j</artifactId>
			<scope>test</scope>
		</dependency>
    </dependencies>

</project>


text:
# program090:
# By using list comprehension, please write a program generate a 3*5*8 3D
# array whose each element is 0.

# Hints:
# Use list comprehension to make an array.

def main(depth, rows, cols):
    array = [[[0 for col in range(cols)]
              for row in range(rows)]
             for dpth in range(depth)]

    print array

if __name__ == '__main__':
    main(3, 5, 8)


text:
<?php
    namespace Album\Controller;
    use Zend\Mvc\Controller\AbstractActionController;
    use Zend\View\Model\ViewModel;
    use Album\Model\Album;
    use Album\Form\AlbumForm;

    class AlbumController extends AbstractActionController
    {
        protected $albumTable;

        public function indexAction()
        {
            return new ViewModel(array(
                'albums' => $this->getAlbumTable()->fetchAll(),
            ));
        }

        public function addAction()
        {
            $form = new AlbumForm();
            $form->get('submit')->setValue('Add');

            $request = $this->getRequest();
            if ($request->isPost()) {
                $album = new Album();
                $form->setInputFilter($album->getInputFilter());
                $form->setData($request->getPost());

                if ($form->isValid()) {
                    $album->exchangeArray($form->getData());
                    $this->getAlbumTable()->saveAlbum($album);

                    return $this->redirect()->toRoute('album');
                }
            }
            return array('form' => $form);
        }

        public function editAction()
        {
            $id=(int)$this->params()->fromRoute('id',0);
            if(!$id){
                return $this->redirect()->toRoute('album',array(
                    'action'=>'add'
                ));
            }
            try{
                $album=$this->getAlbumTable()->getAlbum($id);
            }
            catch(\Exception $ex){
                return $this->redirect()->toRoute('album',array(
                    'action'=>'index'
                ));
            }

            $form= new AlbumForm();
            $form->bind($album);
            $form->get('submit')->setAttribute('value','Edit');

            $request=$this->getRequest();
            if($request->isPost()){
                $form->setInputFilter($album->getInputFilter());
                $form->setData($request->getPost());

                if($form->isValid()){
                    $this->getAlbumTable()->saveAlbum($album);
                    return $this->redirect()->toRoute('album');
                }
            }
            return array(
                'id'=>$id,
                'form'=>$form,
            );

        }

        public function  deleteAction()
        {
            $id=(int)$this->params()->fromRoute('id',0);
            if(!$id){
                return $this->redirect()->toRoute('album');
            }
            $request=$this->getRequest();
            if($request->isPost()){
                $del=$request->getPost('del','No');
                if($del=='Yes'){
                    $id=(int)$request->getPost('id');
                    $this->getAlbumTable()->deleteAlbum($id);
                }
                return $this->redirect()->toRoute('album');
            }
            return array(
                'id'=>$id,
                'album'=>$this->getAlbumTable()->getAlbum($id)
            );
        }

        public function getAlbumTable()
        {
            if (!$this->albumTable) {
                $sm = $this->getServiceLocator();
                $this->albumTable = $sm->get('Album\Model\AlbumTable');
            }
            return $this->albumTable;
        }

    }


text:
package org.osgi.test.cases.transaction;

import javax.transaction.RollbackException;

import org.osgi.test.support.sleep.Sleep;

/**
 * @version $Rev$ $Date$
 *
 * Test transaction manager timeout
 *
 *
 */

public class LengthyTransactionManagerTest extends TransactionTestBundleControl {
    private static final int TOTAL_TRANSACTION_LIFETIME_TIMEOUT = 10;
    private static final int SUITABLE_DELAY = 5;

    public void setUp() throws Exception {
		super.setUp();
        super.setUpTransactionManager();
    }

    public void testTM035() throws Exception {
        try
        {
            tm.setTransactionTimeout(TOTAL_TRANSACTION_LIFETIME_TIMEOUT);
            tm.begin();
			Sleep.sleep(1000 * (TOTAL_TRANSACTION_LIFETIME_TIMEOUT - SUITABLE_DELAY));
        }
        catch (Exception e)
        {
            e.printStackTrace(System.out);
            fail();
        }

        try
        {
            tm.commit();
        }
        catch (Exception e)
        {
            e.printStackTrace(System.out);
            fail();
        }
    }

    public void testTM036() throws Exception {
        try
        {
            tm.setTransactionTimeout(TOTAL_TRANSACTION_LIFETIME_TIMEOUT);
            tm.begin();
			Sleep.sleep(1000 * (TOTAL_TRANSACTION_LIFETIME_TIMEOUT + SUITABLE_DELAY));
        }
        catch (Exception e)
        {
            e.printStackTrace(System.out);
            fail();
        }

        try
        {
            tm.commit();
            fail();
        }
        catch (RollbackException e)
        {
            // As expected
        }
        catch (Exception e)
        {
            e.printStackTrace(System.out);
            fail();
        }
    }

}


text:
package iso20022

// Choice between an indicative price or a market price.
type IndicativeOrMarketPrice8Choice struct {

	// Estimated price, for example, for valuation purposes.
	IndicativePrice *PriceFormat50Choice `xml:"IndctvPric"`

	// Last reported/known price of a financial instrument in a market.
	MarketPrice *PriceFormat50Choice `xml:"MktPric"`
}

func (i *IndicativeOrMarketPrice8Choice) AddIndicativePrice() *PriceFormat50Choice {
	i.IndicativePrice = new(PriceFormat50Choice)
	return i.IndicativePrice
}

func (i *IndicativeOrMarketPrice8Choice) AddMarketPrice() *PriceFormat50Choice {
	i.MarketPrice = new(PriceFormat50Choice)
	return i.MarketPrice
}


text:
<?php

require_once 'PHPUnit/Framework/TestCase.php';
require_once 'model/Column.php';
require_once 'builder/util/XmlToAppData.php';
require_once 'platform/MysqlPlatform.php';

/**
 * Tests for package handling.
 *
 * @author     Martin Poeschl
 * @version    $Revision: 1612 $
 * @package    generator.model
 */
class ColumnTest extends PHPUnit_Framework_TestCase {

	/**
	 * Tests static Column::makeList() method.
	 * @deprecated - Column::makeList() is deprecated and set to be removed in 1.3
	 */
	public function testMakeList()
	{
		$expected = "`Column0`, `Column1`, `Column2`, `Column3`, `Column4`";
		$objArray = array();
		for ($i=0; $i<5; $i++) {
			$c = new Column();
			$c->setName("Column" . $i);
			$objArray[] = $c;
		}

		$list = Column::makeList($objArray, new MySQLPlatform());
		$this->assertEquals($expected, $list, sprintf("Expected '%s' match, got '%s' ", var_export($expected, true), var_export($list,true)));

		$strArray = array();
		for ($i=0; $i<5; $i++) {
			$strArray[] = "Column" . $i;
		}

		$list = Column::makeList($strArray, new MySQLPlatform());
		$this->assertEquals($expected, $list, sprintf("Expected '%s' match, got '%s' ", var_export($expected, true), var_export($list,true)));

	}

	public function testPhpNamingMethod()
	{
		set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
		Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
	  $bookTmap = Propel::getDatabaseMap(BookPeer::DATABASE_NAME)->getTable(BookPeer::TABLE_NAME);
	  $this->assertEquals('AuthorId', $bookTmap->getColumn('AUTHOR_ID')->getPhpName(), 'setPhpName() uses the default phpNamingMethod');
	  $pageTmap = Propel::getDatabaseMap(PagePeer::DATABASE_NAME)->getTable(PagePeer::TABLE_NAME);
	  $this->assertEquals('LeftChild', $pageTmap->getColumn('LEFTCHILD')->getPhpName(), 'setPhpName() uses the configured phpNamingMethod');
	}

	public function testGetConstantName()
	{
		$xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null);
    $appData = $xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml');
    $column = $appData->getDatabase("bookstore-behavior")->getTable('table1')->getColumn('title');
    $this->assertEquals('Table1Peer::TITLE', $column->getConstantName(), 'getConstantName() returns the complete constant name by default');
	}

	public function testIsLocalColumnsRequired()
	{
		$xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null);
		$appData = $xmlToAppData->parseFile('fixtures/bookstore/schema.xml');
		$fk = $appData->getDatabase("bookstore")->getTable('book')->getColumnForeignKeys('publisher_id');
		$this->assertFalse($fk[0]->isLocalColumnsRequired());
		$fk = $appData->getDatabase("bookstore")->getTable('review')->getColumnForeignKeys('book_id');
		$this->assertTrue($fk[0]->isLocalColumnsRequired());
	}

}


text:
package org.apache.polygene.tools.model.descriptor;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import org.apache.polygene.api.sideeffect.SideEffectDescriptor;

public final class MethodSideEffectDetailDescriptor
    implements InjectableDetailDescriptor
{
    private final SideEffectDescriptor descriptor;
    private MethodSideEffectDetailDescriptor sideEffects;

    private final List<ConstructorDetailDescriptor> constructors;
    private final List<InjectedMethodDetailDescriptor> injectedMethods;
    private final List<InjectedFieldDetailDescriptor> injectedFields;

    MethodSideEffectDetailDescriptor( SideEffectDescriptor aDescriptor )
        throws IllegalArgumentException
    {
        Objects.requireNonNull( aDescriptor, "aDescriptor" );
        descriptor = aDescriptor;
        constructors = new LinkedList<>();
        injectedMethods = new LinkedList<>();
        injectedFields = new LinkedList<>();
    }

    /**
     * @return Descriptor of this {@code MethodSideEffectDetailDescriptor}. Never returns {@code null}.
     *
     * @since 0.5
     */
    public final SideEffectDescriptor descriptor()
    {
        return descriptor;
    }

    /**
     * @return Method side effects that owns this {@code MethodSideEffectDetailDescriptor}. Never returns {@code null}.
     *
     * @since 0.5
     */
    public final MethodSideEffectDetailDescriptor sideEffects()
    {
        return sideEffects;
    }

    /**
     * @return Constructors of this {@code MethodSideEffectDetailDescriptor}. Never return {@code null}.
     *
     * @since 0.5
     */
    @Override
    public final Iterable<ConstructorDetailDescriptor> constructors()
    {
        return constructors;
    }

    /**
     * @return Injected methods of this {@code MethodSideEffectDetailDescriptor}. Never return {@code null}.
     *
     * @since 0.5
     */
    @Override
    public final Iterable<InjectedMethodDetailDescriptor> injectedMethods()
    {
        return injectedMethods;
    }

    /**
     * @return Injected fields of this {@code MethodSideEffectDetailDescriptor}. Never return {@code null}.
     *
     * @since 0.5
     */
    @Override
    public final Iterable<InjectedFieldDetailDescriptor> injectedFields()
    {
        return injectedFields;
    }

    final void setSideEffects( MethodSideEffectDetailDescriptor aDescriptor )
    {
        Objects.requireNonNull( aDescriptor, "aDescriptor" );
        sideEffects = aDescriptor;
    }

   @Override
   public String toString()
   {
      return descriptor.modifierClass().getName();
   }

   final void addConstructor( ConstructorDetailDescriptor aDescriptor )
        throws IllegalArgumentException
    {
        Objects.requireNonNull( aDescriptor, "aDescriptor" );

        aDescriptor.setMethodSideEffect( this );
        constructors.add( aDescriptor );
    }

    final void addInjectedMethod( InjectedMethodDetailDescriptor aDescriptor )
        throws IllegalArgumentException
    {
        Objects.requireNonNull( aDescriptor, "aDescriptor" );

        aDescriptor.setMethodSideEffect( this );
        injectedMethods.add( aDescriptor );
    }

    final void addInjectedField( InjectedFieldDetailDescriptor aDescriptor )
        throws IllegalArgumentException
    {
        Objects.requireNonNull( aDescriptor, "aDescriptor" );

        aDescriptor.setMethodSideEffect( this );
        injectedFields.add( aDescriptor );
    }

    public JsonObjectBuilder toJson()
    {
        JsonObjectBuilder builder = Json.createObjectBuilder();
        builder.add( "fragment", descriptor().modifierClass().getName() );
        JsonObjectBuilder injectionBuilder = Json.createObjectBuilder();
        {
            JsonArrayBuilder constructorsBuilder = Json.createArrayBuilder();
            constructors().forEach( constructor -> constructorsBuilder.add( constructor.toJson() ) );
            builder.add( "constructors", constructorsBuilder );
        }
        builder.add( "injection", injectionBuilder );
        {
            JsonArrayBuilder injectedFieldsBuilder = Json.createArrayBuilder();
            injectedFields().forEach( field -> injectedFieldsBuilder.add( field.toJson() ) );
            injectionBuilder.add( "fields", injectedFieldsBuilder );
        }
        {
            JsonArrayBuilder injectedMethodsBuilder = Json.createArrayBuilder();
            injectedMethods().forEach( method -> injectedMethodsBuilder.add( method.toJson() ) );
            injectionBuilder.add( "methods", injectedMethodsBuilder );
        }
        return builder;
    }
}