text:
__author__ = 'tylin'
from tokenizer.ptbtokenizer import PTBTokenizer
from bleu.bleu import Bleu
from meteor.meteor import Meteor
from rouge.rouge import Rouge
from cider.cider import Cider

class COCOEvalCap:
    def __init__(self, coco, cocoRes):
        self.evalImgs = []
        self.eval = {}
        self.imgToEval = {}
        self.coco = coco
        self.cocoRes = cocoRes
        self.params = {'image_id': coco.getImgIds()}

    def evaluate(self):
        imgIds = self.params['image_id']
        # imgIds = self.coco.getImgIds()
        gts = {}
        res = {}
        for imgId in imgIds:
            gts[imgId] = self.coco.imgToAnns[imgId]
            res[imgId] = self.cocoRes.imgToAnns[imgId]

        # =================================================
        # Set up scorers
        # =================================================
        print 'tokenization...'
        tokenizer = PTBTokenizer()
        gts  = tokenizer.tokenize(gts)
        res = tokenizer.tokenize(res)

        # =================================================
        # Set up scorers
        # =================================================
        print 'setting up scorers...'
        scorers = [
            (Bleu(4), ["Bleu_1", "Bleu_2", "Bleu_3", "Bleu_4"]),
            (Meteor(),"METEOR"),
            (Rouge(), "ROUGE_L"),
            (Cider(), "CIDEr")
        ]

        # =================================================
        # Compute scores
        # =================================================
        for scorer, method in scorers:
            print 'computing %s score...'%(scorer.method())
            score, scores = scorer.compute_score(gts, res)
            if type(method) == list:
                for sc, scs, m in zip(score, scores, method):
                    self.setEval(sc, m)
                    self.setImgToEvalImgs(scs, gts.keys(), m)
                    print "%s: %0.3f"%(m, sc)
            else:
                self.setEval(score, method)
                self.setImgToEvalImgs(scores, gts.keys(), method)
                print "%s: %0.3f"%(method, score)
        self.setEvalImgs()

    def setEval(self, score, method):
        self.eval[method] = score

    def setImgToEvalImgs(self, scores, imgIds, method):
        for imgId, score in zip(imgIds, scores):
            if not imgId in self.imgToEval:
                self.imgToEval[imgId] = {}
                self.imgToEval[imgId]["image_id"] = imgId
            self.imgToEval[imgId][method] = score

    def setEvalImgs(self):
        self.evalImgs = [eval for imgId, eval in self.imgToEval.items()]


text:
layout:     post
title:      "Whats-new-Unity2018"
subtitle:   "来看看Unity2018有哪些新特性"
date:       2018-05-31 14:18:00
author:     "ly"
header-img: "img/post-bg-Unity.jpg"
tags:
    - 翻译
---

> [原地址](https://unity3d.com/cn/unity/whats-new/unity-2018.1.0?_ga=2.28675386.782122071.1527747503-1549264406.1483410723)

# **发行说明**

## 系统要求变化

* Windows独立平台:不再支持Windows XP,仅支持Windows Vista以上的系统
* 弃用MonoDevelop,推荐使用VisualStudio来写C#代码在macOS和Windows平台

## 包体

* Services: Updated Unity Ads (com.unity.ads) to v2.0.7.

  - Note that this is not to be confused with the Unity Ads SDK version, which is v2.1.1.
    Services: Updated Analytics (com.unity.analytics) to v2.0.16

* Services: Updated IAP (com.unity.purchasing) to v2.0.1

* Services: Updated Standard Events (com.unity.standardevents) to v1.0.13

* Editor: Added Package Manager UI (com.unity.package-manager-ui) at v1.8.8

  - Note that versions 1.8.X of the package are verified for use with 2018.1. Versions 1.9.x (or newer) may be available for download via the Package   Manager UI itself, but are not officially verified for 2018.1.
  - See entry in Features section for further details.

## 特性

* 2D: [试验]添加试验的API来支持Sprite动画

* 2D: [试验]添加可以自定义功能的Sprite Editor Window

* Android: 新增一个接口,IPostGenerateGradleAndroidProject,包含一个在生成Android Gradle project之后,构建之前的回调

* Android: 添加一个新的设置,Sustained Performance Mode,which sets a predictable, consistent level of device performance over longer periods of time
without thermal throttling.

* Android: 添加ARM64(或叫AArch64)支持(试验)

* Animation: 添加 **Position Constraint**,**Rotation Constraint** 和 **Scale Constraint** 组件

* Animation: 添加新的**Parent Constraint**组件

* Animation: 添加新的**Aim Constraint**组件

* Animation: AnimationCurve添加加权tangent支持

* Animation: Constraint Activation

* Animation: Constraint Creation

* Asset Import: 支持从FBX导入Aim constraints

* Asset Import: 支持从FBX导入Parent Constraints

* Asset Import: 支持从FBX导入Point, Orient and Scale constraints

* Asset Import: 添加**OnPreprocessAsset**回调在**AssetPostprocessor**

* Asset Import: [试验] 添加试验的API来从Importer Settings生成Textures/Sprites

* Audio: 添加Google's Resonance Audio插件

* Build Pipeline: 添加可以用EditorBuildSettings通过名字存储或恢复GameObject引用的能力

* Build Pipeline: 添加新的API来修改平台图标。[PlayerSettings.SetPlatformIcons]
(https://docs.unity3d.com/2018.1/Documentation/ScriptReference/PlayerSettings.SetPlatformIcons.html?_ga=2.5891637.782122071.1527747503-1549264406.1483410723)

* Build Pipeline: 添加新的 BuildReport API。Building Players和AssetBundles可以返回BuildReport让你可以查看构建信息和输出信息

* Cache Server: 添加 -CacheServerIPAddress 的命令行参数来用于编辑器启动时连接特定的Cache Server

* Editor: Added a Clear on play button to the Unity Profiler window.

* Editor: Added a preset class that allows you to save serialized information about a GameObject to a .preset Asset, and apply it later to the same GameObject type.

* Editor: Added new ObjectFactory API that allows you to create a GameObject using default values. See Scripting API and documentation on **Presets** for more details.

* Editor: Added Templates for 3D, 2D, 3D with Extras (Preview), Lightweight (Preview), Lightweight VR (Preview), and High Definition (Preview) to streamline the new user experience with Scriptable Render Pipeline features, as well as to define better starting points for graphical, player, and lighting settings.

* Editor: Unity now compiles Assembly Definition File (asmdef) assemblies on startup, before any other scripts (such as Assembly-CSharp.dll), and does not stop compilation on the first compile error. Uniy loads all asmdef assemblies that succesfully compile and have all their references compiled, then compiles the remaining scripts (Assembly-CSharp.dll and friends). This ensures that Unity packages are always built and and loaded, regardless of other compile errors in the Project.

* Editor: When running PlayMode and EditMode tests in batch mode, you can now specify which scripting back-end to use, via a Test Settings file.

* GI: Progressive Lightmapper is now out of preview!

* GI: [Experimental] Added experimental API for baking sky occlusion in Progressive Lightmapper. The sky occlusion value for a given input position defines what fraction of the sky is visible for that point. It takes into account any static GameObjects. The sky occlusion allows you to apply the correct amount of sky lighting to GameObjects that are otherwise hard to lightmap, such as trees and foliage.

* GI: [Experimental] Added new experimental C# interface to pass light information to the GI baking back-ends.

* Graphics: Added dynamic resolution support for Playstation 4.

* Graphics: GPU Instancing now supports GI.
- Unity can now automatically batch GameObjects affected by Light Probes, Occlusion Probes (in Shadowmask mode) or lightmaps, with Foward and Deferred pipeline.
- Unity can send Light Probe and Occlusion Probe data to Graphics.DrawMeshInstanced using the LightProbeUsage.CustomProvided mode.
- Added New APIs to calculate probe data and copy it to MaterialPropertyBlock: LightProbes.CalculateInterpolatedLightAndOcclusionProbes, MaterialPropertyBlock.CopySHCoefficientArrayFrom, MaterialPropertyBlock.CopyProbeOcclusionArrayFrom.

* Graphics: Metal: Added support for tessellation using DX11 convention through hull/domain shader stages.

* Graphics: [Preview] High Definition (HD) Render Pipeline (in preview for 2018.1): a modern renderer built on the Scriptable Render Pipeline (SRP).
- See documentation here:[High Definition Render Pipeline overview](https://github.com/Unity-Technologies/ScriptableRenderPipeline/wiki/High-Definition-Render-Pipeline-overview)
- Blogpost:[The High Definition Render Pipeline: Focused on visual quality](https://blogs.unity3d.com/cn/2018/03/16/the-high-definition-render-pipeline-focused-on-visual-quality/?_ga=2.32131640.782122071.1527747503-1549264406.1483410723)
* Launcher: The launcher now allows users to select one of the new project templates when creating new projects. Project templates available currently: 2D, 3D, 3D With Extras (Preview), Lightweight (Preview), Lightweight VR (Preview), and High Definition (Preview).

* Multiplayer: You can now set Unity up to send you notifications about defined callbacks when there is something to read or the connection is ready to send information.

* OSX: Added support for IL2CPP scripting backend for Mac Standalone player.

* Package Manager: Added Package Manager User Interface to allow you to manage a Project's packages and discover new packages.

* Particles: 为粒子系统的面片渲染添加GPU instancing支持

* Particles: Added support for Orbital Velocity to the **Velocity over Lifetime** module.

* Particles: All Particle Emitter shapes now support reading a Texture for masking and color tinting.

* Physics: 2D Physics can now use all the cores on a device to run its simulation. See **Job Options (Experimental)** in 2D Physics Settings.

* Player:新增一个实验API,**UnityEngine.Experimental.LowLevel.PlayerLoop** 它让你可以改变Unity生命周期里调用引擎系统,删除引擎系统或者插入一个新的入口到生命周期中。

* Scripting: Added a new command line option, overrideMonoSearchPath, for desktop standalone players (OSX, Windows). This specifies an extra folder to search when Mono is loading assemblies. You can use this to re-use Assets but load different scripts.

* Scripting Upgrade: Added support for Portable PDBs when running with the new scripting runtime.

* Video: Added audio sample output API for the VideoPlayer, with support for access from C# or C++.

* Video: Added support for reading videos from AssetBundles on Android.

* Web: 为UnityWebRequest添加自定义证书验证支持. See **CertificateHandler** script documentation for more info.

* Web: Added UploadHandlerFile for UnityWebRequest. This sends file contents as a request body, without loading the entire file to memory.

* Windows: Added support for IL2CPP scripting backend for Windows Standalone player.

* XR: Added 360-degree stereo image capturing, with support for converting rendered textures (cubemap) to stereo and mono equi-rectangular format for display in VR. Added new API: RenderTexture.ConvertToEquirect().

* XR: Added a new option in the Windows MR Player Settings called Enable Depth Buffer Sharing. This allows the OS to better stabilize images without the need to manually set the focus plane.

* XR: Added Standalone player support for stereoscopic 360-degree image capture for VR and non-VR projects on Win64/macOS platforms.
- Use the 360 Stereo Capture UI checkbox in the VR Editor Settings panel to generate 360-degree capture shader variants when building a Standalone Player.
- Added PlayerSettings.enable360StereoCapture binding.

* XR: Added support for capturing stereoscopic 360-degree images for VR and non-VR projects. Added omni-directional stereo (ODS) support in the Shader pipeline for rendering to 360-degree stereo cubemap.
- Added support for 360-degree stereo cubemap rendering in forward/deferred pipelines, directional/point light shadows, Skybox, MSAA, HDR and post-processing stack.
- Added ODS rendering support for screenspace shadows via separate ODS world space passes and render textures, to avoid incorrect shadows per eye.
- Added stereo RenderToCubemap API script support: camera.RenderToCubemap with stereo eye parameter.

## 无法向后兼容的变化

* Particles: 删除旧的Particle System脚本绑定

* Tizen: Removed Tizen mobile support.

## Changes

* Android: Input field character now always appears at the end of text when opening keyboard.[(966477)](https://issuetracker.unity3d.com/issues/android-caret-is-always-at-the-beginning-of-existing-text-when-selecting-inputfield-with-line-type-set-to-multi-line?_ga=2.40610980.782122071.1527747503-1549264406.1483410723)

* Android: Newly created projects now default to ARMv7 CPU architecture.

* Android: Removed support for UnityPlayerProxyActivity.

* Android: SDK Platform 26 now required to build for Android.

* Android: Unity now creates a 2048-bit RSA key for signing the APK.

* Android: Updated JDK requirements to JDK 8. This a requirement from the latest Android SDK.

* Animation: Starting play mode while editing an Avatar configuration will no longer change the current scene. [(916586)](https://issuetracker.unity3d.com/issues/entering-play-mode-while-editing-avatar-throws-invalidoperationexception-error?_ga=2.2286134.782122071.1527747503-1549264406.1483410723)

* Audio: Added error message when calling AudioSource.GetSpectrumData or AudioListener.GetSpectrumData with float arrays that are not a power of 2 or are outside the valid range between 64 and 8192 samples. [(827154)](https://issuetracker.unity3d.com/issues/audio-error-executing-m-drygroup-getspectrum-when-using-array-with-a-length-that-is-not-a-power-of-2?_ga=2.2286134.782122071.1527747503-1549264406.1483410723)

* Editor: 添加 InspectorWindow.OnPostHeaderGUI 回调来在inspector window中画自定义 GUI 元素.

* Editor: Compiling 'unsafe' C# code now requires the "Allow 'unsafe' code" option to be enabled in the player settings for predefined assemblies (Assembly-CSharp.dll, etc.) and in the inspector for Assembly Definition Files assemblies. Enabling this option will make Unity pass the /unsafe option to the C# compiler when compiling scripts.

* Editor: Removed MonoDevelop 5.9.6 from macOS and Windows installers and deprecated support for it in Unity. Visual Studio for Mac is installed as the C# code editor on macOS and Visual Studio 2017 Community on Windows.

* Editor: Removed the "Intensity" float field next to HDR texture fields in Material editors. Use the exposure controls in the Color Picker instead.

* Editor: Substituted "intensity" float field in the Static Emissives tab of the Light Explorer for HDR color field; instead use the exposure controls in Color Picker.

* Editor: The plug-in code that creates Textures used in rendering with IMGUI should now avoid specifying them in linear space (i.e. should set the linear parameter to false in the Texture2D constructor). Otherwise, GUI elements drawn with such textures might look washed out when the project is working in Linear space (Player Settings > Color space: Linear). (908904)

* GI: s Support for hiding and disabling GI featurewhen making a render pipeline.

* Graphics: Deprecated PlayerSettings.defaultIsFullscreen. Use PlayerSettings.fullscreenMode instead.

* Graphics: GraphicsSettings shaders 不再启动时加载.

* Graphics: Metal tessellation: Improved shader importing error reporting for when features are unsupported.

* IL2CPP: Deprecated BuildOptions.IL2CPP, which never actually did anything. [(986326)](https://issuetracker.unity3d.com/issues/buildplayer-with-buildoptions-dot-il2cpp-does-not-output-an-il2cpp-build?_ga=2.31107641.782122071.1527747503-1549264406.1483410723)

* iOS: Increased min target iOS version to 8.0.

* iOS: iOS now links with Security framework by default. To remove it, set a pre-processor define DISABLE_WEBREQUEST_CERTIFICATE_CALLBACK and remove "Security" from the list of linked frameworks in Xcode.

* iOS: ScreenOrientation.Unknown 弃用.

* OSX: Metal is now the default graphics backend for Editor.

* Package Manager: Unity Package Manager project sub-folder was moved from UnityPackageManager to Packages. This is to align the physical path with the logical path of packages. Notes:
- Projects configured with a NuGet should change their configuration to point to another folder (default repository path for NuGet configuration is \packages). The risk of NuGet and Unity Package Manager sharing the Packages folder is minimal, but we suggest to separate them nonetheless to avoid any issues.
- When opening a project created with a previous version, a migration flow will copy the content of the UnityPackageManager folder to the Packages folder. It is left to the project maintainer to erase the UnityPackageManager folder and update source control configuration.

* Services: Replaced web-based Collab history window with improved RMGUI version.

* Substance: Built-in support for Substance Designer materials is deprecated in Unity 2017.3, and will be removed in 2018.1. To continue using Substance Designer materials in Unity 2018.1, you will need to install a suitable third-party external importer from the Asset Store.

* Universal Windows Platform: Build & Run now defaults to 64-bit player when running on local machine.

* **重要**Web: AssetBundle-related parts of UnityWebRequest have been split into a new module, allowing UnityWebRequest to be used without pulling in AssetBundle module. API change: UnityWebRequest.GetAssetBundle -> UnityWebRequestAssetBundle.GetAssetBundle.

* WebGL: Removed experimental label from WebAssembly linker target.

* Windows: Removed support for Windows XP in Standalone Player builds. Windows Vista is the minimum supported OS now.

* Windows: The Build Player location selection dialog now asks for a folder rather than a file name when building Windows standalone player. The BuildPipeline.BuildPlayer API is not affected by this change. [(995320)](https://issuetracker.unity3d.com/issues/windows-standalone-build-getting-more-stuff-dumped-into-root-build-folder?_ga=2.208962964.782122071.1527747503-1549264406.1483410723)

* XR: Standalone UWP applications targeting Windows Mixed Reality now cause the OS to notify you if the Mixed Reality components are not installed or a headset is not connected, rather than silently falling back to non-VR desktop mode.

## 改进

redpajama_set_name: RedPajamaGithub


text:
 1. Please do not send pull requests to the `stable` branch.

 1. Please [create a new ticket](https://github.com/yapapaya/jquery-cloneya/issues/new) before setting out to add new features or enhancements, so that we may discuss it. Any pull requests without such discussions may not be accepted.

 1. If fixing a bug, [create a new ticket](https://github.com/yapapaya/jquery-cloneya/issues/new) describing the bug and refer the ticket number in the commit message.

 1. Please run all the unit tests by running `grunt` before committing and sending pull requests.

 1. If adding or modifying a feature, be sure to update:

  1. the appropriate [QUnit](http://qunitjs.com/) unit tests in *tests/jquery-cloneya.html*.
  1. the appropriate demo in *demo/index.html*.
  1. the [Wiki](https://github.com/yapapaya/jquery-cloneya/wiki)
  1. the examples in the `gh-pages` branch that shows up on [the pages here](http://yapapaya.github.io/jquery-cloneya/)

 1. If for some reason, you can't do 3 and 4, let us know by creating a new ticket. If you don't, the pull request won't be accepted (sorry!). 1 and 2 are absolute must.


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

namespace DouduckGame.EventManager {
    public class EventSubject<T> : EventSubjectBase where T : struct, IConvertible {
        protected List<EventObserver<T>> m_Observers = new List<EventObserver<T>> ();
        private Dictionary<T, Action<T, EventArgs>> m_Callbacks = new Dictionary<T, Action<T, EventArgs>> ();

        public EventSubject () {
            if (!typeof (T).IsEnum) {
                throw new ArgumentException ("T must be an enumerated type");
            }
        }

        protected void AddCallback (T eventCode, Action<T, EventArgs> observerCallback) {
            if (m_Callbacks.ContainsKey (eventCode)) {
                m_Callbacks[eventCode] += observerCallback;
            } else {
                m_Callbacks.Add (eventCode, observerCallback);
            }
        }

        protected void RemoveCallback (T eventCode, Action<T, EventArgs> observerCallback) {
            if (m_Callbacks.ContainsKey (eventCode)) {
                m_Callbacks[eventCode] -= observerCallback;
                if (m_Callbacks[eventCode] == null) {
                    m_Callbacks.Remove (eventCode);
                }
            }
        }

        public virtual EventObserver<T> RegisterCallback (T eventCode, Action<T, EventArgs> observerCallback) {
            AddCallback (eventCode, observerCallback);
            EventObserver<T> newObserver_ = new EventObserver<T> (eventCode, observerCallback);
            m_Observers.Add (newObserver_);
            return newObserver_;
        }

        public virtual void UnregisterCallback (T eventCode, Action<T, EventArgs> observerCallback) {
            RemoveCallback (eventCode, observerCallback);
            for (int i = m_Observers.Count - 1; i >= 0; i--) {
                if (m_Observers[i].EventCode.Equals(eventCode) && m_Observers[i].Callback == observerCallback) {
                    m_Observers.RemoveAt (i);
                    return; // only remove one observer
                }
            }
        }

        public virtual void Notify (T eventCode, EventArgs eventArgs, bool useMultiple = false) {
            if (m_Callbacks.ContainsKey (eventCode)) {
                m_Callbacks[eventCode] (eventCode, eventArgs);
            }
        }

        public virtual void KillObserverByEventId (T eventCode) {
            for (int i = m_Observers.Count - 1; i >= 0; i--) {
                if (m_Observers[i].EventCode.Equals(eventCode)) {
                    m_Observers.RemoveAt (i);
                }
            }
            if (m_Callbacks.ContainsKey (eventCode)) {
                m_Callbacks.Remove (eventCode);
            }
        }

        public virtual void KillObserverById (int id) {
            for (int i = m_Observers.Count - 1; i >= 0; i--) {
                if (m_Observers[i].Id == id) {
                    RemoveCallback (m_Observers[i].EventCode, m_Observers[i].Callback);
                    m_Observers.RemoveAt (i);
                }
            }
        }

        public virtual void KillObserverByTarget (object target) {
            for (int i = m_Observers.Count - 1; i >= 0; i--) {
                if (m_Observers[i].Callback.Target == target) {
                    RemoveCallback (m_Observers[i].EventCode, m_Observers[i].Callback);
                    m_Observers.RemoveAt (i);
                }
            }
        }

        public virtual void KillAllObserver () {
            m_Observers.Clear ();
            m_Callbacks.Clear ();
        }
    }
}


text:
import asyncio
import collections
import datetime
import json
import re
import tempfile
import warnings
from email.utils import parsedate
from types import MappingProxyType
from urllib.parse import parse_qsl

from multidict import CIMultiDict, MultiDict, MultiDictProxy
from yarl import URL

from . import hdrs, multipart
from .helpers import HeadersMixin, SimpleCookie, reify, sentinel
from .web_exceptions import HTTPRequestEntityTooLarge

__all__ = ('BaseRequest', 'FileField', 'Request')

FileField = collections.namedtuple(
    'Field', 'name filename file content_type headers')

############################################################
# HTTP Request
############################################################

class BaseRequest(collections.MutableMapping, HeadersMixin):

    POST_METHODS = {hdrs.METH_PATCH, hdrs.METH_POST, hdrs.METH_PUT,
                    hdrs.METH_TRACE, hdrs.METH_DELETE}

    def __init__(self, message, payload, protocol, writer, time_service, task,
                 *, secure_proxy_ssl_header=None, client_max_size=1024**2):
        self._message = message
        self._protocol = protocol
        self._transport = protocol.transport
        self._writer = writer

        self._payload = payload
        self._headers = message.headers
        self._method = message.method
        self._version = message.version
        self._rel_url = message.url
        self._post = None
        self._read_bytes = None

        self._secure_proxy_ssl_header = secure_proxy_ssl_header
        self._time_service = time_service
        self._state = {}
        self._cache = {}
        self._task = task
        self._client_max_size = client_max_size

    def clone(self, *, method=sentinel, rel_url=sentinel,
              headers=sentinel):
        """Clone itself with replacement some attributes.

        Creates and returns a new instance of Request object. If no parameters
        are given, an exact copy is returned. If a parameter is not passed, it
        will reuse the one from the current request object.

        """

        if self._read_bytes:
            raise RuntimeError("Cannot clone request "
                               "after reading it's content")

        dct = {}
        if method is not sentinel:
            dct['method'] = method
        if rel_url is not sentinel:
            rel_url = URL(rel_url)
            dct['url'] = rel_url
            dct['path'] = str(rel_url)
        if headers is not sentinel:
            dct['headers'] = CIMultiDict(headers)
            dct['raw_headers'] = tuple((k.encode('utf-8'), v.encode('utf-8'))
                                       for k, v in headers.items())

        message = self._message._replace(**dct)

        return self.__class__(
            message,
            self._payload,
            self._protocol,
            self._writer,
            self._time_service,
            self._task,
            secure_proxy_ssl_header=self._secure_proxy_ssl_header)

    @property
    def task(self):
        return self._task

    @property
    def protocol(self):
        return self._protocol

    @property
    def transport(self):
        return self._protocol.transport

    @property
    def writer(self):
        return self._writer

    @property
    def message(self):
        return self._message

    @property
    def rel_url(self):
        return self._rel_url

    # MutableMapping API

    def __getitem__(self, key):
        return self._state[key]

    def __setitem__(self, key, value):
        self._state[key] = value

    def __delitem__(self, key):
        del self._state[key]

    def __len__(self):
        return len(self._state)

    def __iter__(self):
        return iter(self._state)

    ########

    @property
    def scheme(self):
        """A string representing the scheme of the request.

        'http' or 'https'.
        """
        return self.url.scheme

    @reify
    def _scheme(self):
        if self._transport.get_extra_info('sslcontext'):
            return 'https'
        secure_proxy_ssl_header = self._secure_proxy_ssl_header
        if secure_proxy_ssl_header is not None:
            header, value = secure_proxy_ssl_header
            if self.headers.get(header) == value:
                return 'https'
        return 'http'

    @property
    def method(self):
        """Read only property for getting HTTP method.

        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.
        """
        return self._method

    @property
    def version(self):
        """Read only property for getting HTTP version of request.

        Returns aiohttp.protocol.HttpVersion instance.
        """
        return self._version

    @reify
    def host(self):
        """Read only property for getting *HOST* header of request.

        Returns str or None if HTTP request has no HOST header.
        """
        return self._message.headers.get(hdrs.HOST)

    @reify
    def url(self):
        return URL('{}://{}{}'.format(self._scheme,
                                      self._message.headers.get(hdrs.HOST),
                                      str(self._rel_url)))

    @property
    def path(self):
        """The URL including *PATH INFO* without the host or scheme.

        E.g., ``/app/blog``
        """
        return self._rel_url.path

    @reify
    def path_qs(self):
        """The URL including PATH_INFO and the query string.

        E.g, /app/blog?id=10
        """
        return str(self._rel_url)

    @property
    def raw_path(self):
        """ The URL including raw *PATH INFO* without the host or scheme.
        Warning, the path is unquoted and may contains non valid URL characters

        E.g., ``/my%2Fpath%7Cwith%21some%25strange%24characters``
        """
        return self._message.path

    @property
    def query(self):
        """A multidict with all the variables in the query string."""
        return self._rel_url.query

    @property
    def GET(self):
        """A multidict with all the variables in the query string."""
        warnings.warn("GET property is deprecated, use .query instead",
                      DeprecationWarning)
        return self._rel_url.query

    @property
    def query_string(self):
        """The query string in the URL.

        E.g., id=10
        """
        return self._rel_url.query_string

    @property
    def headers(self):
        """A case-insensitive multidict proxy with all headers."""
        return self._headers

    @property
    def raw_headers(self):
        """A sequence of pars for all headers."""
        return self._message.raw_headers

    @reify
    def if_modified_since(self, _IF_MODIFIED_SINCE=hdrs.IF_MODIFIED_SINCE):
        """The value of If-Modified-Since HTTP header, or None.

        This header is represented as a `datetime` object.
        """
        httpdate = self.headers.get(_IF_MODIFIED_SINCE)
        if httpdate is not None:
            timetuple = parsedate(httpdate)
            if timetuple is not None:
                return datetime.datetime(*timetuple[:6],
                                         tzinfo=datetime.timezone.utc)
        return None

    @property
    def keep_alive(self):
        """Is keepalive enabled by client?"""
        return not self._message.should_close

    @property
    def time_service(self):
        """Time service"""
        return self._time_service

    @reify
    def cookies(self):
        """Return request cookies.

        A read-only dictionary-like object.
        """
        raw = self.headers.get(hdrs.COOKIE, '')
        parsed = SimpleCookie(raw)
        return MappingProxyType(
            {key: val.value for key, val in parsed.items()})

    @property
    def http_range(self, *, _RANGE=hdrs.RANGE):
        """The content of Range HTTP header.

        Return a slice instance.

        """
        rng = self._headers.get(_RANGE)
        start, end = None, None
        if rng is not None:
            try:
                pattern = r'^bytes=(\d*)-(\d*)$'
                start, end = re.findall(pattern, rng)[0]
            except IndexError:  # pattern was not found in header
                raise ValueError("range not in acceptible format")

            end = int(end) if end else None
            start = int(start) if start else None

            if start is None and end is not None:
                # end with no start is to return tail of content
                end = -end

            if start is not None and end is not None:
                # end is inclusive in range header, exclusive for slice
                end += 1

                if start >= end:
                    raise ValueError('start cannot be after end')

            if start is end is None:  # No valid range supplied
                raise ValueError('No start or end of range specified')
        return slice(start, end, 1)

    @property
    def content(self):
        """Return raw payload stream."""
        return self._payload

    @property
    def has_body(self):
        """Return True if request has HTTP BODY, False otherwise."""
        return not self._payload.at_eof()

    @asyncio.coroutine
    def release(self):
        """Release request.

        Eat unread part of HTTP BODY if present.
        """
        while not self._payload.at_eof():
            yield from self._payload.readany()

    @asyncio.coroutine
    def read(self):
        """Read request body if present.

        Returns bytes object with full request content.
        """
        if self._read_bytes is None:
            body = bytearray()
            while True:
                chunk = yield from self._payload.readany()
                body.extend(chunk)
                if self._client_max_size \
                        and len(body) >= self._client_max_size:
                    raise HTTPRequestEntityTooLarge
                if not chunk:
                    break
            self._read_bytes = bytes(body)
        return self._read_bytes

    @asyncio.coroutine
    def text(self):
        """Return BODY as text using encoding from .charset."""
        bytes_body = yield from self.read()
        encoding = self.charset or 'utf-8'
        return bytes_body.decode(encoding)

    @asyncio.coroutine
    def json(self, *, loads=json.loads):
        """Return BODY as JSON."""
        body = yield from self.text()
        return loads(body)

    @asyncio.coroutine
    def multipart(self, *, reader=multipart.MultipartReader):
        """Return async iterator to process BODY as multipart."""
        return reader(self._headers, self._payload)

    @asyncio.coroutine
    def post(self):
        """Return POST parameters."""
        if self._post is not None:
            return self._post
        if self._method not in self.POST_METHODS:
            self._post = MultiDictProxy(MultiDict())
            return self._post

        content_type = self.content_type
        if (content_type not in ('',
                                 'application/x-www-form-urlencoded',
                                 'multipart/form-data')):
            self._post = MultiDictProxy(MultiDict())
            return self._post

        out = MultiDict()

        if content_type == 'multipart/form-data':
            multipart = yield from self.multipart()

            field = yield from multipart.next()
            while field is not None:
                size = 0
                max_size = self._client_max_size
                content_type = field.headers.get(hdrs.CONTENT_TYPE)

                if field.filename:
                    # store file in temp file
                    tmp = tempfile.TemporaryFile()
                    chunk = yield from field.read_chunk(size=2**16)
                    while chunk:
                        chunk = field.decode(chunk)
                        tmp.write(chunk)
                        size += len(chunk)
                        if max_size > 0 and size > max_size:
                            raise ValueError(
                                'Maximum request body size exceeded')
                        chunk = yield from field.read_chunk(size=2**16)
                    tmp.seek(0)

                    ff = FileField(field.name, field.filename,
                                   tmp, content_type, field.headers)
                    out.add(field.name, ff)
                else:
                    value = yield from field.read(decode=True)
                    if content_type is None or \
                            content_type.startswith('text/'):
                        charset = field.get_charset(default='utf-8')
                        value = value.decode(charset)
                    out.add(field.name, value)
                    size += len(value)
                    if max_size > 0 and size > max_size:
                        raise ValueError(
                            'Maximum request body size exceeded')

                field = yield from multipart.next()
        else:
            data = yield from self.read()
            if data:
                charset = self.charset or 'utf-8'
                out.extend(
                    parse_qsl(
                        data.rstrip().decode(charset),
                        keep_blank_values=True,
                        encoding=charset))

        self._post = MultiDictProxy(out)
        return self._post

    def __repr__(self):
        ascii_encodable_path = self.path.encode('ascii', 'backslashreplace') \
            .decode('ascii')
        return "<{} {} {} >".format(self.__class__.__name__,
                                    self._method, ascii_encodable_path)

    @asyncio.coroutine
    def _prepare_hook(self, response):
        return
        yield  # pragma: no cover

class Request(BaseRequest):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # matchdict, route_name, handler
        # or information about traversal lookup
        self._match_info = None  # initialized after route resolving

    @property
    def match_info(self):
        """Result of route resolving."""
        return self._match_info

    @reify
    def app(self):
        """Application instance."""
        return self._match_info.apps[-1]

    @asyncio.coroutine
    def _prepare_hook(self, response):
        match_info = self._match_info
        if match_info is None:
            return
        for app in match_info.apps:
            yield from app.on_response_prepare.send(self, response)


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

<title>Point (PrimaMaths API)</title>
<meta name="date" content="2021-01-30">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.primaresearch.maths.geometry

Class Point

java.lang.Object

org.primaresearch.maths.geometry.Point

All Implemented Interfaces:

java.io.Serializable

public class Point
extends java.lang.Object
implements java.io.Serializable

Simple two-dimensional point.

Author:

clc

See Also:

Serialized Form

Field Summary

Fields

Modifier and Type
Field and Description

int
x

int
y

Constructor Summary

Constructors

Constructor and Description

Point()

Constructor with initialisation to 0,0.

Point(int x,
     int y)

Constructor with custom initialisation.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

double
calculateDistance(int xOther,
                 int yOther)

Calculates the distance between this point and a given other point.

double
calculateDistance(int lineX1,
                 int lineY1,
                 int lineX2,
                 int lineY2,
                 Point pointOnLine)

Calculates the distance between this point and a given line.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

x

public int x

y

public int y

Constructor Detail

Point

public Point()

Constructor with initialisation to 0,0.

Point

public Point(int x,
             int y)

Constructor with custom initialisation.

Method Detail

calculateDistance

public double calculateDistance(int xOther,
                                int yOther)

Calculates the distance between this point and a given other point.

calculateDistance

public double calculateDistance(int lineX1,
                                int lineY1,
                                int lineX2,
                                int lineY2,
                                Point pointOnLine)

Calculates the distance between this point and a given line.

Parameters:

pointOnLine - Nearest point on line (output, optional)

Returns:

Distance

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2019 PRImA Research Lab. All Rights Reserved.


text:
'use strict';

describe('Filter: chartFilter', function () {

  // load the filter's module
  beforeEach(module('geckoApp'));

  // initialize a new instance of the filter before each test
  var chartFilter;
  beforeEach(inject(function ($filter) {
    chartFilter = $filter('chartFilter');
  }));

  it('should return the input prefixed with "chartFilter filter:"', function () {
    var text = 'angularjs';
    expect(chartFilter(text)).toBe('chartFilter filter: ' + text);
  });

});


text:
package com.connell.pi;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.TextOutputFormat;

public class Runner {

  public static void main(String[] args) throws Exception {
    JobConf job = new JobConf(EstimatePiJob.class);
    job.setJobName("estimate-pi");
    job.setMapperClass(EstimatePiJob.EstimatePiMapper.class);
    job.setReducerClass(EstimatePiJob.EstimatePiReducer.class);

    job.setMapOutputKeyClass(IntWritable.class);
    job.setMapOutputValueClass(BytesWritable.class);

    job.setOutputKeyClass(IntWritable.class);
    job.setOutputValueClass(Text.class);

    job.setInputFormat(EstimatorInputFormat.class);
    job.setOutputFormat(TextOutputFormat.class);

    job.setNumReduceTasks(1);

    // Adjust this to suit your cluster
    int digits = Integer.valueOf(args[0]);
    job.setNumMapTasks(digits/1000);
    EstimatorInputFormat.setDigits(job, digits);

    FileOutputFormat.setOutputPath(job, new Path("/tmp/estimate-pi/results/" + System.currentTimeMillis()));

    JobClient.runJob(job);
  }
}


text:
package GenTest::Validator::ErrorMessageCorruption;

require Exporter;
@ISA = qw(GenTest::Validator GenTest);

use strict;

use GenTest;
use GenTest::Constants;
use GenTest::Result;
use GenTest::Validator;

use constant ASCII_ALLOWED_MIN	=> chr(32);  # space
use constant ASCII_ALLOWED_MAX  => chr(126); # tilde

1;

sub validate {
        my ($comparator, $executors, $results) = @_;
	my ($ascii_min, $ascii_max) = (ASCII_ALLOWED_MIN, ASCII_ALLOWED_MAX);
	foreach my $result (@$results) {
		if (
			(defined $result->errstr()) &&
			($result->errstr() =~ m{[^$ascii_min-$ascii_max\s]}siox )
		) {
			say("Error: '".$result->errstr()."' indicates memory corruption. Note that this may be a false alarm if the test contains non-ascii character sets and non-alphanumeric characters.");
			return STATUS_DATABASE_CORRUPTION;
		}
	}

	return STATUS_OK;
}

1;


text:
<?php

/***
 * Represent available name list for payment method
 */
class PagSeguroPaymentMethodName
{

    private static $availableNameList = array(
        'DEBITO_BRADESCO' => 'Bradesco debit',
        'DEBITO_ITAU' => 'Itaú debit',
        'DEBITO_UNIBANCO' => 'Unibanco debit',
        'DEBITO_BANCO_BRASIL' => 'Banco do Brasil debit',
        'DEBITO_BANRISUL' => 'Banrisul debit',
        'DEBITO_HSBC' => 'HSBC bank debit',
        'BOLETO' => 'Boleto',
        'VISA' => 'Visa brand',
        'MASTERCARD' => 'MasterCard brand',
        'AMEX' => 'Amex brand',
        'DINERS' => 'Diners brand',
        'HIPERCARD' => 'Hipercard brand',
        'AURA' => 'Aura brand',
        'ELO' => 'ELO brand',
        'PLENOCARD' => 'PlenoCard brand',
        'PERSONALCARD' => 'PersonalCard brand',
        'JCB' => 'JCB brand',
        'DISCOVER' => 'Discover brand',
        'BRASILCARD' => 'BrasilCard brand',
        'FORTBRASIL' => 'FortBrasil brand',
        'CARDBAN' => 'CardBAN brand',
        'VALECARD' => 'ValeCard brand',
        'CABAL' => 'Cabal brand',
        'MAIS' => 'MAIS brand',
        'AVISTA' => 'AVISTA brand',
        'GRANDCARD' => 'GrandCard brand',
        'SOROCRED' => 'Sorocred brand'
    );

    /***
     * Get available list for accepted payment methods
     * @return array
     */
    public static function getAvailableKeysList()
    {
        return self::$availableNameList;
    }

    /***
     * Check if a name is available for accepted payment methods.
     * @param string $name
     * @return boolean
     */
    public static function isNameAvailable($name)
    {
        $key = strtoupper($name);
        return (isset(self::$availableNameList[$key]));
    }

    /***
     * Gets description by name
     * @param string $name
     * @return string
     */
    public static function getDescriptionByName($name)
    {
        $key = strtoupper($name);
        if (isset(self::$availableNameList[$key])) {
            return self::$availableNameList[$key];
        } else {
            return false;
        }
    }

    /***
     * Gets name key by description
     * @param string $description
     * @return string
     */
    public static function getKeyByDescription($description)
    {
        return array_search(strtolower($description), array_map('strtolower', self::$availableNameList));
    }
}


text:
LootomaticItem = {}
LootomaticItem.__index = LootomaticItem

--[[
-- @param string itemName
--
-- @return LootomaticItem
--]]
function LootomaticItem.New(itemName)
    local self = setmetatable({data={}}, LootomaticItem)
    -- Not sure what all of these are
    self.name,  self.color, self.n3,  self.id,
    self.n5,  self.n6, self.n7,  self.n8,
    self.n9,  self.n10, self.n11, self.n12,
    self.n13, self.n14, self.n15, self.n16,
    self.n17, self.n18, self.n19, self.n20,
    self.n21, self.n22, self.n23, self.n24 = ZO_LinkHandler_ParseLink(itemName)
    self.icon, self.sellPrice, self.meetsUsageRequirement, self.equipType, self.itemStyle = GetItemLinkInfo(itemName)
    return self
end

--[[
-- Loads an item based on where it is based on the slot in a bag
--
-- @param integer bagId
-- @param integer slotId
-- @return LootomaticItem
--]]
function LootomaticItem.LoadByBagAndSlot(bagId, slotId)
    local i = LootomaticItem.New(GetItemLink(bagId, slotId, LINK_STYLE_DEFAULT))
    i.itemType = GetItemType(bagId, slotId)
    return i
end


text:
using tesseract::ColPartition;
using tesseract::ColPartition_LIST;
using tesseract::ColPartitionGrid;

namespace {

class TestableTableFinder : public tesseract::TableFinder {
 public:
  using TableFinder::GapInXProjection;
  using TableFinder::HasLeaderAdjacent;
  using TableFinder::InsertLeaderPartition;
  using TableFinder::InsertTextPartition;
  using TableFinder::set_global_median_blob_width;
  using TableFinder::set_global_median_ledding;
  using TableFinder::set_global_median_xheight;
  using TableFinder::SplitAndInsertFragmentedTextPartition;

  void ExpectPartition(const TBOX& box) {
    tesseract::ColPartitionGridSearch gsearch(&fragmented_text_grid_);
    gsearch.SetUniqueMode(true);
    gsearch.StartFullSearch();
    ColPartition* part = nullptr;
    bool found = false;
    while ((part = gsearch.NextFullSearch()) != nullptr) {
      if (part->bounding_box().left() == box.left() &&
          part->bounding_box().bottom() == box.bottom() &&
          part->bounding_box().right() == box.right() &&
          part->bounding_box().top() == box.top()) {
        found = true;
      }
    }
    EXPECT_TRUE(found);
  }
  void ExpectPartitionCount(int expected_count) {
    tesseract::ColPartitionGridSearch gsearch(&fragmented_text_grid_);
    gsearch.SetUniqueMode(true);
    gsearch.StartFullSearch();
    ColPartition* part = nullptr;
    int count = 0;
    while ((part = gsearch.NextFullSearch()) != nullptr) {
      ++count;
    }
    EXPECT_EQ(expected_count, count);
  }
};

class TableFinderTest : public testing::Test {
 protected:
  void SetUp() {
    std::locale::global(std::locale(""));
    free_boxes_it_.set_to_list(&free_boxes_);
    finder_.reset(new TestableTableFinder());
    finder_->Init(1, ICOORD(0, 0), ICOORD(500, 500));
    // gap finding
    finder_->set_global_median_xheight(5);
    finder_->set_global_median_blob_width(5);
  }

  void TearDown() {
    if (partition_.get() != nullptr) partition_->DeleteBoxes();
    DeletePartitionListBoxes();
    finder_.reset(nullptr);
  }

  void MakePartition(int x_min, int y_min, int x_max, int y_max) {
    MakePartition(x_min, y_min, x_max, y_max, 0, 0);
  }

  void MakePartition(int x_min, int y_min, int x_max, int y_max,
                     int first_column, int last_column) {
    if (partition_.get() != nullptr) partition_->DeleteBoxes();
    TBOX box;
    box.set_to_given_coords(x_min, y_min, x_max, y_max);
    partition_.reset(
        ColPartition::FakePartition(box, PT_UNKNOWN, BRT_UNKNOWN, BTFT_NONE));
    partition_->set_first_column(first_column);
    partition_->set_last_column(last_column);
  }

  void InsertTextPartition(ColPartition* part) {
    finder_->InsertTextPartition(part);
    free_boxes_it_.add_after_then_move(part);
  }

  void InsertLeaderPartition(int x_min, int y_min, int x_max, int y_max) {
    InsertLeaderPartition(x_min, y_min, x_max, y_max, 0, 0);
  }

  void InsertLeaderPartition(int x_min, int y_min, int x_max, int y_max,
                             int first_column, int last_column) {
    TBOX box;
    box.set_to_given_coords(x_min, y_min, x_max, y_max);
    ColPartition* part = ColPartition::FakePartition(box, PT_FLOWING_TEXT,
                                                     BRT_UNKNOWN, BTFT_LEADER);
    part->set_first_column(first_column);
    part->set_last_column(last_column);
    finder_->InsertLeaderPartition(part);
    free_boxes_it_.add_after_then_move(part);
  }

  void DeletePartitionListBoxes() {
    for (free_boxes_it_.mark_cycle_pt(); !free_boxes_it_.cycled_list();
         free_boxes_it_.forward()) {
      ColPartition* part = free_boxes_it_.data();
      part->DeleteBoxes();
    }
  }

  std::unique_ptr<TestableTableFinder> finder_;
  std::unique_ptr<ColPartition> partition_;

 private:
  tesseract::ColPartition_CLIST free_boxes_;
  tesseract::ColPartition_C_IT free_boxes_it_;
};

TEST_F(TableFinderTest, GapInXProjectionNoGap) {
  int data[100];
  for (int i = 0; i < 100; ++i) data[i] = 10;
  EXPECT_FALSE(finder_->GapInXProjection(data, 100));
}

TEST_F(TableFinderTest, GapInXProjectionEdgeGap) {
  int data[100];
  for (int i = 0; i < 10; ++i) data[i] = 2;
  for (int i = 10; i < 90; ++i) data[i] = 10;
  for (int i = 90; i < 100; ++i) data[i] = 2;
  EXPECT_FALSE(finder_->GapInXProjection(data, 100));
}

TEST_F(TableFinderTest, GapInXProjectionExists) {
  int data[100];
  for (int i = 0; i < 10; ++i) data[i] = 10;
  for (int i = 10; i < 90; ++i) data[i] = 2;
  for (int i = 90; i < 100; ++i) data[i] = 10;
  EXPECT_TRUE(finder_->GapInXProjection(data, 100));
}

TEST_F(TableFinderTest, HasLeaderAdjacentOverlapping) {
  InsertLeaderPartition(90, 0, 150, 5);
  MakePartition(0, 0, 100, 10);
  EXPECT_TRUE(finder_->HasLeaderAdjacent(*partition_));
  MakePartition(0, 25, 100, 40);
  EXPECT_FALSE(finder_->HasLeaderAdjacent(*partition_));
  MakePartition(145, 0, 200, 20);
  EXPECT_TRUE(finder_->HasLeaderAdjacent(*partition_));
  MakePartition(40, 0, 50, 4);
  EXPECT_TRUE(finder_->HasLeaderAdjacent(*partition_));
}

TEST_F(TableFinderTest, HasLeaderAdjacentNoOverlap) {
  InsertLeaderPartition(90, 10, 150, 15);
  MakePartition(0, 10, 85, 20);
  EXPECT_TRUE(finder_->HasLeaderAdjacent(*partition_));
  MakePartition(0, 25, 100, 40);
  EXPECT_FALSE(finder_->HasLeaderAdjacent(*partition_));
  MakePartition(0, 0, 100, 10);
  EXPECT_FALSE(finder_->HasLeaderAdjacent(*partition_));
  // TODO(nbeato): is this a useful metric? case fails
  // MakePartition(160, 0, 200, 15);  // leader is primarily above it
  // EXPECT_FALSE(finder_->HasLeaderAdjacent(*partition_));
}

TEST_F(TableFinderTest, HasLeaderAdjacentPreservesColumns) {
  InsertLeaderPartition(90, 0, 150, 5, 1, 2);
  MakePartition(0, 0, 85, 10, 0, 0);
  EXPECT_FALSE(finder_->HasLeaderAdjacent(*partition_));
  MakePartition(0, 0, 100, 10, 0, 1);
  EXPECT_TRUE(finder_->HasLeaderAdjacent(*partition_));
  MakePartition(0, 0, 200, 10, 0, 5);
  EXPECT_TRUE(finder_->HasLeaderAdjacent(*partition_));
  MakePartition(155, 0, 200, 10, 5, 5);
  EXPECT_FALSE(finder_->HasLeaderAdjacent(*partition_));
}

// TODO(nbeato): Only testing a splitting case. Add more...
// Also test non-split cases.
TEST_F(TableFinderTest, SplitAndInsertFragmentedPartitionsBasicPass) {
  finder_->set_global_median_blob_width(3);
  finder_->set_global_median_xheight(10);

  TBOX part_box(10, 5, 100, 15);
  ColPartition* all = new ColPartition(BRT_UNKNOWN, ICOORD(0, 1));
  all->set_type(PT_FLOWING_TEXT);
  all->set_blob_type(BRT_TEXT);
  all->set_flow(BTFT_CHAIN);
  all->set_left_margin(10);
  all->set_right_margin(100);
  TBOX blob_box = part_box;
  for (int i = 10; i <= 20; i += 5) {
    blob_box.set_left(i + 1);
    blob_box.set_right(i + 4);
    all->AddBox(new BLOBNBOX(C_BLOB::FakeBlob(blob_box)));
  }
  for (int i = 35; i <= 55; i += 5) {
    blob_box.set_left(i + 1);
    blob_box.set_right(i + 4);
    all->AddBox(new BLOBNBOX(C_BLOB::FakeBlob(blob_box)));
  }
  for (int i = 80; i <= 95; i += 5) {
    blob_box.set_left(i + 1);
    blob_box.set_right(i + 4);
    all->AddBox(new BLOBNBOX(C_BLOB::FakeBlob(blob_box)));
  }
  // TODO(nbeato): Ray's newer code...
  // all->ClaimBoxes();
  all->ComputeLimits();      // This is to make sure median iinfo is set.
  InsertTextPartition(all);  // This is to delete blobs
  ColPartition* fragment_me = all->CopyButDontOwnBlobs();

  finder_->SplitAndInsertFragmentedTextPartition(fragment_me);
  finder_->ExpectPartition(TBOX(11, 5, 24, 15));
  finder_->ExpectPartition(TBOX(36, 5, 59, 15));
  finder_->ExpectPartition(TBOX(81, 5, 99, 15));
  finder_->ExpectPartitionCount(3);
}

TEST_F(TableFinderTest, SplitAndInsertFragmentedPartitionsBasicFail) {
  finder_->set_global_median_blob_width(3);
  finder_->set_global_median_xheight(10);

  TBOX part_box(10, 5, 100, 15);
  ColPartition* all = new ColPartition(BRT_UNKNOWN, ICOORD(0, 1));
  all->set_type(PT_FLOWING_TEXT);
  all->set_blob_type(BRT_TEXT);
  all->set_flow(BTFT_CHAIN);
  all->set_left_margin(10);
  all->set_right_margin(100);
  TBOX blob_box = part_box;
  for (int i = 10; i <= 95; i += 5) {
    blob_box.set_left(i + 1);
    blob_box.set_right(i + 4);
    all->AddBox(new BLOBNBOX(C_BLOB::FakeBlob(blob_box)));
  }
  // TODO(nbeato): Ray's newer code...
  // all->ClaimBoxes();
  all->ComputeLimits();      // This is to make sure median iinfo is set.
  InsertTextPartition(all);  // This is to delete blobs
  ColPartition* fragment_me = all->CopyButDontOwnBlobs();

  finder_->SplitAndInsertFragmentedTextPartition(fragment_me);
  finder_->ExpectPartition(TBOX(11, 5, 99, 15));
  finder_->ExpectPartitionCount(1);
}

}  // namespace


text:
<?php

namespace Eps\VhostGeneratorBundle\Generator\Exception;

/**
 * Class ValidationException
 * @package Eps\VhostGeneratorBundle\Generator\Exception
 * @author Jakub Turek <ja@kubaturek.pl>
 */
class ValidationException extends \Exception
{
    /**
     * @param string $message
     * @param string $context
     * @param int $code
     * @param \Exception $previous
     */
    public function __construct($message = '', $context = '', $code = 0, \Exception $previous = null)
    {
        if ($context) {
            $message = $message . " ($context)";
        }

        parent::__construct($message, $code, $previous);
    }
}


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

<TITLE>
JndiObjectLocator (Spring Framework)
</TITLE>

<META NAME="keywords" CONTENT="org.springframework.jndi.JndiObjectLocator class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.springframework.jndi

Class JndiObjectLocator

java.lang.Object
  org.springframework.jndi.JndiAccessor
      org.springframework.jndi.JndiLocatorSupport
          org.springframework.jndi.JndiObjectLocator

All Implemented Interfaces:
InitializingBean

Direct Known Subclasses:
AbstractJndiLocator, AbstractSlsbInvokerInterceptor, JndiObjectFactoryBean, JndiObjectTargetSource, JndiRmiClientInterceptor

public abstract class JndiObjectLocator
extends JndiLocatorSupport
implements InitializingBean

Convenient superclass for JNDI-based service locators. Subclasses are
 JavaBeans, exposing a jndiName property. This may or may not include
 the "java:comp/env/" prefix expected by J2EE applications when accessing
 a locally mapped (ENC - Environmental Naming Context) resource. If it
 doesn't, the "java:comp/env/" prefix will be prepended if the "resourceRef"
 property is true (the default is false) and no other scheme
 like "java:" is given.

Subclasses can invoke the lookup method whenever it is appropriate.
 Some classes might do this on initialization, while others might do it
 on demand. The latter strategy is more flexible in that it allows for
 initialization of the locator before the JNDI object is available.

Author:

Juergen Hoeller

See Also:
setJndiName(java.lang.String),
JndiAccessor.setJndiTemplate(org.springframework.jndi.JndiTemplate),
JndiAccessor.setJndiEnvironment(java.util.Properties),
JndiLocatorSupport.setResourceRef(boolean),
lookup()

Field Summary

Fields inherited from class org.springframework.jndi.JndiLocatorSupport

CONTAINER_PREFIX

Fields inherited from class org.springframework.jndi.JndiAccessor

logger

Constructor Summary

JndiObjectLocator()

Method Summary

 void
afterPropertiesSet()

          Check the jndiName property and initiate a lookup.

 java.lang.String
getJndiName()

          Return the JNDI name to look up.

protected  java.lang.Object
lookup()

          Perform the actual JNDI lookup via the JndiTemplate.

 void
setJndiName(java.lang.String jndiName)

          Set the JNDI name to look up.

Methods inherited from class org.springframework.jndi.JndiLocatorSupport

convertJndiName, isResourceRef, lookup, setResourceRef

Methods inherited from class org.springframework.jndi.JndiAccessor

getJndiEnvironment, getJndiTemplate, setJndiEnvironment, setJndiTemplate

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

JndiObjectLocator

public JndiObjectLocator()

Method Detail

setJndiName

public void setJndiName(java.lang.String jndiName)

Set the JNDI name to look up. If it doesn't begin with "java:comp/env/"
 this prefix is added if resourceRef is set to true.

Parameters:
jndiName - JNDI name to look up
See Also:
JndiLocatorSupport.setResourceRef(boolean)

getJndiName

public java.lang.String getJndiName()

Return the JNDI name to look up.

afterPropertiesSet

public void afterPropertiesSet()
                        throws javax.naming.NamingException

Check the jndiName property and initiate a lookup.

The JNDI object will thus be fetched eagerly on initialization.
 For refreshing the JNDI object, subclasses can invoke lookup
 at any later time.

Specified by:
afterPropertiesSet in interface InitializingBean

Throws:

javax.naming.NamingException
See Also:
lookup()

lookup

protected java.lang.Object lookup()
                           throws javax.naming.NamingException

Perform the actual JNDI lookup via the JndiTemplate.
 Invokes the located method after successful lookup.

Throws:

javax.naming.NamingException - if the JNDI lookup failed

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (C) 2003-2004 The Spring Framework Project.


text:
extern crate kpdb;
extern crate rpassword;
extern crate clipboard;
#[macro_use]
extern crate serde_derive;
extern crate docopt;
extern crate termios;
extern crate qptrie;
extern crate ansi_term;
extern crate secstr;

use kpdb::{CompositeKey, Database, EntryUuid, Entry};
use kpdb::StringValue::{Plain, Protected};
use std::fs::File;
use std::io::{self, Read, Write};
use std::char;
use std::collections::hash_map::Values;
use clipboard::{ClipboardContext, ClipboardProvider};
use docopt::Docopt;
use termios::{Termios, TCSANOW, ECHO, ICANON, tcsetattr};
use qptrie::Trie;
use ansi_term::Colour::{Red, Green};
use secstr::SecStr;

const USAGE: &'static str = "
Rust Keypass CLI

Usage:
  kpsh <kdbx-file-path>
  kpsh (-h | --help)
  kpsh --version

Options:
  -h --help     Show this screen.
  --version     Show version.
";

#[derive(Debug, Deserialize)]
struct Args {
    arg_kdbx_file_path: String,
}

fn main() {
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.deserialize())
        .unwrap_or_else(|e| e.exit());
    println!("{:?}", args);

    let mut file = File::open(args.arg_kdbx_file_path).unwrap();

    let pass = rpassword::prompt_password_stdout("Master Password: ").unwrap();
    let key = CompositeKey::from_password(pass);
    let db = Database::open(&mut file, &key).unwrap();

    let t = into_trie(db.entries.values());

    loop {
        let account_name = get_account_name(&t);
        if let Some(password) = t.get(&account_name) {
            let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
            let password = std::str::from_utf8(password.unsecure()).unwrap();
            ctx.set_contents(password.to_owned()).unwrap();
            println!("{}",
                     Green
                         .bold()
                         .paint(format!("Password for {} copied onto clipboard\n",
                                        account_name)));
        } else {
            println!("{}",
                     Red.bold()
                         .paint(format!("Password for {} not found\n", account_name)));
        }
    }
}

fn into_trie(values: Values<EntryUuid, Entry>) -> Trie<String, &SecStr> {
    let mut t = Trie::new();
    let title_string_key = kpdb::StringKey::Title;
    let password_string_key = kpdb::StringKey::Password;

    for val in values {
        if let Plain(ref title) = val.strings[&title_string_key] {
            if let Protected(ref password) = val.strings[&password_string_key] {
                t.insert(title.to_string(), password);
            }
        }
    }
    t
}

fn get_account_name(t: &Trie<String, &SecStr>) -> String {
    let stdin = 0; // couldn't get std::os::unix::io::FromRawFd to work
    // on /dev/stdin or /dev/tty
    let termios = Termios::from_fd(stdin).unwrap();
    let mut new_termios = termios.clone(); // make a mutable copy of termios
    // that we will modify
    new_termios.c_lflag &= !(ICANON | ECHO); // no echo and canonical mode
    tcsetattr(stdin, TCSANOW, &mut new_termios).unwrap();
    let stdout = io::stdout();
    let mut reader = io::stdin();
    let mut buffer = [0; 1]; // read exactly one byte
    let mut account = String::new();
    println!("Get password for which account?");
    loop {
        stdout.lock().flush().unwrap();
        reader.read_exact(&mut buffer).unwrap();
        match char::from_u32(buffer[0] as u32) {
            Some('\n') => {
                println!();
                return account;
            }
            Some('\u{7f}') => {
                account.pop();
            }
            Some('\t') => account = typeahead(&t, &account),
            Some(c) => {
                account.push(c);
            }
            None => (),
        }
        print!("{} \r{}", '\u{8}', account);
    }
    // tcsetattr(stdin, TCSANOW, & termios).unwrap();  // reset the stdin to
    // original termios data
}

fn typeahead(t: &Trie<String, &SecStr>, prefix: &str) -> String {
    let m = matching_accounts(t, prefix);
    let lcp = longest_common_prefix(&m);
    if lcp == prefix {
        show_vector(&m);
    }
    lcp
}

fn longest_common_prefix(v: &Vec<String>) -> String {
    v.iter()
        .fold(v[0].to_owned(), |acc, s| lcp_util(acc, s.to_owned()))
}

fn lcp_util(s1: String, s2: String) -> String {
    let mut c1 = s1.chars();
    let mut c2 = s2.chars();
    let mut i = 0;
    while let (Some(a), Some(b)) = (c1.next(), c2.next()) {
        if a == b {
            i += 1;
        } else {
            break;
        }
    }
    (&s1)[..i].to_string()
}

fn matching_accounts(t: &Trie<String, &SecStr>, prefix: &str) -> Vec<String> {
    t.prefix_iter(&prefix.to_string())
        .include_prefix()
        .map(|(k, _)| k.to_owned())
        .collect()
}

fn show_vector(v: &Vec<String>) {
    println!("\n{}",
             v.iter().fold(String::new(), |acc, s| acc + s + "\t"));
}

#[cfg(test)]
mod tests {
    use super::{longest_common_prefix, lcp_util};

    #[test]
    fn lcp_util_returns_the_longest_common_prefix_of_two_strings() {
        let s1 = "foobar".to_string();
        let s2 = "fooqux".to_string();

        assert_eq!("foo", lcp_util(s1, s2));
    }

    #[test]
    fn longest_common_prefix_returns_the_longest_common_prefix_of_a_vector_of_strings() {
        let v = vec!["foo1".to_string(), "foo2".to_string(), "foo3".to_string()];

        assert_eq!("foo", longest_common_prefix(&v));
    }
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from thrift_compiler.generate.t_output import CompositeOutput
from thrift_compiler.generate.t_output_aggregator import OutputContext

# ---------------------------------------------------------------
# OutputContext
# ---------------------------------------------------------------

class SchemaOutputContext(OutputContext):
    def __init__(self, schema_file):
        self._schema_file = schema_file

        outputs = [schema_file]

        # shorthand to write to all outputs at the same time
        self._all_outputs = CompositeOutput(*outputs)
        # start writing in the header
        self.output = schema_file

    @property
    def schema(self):
        return self._schema_file

    @property
    def output(self):
        return self._output_crt

    @output.setter
    def output(self, output):
        self._output_crt = output

    @property
    def outputs(self):
        return self._all_outputs

    def _enter_scope_handler(self, scope, physical_scope=True):
        raise NotImplementedError

    def _exit_scope_handler(self, scope, physical_scope=True):
        raise NotImplementedError


text:
<?php

namespace LaraCourse\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use LaraCourse\Models\User;

class TestEmail extends Mailable
{
    use Queueable, SerializesModels;
public $user;
    /**
     * @var $user
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('mails.testemail')->with(['username'=>'Hidran']);
    }
}


text:
package org.qi4j.runtime.instantiation;

import org.junit.Assert;
import org.junit.Test;
import org.qi4j.api.composite.TransientBuilder;
import org.qi4j.api.composite.TransientComposite;
import org.qi4j.api.mixin.Mixins;
import org.qi4j.bootstrap.AssemblyException;
import org.qi4j.bootstrap.ModuleAssembly;
import org.qi4j.test.AbstractQi4jTest;

public class TransientInstantiationTests
    extends AbstractQi4jTest
{
    public void assemble( ModuleAssembly module )
        throws AssemblyException
    {
        module.transients( MyTransient.class );
    }

    @Test
    public void whenCreatingServiceCompositeGivenAServiceCompositeThenSucceed()
        throws Exception
    {
        TransientBuilder<My> builder = module.newTransientBuilder( My.class );
        My my = builder.newInstance();
        Assert.assertEquals( "Niclas", my.doSomething() );
    }

    @Mixins( MyMixin.class )
    public interface MyTransient
        extends TransientComposite, My
    {
    }

    public interface My
    {
        String doSomething();
    }

    public static class MyMixin
        implements My
    {

        public String doSomething()
        {
            return "Niclas";
        }
    }
}


text:
#pragma once

void mraa_python_isr(void (*isr)(void*), void* isr_args);


text:
<?xml version="1.0" encoding="UTF-8"?>
<dialogue>

	<dialogueSection>
		<audio>phonering</audio>
		<text>[Phone ringing]</text>
	</dialogueSection>

	<dialogueSection>
		<audio>phonepickup</audio>
		<image>tom</image>
		<text>Sully: This better be important, you've got 5 seconds before I hang up.</text>
	</dialogueSection>

	<dialogueSection>
		<image>partnerchathead</image>
		<text>Det Carter: Sully, it's me, Carter.</text>
	</dialogueSection>

	<dialogueSection>
		<image>tom</image>
		<text>Sully: Why the hell are you bothering me in the middle of the night Carter?</text>
	</dialogueSection>

	<dialogueSection>
		<image>partnerchathead</image>
		<text>Det Carter: We need you back.</text>
	</dialogueSection>

	<dialogueSection>
		<image>tom</image>
		<text>Sully: I'm a reckless drunk, remember. Why would you want me back?</text>
	</dialogueSection>

	<dialogueSection>
		<image>partnerchathead</image>
		<text>Det Carter: There has been another killing, but there is something different about this killing. Almost like it was for a ritual...
</text>
	</dialogueSection>

	<dialogueSection>
		<image>partnerchathead</image>
		<text>Det Carter: ...plus the department is running short on manpower and you know this case better than anyone on the force.</text>
	</dialogueSection>

	<dialogueSection>
		<image>tom</image>
		<text>Sully: I'm getting too old for this crap.</text>
	</dialogueSection>

	<dialogueSection>
		<image>partnerchathead</image>
		<text>Det Carter: Dammit Frank! Get off your ass and get down here now! </text>
	</dialogueSection>

	<dialogueSection>
		<image>partnerchathead</image>
		<text>Det Carter: We need you!</text>
	</dialogueSection>

	<dialogueSection>
		<image>tom</image>
		<text>Sully: Alright fine, I'll be there. </text>
	</dialogueSection>

	<dialogueSection>
		<image>tom</image>
		<text>Sully: I've got a bad feeling about this.</text>
	</dialogueSection>

	<dialogueSection>
		<audio addTo="Canvas">phonehangup</audio>
		<image></image>
		<text></text>
	</dialogueSection>

</dialogue>


text:
module RuboCop
  module Cop
    module RSpec
      # Checks if there is an empty line after example group blocks.
      #
      # @example
      #   # bad
      #   RSpec.describe Foo do
      #     describe '#bar' do
      #     end
      #     describe '#baz' do
      #     end
      #   end
      #
      #   # good
      #   RSpec.describe Foo do
      #     describe '#bar' do
      #     end
      #
      #     describe '#baz' do
      #     end
      #   end
      #
      class EmptyLineAfterExampleGroup < Base
        extend AutoCorrector
        include EmptyLineSeparation

        MSG = 'Add an empty line after `%<example_group>s`.'

        def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
          return unless example_group?(node)

          missing_separating_line_offense(node) do |method|
            format(MSG, example_group: method)
          end
        end
      end
    end
  end
end


text:
package com.xem.mzbphoneapp.atys;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xem.mzbphoneapp.R;
import com.xem.mzbphoneapp.entity.OrderRecord;
import com.xem.mzbphoneapp.utils.MzbUrlFactory;
import com.xem.mzbphoneapp.utils.NetCallBack;
import com.xem.mzbphoneapp.utils.RequestUtils;
import com.xem.mzbphoneapp.utils.TitleBuilder;
import com.xem.mzbphoneapp.utils.Utility;
import com.xem.mzbphoneapp.view.MzbProgressDialog;
import com.xem.swipemenulistview.SwipeMenu;
import com.xem.swipemenulistview.SwipeMenuCreator;
import com.xem.swipemenulistview.SwipeMenuItem;
import com.xem.swipemenulistview.SwipeMenuListView;

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

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by xuebing on 15/7/2.
 */
public class B1_OrderRecordAty extends MzbActivity {

    @InjectView(R.id.titlebar_iv_left)
    ImageView back;
    @InjectView(R.id.b1_orderlist_ground)
    RelativeLayout orderlistGround;
    @InjectView(R.id.b1_orderlist)
    SwipeMenuListView mListView;

    private List<OrderRecord> data;
    private OrderRecordAdapter adapter;
    private String branid;
    private String custid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.b1_order_record_aty);
        ButterKnife.inject(this);
        new TitleBuilder(this).setTitleText("预约纪录").setLeftImage(R.mipmap.top_view_back);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        branid = bundle.getInt("branid") + "";
        custid = bundle.getInt("custid") + "";
        GetOrderRecordList(0);

        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                switch (menu.getViewType()) {
                    case 1:
                        createMenu1(menu);
                        break;
                    case 2:
                        createMenu1(menu);
                        break;
                    default:
                        break;
                }
            }

            private void createMenu1(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xbc, 0x31, 0x72)));
                deleteItem.setWidth(dp2px(90));
                deleteItem.setTitle("取消预约");
                deleteItem.setTitleSize(15);
                deleteItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(deleteItem);
            }
        };

        mListView.setMenuCreator(creator);

        mListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                OrderRecord item = data.get(position);
                CancelOrder(item.getAppoid(), position);
//                adapter.notifyDataSetChanged();
            }
        });

       /* mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OrderRecord item = data.get(position);
                CancelOrder(item.getAppoid(), position);
            }
        });
*/

       /* mListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });*/
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @OnClick({R.id.titlebar_iv_left})
    public void onDo(View v) {
        switch (v.getId()) {
            case R.id.titlebar_iv_left:
                finish();
                break;

            default:
                break;
        }
    }

    public void GetOrderRecordList(final int page) {
        RequestParams params1 = new RequestParams();
        params1.put("branid", branid);
        params1.put("custid", custid);
        params1.put("begin", page + "");
        params1.put("count", 20 + "");

        RequestUtils.ClientTokenPost(B1_OrderRecordAty.this, MzbUrlFactory.BASE_URL + MzbUrlFactory.PLATFORM_RECORDS, params1, new NetCallBack(this) {

            @TargetApi(Build.VERSION_CODES.KITKAT)
            @Override
            public void onMzbSuccess(String result) {

                data = new ArrayList<OrderRecord>();
                try {
                    JSONObject obj = new JSONObject(result);
                    JSONArray jsonArray;
                    Gson gson = new Gson();//new一个Gson对象
                    if (obj.getInt("code") == 0) {
                        jsonArray = new JSONArray(obj.getString("data"));
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            OrderRecord orderRecord = new OrderRecord();
                            orderRecord = gson.fromJson(object.toString(), OrderRecord.class);
                            data.add(orderRecord);
                        }

                        Utility.getInstance().hasDataLayout(B1_OrderRecordAty.this, data.size() != 0, orderlistGround, "预约纪录为空", R.mipmap.yuyue_err);
                        adapter = new OrderRecordAdapter(B1_OrderRecordAty.this);
                        mListView.setAdapter(adapter);
                    } else {
                        Toast.makeText(B1_OrderRecordAty.this, obj.getString("message"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMzbFailues(Throwable arg0) {
                showToast("请求失败");
            }
        });
    }

    public void CancelOrder(int appoid, final int positon) {
        RequestParams params1 = new RequestParams();
        params1.put("appoid", appoid + "");

        RequestUtils.ClientTokenPost(B1_OrderRecordAty.this, MzbUrlFactory.BASE_URL + MzbUrlFactory.PLATFORM_CANCEL, params1, new NetCallBack(this) {
            @Override
            public void onMzbSuccess(String result) {

                try {
                    JSONObject obj = new JSONObject(result);

                    if (obj.getInt("code") == 0) {
                        showToast("预约取消成功");
                        data.get(positon).setState(3);
                        adapter.notifyDataSetChanged();
                    } else {
                        adapter.notifyDataSetChanged();
                        showToast("预约取消失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMzbFailues(Throwable arg0) {
                showToast("请求失败");
            }
        });
    }

    // ViewHolder静态类
    static class ViewHolder {
        public ImageView img;
        public TextView storename;
        public TextView ordertime;
        public TextView servicename;
        public TextView btn;
    }

    private class OrderRecordAdapter extends BaseAdapter {
        private LayoutInflater mInflater = null;

        private OrderRecordAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return super.getViewTypeCount();
        }

        @Override
        public int getItemViewType(int position) {

            return data.get(position).getState();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.b1_order_record_cell, null);
                holder.img = (ImageView) convertView.findViewById(R.id.b1_orderrecord_img);
                holder.storename = (TextView) convertView.findViewById(R.id.b1_orderrecord_name);
                holder.ordertime = (TextView) convertView.findViewById(R.id.b1_orderrecord_time);
                holder.servicename = (TextView) convertView.findViewById(R.id.b1_orderrecord_service);
                holder.btn = (TextView) convertView.findViewById(R.id.b1_orderrecord_btn);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            imageLoader.displayImage(data.get(position).getLogo(), holder.img);
            holder.storename.setText(data.get(position).getName());
            holder.ordertime.setText(data.get(position).getTime());
            String name = data.get(position).getWaiter();
            if (name == (null)) {
                holder.servicename.setText("");
            } else {
                holder.servicename.setText(name);
            }

            switch (data.get(position).getState()) {
                case 1:
                    holder.btn.setText(getResources().getString(R.string.order_one));
                    holder.btn.setTextColor(getResources().getColor(R.color.recordone));
                    break;
                case 2:
                    holder.btn.setText(getResources().getString(R.string.order_two));
                    holder.btn.setTextColor(getResources().getColor(R.color.recordtwo));
                    break;
                case 3:
                    holder.btn.setText(getResources().getString(R.string.order_three));
                    holder.btn.setTextColor(getResources().getColor(R.color.recordthree));
                    break;
                case 4:
                    holder.btn.setText(getResources().getString(R.string.order_four));
                    holder.btn.setTextColor(getResources().getColor(R.color.recordfour));
                    break;
                default:
                    break;
            }
            return convertView;
        }
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

}


text:
const path = require('path');
const webpackConfig = require('@kadira/storybook/dist/server/config/defaults/webpack.config.js');

module.exports = function(config, env) {
  const newConfig = webpackConfig(config, env);

  newConfig.eslint = {
    configFile: path.join(__dirname, './eslint.config.js'),
    useEslintrc: false
  };

  newConfig.module.preLoaders = (newConfig.module.preLoaders || []).concat({
    test: /\.js$/,
    exclude: /node_modules/,
    include: /src/,
    loader: 'eslint'
  });

  return newConfig;
};


text:
namespace MvcMonitor.Data.Providers.Factories
{
    public interface IIndexProviderFactory
    {
        IIndexProvider Create();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">

	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

	<jaxrs:server address="/" docLocation="wadl/jaxrs-command.wadl">

		<jaxrs:inInterceptors>
			<ref bean="validationInInterceptor" />
		</jaxrs:inInterceptors>

		<jaxrs:outInterceptors>
			<ref bean="validationOutInterceptor" />
		</jaxrs:outInterceptors>

		<jaxrs:serviceBeans>

			<bean name="jaxrsCommandImpl"
				class="com.maven.project.jaxrs.command.resource.impl.JaxrsCommandImpl" />

			<bean name="jaxrsQueryImpl"
				class="com.maven.project.jaxrs.query.resource.impl.JaxrsQueryImpl" />

		</jaxrs:serviceBeans>

		<jaxrs:providers>
			<ref bean="jsonProvider" />
			<ref bean="userRegistrationExceptionMapper" />
			<ref bean="userExceptionMapper" />
			<ref bean="userActivationExceptionMapper" />
		</jaxrs:providers>

		<jaxrs:features>
			<bean class="org.apache.cxf.feature.LoggingFeature" />
		</jaxrs:features>

	</jaxrs:server>

	<bean id="jsonProvider" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" />

	<!-- ExceptionMappers -->
	<bean id="validationExceptionMapper"
		class="org.apache.cxf.jaxrs.validation.ValidationExceptionMapper" />

	<bean id="userRegistrationExceptionMapper"
		class="com.maven.project.exception.mapper.UserRegistrationExceptionMapper" />
	<bean id="userExceptionMapper"
		class="com.maven.project.exception.mapper.UserExceptionMapper" />
	<bean id="userActivationExceptionMapper"
		class="com.maven.project.exception.mapper.UserActivationExceptionMapper" />

	<!-- validation interceptor related configration -->

	<bean id="validationInInterceptor"
		class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor">
		<property name="provider" ref="validationProvider" />
	</bean>
	<bean id="validationOutInterceptor"
		class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor">
		<property name="provider" ref="validationProvider" />
	</bean>
	<bean id="validationProvider" class="org.apache.cxf.validation.BeanValidationProvider" />

	<!-- application specific bean configrations -->

</beans>


text:
package org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.extended.close;

import org.apache.shardingsphere.db.protocol.postgresql.packet.PostgreSQLPacket;
import org.apache.shardingsphere.db.protocol.postgresql.packet.identifier.PostgreSQLMessagePacketType;
import org.apache.shardingsphere.db.protocol.postgresql.payload.PostgreSQLPacketPayload;

/**
 * Close complete packet for PostgreSQL.
 */
public final class PostgreSQLCloseCompletePacket implements PostgreSQLPacket {

    private static final byte[] VALUE = new byte[]{(byte) PostgreSQLMessagePacketType.CLOSE_COMPLETE.getValue(), 0, 0, 0, 4};

    private static final PostgreSQLCloseCompletePacket INSTANCE = new PostgreSQLCloseCompletePacket();

    /**
     * Get instance of {@link PostgreSQLCloseCompletePacket}.
     *
     * @return instance of {@link PostgreSQLCloseCompletePacket}
     */
    public static PostgreSQLCloseCompletePacket getInstance() {
        return INSTANCE;
    }

    @Override
    public void write(final PostgreSQLPacketPayload payload) {
        payload.getByteBuf().writeBytes(VALUE);
    }
}


text:
package com.baidubce.services.cdn.model.dsa;

import com.baidubce.services.cdn.model.JsonObject;

import java.util.ArrayList;
import java.util.List;

/**
 * create by changxing01 on 19/8/28
 */
public class DSADomain extends JsonObject {
    private String domain;
    private List<DSARule> rules;
    private String modifyTime;
    private String comment;

    /**
     * @return domain
     */
    public String getDomain() {
        return domain;
    }

    /**
     * @param domain the domain name
     */
    public void setDomain(String domain) {
        this.domain = domain;
    }

    /**
     * @param domain the domain name
     * @return returns this object
     */
    public DSADomain withDomain(String domain) {
        this.domain = domain;
        return this;
    }

    /**
     * @return rules
     */
    public List<DSARule> getRules() {
        return rules;
    }

    /**
     * @param rules rule list
     */
    public void setRules(List<DSARule> rules) {
        this.rules = rules;
    }

    /**
     * @param rules rule list
     * @return this object
     */
    public DSADomain withRules(List<DSARule> rules) {
        this.rules = rules;
        return this;
    }

    /**
     * @param rule
     * @return this object
     */
    public DSADomain addRules(DSARule rule) {
        if (this.rules == null) {
            this.rules = new ArrayList<DSARule>();
        }
        this.rules.add(rule);
        return this;
    }

    /**
     * @return modifyTime
     */
    public String getModifyTime() {
        return modifyTime;
    }

    /**
     * @param modifyTime
     */
    public void setModifyTime(String modifyTime) {
        this.modifyTime = modifyTime;
    }

    /**
     * @param modifyTime
     * @return this object
     */
    public DSADomain withModifyTime(String modifyTime) {
        this.modifyTime = modifyTime;
        return this;
    }

    /**
     * @return comment
     */
    public String getComment() {
        return comment;
    }

    /**
     * @param comment
     */
    public void setComment(String comment) {
        this.comment = comment;
    }

    /**
     * @param comment
     * @return this object
     */
    public DSADomain withComment(String comment) {
        this.comment = comment;
        return this;
    }
}