text:
import {Component, NgZone, OnDestroy, OnInit} from "@angular/core";
import template from "./user-modal.html";
import style from "./user-modal.scss";
import * as _ from "lodash";
import {NavParams, ToastController, ViewController} from "ionic-angular";
import {User} from "../../../../../both/models/user.model";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {UserService} from "../../services/user";
import {TranslateHelperService} from "../../services/translate-helper";
import {TranslateOption} from "../../services/translate";
import {AdvancedEmailValidatorDirective} from "../../services/advanced-email-validator";

class RoleAccess {
    constructor(private user: User, public roleDef: TranslateOption) {
    }

    public isWorking: boolean;

    get isMember(): boolean {
        return _.includes(this.user.roles, this.roleDef.value);
    }

    set isMember(value: boolean) {
        this.isWorking = true;
        if (value) {
            Meteor.users.update({_id: this.user._id}, {$addToSet: {roles: this.roleDef.value}}, {}, (err) => {
                this.isWorking = false;
                if (err) {
                    console.log("Error:", err);
                }
            });
        } else {
            Meteor.users.update({_id: this.user._id}, {$pull: {roles: this.roleDef.value}}, {}, (err) => {
                this.isWorking = false;
                if (err) {
                    console.log("Error:", err);
                }
            });
        }
    }
}

interface EditEmail extends Meteor.UserEmail {
    editAddress: string;
}

@Component({
    selector: "user-modal",
    template,
    styles: [ style ]
})
export class UserModal implements OnInit, OnDestroy {
    userId: string;
    user: User;

    hadInitialData: boolean = false;

    queryHandle: Meteor.LiveQueryHandle;
    emails: EditEmail[];

    get isAdmin(): boolean {
        return this.userService.isAdmin;
    }

    get isSelf(): boolean {
        return this.userId === this.userService.user._id;
    }

    get canEdit(): boolean {
        return this.isAdmin || this.isSelf;
    }

    userForm: FormGroup;
    usernameForm: FormGroup;
    userPasswordForm: FormGroup;

    _userState: string = "";
    userStateIsWorking: boolean = false;
    newEmailAddress: string = "";

    roles: RoleAccess[] = [];

    get titleParams() {
        return {name: (this.user?this.user.fullName:this.userId)};
    }

    constructor(private viewCtrl: ViewController, private params: NavParams,
                private fb: FormBuilder, private ngZone: NgZone, private userService: UserService,
                private toast: ToastController, private translateHelper: TranslateHelperService) {
        this.userId = this.params.get('userId');
        this.userForm = fb.group({
            fullName: ["", Validators.required],
            phone: ["", Validators.required],
        });
        this.usernameForm = fb.group({
            username: [""],
        });
        this.userPasswordForm = fb.group({
            oldPassword: [""],
            newPassword: ["", Validators.minLength(6)],
            newPasswordRepeat: ["", Validators.required],
            passwordRandom: ""
        }, {validator: this.matchPassword('newPassword', 'newPasswordRepeat')});
    }

    updateUser(user: User) {
        this.user = user;
        console.log("Got user", this.user);
        this.emails = _.map(this.user.emails, (email) => {
            return {
                address: email.address,
                verified: email.verified,
                editAddress: email.address
            };
        });
        this._userState = this.user.state;
        this.roles = this.userService.userRolesOptions.map((roleDef) => {
            return new RoleAccess(this.user, roleDef);
        });
        if (!this.hadInitialData) {
            this.usernameForm.controls['username'].setValue(this.user.username);
            this.usernameForm.markAsPristine();
            this.usernameForm.markAsUntouched();
            this.usernameForm.updateValueAndValidity();
            this.userForm.controls['phone'].setValue(this.user.phone);
            this.userForm.controls['fullName'].setValue(this.user.fullName);
            this.userForm.markAsPristine();
            this.userForm.markAsUntouched();
            this.userForm.updateValueAndValidity();
            this.hadInitialData = true;
        }
    }

    ngOnInit() {
        this.queryHandle = Meteor.users.find(this.userId).observe({
            changed: (user) => {
                console.log("changed", user);
                this.ngZone.run(() => {
                    this.updateUser(user);
                });
            },
            added: (user) => {
                console.log("added", user);
                this.ngZone.run(() => {
                    this.updateUser(user);
                });
            }
        });
    }

    ngOnDestroy() {
        if (this.queryHandle) {
            this.queryHandle.stop();
            this.queryHandle = null;
        }
    }

    matchPassword(password1: string, password2: string) {
        return (group: FormGroup) => {
            let password1Input = group.controls[password1];
            let password2Input = group.controls[password2];
            if (password1Input.value !== password2Input.value) {
                return password2Input.setErrors({noMatch: true});
            }
        };
    }

    savePersonal() {
        this.userForm.disable();
        console.log("Saving personal:", this.userForm.controls['fullName'].value, this.userForm.controls['phone'].value);
        this.userService.savePersonal(this.user._id, this.userForm.controls['fullName'].value, this.userForm.controls['phone'].value,
            (err, res) => {
                this.userForm.enable();
                console.log("Saved personal");
                if (err) {
                    console.log("Error:", err);
                    this.toast.create({
                        message: this.translateHelper.getError(err),
                        duration: 2500
                    }).present();
                } else {
                    this.userForm.markAsPristine();
                    this.userForm.markAsUntouched();
                    this.userForm.updateValueAndValidity();
                }
            });
    }

    saveUsername() {
        this.usernameForm.disable();
        console.log("saveUsername", this.usernameForm.controls['username'].value);
        this.userService.saveUsername(this.user._id, this.usernameForm.controls['username'].value,
            (err, result) => {
                this.usernameForm.enable();
                if (err) {
                    console.log("Error:", err);
                    this.toast.create({
                        message: this.translateHelper.getError(err),
                        duration: 2500
                    }).present();
                }
            });
    }

    saveEmail(email: EditEmail) {
        if (!AdvancedEmailValidatorDirective.check(email.editAddress)) {
            return;
        }
        console.log("saveEmail", email.address, "==>", email.editAddress);
        if (email.editAddress !== email.address) {
            this.userService.saveEmail(this.user._id, email.address, email.editAddress,
                (err, result) => {
                    if (err) {
                        console.log("Error:", err);
                        this.toast.create({
                            message: this.translateHelper.getError(err),
                            duration: 2500
                        }).present();
                    }
                });
        }
    }

    addEmail() {
        if (!AdvancedEmailValidatorDirective.check(this.newEmailAddress)) {
            return;
        }
        console.log("addEmail", this.newEmailAddress);
        this.userService.addEmail(this.user._id, this.newEmailAddress,
            (err, result) => {
                if (err) {
                    console.log("Error:", err);
                    this.toast.create({
                        message: this.translateHelper.getError(err),
                        duration: 2500
                    }).present();
                } else {
                    this.newEmailAddress = "";
                }
            });
    }

    deleteEmail(email: EditEmail) {
        if (this.emails.length <= 1) {
            return;
        }
        console.log("deleteEmail", email);
        this.userService.deleteEmail(this.user._id, email.address,
            (err, result) => {
                if (err) {
                    console.log("Error:", err);
                    this.toast.create({
                        message: this.translateHelper.getError(err),
                        duration: 2500
                    }).present();
                }
            });
    }

    randomPassword() {
        let text = "";
        let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-!/=:?";

        for (let i = 0; i < 10; i++) {
            text += chars.charAt(Math.floor(Math.random() * chars.length));
        }

        this.userPasswordForm.controls['passwordRandom'].setValue(text);
        this.userPasswordForm.controls['newPassword'].setValue(text);
        this.userPasswordForm.controls['newPasswordRepeat'].setValue(text);
        this.userPasswordForm.updateValueAndValidity();
    }

    savePassword() {
        console.log("savePassword");
        this.userPasswordForm.disable();
        this.userService.savePassword(this.user._id, this.userPasswordForm.controls['newPassword'].value,
            this.userPasswordForm.controls['oldPassword'].value,
            (err, result) => {
                this.userPasswordForm.enable();
                if (err) {
                    console.log("Error:", err);
                    this.toast.create({
                        message: this.translateHelper.getError(err),
                        duration: 2500
                    }).present();
                } else {
                    this.userPasswordForm.controls['newPassword'].setValue("");
                    this.userPasswordForm.controls['newPasswordRepeat'].setValue("");
                    this.userPasswordForm.controls['oldPassword'].setValue("");
                    this.userPasswordForm.controls['passwordRandom'].setValue("");
                    this.userPasswordForm.markAsPristine();
                    this.userPasswordForm.markAsUntouched();
                    this.userPasswordForm.updateValueAndValidity();
                }
            });
    }

    get userState(): string {
        return this._userState;
    }

    set userState(state: string) {
        this._userState = state;
        console.log("saveState", state);
        this.userStateIsWorking = true;
        this.userService.saveUserState(this.user._id, state,
            (err, result) => {
                this.userStateIsWorking = false;
                if (err) {
                    console.log("Error:", err);
                    this.toast.create({
                        message: this.translateHelper.getError(err),
                        duration: 2500
                    }).present();
                }
            });
    }

    close() {
        this.viewCtrl.dismiss();
    }
}


text:
<manifest package="me.yokeyword.fragmentation_swipeback"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <application/>

</manifest>

redpajama_set_name: RedPajamaGithub


text:
package org.hl7.v3;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

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

 *

 * <simpleType name="PharmacySupplyRequestRenewalRefusalReasonCode">
 *   <restriction base="{urn:hl7-org:v3}cs">
 *     <enumeration value="FAMPHYS"/>
 *     <enumeration value="ONHOLD"/>
 *     <enumeration value="MODIFY"/>
 *     <enumeration value="ALREADYRX"/>
 *     <enumeration value="NEEDAPMT"/>
 *     <enumeration value="NOTPAT"/>
 *     <enumeration value="NOTAVAIL"/>
 *     <enumeration value="DISCONT"/>
 *     <enumeration value="TOOEARLY"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "PharmacySupplyRequestRenewalRefusalReasonCode")
@XmlEnum
public enum PharmacySupplyRequestRenewalRefusalReasonCode {

    FAMPHYS,
    ONHOLD,
    MODIFY,
    ALREADYRX,
    NEEDAPMT,
    NOTPAT,
    NOTAVAIL,
    DISCONT,
    TOOEARLY;

    public String value() {
        return name();
    }

    public static PharmacySupplyRequestRenewalRefusalReasonCode fromValue(String v) {
        return valueOf(v);
    }

}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator;
use App\Categoria;
use Response;

class CategoriaController extends Controller
{
	protected $context;

	public function __construct(Categoria $context){
		$this->context = $context;
	}

	public function index(){
		return $this->context->all();
	}

	public function store(Request $request){
		$validator = Validator::make(
			$request->all(),
			[
				'nome' => 'required|unique:categorias|min:5'
			]
		);

		if ( $validator->fails() ) {
			return response()->json($validator->errors(), 401);
		};

		$result = $this->context->create($request->all());
		return $result;
	}

	public function show($id){
		return $this->context->find($id);
	}

	public function update(Request $request, $id){
		$validator = Validator::make(
			$request->all(),
			[
				'nome' => 'required|unique:categorias|min:5|max:40'.$id
			]
		);

		if ( $validator->fails() ) {
			return response()->json($validator->errors(), 401);
		};

		$result = $this->context->find($id);
		if ( $result ){
			$result->update($request->all());
		}

		return $result;
	}

	public function destroy($id){
		$result = $this->context->find($id);

		if ($result) {
			$result->delete();
		}
		return $result;

	}

}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/google/apis-client-generator/
 * (build: 2022-10-26 23:10:20 UTC)
 * on 2022-10-26 at 23:10:36 UTC
 * Modify at your own risk.
 */

package com.google.api.services.businesscommunications.v1.model;

/**
 * Details about a location launch.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Business Communications. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class LocationLaunch extends com.google.api.client.json.GenericJson {

  /**
   * The launch state.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String launchState;

  /**
   * Required. The identifier for launch.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * The launch state.
   * @return value or {@code null} for none
   */
  public java.lang.String getLaunchState() {
    return launchState;
  }

  /**
   * The launch state.
   * @param launchState launchState or {@code null} for none
   */
  @com.google.errorprone.annotations.CanIgnoreReturnValue
  public LocationLaunch setLaunchState(java.lang.String launchState) {
    this.launchState = launchState;
    return this;
  }

  /**
   * Required. The identifier for launch.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * Required. The identifier for launch.
   * @param name name or {@code null} for none
   */
  @com.google.errorprone.annotations.CanIgnoreReturnValue
  public LocationLaunch setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  @Override
  public LocationLaunch set(String fieldName, Object value) {
    return (LocationLaunch) super.set(fieldName, value);
  }

  @Override
  public LocationLaunch clone() {
    return (LocationLaunch) super.clone();
  }

}


text:
package com.swfarm.biz.schedule.dao.impl;

import com.swfarm.biz.schedule.bo.QrtzSimpleTrigger;
import com.swfarm.biz.schedule.dao.QrtzSimpleTriggerDao;
import com.swfarm.pub.framework.dao.GenericDaoHibernateImpl;

public class QrtzSimpleTriggerDaoImpl extends
		GenericDaoHibernateImpl<QrtzSimpleTrigger, String> implements
		QrtzSimpleTriggerDao {

	public QrtzSimpleTriggerDaoImpl(Class<QrtzSimpleTrigger> type) {
		super(type);
	}

}


text:
<mvc:View
	controllerName="sap.m.sample.Popover.controller.Popover"
	xmlns:l="sap.ui.layout"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns="sap.m">
	<l:VerticalLayout
		class="sapUiContentPadding"
		width="100%">
		<l:content>
			<Button
				text="Show Popover"
				press="handlePopoverPress"
				ariaHasPopup="Dialog" />
		</l:content>
	</l:VerticalLayout>
</mvc:View>


text:
namespace arrow {

class TestChunkedArray : public TestBase {
 protected:
  virtual void Construct() {
    one_ = std::make_shared<ChunkedArray>(arrays_one_);
    if (!arrays_another_.empty()) {
      another_ = std::make_shared<ChunkedArray>(arrays_another_);
    }
  }

  ArrayVector arrays_one_;
  ArrayVector arrays_another_;

  std::shared_ptr<ChunkedArray> one_;
  std::shared_ptr<ChunkedArray> another_;
};

TEST_F(TestChunkedArray, Make) {
  ASSERT_RAISES(Invalid, ChunkedArray::Make({}));

  ASSERT_OK_AND_ASSIGN(std::shared_ptr<ChunkedArray> result,
                       ChunkedArray::Make({}, int64()));
  AssertTypeEqual(*int64(), *result->type());
  ASSERT_EQ(result->num_chunks(), 0);

  auto chunk0 = ArrayFromJSON(int8(), "[0, 1, 2]");
  auto chunk1 = ArrayFromJSON(int16(), "[3, 4, 5]");

  ASSERT_OK_AND_ASSIGN(result, ChunkedArray::Make({chunk0, chunk0}));
  ASSERT_OK_AND_ASSIGN(auto result2, ChunkedArray::Make({chunk0, chunk0}, int8()));
  AssertChunkedEqual(*result, *result2);

  ASSERT_RAISES(Invalid, ChunkedArray::Make({chunk0, chunk1}));
  ASSERT_RAISES(Invalid, ChunkedArray::Make({chunk0}, int16()));
}

TEST_F(TestChunkedArray, BasicEquals) {
  std::vector<bool> null_bitmap(100, true);
  std::vector<int32_t> data(100, 1);
  std::shared_ptr<Array> array;
  ArrayFromVector<Int32Type, int32_t>(null_bitmap, data, &array);
  arrays_one_.push_back(array);
  arrays_another_.push_back(array);

  Construct();
  ASSERT_TRUE(one_->Equals(one_));
  ASSERT_FALSE(one_->Equals(nullptr));
  ASSERT_TRUE(one_->Equals(another_));
  ASSERT_TRUE(one_->Equals(*another_.get()));
}

TEST_F(TestChunkedArray, EqualsDifferingTypes) {
  std::vector<bool> null_bitmap(100, true);
  std::vector<int32_t> data32(100, 1);
  std::vector<int64_t> data64(100, 1);
  std::shared_ptr<Array> array;
  ArrayFromVector<Int32Type, int32_t>(null_bitmap, data32, &array);
  arrays_one_.push_back(array);
  ArrayFromVector<Int64Type, int64_t>(null_bitmap, data64, &array);
  arrays_another_.push_back(array);

  Construct();
  ASSERT_FALSE(one_->Equals(another_));
  ASSERT_FALSE(one_->Equals(*another_.get()));
}

TEST_F(TestChunkedArray, EqualsDifferingLengths) {
  std::vector<bool> null_bitmap100(100, true);
  std::vector<bool> null_bitmap101(101, true);
  std::vector<int32_t> data100(100, 1);
  std::vector<int32_t> data101(101, 1);
  std::shared_ptr<Array> array;
  ArrayFromVector<Int32Type, int32_t>(null_bitmap100, data100, &array);
  arrays_one_.push_back(array);
  ArrayFromVector<Int32Type, int32_t>(null_bitmap101, data101, &array);
  arrays_another_.push_back(array);

  Construct();
  ASSERT_FALSE(one_->Equals(another_));
  ASSERT_FALSE(one_->Equals(*another_.get()));

  std::vector<bool> null_bitmap1(1, true);
  std::vector<int32_t> data1(1, 1);
  ArrayFromVector<Int32Type, int32_t>(null_bitmap1, data1, &array);
  arrays_one_.push_back(array);

  Construct();
  ASSERT_TRUE(one_->Equals(another_));
  ASSERT_TRUE(one_->Equals(*another_.get()));
}

TEST_F(TestChunkedArray, EqualsDifferingMetadata) {
  auto left_ty = list(field("item", int32()));

  auto metadata = key_value_metadata({"foo"}, {"bar"});
  auto right_ty = list(field("item", int32(), true, metadata));

  std::vector<std::shared_ptr<Array>> left_chunks = {ArrayFromJSON(left_ty, "[[]]")};
  std::vector<std::shared_ptr<Array>> right_chunks = {ArrayFromJSON(right_ty, "[[]]")};

  ChunkedArray left(left_chunks);
  ChunkedArray right(right_chunks);
  ASSERT_TRUE(left.Equals(right));
}

TEST_F(TestChunkedArray, SliceEquals) {
  arrays_one_.push_back(MakeRandomArray<Int32Array>(100));
  arrays_one_.push_back(MakeRandomArray<Int32Array>(50));
  arrays_one_.push_back(MakeRandomArray<Int32Array>(50));
  Construct();

  std::shared_ptr<ChunkedArray> slice = one_->Slice(125, 50);
  ASSERT_EQ(slice->length(), 50);
  AssertChunkedEqual(*one_->Slice(125, 50), *slice);

  std::shared_ptr<ChunkedArray> slice2 = one_->Slice(75)->Slice(25)->Slice(25, 50);
  ASSERT_EQ(slice2->length(), 50);
  AssertChunkedEqual(*slice, *slice2);

  // Making empty slices of a ChunkedArray
  std::shared_ptr<ChunkedArray> slice3 = one_->Slice(one_->length(), 99);
  ASSERT_EQ(slice3->length(), 0);
  ASSERT_EQ(slice3->num_chunks(), 1);
  ASSERT_TRUE(slice3->type()->Equals(one_->type()));

  std::shared_ptr<ChunkedArray> slice4 = one_->Slice(10, 0);
  ASSERT_EQ(slice4->length(), 0);
  ASSERT_EQ(slice4->num_chunks(), 1);
  ASSERT_TRUE(slice4->type()->Equals(one_->type()));

  // Slicing an empty ChunkedArray
  std::shared_ptr<ChunkedArray> slice5 = slice4->Slice(0, 10);
  ASSERT_EQ(slice5->length(), 0);
  ASSERT_EQ(slice5->num_chunks(), 1);
  ASSERT_TRUE(slice5->type()->Equals(one_->type()));
}

TEST_F(TestChunkedArray, ZeroChunksIssues) {
  ArrayVector empty = {};
  auto no_chunks = std::make_shared<ChunkedArray>(empty, int8());

  // ARROW-8911, assert that slicing is a no-op when there are zero-chunks
  auto sliced = no_chunks->Slice(0, 0);
  auto sliced2 = no_chunks->Slice(0, 5);
  AssertChunkedEqual(*no_chunks, *sliced);
  AssertChunkedEqual(*no_chunks, *sliced2);
}

TEST_F(TestChunkedArray, Validate) {
  // Valid if empty
  ArrayVector empty = {};
  auto no_chunks = std::make_shared<ChunkedArray>(empty, utf8());
  ASSERT_OK(no_chunks->ValidateFull());

  random::RandomArrayGenerator gen(0);
  arrays_one_.push_back(gen.Int32(50, 0, 100, 0.1));
  Construct();
  ASSERT_OK(one_->ValidateFull());

  arrays_one_.push_back(gen.Int32(50, 0, 100, 0.1));
  Construct();
  ASSERT_OK(one_->ValidateFull());

  arrays_one_.push_back(gen.String(50, 0, 10, 0.1));
  Construct();
  ASSERT_RAISES(Invalid, one_->ValidateFull());
}

TEST_F(TestChunkedArray, PrintDiff) {
  random::RandomArrayGenerator gen(0);
  arrays_one_.push_back(gen.Int32(50, 0, 100, 0.1));
  Construct();

  auto other = one_->Slice(25);
  ASSERT_OK_AND_ASSIGN(auto diff, PrintArrayDiff(*one_, *other));
  ASSERT_EQ(*diff, "Expected length 50 but was actually 25");

  ASSERT_OK_AND_ASSIGN(diff, PrintArrayDiff(*other, *one_));
  ASSERT_EQ(*diff, "Expected length 25 but was actually 50");
}

TEST_F(TestChunkedArray, View) {
  auto in_ty = int32();
  auto out_ty = fixed_size_binary(4);
#if ARROW_LITTLE_ENDIAN
  auto arr = ArrayFromJSON(in_ty, "[2020568934, 2054316386, null]");
  auto arr2 = ArrayFromJSON(in_ty, "[2020568934, 2054316386]");
#else
  auto arr = ArrayFromJSON(in_ty, "[1718579064, 1650553466, null]");
  auto arr2 = ArrayFromJSON(in_ty, "[1718579064, 1650553466]");
#endif
  auto ex = ArrayFromJSON(out_ty, R"(["foox", "barz", null])");
  auto ex2 = ArrayFromJSON(out_ty, R"(["foox", "barz"])");

  ArrayVector chunks = {arr, arr2};
  ArrayVector ex_chunks = {ex, ex2};
  auto carr = std::make_shared<ChunkedArray>(chunks);
  auto expected = std::make_shared<ChunkedArray>(ex_chunks);

  ASSERT_OK_AND_ASSIGN(auto result, carr->View(out_ty));
  AssertChunkedEqual(*expected, *result);

  // Zero length
  ArrayVector empty = {};
  carr = std::make_shared<ChunkedArray>(empty, in_ty);
  expected = std::make_shared<ChunkedArray>(empty, out_ty);
  ASSERT_OK_AND_ASSIGN(result, carr->View(out_ty));
  AssertChunkedEqual(*expected, *result);
}

}  // namespace arrow


text:
require_relative 'DoorFactory'
require_relative 'IronDoor'
require_relative 'Welder'

class IronDoorFactory include DoorFactory
  def make_door
    return IronDoor.new
  end

  def make_fitting_expert
    return Welder.new
  end
end


text:
from test_helper import TestHelper

from app import app, db
from app.models.plant import Plant

class TestPlant(TestHelper):

    def test_create_plant(self):
        p = Plant(group_id='999', plant_id='011', name_common='Feather Reed Grass', name_botanical="other")
        assert Plant.save_to_db(p) == True
        plant = Plant.find_by_botanical("other")
        assert plant != None

    def test_validation(self):
        p1 = Plant(group_id='999', plant_id='011', name_common='Feather Reed Grass', name_botanical="other")
        Plant.save_to_db(p1)
        p2 = Plant(group_id='999', plant_id='011', name_common='Feather Reed Grass', name_botanical="other")
        assert Plant.save_to_db(p2) == False


text:
package com.cellbots;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * Allow a user to edit or create a robot profile. The profile contains
 * information like the name, method of connection, etc.
 *
 * @see RobotEntry.java
 *@author css@google.com (Charles Spirakis)
 */
public class RobotCreationActivity extends RobotBaseCreate {
    private static final String TAG = "CellbotRobotCreation";

    private static final int INTENT_BLUETOOTH_DEVICES = 1;

    private EditText mFieldName;

    private Spinner mFieldType;

    private Spinner mFieldBluetooth;

    private LinearLayout mTopChoiceLayout;

    private LinearLayout mCreateProfileLayout;

    private int editIndex;

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

        setContentView(R.layout.robot_creation);
        final Activity self = this;

        mFieldName = (EditText) findViewById(R.id.create_name);
        mFieldType = (Spinner) findViewById(R.id.create_type);
        mFieldBluetooth = (Spinner) findViewById(R.id.create_bluetooth);
        mTopChoiceLayout = (LinearLayout) findViewById(R.id.top_choices_view);
        mCreateProfileLayout = (LinearLayout) findViewById(R.id.add_cellbot_profile_view);

        setupRobotTypeList(this, mFieldType);
        setupBluetoothPairList(mFieldBluetooth);

        if (mIsEdit) {
            if (mName.length() < 1) {
                Log.e(TAG, "Bad name passed to creation");
                // treat as a create
            } else {
                // If this is an edit, pre-fill in fields.
                Log.d(TAG, "adding edit information");

                // Always fill in the name if we have one.
                mFieldName.setText(mName);

                // Find the name that matches
                editIndex = mRobotProfiles.findIndexByName(mName);
                if (editIndex >= 0) {
                    RobotEntry entry = mRobotProfiles.getEntry(editIndex);
                    fillFormFromEntry(entry);
                }
            }
        }

        // Finally, setup the buttons
        setupCancelButton(self, R.id.create_cancel);
        setupQrScanButton(self, R.id.create_scan_qrcode);

        Button saveButton = (Button) findViewById(R.id.create_save);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Saving");

                String name = getStringFromField(mFieldName.getText());
                if (name.length() <= 0) {
                    // No name, so tell them and let them try again.
                    Toast.makeText(getApplicationContext(),
                            "Robot needs a name",
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String type = getStringFromField(mFieldType.getSelectedItem());
                String bluetoothPair = getStringFromField(mFieldBluetooth.getSelectedItem());

                String[] blueInfo = RobotEntry.splitNameMacPair(bluetoothPair);

                RobotEntry entry = RobotEntry.newDirectRobotEntry(
                        name, type, blueInfo[0], blueInfo[1]);

                if (mIsEdit) {
                  if (!mRobotProfiles.replaceEntry(editIndex, entry)) {
                      new AlertDialog.Builder(RobotCreationActivity.this).setTitle("Error")
                              .setMessage(R.string.edit_failed_msg)
                              .setPositiveButton(android.R.string.ok, null)
                              .create().show();
                      return;
                  }
                } else {
                    // Save the new profile in the robot list
                    if (!mRobotProfiles.addEntry(entry)) {
                        new AlertDialog.Builder(RobotCreationActivity.this).setTitle("Error")
                                .setMessage(R.string.add_failed_msg)
                                .setPositiveButton(android.R.string.ok, null)
                                .create().show();
                        return;
                    }
                }
                mRobotProfiles.save();

                // If this was a create, then we want to start
                // driving the robot now.
                if (!mIsEdit) {
                    Intent i = new Intent();
                    i.setClass(self, com.cellbots.directcontrol.CellDroidActivity.class);
                    i.putExtra(RobotSelectionActivity.EXTRA_NAME, entry.getName());
                    startActivity(i);
                }

                // Done with this activity. We're either driving a robot at this
                // point or we're heading back to the list of robots.
                self.setResult(RobotSelectionActivity.RESULT_SAVE);
                self.finish();
            }
        });

        Button skipToCloudButton = (Button) findViewById(R.id.create_goto_cloud);
        skipToCloudButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Cloud Remote");
                // if we are heading off to web remote land, we are done here.
                self.setResult(RobotSelectionActivity.RESULT_START_WEB_CREATE);
                self.finish();
            }
        });

        Button chooseDevice = (Button) findViewById(R.id.check_devices);
        chooseDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Device");
                Intent i = new Intent();
                i.setClass(self, com.cellbots.FindBluetoothDevicesActivity.class);
                startActivityForResult(i, INTENT_BLUETOOTH_DEVICES);
            }
        });

        Button createCellbotProfile = (Button) findViewById(R.id.create_cellbot);
        createCellbotProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              showCreateProfileLayout();
            }
        });

        if (mIsEdit) {
          showCreateProfileLayout();
        }
    }

    private void showCreateProfileLayout() {
      mCreateProfileLayout.setVisibility(View.VISIBLE);
      mCreateProfileLayout.setLayoutParams(new LinearLayout.LayoutParams(
              LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
      mTopChoiceLayout.setVisibility(View.INVISIBLE);
      mTopChoiceLayout.setLayoutParams(new LinearLayout.LayoutParams(
              LayoutParams.FILL_PARENT, 0));
    }

    private void fillFormFromEntry(RobotEntry entry) {
        for (int i = 0; i < mCellbotTypes.length; i++) {
            if (entry.getType().equals(mCellbotTypes[i])) {
                mFieldType.setSelection(i);
            }
        }
        for (int i = 0; i < mCellbotBts.length; i++) {
            if (entry.createNameMacPair().equals(mCellbotBts[i])) {
                mFieldBluetooth.setSelection(i);
            }
        }
    }

    protected void robotScanResult(RobotEntry scannedEntry) {
        fillFormFromEntry(scannedEntry);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == INTENT_BLUETOOTH_DEVICES) {
            if (resultCode == FindBluetoothDevicesActivity.RESULT_OK) {
                // User may have changed the pairings, so rescan the available
                // bluetooth devices.
                setupBluetoothPairList(mFieldBluetooth);
                Bundle extras = data.getExtras();
                if (extras != null) {
                    String btName = extras.getString(
                            FindBluetoothDevicesActivity.EXTRA_BLUETOOTH_NAME);
                    String btMac = extras.getString(
                        FindBluetoothDevicesActivity.EXTRA_BLUETOOTH_MAC);
                    if ((btName != null) && (btName.length() > 0)) {
                        String pairName = RobotEntry.generateNameMacPair(btName, btMac);
                        for (int i = 0; i < mCellbotBts.length; i++) {
                            if (pairName.equals(mCellbotBts[i])) {
                                mFieldBluetooth.setSelection(i);
                            }
                        }
                    }
                }
            }
        } else {
            Log.e(TAG, "unexpected activity requestCode: " + requestCode);
        }
    }
}


text:
using KubeClient;
using KubeClient.Models;
using Ocelot.Logging;
using Ocelot.ServiceDiscovery.Providers;
using Ocelot.Values;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Ocelot.Provider.Kubernetes
{
    public class Kube : IServiceDiscoveryProvider
    {
        private KubeRegistryConfiguration kubeRegistryConfiguration;
        private IOcelotLogger logger;
        private IKubeApiClient kubeApi;

        public Kube(KubeRegistryConfiguration kubeRegistryConfiguration, IOcelotLoggerFactory factory, IKubeApiClient kubeApi)
        {
            this.kubeRegistryConfiguration = kubeRegistryConfiguration;
            this.logger = factory.CreateLogger<Kube>();
            this.kubeApi = kubeApi;
        }

        public async Task<List<Service>> Get()
        {
            var service = await kubeApi.ServicesV1().Get(kubeRegistryConfiguration.KeyOfServiceInK8s, kubeRegistryConfiguration.KubeNamespace);
            var services = new List<Service>();
            if (IsValid(service))
            {
                services.Add(BuildService(service));
            }
            else
            {
                logger.LogWarning($"namespace:{kubeRegistryConfiguration.KubeNamespace }service:{kubeRegistryConfiguration.KeyOfServiceInK8s} Unable to use ,it is invalid. Address must contain host only e.g. localhost and port must be greater than 0");
            }
            return services;
        }

        private bool IsValid(ServiceV1 service)
        {
            if (string.IsNullOrEmpty(service.Spec.ClusterIP) || service.Spec.Ports.Count <= 0)
            {
                return false;
            }

            return true;
        }

        private Service BuildService(ServiceV1 serviceEntry)
        {
            var servicePort = serviceEntry.Spec.Ports.FirstOrDefault();
            return new Service(
                serviceEntry.Metadata.Name,
                new ServiceHostAndPort(serviceEntry.Spec.ClusterIP, servicePort.Port),
                serviceEntry.Metadata.Uid,
                string.Empty,
                Enumerable.Empty<string>());
        }
    }
}


text:
"""
This is a most naive algorithm. For each sentence it assumes each word is generated by the
domain it belongs to. It simply predict the target domain d as the one that maximize the value of:
P(w1|d) * P(w2|d) * ... * P(wn|d)
Use backoff discounting for words never occured in domain d. Ignore words never seen in the
training data.

http://en.wikipedia.org/wiki/Katz's_back-off_model
"""

import sys, os, math
import argparse
import cPickle as pickle
from collections import defaultdict
import numpy as np
from sklearn import cross_validation
from util import conv
from util.log import _logger
from feat.terms.term_categorize import term_category

class NaiveBayes(object):
    def __init__(self, train_path, term_path, alpha = 0.5):
        self.train_path = train_path
        self.term_path = term_path
        self.alpha = alpha
        self.reset()
        self.load_data()

    def get_category(self, term):
        return term_category(term)

    def load_data(self):
        _logger.info("Loading training data from %s" % self.train_path)
        self.X = []
        self.y = []
        with open(self.train_path) as train_file:
            for line in train_file:
                line = line.strip().decode('utf-8')
                if not line:
                    continue
                terms, domain = line.split('\t')
                self.X.append(terms)
                self.y.append(domain)

    def reset(self):
        self.training_sentence_count = 0
        self.count = defaultdict(int)
        self.domain_has = defaultdict(set)
        self.domain_count = defaultdict(int) # Number of sentence in each domain
        self.domain_backoff = dict()
        self.term_count = defaultdict(int)
        self.terms = set()

    def fit(self, X, y):
        self.reset()
        size = len(y)
        for i in xrange(size):
            if (i + 1) % 10000 == 0:
                _logger.debug("%d processed" % (i+1))
            terms = X[i]
            domain = y[i]
            self.training_sentence_count += 1
            terms = terms.split(' ')
            self.domain_count[domain] += 1
            term_set = set()
            for term in terms:
                term = self.get_category(term)
                if term in term_set:
                    continue
                term_set.add(term)
                self.terms.add(term)
                self.count[term, domain] += 1
                self.count[domain] += 1
                self.term_count[term] += 1
                self.domain_has[domain].add(term)

        for domain in self.domain_has:
            backoff = len(self.domain_has[domain]) * self.alpha / self.count[domain]
            backoff /= len(self.term_count) - len(self.domain_has[domain])
            self.domain_backoff[domain] = backoff

        self.domains = self.domain_backoff.keys()

    def train(self):
        self.fit(self.X, self.y)

    def get_test_accuracy(self, X, y):
        total = len(y)
        correct = 0.0
        from decode import NaiveDecoder
        decoder = NaiveDecoder(self)
        for idx, x in enumerate(X):
            y_pred = decoder.predict(x)
            if y_pred == y[idx]:
                correct += 1
        return correct / total

    def cv(self, fold):
        size = len(self.y)
        kf = cross_validation.KFold(size, fold, shuffle=True)
        iteration = 0
        scores = list()
        for train_idx, test_idx in kf:
            X = [self.X[idx] for idx in train_idx]
            y = [self.y[idx] for idx in train_idx]
            X_test = [self.X[idx] for idx in test_idx]
            y_test = [self.y[idx] for idx in test_idx]
            _logger.debug("Training...")
            self.fit(X, y)
            _logger.debug("Testing...")
            score = self.get_test_accuracy(X_test, y_test)
            scores.append(score)
            iteration += 1
            _logger.info("CV iteration %d: CV accuracy: %f" % \
                             (iteration, score))

        scores = np.array(scores)
        return scores.mean(), scores.std()

if __name__ == "__main__":
    cmd = argparse.ArgumentParser()
    cmd.add_argument("--input", help="path of the training data",default="train.dat")
    cmd.add_argument("--terms", help="path of the terms file",default="terms.dat")
    cmd.add_argument("--alpha", help="alpha of discounting", type=float, default=0.5)
    cmd.add_argument("--cv", help="enable cross validation", type=int, default=0)
    args = cmd.parse_args()

    naive = NaiveBayes(conv.redirect(args.input), conv.redirect(args.terms), args.alpha)
    if args.cv > 0:
        _logger.info("CV accuracy: %f +/- %f" % naive.cv(args.cv))
    else:
        _logger.info("Start training");
        naive.train()
        with open("naive.model", "w") as outfile:
            pickle.dump(naive, outfile)
            _logger.info("Model dumped to naive.model")


text:
namespace cast {
namespace utils {
namespace {

using ::cast::test::StatusIs;

static const auto kEventTimeout = base::Seconds(1);
static const auto kServerStopTimeout = base::Seconds(1);

class GrpcUnaryTest : public ::testing::Test {
 protected:
  GrpcUnaryTest()
      : grpc_client_task_runner_(
            base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) {
    CHECK(temp_dir_.CreateUniqueTempDir());
    endpoint_ = "unix:" +
                temp_dir_.GetPath()
                    .AppendASCII("cast-uds-" + base::GenerateGUID().substr(24))
                    .value();
  }

  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  scoped_refptr<base::SequencedTaskRunner> grpc_client_task_runner_;
  base::ScopedTempDir temp_dir_;
  std::string endpoint_;
};

TEST_F(GrpcUnaryTest, SyncUnaryCallSucceeds) {
  GrpcServer server;
  server.SetHandler<SimpleServiceHandler::SimpleCall>(
      base::BindLambdaForTesting(
          [](TestRequest request,
             SimpleServiceHandler::SimpleCall::Reactor* reactor) {
            EXPECT_EQ(request.foo(), "test_foo");
            TestResponse response;
            response.set_bar("test_bar");
            reactor->Write(std::move(response));
          }));
  server.Start(endpoint_);

  SimpleServiceStub stub(endpoint_);
  auto call = stub.CreateCall<SimpleServiceStub::SimpleCall>();
  call.request().set_foo("test_foo");
  auto response = std::move(call).Invoke();
  CU_ASSERT_OK(response);
  EXPECT_EQ(response->bar(), "test_bar");

  server.StopForTesting(kServerStopTimeout);
}

TEST_F(GrpcUnaryTest, SyncUnaryCallReturnsErrorStatus) {
  GrpcServer server;
  server.SetHandler<SimpleServiceHandler::SimpleCall>(
      base::BindLambdaForTesting(
          [&](TestRequest request,
              SimpleServiceHandler::SimpleCall::Reactor* reactor) {
            EXPECT_EQ(request.foo(), "test_foo");
            reactor->Write(
                grpc::Status(grpc::StatusCode::NOT_FOUND, "Not found"));
          }));
  server.Start(endpoint_);

  SimpleServiceStub stub(endpoint_);
  auto call = stub.CreateCall<SimpleServiceStub::SimpleCall>();
  call.request().set_foo("test_foo");
  auto response = std::move(call).Invoke();
  ASSERT_THAT(response.status(),
              StatusIs(grpc::StatusCode::NOT_FOUND, "Not found"));

  server.StopForTesting(kServerStopTimeout);
}

TEST_F(GrpcUnaryTest, SyncUnaryCallCancelledIfServerIsStopped) {
  GrpcServer server;
  base::WaitableEvent server_stopped_event;
  server.SetHandler<SimpleServiceHandler::SimpleCall>(
      base::BindLambdaForTesting(
          [&](TestRequest request,
              SimpleServiceHandler::SimpleCall::Reactor* reactor) {
            // Stop the server to trigger call cancellation.
            server.Stop(base::Milliseconds(100),
                        base::BindLambdaForTesting(
                            [&]() { server_stopped_event.Signal(); }));
          }));
  server.Start(endpoint_);

  SimpleServiceStub stub(endpoint_);
  auto call = stub.CreateCall<SimpleServiceStub::SimpleCall>();
  call.request().set_foo("test_foo");
  auto response = std::move(call).Invoke();
  ASSERT_THAT(response, StatusIs(grpc::StatusCode::UNAVAILABLE));

  // Need to wait for server to fully stop.
  ASSERT_TRUE(server_stopped_event.TimedWait(kEventTimeout));
}

TEST_F(GrpcUnaryTest, AsyncUnaryCallSucceeds) {
  GrpcServer server;
  server.SetHandler<SimpleServiceHandler::SimpleCall>(base::BindPostTask(
      grpc_client_task_runner_,
      base::BindLambdaForTesting(
          [](TestRequest request,
             SimpleServiceHandler::SimpleCall::Reactor* reactor) {
            EXPECT_EQ(request.foo(), "test_foo");
            TestResponse response;
            response.set_bar("test_bar");
            reactor->Write(std::move(response));
          })));
  server.Start(endpoint_);

  SimpleServiceStub stub(endpoint_);
  auto call = stub.CreateCall<SimpleServiceStub::SimpleCall>();
  call.request().set_foo("test_foo");
  base::WaitableEvent response_received_event;
  std::move(call).InvokeAsync(
      base::BindLambdaForTesting([&](GrpcStatusOr<TestResponse> response) {
        CU_CHECK_OK(response);
        EXPECT_EQ(response->bar(), "test_bar");
        response_received_event.Signal();
      }));
  {
    base::ScopedAllowBaseSyncPrimitivesForTesting allow_base_sync_primitives;
    ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout));
  }

  server.StopForTesting(kServerStopTimeout);
}

TEST_F(GrpcUnaryTest, AsyncUnaryCallReturnsErrorStatus) {
  GrpcServer server;
  server.SetHandler<SimpleServiceHandler::SimpleCall>(base::BindPostTask(
      grpc_client_task_runner_,
      base::BindLambdaForTesting(
          [&](TestRequest request,
              SimpleServiceHandler::SimpleCall::Reactor* reactor) {
            EXPECT_EQ(request.foo(), "test_foo");
            reactor->Write(
                grpc::Status(grpc::StatusCode::NOT_FOUND, "Not Found"));
          })));
  server.Start(endpoint_);

  SimpleServiceStub stub(endpoint_);
  auto call = stub.CreateCall<SimpleServiceStub::SimpleCall>();
  call.request().set_foo("test_foo");
  base::WaitableEvent response_received_event;
  std::move(call).InvokeAsync(base::BindPostTask(
      grpc_client_task_runner_,
      base::BindLambdaForTesting([&](GrpcStatusOr<TestResponse> response) {
        ASSERT_THAT(response.status(),
                    StatusIs(grpc::StatusCode::NOT_FOUND, "Not Found"));
        response_received_event.Signal();
      })));
  {
    base::ScopedAllowBaseSyncPrimitivesForTesting allow_base_sync_primitives;
    ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout));
  }

  server.StopForTesting(kServerStopTimeout);
}

TEST_F(GrpcUnaryTest, AsyncUnaryCallCancelledIfServerIsStopped) {
  GrpcServer server;
  base::WaitableEvent server_stopped_event;
  server.SetHandler<SimpleServiceHandler::SimpleCall>(base::BindPostTask(
      grpc_client_task_runner_,
      base::BindLambdaForTesting(
          [&](TestRequest request,
              SimpleServiceHandler::SimpleCall::Reactor* reactor) {
            // Stop the server to trigger call cancellation.
            server.Stop(base::Milliseconds(100),
                        base::BindLambdaForTesting(
                            [&]() { server_stopped_event.Signal(); }));
          })));
  server.Start(endpoint_);

  SimpleServiceStub stub(endpoint_);
  auto call = stub.CreateCall<SimpleServiceStub::SimpleCall>();
  call.request().set_foo("test_foo");
  base::WaitableEvent response_received_event;
  std::move(call).InvokeAsync(base::BindPostTask(
      grpc_client_task_runner_,
      base::BindLambdaForTesting([&](GrpcStatusOr<TestResponse> response) {
        ASSERT_THAT(response, StatusIs(grpc::StatusCode::UNAVAILABLE));
        response_received_event.Signal();
      })));
  {
    base::ScopedAllowBaseSyncPrimitivesForTesting allow_base_sync_primitives;
    ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout));

    // Need to wait for server to fully stop.
    ASSERT_TRUE(server_stopped_event.TimedWait(kEventTimeout));
  }
}

TEST_F(GrpcUnaryTest, SyncUnaryCallSucceedsExtra) {
  GrpcServer server;
  server.SetHandler<SimpleServiceExtraHandler::SimpleCall>(
      base::BindLambdaForTesting(
          [](TestExtraRequest request,
             SimpleServiceExtraHandler::SimpleCall::Reactor* reactor) {
            EXPECT_EQ(request.extra(), "test_extra");
            TestResponse response;
            response.set_bar("test_bar");
            reactor->Write(std::move(response));
          }));
  server.Start(endpoint_);

  SimpleServiceExtraStub stub(endpoint_);
  auto call = stub.CreateCall<SimpleServiceExtraStub::SimpleCall>();
  call.request().set_extra("test_extra");
  auto response = std::move(call).Invoke();
  CU_ASSERT_OK(response);
  EXPECT_EQ(response->bar(), "test_bar");

  server.StopForTesting(kServerStopTimeout);
}

}  // namespace
}  // namespace utils
}  // namespace cast


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Anal. Soc. cient. argent. 22(4): 196 (1886)

#### Original name
Capnodium paraguayense Speg.

### Remarks
null


text:
#include "config.h"
#include "core/layout/LayoutTheme.h"

#include "core/CSSValueKeywords.h"
#include "core/HTMLNames.h"
#include "core/InputTypeNames.h"
#include "core/dom/Document.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/editing/FrameSelection.h"
#include "core/fileapi/FileList.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/html/HTMLCollection.h"
#include "core/html/HTMLDataListElement.h"
#include "core/html/HTMLDataListOptionsCollection.h"
#include "core/html/HTMLFormControlElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLMeterElement.h"
#include "core/html/HTMLOptionElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/shadow/MediaControlElements.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/html/shadow/SpinButtonElement.h"
#include "core/html/shadow/TextControlInnerElements.h"
#include "core/layout/LayoutMeter.h"
#include "core/layout/LayoutView.h"
#include "core/layout/PaintInfo.h"
#include "core/layout/style/AuthorStyleInfo.h"
#include "core/layout/style/LayoutStyle.h"
#include "core/page/FocusController.h"
#include "core/page/Page.h"
#include "platform/FileMetadata.h"
#include "platform/FloatConversion.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/fonts/FontSelector.h"
#include "platform/graphics/GraphicsContextStateSaver.h"
#include "platform/text/PlatformLocale.h"
#include "platform/text/StringTruncator.h"
#include "public/platform/Platform.h"
#include "public/platform/WebFallbackThemeEngine.h"
#include "public/platform/WebRect.h"
#include "wtf/text/StringBuilder.h"

// The methods in this file are shared by all themes on every platform.

namespace blink {

using namespace HTMLNames;

static WebFallbackThemeEngine::State getWebFallbackThemeState(const LayoutTheme* theme, const LayoutObject* o)
{
    if (!theme->isEnabled(o))
        return WebFallbackThemeEngine::StateDisabled;
    if (theme->isPressed(o))
        return WebFallbackThemeEngine::StatePressed;
    if (theme->isHovered(o))
        return WebFallbackThemeEngine::StateHover;

    return WebFallbackThemeEngine::StateNormal;
}

LayoutTheme::LayoutTheme()
    : m_hasCustomFocusRingColor(false)
#if USE(NEW_THEME)
    , m_platformTheme(platformTheme())
#endif
{
}

void LayoutTheme::adjustStyle(LayoutStyle& style, Element* e, const AuthorStyleInfo& authorStyle)
{
    ASSERT(style.hasAppearance());

    // Force inline and table display styles to be inline-block (except for table- which is block)
    ControlPart part = style.appearance();
    if (style.display() == INLINE || style.display() == INLINE_TABLE || style.display() == TABLE_ROW_GROUP
        || style.display() == TABLE_HEADER_GROUP || style.display() == TABLE_FOOTER_GROUP
        || style.display() == TABLE_ROW || style.display() == TABLE_COLUMN_GROUP || style.display() == TABLE_COLUMN
        || style.display() == TABLE_CELL || style.display() == TABLE_CAPTION)
        style.setDisplay(INLINE_BLOCK);
    else if (style.display() == LIST_ITEM || style.display() == TABLE)
        style.setDisplay(BLOCK);

    if (isControlStyled(style, authorStyle)) {
        if (part == MenulistPart) {
            style.setAppearance(MenulistButtonPart);
            part = MenulistButtonPart;
        } else {
            style.setAppearance(NoControlPart);
        }
    }

    if (!style.hasAppearance())
        return;

    if (shouldUseFallbackTheme(style)) {
        adjustStyleUsingFallbackTheme(style, e);
        return;
    }

#if USE(NEW_THEME)
    switch (part) {
    case CheckboxPart:
    case InnerSpinButtonPart:
    case RadioPart:
    case PushButtonPart:
    case SquareButtonPart:
    case ButtonPart: {
        // Border
        LengthBox borderBox(style.borderTopWidth(), style.borderRightWidth(), style.borderBottomWidth(), style.borderLeftWidth());
        borderBox = m_platformTheme->controlBorder(part, style.font().fontDescription(), borderBox, style.effectiveZoom());
        if (borderBox.top().value() != static_cast<int>(style.borderTopWidth())) {
            if (borderBox.top().value())
                style.setBorderTopWidth(borderBox.top().value());
            else
                style.resetBorderTop();
        }
        if (borderBox.right().value() != static_cast<int>(style.borderRightWidth())) {
            if (borderBox.right().value())
                style.setBorderRightWidth(borderBox.right().value());
            else
                style.resetBorderRight();
        }
        if (borderBox.bottom().value() != static_cast<int>(style.borderBottomWidth())) {
            style.setBorderBottomWidth(borderBox.bottom().value());
            if (borderBox.bottom().value())
                style.setBorderBottomWidth(borderBox.bottom().value());
            else
                style.resetBorderBottom();
        }
        if (borderBox.left().value() != static_cast<int>(style.borderLeftWidth())) {
            style.setBorderLeftWidth(borderBox.left().value());
            if (borderBox.left().value())
                style.setBorderLeftWidth(borderBox.left().value());
            else
                style.resetBorderLeft();
        }

        // Padding
        LengthBox paddingBox = m_platformTheme->controlPadding(part, style.font().fontDescription(), style.paddingBox(), style.effectiveZoom());
        if (paddingBox != style.paddingBox())
            style.setPaddingBox(paddingBox);

        // Whitespace
        if (m_platformTheme->controlRequiresPreWhiteSpace(part))
            style.setWhiteSpace(PRE);

        // Width / Height
        // The width and height here are affected by the zoom.
        // FIXME: Check is flawed, since it doesn't take min-width/max-width into account.
        LengthSize controlSize = m_platformTheme->controlSize(part, style.font().fontDescription(), LengthSize(style.width(), style.height()), style.effectiveZoom());
        if (controlSize.width() != style.width())
            style.setWidth(controlSize.width());
        if (controlSize.height() != style.height())
            style.setHeight(controlSize.height());

        // Min-Width / Min-Height
        LengthSize minControlSize = m_platformTheme->minimumControlSize(part, style.font().fontDescription(), style.effectiveZoom());
        if (minControlSize.width() != style.minWidth())
            style.setMinWidth(minControlSize.width());
        if (minControlSize.height() != style.minHeight())
            style.setMinHeight(minControlSize.height());

        // Font
        FontDescription controlFont = m_platformTheme->controlFont(part, style.font().fontDescription(), style.effectiveZoom());
        if (controlFont != style.font().fontDescription()) {
            // Reset our line-height
            style.setLineHeight(LayoutStyle::initialLineHeight());

            // Now update our font.
            if (style.setFontDescription(controlFont))
                style.font().update(nullptr);
        }
    }
    default:
        break;
    }
#endif

    // Call the appropriate style adjustment method based off the appearance value.
    switch (style.appearance()) {
#if !USE(NEW_THEME)
    case CheckboxPart:
        return adjustCheckboxStyle(style, e);
    case RadioPart:
        return adjustRadioStyle(style, e);
    case PushButtonPart:
    case SquareButtonPart:
    case ButtonPart:
        return adjustButtonStyle(style, e);
    case InnerSpinButtonPart:
        return adjustInnerSpinButtonStyle(style, e);
#endif
    case MenulistPart:
        return adjustMenuListStyle(style, e);
    case MenulistButtonPart:
        return adjustMenuListButtonStyle(style, e);
    case SliderThumbHorizontalPart:
    case SliderThumbVerticalPart:
        return adjustSliderThumbStyle(style, e);
    case SearchFieldPart:
        return adjustSearchFieldStyle(style, e);
    case SearchFieldCancelButtonPart:
        return adjustSearchFieldCancelButtonStyle(style, e);
    case SearchFieldDecorationPart:
        return adjustSearchFieldDecorationStyle(style, e);
    case SearchFieldResultsDecorationPart:
        return adjustSearchFieldResultsDecorationStyle(style, e);
    default:
        break;
    }
}

bool LayoutTheme::paint(LayoutObject* o, const PaintInfo& paintInfo, const IntRect& r)
{
    ControlPart part = o->styleRef().appearance();

    if (shouldUseFallbackTheme(o->styleRef()))
        return paintUsingFallbackTheme(o, paintInfo, r);

#if USE(NEW_THEME)
    switch (part) {
    case CheckboxPart:
    case RadioPart:
    case PushButtonPart:
    case SquareButtonPart:
    case ButtonPart:
    case InnerSpinButtonPart:
        m_platformTheme->paint(part, controlStatesForRenderer(o), const_cast<GraphicsContext*>(paintInfo.context), r, o->styleRef().effectiveZoom(), o->view()->frameView());
        return false;
    default:
        break;
    }
#endif

    // Call the appropriate paint method based off the appearance value.
    switch (part) {
#if !USE(NEW_THEME)
    case CheckboxPart:
        return paintCheckbox(o, paintInfo, r);
    case RadioPart:
        return paintRadio(o, paintInfo, r);
    case PushButtonPart:
    case SquareButtonPart:
    case ButtonPart:
        return paintButton(o, paintInfo, r);
    case InnerSpinButtonPart:
        return paintInnerSpinButton(o, paintInfo, r);
#endif
    case MenulistPart:
        return paintMenuList(o, paintInfo, r);
    case MeterPart:
    case RelevancyLevelIndicatorPart:
    case ContinuousCapacityLevelIndicatorPart:
    case DiscreteCapacityLevelIndicatorPart:
    case RatingLevelIndicatorPart:
        return paintMeter(o, paintInfo, r);
    case ProgressBarPart:
        return paintProgressBar(o, paintInfo, r);
    case SliderHorizontalPart:
    case SliderVerticalPart:
        return paintSliderTrack(o, paintInfo, r);
    case SliderThumbHorizontalPart:
    case SliderThumbVerticalPart:
        return paintSliderThumb(o, paintInfo, r);
    case MediaEnterFullscreenButtonPart:
    case MediaExitFullscreenButtonPart:
        return paintMediaFullscreenButton(o, paintInfo, r);
    case MediaPlayButtonPart:
        return paintMediaPlayButton(o, paintInfo, r);
    case MediaOverlayPlayButtonPart:
        return paintMediaOverlayPlayButton(o, paintInfo, r);
    case MediaMuteButtonPart:
        return paintMediaMuteButton(o, paintInfo, r);
    case MediaToggleClosedCaptionsButtonPart:
        return paintMediaToggleClosedCaptionsButton(o, paintInfo, r);
    case MediaSliderPart:
        return paintMediaSliderTrack(o, paintInfo, r);
    case MediaSliderThumbPart:
        return paintMediaSliderThumb(o, paintInfo, r);
    case MediaVolumeSliderContainerPart:
        return paintMediaVolumeSliderContainer(o, paintInfo, r);
    case MediaVolumeSliderPart:
        return paintMediaVolumeSliderTrack(o, paintInfo, r);
    case MediaVolumeSliderThumbPart:
        return paintMediaVolumeSliderThumb(o, paintInfo, r);
    case MediaFullScreenVolumeSliderPart:
        return paintMediaFullScreenVolumeSliderTrack(o, paintInfo, r);
    case MediaFullScreenVolumeSliderThumbPart:
        return paintMediaFullScreenVolumeSliderThumb(o, paintInfo, r);
    case MediaTimeRemainingPart:
        return paintMediaTimeRemaining(o, paintInfo, r);
    case MediaCurrentTimePart:
        return paintMediaCurrentTime(o, paintInfo, r);
    case MediaControlsBackgroundPart:
        return paintMediaControlsBackground(o, paintInfo, r);
    case MediaCastOffButtonPart:
        return paintMediaCastButton(o, paintInfo, r);
    case MediaOverlayCastOffButtonPart:
        return paintMediaCastButton(o, paintInfo, r);
    case MenulistButtonPart:
    case TextFieldPart:
    case TextAreaPart:
        return true;
    case SearchFieldPart:
        return paintSearchField(o, paintInfo, r);
    case SearchFieldCancelButtonPart:
        return paintSearchFieldCancelButton(o, paintInfo, r);
    case SearchFieldDecorationPart:
        return paintSearchFieldDecoration(o, paintInfo, r);
    case SearchFieldResultsDecorationPart:
        return paintSearchFieldResultsDecoration(o, paintInfo, r);
    default:
        break;
    }

    return true; // We don't support the appearance, so let the normal background/border paint.
}

bool LayoutTheme::paintBorderOnly(LayoutObject* o, const PaintInfo& paintInfo, const IntRect& r)
{
    // Call the appropriate paint method based off the appearance value.
    switch (o->style()->appearance()) {
    case TextFieldPart:
        return paintTextField(o, paintInfo, r);
    case TextAreaPart:
        return paintTextArea(o, paintInfo, r);
    case MenulistButtonPart:
    case SearchFieldPart:
    case ListboxPart:
        return true;
    case CheckboxPart:
    case RadioPart:
    case PushButtonPart:
    case SquareButtonPart:
    case ButtonPart:
    case MenulistPart:
    case MeterPart:
    case RelevancyLevelIndicatorPart:
    case ContinuousCapacityLevelIndicatorPart:
    case DiscreteCapacityLevelIndicatorPart:
    case RatingLevelIndicatorPart:
    case ProgressBarPart:
    case SliderHorizontalPart:
    case SliderVerticalPart:
    case SliderThumbHorizontalPart:
    case SliderThumbVerticalPart:
    case SearchFieldCancelButtonPart:
    case SearchFieldDecorationPart:
    case SearchFieldResultsDecorationPart:
    default:
        break;
    }

    return false;
}

bool LayoutTheme::paintDecorations(LayoutObject* o, const PaintInfo& paintInfo, const IntRect& r)
{
    // Call the appropriate paint method based off the appearance value.
    switch (o->style()->appearance()) {
    case MenulistButtonPart:
        return paintMenuListButton(o, paintInfo, r);
    case TextFieldPart:
    case TextAreaPart:
    case CheckboxPart:
    case RadioPart:
    case PushButtonPart:
    case SquareButtonPart:
    case ButtonPart:
    case MenulistPart:
    case MeterPart:
    case RelevancyLevelIndicatorPart:
    case ContinuousCapacityLevelIndicatorPart:
    case DiscreteCapacityLevelIndicatorPart:
    case RatingLevelIndicatorPart:
    case ProgressBarPart:
    case SliderHorizontalPart:
    case SliderVerticalPart:
    case SliderThumbHorizontalPart:
    case SliderThumbVerticalPart:
    case SearchFieldPart:
    case SearchFieldCancelButtonPart:
    case SearchFieldDecorationPart:
    case SearchFieldResultsDecorationPart:
    default:
        break;
    }

    return false;
}

String LayoutTheme::extraDefaultStyleSheet()
{
    StringBuilder runtimeCSS;
    if (RuntimeEnabledFeatures::contextMenuEnabled())
        runtimeCSS.appendLiteral("menu[type=\"popup\" i] { display: none; }");
    return runtimeCSS.toString();
}

String LayoutTheme::formatMediaControlsTime(float time) const
{
    if (!std::isfinite(time))
        time = 0;
    int seconds = (int)fabsf(time);
    int hours = seconds / (60 * 60);
    int minutes = (seconds / 60) % 60;
    seconds %= 60;
    if (hours) {
        if (hours > 9)
            return String::format("%s%02d:%02d:%02d", (time < 0 ? "-" : ""), hours, minutes, seconds);

        return String::format("%s%01d:%02d:%02d", (time < 0 ? "-" : ""), hours, minutes, seconds);
    }

    return String::format("%s%02d:%02d", (time < 0 ? "-" : ""), minutes, seconds);
}

String LayoutTheme::formatMediaControlsCurrentTime(float currentTime, float /*duration*/) const
{
    return formatMediaControlsTime(currentTime);
}

Color LayoutTheme::activeSelectionBackgroundColor() const
{
    return platformActiveSelectionBackgroundColor().blendWithWhite();
}

Color LayoutTheme::inactiveSelectionBackgroundColor() const
{
    return platformInactiveSelectionBackgroundColor().blendWithWhite();
}

Color LayoutTheme::activeSelectionForegroundColor() const
{
    return platformActiveSelectionForegroundColor();
}

Color LayoutTheme::inactiveSelectionForegroundColor() const
{
    return platformInactiveSelectionForegroundColor();
}

Color LayoutTheme::activeListBoxSelectionBackgroundColor() const
{
    return platformActiveListBoxSelectionBackgroundColor();
}

Color LayoutTheme::inactiveListBoxSelectionBackgroundColor() const
{
    return platformInactiveListBoxSelectionBackgroundColor();
}

Color LayoutTheme::activeListBoxSelectionForegroundColor() const
{
    return platformActiveListBoxSelectionForegroundColor();
}

Color LayoutTheme::inactiveListBoxSelectionForegroundColor() const
{
    return platformInactiveListBoxSelectionForegroundColor();
}

Color LayoutTheme::platformActiveSelectionBackgroundColor() const
{
    // Use a blue color by default if the platform theme doesn't define anything.
    return Color(0, 0, 255);
}

Color LayoutTheme::platformActiveSelectionForegroundColor() const
{
    // Use a white color by default if the platform theme doesn't define anything.
    return Color::white;
}

Color LayoutTheme::platformInactiveSelectionBackgroundColor() const
{
    // Use a grey color by default if the platform theme doesn't define anything.
    // This color matches Firefox's inactive color.
    return Color(176, 176, 176);
}

Color LayoutTheme::platformInactiveSelectionForegroundColor() const
{
    // Use a black color by default.
    return Color::black;
}

Color LayoutTheme::platformActiveListBoxSelectionBackgroundColor() const
{
    return platformActiveSelectionBackgroundColor();
}

Color LayoutTheme::platformActiveListBoxSelectionForegroundColor() const
{
    return platformActiveSelectionForegroundColor();
}

Color LayoutTheme::platformInactiveListBoxSelectionBackgroundColor() const
{
    return platformInactiveSelectionBackgroundColor();
}

Color LayoutTheme::platformInactiveListBoxSelectionForegroundColor() const
{
    return platformInactiveSelectionForegroundColor();
}

int LayoutTheme::baselinePosition(const LayoutObject* o) const
{
    if (!o->isBox())
        return 0;

    const LayoutBox* box = toLayoutBox(o);

#if USE(NEW_THEME)
    return box->size().height() + box->marginTop() + m_platformTheme->baselinePositionAdjustment(o->style()->appearance()) * o->style()->effectiveZoom();
#else
    return box->size().height() + box->marginTop();
#endif
}

bool LayoutTheme::isControlContainer(ControlPart appearance) const
{
    // There are more leaves than this, but we'll patch this function as we add support for
    // more controls.
    return appearance != CheckboxPart && appearance != RadioPart;
}

bool LayoutTheme::isControlStyled(const LayoutStyle& style, const AuthorStyleInfo& authorStyle) const
{
    switch (style.appearance()) {
    case PushButtonPart:
    case SquareButtonPart:
    case ButtonPart:
    case ProgressBarPart:
    case MeterPart:
    case RelevancyLevelIndicatorPart:
    case ContinuousCapacityLevelIndicatorPart:
    case DiscreteCapacityLevelIndicatorPart:
    case RatingLevelIndicatorPart:
        return authorStyle.specifiesBackground() || authorStyle.specifiesBorder();

    case MenulistPart:
    case SearchFieldPart:
    case TextAreaPart:
    case TextFieldPart:
        return authorStyle.specifiesBackground() || authorStyle.specifiesBorder() || style.boxShadow();

    case SliderHorizontalPart:
    case SliderVerticalPart:
        return style.boxShadow();

    default:
        return false;
    }
}

void LayoutTheme::adjustPaintInvalidationRect(const LayoutObject* o, IntRect& r)
{
#if USE(NEW_THEME)
    m_platformTheme->inflateControlPaintRect(o->style()->appearance(), controlStatesForRenderer(o), r, o->style()->effectiveZoom());
#endif
}

bool LayoutTheme::shouldDrawDefaultFocusRing(LayoutObject* renderer) const
{
    if (supportsFocusRing(renderer->styleRef()))
        return false;
    Node* node = renderer->node();
    if (!node)
        return true;
    if (!renderer->styleRef().hasAppearance() && !node->isLink())
        return true;
    // We can't use LayoutTheme::isFocused because outline:auto might be
    // specified to non-:focus rulesets.
    if (node->focused() && !node->shouldHaveFocusAppearance())
        return false;
    return true;
}

bool LayoutTheme::supportsFocusRing(const LayoutStyle& style) const
{
    return (style.hasAppearance() && style.appearance() != TextFieldPart && style.appearance() != TextAreaPart && style.appearance() != MenulistButtonPart && style.appearance() != ListboxPart);
}

bool LayoutTheme::stateChanged(LayoutObject* o, ControlState state) const
{
    // Default implementation assumes the controls don't respond to changes in :hover state
    if (state == HoverControlState && !supportsHover(o->styleRef()))
        return false;

    // Assume pressed state is only responded to if the control is enabled.
    if (state == PressedControlState && !isEnabled(o))
        return false;

    o->setShouldDoFullPaintInvalidation();
    return true;
}

ControlStates LayoutTheme::controlStatesForRenderer(const LayoutObject* o) const
{
    ControlStates result = 0;
    if (isHovered(o)) {
        result |= HoverControlState;
        if (isSpinUpButtonPartHovered(o))
            result |= SpinUpControlState;
    }
    if (isPressed(o)) {
        result |= PressedControlState;
        if (isSpinUpButtonPartPressed(o))
            result |= SpinUpControlState;
    }
    if (isFocused(o) && o->style()->outlineStyleIsAuto())
        result |= FocusControlState;
    if (isEnabled(o))
        result |= EnabledControlState;
    if (isChecked(o))
        result |= CheckedControlState;
    if (isReadOnlyControl(o))
        result |= ReadOnlyControlState;
    if (!isActive(o))
        result |= WindowInactiveControlState;
    if (isIndeterminate(o))
        result |= IndeterminateControlState;
    return result;
}

bool LayoutTheme::isActive(const LayoutObject* o) const
{
    Node* node = o->node();
    if (!node)
        return false;

    Page* page = node->document().page();
    if (!page)
        return false;

    return page->focusController().isActive();
}

bool LayoutTheme::isChecked(const LayoutObject* o) const
{
    if (!isHTMLInputElement(o->node()))
        return false;
    return toHTMLInputElement(o->node())->shouldAppearChecked();
}

bool LayoutTheme::isIndeterminate(const LayoutObject* o) const
{
    if (!isHTMLInputElement(o->node()))
        return false;
    return toHTMLInputElement(o->node())->shouldAppearIndeterminate();
}

bool LayoutTheme::isEnabled(const LayoutObject* o) const
{
    Node* node = o->node();
    if (!node || !node->isElementNode())
        return true;
    return !toElement(node)->isDisabledFormControl();
}

bool LayoutTheme::isFocused(const LayoutObject* o) const
{
    Node* node = o->node();
    if (!node)
        return false;

    node = node->focusDelegate();
    Document& document = node->document();
    LocalFrame* frame = document.frame();
    return node == document.focusedElement() && node->focused() && node->shouldHaveFocusAppearance() && frame && frame->selection().isFocusedAndActive();
}

bool LayoutTheme::isPressed(const LayoutObject* o) const
{
    if (!o->node())
        return false;
    return o->node()->active();
}

bool LayoutTheme::isSpinUpButtonPartPressed(const LayoutObject* o) const
{
    Node* node = o->node();
    if (!node || !node->active() || !node->isElementNode()
        || !toElement(node)->isSpinButtonElement())
        return false;
    SpinButtonElement* element = toSpinButtonElement(node);
    return element->upDownState() == SpinButtonElement::Up;
}

bool LayoutTheme::isReadOnlyControl(const LayoutObject* o) const
{
    Node* node = o->node();
    if (!node || !node->isElementNode() || !toElement(node)->isFormControlElement())
        return false;
    HTMLFormControlElement* element = toHTMLFormControlElement(node);
    return element->isReadOnly();
}

bool LayoutTheme::isHovered(const LayoutObject* o) const
{
    Node* node = o->node();
    if (!node)
        return false;
    if (!node->isElementNode() || !toElement(node)->isSpinButtonElement())
        return node->hovered();
    SpinButtonElement* element = toSpinButtonElement(node);
    return element->hovered() && element->upDownState() != SpinButtonElement::Indeterminate;
}

bool LayoutTheme::isSpinUpButtonPartHovered(const LayoutObject* o) const
{
    Node* node = o->node();
    if (!node || !node->isElementNode() || !toElement(node)->isSpinButtonElement())
        return false;
    SpinButtonElement* element = toSpinButtonElement(node);
    return element->upDownState() == SpinButtonElement::Up;
}

#if !USE(NEW_THEME)

void LayoutTheme::adjustCheckboxStyle(LayoutStyle& style, Element*) const
{
    // A summary of the rules for checkbox designed to match WinIE:
    // width/height - honored (WinIE actually scales its control for small widths, but lets it overflow for small heights.)
    // font-size - not honored (control has no text), but we use it to decide which control size to use.
    setCheckboxSize(style);

    // padding - not honored by WinIE, needs to be removed.
    style.resetPadding();

    // border - honored by WinIE, but looks terrible (just paints in the control box and turns off the Windows XP theme)
    // for now, we will not honor it.
    style.resetBorder();
}

void LayoutTheme::adjustRadioStyle(LayoutStyle& style, Element*) const
{
    // A summary of the rules for checkbox designed to match WinIE:
    // width/height - honored (WinIE actually scales its control for small widths, but lets it overflow for small heights.)
    // font-size - not honored (control has no text), but we use it to decide which control size to use.
    setRadioSize(style);

    // padding - not honored by WinIE, needs to be removed.
    style.resetPadding();

    // border - honored by WinIE, but looks terrible (just paints in the control box and turns off the Windows XP theme)
    // for now, we will not honor it.
    style.resetBorder();
}

void LayoutTheme::adjustButtonStyle(LayoutStyle& style, Element*) const
{
}

void LayoutTheme::adjustInnerSpinButtonStyle(LayoutStyle&, Element*) const
{
}
#endif

void LayoutTheme::adjustMenuListStyle(LayoutStyle&, Element*) const
{
}

IntSize LayoutTheme::meterSizeForBounds(const LayoutMeter*, const IntRect& bounds) const
{
    return bounds.size();
}

bool LayoutTheme::supportsMeter(ControlPart) const
{
    return false;
}

bool LayoutTheme::paintMeter(LayoutObject*, const PaintInfo&, const IntRect&)
{
    return true;
}

void LayoutTheme::paintSliderTicks(LayoutObject* o, const PaintInfo& paintInfo, const IntRect& rect)
{
    Node* node = o->node();
    if (!isHTMLInputElement(node))
        return;

    HTMLInputElement* input = toHTMLInputElement(node);
    if (input->type() != InputTypeNames::range)
        return;

    HTMLDataListElement* dataList = input->dataList();
    if (!dataList)
        return;

    double min = input->minimum();
    double max = input->maximum();
    ControlPart part = o->style()->appearance();
    // We don't support ticks on alternate sliders like MediaVolumeSliders.
    if (part !=  SliderHorizontalPart && part != SliderVerticalPart)
        return;
    bool isHorizontal = part ==  SliderHorizontalPart;

    IntSize thumbSize;
    LayoutObject* thumbRenderer = input->closedShadowRoot()->getElementById(ShadowElementNames::sliderThumb())->layoutObject();
    if (thumbRenderer) {
        const LayoutStyle& thumbStyle = thumbRenderer->styleRef();
        int thumbWidth = thumbStyle.width().intValue();
        int thumbHeight = thumbStyle.height().intValue();
        thumbSize.setWidth(isHorizontal ? thumbWidth : thumbHeight);
        thumbSize.setHeight(isHorizontal ? thumbHeight : thumbWidth);
    }

    IntSize tickSize = sliderTickSize();
    float zoomFactor = o->style()->effectiveZoom();
    FloatRect tickRect;
    int tickRegionSideMargin = 0;
    int tickRegionWidth = 0;
    IntRect trackBounds;
    LayoutObject* trackRenderer = input->closedShadowRoot()->getElementById(ShadowElementNames::sliderTrack())->layoutObject();
    // We can ignoring transforms because transform is handled by the graphics context.
    if (trackRenderer)
        trackBounds = trackRenderer->absoluteBoundingBoxRectIgnoringTransforms();
    IntRect sliderBounds = o->absoluteBoundingBoxRectIgnoringTransforms();

    // Make position relative to the transformed ancestor element.
    trackBounds.setX(trackBounds.x() - sliderBounds.x() + rect.x());
    trackBounds.setY(trackBounds.y() - sliderBounds.y() + rect.y());

    if (isHorizontal) {
        tickRect.setWidth(floor(tickSize.width() * zoomFactor));
        tickRect.setHeight(floor(tickSize.height() * zoomFactor));
        tickRect.setY(floor(rect.y() + rect.height() / 2.0 + sliderTickOffsetFromTrackCenter() * zoomFactor));
        tickRegionSideMargin = trackBounds.x() + (thumbSize.width() - tickSize.width() * zoomFactor) / 2.0;
        tickRegionWidth = trackBounds.width() - thumbSize.width();
    } else {
        tickRect.setWidth(floor(tickSize.height() * zoomFactor));
        tickRect.setHeight(floor(tickSize.width() * zoomFactor));
        tickRect.setX(floor(rect.x() + rect.width() / 2.0 + sliderTickOffsetFromTrackCenter() * zoomFactor));
        tickRegionSideMargin = trackBounds.y() + (thumbSize.width() - tickSize.width() * zoomFactor) / 2.0;
        tickRegionWidth = trackBounds.height() - thumbSize.width();
    }
    RefPtrWillBeRawPtr<HTMLDataListOptionsCollection> options = dataList->options();
    for (unsigned i = 0; HTMLOptionElement* optionElement = options->item(i); i++) {
        String value = optionElement->value();
        if (!input->isValidValue(value))
            continue;
        double parsedValue = parseToDoubleForNumberType(input->sanitizeValue(value));
        double tickFraction = (parsedValue - min) / (max - min);
        double tickRatio = isHorizontal && o->style()->isLeftToRightDirection() ? tickFraction : 1.0 - tickFraction;
        double tickPosition = round(tickRegionSideMargin + tickRegionWidth * tickRatio);
        if (isHorizontal)
            tickRect.setX(tickPosition);
        else
            tickRect.setY(tickPosition);
        paintInfo.context->fillRect(tickRect, o->resolveColor(CSSPropertyColor));
    }
}

double LayoutTheme::animationRepeatIntervalForProgressBar() const
{
    return 0;
}

double LayoutTheme::animationDurationForProgressBar() const
{
    return 0;
}

bool LayoutTheme::shouldHaveSpinButton(HTMLInputElement* inputElement) const
{
    return inputElement->isSteppable() && inputElement->type() != InputTypeNames::range;
}

void LayoutTheme::adjustMenuListButtonStyle(LayoutStyle&, Element*) const
{
}

void LayoutTheme::adjustSliderThumbStyle(LayoutStyle& style, Element* element) const
{
    adjustSliderThumbSize(style, element);
}

void LayoutTheme::adjustSliderThumbSize(LayoutStyle&, Element*) const
{
}

void LayoutTheme::adjustSearchFieldStyle(LayoutStyle&, Element*) const
{
}

void LayoutTheme::adjustSearchFieldCancelButtonStyle(LayoutStyle&, Element*) const
{
}

void LayoutTheme::adjustSearchFieldDecorationStyle(LayoutStyle&, Element*) const
{
}

void LayoutTheme::adjustSearchFieldResultsDecorationStyle(LayoutStyle&, Element*) const
{
}

void LayoutTheme::platformColorsDidChange()
{
    Page::platformColorsChanged();
}

static FontDescription& getCachedFontDescription(CSSValueID systemFontID)
{
    DEFINE_STATIC_LOCAL(FontDescription, caption, ());
    DEFINE_STATIC_LOCAL(FontDescription, icon, ());
    DEFINE_STATIC_LOCAL(FontDescription, menu, ());
    DEFINE_STATIC_LOCAL(FontDescription, messageBox, ());
    DEFINE_STATIC_LOCAL(FontDescription, smallCaption, ());
    DEFINE_STATIC_LOCAL(FontDescription, statusBar, ());
    DEFINE_STATIC_LOCAL(FontDescription, webkitMiniControl, ());
    DEFINE_STATIC_LOCAL(FontDescription, webkitSmallControl, ());
    DEFINE_STATIC_LOCAL(FontDescription, webkitControl, ());
    DEFINE_STATIC_LOCAL(FontDescription, defaultDescription, ());
    switch (systemFontID) {
    case CSSValueCaption:
        return caption;
    case CSSValueIcon:
        return icon;
    case CSSValueMenu:
        return menu;
    case CSSValueMessageBox:
        return messageBox;
    case CSSValueSmallCaption:
        return smallCaption;
    case CSSValueStatusBar:
        return statusBar;
    case CSSValueWebkitMiniControl:
        return webkitMiniControl;
    case CSSValueWebkitSmallControl:
        return webkitSmallControl;
    case CSSValueWebkitControl:
        return webkitControl;
    case CSSValueNone:
        return defaultDescription;
    default:
        ASSERT_NOT_REACHED();
        return defaultDescription;
    }
}

void LayoutTheme::systemFont(CSSValueID systemFontID, FontDescription& fontDescription)
{
    fontDescription = getCachedFontDescription(systemFontID);
    if (fontDescription.isAbsoluteSize())
        return;

    FontStyle fontStyle = FontStyleNormal;
    FontWeight fontWeight = FontWeightNormal;
    float fontSize = 0;
    AtomicString fontFamily;
    systemFont(systemFontID, fontStyle, fontWeight, fontSize, fontFamily);
    fontDescription.setStyle(fontStyle);
    fontDescription.setWeight(fontWeight);
    fontDescription.setSpecifiedSize(fontSize);
    fontDescription.setIsAbsoluteSize(true);
    fontDescription.firstFamily().setFamily(fontFamily);
    fontDescription.setGenericFamily(FontDescription::NoFamily);
}

Color LayoutTheme::systemColor(CSSValueID cssValueId) const
{
    switch (cssValueId) {
    case CSSValueActiveborder:
        return 0xFFFFFFFF;
    case CSSValueActivecaption:
        return 0xFFCCCCCC;
    case CSSValueAppworkspace:
        return 0xFFFFFFFF;
    case CSSValueBackground:
        return 0xFF6363CE;
    case CSSValueButtonface:
        return 0xFFC0C0C0;
    case CSSValueButtonhighlight:
        return 0xFFDDDDDD;
    case CSSValueButtonshadow:
        return 0xFF888888;
    case CSSValueButtontext:
        return 0xFF000000;
    case CSSValueCaptiontext:
        return 0xFF000000;
    case CSSValueGraytext:
        return 0xFF808080;
    case CSSValueHighlight:
        return 0xFFB5D5FF;
    case CSSValueHighlighttext:
        return 0xFF000000;
    case CSSValueInactiveborder:
        return 0xFFFFFFFF;
    case CSSValueInactivecaption:
        return 0xFFFFFFFF;
    case CSSValueInactivecaptiontext:
        return 0xFF7F7F7F;
    case CSSValueInfobackground:
        return 0xFFFBFCC5;
    case CSSValueInfotext:
        return 0xFF000000;
    case CSSValueMenu:
        return 0xFFC0C0C0;
    case CSSValueMenutext:
        return 0xFF000000;
    case CSSValueScrollbar:
        return 0xFFFFFFFF;
    case CSSValueText:
        return 0xFF000000;
    case CSSValueThreeddarkshadow:
        return 0xFF666666;
    case CSSValueThreedface:
        return 0xFFC0C0C0;
    case CSSValueThreedhighlight:
        return 0xFFDDDDDD;
    case CSSValueThreedlightshadow:
        return 0xFFC0C0C0;
    case CSSValueThreedshadow:
        return 0xFF888888;
    case CSSValueWindow:
        return 0xFFFFFFFF;
    case CSSValueWindowframe:
        return 0xFFCCCCCC;
    case CSSValueWindowtext:
        return 0xFF000000;
    case CSSValueInternalActiveListBoxSelection:
        return activeListBoxSelectionBackgroundColor();
        break;
    case CSSValueInternalActiveListBoxSelectionText:
        return activeListBoxSelectionForegroundColor();
        break;
    case CSSValueInternalInactiveListBoxSelection:
        return inactiveListBoxSelectionBackgroundColor();
        break;
    case CSSValueInternalInactiveListBoxSelectionText:
        return inactiveListBoxSelectionForegroundColor();
        break;
    default:
        break;
    }
    ASSERT_NOT_REACHED();
    return Color();
}

Color LayoutTheme::platformActiveTextSearchHighlightColor() const
{
    return Color(255, 150, 50); // Orange.
}

Color LayoutTheme::platformInactiveTextSearchHighlightColor() const
{
    return Color(255, 255, 0); // Yellow.
}

Color LayoutTheme::tapHighlightColor()
{
    return theme().platformTapHighlightColor();
}

void LayoutTheme::setCustomFocusRingColor(const Color& c)
{
    m_customFocusRingColor = c;
    m_hasCustomFocusRingColor = true;
}

Color LayoutTheme::focusRingColor() const
{
    return m_hasCustomFocusRingColor ? m_customFocusRingColor : theme().platformFocusRingColor();
}

String LayoutTheme::fileListNameForWidth(Locale& locale, const FileList* fileList, const Font& font, int width) const
{
    if (width <= 0)
        return String();

    String string;
    if (fileList->isEmpty()) {
        string = locale.queryString(WebLocalizedString::FileButtonNoFileSelectedLabel);
    } else if (fileList->length() == 1) {
        string = fileList->item(0)->name();
    } else {
        // FIXME: Localization of fileList->length().
        return StringTruncator::rightTruncate(locale.queryString(WebLocalizedString::MultipleFileUploadText, String::number(fileList->length())), width, font);
    }

    return StringTruncator::centerTruncate(string, width, font);
}

bool LayoutTheme::shouldOpenPickerWithF4Key() const
{
    return false;
}

#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
bool LayoutTheme::supportsCalendarPicker(const AtomicString& type) const
{
    return type == InputTypeNames::date
        || type == InputTypeNames::datetime
        || type == InputTypeNames::datetime_local
        || type == InputTypeNames::month
        || type == InputTypeNames::week;
}
#endif

bool LayoutTheme::shouldUseFallbackTheme(const LayoutStyle&) const
{
    return false;
}

void LayoutTheme::adjustStyleUsingFallbackTheme(LayoutStyle& style, Element* e)
{
    ControlPart part = style.appearance();
    switch (part) {
    case CheckboxPart:
        return adjustCheckboxStyleUsingFallbackTheme(style, e);
    case RadioPart:
        return adjustRadioStyleUsingFallbackTheme(style, e);
    default:
        break;
    }
}

bool LayoutTheme::paintUsingFallbackTheme(LayoutObject* o, const PaintInfo& i, const IntRect& r)
{
    ControlPart part = o->style()->appearance();
    switch (part) {
    case CheckboxPart:
        return paintCheckboxUsingFallbackTheme(o, i, r);
    case RadioPart:
        return paintRadioUsingFallbackTheme(o, i, r);
    default:
        break;
    }
    return true;
}

// static
void LayoutTheme::setSizeIfAuto(LayoutStyle& style, const IntSize& size)
{
    if (style.width().isIntrinsicOrAuto())
        style.setWidth(Length(size.width(), Fixed));
    if (style.height().isAuto())
        style.setHeight(Length(size.height(), Fixed));
}

bool LayoutTheme::paintCheckboxUsingFallbackTheme(LayoutObject* o, const PaintInfo& i, const IntRect& r)
{
    WebFallbackThemeEngine::ExtraParams extraParams;
    WebCanvas* canvas = i.context->canvas();
    extraParams.button.checked = isChecked(o);
    extraParams.button.indeterminate = isIndeterminate(o);

    float zoomLevel = o->style()->effectiveZoom();
    GraphicsContextStateSaver stateSaver(*i.context);
    IntRect unzoomedRect = r;
    if (zoomLevel != 1) {
        unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
        unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
        i.context->translate(unzoomedRect.x(), unzoomedRect.y());
        i.context->scale(zoomLevel, zoomLevel);
        i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
    }

    Platform::current()->fallbackThemeEngine()->paint(canvas, WebFallbackThemeEngine::PartCheckbox, getWebFallbackThemeState(this, o), WebRect(unzoomedRect), &extraParams);
    return false;
}

void LayoutTheme::adjustCheckboxStyleUsingFallbackTheme(LayoutStyle& style, Element*) const
{
    // If the width and height are both specified, then we have nothing to do.
    if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
        return;

    IntSize size = Platform::current()->fallbackThemeEngine()->getSize(WebFallbackThemeEngine::PartCheckbox);
    float zoomLevel = style.effectiveZoom();
    size.setWidth(size.width() * zoomLevel);
    size.setHeight(size.height() * zoomLevel);
    setSizeIfAuto(style, size);

    // padding - not honored by WinIE, needs to be removed.
    style.resetPadding();

    // border - honored by WinIE, but looks terrible (just paints in the control box and turns off the Windows XP theme)
    // for now, we will not honor it.
    style.resetBorder();
}

bool LayoutTheme::paintRadioUsingFallbackTheme(LayoutObject* o, const PaintInfo& i, const IntRect& r)
{
    WebFallbackThemeEngine::ExtraParams extraParams;
    WebCanvas* canvas = i.context->canvas();
    extraParams.button.checked = isChecked(o);
    extraParams.button.indeterminate = isIndeterminate(o);

    float zoomLevel = o->style()->effectiveZoom();
    GraphicsContextStateSaver stateSaver(*i.context);
    IntRect unzoomedRect = r;
    if (zoomLevel != 1) {
        unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
        unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
        i.context->translate(unzoomedRect.x(), unzoomedRect.y());
        i.context->scale(zoomLevel, zoomLevel);
        i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
    }

    Platform::current()->fallbackThemeEngine()->paint(canvas, WebFallbackThemeEngine::PartRadio, getWebFallbackThemeState(this, o), WebRect(unzoomedRect), &extraParams);
    return false;
}

void LayoutTheme::adjustRadioStyleUsingFallbackTheme(LayoutStyle& style, Element*) const
{
    // If the width and height are both specified, then we have nothing to do.
    if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
        return;

    IntSize size = Platform::current()->fallbackThemeEngine()->getSize(WebFallbackThemeEngine::PartRadio);
    float zoomLevel = style.effectiveZoom();
    size.setWidth(size.width() * zoomLevel);
    size.setHeight(size.height() * zoomLevel);
    setSizeIfAuto(style, size);

    // padding - not honored by WinIE, needs to be removed.
    style.resetPadding();

    // border - honored by WinIE, but looks terrible (just paints in the control box and turns off the Windows XP theme)
    // for now, we will not honor it.
    style.resetBorder();
}

} // namespace blink


text:
select MAX(PANEL_ID) as tracking_data_PANEL_ID_Max from [dbo].[tracking_data]
select COUNT(PANEL_ID) as tracking_data_PANEL_ID_Count from [dbo].[tracking_data]
go
select MAX(PATTERN_ID) as tracking_data_PATTERN_ID_Max from [dbo].[tracking_data]
select COUNT(PATTERN_ID) as tracking_data_PATTERN_ID_Count from [dbo].[tracking_data]
go
select MAX(PANEL_ID) as panels_PANEL_ID_Max from [dbo].[panels]
go
select MAX(PANEL_ID) as panel_seq_PANEL_ID_Max from [dbo].[panel_seq]
go
select MAX(PANEL_ID) as pattern_seq_PANEL_ID_Max from [dbo].[pattern_seq]
go
select COUNT(PANEL_ID) as panel_seq_PANEL_ID_Count from [dbo].[panel_seq]
go
select COUNT(PANEL_ID) as pattern_seq_PANEL_ID_Count from [dbo].[pattern_seq]
go


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

<!--
  ~ Copyright 2014 Nuuptech
  ~
  ~    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.
  -->

<features name="login-ampersand-${project.version}"
          xmlns="http://karaf.apache.org/xmlns/features/v1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.0.0 http://karaf.apache.org/xmlns/features/v1.0.0">

    <repository>mvn:org.apache.camel.karaf/apache-camel/2.10.0.redhat-60024/xml/features</repository>

    <feature name="login-ampersand" description="Login Ampersand" version="${project.version}">
        <feature version="2.10.0.redhat-60024">camel-blueprint</feature>
        <feature version="2.10.0.redhat-60024">camel-jaxb</feature>
        <feature version="2.10.0.redhat-60024">camel-xstream</feature>
        <feature version="2.10.0.redhat-60024">camel-cxf</feature>
        <bundle>mvn:${project.groupId}/${project.artifactId}/${project.version}</bundle>
    </feature>

</features>


text:
from __future__ import unicode_literals

import logging
import pykka

from mopidy import backend

from .library import AmpacheLibraryProvider
from .playlist import AmpachePlaylistsProvider
from .client import AmpacheRemoteClient

logger = logging.getLogger(__name__)

class AmpacheBackend(pykka.ThreadingActor, backend.Backend):

    def __init__(self, config, audio):
        super(AmpacheBackend, self).__init__()

        self.remote = AmpacheRemoteClient(
            config['ampache']['hostname'],
            config['ampache']['port'],
            config['ampache']['username'],
            config['ampache']['password'],
            config['ampache']['ssl'],
            config['ampache']['context'])

        self.config = config
        self.library = AmpacheLibraryProvider(backend=self)
        self.playback = AmpachePlaybackProvider(audio=audio, backend=self)
        self.playlists = AmpachePlaylistsProvider(backend=self)

        self.uri_schemes = ['ampache']

class AmpachePlaybackProvider(backend.PlaybackProvider):

    def translate_uri(self, uri):
        logger.debug('Getting info for track %s' % uri)
        id = uri.split('ampache://')[1]
        real_uri = self.backend.remote.build_url_from_song_id(id)
        return real_uri


text:
<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/maven-v4_0_0.xsd">
    <parent>
        <artifactId>myapp</artifactId>
        <groupId>com.zhourl</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>myapp-demo</artifactId>
    <packaging>war</packaging>
    <name>myapp-demo Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
    	<project.build.targetJdk>1.7</project.build.targetJdk>
    </properties>
    <dependencies>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.5</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>myapp-demo</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${project.build.targetJdk}</source>
                    <target>${project.build.targetJdk}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>