text
stringlengths 2
97.5k
| meta
dict |
|---|---|
// https://github.com/lightbend/mima/issues/422
resolvers += Resolver.url(
"typesafe sbt-plugins",
url("https://dl.bintray.com/typesafe/sbt-plugins")
)(Resolver.ivyStylePatterns)
|
{
"pile_set_name": "Github"
}
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
package syscall
import (
"internal/race"
"runtime"
"sync"
"unsafe"
)
var (
Stdin = 0
Stdout = 1
Stderr = 2
)
const (
darwin64Bit = runtime.GOOS == "darwin" && sizeofPtr == 8
dragonfly64Bit = runtime.GOOS == "dragonfly" && sizeofPtr == 8
netbsd32Bit = runtime.GOOS == "netbsd" && sizeofPtr == 4
solaris64Bit = runtime.GOOS == "solaris" && sizeofPtr == 8
)
func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
// Mmap manager, for use by operating system-specific implementations.
type mmapper struct {
sync.Mutex
active map[*byte][]byte // active mappings; key is last byte in mapping
mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error)
munmap func(addr uintptr, length uintptr) error
}
func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
if length <= 0 {
return nil, EINVAL
}
// Map the requested memory.
addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset)
if errno != nil {
return nil, errno
}
// Slice memory layout
var sl = struct {
addr uintptr
len int
cap int
}{addr, length, length}
// Use unsafe to turn sl into a []byte.
b := *(*[]byte)(unsafe.Pointer(&sl))
// Register mapping in m and return it.
p := &b[cap(b)-1]
m.Lock()
defer m.Unlock()
m.active[p] = b
return b, nil
}
func (m *mmapper) Munmap(data []byte) (err error) {
if len(data) == 0 || len(data) != cap(data) {
return EINVAL
}
// Find the base of the mapping.
p := &data[cap(data)-1]
m.Lock()
defer m.Unlock()
b := m.active[p]
if b == nil || &b[0] != &data[0] {
return EINVAL
}
// Unmap the memory and update m.
if errno := m.munmap(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))); errno != nil {
return errno
}
delete(m.active, p)
return nil
}
// An Errno is an unsigned number describing an error condition.
// It implements the error interface. The zero Errno is by convention
// a non-error, so code to convert from Errno to error should use:
// err = nil
// if errno != 0 {
// err = errno
// }
type Errno uintptr
func (e Errno) Error() string {
if 0 <= int(e) && int(e) < len(errors) {
s := errors[e]
if s != "" {
return s
}
}
return "errno " + itoa(int(e))
}
func (e Errno) Temporary() bool {
return e == EINTR || e == EMFILE || e == ECONNRESET || e == ECONNABORTED || e.Timeout()
}
func (e Errno) Timeout() bool {
return e == EAGAIN || e == EWOULDBLOCK || e == ETIMEDOUT
}
// Do the interface allocations only once for common
// Errno values.
var (
errEAGAIN error = EAGAIN
errEINVAL error = EINVAL
errENOENT error = ENOENT
)
// errnoErr returns common boxed Errno values, to prevent
// allocations at runtime.
func errnoErr(e Errno) error {
switch e {
case 0:
return nil
case EAGAIN:
return errEAGAIN
case EINVAL:
return errEINVAL
case ENOENT:
return errENOENT
}
return e
}
// A Signal is a number describing a process signal.
// It implements the os.Signal interface.
type Signal int
func (s Signal) Signal() {}
func (s Signal) String() string {
if 0 <= s && int(s) < len(signals) {
str := signals[s]
if str != "" {
return str
}
}
return "signal " + itoa(int(s))
}
func Read(fd int, p []byte) (n int, err error) {
n, err = read(fd, p)
if race.Enabled {
if n > 0 {
race.WriteRange(unsafe.Pointer(&p[0]), n)
}
if err == nil {
race.Acquire(unsafe.Pointer(&ioSync))
}
}
if msanenabled && n > 0 {
msanWrite(unsafe.Pointer(&p[0]), n)
}
return
}
func Write(fd int, p []byte) (n int, err error) {
if race.Enabled {
race.ReleaseMerge(unsafe.Pointer(&ioSync))
}
n, err = write(fd, p)
if race.Enabled && n > 0 {
race.ReadRange(unsafe.Pointer(&p[0]), n)
}
if msanenabled && n > 0 {
msanRead(unsafe.Pointer(&p[0]), n)
}
return
}
// For testing: clients can set this flag to force
// creation of IPv6 sockets to return EAFNOSUPPORT.
var SocketDisableIPv6 bool
type Sockaddr interface {
sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs
}
type SockaddrInet4 struct {
Port int
Addr [4]byte
raw RawSockaddrInet4
}
type SockaddrInet6 struct {
Port int
ZoneId uint32
Addr [16]byte
raw RawSockaddrInet6
}
type SockaddrUnix struct {
Name string
raw RawSockaddrUnix
}
func Bind(fd int, sa Sockaddr) (err error) {
ptr, n, err := sa.sockaddr()
if err != nil {
return err
}
return bind(fd, ptr, n)
}
func Connect(fd int, sa Sockaddr) (err error) {
ptr, n, err := sa.sockaddr()
if err != nil {
return err
}
return connect(fd, ptr, n)
}
func Getpeername(fd int) (sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
if err = getpeername(fd, &rsa, &len); err != nil {
return
}
return anyToSockaddr(&rsa)
}
func GetsockoptInt(fd, level, opt int) (value int, err error) {
var n int32
vallen := _Socklen(4)
err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen)
return int(n), err
}
func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
if n, err = recvfrom(fd, p, flags, &rsa, &len); err != nil {
return
}
if rsa.Addr.Family != AF_UNSPEC {
from, err = anyToSockaddr(&rsa)
}
return
}
func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error) {
ptr, n, err := to.sockaddr()
if err != nil {
return err
}
return sendto(fd, p, flags, ptr, n)
}
func SetsockoptByte(fd, level, opt int, value byte) (err error) {
return setsockopt(fd, level, opt, unsafe.Pointer(&value), 1)
}
func SetsockoptInt(fd, level, opt int, value int) (err error) {
var n = int32(value)
return setsockopt(fd, level, opt, unsafe.Pointer(&n), 4)
}
func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error) {
return setsockopt(fd, level, opt, unsafe.Pointer(&value[0]), 4)
}
func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error) {
return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPMreq)
}
func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error) {
return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPv6Mreq)
}
func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error {
return setsockopt(fd, level, opt, unsafe.Pointer(filter), SizeofICMPv6Filter)
}
func SetsockoptLinger(fd, level, opt int, l *Linger) (err error) {
return setsockopt(fd, level, opt, unsafe.Pointer(l), SizeofLinger)
}
func SetsockoptString(fd, level, opt int, s string) (err error) {
return setsockopt(fd, level, opt, unsafe.Pointer(&[]byte(s)[0]), uintptr(len(s)))
}
func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error) {
return setsockopt(fd, level, opt, unsafe.Pointer(tv), unsafe.Sizeof(*tv))
}
func Socket(domain, typ, proto int) (fd int, err error) {
if domain == AF_INET6 && SocketDisableIPv6 {
return -1, EAFNOSUPPORT
}
fd, err = socket(domain, typ, proto)
return
}
func Socketpair(domain, typ, proto int) (fd [2]int, err error) {
var fdx [2]int32
err = socketpair(domain, typ, proto, &fdx)
if err == nil {
fd[0] = int(fdx[0])
fd[1] = int(fdx[1])
}
return
}
func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
if race.Enabled {
race.ReleaseMerge(unsafe.Pointer(&ioSync))
}
return sendfile(outfd, infd, offset, count)
}
var ioSync int64
|
{
"pile_set_name": "Github"
}
|
include_directories ("${CMAKE_CURRENT_SOURCE_DIR}")
include_directories ("${CMAKE_CURRENT_BINARY_DIR}")
set (FUSIONDALE_ONE_LIBS
pthread
dl
rt
direct
fusion
fusiondale
one
)
DEFINE_DIRECTFB_MODULE (ifusiondale_one
ifusiondale_one ifusiondale_one.c "${FUSIONDALE_ONE_LIBS}" ${INTERFACES_DIR}/IFusionDale
)
DEFINE_DIRECTFB_MODULE (ifusiondalemessenger_one
ifusiondalemessenger_one ifusiondalemessenger_one.c "${FUSIONDALE_ONE_LIBS}" ${INTERFACES_DIR}/IFusionDaleMessenger
)
DEFINE_DIRECTFB_MODULE (icoma_one
icoma_one icoma_one.c "${FUSIONDALE_ONE_LIBS}" ${INTERFACES_DIR}/IComa
)
DEFINE_DIRECTFB_MODULE (icomacomponent_one
icomacomponent_one icomacomponent_one.c "${FUSIONDALE_ONE_LIBS}" ${INTERFACES_DIR}/IComaComponent
)
|
{
"pile_set_name": "Github"
}
|
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.servicelayer.common;
import java.util.List;
/**
*
* Dao interface.
*
* @param <E>
*
*/
public interface Dao<E extends BaseEntity> {
E find(Long id);
void persist(E entity);
E merge(E entity);
void delete(E entity);
List<E> findAll();
}
|
{
"pile_set_name": "Github"
}
|
# frozen_string_literal: true
require 'spec_helper'
describe Overcommit::Hook::PreCommit::HtmlHint do
let(:config) { Overcommit::ConfigurationLoader.default_configuration }
let(:context) { double('context') }
subject { described_class.new(config, context) }
before do
subject.stub(:applicable_files).and_return(%w[file1.html file2.html])
end
context 'when htmlhint exits successfully' do
let(:result) { double('result') }
before do
subject.stub(:execute).and_return(result)
end
context 'with no errors' do
before do
result.stub(:stdout).and_return('')
end
it { should pass }
end
context 'and it reports an error' do
before do
result.stub(:stdout).and_return([
'file1.html:',
"\tline 355, col 520: \e[31mId redefinition of [ stats ].\e[39m",
'',
'',
'1 problem.'
].join("\n"))
end
it { should fail_hook }
end
end
end
|
{
"pile_set_name": "Github"
}
|
[preset00]
fRating=1
fGammaAdj=2
fDecay=0.99
fVideoEchoZoom=2
fVideoEchoAlpha=0
nVideoEchoOrientation=0
nWaveMode=2
bAdditiveWaves=0
bWaveDots=0
bWaveThick=0
bModWaveAlphaByVolume=1
bMaximizeWaveColor=0
bTexWrap=1
bDarkenCenter=0
bRedBlueStereo=0
bBrighten=0
bDarken=0
bSolarize=0
bInvert=0
fWaveAlpha=2.426125
fWaveScale=1.8817
fWaveSmoothing=0.9
fWaveParam=0
fModWaveAlphaStart=0.75
fModWaveAlphaEnd=0.95
fWarpAnimSpeed=1
fWarpScale=1
fZoomExponent=1
fShader=0
zoom=1.02
rot=0
cx=0.5
cy=0.5
dx=0
dy=0
warp=0.076
sx=1
sy=1
wave_r=0.65
wave_g=0.15
wave_b=0.35
wave_x=0.5
wave_y=0.5
ob_size=0.01
ob_r=0
ob_g=0
ob_b=0
ob_a=0
ib_size=0.01
ib_r=0.25
ib_g=0.25
ib_b=0.25
ib_a=0
nMotionVectorsX=12
nMotionVectorsY=9
mv_dx=0
mv_dy=0
mv_l=0.9
mv_r=1
mv_g=1
mv_b=1
mv_a=0
per_frame_1=wave_r = wave_r + 1.000*( 0.60*sin(1.517*time) + 0.40*sin(1.580*time) );
per_frame_2=wave_g = wave_g + 1.000*( 0.60*sin(1.088*time) + 0.40*sin(1.076*time) );
per_frame_3=wave_b = wave_b + 1.000*( 0.60*sin(1.037*time) + 0.40*sin(0.922*time) );
per_frame_4=rot = rot + 0.040*( 0.60*sin(0.381*time) + 0.40*sin(0.579*time) );
per_frame_5=cx = cx + 0.110*( 0.60*sin(0.374*time) + 0.40*sin(0.294*time) );
per_frame_6=cy = cy + 0.110*( 0.60*sin(0.393*time) + 0.40*sin(0.223*time) );
per_frame_7=q1=cos(1.41*time);
per_frame_8=q2=time + 0.3*sin(time*1.47);
per_pixel_1=rot=rot+0.05*sin(rad*13.5 + q2*1.3 + q*1.31);
per_pixel_2=zoom=zoom+0.05*sin(ang*10.0 + rad*7.5 + q2*1.63 + q);
|
{
"pile_set_name": "Github"
}
|
---
title: Master.DrawRectangle Method (Visio)
keywords: vis_sdr.chm10716220
f1_keywords:
- vis_sdr.chm10716220
ms.prod: visio
api_name:
- Visio.Master.DrawRectangle
ms.assetid: e41ec411-ccd7-0fe6-f560-cf3934d18b59
ms.date: 06/08/2017
---
# Master.DrawRectangle Method (Visio)
Adds a rectangle to the **Shapes** collection of a page, master, or group.
## Syntax
_expression_ . **DrawRectangle**( **_x1_** , **_y1_** , **_x2_** , **_y2_** )
_expression_ A variable that represents a **Master** object.
### Parameters
|**Name**|**Required/Optional**|**Data Type**|**Description**|
|:-----|:-----|:-----|:-----|
| _x1_|Required| **Double**|The _x_-coordinate of one corner of the rectangle's width-height box.|
| _y1_|Required| **Double**|The _y_-coordinate of one corner of the rectangle's width-height box.|
| _x2_|Required| **Double**|The _x_-coordinate of the other corner of the rectangle's width-height box.|
| _y2_|Required| **Double**|The _y_-coordinate of the other corner of the rectangle's width-height box.|
### Return Value
Shape
## Remarks
Using the **DrawRectangle** method is equivalent to using the **Rectangle** tool in the application. The arguments are in internal drawing units with respect to the coordinate space of the page, master, or group where the rectangle is being placed.
## Example
The following example shows how to draw a rectangle on the active page.
```vb
Public Sub DrawRectangle_Example()
Dim vsoShape As Visio.Shape
Set vsoShape = ActivePage.DrawRectangle(1, 4, 4, 1)
End Sub
```
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright Andrey Semashev 2007 - 2015.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file keywords/depth.hpp
* \author Andrey Semashev
* \date 14.03.2009
*
* The header contains the \c depth keyword declaration.
*/
#ifndef BOOST_LOG_KEYWORDS_DEPTH_HPP_INCLUDED_
#define BOOST_LOG_KEYWORDS_DEPTH_HPP_INCLUDED_
#include <boost/parameter/keyword.hpp>
#include <boost/log/detail/config.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace keywords {
//! The keyword for passing maximum scopes depth to the \c named_scope formatter
BOOST_PARAMETER_KEYWORD(tag, depth)
} // namespace keywords
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#endif // BOOST_LOG_KEYWORDS_DEPTH_HPP_INCLUDED_
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Tabs
*
* PHP version 5
*
* @category Class
* @package DocuSign\eSign
* @author Swaagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.13-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace DocuSign\eSign\Model;
use \ArrayAccess;
use \DocuSign\eSign\ObjectSerializer;
/**
* Tabs Class Doc Comment
*
* @category Class
* @package DocuSign\eSign
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class Tabs implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'tabs';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'approve_tabs' => '\DocuSign\eSign\Model\Approve[]',
'checkbox_tabs' => '\DocuSign\eSign\Model\Checkbox[]',
'comment_thread_tabs' => '\DocuSign\eSign\Model\CommentThread[]',
'company_tabs' => '\DocuSign\eSign\Model\Company[]',
'date_signed_tabs' => '\DocuSign\eSign\Model\DateSigned[]',
'date_tabs' => '\DocuSign\eSign\Model\\Date[]',
'decline_tabs' => '\DocuSign\eSign\Model\Decline[]',
'draw_tabs' => '\DocuSign\eSign\Model\Draw[]',
'email_address_tabs' => '\DocuSign\eSign\Model\EmailAddress[]',
'email_tabs' => '\DocuSign\eSign\Model\Email[]',
'envelope_id_tabs' => '\DocuSign\eSign\Model\EnvelopeId[]',
'first_name_tabs' => '\DocuSign\eSign\Model\FirstName[]',
'formula_tabs' => '\DocuSign\eSign\Model\FormulaTab[]',
'full_name_tabs' => '\DocuSign\eSign\Model\FullName[]',
'initial_here_tabs' => '\DocuSign\eSign\Model\InitialHere[]',
'last_name_tabs' => '\DocuSign\eSign\Model\LastName[]',
'list_tabs' => '\DocuSign\eSign\Model\array[]',
'notarize_tabs' => '\DocuSign\eSign\Model\Notarize[]',
'notary_certificate_tabs' => '\DocuSign\eSign\Model\NotaryCertificate[]',
'notary_seal_tabs' => '\DocuSign\eSign\Model\NotarySeal[]',
'note_tabs' => '\DocuSign\eSign\Model\Note[]',
'number_tabs' => '\DocuSign\eSign\Model\Number[]',
'poly_line_overlay_tabs' => '\DocuSign\eSign\Model\PolyLineOverlay[]',
'radio_group_tabs' => '\DocuSign\eSign\Model\RadioGroup[]',
'signer_attachment_tabs' => '\DocuSign\eSign\Model\SignerAttachment[]',
'sign_here_tabs' => '\DocuSign\eSign\Model\SignHere[]',
'smart_section_tabs' => '\DocuSign\eSign\Model\SmartSection[]',
'ssn_tabs' => '\DocuSign\eSign\Model\Ssn[]',
'tab_groups' => '\DocuSign\eSign\Model\TabGroup[]',
'text_tabs' => '\DocuSign\eSign\Model\Text[]',
'title_tabs' => '\DocuSign\eSign\Model\Title[]',
'view_tabs' => '\DocuSign\eSign\Model\View[]',
'zip_tabs' => '\DocuSign\eSign\Model\Zip[]'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'approve_tabs' => null,
'checkbox_tabs' => null,
'comment_thread_tabs' => null,
'company_tabs' => null,
'date_signed_tabs' => null,
'date_tabs' => null,
'decline_tabs' => null,
'draw_tabs' => null,
'email_address_tabs' => null,
'email_tabs' => null,
'envelope_id_tabs' => null,
'first_name_tabs' => null,
'formula_tabs' => null,
'full_name_tabs' => null,
'initial_here_tabs' => null,
'last_name_tabs' => null,
'list_tabs' => null,
'notarize_tabs' => null,
'notary_certificate_tabs' => null,
'notary_seal_tabs' => null,
'note_tabs' => null,
'number_tabs' => null,
'poly_line_overlay_tabs' => null,
'radio_group_tabs' => null,
'signer_attachment_tabs' => null,
'sign_here_tabs' => null,
'smart_section_tabs' => null,
'ssn_tabs' => null,
'tab_groups' => null,
'text_tabs' => null,
'title_tabs' => null,
'view_tabs' => null,
'zip_tabs' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'approve_tabs' => 'approveTabs',
'checkbox_tabs' => 'checkboxTabs',
'comment_thread_tabs' => 'commentThreadTabs',
'company_tabs' => 'companyTabs',
'date_signed_tabs' => 'dateSignedTabs',
'date_tabs' => 'dateTabs',
'decline_tabs' => 'declineTabs',
'draw_tabs' => 'drawTabs',
'email_address_tabs' => 'emailAddressTabs',
'email_tabs' => 'emailTabs',
'envelope_id_tabs' => 'envelopeIdTabs',
'first_name_tabs' => 'firstNameTabs',
'formula_tabs' => 'formulaTabs',
'full_name_tabs' => 'fullNameTabs',
'initial_here_tabs' => 'initialHereTabs',
'last_name_tabs' => 'lastNameTabs',
'list_tabs' => 'listTabs',
'notarize_tabs' => 'notarizeTabs',
'notary_certificate_tabs' => 'notaryCertificateTabs',
'notary_seal_tabs' => 'notarySealTabs',
'note_tabs' => 'noteTabs',
'number_tabs' => 'numberTabs',
'poly_line_overlay_tabs' => 'polyLineOverlayTabs',
'radio_group_tabs' => 'radioGroupTabs',
'signer_attachment_tabs' => 'signerAttachmentTabs',
'sign_here_tabs' => 'signHereTabs',
'smart_section_tabs' => 'smartSectionTabs',
'ssn_tabs' => 'ssnTabs',
'tab_groups' => 'tabGroups',
'text_tabs' => 'textTabs',
'title_tabs' => 'titleTabs',
'view_tabs' => 'viewTabs',
'zip_tabs' => 'zipTabs'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'approve_tabs' => 'setApproveTabs',
'checkbox_tabs' => 'setCheckboxTabs',
'comment_thread_tabs' => 'setCommentThreadTabs',
'company_tabs' => 'setCompanyTabs',
'date_signed_tabs' => 'setDateSignedTabs',
'date_tabs' => 'setDateTabs',
'decline_tabs' => 'setDeclineTabs',
'draw_tabs' => 'setDrawTabs',
'email_address_tabs' => 'setEmailAddressTabs',
'email_tabs' => 'setEmailTabs',
'envelope_id_tabs' => 'setEnvelopeIdTabs',
'first_name_tabs' => 'setFirstNameTabs',
'formula_tabs' => 'setFormulaTabs',
'full_name_tabs' => 'setFullNameTabs',
'initial_here_tabs' => 'setInitialHereTabs',
'last_name_tabs' => 'setLastNameTabs',
'list_tabs' => 'setListTabs',
'notarize_tabs' => 'setNotarizeTabs',
'notary_certificate_tabs' => 'setNotaryCertificateTabs',
'notary_seal_tabs' => 'setNotarySealTabs',
'note_tabs' => 'setNoteTabs',
'number_tabs' => 'setNumberTabs',
'poly_line_overlay_tabs' => 'setPolyLineOverlayTabs',
'radio_group_tabs' => 'setRadioGroupTabs',
'signer_attachment_tabs' => 'setSignerAttachmentTabs',
'sign_here_tabs' => 'setSignHereTabs',
'smart_section_tabs' => 'setSmartSectionTabs',
'ssn_tabs' => 'setSsnTabs',
'tab_groups' => 'setTabGroups',
'text_tabs' => 'setTextTabs',
'title_tabs' => 'setTitleTabs',
'view_tabs' => 'setViewTabs',
'zip_tabs' => 'setZipTabs'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'approve_tabs' => 'getApproveTabs',
'checkbox_tabs' => 'getCheckboxTabs',
'comment_thread_tabs' => 'getCommentThreadTabs',
'company_tabs' => 'getCompanyTabs',
'date_signed_tabs' => 'getDateSignedTabs',
'date_tabs' => 'getDateTabs',
'decline_tabs' => 'getDeclineTabs',
'draw_tabs' => 'getDrawTabs',
'email_address_tabs' => 'getEmailAddressTabs',
'email_tabs' => 'getEmailTabs',
'envelope_id_tabs' => 'getEnvelopeIdTabs',
'first_name_tabs' => 'getFirstNameTabs',
'formula_tabs' => 'getFormulaTabs',
'full_name_tabs' => 'getFullNameTabs',
'initial_here_tabs' => 'getInitialHereTabs',
'last_name_tabs' => 'getLastNameTabs',
'list_tabs' => 'getListTabs',
'notarize_tabs' => 'getNotarizeTabs',
'notary_certificate_tabs' => 'getNotaryCertificateTabs',
'notary_seal_tabs' => 'getNotarySealTabs',
'note_tabs' => 'getNoteTabs',
'number_tabs' => 'getNumberTabs',
'poly_line_overlay_tabs' => 'getPolyLineOverlayTabs',
'radio_group_tabs' => 'getRadioGroupTabs',
'signer_attachment_tabs' => 'getSignerAttachmentTabs',
'sign_here_tabs' => 'getSignHereTabs',
'smart_section_tabs' => 'getSmartSectionTabs',
'ssn_tabs' => 'getSsnTabs',
'tab_groups' => 'getTabGroups',
'text_tabs' => 'getTextTabs',
'title_tabs' => 'getTitleTabs',
'view_tabs' => 'getViewTabs',
'zip_tabs' => 'getZipTabs'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['approve_tabs'] = isset($data['approve_tabs']) ? $data['approve_tabs'] : null;
$this->container['checkbox_tabs'] = isset($data['checkbox_tabs']) ? $data['checkbox_tabs'] : null;
$this->container['comment_thread_tabs'] = isset($data['comment_thread_tabs']) ? $data['comment_thread_tabs'] : null;
$this->container['company_tabs'] = isset($data['company_tabs']) ? $data['company_tabs'] : null;
$this->container['date_signed_tabs'] = isset($data['date_signed_tabs']) ? $data['date_signed_tabs'] : null;
$this->container['date_tabs'] = isset($data['date_tabs']) ? $data['date_tabs'] : null;
$this->container['decline_tabs'] = isset($data['decline_tabs']) ? $data['decline_tabs'] : null;
$this->container['draw_tabs'] = isset($data['draw_tabs']) ? $data['draw_tabs'] : null;
$this->container['email_address_tabs'] = isset($data['email_address_tabs']) ? $data['email_address_tabs'] : null;
$this->container['email_tabs'] = isset($data['email_tabs']) ? $data['email_tabs'] : null;
$this->container['envelope_id_tabs'] = isset($data['envelope_id_tabs']) ? $data['envelope_id_tabs'] : null;
$this->container['first_name_tabs'] = isset($data['first_name_tabs']) ? $data['first_name_tabs'] : null;
$this->container['formula_tabs'] = isset($data['formula_tabs']) ? $data['formula_tabs'] : null;
$this->container['full_name_tabs'] = isset($data['full_name_tabs']) ? $data['full_name_tabs'] : null;
$this->container['initial_here_tabs'] = isset($data['initial_here_tabs']) ? $data['initial_here_tabs'] : null;
$this->container['last_name_tabs'] = isset($data['last_name_tabs']) ? $data['last_name_tabs'] : null;
$this->container['list_tabs'] = isset($data['list_tabs']) ? $data['list_tabs'] : null;
$this->container['notarize_tabs'] = isset($data['notarize_tabs']) ? $data['notarize_tabs'] : null;
$this->container['notary_certificate_tabs'] = isset($data['notary_certificate_tabs']) ? $data['notary_certificate_tabs'] : null;
$this->container['notary_seal_tabs'] = isset($data['notary_seal_tabs']) ? $data['notary_seal_tabs'] : null;
$this->container['note_tabs'] = isset($data['note_tabs']) ? $data['note_tabs'] : null;
$this->container['number_tabs'] = isset($data['number_tabs']) ? $data['number_tabs'] : null;
$this->container['poly_line_overlay_tabs'] = isset($data['poly_line_overlay_tabs']) ? $data['poly_line_overlay_tabs'] : null;
$this->container['radio_group_tabs'] = isset($data['radio_group_tabs']) ? $data['radio_group_tabs'] : null;
$this->container['signer_attachment_tabs'] = isset($data['signer_attachment_tabs']) ? $data['signer_attachment_tabs'] : null;
$this->container['sign_here_tabs'] = isset($data['sign_here_tabs']) ? $data['sign_here_tabs'] : null;
$this->container['smart_section_tabs'] = isset($data['smart_section_tabs']) ? $data['smart_section_tabs'] : null;
$this->container['ssn_tabs'] = isset($data['ssn_tabs']) ? $data['ssn_tabs'] : null;
$this->container['tab_groups'] = isset($data['tab_groups']) ? $data['tab_groups'] : null;
$this->container['text_tabs'] = isset($data['text_tabs']) ? $data['text_tabs'] : null;
$this->container['title_tabs'] = isset($data['title_tabs']) ? $data['title_tabs'] : null;
$this->container['view_tabs'] = isset($data['view_tabs']) ? $data['view_tabs'] : null;
$this->container['zip_tabs'] = isset($data['zip_tabs']) ? $data['zip_tabs'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets approve_tabs
*
* @return \DocuSign\eSign\Model\Approve[]
*/
public function getApproveTabs()
{
return $this->container['approve_tabs'];
}
/**
* Sets approve_tabs
*
* @param \DocuSign\eSign\Model\Approve[] $approve_tabs Specifies a tag on the document where you want the recipient to approve documents in an envelope without placing a signature or initials on the document. If the recipient clicks the Approve tag during the signing process, the recipient is considered to have signed the document. No information is shown on the document for the approval, but it is recorded as a signature in the envelope history.
*
* @return $this
*/
public function setApproveTabs($approve_tabs)
{
$this->container['approve_tabs'] = $approve_tabs;
return $this;
}
/**
* Gets checkbox_tabs
*
* @return \DocuSign\eSign\Model\Checkbox[]
*/
public function getCheckboxTabs()
{
return $this->container['checkbox_tabs'];
}
/**
* Sets checkbox_tabs
*
* @param \DocuSign\eSign\Model\Checkbox[] $checkbox_tabs Specifies a tag on the document in a location where the recipient can select an option.
*
* @return $this
*/
public function setCheckboxTabs($checkbox_tabs)
{
$this->container['checkbox_tabs'] = $checkbox_tabs;
return $this;
}
/**
* Gets comment_thread_tabs
*
* @return \DocuSign\eSign\Model\CommentThread[]
*/
public function getCommentThreadTabs()
{
return $this->container['comment_thread_tabs'];
}
/**
* Sets comment_thread_tabs
*
* @param \DocuSign\eSign\Model\CommentThread[] $comment_thread_tabs
*
* @return $this
*/
public function setCommentThreadTabs($comment_thread_tabs)
{
$this->container['comment_thread_tabs'] = $comment_thread_tabs;
return $this;
}
/**
* Gets company_tabs
*
* @return \DocuSign\eSign\Model\Company[]
*/
public function getCompanyTabs()
{
return $this->container['company_tabs'];
}
/**
* Sets company_tabs
*
* @param \DocuSign\eSign\Model\Company[] $company_tabs Specifies a tag on the document where you want the recipient's company name to appear. When getting information that includes this tab type, the original value of the tab when the associated envelope was sent is included in the response.
*
* @return $this
*/
public function setCompanyTabs($company_tabs)
{
$this->container['company_tabs'] = $company_tabs;
return $this;
}
/**
* Gets date_signed_tabs
*
* @return \DocuSign\eSign\Model\DateSigned[]
*/
public function getDateSignedTabs()
{
return $this->container['date_signed_tabs'];
}
/**
* Sets date_signed_tabs
*
* @param \DocuSign\eSign\Model\DateSigned[] $date_signed_tabs Specifies a tab on the document where the date the document was signed will automatically appear.
*
* @return $this
*/
public function setDateSignedTabs($date_signed_tabs)
{
$this->container['date_signed_tabs'] = $date_signed_tabs;
return $this;
}
/**
* Gets date_tabs
*
* @return \DocuSign\eSign\Model\\DateTime[]
*/
public function getDateTabs()
{
return $this->container['date_tabs'];
}
/**
* Sets date_tabs
*
* @param \DocuSign\eSign\Model\\DateTime[] $date_tabs Specifies a tab on the document where you want the recipient to enter a date. Date tabs are single-line fields that allow date information to be entered in any format. The tooltip for this tab recommends entering the date as MM/DD/YYYY, but this is not enforced. The format entered by the signer is retained. If you need a particular date format enforced, DocuSign recommends using a Text tab with a Validation Pattern and Validation Message to enforce the format.
*
* @return $this
*/
public function setDateTabs($date_tabs)
{
$this->container['date_tabs'] = $date_tabs;
return $this;
}
/**
* Gets decline_tabs
*
* @return \DocuSign\eSign\Model\Decline[]
*/
public function getDeclineTabs()
{
return $this->container['decline_tabs'];
}
/**
* Sets decline_tabs
*
* @param \DocuSign\eSign\Model\Decline[] $decline_tabs Specifies a tag on the document where you want to give the recipient the option of declining an envelope. If the recipient clicks the Decline tag during the signing process, the envelope is voided.
*
* @return $this
*/
public function setDeclineTabs($decline_tabs)
{
$this->container['decline_tabs'] = $decline_tabs;
return $this;
}
/**
* Gets draw_tabs
*
* @return \DocuSign\eSign\Model\Draw[]
*/
public function getDrawTabs()
{
return $this->container['draw_tabs'];
}
/**
* Sets draw_tabs
*
* @param \DocuSign\eSign\Model\Draw[] $draw_tabs
*
* @return $this
*/
public function setDrawTabs($draw_tabs)
{
$this->container['draw_tabs'] = $draw_tabs;
return $this;
}
/**
* Gets email_address_tabs
*
* @return \DocuSign\eSign\Model\EmailAddress[]
*/
public function getEmailAddressTabs()
{
return $this->container['email_address_tabs'];
}
/**
* Sets email_address_tabs
*
* @param \DocuSign\eSign\Model\EmailAddress[] $email_address_tabs Specifies a location on the document where you want where you want the recipient's email, as entered in the recipient information, to display.
*
* @return $this
*/
public function setEmailAddressTabs($email_address_tabs)
{
$this->container['email_address_tabs'] = $email_address_tabs;
return $this;
}
/**
* Gets email_tabs
*
* @return \DocuSign\eSign\Model\Email[]
*/
public function getEmailTabs()
{
return $this->container['email_tabs'];
}
/**
* Sets email_tabs
*
* @param \DocuSign\eSign\Model\Email[] $email_tabs Specifies a tag on the document where you want the recipient to enter an email. Email tags are single-line fields that accept any characters. The system checks that a valid email format (i.e. xxx@yyy.zzz) is entered in the tag. It uses the same parameters as a Text tab, with the validation message and pattern set for email information. When getting information that includes this tab type, the original value of the tab when the associated envelope was sent is included in the response.
*
* @return $this
*/
public function setEmailTabs($email_tabs)
{
$this->container['email_tabs'] = $email_tabs;
return $this;
}
/**
* Gets envelope_id_tabs
*
* @return \DocuSign\eSign\Model\EnvelopeId[]
*/
public function getEnvelopeIdTabs()
{
return $this->container['envelope_id_tabs'];
}
/**
* Sets envelope_id_tabs
*
* @param \DocuSign\eSign\Model\EnvelopeId[] $envelope_id_tabs Specifies a tag on the document where you want the envelope ID for to appear. Recipients cannot enter or change the information in this tab, it is for informational purposes only.
*
* @return $this
*/
public function setEnvelopeIdTabs($envelope_id_tabs)
{
$this->container['envelope_id_tabs'] = $envelope_id_tabs;
return $this;
}
/**
* Gets first_name_tabs
*
* @return \DocuSign\eSign\Model\FirstName[]
*/
public function getFirstNameTabs()
{
return $this->container['first_name_tabs'];
}
/**
* Sets first_name_tabs
*
* @param \DocuSign\eSign\Model\FirstName[] $first_name_tabs Specifies tag on a document where you want the recipient's first name to appear. This tag takes the recipient's name, as entered in the recipient information, splits it into sections based on spaces and uses the first section as the first name.
*
* @return $this
*/
public function setFirstNameTabs($first_name_tabs)
{
$this->container['first_name_tabs'] = $first_name_tabs;
return $this;
}
/**
* Gets formula_tabs
*
* @return \DocuSign\eSign\Model\FormulaTab[]
*/
public function getFormulaTabs()
{
return $this->container['formula_tabs'];
}
/**
* Sets formula_tabs
*
* @param \DocuSign\eSign\Model\FormulaTab[] $formula_tabs Specifies a tag that is used to add a calculated field to a document. Envelope recipients cannot directly enter information into the tag; the formula tab calculates and displays a new value when changes are made to the reference tag values. The reference tag information and calculation operations are entered in the \"formula\" element. See the [ML:Using the Calculated Fields Feature] quick start guide or [ML:DocuSign Service User Guide] for more information about formulas.
*
* @return $this
*/
public function setFormulaTabs($formula_tabs)
{
$this->container['formula_tabs'] = $formula_tabs;
return $this;
}
/**
* Gets full_name_tabs
*
* @return \DocuSign\eSign\Model\FullName[]
*/
public function getFullNameTabs()
{
return $this->container['full_name_tabs'];
}
/**
* Sets full_name_tabs
*
* @param \DocuSign\eSign\Model\FullName[] $full_name_tabs Specifies a tag on the document where you want the recipient's name to appear.
*
* @return $this
*/
public function setFullNameTabs($full_name_tabs)
{
$this->container['full_name_tabs'] = $full_name_tabs;
return $this;
}
/**
* Gets initial_here_tabs
*
* @return \DocuSign\eSign\Model\InitialHere[]
*/
public function getInitialHereTabs()
{
return $this->container['initial_here_tabs'];
}
/**
* Sets initial_here_tabs
*
* @param \DocuSign\eSign\Model\InitialHere[] $initial_here_tabs Specifies a tag location in the document at which a recipient will place their initials. The `optional` parameter specifies whether the initials are required or optional.
*
* @return $this
*/
public function setInitialHereTabs($initial_here_tabs)
{
$this->container['initial_here_tabs'] = $initial_here_tabs;
return $this;
}
/**
* Gets last_name_tabs
*
* @return \DocuSign\eSign\Model\LastName[]
*/
public function getLastNameTabs()
{
return $this->container['last_name_tabs'];
}
/**
* Sets last_name_tabs
*
* @param \DocuSign\eSign\Model\LastName[] $last_name_tabs Specifies a tag on a document where you want the recipient's last name to appear. This tag takes the recipient's name, as entered in the recipient information, splits it into sections based on spaces and uses the last section as the last name.
*
* @return $this
*/
public function setLastNameTabs($last_name_tabs)
{
$this->container['last_name_tabs'] = $last_name_tabs;
return $this;
}
/**
* Gets list_tabs
*
* @return \DocuSign\eSign\Model\array[]
*/
public function getListTabs()
{
return $this->container['list_tabs'];
}
/**
* Sets list_tabs
*
* @param \DocuSign\eSign\Model\array[] $list_tabs Specify this tag to give your recipient a list of options, presented as a drop-down list, from which they can select.
*
* @return $this
*/
public function setListTabs($list_tabs)
{
$this->container['list_tabs'] = $list_tabs;
return $this;
}
/**
* Gets notarize_tabs
*
* @return \DocuSign\eSign\Model\Notarize[]
*/
public function getNotarizeTabs()
{
return $this->container['notarize_tabs'];
}
/**
* Sets notarize_tabs
*
* @param \DocuSign\eSign\Model\Notarize[] $notarize_tabs
*
* @return $this
*/
public function setNotarizeTabs($notarize_tabs)
{
$this->container['notarize_tabs'] = $notarize_tabs;
return $this;
}
/**
* Gets notary_certificate_tabs
*
* @return \DocuSign\eSign\Model\NotaryCertificate[]
*/
public function getNotaryCertificateTabs()
{
return $this->container['notary_certificate_tabs'];
}
/**
* Sets notary_certificate_tabs
*
* @param \DocuSign\eSign\Model\NotaryCertificate[] $notary_certificate_tabs
*
* @return $this
*/
public function setNotaryCertificateTabs($notary_certificate_tabs)
{
$this->container['notary_certificate_tabs'] = $notary_certificate_tabs;
return $this;
}
/**
* Gets notary_seal_tabs
*
* @return \DocuSign\eSign\Model\NotarySeal[]
*/
public function getNotarySealTabs()
{
return $this->container['notary_seal_tabs'];
}
/**
* Sets notary_seal_tabs
*
* @param \DocuSign\eSign\Model\NotarySeal[] $notary_seal_tabs
*
* @return $this
*/
public function setNotarySealTabs($notary_seal_tabs)
{
$this->container['notary_seal_tabs'] = $notary_seal_tabs;
return $this;
}
/**
* Gets note_tabs
*
* @return \DocuSign\eSign\Model\Note[]
*/
public function getNoteTabs()
{
return $this->container['note_tabs'];
}
/**
* Sets note_tabs
*
* @param \DocuSign\eSign\Model\Note[] $note_tabs Specifies a location on the document where you want to place additional information, in the form of a note, for a recipient.
*
* @return $this
*/
public function setNoteTabs($note_tabs)
{
$this->container['note_tabs'] = $note_tabs;
return $this;
}
/**
* Gets number_tabs
*
* @return \DocuSign\eSign\Model\Number[]
*/
public function getNumberTabs()
{
return $this->container['number_tabs'];
}
/**
* Sets number_tabs
*
* @param \DocuSign\eSign\Model\Number[] $number_tabs Specifies a tag on the document where you want the recipient to enter a number. It uses the same parameters as a Text tab, with the validation message and pattern set for number information. When getting information that includes this tab type, the original value of the tab when the associated envelope was sent is included in the response.
*
* @return $this
*/
public function setNumberTabs($number_tabs)
{
$this->container['number_tabs'] = $number_tabs;
return $this;
}
/**
* Gets poly_line_overlay_tabs
*
* @return \DocuSign\eSign\Model\PolyLineOverlay[]
*/
public function getPolyLineOverlayTabs()
{
return $this->container['poly_line_overlay_tabs'];
}
/**
* Sets poly_line_overlay_tabs
*
* @param \DocuSign\eSign\Model\PolyLineOverlay[] $poly_line_overlay_tabs
*
* @return $this
*/
public function setPolyLineOverlayTabs($poly_line_overlay_tabs)
{
$this->container['poly_line_overlay_tabs'] = $poly_line_overlay_tabs;
return $this;
}
/**
* Gets radio_group_tabs
*
* @return \DocuSign\eSign\Model\RadioGroup[]
*/
public function getRadioGroupTabs()
{
return $this->container['radio_group_tabs'];
}
/**
* Sets radio_group_tabs
*
* @param \DocuSign\eSign\Model\RadioGroup[] $radio_group_tabs Specifies a tag on the document in a location where the recipient can select one option from a group of options using a radio button. The radio buttons do not have to be on the same page in a document.
*
* @return $this
*/
public function setRadioGroupTabs($radio_group_tabs)
{
$this->container['radio_group_tabs'] = $radio_group_tabs;
return $this;
}
/**
* Gets signer_attachment_tabs
*
* @return \DocuSign\eSign\Model\SignerAttachment[]
*/
public function getSignerAttachmentTabs()
{
return $this->container['signer_attachment_tabs'];
}
/**
* Sets signer_attachment_tabs
*
* @param \DocuSign\eSign\Model\SignerAttachment[] $signer_attachment_tabs Specifies a tag on the document when you want the recipient to add supporting documents to an envelope.
*
* @return $this
*/
public function setSignerAttachmentTabs($signer_attachment_tabs)
{
$this->container['signer_attachment_tabs'] = $signer_attachment_tabs;
return $this;
}
/**
* Gets sign_here_tabs
*
* @return \DocuSign\eSign\Model\SignHere[]
*/
public function getSignHereTabs()
{
return $this->container['sign_here_tabs'];
}
/**
* Sets sign_here_tabs
*
* @param \DocuSign\eSign\Model\SignHere[] $sign_here_tabs A complex type the contains information about the tag that specifies where the recipient places their signature in the document. The \"optional\" parameter sets if the signature is required or optional.
*
* @return $this
*/
public function setSignHereTabs($sign_here_tabs)
{
$this->container['sign_here_tabs'] = $sign_here_tabs;
return $this;
}
/**
* Gets smart_section_tabs
*
* @return \DocuSign\eSign\Model\SmartSection[]
*/
public function getSmartSectionTabs()
{
return $this->container['smart_section_tabs'];
}
/**
* Sets smart_section_tabs
*
* @param \DocuSign\eSign\Model\SmartSection[] $smart_section_tabs
*
* @return $this
*/
public function setSmartSectionTabs($smart_section_tabs)
{
$this->container['smart_section_tabs'] = $smart_section_tabs;
return $this;
}
/**
* Gets ssn_tabs
*
* @return \DocuSign\eSign\Model\Ssn[]
*/
public function getSsnTabs()
{
return $this->container['ssn_tabs'];
}
/**
* Sets ssn_tabs
*
* @param \DocuSign\eSign\Model\Ssn[] $ssn_tabs Specifies a tag on the document where you want the recipient to enter a Social Security Number (SSN). A SSN can be typed with or without dashes. It uses the same parameters as a Text tab, with the validation message and pattern set for SSN information. When getting information that includes this tab type, the original value of the tab when the associated envelope was sent is included in the response.
*
* @return $this
*/
public function setSsnTabs($ssn_tabs)
{
$this->container['ssn_tabs'] = $ssn_tabs;
return $this;
}
/**
* Gets tab_groups
*
* @return \DocuSign\eSign\Model\TabGroup[]
*/
public function getTabGroups()
{
return $this->container['tab_groups'];
}
/**
* Sets tab_groups
*
* @param \DocuSign\eSign\Model\TabGroup[] $tab_groups
*
* @return $this
*/
public function setTabGroups($tab_groups)
{
$this->container['tab_groups'] = $tab_groups;
return $this;
}
/**
* Gets text_tabs
*
* @return \DocuSign\eSign\Model\Text[]
*/
public function getTextTabs()
{
return $this->container['text_tabs'];
}
/**
* Sets text_tabs
*
* @param \DocuSign\eSign\Model\Text[] $text_tabs Specifies a that that is an adaptable field that allows the recipient to enter different text information. When getting information that includes this tab type, the original value of the tab when the associated envelope was sent is included in the response.
*
* @return $this
*/
public function setTextTabs($text_tabs)
{
$this->container['text_tabs'] = $text_tabs;
return $this;
}
/**
* Gets title_tabs
*
* @return \DocuSign\eSign\Model\Title[]
*/
public function getTitleTabs()
{
return $this->container['title_tabs'];
}
/**
* Sets title_tabs
*
* @param \DocuSign\eSign\Model\Title[] $title_tabs Specifies a tag on the document where you want the recipient's title to appear. When getting information that includes this tab type, the original value of the tab when the associated envelope was sent is included in the response.
*
* @return $this
*/
public function setTitleTabs($title_tabs)
{
$this->container['title_tabs'] = $title_tabs;
return $this;
}
/**
* Gets view_tabs
*
* @return \DocuSign\eSign\Model\View[]
*/
public function getViewTabs()
{
return $this->container['view_tabs'];
}
/**
* Sets view_tabs
*
* @param \DocuSign\eSign\Model\View[] $view_tabs
*
* @return $this
*/
public function setViewTabs($view_tabs)
{
$this->container['view_tabs'] = $view_tabs;
return $this;
}
/**
* Gets zip_tabs
*
* @return \DocuSign\eSign\Model\Zip[]
*/
public function getZipTabs()
{
return $this->container['zip_tabs'];
}
/**
* Sets zip_tabs
*
* @param \DocuSign\eSign\Model\Zip[] $zip_tabs Specifies a tag on the document where you want the recipient to enter a ZIP code. The ZIP code can be a five numbers or the ZIP+4 format with nine numbers. The zip code can be typed with or without dashes. It uses the same parameters as a Text tab, with the validation message and pattern set for ZIP code information. When getting information that includes this tab type, the original value of the tab when the associated envelope was sent is included in the response.
*
* @return $this
*/
public function setZipTabs($zip_tabs)
{
$this->container['zip_tabs'] = $zip_tabs;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
|
{
"pile_set_name": "Github"
}
|
/*
This project is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Deviation is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Deviation. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common.h"
#include "target/drivers/mcu/stm32/spi.h"
void MMC_Init()
{
rcc_periph_clock_enable(get_rcc_from_pin(MMC_SPI.csn));
GPIO_setup_output(MMC_SPI.csn, OTYPE_PUSHPULL);
GPIO_pin_set(MMC_SPI.csn);
if (HAS_PIN(MMC_PRESENT)) {
rcc_periph_clock_enable(get_rcc_from_pin(MMC_PRESENT));
GPIO_setup_input(MMC_PRESENT, ITYPE_PULLUP);
}
if (HAS_PIN(MMC_PROTECT)) {
rcc_periph_clock_enable(get_rcc_from_pin(MMC_PROTECT));
GPIO_setup_input(MMC_PROTECT, ITYPE_PULLUP);
}
_spi_init(MMC_SPI_CFG);
rcc_periph_clock_enable(get_rcc_from_port(MMC_RX_DMA.dma));
}
|
{
"pile_set_name": "Github"
}
|
ALTER TABLE STORE_INFO ADD COLUMN STATUS VARCHAR(50);
|
{
"pile_set_name": "Github"
}
|
#import "GeneratedPluginRegistrant.h"
|
{
"pile_set_name": "Github"
}
|
package Moose::Exception::RoleNameRequired;
our $VERSION = '2.2014';
use Moose;
extends 'Moose::Exception';
with 'Moose::Exception::Role::Class';
sub _build_message {
"You must supply a role name to look for";
}
__PACKAGE__->meta->make_immutable;
1;
|
{
"pile_set_name": "Github"
}
|
"""
A module containing volatile, experimental and legacy code.
"""
from . import layers
from . import models
|
{
"pile_set_name": "Github"
}
|
/*
* edge_se3Switchable.cpp
*
* Created on: 17.10.2011
* Author: niko
*
* Updated on: 14.01.2013
* Author: Christian Kerl <christian.kerl@in.tum.de>
*/
#include "edge_se3Switchable.h"
#include "vertex_switchLinear.h"
#include "g2o/types/slam3d/vertex_se3.h"
#include "g2o/types/slam3d/isometry3d_gradients.h"
using namespace std;
using namespace Eigen;
// ================================================
EdgeSE3Switchable::EdgeSE3Switchable() : g2o::BaseMultiEdge<6, Eigen::Isometry3d>()
{
resize(3);
_jacobianOplus.clear();
_jacobianOplus.push_back(JacobianType(0, 6, 6));
_jacobianOplus.push_back(JacobianType(0, 6, 6));
_jacobianOplus.push_back(JacobianType(0, 6, 1));
}
// ================================================
bool EdgeSE3Switchable::read(std::istream& is)
{
/* g2o::Vector7d meas;
for (int i=0; i<7; i++)
is >> meas[i];
// normalize the quaternion to recover numerical precision lost by storing as human readable text
Vector4d::MapType(meas.data()+3).normalize();
setMeasurement(g2o::internal::fromVectorQT(meas));
for (int i=0; i<6; i++)
for (int j=i; j<6; j++) {
is >> information()(i,j);
if (i!=j)
information()(j,i) = information()(i,j);
}
return true;*/
return false;
}
// ================================================
bool EdgeSE3Switchable::write(std::ostream& os) const
{
/* g2o::Vector7d meas = g2o::internal::toVectorQT(measurement());
for (int i=0; i<7; i++) os << meas[i] << " ";
for (int i = 0; i < 6; ++i)
for (int j = i; j < 6; ++j)
os << " " << information()(i, j);
return os.good();*/
return false;
}
// ================================================
void EdgeSE3Switchable::linearizeOplus()
{
g2o::VertexSE3* from = static_cast<g2o::VertexSE3*>(_vertices[0]);
g2o::VertexSE3* to = static_cast<g2o::VertexSE3*>(_vertices[1]);
const VertexSwitchLinear* vSwitch = static_cast<const VertexSwitchLinear*>(_vertices[2]);
Eigen::Isometry3d E;
const Eigen::Isometry3d& Xi=from->estimate();
const Eigen::Isometry3d& Xj=to->estimate();
const Eigen::Isometry3d& Z=_measurement;
g2o::internal::computeEdgeSE3Gradient(E, _jacobianOplus[0], _jacobianOplus[1], Z, Xi, Xj);
_jacobianOplus[0]*=vSwitch->estimate();
_jacobianOplus[1]*=vSwitch->estimate();
// derivative w.r.t switch vertex
_jacobianOplus[2].setZero();
_jacobianOplus[2] = g2o::internal::toVectorMQT(E) * vSwitch->gradient();
}
// ================================================
void EdgeSE3Switchable::computeError()
{
const g2o::VertexSE3* v1 = dynamic_cast<const g2o::VertexSE3*>(_vertices[0]);
const g2o::VertexSE3* v2 = dynamic_cast<const g2o::VertexSE3*>(_vertices[1]);
const VertexSwitchLinear* v3 = static_cast<const VertexSwitchLinear*>(_vertices[2]);
Eigen::Isometry3d delta = _inverseMeasurement * (v1->estimate().inverse()*v2->estimate());
_error = g2o::internal::toVectorMQT(delta) * v3->estimate();
}
/*
#include <GL/gl.h>
#ifdef G2O_HAVE_OPENGL
EdgeSE3SwitchableDrawAction::EdgeSE3SwitchableDrawAction(): DrawAction(typeid(EdgeSE3Switchable).name()){}
g2o::HyperGraphElementAction* EdgeSE3SwitchableDrawAction::operator()(g2o::HyperGraph::HyperGraphElement* element,
g2o::HyperGraphElementAction::Parameters* ){
if (typeid(*element).name()!=_typeName)
return 0;
EdgeSE3Switchable* e = static_cast<EdgeSE3Switchable*>(element);
g2o::VertexSE3* fromEdge = static_cast<g2o::VertexSE3*>(e->vertices()[0]);
g2o::VertexSE3* toEdge = static_cast<g2o::VertexSE3*>(e->vertices()[1]);
VertexSwitchLinear* s = static_cast<VertexSwitchLinear*>(e->vertices()[2]);
glColor3f(s->estimate()*1.0,s->estimate()*0.1,s->estimate()*0.1);
glPushAttrib(GL_ENABLE_BIT);
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
glVertex3f(fromEdge->estimate().translation().x(),fromEdge->estimate().translation().y(),fromEdge->estimate().translation().z());
glVertex3f(toEdge->estimate().translation().x(),toEdge->estimate().translation().y(),toEdge->estimate().translation().z());
glEnd();
glPopAttrib();
return this;
}
#endif
*/
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
"""
To be used with processors in module `highstate_doc`.
"""
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
__virtualname__ = "highstate_doc"
def note(name, source=None, contents=None, **kwargs):
"""
Add content to a document generated using `highstate_doc.render`.
This state does not preform any tasks on the host. It only is used in highstate_doc lowstate processors
to include extra documents.
.. code-block:: yaml
{{sls}} example note:
highstate_doc.note:
- name: example note
- require_in:
- pkg: somepackage
- contents: |
example `highstate_doc.note`
------------------
This state does not do anything to the system! It is only used by a `processor`
you can use `requisites` and `order` to move your docs around the rendered file.
.. this message appare above the `pkg: somepackage` state.
- source: salt://{{tpldir}}/also_include_a_file.md
{{sls}} extra help:
highstate_doc.note:
- name: example
- order: 0
- source: salt://{{tpldir}}/HELP.md
"""
comment = ""
if source:
comment += "include file: {0}\n".format(source)
if contents and len(contents) < 200:
comment += contents
return {"name": name, "result": True, "comment": comment, "changes": {}}
|
{
"pile_set_name": "Github"
}
|
#--------------------------------------------------------------------------------
vsim -c -do simulate_mti.do
|
{
"pile_set_name": "Github"
}
|
{
"contextState": true,
"closureShortcuts": false,
"closureStorageField": "C",
"varStorageField": "V",
"evalCtx": {
"a": ["_a", 0],
"b": ["_b", 1],
"c": ["_c", 2]
},
"contextMethodOps":true,
"injectEvalCtx":true,
"injectFuncMeta": "meta"
}
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/perl -w
#
# Boost.Function library
#
# Copyright (C) 2001-2003 Douglas Gregor (gregod@cs.rpi.edu)
#
# Permission to copy, use, sell and distribute this software is granted
# provided this copyright notice appears in all copies.
# Permission to modify the code and to distribute modified code is granted
# provided this copyright notice appears in all copies, and a notice
# that the code was modified is included with the copyright notice.
#
# This software is provided "as is" without express or implied warranty,
# and with no claim as to its suitability for any purpose.
#
# For more information, see http://www.boost.org
use English;
$max_args = $ARGV[0];
open (OUT, ">maybe_include.hpp") or die("Cannot write to maybe_include.hpp");
for($on_arg = 0; $on_arg <= $max_args; ++$on_arg) {
if ($on_arg == 0) {
print OUT "#if";
}
else {
print OUT "#elif";
}
print OUT " BOOST_FUNCTION_NUM_ARGS == $on_arg\n";
print OUT "# ifndef BOOST_FUNCTION_$on_arg\n";
print OUT "# define BOOST_FUNCTION_$on_arg\n";
print OUT "# include <boost/function/function_template.hpp>\n";
print OUT "# endif\n";
}
print OUT "#else\n";
print OUT "# error Cannot handle Boost.Function objects that accept more than $max_args arguments!\n";
print OUT "#endif\n";
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ReefJS Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- stylesheets -->
<style type="text/css">
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
font-size: 112.5%;
margin-left: auto;
margin-right: auto;
max-width: 32em;
width: 88%;
}
label,
input {
display: block;
width: 100%;
}
</style>
<!-- scripts -->
<script src="../dist/reef.js"></script>
</head>
<body>
<main>
<div id="test2"></div>
<div id="test"></div>
<div id="app"></div>
<script>
// Turn on debug mode
Reef.debug(true);
var test2 = new Reef('#test2', {
data: {
showContent: true,
xss: `<img onerror="alert('xss attack yo!')" src=x>`
},
template: function (props) {
if (!props.showContent) return 'Hi';
return `
${props.xss}
<style>.color { color: red; }</style>
<p class="color">Hi!</p>`;
}
});
test2.render();
setTimeout(function () {
sourceOfTruth.data.showContent = true;
}, 2000);
var test = new Reef('#test', {
data: {
items: [1, 2, 3, 4],
sub: true
},
template: function (props) {
var html =
'<ul>' +
props.items.map(function (item) {
return '<li>' + item + '</li>';
}).join('') +
'</ul>';
if (props.sub) {
html +=
'<div><div><div>Hello</div>World</div>!</div>';
}
return html;
}
});
test.render();
var sourceOfTruth = new Reef.Store({
data: {
heading: '',
items: {
todos: [
'Buy milk',
'Bake a birthday cake',
'Go apple picking'
],
heading: 'Things'
},
}
});
var wrapper = new Reef('#app', {
store: sourceOfTruth,
template: function (props) {
return '<h1 sandwich="tuna">' + (props.items.heading.length > 0 ? props.items.heading : 'Hello, world!') + '</h1><div id="content"></div>';
},
attachTo: [sourceOfTruth]
});
var app = new Reef('#content', {
store: sourceOfTruth,
template: function (props) {
var html = '<h1>Todos</h1><ul sandwich="tuna">';
var styles = props.heading.length > 4 ? ' style="font-weight: bold; color: rebeccapurple; background-color: gainsboro;"' : '';
props.items.todos.forEach(function (todo) {
html += '<li' + styles + '>' + todo + '</li>';
});
html += '<input type="checkbox" defaultChecked>';
html += '<input type="text" id="heading"><br>';
html += '<strong>The title is:</strong> ' + (props.heading.length > 0 ? props.heading : 'Hello, world!');
html += '</ul>';
html += `
<label for="wizards">Who is the best wizard?</label>
<select>
<option value="harry">Harry</option>
<option value="hermione" defaultSelected>Hermione</option>
<option value="neville">Neville</option>
</select><br><br>`;
// html += '<img src="x" onerror="alert(\'XSS attack!\')">';
html += '<svg xmlns="http://www.w3.org/2000/svg" style="height:.8em;width:.8em" viewBox="0 0 16 16"><path fill="currentColor" d="M14 9v2.066c-1.258 1.285-3.016 2.526-5 2.852V8.001h3v-1L9 5.83A3.001 3.001 0 0 0 8 .001 3 3 0 0 0 7 5.83L4 7.001v1h3v5.917c-1.984-.326-3.742-1.567-5-2.852V9H0v1c0 2 4 6 8 6s8-4 8-6V9h-2zM9 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/></svg>';
html += '<button ' + (props.heading.length > 4 ? 'disabled' : '') + '>Disabled Button</button>';
return html;
},
attachTo: [wrapper]
});
// app.attach(wrapper);
wrapper.render();
// Update state on input change
document.addEventListener('input', function (event) {
if (!event.target.matches('#heading')) return;
sourceOfTruth.data.heading = event.target.value;
}, false);
</script>
</main>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DvdLib.Ifo
{
public class Program
{
public readonly List<Cell> Cells;
public Program(List<Cell> cells)
{
Cells = cells;
}
}
}
|
{
"pile_set_name": "Github"
}
|
#ifndef MATH_GRISU_H
#define MATH_GRISU_H
int dtoa_grisu3(double v, char *dst, int size);
#endif
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category design
* @package base_default
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
?>
<?php if($this->getResultCount()): ?>
<?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
<div class="page-title">
<?php if ($this->helper('rss/catalog')->getTagFeedUrl()): ?>
<a href="<?php echo $this->helper('rss/catalog')->getTagFeedUrl() ?>" class="nobr link-rss"><?php echo $this->__('Subscribe to Feed') ?></a>
<?php endif; ?>
<h1><?php echo ($this->getHeaderText() || $this->getHeaderText() === false) ? $this->getHeaderText() : $this->__("Search results for '%s'", $this->helper('catalogsearch')->getEscapedQueryText()) ?></h1>
</div>
<?php if ($messages = $this->getNoteMessages()):?>
<p class="note-msg">
<?php foreach ($messages as $message):?>
<?php echo $message?><br />
<?php endforeach;?>
</p>
<?php endif; ?>
<?php echo $this->getProductListHtml() ?>
<?php else: ?>
<div class="page-title">
<h1><?php echo ($this->getHeaderText() || $this->getHeaderText() === false) ? $this->getHeaderText() : $this->__("Search results for '%s'", $this->helper('catalogsearch')->getEscapedQueryText()) ?></h1>
</div>
<p class="note-msg">
<?php echo ($this->getNoResultText()) ? $this->getNoResultText() : $this->__('Your search returns no results.') ?>
<?php if ($messages = $this->getNoteMessages()):?>
<?php foreach ($messages as $message):?>
<br /><?php echo $message?>
<?php endforeach;?>
<?php endif; ?>
</p>
<?php endif; ?>
|
{
"pile_set_name": "Github"
}
|
package tahrir.tools;
import tahrir.io.crypto.TrCrypto;
import tahrir.io.net.PhysicalNetworkLocation;
import tahrir.io.net.RemoteNodeAddress;
import tahrir.io.net.TrPeerManager;
import tahrir.io.net.udpV1.UdpNetworkLocation;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.interfaces.RSAPublicKey;
import java.util.Random;
public class Generic {
public static Integer randomInt(Integer i) {
return new Random().nextInt(i);
}
public static Integer genericPort() {
return randomInt(60000);
}
public static Integer genericSessionId() {
return randomInt(1000);
}
public static Integer genericTopologyLocation() {
return new Random().nextInt();
}
public static InetAddress genericInetAddress() {
try {
return InetAddress.getByName("127.0.0.1");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public static RemoteNodeAddress genericRemoteNodeAddress() {
final RSAPublicKey pubKey = TrCrypto.createRsaKeyPair().a;
final PhysicalNetworkLocation location = new UdpNetworkLocation(genericInetAddress(), genericPort());
return new RemoteNodeAddress(location, pubKey);
}
public static TrPeerManager.TopologyLocationInfo genericTopologyLocationInfo() {
return new TrPeerManager.TopologyLocationInfo(null);
}
}
|
{
"pile_set_name": "Github"
}
|
//
// ACAppDelegate.h
// ParallaxDemo
//
// Created by Arnaud Coomans on 6/11/13.
// Copyright (c) 2013 acoomans. All rights reserved.
//
#import <UIKit/UIKit.h>
@class ACViewController;
@interface ACAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ACViewController *viewController;
@end
|
{
"pile_set_name": "Github"
}
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/model/data_type_error_handler_impl.h"
#include "base/bind.h"
#include "base/metrics/histogram_macros.h"
namespace syncer {
DataTypeErrorHandlerImpl::DataTypeErrorHandlerImpl(
const scoped_refptr<base::SingleThreadTaskRunner>& ui_thread,
const base::Closure& dump_stack,
const ErrorCallback& sync_callback)
: ui_thread_(ui_thread),
dump_stack_(dump_stack),
sync_callback_(sync_callback) {}
DataTypeErrorHandlerImpl::~DataTypeErrorHandlerImpl() {}
void DataTypeErrorHandlerImpl::OnUnrecoverableError(const SyncError& error) {
if (!dump_stack_.is_null())
dump_stack_.Run();
UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeRunFailures",
ModelTypeToHistogramInt(error.model_type()),
MODEL_TYPE_COUNT);
ui_thread_->PostTask(error.location(), base::Bind(sync_callback_, error));
}
SyncError DataTypeErrorHandlerImpl::CreateAndUploadError(
const tracked_objects::Location& location,
const std::string& message,
ModelType type) {
if (!dump_stack_.is_null())
dump_stack_.Run();
return SyncError(location, SyncError::DATATYPE_ERROR, message, type);
}
std::unique_ptr<DataTypeErrorHandler> DataTypeErrorHandlerImpl::Copy() const {
return base::MakeUnique<DataTypeErrorHandlerImpl>(ui_thread_, dump_stack_,
sync_callback_);
}
} // namespace syncer
|
{
"pile_set_name": "Github"
}
|
# Copyright (c) 2017 OpenStack Foundation
#
# 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.
import json
import six
from xml.etree.cElementTree import Element, SubElement, tostring
from swift.common.constraints import valid_api_version
from swift.common.http import HTTP_NO_CONTENT
from swift.common.request_helpers import get_param
from swift.common.swob import HTTPException, HTTPNotAcceptable, Request, \
RESPONSE_REASONS, HTTPBadRequest, wsgi_quote, wsgi_to_bytes
from swift.common.utils import RESERVED, get_logger, list_from_csv
#: Mapping of query string ``format=`` values to their corresponding
#: content-type values.
FORMAT2CONTENT_TYPE = {'plain': 'text/plain', 'json': 'application/json',
'xml': 'application/xml'}
#: Maximum size of a valid JSON container listing body. If we receive
#: a container listing response larger than this, assume it's a staticweb
#: response and pass it on to the client.
# Default max object length is 1024, default container listing limit is 1e4;
# add a fudge factor for things like hash, last_modified, etc.
MAX_CONTAINER_LISTING_CONTENT_LENGTH = 1024 * 10000 * 2
def get_listing_content_type(req):
"""
Determine the content type to use for an account or container listing
response.
:param req: request object
:returns: content type as a string (e.g. text/plain, application/json)
:raises HTTPNotAcceptable: if the requested content type is not acceptable
:raises HTTPBadRequest: if the 'format' query param is provided and
not valid UTF-8
"""
query_format = get_param(req, 'format')
if query_format:
req.accept = FORMAT2CONTENT_TYPE.get(
query_format.lower(), FORMAT2CONTENT_TYPE['plain'])
try:
out_content_type = req.accept.best_match(
['text/plain', 'application/json', 'application/xml', 'text/xml'])
except ValueError:
raise HTTPBadRequest(request=req, body=b'Invalid Accept header')
if not out_content_type:
raise HTTPNotAcceptable(request=req)
return out_content_type
def to_xml(document_element):
result = tostring(document_element, encoding='UTF-8').replace(
b"<?xml version='1.0' encoding='UTF-8'?>",
b'<?xml version="1.0" encoding="UTF-8"?>', 1)
if not result.startswith(b'<?xml '):
# py3 tostring doesn't (necessarily?) include the XML declaration;
# add it if it's missing.
result = b'<?xml version="1.0" encoding="UTF-8"?>\n' + result
return result
def account_to_xml(listing, account_name):
doc = Element('account', name=account_name)
doc.text = '\n'
for record in listing:
if 'subdir' in record:
name = record.pop('subdir')
sub = SubElement(doc, 'subdir', name=name)
else:
sub = SubElement(doc, 'container')
for field in ('name', 'count', 'bytes', 'last_modified'):
SubElement(sub, field).text = six.text_type(
record.pop(field))
sub.tail = '\n'
return to_xml(doc)
def container_to_xml(listing, base_name):
doc = Element('container', name=base_name)
for record in listing:
if 'subdir' in record:
name = record.pop('subdir')
sub = SubElement(doc, 'subdir', name=name)
SubElement(sub, 'name').text = name
else:
sub = SubElement(doc, 'object')
for field in ('name', 'hash', 'bytes', 'content_type',
'last_modified'):
SubElement(sub, field).text = six.text_type(
record.pop(field))
return to_xml(doc)
def listing_to_text(listing):
def get_lines():
for item in listing:
if 'name' in item:
yield item['name'].encode('utf-8') + b'\n'
else:
yield item['subdir'].encode('utf-8') + b'\n'
return b''.join(get_lines())
class ListingFilter(object):
def __init__(self, app, conf, logger=None):
self.app = app
self.logger = logger or get_logger(conf, log_route='listing-filter')
def filter_reserved(self, listing, account, container):
new_listing = []
for entry in list(listing):
for key in ('name', 'subdir'):
value = entry.get(key, '')
if six.PY2:
value = value.encode('utf-8')
if RESERVED in value:
if container:
self.logger.warning(
'Container listing for %s/%s had '
'reserved byte in %s: %r',
wsgi_quote(account), wsgi_quote(container),
key, value)
else:
self.logger.warning(
'Account listing for %s had '
'reserved byte in %s: %r',
wsgi_quote(account), key, value)
break # out of the *key* loop; check next entry
else:
new_listing.append(entry)
return new_listing
def __call__(self, env, start_response):
req = Request(env)
try:
# account and container only
version, acct, cont = req.split_path(2, 3)
except ValueError:
is_account_or_container_req = False
else:
is_account_or_container_req = True
if not is_account_or_container_req:
return self.app(env, start_response)
if not valid_api_version(version) or req.method not in ('GET', 'HEAD'):
return self.app(env, start_response)
# OK, definitely have an account/container request.
# Get the desired content-type, then force it to a JSON request.
try:
out_content_type = get_listing_content_type(req)
except HTTPException as err:
return err(env, start_response)
params = req.params
can_vary = 'format' not in params
params['format'] = 'json'
req.params = params
# Give other middlewares a chance to be in charge
env.setdefault('swift.format_listing', True)
status, headers, resp_iter = req.call_application(self.app)
if not env.get('swift.format_listing'):
start_response(status, headers)
return resp_iter
header_to_index = {}
resp_content_type = resp_length = None
for i, (header, value) in enumerate(headers):
header = header.lower()
if header == 'content-type':
header_to_index[header] = i
resp_content_type = value.partition(';')[0]
elif header == 'content-length':
header_to_index[header] = i
resp_length = int(value)
elif header == 'vary':
header_to_index[header] = i
if not status.startswith(('200 ', '204 ')):
start_response(status, headers)
return resp_iter
if can_vary:
if 'vary' in header_to_index:
value = headers[header_to_index['vary']][1]
if 'accept' not in list_from_csv(value.lower()):
headers[header_to_index['vary']] = (
'Vary', value + ', Accept')
else:
headers.append(('Vary', 'Accept'))
if resp_content_type != 'application/json':
start_response(status, headers)
return resp_iter
if resp_length is None or \
resp_length > MAX_CONTAINER_LISTING_CONTENT_LENGTH:
start_response(status, headers)
return resp_iter
def set_header(header, value):
if value is None:
del headers[header_to_index[header]]
else:
headers[header_to_index[header]] = (
headers[header_to_index[header]][0], str(value))
if req.method == 'HEAD':
set_header('content-type', out_content_type + '; charset=utf-8')
set_header('content-length', None) # don't know, can't determine
start_response(status, headers)
return resp_iter
body = b''.join(resp_iter)
try:
listing = json.loads(body)
# Do a couple sanity checks
if not isinstance(listing, list):
raise ValueError
if not all(isinstance(item, dict) for item in listing):
raise ValueError
except ValueError:
# Static web listing that's returning invalid JSON?
# Just pass it straight through; that's about all we *can* do.
start_response(status, headers)
return [body]
if not req.allow_reserved_names:
listing = self.filter_reserved(listing, acct, cont)
try:
if out_content_type.endswith('/xml'):
if cont:
body = container_to_xml(
listing, wsgi_to_bytes(cont).decode('utf-8'))
else:
body = account_to_xml(
listing, wsgi_to_bytes(acct).decode('utf-8'))
elif out_content_type == 'text/plain':
body = listing_to_text(listing)
else:
body = json.dumps(listing).encode('ascii')
except KeyError:
# listing was in a bad format -- funky static web listing??
start_response(status, headers)
return [body]
if not body:
status = '%s %s' % (HTTP_NO_CONTENT,
RESPONSE_REASONS[HTTP_NO_CONTENT][0])
set_header('content-type', out_content_type + '; charset=utf-8')
set_header('content-length', len(body))
start_response(status, headers)
return [body]
def filter_factory(global_conf, **local_conf):
conf = global_conf.copy()
conf.update(local_conf)
def listing_filter(app):
return ListingFilter(app, conf)
return listing_filter
|
{
"pile_set_name": "Github"
}
|
console.log('hello this is myindex');
module.exports=function(){
console.log('hello this is myindex');
}
|
{
"pile_set_name": "Github"
}
|
# KUDO Cassandra Architecture
Apache Cassandra is a stateful workload. KUDO Cassandra uses kubernetes
statefulset as the basic piece of the KUDO Cassandra Architecture
As a StatefulSet maintains sticky identities for each of its Pods, this helps
KUDO Cassandra to automate all necessary operations with Apache Cassandra nodes.
To help with updates and upgrades, KUDO Cassandra comes with a custom config
maps thats helps for rolling updates for KUDO Cassandra. Apache Cassandra
maintenance jobs like `repair` and `backup/restore` are configured as kubernetes
jobs and are only deployed on-demand when configuring their respective
parameters.

## Multi-Datacenter Architecture
KUDO Cassandra can span a ring across multiple kubernetes clusters, to
facilitate the deployment across various regions and zones. Read more about
multidataceneter configuration options in the
[multi-dataceneter](./multidataceneter.md) docs.

|
{
"pile_set_name": "Github"
}
|
use crate::aio::{ActualConnection, Connect};
use crate::types::RedisResult;
#[cfg(feature = "tls")]
use async_native_tls::{TlsConnector, TlsStream};
use async_std::net::TcpStream;
#[cfg(unix)]
use async_std::os::unix::net::UnixStream;
use async_trait::async_trait;
use std::net::SocketAddr;
#[cfg(unix)]
use std::path::Path;
use std::pin::Pin;
use tokio::io::{AsyncRead, AsyncWrite};
/// Wraps the async_std TcpStream in order to implement the required Traits for it
pub struct TcpStreamAsyncStdWrapped(TcpStream);
/// Wraps the async_native_tls TlsStream in order to implement the required Traits for it
#[cfg(feature = "tls")]
pub struct TlsStreamAsyncStdWrapped(TlsStream<TcpStream>);
#[cfg(unix)]
/// Wraps the async_std UnixStream in order to implement the required Traits for it
pub struct UnixStreamAsyncStdWrapped(UnixStream);
impl AsyncWrite for TcpStreamAsyncStdWrapped {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
buf: &[u8],
) -> std::task::Poll<Result<usize, tokio::io::Error>> {
async_std::io::Write::poll_write(Pin::new(&mut self.0), cx, buf)
}
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
) -> std::task::Poll<Result<(), tokio::io::Error>> {
async_std::io::Write::poll_flush(Pin::new(&mut self.0), cx)
}
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
) -> std::task::Poll<Result<(), tokio::io::Error>> {
async_std::io::Write::poll_close(Pin::new(&mut self.0), cx)
}
}
impl AsyncRead for TcpStreamAsyncStdWrapped {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
buf: &mut [u8],
) -> std::task::Poll<Result<usize, tokio::io::Error>> {
async_std::io::Read::poll_read(Pin::new(&mut self.0), cx, buf)
}
}
#[cfg(feature = "tls")]
impl AsyncWrite for TlsStreamAsyncStdWrapped {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
buf: &[u8],
) -> std::task::Poll<Result<usize, tokio::io::Error>> {
async_std::io::Write::poll_write(Pin::new(&mut self.0), cx, buf)
}
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
) -> std::task::Poll<Result<(), tokio::io::Error>> {
async_std::io::Write::poll_flush(Pin::new(&mut self.0), cx)
}
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
) -> std::task::Poll<Result<(), tokio::io::Error>> {
async_std::io::Write::poll_close(Pin::new(&mut self.0), cx)
}
}
#[cfg(feature = "tls")]
impl AsyncRead for TlsStreamAsyncStdWrapped {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
buf: &mut [u8],
) -> std::task::Poll<Result<usize, tokio::io::Error>> {
async_std::io::Read::poll_read(Pin::new(&mut self.0), cx, buf)
}
}
#[cfg(unix)]
impl AsyncWrite for UnixStreamAsyncStdWrapped {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
buf: &[u8],
) -> std::task::Poll<Result<usize, tokio::io::Error>> {
async_std::io::Write::poll_write(Pin::new(&mut self.0), cx, buf)
}
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
) -> std::task::Poll<Result<(), tokio::io::Error>> {
async_std::io::Write::poll_flush(Pin::new(&mut self.0), cx)
}
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
) -> std::task::Poll<Result<(), tokio::io::Error>> {
async_std::io::Write::poll_close(Pin::new(&mut self.0), cx)
}
}
#[cfg(unix)]
impl AsyncRead for UnixStreamAsyncStdWrapped {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context,
buf: &mut [u8],
) -> std::task::Poll<Result<usize, tokio::io::Error>> {
async_std::io::Read::poll_read(Pin::new(&mut self.0), cx, buf)
}
}
/// Represents an AsyncStd connectable
pub struct AsyncStd;
#[async_trait]
impl Connect for AsyncStd {
async fn connect_tcp(socket_addr: SocketAddr) -> RedisResult<ActualConnection> {
Ok(TcpStream::connect(&socket_addr)
.await
.map(|con| ActualConnection::TcpAsyncStd(TcpStreamAsyncStdWrapped(con)))?)
}
#[cfg(feature = "tls")]
async fn connect_tcp_tls(
hostname: &str,
socket_addr: SocketAddr,
insecure: bool,
) -> RedisResult<ActualConnection> {
let tcp_stream = TcpStream::connect(&socket_addr).await?;
let tls_connector = if insecure {
TlsConnector::new()
.danger_accept_invalid_certs(true)
.danger_accept_invalid_hostnames(true)
.use_sni(false)
} else {
TlsConnector::new()
};
Ok(tls_connector
.connect(hostname, tcp_stream)
.await
.map(|con| ActualConnection::TcpTlsAsyncStd(TlsStreamAsyncStdWrapped(con)))?)
}
#[cfg(unix)]
async fn connect_unix(path: &Path) -> RedisResult<ActualConnection> {
Ok(UnixStream::connect(path)
.await
.map(|con| ActualConnection::UnixAsyncStd(UnixStreamAsyncStdWrapped(con)))?)
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* This file contains low level CPU setup functions.
* Kumar Gala <galak@kernel.crashing.org>
* Copyright 2009 Freescale Semiconductor, Inc.
*
* Based on cpu_setup_6xx code by
* Benjamin Herrenschmidt <benh@kernel.crashing.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <asm/processor.h>
#include <asm/cputable.h>
#include <asm/ppc_asm.h>
_GLOBAL(__e500_icache_setup)
mfspr r0, SPRN_L1CSR1
andi. r3, r0, L1CSR1_ICE
bnelr /* Already enabled */
oris r0, r0, L1CSR1_CPE@h
ori r0, r0, (L1CSR1_ICFI | L1CSR1_ICLFR | L1CSR1_ICE)
mtspr SPRN_L1CSR1, r0 /* Enable I-Cache */
isync
blr
_GLOBAL(__e500_dcache_setup)
mfspr r0, SPRN_L1CSR0
andi. r3, r0, L1CSR0_DCE
bnelr /* Already enabled */
msync
isync
li r0, 0
mtspr SPRN_L1CSR0, r0 /* Disable */
msync
isync
li r0, (L1CSR0_DCFI | L1CSR0_CLFC)
mtspr SPRN_L1CSR0, r0 /* Invalidate */
isync
1: mfspr r0, SPRN_L1CSR0
andi. r3, r0, L1CSR0_CLFC
bne+ 1b /* Wait for lock bits reset */
oris r0, r0, L1CSR0_CPE@h
ori r0, r0, L1CSR0_DCE
msync
isync
mtspr SPRN_L1CSR0, r0 /* Enable */
isync
blr
#ifdef CONFIG_PPC32
_GLOBAL(__setup_cpu_e200)
/* enable dedicated debug exception handling resources (Debug APU) */
mfspr r3,SPRN_HID0
ori r3,r3,HID0_DAPUEN@l
mtspr SPRN_HID0,r3
b __setup_e200_ivors
_GLOBAL(__setup_cpu_e500v1)
_GLOBAL(__setup_cpu_e500v2)
mflr r4
bl __e500_icache_setup
bl __e500_dcache_setup
bl __setup_e500_ivors
#ifdef CONFIG_FSL_RIO
/* Ensure that RFXE is set */
mfspr r3,SPRN_HID1
oris r3,r3,HID1_RFXE@h
mtspr SPRN_HID1,r3
#endif
mtlr r4
blr
_GLOBAL(__setup_cpu_e500mc)
mflr r4
bl __e500_icache_setup
bl __e500_dcache_setup
bl __setup_e500mc_ivors
mtlr r4
blr
#endif
/* Right now, restore and setup are the same thing */
_GLOBAL(__restore_cpu_e5500)
_GLOBAL(__setup_cpu_e5500)
mflr r4
bl __e500_icache_setup
bl __e500_dcache_setup
#ifdef CONFIG_PPC_BOOK3E_64
bl .__setup_base_ivors
bl .setup_perfmon_ivor
bl .setup_doorbell_ivors
bl .setup_ehv_ivors
#else
bl __setup_e500mc_ivors
#endif
mtlr r4
blr
|
{
"pile_set_name": "Github"
}
|
//
// LDMasterViewController.h
// LivelyDemo
//
// Created by Romain Goyet on 24/04/12.
// Copyright (c) 2012 Applidium. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface LDMasterViewController : UITableViewController <UIActionSheetDelegate> {
NSArray * _objects;
}
- (IBAction)pickTransform:(id)sender;
@end
|
{
"pile_set_name": "Github"
}
|
from binaryninja import *
import base64
import copy
import json
def falcon_export(bv) :
filename = interaction.get_save_filename_input("Filename for Binja export")
segments = []
for segment in bv.segments :
segments.append({
'address': segment.start,
'bytes': base64.b64encode(bv.read(segment.start, segment.length))
})
functions = []
for function in bv.functions :
functions.append({
'name': function.name,
'address': function.start,
})
fh = open(filename, 'wb')
fh.write(json.dumps({
'functions': functions,
'segments': segments,
'arch': bv.arch.name,
'entry': bv.entry_point
}))
fh.close()
PluginCommand.register("Export for Falcon",
"Export disassembly information for Falcon",
falcon_export)
|
{
"pile_set_name": "Github"
}
|
/*!
* jQuery Validation Plugin v1.14.0
*
* http://jqueryvalidation.org/
*
* Copyright (c) 2015 Jörn Zaefferer
* Released under the MIT license
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ["jquery"], factory );
} else {
factory( jQuery );
}
}(function( $ ) {
$.extend($.fn, {
// http://jqueryvalidation.org/validate/
validate: function( options ) {
// if nothing is selected, return nothing; can't chain anyway
if ( !this.length ) {
if ( options && options.debug && window.console ) {
console.warn( "Nothing selected, can't validate, returning nothing." );
}
return;
}
// check if a validator for this form was already created
var validator = $.data( this[ 0 ], "validator" );
if ( validator ) {
return validator;
}
// Add novalidate tag if HTML5.
this.attr( "novalidate", "novalidate" );
validator = new $.validator( options, this[ 0 ] );
$.data( this[ 0 ], "validator", validator );
if ( validator.settings.onsubmit ) {
this.on( "click.validate", ":submit", function( event ) {
if ( validator.settings.submitHandler ) {
validator.submitButton = event.target;
}
// allow suppressing validation by adding a cancel class to the submit button
if ( $( this ).hasClass( "cancel" ) ) {
validator.cancelSubmit = true;
}
// allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
if ( $( this ).attr( "formnovalidate" ) !== undefined ) {
validator.cancelSubmit = true;
}
});
// validate the form on submit
this.on( "submit.validate", function( event ) {
if ( validator.settings.debug ) {
// prevent form submit to be able to see console output
event.preventDefault();
}
function handle() {
var hidden, result;
if ( validator.settings.submitHandler ) {
if ( validator.submitButton ) {
// insert a hidden input as a replacement for the missing submit button
hidden = $( "<input type='hidden'/>" )
.attr( "name", validator.submitButton.name )
.val( $( validator.submitButton ).val() )
.appendTo( validator.currentForm );
}
result = validator.settings.submitHandler.call( validator, validator.currentForm, event );
if ( validator.submitButton ) {
// and clean up afterwards; thanks to no-block-scope, hidden can be referenced
hidden.remove();
}
if ( result !== undefined ) {
return result;
}
return false;
}
return true;
}
// prevent submit for invalid forms or custom submit handlers
if ( validator.cancelSubmit ) {
validator.cancelSubmit = false;
return handle();
}
if ( validator.form() ) {
if ( validator.pendingRequest ) {
validator.formSubmitted = true;
return false;
}
return handle();
} else {
validator.focusInvalid();
return false;
}
});
}
return validator;
},
// http://jqueryvalidation.org/valid/
valid: function() {
var valid, validator, errorList;
if ( $( this[ 0 ] ).is( "form" ) ) {
valid = this.validate().form();
} else {
errorList = [];
valid = true;
validator = $( this[ 0 ].form ).validate();
this.each( function() {
valid = validator.element( this ) && valid;
errorList = errorList.concat( validator.errorList );
});
validator.errorList = errorList;
}
return valid;
},
// http://jqueryvalidation.org/rules/
rules: function( command, argument ) {
var element = this[ 0 ],
settings, staticRules, existingRules, data, param, filtered;
if ( command ) {
settings = $.data( element.form, "validator" ).settings;
staticRules = settings.rules;
existingRules = $.validator.staticRules( element );
switch ( command ) {
case "add":
$.extend( existingRules, $.validator.normalizeRule( argument ) );
// remove messages from rules, but allow them to be set separately
delete existingRules.messages;
staticRules[ element.name ] = existingRules;
if ( argument.messages ) {
settings.messages[ element.name ] = $.extend( settings.messages[ element.name ], argument.messages );
}
break;
case "remove":
if ( !argument ) {
delete staticRules[ element.name ];
return existingRules;
}
filtered = {};
$.each( argument.split( /\s/ ), function( index, method ) {
filtered[ method ] = existingRules[ method ];
delete existingRules[ method ];
if ( method === "required" ) {
$( element ).removeAttr( "aria-required" );
}
});
return filtered;
}
}
data = $.validator.normalizeRules(
$.extend(
{},
$.validator.classRules( element ),
$.validator.attributeRules( element ),
$.validator.dataRules( element ),
$.validator.staticRules( element )
), element );
// make sure required is at front
if ( data.required ) {
param = data.required;
delete data.required;
data = $.extend( { required: param }, data );
$( element ).attr( "aria-required", "true" );
}
// make sure remote is at back
if ( data.remote ) {
param = data.remote;
delete data.remote;
data = $.extend( data, { remote: param });
}
return data;
}
});
// Custom selectors
$.extend( $.expr[ ":" ], {
// http://jqueryvalidation.org/blank-selector/
blank: function( a ) {
return !$.trim( "" + $( a ).val() );
},
// http://jqueryvalidation.org/filled-selector/
filled: function( a ) {
return !!$.trim( "" + $( a ).val() );
},
// http://jqueryvalidation.org/unchecked-selector/
unchecked: function( a ) {
return !$( a ).prop( "checked" );
}
});
// constructor for validator
$.validator = function( options, form ) {
this.settings = $.extend( true, {}, $.validator.defaults, options );
this.currentForm = form;
this.init();
};
// http://jqueryvalidation.org/jQuery.validator.format/
$.validator.format = function( source, params ) {
if ( arguments.length === 1 ) {
return function() {
var args = $.makeArray( arguments );
args.unshift( source );
return $.validator.format.apply( this, args );
};
}
if ( arguments.length > 2 && params.constructor !== Array ) {
params = $.makeArray( arguments ).slice( 1 );
}
if ( params.constructor !== Array ) {
params = [ params ];
}
$.each( params, function( i, n ) {
source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() {
return n;
});
});
return source;
};
$.extend( $.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "error",
validClass: "valid",
errorElement: "label",
focusCleanup: false,
focusInvalid: true,
errorContainer: $( [] ),
errorLabelContainer: $( [] ),
onsubmit: true,
ignore: ":hidden",
ignoreTitle: false,
onfocusin: function( element ) {
this.lastActive = element;
// Hide error label and remove error class on focus if enabled
if ( this.settings.focusCleanup ) {
if ( this.settings.unhighlight ) {
this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
}
this.hideThese( this.errorsFor( element ) );
}
},
onfocusout: function( element ) {
if ( !this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) ) {
this.element( element );
}
},
onkeyup: function( element, event ) {
// Avoid revalidate the field when pressing one of the following keys
// Shift => 16
// Ctrl => 17
// Alt => 18
// Caps lock => 20
// End => 35
// Home => 36
// Left arrow => 37
// Up arrow => 38
// Right arrow => 39
// Down arrow => 40
// Insert => 45
// Num lock => 144
// AltGr key => 225
var excludedKeys = [
16, 17, 18, 20, 35, 36, 37,
38, 39, 40, 45, 144, 225
];
if ( event.which === 9 && this.elementValue( element ) === "" || $.inArray( event.keyCode, excludedKeys ) !== -1 ) {
return;
} else if ( element.name in this.submitted || element === this.lastElement ) {
this.element( element );
}
},
onclick: function( element ) {
// click on selects, radiobuttons and checkboxes
if ( element.name in this.submitted ) {
this.element( element );
// or option elements, check parent select in that case
} else if ( element.parentNode.name in this.submitted ) {
this.element( element.parentNode );
}
},
highlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );
} else {
$( element ).addClass( errorClass ).removeClass( validClass );
}
},
unhighlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );
} else {
$( element ).removeClass( errorClass ).addClass( validClass );
}
}
},
// http://jqueryvalidation.org/jQuery.validator.setDefaults/
setDefaults: function( settings ) {
$.extend( $.validator.defaults, settings );
},
messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date ( ISO ).",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
maxlength: $.validator.format( "Please enter no more than {0} characters." ),
minlength: $.validator.format( "Please enter at least {0} characters." ),
rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ),
range: $.validator.format( "Please enter a value between {0} and {1}." ),
max: $.validator.format( "Please enter a value less than or equal to {0}." ),
min: $.validator.format( "Please enter a value greater than or equal to {0}." )
},
autoCreateRanges: false,
prototype: {
init: function() {
this.labelContainer = $( this.settings.errorLabelContainer );
this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm );
this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer );
this.submitted = {};
this.valueCache = {};
this.pendingRequest = 0;
this.pending = {};
this.invalid = {};
this.reset();
var groups = ( this.groups = {} ),
rules;
$.each( this.settings.groups, function( key, value ) {
if ( typeof value === "string" ) {
value = value.split( /\s/ );
}
$.each( value, function( index, name ) {
groups[ name ] = key;
});
});
rules = this.settings.rules;
$.each( rules, function( key, value ) {
rules[ key ] = $.validator.normalizeRule( value );
});
function delegate( event ) {
var validator = $.data( this.form, "validator" ),
eventType = "on" + event.type.replace( /^validate/, "" ),
settings = validator.settings;
if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) {
settings[ eventType ].call( validator, this, event );
}
}
$( this.currentForm )
.on( "focusin.validate focusout.validate keyup.validate",
":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], " +
"[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], " +
"[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], " +
"[type='radio'], [type='checkbox']", delegate)
// Support: Chrome, oldIE
// "select" is provided as event.target when clicking a option
.on("click.validate", "select, option, [type='radio'], [type='checkbox']", delegate);
if ( this.settings.invalidHandler ) {
$( this.currentForm ).on( "invalid-form.validate", this.settings.invalidHandler );
}
// Add aria-required to any Static/Data/Class required fields before first validation
// Screen readers require this attribute to be present before the initial submission http://www.w3.org/TR/WCAG-TECHS/ARIA2.html
$( this.currentForm ).find( "[required], [data-rule-required], .required" ).attr( "aria-required", "true" );
},
// http://jqueryvalidation.org/Validator.form/
form: function() {
this.checkForm();
$.extend( this.submitted, this.errorMap );
this.invalid = $.extend({}, this.errorMap );
if ( !this.valid() ) {
$( this.currentForm ).triggerHandler( "invalid-form", [ this ]);
}
this.showErrors();
return this.valid();
},
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) {
this.check( elements[ i ] );
}
return this.valid();
},
// http://jqueryvalidation.org/Validator.element/
element: function( element ) {
var cleanElement = this.clean( element ),
checkElement = this.validationTargetFor( cleanElement ),
result = true;
this.lastElement = checkElement;
if ( checkElement === undefined ) {
delete this.invalid[ cleanElement.name ];
} else {
this.prepareElement( checkElement );
this.currentElements = $( checkElement );
result = this.check( checkElement ) !== false;
if ( result ) {
delete this.invalid[ checkElement.name ];
} else {
this.invalid[ checkElement.name ] = true;
}
}
// Add aria-invalid status for screen readers
$( element ).attr( "aria-invalid", !result );
if ( !this.numberOfInvalids() ) {
// Hide error containers on last error
this.toHide = this.toHide.add( this.containers );
}
this.showErrors();
return result;
},
// http://jqueryvalidation.org/Validator.showErrors/
showErrors: function( errors ) {
if ( errors ) {
// add items to error list and map
$.extend( this.errorMap, errors );
this.errorList = [];
for ( var name in errors ) {
this.errorList.push({
message: errors[ name ],
element: this.findByName( name )[ 0 ]
});
}
// remove items from success list
this.successList = $.grep( this.successList, function( element ) {
return !( element.name in errors );
});
}
if ( this.settings.showErrors ) {
this.settings.showErrors.call( this, this.errorMap, this.errorList );
} else {
this.defaultShowErrors();
}
},
// http://jqueryvalidation.org/Validator.resetForm/
resetForm: function() {
if ( $.fn.resetForm ) {
$( this.currentForm ).resetForm();
}
this.submitted = {};
this.lastElement = null;
this.prepareForm();
this.hideErrors();
var i, elements = this.elements()
.removeData( "previousValue" )
.removeAttr( "aria-invalid" );
if ( this.settings.unhighlight ) {
for ( i = 0; elements[ i ]; i++ ) {
this.settings.unhighlight.call( this, elements[ i ],
this.settings.errorClass, "" );
}
} else {
elements.removeClass( this.settings.errorClass );
}
},
numberOfInvalids: function() {
return this.objectLength( this.invalid );
},
objectLength: function( obj ) {
/* jshint unused: false */
var count = 0,
i;
for ( i in obj ) {
count++;
}
return count;
},
hideErrors: function() {
this.hideThese( this.toHide );
},
hideThese: function( errors ) {
errors.not( this.containers ).text( "" );
this.addWrapper( errors ).hide();
},
valid: function() {
return this.size() === 0;
},
size: function() {
return this.errorList.length;
},
focusInvalid: function() {
if ( this.settings.focusInvalid ) {
try {
$( this.findLastActive() || this.errorList.length && this.errorList[ 0 ].element || [])
.filter( ":visible" )
.focus()
// manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
.trigger( "focusin" );
} catch ( e ) {
// ignore IE throwing errors when focusing hidden elements
}
}
},
findLastActive: function() {
var lastActive = this.lastActive;
return lastActive && $.grep( this.errorList, function( n ) {
return n.element.name === lastActive.name;
}).length === 1 && lastActive;
},
elements: function() {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
return $( this.currentForm )
.find( "input, select, textarea" )
.not( ":submit, :reset, :image, :disabled" )
.not( this.settings.ignore )
.filter( function() {
if ( !this.name && validator.settings.debug && window.console ) {
console.error( "%o has no name assigned", this );
}
// select only the first element for each name, and only those with rules specified
if ( this.name in rulesCache || !validator.objectLength( $( this ).rules() ) ) {
return false;
}
rulesCache[ this.name ] = true;
return true;
});
},
clean: function( selector ) {
return $( selector )[ 0 ];
},
errors: function() {
var errorClass = this.settings.errorClass.split( " " ).join( "." );
return $( this.settings.errorElement + "." + errorClass, this.errorContext );
},
reset: function() {
this.successList = [];
this.errorList = [];
this.errorMap = {};
this.toShow = $( [] );
this.toHide = $( [] );
this.currentElements = $( [] );
},
prepareForm: function() {
this.reset();
this.toHide = this.errors().add( this.containers );
},
prepareElement: function( element ) {
this.reset();
this.toHide = this.errorsFor( element );
},
elementValue: function( element ) {
var val,
$element = $( element ),
type = element.type;
if ( type === "radio" || type === "checkbox" ) {
return this.findByName( element.name ).filter(":checked").val();
} else if ( type === "number" && typeof element.validity !== "undefined" ) {
return element.validity.badInput ? false : $element.val();
}
val = $element.val();
if ( typeof val === "string" ) {
return val.replace(/\r/g, "" );
}
return val;
},
check: function( element ) {
element = this.validationTargetFor( this.clean( element ) );
var rules = $( element ).rules(),
rulesCount = $.map( rules, function( n, i ) {
return i;
}).length,
dependencyMismatch = false,
val = this.elementValue( element ),
result, method, rule;
for ( method in rules ) {
rule = { method: method, parameters: rules[ method ] };
try {
result = $.validator.methods[ method ].call( this, val, element, rule.parameters );
// if a method indicates that the field is optional and therefore valid,
// don't mark it as valid when there are no other rules
if ( result === "dependency-mismatch" && rulesCount === 1 ) {
dependencyMismatch = true;
continue;
}
dependencyMismatch = false;
if ( result === "pending" ) {
this.toHide = this.toHide.not( this.errorsFor( element ) );
return;
}
if ( !result ) {
this.formatAndAdd( element, rule );
return false;
}
} catch ( e ) {
if ( this.settings.debug && window.console ) {
console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e );
}
if ( e instanceof TypeError ) {
e.message += ". Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.";
}
throw e;
}
}
if ( dependencyMismatch ) {
return;
}
if ( this.objectLength( rules ) ) {
this.successList.push( element );
}
return true;
},
// return the custom message for the given element and validation method
// specified in the element's HTML5 data attribute
// return the generic message if present and no method specific message is present
customDataMessage: function( element, method ) {
return $( element ).data( "msg" + method.charAt( 0 ).toUpperCase() +
method.substring( 1 ).toLowerCase() ) || $( element ).data( "msg" );
},
// return the custom message for the given element name and validation method
customMessage: function( name, method ) {
var m = this.settings.messages[ name ];
return m && ( m.constructor === String ? m : m[ method ]);
},
// return the first defined argument, allowing empty strings
findDefined: function() {
for ( var i = 0; i < arguments.length; i++) {
if ( arguments[ i ] !== undefined ) {
return arguments[ i ];
}
}
return undefined;
},
defaultMessage: function( element, method ) {
return this.findDefined(
this.customMessage( element.name, method ),
this.customDataMessage( element, method ),
// title is never undefined, so handle empty string as undefined
!this.settings.ignoreTitle && element.title || undefined,
$.validator.messages[ method ],
"<strong>Warning: No message defined for " + element.name + "</strong>"
);
},
formatAndAdd: function( element, rule ) {
var message = this.defaultMessage( element, rule.method ),
theregex = /\$?\{(\d+)\}/g;
if ( typeof message === "function" ) {
message = message.call( this, rule.parameters, element );
} else if ( theregex.test( message ) ) {
message = $.validator.format( message.replace( theregex, "{$1}" ), rule.parameters );
}
this.errorList.push({
message: message,
element: element,
method: rule.method
});
this.errorMap[ element.name ] = message;
this.submitted[ element.name ] = message;
},
addWrapper: function( toToggle ) {
if ( this.settings.wrapper ) {
toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
}
return toToggle;
},
defaultShowErrors: function() {
var i, elements, error;
for ( i = 0; this.errorList[ i ]; i++ ) {
error = this.errorList[ i ];
if ( this.settings.highlight ) {
this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
}
this.showLabel( error.element, error.message );
}
if ( this.errorList.length ) {
this.toShow = this.toShow.add( this.containers );
}
if ( this.settings.success ) {
for ( i = 0; this.successList[ i ]; i++ ) {
this.showLabel( this.successList[ i ] );
}
}
if ( this.settings.unhighlight ) {
for ( i = 0, elements = this.validElements(); elements[ i ]; i++ ) {
this.settings.unhighlight.call( this, elements[ i ], this.settings.errorClass, this.settings.validClass );
}
}
this.toHide = this.toHide.not( this.toShow );
this.hideErrors();
this.addWrapper( this.toShow ).show();
},
validElements: function() {
return this.currentElements.not( this.invalidElements() );
},
invalidElements: function() {
return $( this.errorList ).map(function() {
return this.element;
});
},
showLabel: function( element, message ) {
var place, group, errorID,
error = this.errorsFor( element ),
elementID = this.idOrName( element ),
describedBy = $( element ).attr( "aria-describedby" );
if ( error.length ) {
// refresh error/success class
error.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );
// replace message on existing label
error.html( message );
} else {
// create error element
error = $( "<" + this.settings.errorElement + ">" )
.attr( "id", elementID + "-error" )
.addClass( this.settings.errorClass )
.html( message || "" );
// Maintain reference to the element to be placed into the DOM
place = error;
if ( this.settings.wrapper ) {
// make sure the element is visible, even in IE
// actually showing the wrapped element is handled elsewhere
place = error.hide().show().wrap( "<" + this.settings.wrapper + "/>" ).parent();
}
if ( this.labelContainer.length ) {
this.labelContainer.append( place );
} else if ( this.settings.errorPlacement ) {
this.settings.errorPlacement( place, $( element ) );
} else {
place.insertAfter( element );
}
// Link error back to the element
if ( error.is( "label" ) ) {
// If the error is a label, then associate using 'for'
error.attr( "for", elementID );
} else if ( error.parents( "label[for='" + elementID + "']" ).length === 0 ) {
// If the element is not a child of an associated label, then it's necessary
// to explicitly apply aria-describedby
errorID = error.attr( "id" ).replace( /(:|\.|\[|\]|\$)/g, "\\$1");
// Respect existing non-error aria-describedby
if ( !describedBy ) {
describedBy = errorID;
} else if ( !describedBy.match( new RegExp( "\\b" + errorID + "\\b" ) ) ) {
// Add to end of list if not already present
describedBy += " " + errorID;
}
$( element ).attr( "aria-describedby", describedBy );
// If this element is grouped, then assign to all elements in the same group
group = this.groups[ element.name ];
if ( group ) {
$.each( this.groups, function( name, testgroup ) {
if ( testgroup === group ) {
$( "[name='" + name + "']", this.currentForm )
.attr( "aria-describedby", error.attr( "id" ) );
}
});
}
}
}
if ( !message && this.settings.success ) {
error.text( "" );
if ( typeof this.settings.success === "string" ) {
error.addClass( this.settings.success );
} else {
this.settings.success( error, element );
}
}
this.toShow = this.toShow.add( error );
},
errorsFor: function( element ) {
var name = this.idOrName( element ),
describer = $( element ).attr( "aria-describedby" ),
selector = "label[for='" + name + "'], label[for='" + name + "'] *";
// aria-describedby should directly reference the error element
if ( describer ) {
selector = selector + ", #" + describer.replace( /\s+/g, ", #" );
}
return this
.errors()
.filter( selector );
},
idOrName: function( element ) {
return this.groups[ element.name ] || ( this.checkable( element ) ? element.name : element.id || element.name );
},
validationTargetFor: function( element ) {
// If radio/checkbox, validate first element in group instead
if ( this.checkable( element ) ) {
element = this.findByName( element.name );
}
// Always apply ignore filter
return $( element ).not( this.settings.ignore )[ 0 ];
},
checkable: function( element ) {
return ( /radio|checkbox/i ).test( element.type );
},
findByName: function( name ) {
return $( this.currentForm ).find( "[name='" + name + "']" );
},
getLength: function( value, element ) {
switch ( element.nodeName.toLowerCase() ) {
case "select":
return $( "option:selected", element ).length;
case "input":
if ( this.checkable( element ) ) {
return this.findByName( element.name ).filter( ":checked" ).length;
}
}
return value.length;
},
depend: function( param, element ) {
return this.dependTypes[typeof param] ? this.dependTypes[typeof param]( param, element ) : true;
},
dependTypes: {
"boolean": function( param ) {
return param;
},
"string": function( param, element ) {
return !!$( param, element.form ).length;
},
"function": function( param, element ) {
return param( element );
}
},
optional: function( element ) {
var val = this.elementValue( element );
return !$.validator.methods.required.call( this, val, element ) && "dependency-mismatch";
},
startRequest: function( element ) {
if ( !this.pending[ element.name ] ) {
this.pendingRequest++;
this.pending[ element.name ] = true;
}
},
stopRequest: function( element, valid ) {
this.pendingRequest--;
// sometimes synchronization fails, make sure pendingRequest is never < 0
if ( this.pendingRequest < 0 ) {
this.pendingRequest = 0;
}
delete this.pending[ element.name ];
if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) {
$( this.currentForm ).submit();
this.formSubmitted = false;
} else if (!valid && this.pendingRequest === 0 && this.formSubmitted ) {
$( this.currentForm ).triggerHandler( "invalid-form", [ this ]);
this.formSubmitted = false;
}
},
previousValue: function( element ) {
return $.data( element, "previousValue" ) || $.data( element, "previousValue", {
old: null,
valid: true,
message: this.defaultMessage( element, "remote" )
});
},
// cleans up all forms and elements, removes validator-specific events
destroy: function() {
this.resetForm();
$( this.currentForm )
.off( ".validate" )
.removeData( "validator" );
}
},
classRuleSettings: {
required: { required: true },
email: { email: true },
url: { url: true },
date: { date: true },
dateISO: { dateISO: true },
number: { number: true },
digits: { digits: true },
creditcard: { creditcard: true }
},
addClassRules: function( className, rules ) {
if ( className.constructor === String ) {
this.classRuleSettings[ className ] = rules;
} else {
$.extend( this.classRuleSettings, className );
}
},
classRules: function( element ) {
var rules = {},
classes = $( element ).attr( "class" );
if ( classes ) {
$.each( classes.split( " " ), function() {
if ( this in $.validator.classRuleSettings ) {
$.extend( rules, $.validator.classRuleSettings[ this ]);
}
});
}
return rules;
},
normalizeAttributeRule: function( rules, type, method, value ) {
// convert the value to a number for number inputs, and for text for backwards compability
// allows type="date" and others to be compared as strings
if ( /min|max/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) {
value = Number( value );
// Support Opera Mini, which returns NaN for undefined minlength
if ( isNaN( value ) ) {
value = undefined;
}
}
if ( value || value === 0 ) {
rules[ method ] = value;
} else if ( type === method && type !== "range" ) {
// exception: the jquery validate 'range' method
// does not test for the html5 'range' type
rules[ method ] = true;
}
},
attributeRules: function( element ) {
var rules = {},
$element = $( element ),
type = element.getAttribute( "type" ),
method, value;
for ( method in $.validator.methods ) {
// support for <input required> in both html5 and older browsers
if ( method === "required" ) {
value = element.getAttribute( method );
// Some browsers return an empty string for the required attribute
// and non-HTML5 browsers might have required="" markup
if ( value === "" ) {
value = true;
}
// force non-HTML5 browsers to return bool
value = !!value;
} else {
value = $element.attr( method );
}
this.normalizeAttributeRule( rules, type, method, value );
}
// maxlength may be returned as -1, 2147483647 ( IE ) and 524288 ( safari ) for text inputs
if ( rules.maxlength && /-1|2147483647|524288/.test( rules.maxlength ) ) {
delete rules.maxlength;
}
return rules;
},
dataRules: function( element ) {
var rules = {},
$element = $( element ),
type = element.getAttribute( "type" ),
method, value;
for ( method in $.validator.methods ) {
value = $element.data( "rule" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() );
this.normalizeAttributeRule( rules, type, method, value );
}
return rules;
},
staticRules: function( element ) {
var rules = {},
validator = $.data( element.form, "validator" );
if ( validator.settings.rules ) {
rules = $.validator.normalizeRule( validator.settings.rules[ element.name ] ) || {};
}
return rules;
},
normalizeRules: function( rules, element ) {
// handle dependency check
$.each( rules, function( prop, val ) {
// ignore rule when param is explicitly false, eg. required:false
if ( val === false ) {
delete rules[ prop ];
return;
}
if ( val.param || val.depends ) {
var keepRule = true;
switch ( typeof val.depends ) {
case "string":
keepRule = !!$( val.depends, element.form ).length;
break;
case "function":
keepRule = val.depends.call( element, element );
break;
}
if ( keepRule ) {
rules[ prop ] = val.param !== undefined ? val.param : true;
} else {
delete rules[ prop ];
}
}
});
// evaluate parameters
$.each( rules, function( rule, parameter ) {
rules[ rule ] = $.isFunction( parameter ) ? parameter( element ) : parameter;
});
// clean number parameters
$.each([ "minlength", "maxlength" ], function() {
if ( rules[ this ] ) {
rules[ this ] = Number( rules[ this ] );
}
});
$.each([ "rangelength", "range" ], function() {
var parts;
if ( rules[ this ] ) {
if ( $.isArray( rules[ this ] ) ) {
rules[ this ] = [ Number( rules[ this ][ 0 ]), Number( rules[ this ][ 1 ] ) ];
} else if ( typeof rules[ this ] === "string" ) {
parts = rules[ this ].replace(/[\[\]]/g, "" ).split( /[\s,]+/ );
rules[ this ] = [ Number( parts[ 0 ]), Number( parts[ 1 ] ) ];
}
}
});
if ( $.validator.autoCreateRanges ) {
// auto-create ranges
if ( rules.min != null && rules.max != null ) {
rules.range = [ rules.min, rules.max ];
delete rules.min;
delete rules.max;
}
if ( rules.minlength != null && rules.maxlength != null ) {
rules.rangelength = [ rules.minlength, rules.maxlength ];
delete rules.minlength;
delete rules.maxlength;
}
}
return rules;
},
// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
normalizeRule: function( data ) {
if ( typeof data === "string" ) {
var transformed = {};
$.each( data.split( /\s/ ), function() {
transformed[ this ] = true;
});
data = transformed;
}
return data;
},
// http://jqueryvalidation.org/jQuery.validator.addMethod/
addMethod: function( name, method, message ) {
$.validator.methods[ name ] = method;
$.validator.messages[ name ] = message !== undefined ? message : $.validator.messages[ name ];
if ( method.length < 3 ) {
$.validator.addClassRules( name, $.validator.normalizeRule( name ) );
}
},
methods: {
// http://jqueryvalidation.org/required-method/
required: function( value, element, param ) {
// check if dependency is met
if ( !this.depend( param, element ) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
// could be an array for select-multiple or a string, both are fine this way
var val = $( element ).val();
return val && val.length > 0;
}
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return value.length > 0;
},
// http://jqueryvalidation.org/email-method/
email: function( value, element ) {
// From https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
// Retrieved 2014-01-14
// If you have a problem with this implementation, report a bug against the above spec
// Or use custom methods to implement your own email validation
return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
},
// http://jqueryvalidation.org/url-method/
url: function( value, element ) {
// Copyright (c) 2010-2013 Diego Perini, MIT licensed
// https://gist.github.com/dperini/729294
// see also https://mathiasbynens.be/demo/url-regex
// modified to allow protocol-relative URLs
return this.optional( element ) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test( value );
},
// http://jqueryvalidation.org/date-method/
date: function( value, element ) {
return this.optional( element ) || !/Invalid|NaN/.test( new Date( value ).toString() );
},
// http://jqueryvalidation.org/dateISO-method/
dateISO: function( value, element ) {
return this.optional( element ) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test( value );
},
// http://jqueryvalidation.org/number-method/
number: function( value, element ) {
return this.optional( element ) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value );
},
// http://jqueryvalidation.org/digits-method/
digits: function( value, element ) {
return this.optional( element ) || /^\d+$/.test( value );
},
// http://jqueryvalidation.org/creditcard-method/
// based on http://en.wikipedia.org/wiki/Luhn_algorithm
creditcard: function( value, element ) {
if ( this.optional( element ) ) {
return "dependency-mismatch";
}
// accept only spaces, digits and dashes
if ( /[^0-9 \-]+/.test( value ) ) {
return false;
}
var nCheck = 0,
nDigit = 0,
bEven = false,
n, cDigit;
value = value.replace( /\D/g, "" );
// Basing min and max length on
// http://developer.ean.com/general_info/Valid_Credit_Card_Types
if ( value.length < 13 || value.length > 19 ) {
return false;
}
for ( n = value.length - 1; n >= 0; n--) {
cDigit = value.charAt( n );
nDigit = parseInt( cDigit, 10 );
if ( bEven ) {
if ( ( nDigit *= 2 ) > 9 ) {
nDigit -= 9;
}
}
nCheck += nDigit;
bEven = !bEven;
}
return ( nCheck % 10 ) === 0;
},
// http://jqueryvalidation.org/minlength-method/
minlength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || length >= param;
},
// http://jqueryvalidation.org/maxlength-method/
maxlength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || length <= param;
},
// http://jqueryvalidation.org/rangelength-method/
rangelength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || ( length >= param[ 0 ] && length <= param[ 1 ] );
},
// http://jqueryvalidation.org/min-method/
min: function( value, element, param ) {
return this.optional( element ) || value >= param;
},
// http://jqueryvalidation.org/max-method/
max: function( value, element, param ) {
return this.optional( element ) || value <= param;
},
// http://jqueryvalidation.org/range-method/
range: function( value, element, param ) {
return this.optional( element ) || ( value >= param[ 0 ] && value <= param[ 1 ] );
},
// http://jqueryvalidation.org/equalTo-method/
equalTo: function( value, element, param ) {
// bind to the blur event of the target in order to revalidate whenever the target field is updated
// TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
var target = $( param );
if ( this.settings.onfocusout ) {
target.off( ".validate-equalTo" ).on( "blur.validate-equalTo", function() {
$( element ).valid();
});
}
return value === target.val();
},
// http://jqueryvalidation.org/remote-method/
remote: function( value, element, param ) {
if ( this.optional( element ) ) {
return "dependency-mismatch";
}
var previous = this.previousValue( element ),
validator, data;
if (!this.settings.messages[ element.name ] ) {
this.settings.messages[ element.name ] = {};
}
previous.originalMessage = this.settings.messages[ element.name ].remote;
this.settings.messages[ element.name ].remote = previous.message;
param = typeof param === "string" && { url: param } || param;
if ( previous.old === value ) {
return previous.valid;
}
previous.old = value;
validator = this;
this.startRequest( element );
data = {};
data[ element.name ] = value;
$.ajax( $.extend( true, {
mode: "abort",
port: "validate" + element.name,
dataType: "json",
data: data,
context: validator.currentForm,
success: function( response ) {
var valid = response === true || response === "true",
errors, message, submitted;
validator.settings.messages[ element.name ].remote = previous.originalMessage;
if ( valid ) {
submitted = validator.formSubmitted;
validator.prepareElement( element );
validator.formSubmitted = submitted;
validator.successList.push( element );
delete validator.invalid[ element.name ];
validator.showErrors();
} else {
errors = {};
message = response || validator.defaultMessage( element, "remote" );
errors[ element.name ] = previous.message = $.isFunction( message ) ? message( value ) : message;
validator.invalid[ element.name ] = true;
validator.showErrors( errors );
}
previous.valid = valid;
validator.stopRequest( element, valid );
}
}, param ) );
return "pending";
}
}
});
// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
var pendingRequests = {},
ajax;
// Use a prefilter if available (1.5+)
if ( $.ajaxPrefilter ) {
$.ajaxPrefilter(function( settings, _, xhr ) {
var port = settings.port;
if ( settings.mode === "abort" ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
pendingRequests[port] = xhr;
}
});
} else {
// Proxy ajax
ajax = $.ajax;
$.ajax = function( settings ) {
var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
port = ( "port" in settings ? settings : $.ajaxSettings ).port;
if ( mode === "abort" ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
pendingRequests[port] = ajax.apply(this, arguments);
return pendingRequests[port];
}
return ajax.apply(this, arguments);
};
}
}));
|
{
"pile_set_name": "Github"
}
|
import maya.cmds as mc
import maya.mel as mm
import glTools.utils.base
import glTools.utils.curve
import glTools.utils.mesh
import glTools.utils.namespace
import glTools.utils.osUtils
import glTools.utils.stringUtils
import glTools.utils.surface
import re
class UserInputError(Exception): pass
class UIError(Exception): pass
# ==============
# - Text Field -
# ==============
def loadFilePath(textField,fileFilter=None,caption='Load File',startDir=None):
'''
Select a file path to load into a specified textField.
@param textField: TextField UI object to load file path to
@type textField: str
@param fileFilter: File filter to apply to the file selection UI
@type fileFilter: str
@param caption: File selection UI caption string
@type caption: str
@param startDir: Directory to start browsing from. In None, use the default or last selected directory.
@type startDir: str
'''
# Get File Path
filePath = mc.fileDialog2( fileFilter=fileFilter,
dialogStyle=2,
fileMode=1,
caption=caption,
okCaption='Load',
startingDirectory=startDir )
# Check File Path
if not filePath:
print('Invalid file path!')
return
# Load File Path to TextField
if mc.textField(textField,q=True,ex=True):
mc.textField(textField,e=True,text=filePath[0])
elif mc.textFieldGrp(textField,q=True,ex=True):
mc.textFieldGrp(textField,e=True,text=filePath[0])
elif mc.textFieldButtonGrp(textField,q=True,ex=True):
mc.textFieldButtonGrp(textField,e=True,text=filePath[0])
else:
print('UI element "" is not a valid textField, textFieldGrp or textFieldButtonGrp!')
return
# Return Result
return filePath[0]
def loadDirectoryPath(textField,caption='Load Directory',startDir=None):
'''
Select a file path to load into a specified textField.
@param textField: TextField UI object to load file path to
@type textField: str
@param caption: File selection UI caption string
@type caption: str
@param startDir: Directory to start browsing from. In None, use the default or last selected directory.
@type startDir: str
'''
# Get File Path
dirPath = mc.fileDialog2( dialogStyle=2,
fileMode=3,
caption=caption,
okCaption='Load',
startingDirectory=startDir )
# Check File Path
if not dirPath:
print('Invalid directory path!')
return
# Load File Path to TextField
if mc.textField(textField,q=True,ex=True):
mc.textField(textField,e=True,text=dirPath[0])
elif mc.textFieldGrp(textField,q=True,ex=True):
mc.textFieldGrp(textField,e=True,text=dirPath[0])
elif mc.textFieldButtonGrp(textField,q=True,ex=True):
mc.textFieldButtonGrp(textField,e=True,text=dirPath[0])
else:
print('UI element "'+textField+'" is of type "'+mc.objectTypeUI(textField)+'"! Expected textField, textFieldGrp or textFieldButtonGrp.')
return
# Return Result
return dirPath[0]
def importFolderBrowser(textField): # ,caption='Import',startingDirectory=None):
'''
Set the input directory from file browser selection
'''
mm.eval('global proc importGetFolder(string $textField,string $path,string $type){ textFieldButtonGrp -e -text $path $textField; deleteUI projectViewerWindow; }')
mm.eval('fileBrowser "importGetFolder '+textField+'" Import "" 4')
#dirPath = mc.fileDialog2(dialogStyle=2,fileMode=3,caption='Load Scenegraph XML',okCaption='Load',startingDirectory=startingDirectory)
def exportFolderBrowser(textField):
'''
Set the output directory from file browser selection
'''
mm.eval('global proc exportGetFolder(string $textField,string $path,string $type){ textFieldButtonGrp -e -text $path $textField; /*deleteUI projectViewerWindow;*/ }')
mm.eval('fileBrowser "exportGetFolder '+textField+'" Export "" 4')
def loadNsSel(textField,topOnly=True):
'''
Load selected namespace into UI text field
@param textField: TextField UI object to load namespace selection into
@type textField: str
@param topOnly: Return the top level namespace only.
@type topOnly: bool
'''
# Get Selection
sel = mc.ls(sl=True)
if not sel: return
# Get Selected Namespace
NS = ''
NS = glTools.utils.namespace.getNS(sel[0],topOnly)
# Update UI
mc.textFieldButtonGrp(textField,e=True,text=NS)
def loadObjectSel(textField,prefixTextField=''):
'''
Load selected object into UI text field
@param textField: TextField UI object to load object selection into
@type textField: str
@param prefixTextField: TextField UI object to load object name prefix into
@type prefixTextField: str
'''
# Get user selection
sel = mc.ls(sl=True)
# Check selection
if not sel: return
# Update UI
mc.textFieldButtonGrp(textField,e=True,text=sel[0])
if prefixTextField:
if not mc.textFieldGrp(prefixTextField,q=True,text=True):
prefix = glTools.utils.stringUtils.stripSuffix(sel[0])
mc.textFieldGrp(prefixTextField,e=True,text=prefix)
def loadTypeSel(textField,prefixTextField='',selType=''):
'''
Load selected joint into UI text field
@param textField: TextField UI object to load joint selection into
@type textField: str
@param prefixTextField: TextField UI object to load curve name prefix into
@type prefixTextField: str
'''
if not selType: raise UserInputError('No selection type specified!!')
# Get user selection
sel = mc.ls(sl=True,type=selType)
# Check selection
if not sel: return
# Update UI
mc.textFieldButtonGrp(textField,e=True,text=sel[0])
if prefixTextField:
prefix = glTools.utils.stringUtils.stripSuffix(sel[0])
mc.textFieldGrp(prefixTextField,e=True,text=prefix)
def loadCurveSel(textField,prefixTextField=''):
'''
Load selected curve into UI text field
@param textField: TextField UI object to load curve selection into
@type textField: str
@param prefixTextField: TextField UI object to load curve name prefix into
@type prefixTextField: str
'''
# Get user selection
sel = mc.ls(sl=True)
# Check selection
if not sel: return
if not glTools.utils.curve.isCurve(sel[0]):
raise UserInputError('Object "'+sel[0]+'" is not a valid nurbs curve!!')
# Update UI
mc.textFieldButtonGrp(textField,e=True,text=sel[0])
if prefixTextField:
if not mc.textFieldGrp(prefixTextField,q=True,text=True):
prefix = glTools.utils.stringUtils.stripSuffix(sel[0])
mc.textFieldGrp(prefixTextField,e=True,text=prefix)
def loadSurfaceSel(textField,prefixTextField=''):
'''
Load selected surface into UI text field
@param textField: TextField UI object to load surface selection into
@type textField: str
@param prefixTextField: TextField UI object to load surface name prefix into
@type prefixTextField: str
'''
# Get user selection
sel = mc.ls(sl=True)
# Check selection
if not sel: return
if not glTools.utils.surface.isSurface(sel[0]):
raise UserInputError('Object "'+sel[0]+'" is not a valid nurbs surface!!')
# Update UI
mc.textFieldButtonGrp(textField,e=True,text=sel[0])
if prefixTextField:
if not mc.textFieldGrp(prefixTextField,q=True,text=True):
prefix = glTools.utils.stringUtils.stripSuffix(sel[0])
mc.textFieldGrp(prefixTextField,e=True,text=prefix)
def loadMeshSel(textField,prefixTextField=''):
'''
Load selected curve into UI text field
@param textField: TextField UI object to load mesh selection into
@type textField: str
@param prefixTextField: TextField UI object to load curve name prefix into
@type prefixTextField: str
'''
# Get user selection
sel = mc.ls(sl=True)
# Check selection
if not sel: return
if not glTools.utils.mesh.isMesh(sel[0]):
raise UserInputError('Object "'+sel[0]+'" is not a valid polygon mesh!!')
# Update UI
mc.textFieldButtonGrp(textField,e=True,text=sel[0])
if prefixTextField:
if not mc.textFieldGrp(prefixTextField,q=True,text=True):
prefix = glTools.utils.stringUtils.stripSuffix(sel[0])
mc.textFieldGrp(prefixTextField,e=True,text=prefix)
def loadChannelBoxSel(textField,fullName=True):
'''
Load selected channel into UI text field
@param textField: TextField UI object to load channelbox selection into
@type textField: str
@param fullName: Use full name of attribute (node.attribute)
@type fullName: bool
'''
# Get channelBox
channelBox = 'mainChannelBox'
# Check main object channels
nodeList = mc.channelBox(channelBox,q=True,mol=True)
channelList = mc.channelBox(channelBox,q=True,sma=True)
# Check shape channels
if not channelList:
channelList = mc.channelBox(channelBox,q=True,ssa=True)
nodeList = mc.channelBox(channelBox,q=True,sol=True)
# Check history channels
if not channelList:
channelList = mc.channelBox(channelBox,q=True,sha=True)
nodeList = mc.channelBox(channelBox,q=True,hol=True)
# Check output channels
if not channelList:
channelList = mc.channelBox(channelBox,q=True,soa=True)
nodeList = mc.channelBox(channelBox,q=True,ool=True)
# Check selection
if not channelList:
print('No channel selected in the channelBox!')
return
# Update UI
attr = ''
if fullName: attr += str(nodeList[0]+'.')
attr += str(channelList[0])
mc.textFieldButtonGrp(textField,e=True,text=attr)
# ====================
# - Text Scroll List -
# ====================
def copyTSLselToTSL(sourceTSL,targetTSL,removeFromSource=False,replaceTargetContents=False):
'''
Copy selected items from one textScrollList to another.
Options to remove from the source list (move) and replace existing target list items.
@param sourceTSL: Source textScrollList to copy selected items from
@type sourceTSL: str
@param targetTSL: Target textScrollList to copy selected items to
@type targetTSL: str
@param removeFromSource: Remove the selected itmes from the source list (move)
@type removeFromSource: bool
@param replaceTargetContents: Replace the existing target list items with the source selection
@type replaceTargetContents: bool
'''
# Get source selection
srcItems = mc.textScrollList(sourceTSL,q=True,si=True)
if not srcItems: return
# Clear target list
if replaceTragetContents: mc.textScrollList(targetTSL,e=True,ra=True)
# Get current target items
tgtItems = mc.textScrollList(targetTSL,q=True,si=True)
# Copy to target list
for src in srcItems:
# Check existing target items
if tgtItems.count(src): continue
# Append to target list
mc.textScrollList(targetTSL,e=True,a=src)
tgtItems.append(src)
# Remove from source
if removeFromSource: mc.textScrollList(sourceTSL,e=True,ri=src)
def addToTSL(TSL,itemList=[]):
'''
Add selected items to the specified textScrollList
@param TSL: TextScrollList UI object to load object selection into
@type TSL: str
'''
# Get user selection
if not itemList: itemList = mc.ls(sl=True)
# Check selection
if not itemList: return
# Update UI
currentList = mc.textScrollList(TSL,q=True,ai=True)
if not currentList: currentList = []
for item in itemList:
if not currentList.count(item):
mc.textScrollList(TSL,e=True,a=item)
def addCvsToTSL(TSL):
'''
Add selected nurbs control points to the specified textScrollList
@param TSL: TextScrollList UI object to load object selection into
@type TSL: str
'''
# Get user selection
sel = mc.filterExpand(sm=28)
# Check selection
if not sel: return
# Update UI
currentList = mc.textScrollList(TSL,q=True,ai=True)
if not currentList: currentList = []
for obj in sel:
if not currentList.count(obj):
mc.textScrollList(TSL,e=True,a=obj)
def removeFromTSL(TSL):
'''
Remove selected items from the specified textScrollList
@param TSL: TextScrollList UI object to remove items from
@type TSL: str
'''
# Update UI
listItems = mc.textScrollList(TSL,q=True,sii=True)
listItems.sort()
listItems.reverse()
mc.textScrollList(TSL,e=True,rii=listItems)
def selectFromTSL(TSL,mode='replace',safeFail=True):
'''
Select (replace mode) the hilited items from the specified textScrollList
@param TSL: TextScrollList UI object to remove items from
@type TSL: str
@param mode: Selection mode. Accepted values are "add", "replace", "toggle" and "remove"
@type mode: str
@param safeFail: Print safe message if item not found. Else, raise Exception.
@type safeFail: bool
'''
# Check Mode
if not mode in ['add','replace','toggle','remove']:
raise Exception('Invalid selection mode! ("'+mode+'")')
# Get Items to Select
listItems = mc.textScrollList(TSL,q=True,si=True)
if not listItems: return
# Clear Selection
if mode.lower() == 'replace': mc.select(cl=True)
# Select Items
for item in listItems:
# Check Object Exists
if not mc.objExists(item):
# Check Safe Fail
if safeFail:
print('Object "'+item+'" does not exist! Skipping...')
continue
else:
raise Exception('Object "'+item+'" does not exist!')
# Add Item to Selection
if (mode == 'add') or (mode == 'replace'):
mc.select(listItems,add=True,noExpand=True)
# Toggle Item Selection
if (mode == 'toggle'):
mc.select(listItems,tgl=True,noExpand=True)
# Remove Item Selection
if (mode == 'remove'):
mc.select(listItems,d=True,noExpand=True)
def moveToTSLPosition(TSL,index):
'''
Move the selected textScrollList item(s) to the specified position in the list
@param TSL: The name of th textScrollList to manipulate
@type TSL: str
@param index: The new index position for the selected list items
@type index: int
'''
# Get all list entries
listLen = len(mc.textScrollList(TSL,q=True,ai=True))
# Get selected item indices
listItems = mc.textScrollList(TSL,q=True,si=True)
listIndex = mc.textScrollList(TSL,q=True,sii=True)
listItems.reverse()
listIndex.reverse()
# Check position value
if not index or index > listLen:
raise UserInputError('Invalid position ('+str(index)+') provided for textScrollList!!')
if index < 0:
index = 2 + listLen + index
# Remove items
for i in range(len(listIndex)):
if listIndex[i] < index: index -= 1
mc.textScrollList(TSL,e=True,rii=listIndex)
# Append items to position
for i in range(len(listIndex)):
mc.textScrollList(TSL,e=True,ap=(index,listItems[i]))
listIndex[i] = index + i
# Select list items
mc.textScrollList(TSL,e=True,da=True)
mc.textScrollList(TSL,e=True,sii=listIndex)
mc.textScrollList(TSL,e=True,shi=listIndex[0])
def moveUpTSLPosition(TSL):
'''
Move the selected textScrollList items up by one position
@param TSL: The name of th textScrollList to manipulate
@type TSL: str
'''
# Method variables
minIndex = 1
# Get selected item indices
listItems = mc.textScrollList(TSL,q=True,si=True)
listIndex = mc.textScrollList(TSL,q=True,sii=True)
# Iterate through list items
for i in range(len(listIndex)):
# Check minIndex
if listIndex[i] <= minIndex:
minIndex += 1
continue
mc.textScrollList(TSL,e=True,sii=listIndex[i])
listIndex[i] -= 1
moveToTSLPosition(TSL,listIndex[i])
# Select list items
mc.textScrollList(TSL,e=True,da=True)
mc.textScrollList(TSL,e=True,sii=listIndex)
mc.textScrollList(TSL,e=True,shi=listIndex[0])
def moveDownTSLPosition(TSL):
'''
Move the selected textScrollList items down by one position
@param TSL: The name of th textScrollList to manipulate
@type TSL: str
'''
# Get list length
listLen = len(mc.textScrollList(TSL,q=True,ai=True))
maxIndex = listLen
# Get selected item indices
listItems = mc.textScrollList(TSL,q=True,si=True)
listIndex = mc.textScrollList(TSL,q=True,sii=True)
# Reverse lists
listItems.reverse()
listIndex.reverse()
# Iterate through list items
for i in range(len(listItems)):
# Check maxIndex
if listIndex[i] >= maxIndex:
maxIndex -= 1
continue
mc.textScrollList(TSL,e=True,sii=listIndex[i])
listIndex[i] += 1
if listIndex[i] == listLen:
moveToTSLPosition(TSL,-1)
else:
moveToTSLPosition(TSL,listIndex[i]+1)
# Select list items
mc.textScrollList(TSL,e=True,da=True)
mc.textScrollList(TSL,e=True,sii=listIndex)
mc.textScrollList(TSL,e=True,shi=listIndex[0])
def loadFileSelection(TSL,fileFilter='*.*',startDir=None,caption='Load Files'):
'''
'''
# Select Files
fileList = mc.fileDialog2( fileFilter=fileFilter,
dialogStyle=2,
fileMode=4,
caption=caption,
okCaption='Load',
startingDirectory=startDir )
# Add File Selection
if fileList:
for item in fileList:
mc.textScrollList(TSL,e=True,a=item)
def loadFileList(TSL,path,filesOnly=False,filterStr='',sort=False):
'''
Load the file list of a specified directory path to a textScrollList
@param TSL: TextScrollList UI object to load file list into.
@type TSL: str
@param path: The directory path to get the file list from.
@type path: str
@param filesOnly: List files only (excludes directories).
@type filesOnly: bool
@param filterStr: Filter string for file name match.
@type filterStr: str
@param sort: Alpha sort list.
@type sort: bool
'''
# Get File List
fileList = glTools.utils.osUtils.getFileList(path,filesOnly=filesOnly)
# Filter (regex)
if filterStr:
reFilter = re.compile(filterStr)
fileList = filter(reFilter.search, fileList)
# Sort
if sort: fileList.sort()
# Add File List to textScrollList
addToTSL(TSL,fileList)
# =============
# - Check Box -
# =============
def checkBoxToggleLayout(CBG,layout,invert=False):
'''
Toggle the enabled state of a UI layout based on a checkBoxGrp
@param CBG: CheckBoxGrp used to toggle layout
@type CBG: str
@param layout: Layout to toggle
@type layout: str
@param invert: Invert the checkBox value
@type invert: bool
'''
# Check CheckBoxGrp
if not mc.checkBoxGrp(CBG,q=True,ex=True):
raise UIError('CheckBoxGrp "'+CBG+'" does not exist!!')
# Check layout
if not mc.layout(layout,q=True,ex=True):
raise UIError('Layout "'+layout+'" does not exist!!')
# Get checkBoxGrp state
state = mc.checkBoxGrp(CBG,q=True,v1=True)
if invert: state = not state
# Toggle Layout
mc.layout(layout,e=True,en=state)
def checkBoxToggleControl(CBG,control,invert=False):
'''
Toggle the enabled state of a UI layout based on a checkBoxGrp
@param CBG: CheckBoxGrp used to toggle layout
@type CBG: str
@param layout: Layout to toggle
@type layout: str
@param invert: Invert the checkBox value
@type invert: bool
'''
# Check CheckBoxGrp
if not mc.checkBoxGrp(CBG,q=True,ex=True):
raise UIError('CheckBoxGrp "'+CBG+'" does not exist!!')
# Check control
if not mc.control(control,q=True,ex=True):
raise UIError('Control "'+control+'" does not exist!!')
# Get checkBoxGrp state
state = mc.checkBoxGrp(CBG,q=True,v1=True)
if invert: state = not state
# Toggle Layout
mc.control(control,e=True,en=state)
# ====================
# - Option Menu List -
# ====================
def setOptionMenuList(OMG,itemList,add=False):
'''
Set the list of items for the specified optionMenuGrp control
@param OMG: OptionMenuGrp to set the item list for
@type OMG: str
@param itemList: List of items to add to optionMenuGrp
@type itemList: list
@param add: Add to existing menu items
@type add: bool
'''
# Check optionMenuGrp
if not mc.optionMenuGrp(OMG,q=True,ex=True):
raise UIError('OptionMenu "'+OMG+'" does not exist!')
# Get existing items
exItemList = mc.optionMenuGrp(OMG,q=True,ill=True)
# Add items
for item in itemList:
mc.setParent(OMG)
mc.menuItem(l=item)
# Remove previous items
if exItemList:
for item in exItemList:
mc.deleteUI(item)
# =====================
# - Float Field Group -
# =====================
def setPointValue(FFG,point=''):
'''
Set the value of a floatFieldGrp with the position value of a specifeid point
@param FFG: FloatFieldgrp to set values for
@type FFG: str
@param point: Point to get position from
@type point: str
'''
# Check point
if point and not mc.objExists(point):
raise Exception('Point object "'+point+'" does not exist!')
# Get object selection
sel = mc.ls(sl=1)
if not point and not sel:
raise Exception('No point specified for floatFieldGrp values!')
# Get point
if point: pos = glTools.utils.base.getPosition(point)
else: pos = glTools.utils.base.getPosition(sel[0])
# Set float field values
mc.floatFieldGrp(FFG,e=True,v1=pos[0],v2=pos[1],v3=pos[2])
# =============
# - Custom UI -
# =============
def displayListWindow(itemList,title,enableSelect=False):
'''
Create a basic list selection window.
@param itemList: Item list to display in window
@type itemList: list
@param title: Window title string
@type title: str
'''
# Check itemList
if not itemList:
mc.confirmDialog(t=title,m='No items to display!',ma='center',b='Close')
return
# Window
window = 'displayListWindowUI'
if mc.window(window,q=True,ex=True): mc.deleteUI(window)
window = mc.window(window,t=title,s=True)
# Layout
FL = mc.formLayout(numberOfDivisions=100)
# ===============
# - UI Elements -
# ===============
# TextScrollList
TSL = mc.textScrollList('displayListWindowTSL',allowMultiSelection=True)
for item in itemList: mc.textScrollList(TSL,e=True,a=item)
if enableSelect: mc.textScrollList(TSL,e=True,sc='glTools.ui.utils.selectFromTSL("'+TSL+'")')
# Close Button
closeB = mc.button('displayListWindowB',l='Close',c='mc.deleteUI("'+window+'")')
# Form Layout
mc.formLayout(FL,e=True,af=[(TSL,'top',5),(TSL,'left',5),(TSL,'right',5)])
mc.formLayout(FL,e=True,af=[(closeB,'bottom',5),(closeB,'left',5),(closeB,'right',5)])
mc.formLayout(FL,e=True,ac=[(TSL,'bottom',5,closeB)])
# Display Window
mc.showWindow(window)
def displayMessageWindow(msg,title):
'''
Create a basic message/report window.
@param msg: Message string to display in window.
@type msg: str
@param title: Window title string
@type title: str
'''
# Check message
if not msg: return
# Window
window = 'messageWindowUI'
if mc.window(window,q=True,ex=True): mc.deleteUI(window)
window = mc.window(window,t=title,s=True)
# Layout
FL = mc.formLayout(numberOfDivisions=100)
# UI Elements
reportSF = mc.scrollField('messageWindowSF',editable=False,wordWrap=True,text=msg)
closeB = mc.button('messageWindowB',l='Close',c='mc.deleteUI("'+window+'")')
# Form Layout
mc.formLayout(FL,e=True,af=[(reportSF,'top',5),(reportSF,'left',5),(reportSF,'right',5)])
mc.formLayout(FL,e=True,af=[(closeB,'bottom',5),(closeB,'left',5),(closeB,'right',5)])
mc.formLayout(FL,e=True,ac=[(reportSF,'bottom',5,closeB)])
# Display Window
mc.showWindow(window)
|
{
"pile_set_name": "Github"
}
|
<?php
namespace Cdn\Request\V20180510;
/**
* @deprecated Please use https://github.com/aliyun/openapi-sdk-php
*
* Request of SetHttpErrorPageConfig
*
* @method string getPageUrl()
* @method string getErrorCode()
* @method string getDomainName()
* @method string getOwnerId()
* @method string getConfigId()
*/
class SetHttpErrorPageConfigRequest extends \RpcAcsRequest
{
/**
* Class constructor.
*/
public function __construct()
{
parent::__construct(
'Cdn',
'2018-05-10',
'SetHttpErrorPageConfig'
);
}
/**
* @param string $pageUrl
*
* @return $this
*/
public function setPageUrl($pageUrl)
{
$this->requestParameters['PageUrl'] = $pageUrl;
$this->queryParameters['PageUrl'] = $pageUrl;
return $this;
}
/**
* @param string $errorCode
*
* @return $this
*/
public function setErrorCode($errorCode)
{
$this->requestParameters['ErrorCode'] = $errorCode;
$this->queryParameters['ErrorCode'] = $errorCode;
return $this;
}
/**
* @param string $domainName
*
* @return $this
*/
public function setDomainName($domainName)
{
$this->requestParameters['DomainName'] = $domainName;
$this->queryParameters['DomainName'] = $domainName;
return $this;
}
/**
* @param string $ownerId
*
* @return $this
*/
public function setOwnerId($ownerId)
{
$this->requestParameters['OwnerId'] = $ownerId;
$this->queryParameters['OwnerId'] = $ownerId;
return $this;
}
/**
* @param string $configId
*
* @return $this
*/
public function setConfigId($configId)
{
$this->requestParameters['ConfigId'] = $configId;
$this->queryParameters['ConfigId'] = $configId;
return $this;
}
}
|
{
"pile_set_name": "Github"
}
|
Invalid group use syntax
-----
<?php
// Missing semicolon
use Foo\{Bar}
use Bar\{Foo};
-----
!!php7
Syntax error, unexpected T_USE, expecting ';' from 4:1 to 4:3
array(
0: Stmt_GroupUse(
type: TYPE_UNKNOWN (0)
prefix: Name(
parts: array(
0: Foo
)
)
uses: array(
0: Stmt_UseUse(
type: TYPE_NORMAL (1)
name: Name(
parts: array(
0: Bar
)
)
alias: null
)
)
comments: array(
0: // Missing semicolon
)
)
1: Stmt_GroupUse(
type: TYPE_UNKNOWN (0)
prefix: Name(
parts: array(
0: Bar
)
)
uses: array(
0: Stmt_UseUse(
type: TYPE_NORMAL (1)
name: Name(
parts: array(
0: Foo
)
)
alias: null
)
)
)
)
-----
<?php
// Missing NS separator
use Foo {Bar, Baz};
-----
!!php7
Syntax error, unexpected '{', expecting ';' from 3:9 to 3:9
array(
0: Stmt_Use(
type: TYPE_NORMAL (1)
uses: array(
0: Stmt_UseUse(
type: TYPE_UNKNOWN (0)
name: Name(
parts: array(
0: Foo
)
)
alias: null
)
)
comments: array(
0: // Missing NS separator
)
)
1: Stmt_Expression(
expr: Expr_ConstFetch(
name: Name(
parts: array(
0: Bar
)
)
)
)
2: Stmt_Expression(
expr: Expr_ConstFetch(
name: Name(
parts: array(
0: Baz
)
)
)
)
)
-----
<?php
// Extra NS separator
use Foo\{\Bar};
-----
Syntax error, unexpected T_NS_SEPARATOR, expecting T_STRING or T_FUNCTION or T_CONST from 3:10 to 3:10
array(
0: Stmt_Expression(
expr: Expr_ConstFetch(
name: Name_FullyQualified(
parts: array(
0: Bar
)
)
)
)
)
|
{
"pile_set_name": "Github"
}
|
//
// PFPurchaseTableViewCell.h
// Parse
//
// Created by Qian Wang on 5/21/12.
// Copyright (c) 2012 Parse Inc. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "PFTableViewCell.h"
/*!
An enum that represents states of the PFPurchaseTableViewCell.
@see PFPurchaseTableViewCell
*/
typedef NS_ENUM(uint8_t, PFPurchaseTableViewCellState) {
/*! Normal state of the cell. */
PFPurchaseTableViewCellStateNormal = 0,
/*! Downloading state of the cell. */
PFPurchaseTableViewCellStateDownloading,
/*! State of the cell, when the product was downloaded. */
PFPurchaseTableViewCellStateDownloaded
};
/*!
PFPurchaseTableViewCell is a subclass PFTableViewCell that is used to show
products in a PFProductTableViewController.
@see PFProductTableViewController
*/
@interface PFPurchaseTableViewCell : PFTableViewCell
/*! State of the cell */
@property (nonatomic, assign) PFPurchaseTableViewCellState state;
/*! Label where price of the product is displayed. */
@property (nonatomic, strong, readonly) UILabel *priceLabel;
/*! Progress view that is shown, when the product is downloading. */
@property (nonatomic, strong, readonly) UIProgressView *progressView;
@end
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DynamicsCompressorKernel_h
#define DynamicsCompressorKernel_h
#include "AudioArray.h"
#include <memory>
#include <wtf/Vector.h>
namespace WebCore {
class DynamicsCompressorKernel {
public:
DynamicsCompressorKernel(float sampleRate, unsigned numberOfChannels);
void setNumberOfChannels(unsigned);
// Performs stereo-linked compression.
void process(float* sourceChannels[],
float* destinationChannels[],
unsigned numberOfChannels,
unsigned framesToProcess,
float dbThreshold,
float dbKnee,
float ratio,
float attackTime,
float releaseTime,
float preDelayTime,
float dbPostGain,
float effectBlend,
float releaseZone1,
float releaseZone2,
float releaseZone3,
float releaseZone4
);
void reset();
unsigned latencyFrames() const { return m_lastPreDelayFrames; }
float sampleRate() const { return m_sampleRate; }
float meteringGain() const { return m_meteringGain; }
protected:
float m_sampleRate;
float m_detectorAverage;
float m_compressorGain;
// Metering
float m_meteringReleaseK;
float m_meteringGain;
// Lookahead section.
enum { MaxPreDelayFrames = 1024 };
enum { MaxPreDelayFramesMask = MaxPreDelayFrames - 1 };
enum { DefaultPreDelayFrames = 256 }; // setPreDelayTime() will override this initial value
unsigned m_lastPreDelayFrames;
void setPreDelayTime(float);
Vector<std::unique_ptr<AudioFloatArray>> m_preDelayBuffers;
int m_preDelayReadIndex;
int m_preDelayWriteIndex;
float m_maxAttackCompressionDiffDb;
// Static compression curve.
float kneeCurve(float x, float k);
float saturate(float x, float k);
float slopeAt(float x, float k);
float kAtSlope(float desiredSlope);
float updateStaticCurveParameters(float dbThreshold, float dbKnee, float ratio);
// Amount of input change in dB required for 1 dB of output change.
// This applies to the portion of the curve above m_kneeThresholdDb (see below).
float m_ratio;
float m_slope; // Inverse ratio.
// The input to output change below the threshold is linear 1:1.
float m_linearThreshold;
float m_dbThreshold;
// m_dbKnee is the number of dB above the threshold before we enter the "ratio" portion of the curve.
// m_kneeThresholdDb = m_dbThreshold + m_dbKnee
// The portion between m_dbThreshold and m_kneeThresholdDb is the "soft knee" portion of the curve
// which transitions smoothly from the linear portion to the ratio portion.
float m_dbKnee;
float m_kneeThreshold;
float m_kneeThresholdDb;
float m_ykneeThresholdDb;
// Internal parameter for the knee portion of the curve.
float m_K;
};
} // namespace WebCore
#endif // DynamicsCompressorKernel_h
|
{
"pile_set_name": "Github"
}
|
statement ok
CREATE TABLE xyz (
x INT,
y INT,
z INT,
pk1 INT,
pk2 INT,
PRIMARY KEY (pk1, pk2)
)
statement ok
INSERT INTO xyz VALUES
(1, 1, NULL, 1, 1),
(1, 1, 2, 2, 2),
(1, 1, 2, 3, 3),
(1, 2, 1, 4, 4),
(2, 2, 3, 5, 5),
(4, 5, 6, 6, 6),
(4, 1, 6, 7, 7)
statement ok
CREATE TABLE abc (
a STRING,
b STRING,
c STRING,
PRIMARY KEY (a, b, c)
)
statement ok
INSERT INTO abc VALUES
('1', '1', '1'),
('1', '1', '2'),
('1', '2', '2')
##################
# Simple queries #
##################
# 3/3 columns
query III rowsort
SELECT DISTINCT ON (x, y, z) x, y, z FROM xyz
----
1 1 NULL
1 1 2
1 2 1
2 2 3
4 5 6
4 1 6
query I rowsort
SELECT DISTINCT ON (y, x, z) x FROM xyz
----
1
1
1
2
4
4
query I rowsort
SELECT DISTINCT ON (z, y, x) z FROM xyz
----
NULL
2
1
3
6
6
query TTT rowsort
SELECT DISTINCT ON (b, c, a) a, c, b FROM abc
----
1 1 1
1 2 1
1 2 2
query T rowsort
SELECT DISTINCT ON (b, c, a) a FROM abc
----
1
1
1
# We need to rowsort this since the ORDER BY isn't on the entire SELECT columns.
query T rowsort
SELECT DISTINCT ON (c, a, b) b FROM abc ORDER BY b
----
1
1
2
# 2/3 columns
query II rowsort
SELECT DISTINCT ON (x, y) y, x FROM xyz
----
1 1
2 1
2 2
5 4
1 4
query I rowsort
SELECT DISTINCT ON (y, x) x FROM xyz
----
1
1
2
4
4
query I rowsort
SELECT DISTINCT ON (x, y) y FROM xyz
----
1
2
2
5
1
query TT
SELECT DISTINCT ON (a, c) a, b FROM abc ORDER BY a, c, b
----
1 1
1 1
# We wrap this with an ORDER BY otherwise this would be non-deterministic.
query TTT
SELECT DISTINCT ON (c, a) b, c, a FROM abc ORDER BY c, a, b DESC
----
1 1 1
2 2 1
# 1/3 columns
query I rowsort
SELECT DISTINCT ON (y) y FROM xyz
----
1
2
5
query T rowsort
SELECT DISTINCT ON (c) a FROM abc
----
1
1
query T rowsort
SELECT DISTINCT ON (b) b FROM abc
----
1
2
# We wrap this with an ORDER BY otherwise this would be non-deterministic.
query TTT
SELECT DISTINCT ON (a) a, b, c FROM abc ORDER BY a, b, c
----
1 1 1
query TT
SELECT DISTINCT ON (a) a, c FROM abc ORDER BY a, c DESC, b
----
1 2
#################
# With ORDER BY #
#################
statement error SELECT DISTINCT ON expressions must match initial ORDER BY expressions
SELECT DISTINCT ON (x) x, y, z FROM xyz ORDER BY y
statement error SELECT DISTINCT ON expressions must match initial ORDER BY expressions
SELECT DISTINCT ON (y) x, y, z FROM xyz ORDER BY x, y
statement error SELECT DISTINCT ON expressions must match initial ORDER BY expressions
SELECT DISTINCT ON (y, z) x, y, z FROM xyz ORDER BY x
query I
SELECT DISTINCT ON (x) x FROM xyz ORDER BY x DESC
----
4
2
1
# We add a filter to eliminate one of the rows that may be flakily returned
# depending on parallel execution of DISTINCT ON.
query III
SELECT DISTINCT ON (x, z) y, z, x FROM xyz WHERE (x,y,z) != (4, 1, 6) ORDER BY z
----
1 NULL 1
2 1 1
1 2 1
2 3 2
5 6 4
query III
SELECT DISTINCT ON (x) y, z, x FROM xyz ORDER BY x ASC, z DESC, y DESC
----
1 2 1
2 3 2
5 6 4
# Regression test for #35437: Discard extra ordering columns after performing
# DISTINCT operation.
query T
SELECT (SELECT DISTINCT ON (a) a FROM abc ORDER BY a, b||'foo') || 'bar';
----
1bar
#####################
# With aggregations #
#####################
statement error column "y" must appear in the GROUP BY clause or be used in an aggregate function
SELECT DISTINCT ON(max(x)) y FROM xyz
statement error column "z" must appear in the GROUP BY clause or be used in an aggregate function
SELECT DISTINCT ON(max(x), z) min(y) FROM xyz
query I
SELECT DISTINCT ON (max(x)) min(y) FROM xyz
----
1
query I
SELECT DISTINCT ON (min(x)) max(y) FROM xyz
----
5
query T
SELECT DISTINCT ON(min(a), max(b), min(c)) max(c) FROM abc
----
2
#################
# With GROUP BY #
#################
statement error column "x" must appear in the GROUP BY clause or be used in an aggregate function
SELECT DISTINCT ON (x) min(x) FROM xyz GROUP BY y
query I rowsort
SELECT DISTINCT ON(y) min(x) FROM xyz GROUP BY y
----
1
1
4
query I
SELECT DISTINCT ON(min(x)) min(x) FROM xyz GROUP BY y HAVING min(x) = 1
----
1
#########################
# With window functions #
#########################
query I rowsort
SELECT DISTINCT ON(row_number() OVER(ORDER BY (pk1, pk2))) y FROM xyz
----
1
1
1
2
2
5
1
query I
SELECT DISTINCT ON(row_number() OVER(ORDER BY (pk1, pk2))) y FROM xyz ORDER BY row_number() OVER(ORDER BY (pk1, pk2)) DESC
----
1
5
2
2
1
1
1
###########################
# With ordinal references #
###########################
statement error DISTINCT ON position 2 is not in select list
SELECT DISTINCT ON (2) x FROM xyz
query I rowsort
SELECT DISTINCT ON (1) x FROM xyz
----
1
2
4
query III rowsort
SELECT DISTINCT ON (1,2,3) x, y, z FROM xyz
----
1 1 NULL
1 1 2
1 2 1
2 2 3
4 5 6
4 1 6
#########################
# With alias references #
#########################
# This should prioritize alias (use 'x' as the key).
# This would be non-deterministic if we don't select y (actually x) from the
# subquery.
query I rowsort
SELECT y FROM (SELECT DISTINCT ON(y) x AS y, y AS x FROM xyz)
----
1
2
4
# Ignores the alias.
query I rowsort
SELECT DISTINCT ON(x) x AS y FROM xyz
----
1
2
4
##################################
# With nested parentheses/tuples #
##################################
query II rowsort
SELECT DISTINCT ON(((x)), (x, y)) x, y FROM xyz
----
1 1
1 2
2 2
4 5
4 1
################################
# Hybrid PK and non-PK queries #
################################
# We need to rowsort this since the ORDER BY isn't on the entire SELECT columns.
query III rowsort
SELECT DISTINCT ON(pk1, pk2, x, y) x, y, z FROM xyz ORDER BY x, y
----
1 1 NULL
1 1 2
1 1 2
1 2 1
2 2 3
4 1 6
4 5 6
# Ordering only propagates up until distinctNode.
# pk1 ordering does not propagate at all since it's not explicitly needed.
# We add a filter since there could be multiple valid pk1s otherwise for distinct
# rows.
query I rowsort
SELECT DISTINCT ON (x, y, z) pk1 FROM (SELECT * FROM xyz WHERE x >= 2) ORDER BY x
----
5
6
7
# Regression tests for #34112: distinct on constant column.
query II
SELECT DISTINCT ON (x) x, y FROM xyz WHERE x = 1 ORDER BY x, y
----
1 1
query I
SELECT count(*) FROM (SELECT DISTINCT ON (x) x, y FROM xyz WHERE x = 1 ORDER BY x, y)
----
1
|
{
"pile_set_name": "Github"
}
|
snippet Ada Gitignore Template
### Ada ###
# Object file
*.o
# Ada Library Information
*.ali
${0}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build amd64,openbsd
package unix
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: sec, Nsec: nsec}
}
func setTimeval(sec, usec int64) Timeval {
return Timeval{Sec: sec, Usec: usec}
}
func SetKevent(k *Kevent_t, fd, mode, flags int) {
k.Ident = uint64(fd)
k.Filter = int16(mode)
k.Flags = uint16(flags)
}
func (iov *Iovec) SetLen(length int) {
iov.Len = uint64(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint32(length)
}
func (msghdr *Msghdr) SetIovlen(length int) {
msghdr.Iovlen = uint32(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint32(length)
}
// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions
// of openbsd/amd64 the syscall is called sysctl instead of __sysctl.
const SYS___SYSCTL = SYS_SYSCTL
|
{
"pile_set_name": "Github"
}
|
julia 0.4
Compat 0.9.4
|
{
"pile_set_name": "Github"
}
|
.. _IP:LocalLink_PerformanceCounter:
PoC.net.FramePerformanceCounter
###############################
.. only:: html
.. |gh-src| image:: /_static/logos/GitHub-Mark-32px.png
:scale: 40
:target: https://github.com/VLSI-EDA/PoC/blob/master/src/net/net_FramePerformanceCounter.vhdl
:alt: Source Code on GitHub
.. |gh-tb| image:: /_static/logos/GitHub-Mark-32px.png
:scale: 40
:target: https://github.com/VLSI-EDA/PoC/blob/master/tb/net/net_FramePerformanceCounter_tb.vhdl
:alt: Source Code on GitHub
.. sidebar:: GitHub Links
* |gh-src| :pocsrc:`Sourcecode <net/net_FramePerformanceCounter.vhdl>`
* |gh-tb| :poctb:`Testbench <net/net_FramePerformanceCounter_tb.vhdl>`
.. rubric:: Entity Declaration:
.. literalinclude:: ../../../src/net/net_FramePerformanceCounter.vhdl
:language: vhdl
:tab-width: 2
:linenos:
:lines: 11-35
.. only:: latex
Source file: :pocsrc:`net/net_FramePerformanceCounter.vhdl <net/net_FramePerformanceCounter.vhdl>`
|
{
"pile_set_name": "Github"
}
|
/* @ngInject */
function confirmModal(pmModal, gettextCatalog, translator) {
const I18N = translator(() => ({
confirm: gettextCatalog.getString('Confirm', null, 'Default text for the confirm button in the confirm modal'),
cancel: gettextCatalog.getString('Cancel', null, 'Default text for the cancel button in the confirm modal')
}));
const getClassName = ({ isDanger = false, isWarning = false } = {}) => {
const danger = isDanger && 'alert-danger';
const warning = isWarning && 'alert-warning';
return ['alert', danger, warning].filter(Boolean).join(' ');
};
return pmModal({
controllerAs: 'ctrl',
templateUrl: require('../../../templates/modals/confirm.tpl.html'),
/* @ngInject */
controller: function(params, hotkeys) {
hotkeys.unbind(['enter']);
this.title = params.title;
this.icon = params.icon;
this.learnMore = params.learnMore;
this.message = params.message;
this.confirmText = params.confirmText || I18N.confirm;
this.hideClose = params.hideClose;
this.classNameMessage = !params.customAlert ? getClassName(params) : '';
this.class = params.class;
this.confirmClass = params.confirmClass || 'primary';
this.cancelText = params.cancelText || I18N.cancel;
this.confirm = () => (hotkeys.bind(['enter']), params.confirm());
this.cancel = (type = 'cross') => (hotkeys.bind(['enter']), params.cancel(type));
// The button is not directly available
setTimeout(() => angular.element('#confirmModalBtn').focus(), 100);
}
});
}
export default confirmModal;
|
{
"pile_set_name": "Github"
}
|
{
"paths": {
"customizerJs": [
"../assets/js/vendor/autoprefixer.js",
"../assets/js/vendor/less.min.js",
"../assets/js/vendor/jszip.min.js",
"../assets/js/vendor/uglify.min.js",
"../assets/js/vendor/Blob.js",
"../assets/js/vendor/FileSaver.js",
"../assets/js/raw-files.min.js",
"../assets/js/src/customizer.js"
],
"docsJs": [
"../assets/js/vendor/holder.js",
"../assets/js/vendor/ZeroClipboard.min.js",
"../assets/js/vendor/anchor.js",
"../assets/js/src/application.js"
]
},
"config": {
"autoprefixerBrowsers": [
"Android 2.3",
"Android >= 4",
"Chrome >= 20",
"Firefox >= 24",
"Explorer >= 8",
"iOS >= 6",
"Opera >= 12",
"Safari >= 6"
],
"jqueryCheck": [
"if (typeof jQuery === 'undefined') {",
" throw new Error('Bootstrap\\'s JavaScript requires jQuery')",
"}\n"
],
"jqueryVersionCheck": [
"+function ($) {",
" 'use strict';",
" var version = $.fn.jquery.split(' ')[0].split('.')",
" if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) {",
" throw new Error('Bootstrap\\'s JavaScript requires jQuery version 1.9.1 or higher')",
" }",
"}(jQuery);\n\n"
]
}
}
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* AMetal
* ----------------------------
* innovating embedded platform
*
* Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd.
* All rights reserved.
*
* Contact information:
* web site: http://www.zlg.cn/
*******************************************************************************/
/**
* \file
* \brief tim0 定时器 CAP 例程,通过标准接口实现
*
* - 操作步骤:
* 1. 使用杜邦线,将 PIOB_3 与 PIOA_0 连接。
*
* - 实验现象:
* 1. TIM3 通过 PIOB_3 引脚输出 2KHz 的 PWM;
* 2. TIM0 捕获输入通道 0 使用 PIOA_0 引脚捕获;
* 3. 串口打印出利用捕获功能得到的 PWM 信号的周期和频率。
*
* \note
* 1. 如需观察串口打印的调试信息,需要将 PIOA_10 引脚连接 PC 串口的 TXD,
* PIOA_9 引脚连接 PC 串口的 RXD。
*
* \par 源代码
* \snippet demo_hc32f07x_std_tim0_cap.c src_hc32f07x_std_tim0_cap
*
* \internal
* \par Modification history
* - 1.00 19-09-20 zp, first implementation
* \endinternal
*/
/**
* \addtogroup demo_if_hc32f07x_std_tim0_cap
* \copydoc demo_hc32f07x_std_tim0_cap.c
*/
/** [src_hc32f07x_std_tim0_cap] */
#include "ametal.h"
#include "am_vdebug.h"
#include "am_hc32f07x_inst_init.h"
#include "demo_std_entries.h"
#include "demo_amf07x_core_entries.h"
/**
* \brief 例程入口
*/
void demo_hc32f07x_core_std_tim0_cap_entry (void)
{
am_pwm_handle_t tim3_pwm_handle = am_hc32_tim3_pwm_inst_init();
am_cap_handle_t tim0_cap_handle = am_hc32_tim0_cap_inst_init();
AM_DBG_INFO("demo amf07x_core std tim0 cap!\r\n");
/* TIM3 输出频率为 2KHz 的 PWM */
am_pwm_config(tim3_pwm_handle, 0, 500000 / 2, 500000);
am_pwm_enable(tim3_pwm_handle, 0);
demo_std_timer_cap_entry(tim0_cap_handle, 0);
}
/** [src_hc32f07x_std_tim0_cap] */
/* end of file */
|
{
"pile_set_name": "Github"
}
|
case SSD1963_800ALT:
LCD_Write_COM(0xE2); //PLL multiplier, set PLL clock to 120M
LCD_Write_DATA(0x23); //N=0x36 for 6.5M, 0x23 for 10M crystal
LCD_Write_DATA(0x02);
LCD_Write_DATA(0x04);
LCD_Write_COM(0xE0); // PLL enable
LCD_Write_DATA(0x01);
delay(10);
LCD_Write_COM(0xE0);
LCD_Write_DATA(0x03);
delay(10);
LCD_Write_COM(0x01); // software reset
delay(100);
LCD_Write_COM(0xE6); //PLL setting for PCLK, depends on resolution
LCD_Write_DATA(0x04);
LCD_Write_DATA(0x93);
LCD_Write_DATA(0xE0);
LCD_Write_COM(0xB0); //LCD SPECIFICATION
LCD_Write_DATA(0x00); // 0x24
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x03); //Set HDP 799
LCD_Write_DATA(0x1F);
LCD_Write_DATA(0x01); //Set VDP 479
LCD_Write_DATA(0xDF);
LCD_Write_DATA(0x00);
LCD_Write_COM(0xB4); //HSYNC
LCD_Write_DATA(0x03); //Set HT 928
LCD_Write_DATA(0xA0);
LCD_Write_DATA(0x00); //Set HPS 46
LCD_Write_DATA(0x2E);
LCD_Write_DATA(0x30); //Set HPW 48
LCD_Write_DATA(0x00); //Set LPS 15
LCD_Write_DATA(0x0F);
LCD_Write_DATA(0x00);
LCD_Write_COM(0xB6); //VSYNC
LCD_Write_DATA(0x02); //Set VT 525
LCD_Write_DATA(0x0D);
LCD_Write_DATA(0x00); //Set VPS 16
LCD_Write_DATA(0x10);
LCD_Write_DATA(0x10); //Set VPW 16
LCD_Write_DATA(0x00); //Set FPS 8
LCD_Write_DATA(0x08);
LCD_Write_COM(0xBA);
LCD_Write_DATA(0x05); //GPIO[3:0] out 1
LCD_Write_COM(0xB8);
LCD_Write_DATA(0x07); //GPIO3=input, GPIO[2:0]=output
LCD_Write_DATA(0x01); //GPIO0 normal
LCD_Write_COM(0x36); //rotation
LCD_Write_DATA(0x22); // -- Set to 0x21 to rotate 180 degrees
LCD_Write_COM(0xF0); //pixel data interface
LCD_Write_DATA(0x03);
delay(10);
setXY(0, 0, 799, 479);
LCD_Write_COM(0x29); //display on
LCD_Write_COM(0xBE); //set PWM for B/L
LCD_Write_DATA(0x06);
LCD_Write_DATA(0xF0);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0xF0);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_COM(0xD0);
LCD_Write_DATA(0x0D);
LCD_Write_COM(0x2C);
break;
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html><html class="theme-next muse use-motion" lang="zh-CN"><head><meta name="generator" content="Hexo 3.8.0"><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><script src="//cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script><link href="/lib/pace/pace-theme-corner-indicator.min.css?v=1.0.2" rel="stylesheet"><meta name="google-site-verification" content="sDeZZSmv4NPbU3sXi1IL5l8PiZt1wVqR5EKUsxOjruY"><link href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.2.5/dist/jquery.fancybox.min.css" rel="stylesheet" type="text/css"><link href="https://fonts.googleapis.cnpmjs.org/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic|Noto Serif SC:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css"><link href="//cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"><link href="/css/main.css?v=6.6.0" rel="stylesheet" type="text/css"><link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.6.0"><link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.6.0"><link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.6.0"><link rel="mask-icon" href="/images/logo.svg?v=6.6.0" color="#222"><script id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Muse",version:"6.6.0",sidebar:{position:"left",display:"hide",offset:12,b2t:!1,scrollpercent:!0,onmobile:!0},fancybox:!0,fastclick:!1,lazyload:!1,tabs:!0,motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}},algolia:{applicationID:"",apiKey:"",indexName:"",hits:{per_page:10},labels:{input_placeholder:"Search for Posts",hits_empty:"We didn't find any results for the search: ${query}",hits_stats:"${hits} results found in ${time} ms"}}}</script><meta name="description" content="【微信首发】macOS Catalina 10.15.7 19H2 正式版 Clover 5122/OC/PE三分区支持Intel及AMD双平台原版镜像9月24日,苹果向macOS推送10.15.7系统补充更新,macOS Catalina 10.15.7 为您的 Mac 提供了重要的安全性更新和错误修复。解决了 macOS 不会自动接入 Wi-Fi 网络的问题修复了文件可能无法通过 iClou"><meta name="keywords" content="镜像,下载,Catalina,dmg,10.15.7,19H2,三EFI分区"><meta property="og:type" content="article"><meta property="og:title" content="【微信首发】macOS Catalina 10.15.7 19H2 正式版 Clover 5122/OC/PE三分区支持Intel及AMD双平台原版镜像"><meta property="og:url" content="https://blog.daliansky.net/WeChat-First-macOS-Catalina-10.15.7-19H2-official-version-Clover-5122-OC-WEPE-supports-both-INTEL-and-AMD-original-images.html"><meta property="og:site_name" content="黑果小兵的部落阁"><meta property="og:description" content="【微信首发】macOS Catalina 10.15.7 19H2 正式版 Clover 5122/OC/PE三分区支持Intel及AMD双平台原版镜像9月24日,苹果向macOS推送10.15.7系统补充更新,macOS Catalina 10.15.7 为您的 Mac 提供了重要的安全性更新和错误修复。解决了 macOS 不会自动接入 Wi-Fi 网络的问题修复了文件可能无法通过 iClou"><meta property="og:locale" content="zh-CN"><meta property="og:image" content="http://7.daliansky.net/10.15.7/19H2_Air13.png"><meta property="og:updated_time" content="2020-09-28T00:54:57.075Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="【微信首发】macOS Catalina 10.15.7 19H2 正式版 Clover 5122/OC/PE三分区支持Intel及AMD双平台原版镜像"><meta name="twitter:description" content="【微信首发】macOS Catalina 10.15.7 19H2 正式版 Clover 5122/OC/PE三分区支持Intel及AMD双平台原版镜像9月24日,苹果向macOS推送10.15.7系统补充更新,macOS Catalina 10.15.7 为您的 Mac 提供了重要的安全性更新和错误修复。解决了 macOS 不会自动接入 Wi-Fi 网络的问题修复了文件可能无法通过 iClou"><meta name="twitter:image" content="http://7.daliansky.net/10.15.7/19H2_Air13.png"><link rel="alternate" href="/atom.xml" title="黑果小兵的部落阁" type="application/atom+xml"><link rel="canonical" href="https://blog.daliansky.net/WeChat-First-macOS-Catalina-10.15.7-19H2-official-version-Clover-5122-OC-WEPE-supports-both-INTEL-and-AMD-original-images.html"><script id="page.configurations">CONFIG.page={sidebar:""}</script><title>【微信首发】macOS Catalina 10.15.7 19H2 正式版 Clover 5122/OC/PE三分区支持Intel及AMD双平台原版镜像 | 黑果小兵的部落阁</title><script async src="https://www.googletagmanager.com/gtag/js?id=UA-18130737-1"></script><script>function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","UA-18130737-1")</script><noscript><style>.sidebar-inner,.use-motion .brand,.use-motion .collection-title,.use-motion .comments,.use-motion .menu-item,.use-motion .motion-element,.use-motion .pagination,.use-motion .post-block,.use-motion .post-body,.use-motion .post-header{opacity:initial}.use-motion .logo,.use-motion .site-subtitle,.use-motion .site-title{opacity:initial;top:initial}.use-motion .logo-line-before i{left:initial}.use-motion .logo-line-after i{right:initial}</style></noscript></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">黑果小兵的部落阁</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle">Hackintosh安装镜像、教程及经验分享</p></div><div class="site-nav-toggle"><button aria-label="切换导航栏"><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br>首页</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br>归档</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br>分类</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br>标签</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i><br>关于</a></li><li class="menu-item menu-item-search"><a href="javascript:;" class="popup-trigger"><i class="menu-item-icon fa fa-search fa-fw"></i><br>搜索</a></li></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div></header><a href="https://github.com/daliansky" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#222;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><div class="reading-progress-bar"></div><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="https://blog.daliansky.net/WeChat-First-macOS-Catalina-10.15.7-19H2-official-version-Clover-5122-OC-WEPE-supports-both-INTEL-and-AMD-original-images.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="黑果小兵"><meta itemprop="description" content="黑果小兵,daliansky,blog.daliansky.net,macOS,Hackintosh,黑苹果,linux"><meta itemprop="image" content="/images/avatar.png"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="黑果小兵的部落阁"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">【微信首发】macOS Catalina 10.15.7 19H2 正式版 Clover 5122/OC/PE三分区支持Intel及AMD双平台原版镜像</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><time title="创建时间:2020-09-24 10:15:07" itemprop="dateCreated datePublished" datetime="2020-09-24T10:15:07+08:00">2020-09-24</time> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i> </span><time title="修改时间:2020-09-28 08:54:57" itemprop="dateModified" datetime="2020-09-28T08:54:57+08:00">2020-09-28</time> </span><span class="post-category"><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-folder-o"></i> </span><span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/下载/" itemprop="url" rel="index"><span itemprop="name">下载</span></a></span> , <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/下载/镜像/" itemprop="url" rel="index"><span itemprop="name">镜像</span></a></span> </span><span class="post-meta-divider">|</span> <span class="post-meta-item-icon" title="阅读次数"><i class="fa fa-eye"></i> <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span><div class="post-symbolscount"><span class="post-meta-item-icon"><i class="fa fa-file-word-o"></i> </span><span title="本文字数">4.6k</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-clock-o"></i> </span><span title="阅读时长">8 分钟</span></div></div></header><div class="post-body" itemprop="articleBody"><div class="post-gallery" itemscope itemtype="http://schema.org/ImageGallery"><div class="post-gallery-row"><a class="post-gallery-img fancybox" href="http://7.daliansky.net/10.15.7/19H2_Air13.png" rel="gallery_ckfnjzw79006u1pakj1uibqls" itemscope itemtype="http://schema.org/ImageObject" itemprop="url"><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/19H2_Air13.png" itemprop="contentUrl"></a></div></div><h1 id="微信首发macos-catalina-10157-19h2-正式版-clover-5122ocpe三分区支持intel及amd双平台原版镜像"><a class="markdownIt-Anchor" href="#微信首发macos-catalina-10157-19h2-正式版-clover-5122ocpe三分区支持intel及amd双平台原版镜像"></a> 【微信首发】macOS Catalina 10.15.7 19H2 正式版 Clover 5122/OC/PE三分区支持Intel及AMD双平台原版镜像</h1><blockquote><p>9月24日,苹果向macOS推送10.15.7系统补充更新,macOS Catalina 10.15.7 为您的 Mac 提供了重要的安全性更新和错误修复。</p><ul><li>解决了 macOS 不会自动接入 Wi-Fi 网络的问题</li><li>修复了文件可能无法通过 iCloud 云盘同步的问题</li><li>解决了配备 Radeon Pro 5700 XT 的 iMac(视网膜 5K 显示屏,27 英寸,2020 年机型)上可能发生的图形卡问题</li></ul></blockquote><blockquote><p>这也许是 10.xx 系列的最后一个版本了,但它一定不是<code>macOS</code>支持黑苹果的最后一版,所以做为生产力工具使用的小伙伴们,可以快乐地升级啦!!!</p><p>该镜像于博客/微信公众号同步更新</p></blockquote><h2 id="特点"><a class="markdownIt-Anchor" href="#特点"></a> 特点:</h2><ul><li>三个独立的<code>EFI</code>引导分区,同时支持<code>CLOVER</code> / <code>OpenCore</code> / <code>WEPE</code>引导</li><li>同时支持 <code>Intel</code> 及 <code>AMD</code> 双平台安装使用,<code>RYZEN</code> CPU请选择 <code>config_AMD_RYZEN</code> 进行安装</li><li>新增<code>32GB</code>安装镜像,适用于<code>32GB及以上</code>容量的U盘制作使用【<code>9-25-2020更新</code>】</li><li><code>PE</code> 可连接网络,可远程协助,集成<code>向日葵</code> 和 <code>AnyDesk</code></li><li>附带<code>exFAT</code>分区,用于装入<code>Windows 10</code>等的<code>iso</code>安装镜像,可直接安装双系统</li><li>支持<code>UEFI</code> / <code>MBR</code>引导,基本上做到一盘在手,可以直接引导安装某些不支持<code>UEFI</code>引导方式的机型,比如<code>Dell inspiron 7559</code>等。</li></ul><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/WeChat/StayUpLate.png" alt="禁止熬夜"></p><h2 id="clover-分区"><a class="markdownIt-Anchor" href="#clover-分区"></a> <code>CLOVER</code> 分区</h2><p>容量:<code>200MB</code></p><ul><li><p><code>9-25-2020</code> 更新</p><ul><li>macOS Catalina <code>10.15.7</code> <code>19H2</code></li><li>Clover默认配置文件<code>config.plist</code>原则上支持各种机型引导安装;</li><li>更新<code>CLOVER</code>到<code>v2.5k r5122</code> ,支持<code>Big Sur</code>安装使用</li><li>内存修正驱动采用<code>OcQuirks</code>,原则上支持<code>Big Sur</code></li><li>驱动更新<ul><li>更新<code>Lilu</code> <code>v1.4.8</code></li><li>更新<code>WhatEverGreen</code> <code>v1.4.3</code></li><li>更新<code>AppleALC</code> <code>v1.5.3</code>,新增<code>Lenovo 天逸510s Mini</code>专用ID</li><li>更新<code>VirtualSMC</code> <code>v1.1.7</code></li><li>更新<code>VoodooPS2Controller</code> <code>v2.1.8</code></li><li>新增<code>RTCMemoryFixup</code> <code>v1.0.7</code></li><li>更新<code>BrcmPatchRAM</code> <code>v2.5.5</code></li><li>更新<code>AirportBrcmFixup</code> <code>v2.1.0</code>,支持<code>DW1820A</code> / <code>DW1560</code> / <code>DW1830</code> / <code>BCM94331CD</code> / <code>BCM943602CDP</code> / <code>BCM94360CD</code> 等</li><li>更新<code>USBInjectAll</code> <code>v0.7.6</code> 新增了对<code>Z490</code> / <code>B460</code>等芯片组的支持</li><li>更新<code>LucyRTL8125Ethernet.kext</code> <code>v1.0.0d6</code>,支持<code>z490</code>主板</li></ul></li></ul><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/CDImage/CLOVER2.png" alt="CLOVER2"></p></li></ul><h2 id="oc-分区"><a class="markdownIt-Anchor" href="#oc-分区"></a> <code>OC</code> 分区</h2><p>容量:<code>200MB</code></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.6/OC_Catalina_Installer.png" alt="OC_Catalina_Installer"></p><ul><li><p>OpenCore <code>v0.6.1</code>正式版,支持GUI图形引导界面,不喜欢勿喷,请自行替换</p></li><li><p>默认配置文件支持<code>z300</code>芯片组,其它主板请做替换EFI使用</p></li><li><p>安装结束后请移除引导参数<code>brcmfx-driver=0</code>以使用博通无线网卡</p></li><li><p>驱动更新</p><ul><li>更新<code>Lilu</code> <code>v1.4.8</code></li><li>更新<code>WhatEverGreen</code> <code>v1.4.3</code></li><li>更新<code>AppleALC</code> <code>v1.5.3</code>,新增<code>Lenovo 天逸510s Mini</code>专用ID</li><li>更新<code>VirtualSMC</code> <code>v1.1.7</code></li><li>更新<code>VoodooPS2Controller</code> <code>v2.1.8</code></li><li>新增<code>RTCMemoryFixup</code> <code>v1.0.7</code></li><li>更新<code>BrcmPatchRAM</code> <code>v2.5.5</code></li><li>更新<code>AirportBrcmFixup</code> <code>v2.1.0</code>,支持<code>DW1820A</code> / <code>DW1560</code> / <code>DW1830</code> / <code>BCM94331CD</code> / <code>BCM943602CDP</code> / <code>BCM94360CD</code> 等</li><li>更新<code>USBInjectAll</code> <code>v0.7.6</code> 新增了对<code>Z490</code> / <code>B460</code>等芯片组的支持</li><li>更新<code>LucyRTL8125Ethernet.kext</code> <code>v1.0.0d6</code>,支持<code>z490</code>主板</li></ul><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/Hackintool_Kexts.png" alt="Kexts"></p></li></ul><h2 id="wepe-分区"><a class="markdownIt-Anchor" href="#wepe-分区"></a> <code>WEPE</code> 分区</h2><p>容量:<code>800MB</code></p><p><code>微PE工具箱v2.0维护盘增强版64位20200409</code> 版本特点</p><ul><li><p>此维护盘增强版及合盘,纯净无广告</p></li><li><p><code>内置网络驱动</code>,可驱动绝大多数有线/无线网卡</p></li><li><p>内置针对<code>黑苹果</code>的部分<code>工具</code>,方便安装</p></li><li><p>内置远程协助工具:包括<code>向日葵</code> 和 <code>AnyDesk</code></p></li><li><p>在原版基础上升级了内核,增加了些常用工具,使经典微PE更加实用</p></li><li><p>更新修改内核集成Office迷你版,增加更新维护工具</p></li><li><p>在由kcyou修复DISM及内核的微PE2.0版核心上进一步DIY折腾而来</p></li></ul><h2 id="install-macos-catalina-分区"><a class="markdownIt-Anchor" href="#install-macos-catalina-分区"></a> <strong><code>Install macOS Catalina</code> 分区</strong></h2><ul><li><p>内置<code>10.15.7</code> <code>19H2</code> 安装镜像【<code>9-25-2020更新</code>】</p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_Desktop_Air.png" alt="19H2"></p></li></ul><h2 id="datas-分区"><a class="markdownIt-Anchor" href="#datas-分区"></a> <code>DATAS</code> 分区</h2><p>容量:<code>5000MB</code></p><ul><li>默认格式成<code>exFAT</code>,方便保存<code>MicroSoft Windows 10</code> 光盘镜像以及其它数据用</li></ul><h2 id="datas2-分区32gb版独有"><a class="markdownIt-Anchor" href="#datas2-分区32gb版独有"></a> <code>DATAS2</code> 分区【<code>32GB版独有</code>】</h2><p>容量:<code>16GB</code></p><ul><li>默认格式成<code>exFAT</code>,数据存贮用</li></ul><h2 id="截图"><a class="markdownIt-Anchor" href="#截图"></a> 截图</h2><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/CDImage/CDIMAGE.png" alt="CDIMAGE"><br><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2.png" alt="19H2"><br><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/Hackintool.png" alt="1About_Hackintool"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_1.png" alt="10.15.7_19H2_1"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_2.png" alt="10.15.7_19H2_2"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_3.png" alt="10.15.7_19H2_3"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_4.png" alt="10.15.7_19H2_4"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_5.png" alt="10.15.7_19H2_5"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_6.png" alt="10.15.7_19H2_6"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_7.png" alt="10.15.7_19H2_7"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_8.png" alt="10.15.7_19H2_8"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_9.png" alt="10.15.7_19H2_9"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_10.png" alt="10.15.7_19H2_10"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_11.png" alt="10.15.7_19H2_11"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_12.png" alt="10.15.7_19H2_12"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.4/DualDisplays.png" alt="21Displays"><br><img src="/images/loading.gif" data-original="http://7.daliansky.net/11.0/11.0_DW1820A.png" alt="DW1820A_Bug_Report"><br><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_13.png" alt="DW1820A_WIFI_Status"><br><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/10.15.7_19H2_14.png" alt="DW1820A_BT_Status"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/dell7000/7Light.png" alt="7Light"><br><img src="/images/loading.gif" data-original="http://7.daliansky.net/dell7000/8Volume.png" alt="8Volume"><br><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.14GM/5TouchPad.png" alt="5TouchPad"><br><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/19H2_iMac.png" alt="18G84"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/CDImage/32GB.png" alt="CDIMAGE"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/CDImage/32GB_Size.png" alt="CDIMAGE"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/CDImage/CLOVER.png" alt="CLOVER"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/10.15.7/Install_macOS_Catalina_19H2.png" alt="Install_macOS_Catalina"></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/CDImage/PE.png" alt="weipe2"></p><h2 id="下载链接"><a class="markdownIt-Anchor" href="#下载链接"></a> 下载链接</h2><div class="note info"><p>请通过 <code>喜欢作者</code> 打赏后获取下载链接</p><p><img src="/images/loading.gif" data-original="https://blog.daliansky.net/uploads/WeChat.png" alt="wechat_hackintosher"></p><p>请通过微信公众号【<code>黑果小兵的部落阁</code>】下载</p></div><p>16GB 及以上 U 盘请下载:<code>macOS Catalina 10.15.7(19H2) Installer for Clover 5122 and OC 0.6.1 and PE.dmg</code></p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># md5 macOS\ Catalina\ 10.15.7\(19H2\)\ Installer\ for\ Clover\ 5122\ and\ OC\ 0.6.1\ and\ PE.dmg</span></span><br><span class="line">MD5 (macOS Catalina 10.15.7(19H2) Installer <span class="keyword">for</span> Clover 5122 and OC 0.6.1 and PE.dmg) = b44de9c1aa8aea1c7414b0d14f187b55</span><br></pre></td></tr></table></figure><p>32GB 及以上 U 盘请下载:<code>macOS Catalina 10.15.7(19H2) Installer for Clover 5122 and OC 0.6.1 and PE 32G.dmg</code></p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># md5 macOS\ Catalina\ 10.15.7\(19H2\)\ Installer\ for\ Clover\ 5122\ and\ OC\ 0.6.1\ and\ PE\ 32G.dmg</span></span><br><span class="line">MD5 (macOS Catalina 10.15.7(19H2) Installer <span class="keyword">for</span> Clover 5122 and OC 0.6.1 and PE 32G.dmg) = f54c4c5c0bf930643469b7f064078fda</span><br></pre></td></tr></table></figure><h2 id="u盘制作"><a class="markdownIt-Anchor" href="#u盘制作"></a> U盘制作:</h2><h3 id="安装教程简单版"><a class="markdownIt-Anchor" href="#安装教程简单版"></a> 安装教程简单版</h3><ul><li><p>安装过程(简易版):详细的安装教程请移步:<a href="https://blog.daliansky.net/MacOS-installation-tutorial-XiaoMi-Pro-installation-process-records.html">macOS安装教程</a></p><ul><li><p>下载镜像:<a href="https://blog.daliansky.net">黑果小兵的部落阁</a></p></li><li><p>校验md5值:</p><ul><li><p>macOS:打开终端,输入命令:</p></li><li><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># md5 macOS\ Catalina\ 10.15.7\(19H2\)\ Installer\ for\ Clover\ 5122\ and\ OC\ 0.6.1\ and\ PE.dmg</span></span><br><span class="line">MD5 (macOS Catalina 10.15.7(19H2) Installer <span class="keyword">for</span> Clover 5122 and OC 0.6.1 and PE.dmg) = b44de9c1aa8aea1c7414b0d14f187b55</span><br></pre></td></tr></table></figure></li><li><p>Windows下:请使用<a href="http://www.winmd5.com" target="_blank" rel="noopener">winmd5</a>,将下载的安装镜像拖进winmd5窗口,核验md5值(截图略)</p></li></ul></li><li><p>镜像制作:</p><ul><li>下载<a href="https://etcher.io" target="_blank" rel="noopener">etcher</a>,打开镜像,选择U盘,点击Flash即可。<em><strong>Windows10需要以管理员权限运行</strong></em><img src="/images/loading.gif" data-original="http://7.daliansky.net/etcher.png" alt="etcher"></li></ul></li></ul></li></ul><h3 id="其它教程"><a class="markdownIt-Anchor" href="#其它教程"></a> 其它教程:</h3><p>请参考博客或者公众号的:<code>安装教程</code></p><p><img src="/images/loading.gif" data-original="http://7.daliansky.net/WeChat/blog.daliansky.net.png" alt="blog.daliansky.net"></p><h2 id="温馨提醒"><a class="markdownIt-Anchor" href="#温馨提醒"></a> 温馨提醒</h2><blockquote><p>赞赏后自动回复的消息,会自动推送到<code>微信公众号:hackintosher</code>,它并不会出现在文章里</p><p><code>天翼云盘</code>支持国内手机号注册使用,并不局限于<code>中国电信</code></p><p>您也可以前往博客下载双EFI分区版本 <a href="https://blog.daliansky.net/WeChat-First-macOS-Catalina-10.15.7-19H2-official-version-Clover-5122-OC-WEPE-supports-both-INTEL-and-AMD-original-images.html">点击前往</a></p></blockquote><h2 id="下载"><a class="markdownIt-Anchor" href="#下载"></a> <strong>下载</strong></h2><p>下载链接请务必进入<code>微信公众号</code>里面的文章通过 <code>喜欢作者</code> 打赏后获取,请点击<code>正在看</code>让更多人关注</p><h2 id="感谢名单"><a class="markdownIt-Anchor" href="#感谢名单"></a> 感谢名单</h2><ul><li><a href="https://www.apple.com/" target="_blank" rel="noopener">Apple</a> 的 macOS</li><li><a href="https://github.com/rehabman" target="_blank" rel="noopener">RehabMan</a>维护的项目:<a href="https://github.com/RehabMan/OS-X-Clover-Laptop-Config" target="_blank" rel="noopener">OS-X-Clover-Laptop-Config</a> <a href="https://github.com/RehabMan/Laptop-DSDT-Patch" target="_blank" rel="noopener">Laptop-DSDT-Patch</a> <a href="https://github.com/RehabMan/OS-X-USB-Inject-All" target="_blank" rel="noopener">OS-X-USB-Inject-All</a>等</li><li><a href="https://github.com/acidanthera" target="_blank" rel="noopener">Acidanthera</a> 维护的项目:<a href="https://github.com/acidanthera/OpenCorePkg" target="_blank" rel="noopener">OpenCorePkg</a> <a href="https://github.com/acidanthera/Lilu" target="_blank" rel="noopener">lilu</a> <a href="https://github.com/acidanthera/AirportBrcmFixup" target="_blank" rel="noopener">AirportBrcmFixup</a> <a href="https://github.com/acidanthera/WhateverGreen" target="_blank" rel="noopener">WhateverGreen</a> <a href="https://github.com/acidanthera/VirtualSMC" target="_blank" rel="noopener">VirtualSMC</a> <a href="https://github.com/acidanthera/AppleALC" target="_blank" rel="noopener">AppleALC</a> <a href="https://github.com/acidanthera/BrcmPatchRAM" target="_blank" rel="noopener">BrcmPatchRAM</a> <a href="https://github.com/acidanthera/MaciASL" target="_blank" rel="noopener">MaciASL</a> 等</li><li><a href="https://www.insanelymac.com/forum/profile/1364628-headkaze/" target="_blank" rel="noopener">headkaze</a> 提供的工具:<a href="https://github.com/headkaze/Hackintool" target="_blank" rel="noopener">hackintool</a> <a href="https://github.com/headkaze/PinConfigurator" target="_blank" rel="noopener">PinConfigurator</a> <a href="https://www.insanelymac.com/forum/topic/339175-brcmpatchram2-for-1015-catalina-broadcom-bluetooth-firmware-upload/" target="_blank" rel="noopener">BrcmPatchRAM</a></li><li><a href="https://github.com/CloverHackyColor" target="_blank" rel="noopener">CloverHackyColor</a>维护的项目:<a href="https://github.com/CloverHackyColor/CloverBootloader" target="_blank" rel="noopener">CloverBootloader</a> <a href="https://github.com/CloverHackyColor/CloverThemes" target="_blank" rel="noopener">CloverThemes</a></li><li>宪武整理的:<a href="https://github.com/daliansky/P-little" target="_blank" rel="noopener">P-little</a> <a href="https://github.com/daliansky/OC-little" target="_blank" rel="noopener">OC-little</a></li><li><a href="https://github.com/chris1111" target="_blank" rel="noopener">chris1111</a>维护的项目:<a href="https://github.com/chris1111/VoodooHDA-2.9.2-Clover-V15" target="_blank" rel="noopener">VoodooHDA</a> <a href="https://github.com/chris1111/Wireless-USB-Adapter-Clover" target="_blank" rel="noopener">Wireless USB Adapter Clover</a></li><li><a href="https://github.com/zxystd" target="_blank" rel="noopener">zxystd</a>开发的<a href="https://github.com/zxystd/itlwm" target="_blank" rel="noopener">itlwm</a> <a href="https://github.com/zxystd/IntelBluetoothFirmware" target="_blank" rel="noopener">IntelBluetoothFirmware</a></li><li><a href="https://github.com/lihaoyun6" target="_blank" rel="noopener">lihaoyun6</a>提供的工具:<a href="https://github.com/lihaoyun6/CPU-S" target="_blank" rel="noopener">CPU-S</a> <a href="https://github.com/lihaoyun6/macOS-Displays-icon" target="_blank" rel="noopener">macOS-Displays-icon</a> <a href="https://github.com/lihaoyun6/SidecarPatcher" target="_blank" rel="noopener">SidecarPatcher</a></li><li><a href="https://github.com/SukkaW" target="_blank" rel="noopener">sukka</a>更新维护的<a href="https://blog.skk.moe/post/from-clover-to-opencore/" target="_blank" rel="noopener">从 Clover 到 OpenCore —— Clover 迁移 OpenCore 指南</a></li><li><a href="https://github.com/xzhih" target="_blank" rel="noopener">xzhih</a>提供的工具:<a href="https://github.com/xzhih/one-key-hidpi" target="_blank" rel="noopener">one-key-hidpi</a></li><li><a href="https://github.com/williambj1" target="_blank" rel="noopener">Bat.bat</a>更新维护的<a href="https://blog.daliansky.net/OpenCore-BootLoader.html">精解OpenCore</a></li><li><a href="https://github.com/shuiyunxc" target="_blank" rel="noopener">shuiyunxc</a> 更新维护的<a href="https://shuiyunxc.gitee.io/2020/04/06/Faults/index/" target="_blank" rel="noopener">OpenCore配置错误、故障与解决办法</a></li><li><a href="https://github.com/athlonreg" target="_blank" rel="noopener">athlonreg</a>更新维护的<a href="https://blog.cloudops.ml/ocbook/" target="_blank" rel="noopener">OpenCore 0.5+ 部件补丁</a> <a href="https://github.com/athlonreg/Common-patches-for-hackintosh" target="_blank" rel="noopener">Common-patches-for-hackintosh</a></li><li><a href="github.com">github.com</a></li><li><a href="gitee.io">码云 gitee.io</a></li><li><a href="coding.net">扣钉 coding.net</a></li></ul><h2 id="参考及引用"><a class="markdownIt-Anchor" href="#参考及引用"></a> 参考及引用:</h2><ul><li><a href="https://deviwiki.com/wiki/Dell" target="_blank" rel="noopener">https://deviwiki.com/wiki/Dell</a></li><li><a href="https://deviwiki.com/wiki/Dell_Wireless_1820A_(DW1820A)" target="_blank" rel="noopener">https://deviwiki.com/wiki/Dell_Wireless_1820A_(DW1820A)</a></li><li><a href="%5Bhttps://osxlatitude.com/profile/4953-herv%C3%A9/%5D(https://osxlatitude.com/profile/4953-herv%C3%A9/)">Hervé</a> 更新的Broadcom 4350:<a href="https://osxlatitude.com/forums/topic/12169-bcm4350-cards-registry-of-cardslaptops-interop/" target="_blank" rel="noopener">https://osxlatitude.com/forums/topic/12169-bcm4350-cards-registry-of-cardslaptops-interop/</a></li><li><a href="%5Bhttps://osxlatitude.com/profile/4953-herv%C3%A9/%5D(https://osxlatitude.com/profile/4953-herv%C3%A9/)">Hervé</a> 更新的DW1820A支持机型列表:<a href="https://osxlatitude.com/forums/topic/11322-broadcom-bcm4350-cards-under-high-sierramojave/" target="_blank" rel="noopener">https://osxlatitude.com/forums/topic/11322-broadcom-bcm4350-cards-under-high-sierramojave/</a></li><li><a href="https://osxlatitude.com/profile/129953-nickhx/" target="_blank" rel="noopener">nickhx</a> 提供的蓝牙驱动:<a href="https://osxlatitude.com/forums/topic/11540-dw1820a-for-7490-help/?do=findComment&comment=92833" target="_blank" rel="noopener">https://osxlatitude.com/forums/topic/11540-dw1820a-for-7490-help/?do=findComment&comment=92833</a></li><li><a href="https://blog.xjn819.com/" target="_blank" rel="noopener">xjn819</a>: <a href="https://blog.xjn819.com/?p=543" target="_blank" rel="noopener">使用OpenCore引导黑苹果</a> <a href="https://blog.xjn819.com/?p=317" target="_blank" rel="noopener">300系列主板正确使用AptioMemoryFix.efi的姿势(重写版)</a></li><li><a href="https://github.com/dortania" target="_blank" rel="noopener">dortania</a></li><li><a href="https://www.insanelymac.com/" target="_blank" rel="noopener">insanelymac.com</a></li><li><a href="https://www.tonymacx86.com/" target="_blank" rel="noopener">tonymacx86.com</a></li><li><a href="http://bbs.pcbeta.com" target="_blank" rel="noopener">远景论坛</a></li><li><a href="https://applelife.ru/" target="_blank" rel="noopener">applelife.ru</a></li><li><a href="https://www.olarila.com/" target="_blank" rel="noopener">olarila.com</a></li></ul></div><div><div id="wechat_subscriber" style="display:block;padding:10px 0;margin:20px auto;width:100%;text-align:center"><img id="wechat_subscriber_qcode" src="/images/loading.gif" data-original="/uploads/WeChat.png" alt="黑果小兵 wechat" style="max-width:90%"><div>微信扫一扫,订阅【黑果小兵的部落阁】</div></div></div><div class="updated"><svg xmlns="http://www.w3.org/2000/svg" width="130" height="20"><lineargradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></lineargradient><clippath id="a"><rect width="130" height="20" rx="3" fill="#fff"/></clippath><g clip-path="url(#a)"><path fill="#555" d="M0 0h55v20H0z"/><path fill="#97CA00" d="M55 0h75v20H55z"/><path fill="url(#b)" d="M0 0h130v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="Menlo,monospace" font-size="110"><text x="285" y="150" fill="#010101" fill-opacity=".3" textlength="450" transform="scale(.1)">更新日期</text><text x="285" y="140" textlength="450" transform="scale(.1)">更新日期</text><text x="915" y="150" fill="#010101" fill-opacity=".3" textlength="650" transform="scale(.1)">2020-09-28</text><text x="915" y="140" textlength="650" transform="scale(.1)">2020-09-28</text></g></svg></div><div><div><div style="text-align:center;color:#ccc;font-size:14px">-------------本文结束<i class="fa fa-apple"></i>感谢您的阅读-------------</div></div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center"><button id="rewardButton" disable="enable" onclick='var qr=document.getElementById("QR");"none"===qr.style.display?qr.style.display="block":qr.style.display="none"'><span>打赏</span></button><div>如果文章对您有帮助,就请站长喝杯咖啡吧 ´◡`</div><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/images/loading.gif" data-original="/images/wechatpay.jpg" alt="黑果小兵 微信支付"><p>微信支付</p></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/images/loading.gif" data-original="/images/alipay.jpg" alt="黑果小兵 支付宝"><p>支付宝</p></div></div></div></div><div><div><ul class="qq-qun"><div><p></p><h2>QQ群列表:</h2><p></p><p>688324116 <a href="http://shang.qq.com/wpa/qunwpa?idkey=6bf69a6f4b983dce94ab42e439f02195dfd19a1601522c10ad41f4df97e0da82" target="_blank" rel="noopener">一起黑苹果</a> 2000人群 人满为患<br>331686786 <a href="http://shang.qq.com/wpa/qunwpa?idkey=db511a29e856f37cbb871108ffa77a6e79dde47e491b8f2c8d8fe4d3c310de91" target="_blank" rel="noopener">一起吃苹果</a> 2000人群 人满为患<br>257995340 <a href="http://shang.qq.com/wpa/qunwpa?idkey=8a63c51acb2bb80184d788b9f419ffcc33aa1ed2080132c82173a3d881625be8" target="_blank" rel="noopener">一起啃苹果</a> 2000人群 远景报备群<br>875482673 <a href="http://shang.qq.com/wpa/qunwpa?idkey=81c3783ae414ddac233af104d949899edde38aeac60defcb05036fa7d3fa2972" target="_blank" rel="noopener">黑果小兵黑苹果技术群</a> 2000人收费群 已满员,请加4群<br>1058822256 <a href="http://shang.qq.com/wpa/qunwpa?idkey=0565a16f6dbfa1c69159d15b8fa4ee6473fbf61cb8e998d56e807459aa3006a2" target="_blank" rel="noopener">黑果小兵黑苹果技术群2</a> 2000人收费群 已满员,请加4群<br>819662911 <a href="http://shang.qq.com/wpa/qunwpa?idkey=f7374ff70f7e52442ed6433abfe844791b2ee595e470d74b462143065210b857" target="_blank" rel="noopener">黑果小兵黑苹果技术群3</a> 2000人收费群,请加4群<br>954098809 <a href="http://shang.qq.com/wpa/qunwpa?idkey=034013783cd47f32ae35f19d3fc55591170fa66c8449a1d7aeae53f0935ec505" target="_blank" rel="noopener">黑果小兵黑苹果技术群4</a> 2000人收费群,尚有空位<br>701278330 <a href="http://shang.qq.com/wpa/qunwpa?idkey=5bfd8b092f5a3f3079eab8bb1a497973dbba78ad785d9520ad090a931aeb06f6" target="_blank" rel="noopener">黑苹果无线网卡交流群</a> 1000人群 DW1820A技术支持群<br>891434070 <a href="http://shang.qq.com/wpa/qunwpa?idkey=be06e4c13e796e06a5cd3151d7fcc8f2feee8f9b68b1620ce8771111e2822084" target="_blank" rel="noopener">Catalina黑苹果交流群</a> 2000人群 远景报备群<br>939122730 <a href="http://shang.qq.com/wpa/qunwpa?idkey=e7fb8ea793aee10f9e86c70cd134867bde4183cc3eb87424e61e50b3e9cabf72" target="_blank" rel="noopener">Catalina黑苹果交流II群</a> 2000人群<br>891677227 <a href="http://shang.qq.com/wpa/qunwpa?idkey=9a1eaa552c45d736bb6b19d82ad80e76bf82729f1c1a975b437aa3858473231d" target="_blank" rel="noopener">黑果小兵高级群</a> 2000人群<br>943307869 <a href="http://shang.qq.com/wpa/qunwpa?idkey=7080e6ff936fd2e207439ea18c0a34b4651db81ff45d0edf27b34a21a037871e" target="_blank" rel="noopener">黑果小兵高级群II</a> 2000人群<br>538643249 <a href="http://shang.qq.com/wpa/qunwpa?idkey=665ed002721454d2e811535020261a04b0aae2fa3b6a2ffde5778a852f892178" target="_blank" rel="noopener">OpenCore技术交流群</a> 2000人群 大神众多非OC适配者慎入<br>673294583 <a href="http://shang.qq.com/wpa/qunwpa?idkey=c00a79b8adbba92c152f71cdc721660cc2de276f62a1d4435c83b884e7f369c0" target="_blank" rel="noopener">小新Pro黑苹果技术群</a> 2000人群 非专用机型请勿加入<br>946132482 <a href="http://shang.qq.com/wpa/qunwpa?idkey=d64dff649d6a19f9496aaa472ee3a14450cfbbeddd0e618edf182ffe320a1fd0" target="_blank" rel="noopener">小新Pro黑苹果</a> 500人群 非专用机型请勿加入<br>943181023 <a href="http://shang.qq.com/wpa/qunwpa?idkey=fb772a7e01436d43e1d856a099549551952bb08161ced4a8fc08b4e75e7ab438" target="_blank" rel="noopener">联想小新Air黑苹果交流群</a> 500人群 非专用机型请勿加入<br></p><p></p><h2>Telegram群:</h2><p></p><p>黑果小兵的部落阁 <a href="http://t.me/daliansky" target="_blank">http://t.me/daliansky</a></p></div></ul></div></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者: </strong>黑果小兵</li><li class="post-copyright-link"><strong>本文链接:</strong> <a href="https://blog.daliansky.net/WeChat-First-macOS-Catalina-10.15.7-19H2-official-version-Clover-5122-OC-WEPE-supports-both-INTEL-and-AMD-original-images.html" title="【微信首发】macOS Catalina 10.15.7 19H2 正式版 Clover 5122/OC/PE三分区支持Intel及AMD双平台原版镜像">https://blog.daliansky.net/WeChat-First-macOS-Catalina-10.15.7-19H2-official-version-Clover-5122-OC-WEPE-supports-both-INTEL-and-AMD-original-images.html</a></li><li class="post-copyright-license"><strong>版权声明: </strong>本博客所有文章除特别声明外,均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处!</li></ul></div><footer class="post-footer"><div class="post-tags"><a href="/tags/镜像/" rel="tag"><i class="fa fa-tag"></i> 镜像</a> <a href="/tags/下载/" rel="tag"><i class="fa fa-tag"></i> 下载</a> <a href="/tags/Catalina/" rel="tag"><i class="fa fa-tag"></i> Catalina</a> <a href="/tags/dmg/" rel="tag"><i class="fa fa-tag"></i> dmg</a> <a href="/tags/10-15-7/" rel="tag"><i class="fa fa-tag"></i> 10.15.7</a> <a href="/tags/19H2/" rel="tag"><i class="fa fa-tag"></i> 19H2</a> <a href="/tags/三EFI分区/" rel="tag"><i class="fa fa-tag"></i> 三EFI分区</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/Hackintosh-on-Lenovo-Tianyi-510s-Mini-PC.html" rel="next" title="【黑果小兵】Lenovo 天逸 510s Mini 黑苹果小主机"><i class="fa fa-chevron-left"></i> 【黑果小兵】Lenovo 天逸 510s Mini 黑苹果小主机</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/macOS-Catalina-10.15.7-19H2-Release-version-with-Clover-5122-original-image-Double-EFI-Version-UEFI-and-MBR.html" rel="prev" title="【黑果小兵】macOS Catalina 10.15.7 19H2 正式版 with Clover 5122原版镜像[双EFI版][UEFI and MBR]">【黑果小兵】macOS Catalina 10.15.7 19H2 正式版 with Clover 5122原版镜像[双EFI版][UEFI and MBR] <i class="fa fa-chevron-right"></i></a></div></div></footer></div></article></div></div><div id="gitalk-container"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div id="sidebar-dimmer"></div><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap">站点概览</li></ul><div class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><a href="/"><img class="site-author-image" itemprop="image" src="/images/loading.gif" data-original="/images/avatar.png" alt="黑果小兵"></a><p class="site-author-name" itemprop="name">黑果小兵</p><p class="site-description motion-element" itemprop="description">黑果小兵</p></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"><a href="/archives/"><span class="site-state-item-count">102</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"><a href="/categories/index.html"><span class="site-state-item-count">24</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"><a href="/tags/index.html"><span class="site-state-item-count">236</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="feed-link motion-element"><a href="/atom.xml" rel="alternate"><i class="fa fa-rss"></i> RSS</a></div><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://github.com/daliansky" title="GitHub → https://github.com/daliansky" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i></a> </span><span class="links-of-author-item"><a href="http://www.jianshu.com/u/df9143008845" title="简书 → http://www.jianshu.com/u/df9143008845" rel="noopener" target="_blank"><i class="fa fa-fw fa-heartbeat"></i></a> </span><span class="links-of-author-item"><a href="http://shang.qq.com/wpa/qunwpa?idkey=db511a29e856f37cbb871108ffa77a6e79dde47e491b8f2c8d8fe4d3c310de91" title="QQ → http://shang.qq.com/wpa/qunwpa?idkey=db511a29e856f37cbb871108ffa77a6e79dde47e491b8f2c8d8fe4d3c310de91" rel="noopener" target="_blank"><i class="fa fa-fw fa-qq"></i></a></span></div><div class="links-of-blogroll motion-element links-of-blogroll-block"><div class="links-of-blogroll-title"><i class="fa fa-fw fa-link"></i> Links</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"><a href="https://blog.tlhub.cn" title="https://blog.tlhub.cn" rel="noopener" target="_blank">Athlonreg</a></li><li class="links-of-blogroll-item"><a href="http://www.sqlsec.com" title="http://www.sqlsec.com" rel="noopener" target="_blank">国光</a></li></ul></div></div></div><div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#微信首发macos-catalina-10157-19h2-正式版-clover-5122ocpe三分区支持intel及amd双平台原版镜像"><span class="nav-number">1.</span> <span class="nav-text">【微信首发】macOS Catalina 10.15.7 19H2 正式版 Clover 5122/OC/PE三分区支持Intel及AMD双平台原版镜像</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#特点"><span class="nav-number">1.1.</span> <span class="nav-text">特点:</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#clover-分区"><span class="nav-number">1.2.</span> <span class="nav-text">CLOVER 分区</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#oc-分区"><span class="nav-number">1.3.</span> <span class="nav-text">OC 分区</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#wepe-分区"><span class="nav-number">1.4.</span> <span class="nav-text">WEPE 分区</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#install-macos-catalina-分区"><span class="nav-number">1.5.</span> <span class="nav-text">Install macOS Catalina 分区</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#datas-分区"><span class="nav-number">1.6.</span> <span class="nav-text">DATAS 分区</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#datas2-分区32gb版独有"><span class="nav-number">1.7.</span> <span class="nav-text">DATAS2 分区【32GB版独有】</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#截图"><span class="nav-number">1.8.</span> <span class="nav-text">截图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#下载链接"><span class="nav-number">1.9.</span> <span class="nav-text">下载链接</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#u盘制作"><span class="nav-number">1.10.</span> <span class="nav-text">U盘制作:</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#安装教程简单版"><span class="nav-number">1.10.1.</span> <span class="nav-text">安装教程简单版</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#其它教程"><span class="nav-number">1.10.2.</span> <span class="nav-text">其它教程:</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#温馨提醒"><span class="nav-number">1.11.</span> <span class="nav-text">温馨提醒</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#下载"><span class="nav-number">1.12.</span> <span class="nav-text">下载</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#感谢名单"><span class="nav-number">1.13.</span> <span class="nav-text">感谢名单</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考及引用"><span class="nav-number">1.14.</span> <span class="nav-text">参考及引用:</span></a></li></ol></li></ol></div></div></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright"><a href="http://www.beian.miit.gov.cn" rel="noopener" target="_blank">辽ICP备15000696号-3 </a>© 2016 – <span itemprop="copyrightYear">2020</span> <span class="with-love" id="animate"><i class="fa fa-apple"></i> </span><span class="author" itemprop="copyrightHolder">黑果小兵</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-area-chart"></i> </span><span title="站点总字数">661k</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-coffee"></i> </span><span title="站点阅读时长">20:01</span></div><div class="busuanzi-count"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span class="site-uv" title="总访客量"><i class="fa fa-user"></i> <span class="busuanzi-value" id="busuanzi_value_site_uv"></span> </span><span class="site-pv" title="总访问量"><i class="fa fa-eye"></i> <span class="busuanzi-value" id="busuanzi_value_site_pv"></span></span></div></div></footer><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span id="scrollpercent"><span>0</span>%</span></div></div><script>"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script src="/lib/jquery/index.js?v=2.1.3"></script><script src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.2.5/dist/jquery.fancybox.min.js"></script><script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-reading-progress@1.1/reading_progress.min.js"></script><script src="/js/src/utils.js?v=6.6.0"></script><script src="/js/src/motion.js?v=6.6.0"></script><script src="/js/src/scrollspy.js?v=6.6.0"></script><script src="/js/src/post-details.js?v=6.6.0"></script><script src="/js/src/bootstrap.js?v=6.6.0"></script><script src="https://cdn.jsdelivr.net/npm/gitalk@1.6.2/dist/gitalk.min.js"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1.6.2/dist/gitalk.css"><script src="//cdn.jsdelivr.net/npm/js-md5@0.7.3/src/md5.min.js"></script><script>var gitalk=new Gitalk({clientID:"0da3e792a21a77938da6",clientSecret:"4d2869563000629ee6dbed48fbbf878aea151cb6",repo:"daliansky.github.io",owner:"daliansky",admin:["daliansky"],id:md5(location.pathname),distractionFreeMode:"true"});gitalk.render("gitalk-container")</script><script>// Popup Window;
var isfetched = false;
var isXml = true;
// Search DB path;
var search_path = "search.xml";
if (search_path.length === 0) {
search_path = "search.xml";
} else if (/json$/i.test(search_path)) {
isXml = false;
}
var path = "/" + search_path;
// monitor main search box;
var onPopupClose = function (e) {
$('.popup').hide();
$('#local-search-input').val('');
$('.search-result-list').remove();
$('#no-result').remove();
$(".local-search-pop-overlay").remove();
$('body').css('overflow', '');
}
function proceedsearch() {
$("body")
.append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
.css('overflow', 'hidden');
$('.search-popup-overlay').click(onPopupClose);
$('.popup').toggle();
var $localSearchInput = $('#local-search-input');
$localSearchInput.attr("autocapitalize", "none");
$localSearchInput.attr("autocorrect", "off");
$localSearchInput.focus();
}
// search function;
var searchFunc = function(path, search_id, content_id) {
'use strict';
// start loading animation
$("body")
.append('<div class="search-popup-overlay local-search-pop-overlay">' +
'<div id="search-loading-icon">' +
'<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
'</div>' +
'</div>')
.css('overflow', 'hidden');
$("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');
$.ajax({
url: path,
dataType: isXml ? "xml" : "json",
async: true,
success: function(res) {
// get the contents from search data
isfetched = true;
$('.popup').detach().appendTo('.header-inner');
var datas = isXml ? $("entry", res).map(function() {
return {
title: $("title", this).text(),
content: $("content",this).text(),
url: $("url" , this).text()
};
}).get() : res;
var input = document.getElementById(search_id);
var resultContent = document.getElementById(content_id);
var inputEventFunction = function() {
var searchText = input.value.trim().toLowerCase();
var keywords = searchText.split(/[\s\-]+/);
if (keywords.length > 1) {
keywords.push(searchText);
}
var resultItems = [];
if (searchText.length > 0) {
// perform local searching
datas.forEach(function(data) {
var isMatch = false;
var hitCount = 0;
var searchTextCount = 0;
var title = data.title.trim();
var titleInLowerCase = title.toLowerCase();
var content = data.content.trim().replace(/<[^>]+>/g,"");
var contentInLowerCase = content.toLowerCase();
var articleUrl = decodeURIComponent(data.url);
var indexOfTitle = [];
var indexOfContent = [];
// only match articles with not empty titles
if(title != '') {
keywords.forEach(function(keyword) {
function getIndexByWord(word, text, caseSensitive) {
var wordLen = word.length;
if (wordLen === 0) {
return [];
}
var startPosition = 0, position = [], index = [];
if (!caseSensitive) {
text = text.toLowerCase();
word = word.toLowerCase();
}
while ((position = text.indexOf(word, startPosition)) > -1) {
index.push({position: position, word: word});
startPosition = position + wordLen;
}
return index;
}
indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
});
if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
isMatch = true;
hitCount = indexOfTitle.length + indexOfContent.length;
}
}
// show search results
if (isMatch) {
// sort index by position of keyword
[indexOfTitle, indexOfContent].forEach(function (index) {
index.sort(function (itemLeft, itemRight) {
if (itemRight.position !== itemLeft.position) {
return itemRight.position - itemLeft.position;
} else {
return itemLeft.word.length - itemRight.word.length;
}
});
});
// merge hits into slices
function mergeIntoSlice(text, start, end, index) {
var item = index[index.length - 1];
var position = item.position;
var word = item.word;
var hits = [];
var searchTextCountInSlice = 0;
while (position + word.length <= end && index.length != 0) {
if (word === searchText) {
searchTextCountInSlice++;
}
hits.push({position: position, length: word.length});
var wordEnd = position + word.length;
// move to next position of hit
index.pop();
while (index.length != 0) {
item = index[index.length - 1];
position = item.position;
word = item.word;
if (wordEnd > position) {
index.pop();
} else {
break;
}
}
}
searchTextCount += searchTextCountInSlice;
return {
hits: hits,
start: start,
end: end,
searchTextCount: searchTextCountInSlice
};
}
var slicesOfTitle = [];
if (indexOfTitle.length != 0) {
slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
}
var slicesOfContent = [];
while (indexOfContent.length != 0) {
var item = indexOfContent[indexOfContent.length - 1];
var position = item.position;
var word = item.word;
// cut out 100 characters
var start = position - 20;
var end = position + 80;
if(start < 0){
start = 0;
}
if (end < position + word.length) {
end = position + word.length;
}
if(end > content.length){
end = content.length;
}
slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
}
// sort slices in content by search text's count and hits' count
slicesOfContent.sort(function (sliceLeft, sliceRight) {
if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
return sliceRight.searchTextCount - sliceLeft.searchTextCount;
} else if (sliceLeft.hits.length !== sliceRight.hits.length) {
return sliceRight.hits.length - sliceLeft.hits.length;
} else {
return sliceLeft.start - sliceRight.start;
}
});
// select top N slices in content
var upperBound = parseInt('1');
if (upperBound >= 0) {
slicesOfContent = slicesOfContent.slice(0, upperBound);
}
// highlight title and content
function highlightKeyword(text, slice) {
var result = '';
var prevEnd = slice.start;
slice.hits.forEach(function (hit) {
result += text.substring(prevEnd, hit.position);
var end = hit.position + hit.length;
result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
prevEnd = end;
});
result += text.substring(prevEnd, slice.end);
return result;
}
var resultItem = '';
if (slicesOfTitle.length != 0) {
resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
} else {
resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
}
slicesOfContent.forEach(function (slice) {
resultItem += "<a href='" + articleUrl + "'>" +
"<p class=\"search-result\">" + highlightKeyword(content, slice) +
"...</p>" + "</a>";
});
resultItem += "</li>";
resultItems.push({
item: resultItem,
searchTextCount: searchTextCount,
hitCount: hitCount,
id: resultItems.length
});
}
})
};
if (keywords.length === 1 && keywords[0] === "") {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
} else if (resultItems.length === 0) {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
} else {
resultItems.sort(function (resultLeft, resultRight) {
if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
return resultRight.searchTextCount - resultLeft.searchTextCount;
} else if (resultLeft.hitCount !== resultRight.hitCount) {
return resultRight.hitCount - resultLeft.hitCount;
} else {
return resultRight.id - resultLeft.id;
}
});
var searchResultList = '<ul class=\"search-result-list\">';
resultItems.forEach(function (result) {
searchResultList += result.item;
})
searchResultList += "</ul>";
resultContent.innerHTML = searchResultList;
}
}
if ('auto' === 'auto') {
input.addEventListener('input', inputEventFunction);
} else {
$('.search-icon').click(inputEventFunction);
input.addEventListener('keypress', function (event) {
if (event.keyCode === 13) {
inputEventFunction();
}
});
}
// remove loading animation
$(".local-search-pop-overlay").remove();
$('body').css('overflow', '');
proceedsearch();
}
});
}
// handle and trigger popup window;
$('.popup-trigger').click(function(e) {
e.stopPropagation();
if (isfetched === false) {
searchFunc(path, 'local-search-input', 'local-search-result');
} else {
proceedsearch();
};
});
$('.popup-btn-close').click(onPopupClose);
$('.popup').click(function(e){
e.stopPropagation();
});
$(document).on('keyup', function (event) {
var shouldDismissSearchPopup = event.which === 27 &&
$('.search-popup').is(':visible');
if (shouldDismissSearchPopup) {
onPopupClose();
}
});</script><script src="/js/src/js.cookie.js?v=6.6.0"></script><script src="/js/src/scroll-cookie.js?v=6.6.0"></script><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({pluginRootPath:"live2dw/",pluginJsPath:"lib/",pluginModelPath:"assets/",model:{scale:1.2,hHeadPos:.5,vHeadPos:.618,jsonPath:"/live2dw/assets/tororo.model.json"},display:{superSample:2,width:150,height:300,position:"right",hOffset:0,vOffset:-20},mobile:{show:!1,scale:.5},react:{opacityDefault:.7,opacityOnHover:.2},log:!1,tagMode:!1})</script><script>window.imageLazyLoadSetting={isSPA:!1,processImages:null}</script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})})</script><script>!function(n){n.imageLazyLoadSetting.processImages=i;var e=n.imageLazyLoadSetting.isSPA,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function i(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=r[a].getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight||document.documentElement.clientHeight)&&function(){var e=r[a],t=e,n=function(){r=r.filter(function(t){return e!==t})},i=new Image,o=t.getAttribute("data-original");i.onload=function(){t.src=o,n()},i.src=o}()}i(),n.addEventListener("scroll",function(){var t=i,e=n;clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this)</script></body></html>
|
{
"pile_set_name": "Github"
}
|
{
"nodeconntype":{
"type":"bool",
"value":false
},
"nodeparmtype":{
"type":"bool",
"value":false
}
}
|
{
"pile_set_name": "Github"
}
|
# Fees
Rippled's fee mechanism consists of several interrelated processes:
1. [Rapid Fee escalation](#fee-escalation)
2. [The Transaction Queue](#transaction-queue)
## Fee Escalation
The guiding principal of fee escalation is that when things are going
smoothly, fees stay low, but as soon as high levels of traffic appear
on the network, fees will grow quickly to extreme levels. This should
dissuade malicious users from abusing the system, while giving
legitimate users the ability to pay a higher fee to get high-priority
transactions into the open ledger, even during unfavorable conditions.
How fees escalate:
1. There is a base [fee level](#fee-level) of 256,
which is the minimum that a typical transaction
is required to pay. For a [reference
transaction](#reference-transaction), that corresponds to the
network base fee, which is currently 10 drops.
2. However, there is a limit on the number of transactions that
can get into an open ledger for that base fee level. The limit
will vary based on the [health](#consensus-health) of the
consensus process, but will be at least [5](#other-constants).
* If consensus stays [healthy](#consensus-health), the limit will
be the max of the number of transactions in the validated ledger
plus [20%](#other-constants) or the current limit until it gets
to [50](#other-constants), at which point, the limit will be the
largest number of transactions plus [20%](#other-constants)
in the last [20](#other-constants) validated ledgers which had
more than [50](#other-constants) transactions. Any time the limit
decreases (i.e. a large ledger is no longer recent), the limit will
decrease to the new largest value by 10% each time the ledger has
more than 50 transactions.
* If consensus does not stay [healthy](#consensus-health),
the limit will clamp down to the smaller of the number of
transactions in the validated ledger minus [50%](#other-constants)
or the previous limit minus [50%](#other-constants).
* The intended effect of these mechanisms is to allow as many base fee
level transactions to get into the ledger as possible while the
network is [healthy](#consensus-health), but to respond quickly to
any condition that makes it [unhealthy](#consensus-health), including,
but not limited to, malicious attacks.
3. Once there are more transactions in the open ledger than indicated
by the limit, the required fee level jumps drastically.
* The formula is `( lastLedgerMedianFeeLevel *
TransactionsInOpenLedger^2 / limit^2 )`,
and returns a [fee level](#fee-level).
4. That may still be pretty small, but as more transactions get
into the ledger, the fee level increases exponentially.
* For example, if the limit is 6, and the median fee is minimal,
and assuming all [reference transactions](#reference-transaction),
the 8th transaction only requires a [level](#fee-level) of about 174,000
or about 6800 drops,
but the 20th transaction requires a [level](#fee-level) of about
1,283,000 or about 50,000 drops.
5. Finally, as each ledger closes, the median fee level of that ledger is
computed and used as `lastLedgerMedianFeeLevel` (with a
[minimum value of 128,000](#other-constants))
in the fee escalation formula for the next open ledger.
* Continuing the example above, if ledger consensus completes with
only those 20 transactions, and all of those transactions paid the
minimum required fee at each step, the limit will be adjusted from
6 to 24, and the `lastLedgerMedianFeeLevel` will be about 322,000,
which is 12,600 drops for a
[reference transaction](#reference-transaction).
* This will only require 10 drops for the first 25 transactions,
but the 26th transaction will require a level of about 349,150
or about 13,649 drops.
* This example assumes a cold-start scenario, with a single, possibly
malicious, user willing to pay arbitrary amounts to get transactions
into the open ledger. It ignores the effects of the [Transaction
Queue](#transaction-queue). Any lower fee level transactions submitted
by other users at the same time as this user's transactions will go into
the transaction queue, and will have the first opportunity to be applied
to the _next_ open ledger. The next section describes how that works in
more detail.
## Transaction Queue
An integral part of making fee escalation work for users of the network
is the transaction queue. The queue allows legitimate transactions to be
considered by the network for future ledgers if the escalated open
ledger fee gets too high. This allows users to submit low priority
transactions with a low fee, and wait for high fees to drop. It also
allows legitimate users to continue submitting transactions during high
traffic periods, and give those transactions a much better chance to
succeed.
1. If an incoming transaction meets both the base [fee
level](#fee-level) and the load fee minimum, but does not have a high
enough [fee level](#fee-level) to immediately go into the open ledger,
it is instead put into the queue and broadcast to peers. Each peer will
then make an independent decision about whether to put the transaction
into its open ledger or the queue. In principle, peers with identical
open ledgers will come to identical decisions. Any discrepancies will be
resolved as usual during consensus.
2. When consensus completes, the open ledger limit is adjusted, and
the required [fee level](#fee-level) drops back to the base
[fee level](#fee-level). Before the ledger is made available to
external transactions, transactions are applied from the queue to the
ledger from highest [fee level](#fee-level) to lowest. These transactions
count against the open ledger limit, so the required [fee level](#fee-level)
may start rising during this process.
3. Once the queue is empty, or the required [fee level](#fee-level)
rises too high for the remaining transactions in the queue, the ledger
is opened up for normal transaction processing.
4. A transaction in the queue can stay there indefinitely in principle,
but in practice, either
* it will eventually get applied to the ledger,
* it will attempt to apply to the ledger and fail,
* it will attempt to apply to the ledger and retry [10
times](#other-constants),
* its last ledger sequence number will expire,
* the user will replace it by submitting another transaction with the same
sequence number and at least a [25% higher fee](#other-constants), or
* it will get dropped when the queue fills up with more valuable transactions.
The size limit is computed dynamically, and can hold transactions for
the next [20 ledgers](#other-constants) (restricted to a minimum of
[2000 transactions](#other-constants)). The lower the transaction's
fee, the more likely that it will get dropped if the network is busy.
If a transaction is submitted for an account with one or more transactions
already in the queue, and a sequence number that is sequential with the other
transactions in the queue for that account, it will be considered
for the queue if it meets these additional criteria:
* the account has fewer than [10](#other-constants) transactions
already in the queue.
* all other queued transactions for that account, in the case where
they spend the maximum possible XRP, leave enough XRP balance to pay
the fee,
* the total fees for the other queued transactions are less than both
the network's minimum reserve and the account's XRP balance, and
* none of the prior queued transactions affect the ability of subsequent
transactions to claim a fee.
Currently, there is an additional restriction that the queue cannot work with
transactions using the `sfPreviousTxnID` or `sfAccountTxnID` fields.
`sfPreviousTxnID` is deprecated and shouldn't be used anyway. Future
development will make the queue aware of `sfAccountTxnID` mechanisms.
## Technical Details
### Fee Level
"Fee level" is used to allow the cost of different types of transactions
to be compared directly. For a [reference
transaction](#reference-transaction), the base fee
level is 256. If a transaction is submitted with a higher `Fee` field,
the fee level is scaled appropriately.
Examples, assuming a [reference transaction](#reference-transaction)
base fee of 10 drops:
1. A single-signed [reference transaction](#reference-transaction)
with `Fee=20` will have a fee level of
`20 drop fee * 256 fee level / 10 drop base fee = 512 fee level`.
2. A multi-signed [reference transaction](#reference-transaction) with
3 signatures (base fee = 40 drops) and `Fee=60` will have a fee level of
`60 drop fee * 256 fee level / ((1tx + 3sigs) * 10 drop base fee) = 384
fee level`.
3. A hypothetical future non-reference transaction with a base
fee of 15 drops multi-signed with 5 signatures and `Fee=90` will
have a fee level of
`90 drop fee * 256 fee level / ((1tx + 5sigs) * 15 drop base fee) = 256
fee level`.
This demonstrates that a simpler transaction paying less XRP can be more
likely to get into the open ledger, or be sorted earlier in the queue
than a more complex transaction paying more XRP.
### Reference Transaction
In this document, a "Reference Transaction" is any currently implemented
single-signed transaction (eg. Payment, Account Set, Offer Create, etc)
that requires a fee.
In the future, there may be other transaction types that require
more (or less) work for rippled to process. Those transactions may have
a higher (or lower) base fee, requiring a correspondingly higher (or
lower) fee to get into the same position as a reference transaction.
### Consensus Health
For consensus to be considered healthy, the consensus process must take
less than 5 seconds. This time limit was chosen based on observed past
behavior of the ripple network. Note that this is not necessarily the
time between ledger closings, as consensus usually starts some amount
of time after a ledger opens.
### Other Constants
* *Base fee transaction limit per ledger*. The minimum value of 5 was
chosen to ensure the limit never gets so small that the ledger becomes
unusable. The "target" value of 50 was chosen so the limit never gets large
enough to invite abuse, but keeps up if the network stays healthy and
active. These exact values were chosen experimentally, and can easily
change in the future.
* *Expected ledger size growth and reduction percentages*. The growth
value of 20% was chosen to allow the limit to grow quickly as load
increases, but not so quickly as to allow bad actors to run unrestricted.
The reduction value of 50% was chosen to cause the limit to drop
significantly, but not so drastically that the limit cannot quickly
recover if the problem is temporary. These exact values were chosen
experimentally, and can easily change in the future.
* *Minimum `lastLedgerMedianFeeLevel`*. The value of 500 was chosen to
ensure that the first escalated fee was more significant and noticable
than what the default would allow. This exact value was chosen
experimentally, and can easily change in the future.
* *Transaction queue size limit*. The limit is computed based on the
base fee transaction limit per ledger, so that the queue can grow
automatically as the ripple network's performance improves, allowing
more transactions per second, and thus more transactions per ledger
to process successfully. The limit of 20 ledgers was used to provide
a balance between resource (specifically memory) usage, and giving
transactions a realistic chance to be processed. The minimum size of
2000 transactions was chosen to allow a decent functional backlog during
network congestion conditions. These exact values were
chosen experimentally, and can easily change in the future.
* *Maximum retries*. A transaction in the queue can attempt to apply
to the open ledger, but get a retry (`ter`) code up to 10 times, at
which point, it will be removed from the queue and dropped. The
value was chosen to be large enough to allow temporary failures to clear
up, but small enough that the queue doesn't fill up with stale
transactions which prevent lower fee level, but more likely to succeed,
transactions from queuing.
* *Maximum transactions per account*. A single account can have up to 10
transactions in the queue at any given time. This is primarily to
mitigate the lost cost of broadcasting multiple transactions if one of
the earlier ones fails or is otherwise removed from the queue without
being applied to the open ledger. The value was chosen arbitrarily, and
can easily change in the future.
* *Minimum last ledger sequence buffer*. If a transaction has a
`LastLedgerSequence` value, and cannot be processed into the open
ledger, that `LastLedgerSequence` must be at least 2 more than the
sequence number of the open ledger to be considered for the queue. The
value was chosen to provide a balance between letting the user control
the lifespan of the transaction, and giving a queued transaction a
chance to get processed out of the queue before getting discarded,
particularly since it may have dependent transactions also in the queue,
which will never succeed if this one is discarded.
* *Replaced transaction fee increase*. Any transaction in the queue can be
replaced by another transaction with the same sequence number and at
least a 25% higher fee level. The 25% increase is intended to cover the
resource cost incurred by broadcasting the original transaction to the
network. This value was chosen experimentally, and can easily change in
the future.
### `fee` command
**The `fee` RPC and WebSocket command is still experimental, and may
change without warning.**
`fee` takes no parameters, and returns information about the current local
[fee escalation](#fee-escalation) and [transaction queue](#transaction-queue)
state as both fee levels and drops. The drop values assume a
single-singed reference transaction. It is up to the user to compute the
neccessary fees for other types of transactions. (E.g. multiply all drop
values by 5 for a multi-signed transaction with 4 signatures.)
The `fee` result is always instantanteous, and relates to the open
ledger. It includes the sequence number of the current open ledger,
but may not make sense if rippled is not synced to the network.
Result format:
```
{
"result" : {
"current_ledger_size" : "16", // number of transactions in the open ledger
"current_queue_size" : "2", // number of transactions waiting in the queue
"expected_ledger_size" : "15", // one less than the number of transactions that can get into the open ledger for the base fee.
"max_queue_size" : "300", // number of transactions allowed into the queue
"ledger_current_index" : 123456789, // sequence number of the current open ledger
"levels" : {
"reference_level" : "256", // level of a reference transaction. Always 256.
"minimum_level" : "256", // minimum fee level to get into the queue. If >256, indicates the queue is full.
"median_level" : "281600", // lastLedgerMedianFeeLevel used in escalation calculations.
"open_ledger_level" : "320398" // minimum fee level to get into the open ledger immediately.
},
"drops" : {
"base_fee" : "10", // base fee of a reference transaction in drops.
"minimum_fee" : "10", // minimum drops to get a reference transaction into the queue. If >base_fee, indicates the queue is full.
"median_fee" : "11000", // drop equivalent of "median_level" for a reference transaction.
"open_ledger_fee" : "12516" // minimum drops to get a reference transaction into the open ledger immediately.
}
}
}
```
### [`server_info`](https://ripple.com/build/rippled-apis/#server-info) command
**The fields listed here are still experimental, and may change
without warning.**
Up to two fields in `server_info` output are related to fee escalation.
1. `load_factor_fee_escalation`: The factor on base transaction cost
that a transaction must pay to get into the open ledger. This value can
change quickly as transactions are processed from the network and
ledgers are closed. If not escalated, the value is 1, so will not be
returned.
2. `load_factor_fee_queue`: If the queue is full, this is the factor on
base transaction cost that a transaction must pay to get into the queue.
If not full, the value is 1, so will not be returned.
In all cases, the transaction fee must be high enough to overcome both
`load_factor_fee_queue` and `load_factor` to be considered. It does not
need to overcome `load_factor_fee_escalation`, though if it does not, it
is more likely to be queued than immediately processed into the open
ledger.
### [`server_state`](https://ripple.com/build/rippled-apis/#server-state) command
**The fields listed here are still experimental, and may change
without warning.**
Three fields in `server_state` output are related to fee escalation.
1. `load_factor_fee_escalation`: The factor on base transaction cost
that a transaction must pay to get into the open ledger. This value can
change quickly as transactions are processed from the network and
ledgers are closed. The ratio between this value and
`load_factor_fee_reference` determines the multiplier for transaction
fees to get into the current open ledger.
2. `load_factor_fee_queue`: This is the factor on base transaction cost
that a transaction must pay to get into the queue. The ratio between
this value and `load_factor_fee_reference` determines the multiplier for
transaction fees to get into the transaction queue to be considered for
a later ledger.
3. `load_factor_fee_reference`: Like `load_base`, this is the baseline
that is used to scale fee escalation computations.
In all cases, the transaction fee must be high enough to overcome both
`load_factor_fee_queue` and `load_factor` to be considered. It does not
need to overcome `load_factor_fee_escalation`, though if it does not, it
is more likely to be queued than immediately processed into the open
ledger.
|
{
"pile_set_name": "Github"
}
|
/******************************************************************************
*
* Project: PDF driver
* Purpose: GDALDataset driver for PDF dataset (read vector features)
* Author: Even Rouault, <even dot rouault at spatialys.com>
*
******************************************************************************
* Copyright (c) 2010-2014, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "gdal_pdf.h"
#include <array>
#define SQUARE(x) ((x)*(x))
#define EPSILON 1e-5
CPL_CVSID("$Id$")
#ifdef HAVE_PDF_READ_SUPPORT
constexpr int BEZIER_STEPS = 10;
/************************************************************************/
/* OpenVectorLayers() */
/************************************************************************/
int PDFDataset::OpenVectorLayers(GDALPDFDictionary* poPageDict)
{
if( bHasLoadedLayers )
return TRUE;
bHasLoadedLayers = TRUE;
if( poPageDict == nullptr )
{
poPageDict = poPageObj->GetDictionary();
if ( poPageDict == nullptr )
return FALSE;
}
GetCatalog();
if( poCatalogObject == nullptr )
return FALSE;
GDALPDFObject* poContents = poPageDict->Get("Contents");
if (poContents == nullptr)
return FALSE;
if (poContents->GetType() != PDFObjectType_Dictionary &&
poContents->GetType() != PDFObjectType_Array)
return FALSE;
GDALPDFObject* poResources = poPageDict->Get("Resources");
if (poResources == nullptr || poResources->GetType() != PDFObjectType_Dictionary)
return FALSE;
GDALPDFObject* poStructTreeRoot = poCatalogObject->GetDictionary()->Get("StructTreeRoot");
if (CPLTestBool(CPLGetConfigOption("OGR_PDF_READ_NON_STRUCTURED", "NO")) ||
poStructTreeRoot == nullptr ||
poStructTreeRoot->GetType() != PDFObjectType_Dictionary)
{
ExploreContentsNonStructured(poContents, poResources);
}
else
{
int nDepth = 0;
int nVisited = 0;
bool bStop = false;
ExploreContents(poContents, poResources, nDepth, nVisited, bStop);
std::set< std::pair<int,int> > aoSetAlreadyVisited;
ExploreTree(poStructTreeRoot, aoSetAlreadyVisited, 0);
}
CleanupIntermediateResources();
int bEmptyDS = TRUE;
for(int i=0;i<nLayers;i++)
{
if (papoLayers[i]->GetFeatureCount() != 0)
{
bEmptyDS = FALSE;
break;
}
}
return !bEmptyDS;
}
/************************************************************************/
/* CleanupIntermediateResources() */
/************************************************************************/
void PDFDataset::CleanupIntermediateResources()
{
std::map<int,OGRGeometry*>::iterator oMapIter = oMapMCID.begin();
for( ; oMapIter != oMapMCID.end(); ++oMapIter)
delete oMapIter->second;
oMapMCID.erase(oMapMCID.begin(), oMapMCID.end());
}
/************************************************************************/
/* InitMapOperators() */
/************************************************************************/
typedef struct
{
char szOpName[4];
int nArgs;
} PDFOperator;
static const PDFOperator asPDFOperators [] =
{
{ "b", 0 },
{ "B", 0 },
{ "b*", 0 },
{ "B*", 0 },
{ "BDC", 2 },
// BI
{ "BMC", 1 },
// BT
{ "BX", 0 },
{ "c", 6 },
{ "cm", 6 },
{ "CS", 1 },
{ "cs", 1 },
{ "d", 1 }, /* we have ignored the first arg */
// d0
// d1
{ "Do", 1 },
{ "DP", 2 },
// EI
{ "EMC", 0 },
// ET
{ "EX", 0 },
{ "f", 0 },
{ "F", 0 },
{ "f*", 0 },
{ "G", 1 },
{ "g", 1 },
{ "gs", 1 },
{ "h", 0 },
{ "i", 1 },
// ID
{ "j", 1 },
{ "J", 1 },
{ "K", 4 },
{ "k", 4 },
{ "l", 2 },
{ "m", 2 },
{ "M", 1 },
{ "MP", 1 },
{ "n", 0 },
{ "q", 0 },
{ "Q", 0 },
{ "re", 4 },
{ "RG", 3 },
{ "rg", 3 },
{ "ri", 1 },
{ "s", 0 },
{ "S", 0 },
{ "SC", -1 },
{ "sc", -1 },
{ "SCN", -1 },
{ "scn", -1 },
{ "sh", 1 },
// T*
{ "Tc", 1},
{ "Td", 2},
{ "TD", 2},
{ "Tf", 1},
{ "Tj", 1},
{ "TJ", 1},
{ "TL", 1},
{ "Tm", 6},
{ "Tr", 1},
{ "Ts", 1},
{ "Tw", 1},
{ "Tz", 1},
{ "v", 4 },
{ "w", 1 },
{ "W", 0 },
{ "W*", 0 },
{ "y", 4 },
// '
// "
};
void PDFDataset::InitMapOperators()
{
for(size_t i=0;i<sizeof(asPDFOperators) / sizeof(asPDFOperators[0]); i++)
oMapOperators[asPDFOperators[i].szOpName] = asPDFOperators[i].nArgs;
}
/************************************************************************/
/* TestCapability() */
/************************************************************************/
int PDFDataset::TestCapability( CPL_UNUSED const char * pszCap )
{
return FALSE;
}
/************************************************************************/
/* GetLayer() */
/************************************************************************/
OGRLayer *PDFDataset::GetLayer( int iLayer )
{
OpenVectorLayers(nullptr);
if (iLayer < 0 || iLayer >= nLayers)
return nullptr;
return papoLayers[iLayer];
}
/************************************************************************/
/* GetLayerCount() */
/************************************************************************/
int PDFDataset::GetLayerCount()
{
OpenVectorLayers(nullptr);
return nLayers;
}
/************************************************************************/
/* ExploreTree() */
/************************************************************************/
void PDFDataset::ExploreTree(GDALPDFObject* poObj,
std::set< std::pair<int,int> > aoSetAlreadyVisited,
int nRecLevel)
{
if (nRecLevel == 16)
return;
std::pair<int,int> oObjPair( poObj->GetRefNum().toInt(), poObj->GetRefGen() );
if( aoSetAlreadyVisited.find( oObjPair ) != aoSetAlreadyVisited.end() )
return;
aoSetAlreadyVisited.insert( oObjPair );
if (poObj->GetType() != PDFObjectType_Dictionary)
return;
GDALPDFDictionary* poDict = poObj->GetDictionary();
GDALPDFObject* poS = poDict->Get("S");
CPLString osS;
if (poS != nullptr && poS->GetType() == PDFObjectType_Name)
{
osS = poS->GetName();
}
GDALPDFObject* poT = poDict->Get("T");
CPLString osT;
if (poT != nullptr && poT->GetType() == PDFObjectType_String)
{
osT = poT->GetString();
}
GDALPDFObject* poK = poDict->Get("K");
if (poK == nullptr)
return;
if (poK->GetType() == PDFObjectType_Array)
{
GDALPDFArray* poArray = poK->GetArray();
if (poArray->GetLength() > 0 &&
poArray->Get(0) &&
poArray->Get(0)->GetType() == PDFObjectType_Dictionary &&
poArray->Get(0)->GetDictionary()->Get("K") != nullptr &&
poArray->Get(0)->GetDictionary()->Get("K")->GetType() == PDFObjectType_Int)
{
CPLString osLayerName;
if (!osT.empty() )
osLayerName = osT;
else
{
if (!osS.empty() )
osLayerName = osS;
else
osLayerName = CPLSPrintf("Layer%d", nLayers + 1);
}
auto poSRSOri = GetSpatialRef();
OGRSpatialReference* poSRS = poSRSOri ? poSRSOri->Clone() : nullptr;
OGRPDFLayer* poLayer =
new OGRPDFLayer(this, osLayerName.c_str(), poSRS, wkbUnknown);
if( poSRS )
poSRS->Release();
poLayer->Fill(poArray);
papoLayers = (OGRLayer**)
CPLRealloc(papoLayers, (nLayers + 1) * sizeof(OGRLayer*));
papoLayers[nLayers] = poLayer;
nLayers ++;
}
else
{
for(int i=0;i<poArray->GetLength();i++)
{
auto poSubObj = poArray->Get(i);
if (poSubObj )
{
ExploreTree(poSubObj, aoSetAlreadyVisited,
nRecLevel + 1);
}
}
}
}
else if (poK->GetType() == PDFObjectType_Dictionary)
{
ExploreTree(poK, aoSetAlreadyVisited, nRecLevel + 1);
}
}
/************************************************************************/
/* GetGeometryFromMCID() */
/************************************************************************/
OGRGeometry* PDFDataset::GetGeometryFromMCID(int nMCID)
{
std::map<int,OGRGeometry*>::iterator oMapIter = oMapMCID.find(nMCID);
if (oMapIter != oMapMCID.end())
return oMapIter->second;
else
return nullptr;
}
/************************************************************************/
/* GraphicState */
/************************************************************************/
class GraphicState
{
public:
std::array<double,6> adfCM;
std::array<double,3> adfStrokeColor;
std::array<double,3> adfFillColor;
GraphicState()
{
adfCM[0] = 1;
adfCM[1] = 0;
adfCM[2] = 0;
adfCM[3] = 1;
adfCM[4] = 0;
adfCM[5] = 0;
adfStrokeColor[0] = 0.0;
adfStrokeColor[1] = 0.0;
adfStrokeColor[2] = 0.0;
adfFillColor[0] = 1.0;
adfFillColor[1] = 1.0;
adfFillColor[2] = 1.0;
}
void MultiplyBy(double adfMatrix[6])
{
/*
[ a b 0 ] [ a' b' 0] [ aa' + bc' ab' + bd' 0 ]
[ c d 0 ] * [ c' d' 0] = [ ca' + dc' cb' + dd' 0 ]
[ e f 1 ] [ e' f' 1] [ ea' + fc' + e' eb' + fd' + f' 1 ]
*/
double a = adfCM[0];
double b = adfCM[1];
double c = adfCM[2];
double d = adfCM[3];
double e = adfCM[4];
double f = adfCM[5];
double ap = adfMatrix[0];
double bp = adfMatrix[1];
double cp = adfMatrix[2];
double dp = adfMatrix[3];
double ep = adfMatrix[4];
double fp = adfMatrix[5];
adfCM[0] = a*ap + b*cp;
adfCM[1] = a*bp + b*dp;
adfCM[2] = c*ap + d*cp;
adfCM[3] = c*bp + d*dp;
adfCM[4] = e*ap + f*cp + ep;
adfCM[5] = e*bp + f*dp + fp;
}
void ApplyMatrix(double adfCoords[2])
{
double x = adfCoords[0];
double y = adfCoords[1];
adfCoords[0] = x * adfCM[0] + y * adfCM[2] + adfCM[4];
adfCoords[1] = x * adfCM[1] + y * adfCM[3] + adfCM[5];
}
};
/************************************************************************/
/* PDFCoordsToSRSCoords() */
/************************************************************************/
void PDFDataset::PDFCoordsToSRSCoords(double x, double y,
double& X, double &Y)
{
x = x / dfPageWidth * nRasterXSize;
if( bGeoTransformValid )
y = (1 - y / dfPageHeight) * nRasterYSize;
else
y = (y / dfPageHeight) * nRasterYSize;
X = adfGeoTransform[0] + x * adfGeoTransform[1] + y * adfGeoTransform[2];
Y = adfGeoTransform[3] + x * adfGeoTransform[4] + y * adfGeoTransform[5];
if( fabs(X - (int)floor(X + 0.5)) < 1e-8 )
X = (int)floor(X + 0.5);
if( fabs(Y - (int)floor(Y + 0.5)) < 1e-8 )
Y = (int)floor(Y + 0.5);
}
/************************************************************************/
/* PDFGetCircleCenter() */
/************************************************************************/
/* Return the center of a circle, or NULL if it is not recognized */
static OGRPoint* PDFGetCircleCenter(OGRLineString* poLS)
{
if (poLS == nullptr || poLS->getNumPoints() != 1 + 4 * BEZIER_STEPS)
return nullptr;
if (poLS->getY(0 * BEZIER_STEPS) == poLS->getY(2 * BEZIER_STEPS) &&
poLS->getX(1 * BEZIER_STEPS) == poLS->getX(3 * BEZIER_STEPS) &&
fabs((poLS->getX(0 * BEZIER_STEPS) + poLS->getX(2 * BEZIER_STEPS)) / 2 - poLS->getX(1 * BEZIER_STEPS)) < EPSILON &&
fabs((poLS->getY(1 * BEZIER_STEPS) + poLS->getY(3 * BEZIER_STEPS)) / 2 - poLS->getY(0 * BEZIER_STEPS)) < EPSILON)
{
return new OGRPoint((poLS->getX(0 * BEZIER_STEPS) + poLS->getX(2 * BEZIER_STEPS)) / 2,
(poLS->getY(1 * BEZIER_STEPS) + poLS->getY(3 * BEZIER_STEPS)) / 2);
}
return nullptr;
}
/************************************************************************/
/* PDFGetSquareCenter() */
/************************************************************************/
/* Return the center of a square, or NULL if it is not recognized */
static OGRPoint* PDFGetSquareCenter(OGRLineString* poLS)
{
if (poLS == nullptr || poLS->getNumPoints() < 4 || poLS->getNumPoints() > 5)
return nullptr;
if (poLS->getX(0) == poLS->getX(3) &&
poLS->getY(0) == poLS->getY(1) &&
poLS->getX(1) == poLS->getX(2) &&
poLS->getY(2) == poLS->getY(3) &&
fabs(fabs(poLS->getX(0) - poLS->getX(1)) - fabs(poLS->getY(0) - poLS->getY(3))) < EPSILON)
{
return new OGRPoint((poLS->getX(0) + poLS->getX(1)) / 2,
(poLS->getY(0) + poLS->getY(3)) / 2);
}
return nullptr;
}
/************************************************************************/
/* PDFGetTriangleCenter() */
/************************************************************************/
/* Return the center of a equilateral triangle, or NULL if it is not recognized */
static OGRPoint* PDFGetTriangleCenter(OGRLineString* poLS)
{
if (poLS == nullptr || poLS->getNumPoints() < 3 || poLS->getNumPoints() > 4)
return nullptr;
double dfSqD1 = SQUARE(poLS->getX(0) - poLS->getX(1)) + SQUARE(poLS->getY(0) - poLS->getY(1));
double dfSqD2 = SQUARE(poLS->getX(1) - poLS->getX(2)) + SQUARE(poLS->getY(1) - poLS->getY(2));
double dfSqD3 = SQUARE(poLS->getX(0) - poLS->getX(2)) + SQUARE(poLS->getY(0) - poLS->getY(2));
if (fabs(dfSqD1 - dfSqD2) < EPSILON && fabs(dfSqD2 - dfSqD3) < EPSILON)
{
return new OGRPoint((poLS->getX(0) + poLS->getX(1) + poLS->getX(2)) / 3,
(poLS->getY(0) + poLS->getY(1) + poLS->getY(2)) / 3);
}
return nullptr;
}
/************************************************************************/
/* PDFGetStarCenter() */
/************************************************************************/
/* Return the center of a 5-point star, or NULL if it is not recognized */
static OGRPoint* PDFGetStarCenter(OGRLineString* poLS)
{
if (poLS == nullptr || poLS->getNumPoints() < 10 || poLS->getNumPoints() > 11)
return nullptr;
double dfSqD01 = SQUARE(poLS->getX(0) - poLS->getX(1)) +
SQUARE(poLS->getY(0) - poLS->getY(1));
double dfSqD02 = SQUARE(poLS->getX(0) - poLS->getX(2)) +
SQUARE(poLS->getY(0) - poLS->getY(2));
double dfSqD13 = SQUARE(poLS->getX(1) - poLS->getX(3)) +
SQUARE(poLS->getY(1) - poLS->getY(3));
const double dfSin18divSin126 = 0.38196601125;
if( dfSqD02 == 0 )
return nullptr;
int bOK = fabs(dfSqD13 / dfSqD02 - SQUARE(dfSin18divSin126)) < EPSILON;
for(int i=1;i<10 && bOK;i++)
{
double dfSqDiip1 = SQUARE(poLS->getX(i) - poLS->getX((i+1)%10)) +
SQUARE(poLS->getY(i) - poLS->getY((i+1)%10));
if (fabs(dfSqDiip1 - dfSqD01) > EPSILON)
{
bOK = FALSE;
}
double dfSqDiip2 = SQUARE(poLS->getX(i) - poLS->getX((i+2)%10)) +
SQUARE(poLS->getY(i) - poLS->getY((i+2)%10));
if ( (i%2) == 1 && fabs(dfSqDiip2 - dfSqD13) > EPSILON )
{
bOK = FALSE;
}
if ( (i%2) == 0 && fabs(dfSqDiip2 - dfSqD02) > EPSILON )
{
bOK = FALSE;
}
}
if (bOK)
{
return new OGRPoint((poLS->getX(0) + poLS->getX(2) + poLS->getX(4) +
poLS->getX(6) + poLS->getX(8)) / 5,
(poLS->getY(0) + poLS->getY(2) + poLS->getY(4) +
poLS->getY(6) + poLS->getY(8)) / 5);
}
return nullptr;
}
/************************************************************************/
/* UnstackTokens() */
/************************************************************************/
int PDFDataset::UnstackTokens(const char* pszToken,
int nRequiredArgs,
char aszTokenStack[TOKEN_STACK_SIZE][MAX_TOKEN_SIZE],
int& nTokenStackSize,
double* adfCoords)
{
if (nTokenStackSize < nRequiredArgs)
{
CPLDebug("PDF", "not enough arguments for %s", pszToken);
return FALSE;
}
nTokenStackSize -= nRequiredArgs;
for(int i=0;i<nRequiredArgs;i++)
{
adfCoords[i] = CPLAtof(aszTokenStack[nTokenStackSize+i]);
}
return TRUE;
}
/************************************************************************/
/* AddBezierCurve() */
/************************************************************************/
static void AddBezierCurve(std::vector<double>& oCoords,
const double* x0_y0,
const double* x1_y1,
const double* x2_y2,
const double* x3_y3)
{
double x0 = x0_y0[0];
double y0 = x0_y0[1];
double x1 = x1_y1[0];
double y1 = x1_y1[1];
double x2 = x2_y2[0];
double y2 = x2_y2[1];
double x3 = x3_y3[0];
double y3 = x3_y3[1];
for( int i = 1; i < BEZIER_STEPS; i++ )
{
const double t = static_cast<double>(i) / BEZIER_STEPS;
const double t2 = t * t;
const double t3 = t2 * t;
const double oneMinust = 1 - t;
const double oneMinust2 = oneMinust * oneMinust;
const double oneMinust3 = oneMinust2 * oneMinust;
const double three_t_oneMinust = 3 * t * oneMinust;
const double x = oneMinust3 * x0 + three_t_oneMinust * (oneMinust * x1 + t * x2) + t3 * x3;
const double y = oneMinust3 * y0 + three_t_oneMinust * (oneMinust * y1 + t * y2) + t3 * y3;
oCoords.push_back(x);
oCoords.push_back(y);
}
oCoords.push_back(x3);
oCoords.push_back(y3);
}
/************************************************************************/
/* ParseContent() */
/************************************************************************/
#define NEW_SUBPATH -99
#define CLOSE_SUBPATH -98
#define FILL_SUBPATH -97
OGRGeometry* PDFDataset::ParseContent(const char* pszContent,
GDALPDFObject* poResources,
int bInitBDCStack,
int bMatchQ,
std::map<CPLString, OGRPDFLayer*>& oMapPropertyToLayer,
OGRPDFLayer* poCurLayer)
{
#define PUSH(aszTokenStack, str, strlen) \
do \
{ \
if(nTokenStackSize < TOKEN_STACK_SIZE) \
memcpy(aszTokenStack[nTokenStackSize ++], str, strlen + 1); \
else \
{ \
CPLError(CE_Failure, CPLE_AppDefined, \
"Max token stack size reached"); \
return nullptr; \
}; \
} while( false )
#define ADD_CHAR(szToken, c) \
do \
{ \
if(nTokenSize < MAX_TOKEN_SIZE-1) \
{ \
szToken[nTokenSize ++ ] = c; \
szToken[nTokenSize ] = '\0'; \
} \
else \
{ \
CPLError(CE_Failure, CPLE_AppDefined, "Max token size reached");\
return nullptr; \
}; \
} while( false )
char szToken[MAX_TOKEN_SIZE];
int nTokenSize = 0;
char ch;
char aszTokenStack[TOKEN_STACK_SIZE][MAX_TOKEN_SIZE];
int nTokenStackSize = 0;
int bInString = FALSE;
int nBDCLevel = 0;
int nParenthesisLevel = 0;
int nArrayLevel = 0;
int nBTLevel = 0;
int bCollectAllObjects = poResources != nullptr && !bInitBDCStack && !bMatchQ;
GraphicState oGS;
std::stack<GraphicState> oGSStack;
std::stack<OGRPDFLayer*> oLayerStack;
std::vector<double> oCoords;
int bHasFoundFill = FALSE;
int bHasMultiPart = FALSE;
szToken[0] = '\0';
if (bInitBDCStack)
{
PUSH(aszTokenStack, "dummy", 5);
PUSH(aszTokenStack, "dummy", 5);
oLayerStack.push(nullptr);
}
while((ch = *pszContent) != '\0')
{
int bPushToken = FALSE;
if (!bInString && ch == '%')
{
/* Skip comments until end-of-line */
while((ch = *pszContent) != '\0')
{
if (ch == '\r' || ch == '\n')
break;
pszContent ++;
}
if (ch == 0)
break;
}
else if (!bInString && (ch == ' ' || ch == '\r' || ch == '\n'))
{
bPushToken = TRUE;
}
/* Ignore arrays */
else if (!bInString && nTokenSize == 0 && ch == '[')
{
nArrayLevel ++;
}
else if (!bInString && nArrayLevel && ch == ']')
{
nArrayLevel --;
}
else if (!bInString && nTokenSize == 0 && ch == '(')
{
bInString = TRUE;
nParenthesisLevel ++;
ADD_CHAR(szToken, ch);
}
else if (bInString && ch == '(')
{
nParenthesisLevel ++;
ADD_CHAR(szToken, ch);
}
else if (bInString && ch == ')')
{
nParenthesisLevel --;
ADD_CHAR(szToken, ch);
if (nParenthesisLevel == 0)
{
bInString = FALSE;
bPushToken = TRUE;
}
}
else if( bInString && ch == '\\' )
{
const auto nextCh = pszContent[1];
if( nextCh == 'n' )
{
ADD_CHAR(szToken, '\n');
pszContent ++;
}
else if( nextCh == 'r' )
{
ADD_CHAR(szToken, '\r');
pszContent ++;
}
else if( nextCh == 't' )
{
ADD_CHAR(szToken, '\t');
pszContent ++;
}
else if( nextCh == 'b' )
{
ADD_CHAR(szToken, '\b');
pszContent ++;
}
else if( nextCh == '(' || nextCh == ')' || nextCh == '\\' )
{
ADD_CHAR(szToken, nextCh);
pszContent ++;
}
else if( nextCh >= '0' && nextCh <= '7' &&
pszContent[2] >= '0' && pszContent[2] <= '7' &&
pszContent[3] >= '0' && pszContent[3] <= '7' )
{
ADD_CHAR(szToken,
((nextCh - '\0') * 64 + (pszContent[2] - '\0') * 8 + pszContent[3] - '\0'));
pszContent += 3;
}
else if( nextCh == '\n' )
{
if( pszContent[2] == '\r' )
pszContent += 2;
else
pszContent ++;
}
else if( nextCh == '\r' )
{
pszContent ++;
}
}
else if (ch == '<' && pszContent[1] == '<' && nTokenSize == 0)
{
int nDictDepth = 0;
while(*pszContent != '\0')
{
if (pszContent[0] == '<' && pszContent[1] == '<')
{
ADD_CHAR(szToken, '<');
ADD_CHAR(szToken, '<');
nDictDepth ++;
pszContent += 2;
}
else if (pszContent[0] == '>' && pszContent[1] == '>')
{
ADD_CHAR(szToken, '>');
ADD_CHAR(szToken, '>');
nDictDepth --;
pszContent += 2;
if (nDictDepth == 0)
break;
}
else
{
ADD_CHAR(szToken, *pszContent);
pszContent ++;
}
}
if (nDictDepth == 0)
{
bPushToken = TRUE;
pszContent --;
}
else
break;
}
else
{
// Do not create too long tokens in arrays, that we will ignore
// anyway
if( nArrayLevel == 0 || nTokenSize == 0 )
{
ADD_CHAR(szToken, ch);
}
}
pszContent ++;
if (pszContent[0] == '\0')
bPushToken = TRUE;
#define EQUAL1(szToken, s) (szToken[0] == s[0] && szToken[1] == '\0')
#define EQUAL2(szToken, s) (szToken[0] == s[0] && szToken[1] == s[1] && szToken[2] == '\0')
#define EQUAL3(szToken, s) (szToken[0] == s[0] && szToken[1] == s[1] && szToken[2] == s[2] && szToken[3] == '\0')
if (bPushToken && nTokenSize)
{
if (EQUAL2(szToken, "BI"))
{
while(*pszContent != '\0')
{
if( pszContent[0] == 'E' && pszContent[1] == 'I' && pszContent[2] == ' ' )
{
break;
}
pszContent ++;
}
if( pszContent[0] == 'E' )
pszContent += 3;
else
return nullptr;
}
else if (EQUAL3(szToken, "BDC"))
{
if (nTokenStackSize < 2)
{
CPLDebug("PDF",
"not enough arguments for %s",
szToken);
return nullptr;
}
nTokenStackSize -= 2;
const char* pszOC = aszTokenStack[nTokenStackSize];
const char* pszOCGName = aszTokenStack[nTokenStackSize+1];
nBDCLevel ++;
if( EQUAL3(pszOC, "/OC") && pszOCGName[0] == '/' )
{
std::map<CPLString, OGRPDFLayer*>::iterator oIter =
oMapPropertyToLayer.find(pszOCGName + 1);
if( oIter != oMapPropertyToLayer.end() )
{
poCurLayer = oIter->second;
//CPLDebug("PDF", "Cur layer : %s", poCurLayer->GetName());
}
}
oLayerStack.push(poCurLayer);
//CPLDebug("PDF", "%s %s BDC", osOC.c_str(), osOCGName.c_str());
}
else if (EQUAL3(szToken, "EMC"))
{
//CPLDebug("PDF", "EMC");
if( !oLayerStack.empty() )
{
oLayerStack.pop();
if( !oLayerStack.empty() )
poCurLayer = oLayerStack.top();
else
poCurLayer = nullptr;
/*if (poCurLayer)
{
CPLDebug("PDF", "Cur layer : %s", poCurLayer->GetName());
}*/
}
else
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
poCurLayer = nullptr;
//return NULL;
}
nBDCLevel --;
if (nBDCLevel == 0 && bInitBDCStack)
break;
}
/* Ignore any text stuff */
else if (EQUAL2(szToken, "BT"))
nBTLevel ++;
else if (EQUAL2(szToken, "ET"))
{
nBTLevel --;
if (nBTLevel < 0)
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
}
else if (!nArrayLevel && !nBTLevel)
{
int bEmitFeature = FALSE;
if( szToken[0] < 'A' )
{
PUSH(aszTokenStack, szToken, nTokenSize);
}
else if (EQUAL1(szToken, "q"))
{
oGSStack.push(oGS);
}
else if (EQUAL1(szToken, "Q"))
{
if (oGSStack.empty())
{
CPLDebug("PDF", "not enough arguments for %s", szToken);
return nullptr;
}
oGS = oGSStack.top();
oGSStack.pop();
if (oGSStack.empty() && bMatchQ)
break;
}
else if (EQUAL2(szToken, "cm"))
{
double adfMatrix[6];
if (!UnstackTokens(szToken, 6, aszTokenStack, nTokenStackSize, adfMatrix))
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
oGS.MultiplyBy(adfMatrix);
}
else if (EQUAL1(szToken, "b") || /* closepath, fill, stroke */
EQUAL2(szToken, "b*") /* closepath, eofill, stroke */)
{
if (!(!oCoords.empty() &&
oCoords[oCoords.size() - 2] == CLOSE_SUBPATH &&
oCoords.back() == CLOSE_SUBPATH))
{
oCoords.push_back(CLOSE_SUBPATH);
oCoords.push_back(CLOSE_SUBPATH);
}
oCoords.push_back(FILL_SUBPATH);
oCoords.push_back(FILL_SUBPATH);
bHasFoundFill = TRUE;
bEmitFeature = TRUE;
}
else if (EQUAL1(szToken, "B") || /* fill, stroke */
EQUAL2(szToken, "B*") || /* eofill, stroke */
EQUAL1(szToken, "f") || /* fill */
EQUAL1(szToken, "F") || /* fill */
EQUAL2(szToken, "f*") /* eofill */ )
{
oCoords.push_back(FILL_SUBPATH);
oCoords.push_back(FILL_SUBPATH);
bHasFoundFill = TRUE;
bEmitFeature = TRUE;
}
else if (EQUAL1(szToken, "h")) /* close subpath */
{
if (!(!oCoords.empty() &&
oCoords[oCoords.size() - 2] == CLOSE_SUBPATH &&
oCoords.back() == CLOSE_SUBPATH))
{
oCoords.push_back(CLOSE_SUBPATH);
oCoords.push_back(CLOSE_SUBPATH);
}
}
else if (EQUAL1(szToken, "n")) /* new subpath without stroking or filling */
{
oCoords.resize(0);
}
else if (EQUAL1(szToken, "s")) /* close and stroke */
{
if (!(!oCoords.empty() &&
oCoords[oCoords.size() - 2] == CLOSE_SUBPATH &&
oCoords.back() == CLOSE_SUBPATH))
{
oCoords.push_back(CLOSE_SUBPATH);
oCoords.push_back(CLOSE_SUBPATH);
}
bEmitFeature = TRUE;
}
else if (EQUAL1(szToken, "S")) /* stroke */
{
bEmitFeature = TRUE;
}
else if (EQUAL1(szToken, "m") || EQUAL1(szToken, "l"))
{
double adfCoords[2];
if (!UnstackTokens(szToken, 2, aszTokenStack, nTokenStackSize, adfCoords))
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
if (EQUAL1(szToken, "m"))
{
if (!oCoords.empty())
bHasMultiPart = TRUE;
oCoords.push_back(NEW_SUBPATH);
oCoords.push_back(NEW_SUBPATH);
}
oGS.ApplyMatrix(adfCoords);
oCoords.push_back(adfCoords[0]);
oCoords.push_back(adfCoords[1]);
}
else if (EQUAL1(szToken, "c")) /* Bezier curve */
{
double adfCoords[6];
if (!UnstackTokens(szToken, 6, aszTokenStack, nTokenStackSize, adfCoords))
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
oGS.ApplyMatrix(adfCoords + 0);
oGS.ApplyMatrix(adfCoords + 2);
oGS.ApplyMatrix(adfCoords + 4);
AddBezierCurve(oCoords,
oCoords.empty() ? &adfCoords[0] : &oCoords[oCoords.size()-2],
&adfCoords[0],
&adfCoords[2],
&adfCoords[4]);
}
else if (EQUAL1(szToken, "v")) /* Bezier curve */
{
double adfCoords[4];
if (!UnstackTokens(szToken, 4, aszTokenStack, nTokenStackSize, adfCoords))
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
oGS.ApplyMatrix(adfCoords + 0);
oGS.ApplyMatrix(adfCoords + 2);
AddBezierCurve(oCoords,
oCoords.empty() ? &adfCoords[0] : &oCoords[oCoords.size()-2],
oCoords.empty() ? &adfCoords[0] : &oCoords[oCoords.size()-2],
&adfCoords[0],
&adfCoords[2]);
}
else if (EQUAL1(szToken, "y")) /* Bezier curve */
{
double adfCoords[4];
if (!UnstackTokens(szToken, 4, aszTokenStack, nTokenStackSize, adfCoords))
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
oGS.ApplyMatrix(adfCoords + 0);
oGS.ApplyMatrix(adfCoords + 2);
AddBezierCurve(oCoords,
oCoords.empty() ? &adfCoords[0] : &oCoords[oCoords.size()-2],
&adfCoords[0],
&adfCoords[2],
&adfCoords[2]);
}
else if (EQUAL2(szToken, "re")) /* Rectangle */
{
double adfCoords[4];
if (!UnstackTokens(szToken, 4, aszTokenStack, nTokenStackSize, adfCoords))
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
adfCoords[2] += adfCoords[0];
adfCoords[3] += adfCoords[1];
oGS.ApplyMatrix(adfCoords);
oGS.ApplyMatrix(adfCoords + 2);
if (!oCoords.empty())
bHasMultiPart = TRUE;
oCoords.push_back(NEW_SUBPATH);
oCoords.push_back(NEW_SUBPATH);
oCoords.push_back(adfCoords[0]);
oCoords.push_back(adfCoords[1]);
oCoords.push_back(adfCoords[2]);
oCoords.push_back(adfCoords[1]);
oCoords.push_back(adfCoords[2]);
oCoords.push_back(adfCoords[3]);
oCoords.push_back(adfCoords[0]);
oCoords.push_back(adfCoords[3]);
oCoords.push_back(CLOSE_SUBPATH);
oCoords.push_back(CLOSE_SUBPATH);
}
else if (EQUAL2(szToken, "Do"))
{
if (nTokenStackSize == 0)
{
CPLDebug("PDF",
"not enough arguments for %s",
szToken);
return nullptr;
}
CPLString osObjectName = aszTokenStack[--nTokenStackSize];
if (osObjectName[0] != '/')
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
if (poResources == nullptr)
{
if (osObjectName.find("/SymImage") == 0)
{
oCoords.push_back(oGS.adfCM[4] + oGS.adfCM[0] / 2);
oCoords.push_back(oGS.adfCM[5] + oGS.adfCM[3] / 2);
szToken[0] = '\0';
nTokenSize = 0;
if( poCurLayer != nullptr)
bEmitFeature = TRUE;
else
continue;
}
else
{
//CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
}
if( !bEmitFeature )
{
GDALPDFObject* poXObject =
poResources->GetDictionary()->Get("XObject");
if (poXObject == nullptr ||
poXObject->GetType() != PDFObjectType_Dictionary)
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
GDALPDFObject* poObject =
poXObject->GetDictionary()->Get(osObjectName.c_str() + 1);
if (poObject == nullptr)
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
int bParseStream = TRUE;
/* Check if the object is an image. If so, no need to try to parse */
/* it. */
if (poObject->GetType() == PDFObjectType_Dictionary)
{
GDALPDFObject* poSubtype = poObject->GetDictionary()->Get("Subtype");
if (poSubtype != nullptr &&
poSubtype->GetType() == PDFObjectType_Name &&
poSubtype->GetName() == "Image" )
{
bParseStream = FALSE;
}
}
if( bParseStream )
{
GDALPDFStream* poStream = poObject->GetStream();
if (!poStream)
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
char* pszStr = poStream->GetBytes();
if( pszStr )
{
OGRGeometry* poGeom = ParseContent(pszStr, nullptr, FALSE, FALSE,
oMapPropertyToLayer, poCurLayer);
CPLFree(pszStr);
if (poGeom && !bCollectAllObjects)
return poGeom;
delete poGeom;
}
}
}
}
else if( EQUAL2(szToken, "RG") || EQUAL2(szToken, "rg") )
{
double* padf = ( EQUAL2(szToken, "RG") ) ? &oGS.adfStrokeColor[0] : &oGS.adfFillColor[0];
if (!UnstackTokens(szToken, 3, aszTokenStack, nTokenStackSize, padf))
{
CPLDebug("PDF", "Should not happen at line %d", __LINE__);
return nullptr;
}
}
else if (oMapOperators.find(szToken) != oMapOperators.end())
{
int nArgs = oMapOperators[szToken];
if (nArgs < 0)
{
while( nTokenStackSize != 0 )
{
CPLString osTopToken = aszTokenStack[--nTokenStackSize];
if (oMapOperators.find(osTopToken) != oMapOperators.end())
break;
}
}
else
{
if( nArgs > nTokenStackSize )
{
CPLDebug("PDF",
"not enough arguments for %s",
szToken);
return nullptr;
}
nTokenStackSize -= nArgs;
}
}
else
{
PUSH(aszTokenStack, szToken, nTokenSize);
}
if( bEmitFeature && poCurLayer != nullptr)
{
OGRGeometry* poGeom = BuildGeometry(oCoords, bHasFoundFill, bHasMultiPart);
bHasFoundFill = FALSE;
bHasMultiPart = FALSE;
if (poGeom)
{
OGRFeature* poFeature = new OGRFeature(poCurLayer->GetLayerDefn());
if( bSetStyle )
{
OGRwkbGeometryType eType = wkbFlatten(poGeom->getGeometryType());
if( eType == wkbLineString || eType == wkbMultiLineString )
{
poFeature->SetStyleString(CPLSPrintf("PEN(c:#%02X%02X%02X)",
(int)(oGS.adfStrokeColor[0] * 255 + 0.5),
(int)(oGS.adfStrokeColor[1] * 255 + 0.5),
(int)(oGS.adfStrokeColor[2] * 255 + 0.5)));
}
else if( eType == wkbPolygon || eType == wkbMultiPolygon )
{
poFeature->SetStyleString(CPLSPrintf("PEN(c:#%02X%02X%02X);BRUSH(fc:#%02X%02X%02X)",
(int)(oGS.adfStrokeColor[0] * 255 + 0.5),
(int)(oGS.adfStrokeColor[1] * 255 + 0.5),
(int)(oGS.adfStrokeColor[2] * 255 + 0.5),
(int)(oGS.adfFillColor[0] * 255 + 0.5),
(int)(oGS.adfFillColor[1] * 255 + 0.5),
(int)(oGS.adfFillColor[2] * 255 + 0.5)));
}
}
poGeom->assignSpatialReference(poCurLayer->GetSpatialRef());
poFeature->SetGeometryDirectly(poGeom);
CPL_IGNORE_RET_VAL(poCurLayer->CreateFeature(poFeature));
delete poFeature;
}
oCoords.resize(0);
}
}
szToken[0] = '\0';
nTokenSize = 0;
}
}
if (nTokenStackSize != 0)
{
while(nTokenStackSize != 0)
{
nTokenStackSize--;
CPLDebug("PDF",
"Remaining values in stack : %s",
aszTokenStack[nTokenStackSize]);
}
return nullptr;
}
if (bCollectAllObjects)
return nullptr;
return BuildGeometry(oCoords, bHasFoundFill, bHasMultiPart);
}
/************************************************************************/
/* BuildGeometry() */
/************************************************************************/
OGRGeometry* PDFDataset::BuildGeometry(std::vector<double>& oCoords,
int bHasFoundFill,
int bHasMultiPart)
{
OGRGeometry* poGeom = nullptr;
if (!oCoords.size())
return nullptr;
if (oCoords.size() == 2)
{
double X, Y;
PDFCoordsToSRSCoords(oCoords[0], oCoords[1], X, Y);
poGeom = new OGRPoint(X, Y);
}
else if (!bHasFoundFill)
{
OGRLineString* poLS = nullptr;
OGRMultiLineString* poMLS = nullptr;
if (bHasMultiPart)
{
poMLS = new OGRMultiLineString();
poGeom = poMLS;
}
for(size_t i=0;i<oCoords.size();i+=2)
{
if (oCoords[i] == NEW_SUBPATH && oCoords[i+1] == NEW_SUBPATH)
{
if (poMLS)
{
poLS = new OGRLineString();
poMLS->addGeometryDirectly(poLS);
}
else
{
delete poLS;
poLS = new OGRLineString();
poGeom = poLS;
}
}
else if (oCoords[i] == CLOSE_SUBPATH && oCoords[i+1] == CLOSE_SUBPATH)
{
if (poLS && poLS->getNumPoints() >= 2 &&
!(poLS->getX(0) == poLS->getX(poLS->getNumPoints()-1) &&
poLS->getY(0) == poLS->getY(poLS->getNumPoints()-1)))
{
poLS->addPoint(poLS->getX(0), poLS->getY(0));
}
}
else if (oCoords[i] == FILL_SUBPATH && oCoords[i+1] == FILL_SUBPATH)
{
/* Should not happen */
}
else
{
if (poLS)
{
double X, Y;
PDFCoordsToSRSCoords(oCoords[i], oCoords[i+1], X, Y);
poLS->addPoint(X, Y);
}
}
}
// Recognize points as written by GDAL (ogr-sym-2 : circle (not filled))
OGRGeometry* poCenter = nullptr;
if (poCenter == nullptr && poLS != nullptr && poLS->getNumPoints() == 1 + BEZIER_STEPS * 4 )
{
poCenter = PDFGetCircleCenter(poLS);
}
// Recognize points as written by GDAL (ogr-sym-4: square (not filled))
if (poCenter == nullptr && poLS != nullptr && (poLS->getNumPoints() == 4 || poLS->getNumPoints() == 5))
{
poCenter = PDFGetSquareCenter(poLS);
}
// Recognize points as written by GDAL (ogr-sym-6: triangle (not filled))
if (poCenter == nullptr && poLS != nullptr && (poLS->getNumPoints() == 3 || poLS->getNumPoints() == 4))
{
poCenter = PDFGetTriangleCenter(poLS);
}
// Recognize points as written by GDAL (ogr-sym-8: star (not filled))
if (poCenter == nullptr && poLS != nullptr && (poLS->getNumPoints() == 10 || poLS->getNumPoints() == 11))
{
poCenter = PDFGetStarCenter(poLS);
}
if (poCenter == nullptr && poMLS != nullptr && poMLS->getNumGeometries() == 2)
{
OGRLineString* poLS1 = poMLS->getGeometryRef(0)->toLineString();
OGRLineString* poLS2 = poMLS->getGeometryRef(1)->toLineString();
// Recognize points as written by GDAL (ogr-sym-0: cross (+) ).
if (poLS1->getNumPoints() == 2 && poLS2->getNumPoints() == 2 &&
poLS1->getY(0) == poLS1->getY(1) &&
poLS2->getX(0) == poLS2->getX(1) &&
fabs(fabs(poLS1->getX(0) - poLS1->getX(1)) - fabs(poLS2->getY(0) - poLS2->getY(1))) < EPSILON &&
fabs((poLS1->getX(0) + poLS1->getX(1)) / 2 - poLS2->getX(0)) < EPSILON &&
fabs((poLS2->getY(0) + poLS2->getY(1)) / 2 - poLS1->getY(0)) < EPSILON)
{
poCenter = new OGRPoint(poLS2->getX(0), poLS1->getY(0));
}
// Recognize points as written by GDAL (ogr-sym-1: diagcross (X) ).
else if (poLS1->getNumPoints() == 2 && poLS2->getNumPoints() == 2 &&
poLS1->getX(0) == poLS2->getX(0) &&
poLS1->getY(0) == poLS2->getY(1) &&
poLS1->getX(1) == poLS2->getX(1) &&
poLS1->getY(1) == poLS2->getY(0) &&
fabs(fabs(poLS1->getX(0) - poLS1->getX(1)) - fabs(poLS1->getY(0) - poLS1->getY(1))) < EPSILON)
{
poCenter = new OGRPoint((poLS1->getX(0) + poLS1->getX(1)) / 2,
(poLS1->getY(0) + poLS1->getY(1)) / 2);
}
}
if (poCenter)
{
delete poGeom;
poGeom = poCenter;
}
}
else
{
OGRLinearRing* poLS = nullptr;
int nPolys = 0;
OGRGeometry** papoPoly = nullptr;
for(size_t i=0;i<oCoords.size();i+=2)
{
if (oCoords[i] == NEW_SUBPATH && oCoords[i+1] == NEW_SUBPATH)
{
if (poLS && poLS->getNumPoints() >= 3)
{
OGRPolygon* poPoly = new OGRPolygon();
poPoly->addRingDirectly(poLS);
poLS = nullptr;
papoPoly = (OGRGeometry**) CPLRealloc(papoPoly, (nPolys + 1) * sizeof(OGRGeometry*));
papoPoly[nPolys ++] = poPoly;
}
delete poLS;
poLS = new OGRLinearRing();
}
else if ((oCoords[i] == CLOSE_SUBPATH && oCoords[i+1] == CLOSE_SUBPATH) ||
(oCoords[i] == FILL_SUBPATH && oCoords[i+1] == FILL_SUBPATH))
{
if (poLS)
{
poLS->closeRings();
std::unique_ptr<OGRPoint> poCenter;
if (nPolys == 0 &&
poLS &&
poLS->getNumPoints() == 1 + BEZIER_STEPS * 4 )
{
// Recognize points as written by GDAL (ogr-sym-3 : circle (filled))
poCenter.reset(PDFGetCircleCenter(poLS));
}
if (nPolys == 0 &&
poCenter == nullptr &&
poLS &&
poLS->getNumPoints() == 5)
{
// Recognize points as written by GDAL (ogr-sym-5: square (filled))
poCenter.reset(PDFGetSquareCenter(poLS));
/* ESRI points */
if (poCenter == nullptr &&
oCoords.size() == 14 &&
poLS->getY(0) == poLS->getY(1) &&
poLS->getX(1) == poLS->getX(2) &&
poLS->getY(2) == poLS->getY(3) &&
poLS->getX(3) == poLS->getX(0))
{
poCenter.reset(new OGRPoint((poLS->getX(0) + poLS->getX(1)) / 2,
(poLS->getY(0) + poLS->getY(2)) / 2));
}
}
// Recognize points as written by GDAL (ogr-sym-7: triangle (filled))
else if (nPolys == 0 &&
poLS &&
poLS->getNumPoints() == 4)
{
poCenter.reset(PDFGetTriangleCenter(poLS));
}
// Recognize points as written by GDAL (ogr-sym-9: star (filled))
else if (nPolys == 0 &&
poLS &&
poLS->getNumPoints() == 11)
{
poCenter.reset(PDFGetStarCenter(poLS));
}
if (poCenter)
{
delete poGeom;
poGeom = poCenter.release();
break;
}
if (poLS->getNumPoints() >= 3)
{
OGRPolygon* poPoly = new OGRPolygon();
poPoly->addRingDirectly(poLS);
poLS = nullptr;
papoPoly = (OGRGeometry**) CPLRealloc(papoPoly, (nPolys + 1) * sizeof(OGRGeometry*));
papoPoly[nPolys ++] = poPoly;
}
else
{
delete poLS;
poLS = nullptr;
}
}
}
else
{
if (poLS)
{
double X, Y;
PDFCoordsToSRSCoords(oCoords[i], oCoords[i+1], X, Y);
poLS->addPoint(X, Y);
}
}
}
delete poLS;
int bIsValidGeometry;
if (nPolys == 2 &&
papoPoly[0]->toPolygon()->getNumInteriorRings() == 0 &&
papoPoly[1]->toPolygon()->getNumInteriorRings() == 0)
{
OGRLinearRing* poRing0 = papoPoly[0]->toPolygon()->getExteriorRing();
OGRLinearRing* poRing1 = papoPoly[1]->toPolygon()->getExteriorRing();
if (poRing0->getNumPoints() == poRing1->getNumPoints())
{
int bSameRing = TRUE;
for(int i=0;i<poRing0->getNumPoints();i++)
{
if (poRing0->getX(i) != poRing1->getX(i))
{
bSameRing = FALSE;
break;
}
if (poRing0->getY(i) != poRing1->getY(i))
{
bSameRing = FALSE;
break;
}
}
/* Just keep on ring if they are identical */
if (bSameRing)
{
delete papoPoly[1];
nPolys = 1;
}
}
}
if (nPolys)
{
poGeom = OGRGeometryFactory::organizePolygons(
papoPoly, nPolys, &bIsValidGeometry, nullptr);
}
CPLFree(papoPoly);
}
return poGeom;
}
/************************************************************************/
/* ExploreContents() */
/************************************************************************/
void PDFDataset::ExploreContents(GDALPDFObject* poObj,
GDALPDFObject* poResources,
int nDepth,
int& nVisited,
bool& bStop)
{
std::map<CPLString, OGRPDFLayer*> oMapPropertyToLayer;
if( nDepth == 10 || nVisited == 1000 )
{
CPLError(CE_Failure, CPLE_AppDefined,
"ExploreContents(): too deep exploration or too many items");
bStop = true;
return;
}
if( bStop )
return;
if (poObj->GetType() == PDFObjectType_Array)
{
GDALPDFArray* poArray = poObj->GetArray();
for(int i=0;i<poArray->GetLength();i++)
{
GDALPDFObject* poSubObj = poArray->Get(i);
if( poSubObj )
{
nVisited ++;
ExploreContents(poSubObj, poResources, nDepth + 1, nVisited, bStop);
if( bStop )
return;
}
}
}
if (poObj->GetType() != PDFObjectType_Dictionary)
return;
GDALPDFStream* poStream = poObj->GetStream();
if (!poStream)
return;
char* pszStr = poStream->GetBytes();
if (!pszStr)
return;
const char* pszMCID = (const char*) pszStr;
while((pszMCID = strstr(pszMCID, "/MCID")) != nullptr)
{
const char* pszBDC = strstr(pszMCID, "BDC");
if (pszBDC)
{
/* Hack for http://www.avenza.com/sites/default/files/spatialpdf/US_County_Populations.pdf */
/* FIXME: that logic is too fragile. */
const char* pszStartParsing = pszBDC;
const char* pszAfterBDC = pszBDC + 3;
int bMatchQ = FALSE;
while (pszAfterBDC[0] == ' ' || pszAfterBDC[0] == '\r' || pszAfterBDC[0] == '\n')
pszAfterBDC ++;
if (STARTS_WITH(pszAfterBDC, "0 0 m"))
{
const char* pszLastq = pszBDC;
while(pszLastq > pszStr && *pszLastq != 'q')
pszLastq --;
if (pszLastq > pszStr && *pszLastq == 'q' &&
(pszLastq[-1] == ' ' || pszLastq[-1] == '\r' || pszLastq[-1] == '\n') &&
(pszLastq[1] == ' ' || pszLastq[1] == '\r' || pszLastq[1] == '\n'))
{
pszStartParsing = pszLastq;
bMatchQ = TRUE;
}
}
int nMCID = atoi(pszMCID + 6);
if (GetGeometryFromMCID(nMCID) == nullptr)
{
OGRGeometry* poGeom = ParseContent(pszStartParsing, poResources,
!bMatchQ, bMatchQ, oMapPropertyToLayer, nullptr);
if( poGeom != nullptr )
{
/* Save geometry in map */
oMapMCID[nMCID] = poGeom;
}
}
}
pszMCID += 5;
}
CPLFree(pszStr);
}
/************************************************************************/
/* ExploreContentsNonStructured() */
/************************************************************************/
void PDFDataset::ExploreContentsNonStructuredInternal(GDALPDFObject* poContents,
GDALPDFObject* poResources,
std::map<CPLString, OGRPDFLayer*>& oMapPropertyToLayer,
OGRPDFLayer* poSingleLayer)
{
if (poContents->GetType() == PDFObjectType_Array)
{
GDALPDFArray* poArray = poContents->GetArray();
char* pszConcatStr = nullptr;
int nConcatLen = 0;
for(int i=0;i<poArray->GetLength();i++)
{
GDALPDFObject* poObj = poArray->Get(i);
if( poObj == nullptr || poObj->GetType() != PDFObjectType_Dictionary)
break;
GDALPDFStream* poStream = poObj->GetStream();
if (!poStream)
break;
char* pszStr = poStream->GetBytes();
if (!pszStr)
break;
int nLen = (int)strlen(pszStr);
char* pszConcatStrNew = (char*)CPLRealloc(pszConcatStr, nConcatLen + nLen + 1);
if( pszConcatStrNew == nullptr )
{
CPLFree(pszStr);
break;
}
pszConcatStr = pszConcatStrNew;
memcpy(pszConcatStr + nConcatLen, pszStr, nLen+1);
nConcatLen += nLen;
CPLFree(pszStr);
}
if( pszConcatStr )
ParseContent(pszConcatStr, poResources, FALSE, FALSE, oMapPropertyToLayer, poSingleLayer);
CPLFree(pszConcatStr);
return;
}
if (poContents->GetType() != PDFObjectType_Dictionary)
return;
GDALPDFStream* poStream = poContents->GetStream();
if (!poStream)
return;
char* pszStr = poStream->GetBytes();
if( !pszStr )
return;
ParseContent(pszStr, poResources, FALSE, FALSE, oMapPropertyToLayer, poSingleLayer);
CPLFree(pszStr);
}
void PDFDataset::ExploreContentsNonStructured(GDALPDFObject* poContents,
GDALPDFObject* poResources)
{
std::map<CPLString, OGRPDFLayer*> oMapPropertyToLayer;
if (poResources != nullptr &&
poResources->GetType() == PDFObjectType_Dictionary)
{
GDALPDFObject* poProperties =
poResources->GetDictionary()->Get("Properties");
if (poProperties != nullptr &&
poProperties->GetType() == PDFObjectType_Dictionary)
{
std::map< std::pair<int, int>, OGRPDFLayer *> oMapNumGenToLayer;
for(const auto& oLayerWithref: aoLayerWithRef )
{
CPLString osSanitizedName(PDFSanitizeLayerName(oLayerWithref.osName));
OGRPDFLayer* poLayer = (OGRPDFLayer*) GetLayerByName(osSanitizedName.c_str());
if (poLayer == nullptr)
{
auto poSRSOri = GetSpatialRef();
OGRSpatialReference* poSRS = poSRSOri ? poSRSOri->Clone() : nullptr;
poLayer =
new OGRPDFLayer(this, osSanitizedName.c_str(), poSRS, wkbUnknown);
if( poSRS )
poSRS->Release();
papoLayers = (OGRLayer**)
CPLRealloc(papoLayers, (nLayers + 1) * sizeof(OGRLayer*));
papoLayers[nLayers] = poLayer;
nLayers ++;
}
oMapNumGenToLayer[ std::pair<int,int>(oLayerWithref.nOCGNum.toInt(), oLayerWithref.nOCGGen) ] = poLayer;
}
std::map<CPLString, GDALPDFObject*>& oMap =
poProperties->GetDictionary()->GetValues();
std::map<CPLString, GDALPDFObject*>::iterator oIter = oMap.begin();
std::map<CPLString, GDALPDFObject*>::iterator oEnd = oMap.end();
for(; oIter != oEnd; ++oIter)
{
const char* pszKey = oIter->first.c_str();
GDALPDFObject* poObj = oIter->second;
if( poObj->GetRefNum().toBool() )
{
std::map< std::pair<int, int>, OGRPDFLayer *>::iterator
oIterNumGenToLayer = oMapNumGenToLayer.find(
std::pair<int,int>(poObj->GetRefNum().toInt(), poObj->GetRefGen()) );
if( oIterNumGenToLayer != oMapNumGenToLayer.end() )
{
oMapPropertyToLayer[pszKey] = oIterNumGenToLayer->second;
}
}
}
}
}
OGRPDFLayer* poSingleLayer = nullptr;
if( nLayers == 0 )
{
if( CPLTestBool(CPLGetConfigOption("OGR_PDF_READ_NON_STRUCTURED", "NO")) )
{
OGRPDFLayer *poLayer =
new OGRPDFLayer(this, "content", nullptr, wkbUnknown);
papoLayers = (OGRLayer**)
CPLRealloc(papoLayers, (nLayers + 1) * sizeof(OGRLayer*));
papoLayers[nLayers] = poLayer;
nLayers ++;
poSingleLayer = poLayer;
}
else
{
return;
}
}
ExploreContentsNonStructuredInternal(poContents,
poResources,
oMapPropertyToLayer,
poSingleLayer);
/* Remove empty layers */
int i = 0;
while(i < nLayers)
{
if (papoLayers[i]->GetFeatureCount() == 0)
{
delete papoLayers[i];
if (i < nLayers - 1)
{
memmove(papoLayers + i, papoLayers + i + 1,
(nLayers - 1 - i) * sizeof(OGRPDFLayer*));
}
nLayers --;
}
else
i ++;
}
}
#endif /* HAVE_PDF_READ_SUPPORT */
|
{
"pile_set_name": "Github"
}
|
package com.mossle.cms.persistence.manager;
import com.mossle.cms.persistence.domain.CommentVoter;
import com.mossle.core.hibernate.HibernateEntityDao;
import org.springframework.stereotype.Service;
@Service
public class CommentVoterManager extends HibernateEntityDao<CommentVoter> {
}
|
{
"pile_set_name": "Github"
}
|
# SPDX-License-Identifier: Apache-2.0
if(DEFINED TOOLCHAIN_HOME)
set(find_program_clang_args PATHS ${TOOLCHAIN_HOME} NO_DEFAULT_PATH)
endif()
find_program(CMAKE_C_COMPILER clang ${find_program_clang_args})
|
{
"pile_set_name": "Github"
}
|
// boost integer.hpp header file -------------------------------------------//
// Copyright Beman Dawes and Daryle Walker 1999. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/integer for documentation.
// Revision History
// 22 Sep 01 Added value-based integer templates. (Daryle Walker)
// 01 Apr 01 Modified to use new <boost/limits.hpp> header. (John Maddock)
// 30 Jul 00 Add typename syntax fix (Jens Maurer)
// 28 Aug 99 Initial version
#ifndef BOOST_INTEGER_HPP
#define BOOST_INTEGER_HPP
#include <boost/integer_fwd.hpp> // self include
#include <boost/integer_traits.hpp> // for boost::::boost::integer_traits
#include <boost/limits.hpp> // for ::std::numeric_limits
#include <boost/cstdint.hpp> // for boost::int64_t and BOOST_NO_INTEGRAL_INT64_T
#include <boost/static_assert.hpp>
//
// We simply cannot include this header on gcc without getting copious warnings of the kind:
//
// boost/integer.hpp:77:30: warning: use of C99 long long integer constant
//
// And yet there is no other reasonable implementation, so we declare this a system header
// to suppress these warnings.
//
#if defined(__GNUC__) && (__GNUC__ >= 4)
#pragma GCC system_header
#endif
namespace boost
{
// Helper templates ------------------------------------------------------//
// fast integers from least integers
// int_fast_t<> works correctly for unsigned too, in spite of the name.
template< typename LeastInt >
struct int_fast_t
{
typedef LeastInt fast;
typedef fast type;
}; // imps may specialize
namespace detail{
// convert category to type
template< int Category > struct int_least_helper {}; // default is empty
template< int Category > struct uint_least_helper {}; // default is empty
// specializatons: 1=long, 2=int, 3=short, 4=signed char,
// 6=unsigned long, 7=unsigned int, 8=unsigned short, 9=unsigned char
// no specializations for 0 and 5: requests for a type > long are in error
#ifdef BOOST_HAS_LONG_LONG
template<> struct int_least_helper<1> { typedef boost::long_long_type least; };
#elif defined(BOOST_HAS_MS_INT64)
template<> struct int_least_helper<1> { typedef __int64 least; };
#endif
template<> struct int_least_helper<2> { typedef long least; };
template<> struct int_least_helper<3> { typedef int least; };
template<> struct int_least_helper<4> { typedef short least; };
template<> struct int_least_helper<5> { typedef signed char least; };
#ifdef BOOST_HAS_LONG_LONG
template<> struct uint_least_helper<1> { typedef boost::ulong_long_type least; };
#elif defined(BOOST_HAS_MS_INT64)
template<> struct uint_least_helper<1> { typedef unsigned __int64 least; };
#endif
template<> struct uint_least_helper<2> { typedef unsigned long least; };
template<> struct uint_least_helper<3> { typedef unsigned int least; };
template<> struct uint_least_helper<4> { typedef unsigned short least; };
template<> struct uint_least_helper<5> { typedef unsigned char least; };
template <int Bits>
struct exact_signed_base_helper{};
template <int Bits>
struct exact_unsigned_base_helper{};
template <> struct exact_signed_base_helper<sizeof(signed char)* CHAR_BIT> { typedef signed char exact; };
template <> struct exact_unsigned_base_helper<sizeof(unsigned char)* CHAR_BIT> { typedef unsigned char exact; };
#if USHRT_MAX != UCHAR_MAX
template <> struct exact_signed_base_helper<sizeof(short)* CHAR_BIT> { typedef short exact; };
template <> struct exact_unsigned_base_helper<sizeof(unsigned short)* CHAR_BIT> { typedef unsigned short exact; };
#endif
#if UINT_MAX != USHRT_MAX
template <> struct exact_signed_base_helper<sizeof(int)* CHAR_BIT> { typedef int exact; };
template <> struct exact_unsigned_base_helper<sizeof(unsigned int)* CHAR_BIT> { typedef unsigned int exact; };
#endif
#if ULONG_MAX != UINT_MAX && ( !defined __TI_COMPILER_VERSION__ || \
( __TI_COMPILER_VERSION__ >= 7000000 && !defined __TI_40BIT_LONG__ ) )
template <> struct exact_signed_base_helper<sizeof(long)* CHAR_BIT> { typedef long exact; };
template <> struct exact_unsigned_base_helper<sizeof(unsigned long)* CHAR_BIT> { typedef unsigned long exact; };
#endif
#if defined(BOOST_HAS_LONG_LONG) &&\
((defined(ULLONG_MAX) && (ULLONG_MAX != ULONG_MAX)) ||\
(defined(ULONG_LONG_MAX) && (ULONG_LONG_MAX != ULONG_MAX)) ||\
(defined(ULONGLONG_MAX) && (ULONGLONG_MAX != ULONG_MAX)) ||\
(defined(_ULLONG_MAX) && (_ULLONG_MAX != ULONG_MAX)))
template <> struct exact_signed_base_helper<sizeof(boost::long_long_type)* CHAR_BIT> { typedef boost::long_long_type exact; };
template <> struct exact_unsigned_base_helper<sizeof(boost::ulong_long_type)* CHAR_BIT> { typedef boost::ulong_long_type exact; };
#endif
} // namespace detail
// integer templates specifying number of bits ---------------------------//
// signed
template< int Bits > // bits (including sign) required
struct int_t : public boost::detail::exact_signed_base_helper<Bits>
{
BOOST_STATIC_ASSERT_MSG(Bits <= (int)(sizeof(boost::intmax_t) * CHAR_BIT),
"No suitable signed integer type with the requested number of bits is available.");
typedef typename boost::detail::int_least_helper
<
#ifdef BOOST_HAS_LONG_LONG
(Bits <= (int)(sizeof(boost::long_long_type) * CHAR_BIT)) +
#else
1 +
#endif
(Bits-1 <= ::std::numeric_limits<long>::digits) +
(Bits-1 <= ::std::numeric_limits<int>::digits) +
(Bits-1 <= ::std::numeric_limits<short>::digits) +
(Bits-1 <= ::std::numeric_limits<signed char>::digits)
>::least least;
typedef typename int_fast_t<least>::type fast;
};
// unsigned
template< int Bits > // bits required
struct uint_t : public boost::detail::exact_unsigned_base_helper<Bits>
{
BOOST_STATIC_ASSERT_MSG(Bits <= (int)(sizeof(boost::uintmax_t) * CHAR_BIT),
"No suitable unsigned integer type with the requested number of bits is available.");
#if (defined(__BORLANDC__) || defined(__CODEGEAR__)) && defined(BOOST_NO_INTEGRAL_INT64_T)
// It's really not clear why this workaround should be needed... shrug I guess! JM
BOOST_STATIC_CONSTANT(int, s =
6 +
(Bits <= ::std::numeric_limits<unsigned long>::digits) +
(Bits <= ::std::numeric_limits<unsigned int>::digits) +
(Bits <= ::std::numeric_limits<unsigned short>::digits) +
(Bits <= ::std::numeric_limits<unsigned char>::digits));
typedef typename detail::int_least_helper< ::boost::uint_t<Bits>::s>::least least;
#else
typedef typename boost::detail::uint_least_helper
<
#ifdef BOOST_HAS_LONG_LONG
(Bits <= (int)(sizeof(boost::long_long_type) * CHAR_BIT)) +
#else
1 +
#endif
(Bits <= ::std::numeric_limits<unsigned long>::digits) +
(Bits <= ::std::numeric_limits<unsigned int>::digits) +
(Bits <= ::std::numeric_limits<unsigned short>::digits) +
(Bits <= ::std::numeric_limits<unsigned char>::digits)
>::least least;
#endif
typedef typename int_fast_t<least>::type fast;
// int_fast_t<> works correctly for unsigned too, in spite of the name.
};
// integer templates specifying extreme value ----------------------------//
// signed
#if !defined(BOOST_NO_INTEGRAL_INT64_T) && !defined(BOOST_NO_INT64_T) && defined(BOOST_HAS_LONG_LONG)
template< boost::long_long_type MaxValue > // maximum value to require support
#else
template< long MaxValue > // maximum value to require support
#endif
struct int_max_value_t
{
typedef typename boost::detail::int_least_helper
<
#if !defined(BOOST_NO_INTEGRAL_INT64_T) && !defined(BOOST_NO_INT64_T) && defined(BOOST_HAS_LONG_LONG)
(MaxValue <= ::boost::integer_traits<boost::long_long_type>::const_max) +
#else
1 +
#endif
(MaxValue <= ::boost::integer_traits<long>::const_max) +
(MaxValue <= ::boost::integer_traits<int>::const_max) +
(MaxValue <= ::boost::integer_traits<short>::const_max) +
(MaxValue <= ::boost::integer_traits<signed char>::const_max)
>::least least;
typedef typename int_fast_t<least>::type fast;
};
#if !defined(BOOST_NO_INTEGRAL_INT64_T) && !defined(BOOST_NO_INT64_T) && defined(BOOST_HAS_LONG_LONG)
template< boost::long_long_type MinValue > // minimum value to require support
#else
template< long MinValue > // minimum value to require support
#endif
struct int_min_value_t
{
typedef typename boost::detail::int_least_helper
<
#if !defined(BOOST_NO_INTEGRAL_INT64_T) && !defined(BOOST_NO_INT64_T) && defined(BOOST_HAS_LONG_LONG)
(MinValue >= ::boost::integer_traits<boost::long_long_type>::const_min) +
#else
1 +
#endif
(MinValue >= ::boost::integer_traits<long>::const_min) +
(MinValue >= ::boost::integer_traits<int>::const_min) +
(MinValue >= ::boost::integer_traits<short>::const_min) +
(MinValue >= ::boost::integer_traits<signed char>::const_min)
>::least least;
typedef typename int_fast_t<least>::type fast;
};
// unsigned
#if !defined(BOOST_NO_INTEGRAL_INT64_T) && defined(BOOST_HAS_LONG_LONG)
template< boost::ulong_long_type MaxValue > // minimum value to require support
#else
template< unsigned long MaxValue > // minimum value to require support
#endif
struct uint_value_t
{
#if (defined(__BORLANDC__) || defined(__CODEGEAR__))
// It's really not clear why this workaround should be needed... shrug I guess! JM
#if defined(BOOST_NO_INTEGRAL_INT64_T)
BOOST_STATIC_CONSTANT(unsigned, which =
1 +
(MaxValue <= ::boost::integer_traits<unsigned long>::const_max) +
(MaxValue <= ::boost::integer_traits<unsigned int>::const_max) +
(MaxValue <= ::boost::integer_traits<unsigned short>::const_max) +
(MaxValue <= ::boost::integer_traits<unsigned char>::const_max));
typedef typename detail::int_least_helper< ::boost::uint_value_t<MaxValue>::which>::least least;
#else // BOOST_NO_INTEGRAL_INT64_T
BOOST_STATIC_CONSTANT(unsigned, which =
1 +
(MaxValue <= ::boost::integer_traits<boost::ulong_long_type>::const_max) +
(MaxValue <= ::boost::integer_traits<unsigned long>::const_max) +
(MaxValue <= ::boost::integer_traits<unsigned int>::const_max) +
(MaxValue <= ::boost::integer_traits<unsigned short>::const_max) +
(MaxValue <= ::boost::integer_traits<unsigned char>::const_max));
typedef typename detail::uint_least_helper< ::boost::uint_value_t<MaxValue>::which>::least least;
#endif // BOOST_NO_INTEGRAL_INT64_T
#else
typedef typename boost::detail::uint_least_helper
<
#if !defined(BOOST_NO_INTEGRAL_INT64_T) && defined(BOOST_HAS_LONG_LONG)
(MaxValue <= ::boost::integer_traits<boost::ulong_long_type>::const_max) +
#else
1 +
#endif
(MaxValue <= ::boost::integer_traits<unsigned long>::const_max) +
(MaxValue <= ::boost::integer_traits<unsigned int>::const_max) +
(MaxValue <= ::boost::integer_traits<unsigned short>::const_max) +
(MaxValue <= ::boost::integer_traits<unsigned char>::const_max)
>::least least;
#endif
typedef typename int_fast_t<least>::type fast;
};
} // namespace boost
#endif // BOOST_INTEGER_HPP
|
{
"pile_set_name": "Github"
}
|
// SPDX-License-Identifier: GPL-2.0
/*
* Miscellaneous character driver for ChromeOS Embedded Controller
*
* Copyright 2014 Google, Inc.
* Copyright 2019 Google LLC
*
* This file is a rework and part of the code is ported from
* drivers/mfd/cros_ec_dev.c that was originally written by
* Bill Richardson.
*/
#include <linux/init.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/notifier.h>
#include <linux/platform_data/cros_ec_chardev.h>
#include <linux/platform_data/cros_ec_commands.h>
#include <linux/platform_data/cros_ec_proto.h>
#include <linux/platform_device.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/uaccess.h>
#define DRV_NAME "cros-ec-chardev"
/* Arbitrary bounded size for the event queue */
#define CROS_MAX_EVENT_LEN PAGE_SIZE
struct chardev_data {
struct cros_ec_dev *ec_dev;
struct miscdevice misc;
};
struct chardev_priv {
struct cros_ec_dev *ec_dev;
struct notifier_block notifier;
wait_queue_head_t wait_event;
unsigned long event_mask;
struct list_head events;
size_t event_len;
};
struct ec_event {
struct list_head node;
size_t size;
u8 event_type;
u8 data[];
};
static int ec_get_version(struct cros_ec_dev *ec, char *str, int maxlen)
{
static const char * const current_image_name[] = {
"unknown", "read-only", "read-write", "invalid",
};
struct ec_response_get_version *resp;
struct cros_ec_command *msg;
int ret;
msg = kzalloc(sizeof(*msg) + sizeof(*resp), GFP_KERNEL);
if (!msg)
return -ENOMEM;
msg->command = EC_CMD_GET_VERSION + ec->cmd_offset;
msg->insize = sizeof(*resp);
ret = cros_ec_cmd_xfer_status(ec->ec_dev, msg);
if (ret < 0) {
snprintf(str, maxlen,
"Unknown EC version, returned error: %d\n",
msg->result);
goto exit;
}
resp = (struct ec_response_get_version *)msg->data;
if (resp->current_image >= ARRAY_SIZE(current_image_name))
resp->current_image = 3; /* invalid */
snprintf(str, maxlen, "%s\n%s\n%s\n%s\n", CROS_EC_DEV_VERSION,
resp->version_string_ro, resp->version_string_rw,
current_image_name[resp->current_image]);
ret = 0;
exit:
kfree(msg);
return ret;
}
static int cros_ec_chardev_mkbp_event(struct notifier_block *nb,
unsigned long queued_during_suspend,
void *_notify)
{
struct chardev_priv *priv = container_of(nb, struct chardev_priv,
notifier);
struct cros_ec_device *ec_dev = priv->ec_dev->ec_dev;
struct ec_event *event;
unsigned long event_bit = 1 << ec_dev->event_data.event_type;
int total_size = sizeof(*event) + ec_dev->event_size;
if (!(event_bit & priv->event_mask) ||
(priv->event_len + total_size) > CROS_MAX_EVENT_LEN)
return NOTIFY_DONE;
event = kzalloc(total_size, GFP_KERNEL);
if (!event)
return NOTIFY_DONE;
event->size = ec_dev->event_size;
event->event_type = ec_dev->event_data.event_type;
memcpy(event->data, &ec_dev->event_data.data, ec_dev->event_size);
spin_lock(&priv->wait_event.lock);
list_add_tail(&event->node, &priv->events);
priv->event_len += total_size;
wake_up_locked(&priv->wait_event);
spin_unlock(&priv->wait_event.lock);
return NOTIFY_OK;
}
static struct ec_event *cros_ec_chardev_fetch_event(struct chardev_priv *priv,
bool fetch, bool block)
{
struct ec_event *event;
int err;
spin_lock(&priv->wait_event.lock);
if (!block && list_empty(&priv->events)) {
event = ERR_PTR(-EWOULDBLOCK);
goto out;
}
if (!fetch) {
event = NULL;
goto out;
}
err = wait_event_interruptible_locked(priv->wait_event,
!list_empty(&priv->events));
if (err) {
event = ERR_PTR(err);
goto out;
}
event = list_first_entry(&priv->events, struct ec_event, node);
list_del(&event->node);
priv->event_len -= sizeof(*event) + event->size;
out:
spin_unlock(&priv->wait_event.lock);
return event;
}
/*
* Device file ops
*/
static int cros_ec_chardev_open(struct inode *inode, struct file *filp)
{
struct miscdevice *mdev = filp->private_data;
struct cros_ec_dev *ec_dev = dev_get_drvdata(mdev->parent);
struct chardev_priv *priv;
int ret;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->ec_dev = ec_dev;
filp->private_data = priv;
INIT_LIST_HEAD(&priv->events);
init_waitqueue_head(&priv->wait_event);
nonseekable_open(inode, filp);
priv->notifier.notifier_call = cros_ec_chardev_mkbp_event;
ret = blocking_notifier_chain_register(&ec_dev->ec_dev->event_notifier,
&priv->notifier);
if (ret) {
dev_err(ec_dev->dev, "failed to register event notifier\n");
kfree(priv);
}
return ret;
}
static __poll_t cros_ec_chardev_poll(struct file *filp, poll_table *wait)
{
struct chardev_priv *priv = filp->private_data;
poll_wait(filp, &priv->wait_event, wait);
if (list_empty(&priv->events))
return 0;
return EPOLLIN | EPOLLRDNORM;
}
static ssize_t cros_ec_chardev_read(struct file *filp, char __user *buffer,
size_t length, loff_t *offset)
{
char msg[sizeof(struct ec_response_get_version) +
sizeof(CROS_EC_DEV_VERSION)];
struct chardev_priv *priv = filp->private_data;
struct cros_ec_dev *ec_dev = priv->ec_dev;
size_t count;
int ret;
if (priv->event_mask) { /* queued MKBP event */
struct ec_event *event;
event = cros_ec_chardev_fetch_event(priv, length != 0,
!(filp->f_flags & O_NONBLOCK));
if (IS_ERR(event))
return PTR_ERR(event);
/*
* length == 0 is special - no IO is done but we check
* for error conditions.
*/
if (length == 0)
return 0;
/* The event is 1 byte of type plus the payload */
count = min(length, event->size + 1);
ret = copy_to_user(buffer, &event->event_type, count);
kfree(event);
if (ret) /* the copy failed */
return -EFAULT;
*offset = count;
return count;
}
/*
* Legacy behavior if no event mask is defined
*/
if (*offset != 0)
return 0;
ret = ec_get_version(ec_dev, msg, sizeof(msg));
if (ret)
return ret;
count = min(length, strlen(msg));
if (copy_to_user(buffer, msg, count))
return -EFAULT;
*offset = count;
return count;
}
static int cros_ec_chardev_release(struct inode *inode, struct file *filp)
{
struct chardev_priv *priv = filp->private_data;
struct cros_ec_dev *ec_dev = priv->ec_dev;
struct ec_event *event, *e;
blocking_notifier_chain_unregister(&ec_dev->ec_dev->event_notifier,
&priv->notifier);
list_for_each_entry_safe(event, e, &priv->events, node) {
list_del(&event->node);
kfree(event);
}
kfree(priv);
return 0;
}
/*
* Ioctls
*/
static long cros_ec_chardev_ioctl_xcmd(struct cros_ec_dev *ec, void __user *arg)
{
struct cros_ec_command *s_cmd;
struct cros_ec_command u_cmd;
long ret;
if (copy_from_user(&u_cmd, arg, sizeof(u_cmd)))
return -EFAULT;
if (u_cmd.outsize > EC_MAX_MSG_BYTES ||
u_cmd.insize > EC_MAX_MSG_BYTES)
return -EINVAL;
s_cmd = kmalloc(sizeof(*s_cmd) + max(u_cmd.outsize, u_cmd.insize),
GFP_KERNEL);
if (!s_cmd)
return -ENOMEM;
if (copy_from_user(s_cmd, arg, sizeof(*s_cmd) + u_cmd.outsize)) {
ret = -EFAULT;
goto exit;
}
if (u_cmd.outsize != s_cmd->outsize ||
u_cmd.insize != s_cmd->insize) {
ret = -EINVAL;
goto exit;
}
s_cmd->command += ec->cmd_offset;
ret = cros_ec_cmd_xfer_status(ec->ec_dev, s_cmd);
/* Only copy data to userland if data was received. */
if (ret < 0)
goto exit;
if (copy_to_user(arg, s_cmd, sizeof(*s_cmd) + s_cmd->insize))
ret = -EFAULT;
exit:
kfree(s_cmd);
return ret;
}
static long cros_ec_chardev_ioctl_readmem(struct cros_ec_dev *ec,
void __user *arg)
{
struct cros_ec_device *ec_dev = ec->ec_dev;
struct cros_ec_readmem s_mem = { };
long num;
/* Not every platform supports direct reads */
if (!ec_dev->cmd_readmem)
return -ENOTTY;
if (copy_from_user(&s_mem, arg, sizeof(s_mem)))
return -EFAULT;
num = ec_dev->cmd_readmem(ec_dev, s_mem.offset, s_mem.bytes,
s_mem.buffer);
if (num <= 0)
return num;
if (copy_to_user((void __user *)arg, &s_mem, sizeof(s_mem)))
return -EFAULT;
return num;
}
static long cros_ec_chardev_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct chardev_priv *priv = filp->private_data;
struct cros_ec_dev *ec = priv->ec_dev;
if (_IOC_TYPE(cmd) != CROS_EC_DEV_IOC)
return -ENOTTY;
switch (cmd) {
case CROS_EC_DEV_IOCXCMD:
return cros_ec_chardev_ioctl_xcmd(ec, (void __user *)arg);
case CROS_EC_DEV_IOCRDMEM:
return cros_ec_chardev_ioctl_readmem(ec, (void __user *)arg);
case CROS_EC_DEV_IOCEVENTMASK:
priv->event_mask = arg;
return 0;
}
return -ENOTTY;
}
static const struct file_operations chardev_fops = {
.open = cros_ec_chardev_open,
.poll = cros_ec_chardev_poll,
.read = cros_ec_chardev_read,
.release = cros_ec_chardev_release,
.unlocked_ioctl = cros_ec_chardev_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = cros_ec_chardev_ioctl,
#endif
};
static int cros_ec_chardev_probe(struct platform_device *pdev)
{
struct cros_ec_dev *ec_dev = dev_get_drvdata(pdev->dev.parent);
struct cros_ec_platform *ec_platform = dev_get_platdata(ec_dev->dev);
struct chardev_data *data;
/* Create a char device: we want to create it anew */
data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->ec_dev = ec_dev;
data->misc.minor = MISC_DYNAMIC_MINOR;
data->misc.fops = &chardev_fops;
data->misc.name = ec_platform->ec_name;
data->misc.parent = pdev->dev.parent;
dev_set_drvdata(&pdev->dev, data);
return misc_register(&data->misc);
}
static int cros_ec_chardev_remove(struct platform_device *pdev)
{
struct chardev_data *data = dev_get_drvdata(&pdev->dev);
misc_deregister(&data->misc);
return 0;
}
static struct platform_driver cros_ec_chardev_driver = {
.driver = {
.name = DRV_NAME,
},
.probe = cros_ec_chardev_probe,
.remove = cros_ec_chardev_remove,
};
module_platform_driver(cros_ec_chardev_driver);
MODULE_ALIAS("platform:" DRV_NAME);
MODULE_AUTHOR("Enric Balletbo i Serra <enric.balletbo@collabora.com>");
MODULE_DESCRIPTION("ChromeOS EC Miscellaneous Character Driver");
MODULE_LICENSE("GPL");
|
{
"pile_set_name": "Github"
}
|
//
// Copyright (c) 2020 Amer Koleci and contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "VulkanTexture.h"
#include "VulkanGraphicsDevice.h"
namespace Alimer
{
VulkanTexture::VulkanTexture(VulkanGraphicsDevice* device, const TextureDescription& desc, VkImage handle_, VkImageLayout layout)
: Texture(desc)
, device{ device }
, layout{ layout }
{
if (handle_ != VK_NULL_HANDLE)
{
handle = handle_;
allocation = VK_NULL_HANDLE;
}
else
{
VkImageCreateInfo createInfo{ VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
createInfo.flags = 0u;
createInfo.imageType = VK_IMAGE_TYPE_2D;
createInfo.format = VK_FORMAT_R8G8B8A8_UNORM; // GetVkFormat(desc->format);
createInfo.extent.width = desc.width;
createInfo.extent.height = desc.height;
createInfo.extent.depth = desc.depth;
createInfo.mipLevels = desc.mipLevels;
createInfo.arrayLayers = desc.arrayLayers;
createInfo.samples = VK_SAMPLE_COUNT_1_BIT;
createInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
createInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT; // vgpu_vkGetImageUsage(desc->usage, desc->format);
createInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 0;
createInfo.pQueueFamilyIndices = nullptr;
createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
VkResult result = vmaCreateImage(device->GetAllocator(),
&createInfo, &allocCreateInfo,
&handle, &allocation,
nullptr);
if (result != VK_SUCCESS)
{
LOGE("Vulkan: Failed to create image");
}
}
}
VulkanTexture::~VulkanTexture()
{
Destroy();
}
void VulkanTexture::Destroy()
{
if (handle != VK_NULL_HANDLE
&& allocation != VK_NULL_HANDLE)
{
//unmap();
//vmaDestroyImage(device->GetAllocator(), handle, allocation);
}
}
void VulkanTexture::BackendSetName()
{
device->SetObjectName(VK_OBJECT_TYPE_IMAGE, (uint64_t)handle, name);
}
void VulkanTexture::Barrier(VkCommandBuffer commandBuffer, VkImageLayout newLayout)
{
if (layout == newLayout)
return;
VkImageMemoryBarrier imageMemoryBarrier{ VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
imageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.oldLayout = layout;
imageMemoryBarrier.newLayout = newLayout;
imageMemoryBarrier.image = handle;
imageMemoryBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageMemoryBarrier.subresourceRange.baseMipLevel = 0;
imageMemoryBarrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS;
imageMemoryBarrier.subresourceRange.baseArrayLayer = 0;
imageMemoryBarrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
// Source layouts (old)
// Source access mask controls actions that have to be finished on the old layout
// before it will be transitioned to the new layout
switch (layout)
{
case VK_IMAGE_LAYOUT_UNDEFINED:
// Image layout is undefined (or does not matter)
// Only valid as initial layout
// No flags required, listed only for completeness
imageMemoryBarrier.srcAccessMask = 0;
break;
case VK_IMAGE_LAYOUT_PREINITIALIZED:
// Image is preinitialized
// Only valid as initial layout for linear images, preserves memory contents
// Make sure host writes have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
// Image is a color attachment
// Make sure any writes to the color buffer have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
// Image is a depth/stencil attachment
// Make sure any writes to the depth/stencil buffer have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
// Image is a transfer source
// Make sure any reads from the image have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
// Image is a transfer destination
// Make sure any writes to the image have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
// Image is read by a shader
// Make sure any shader reads from the image have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
break;
default:
// Other source layouts aren't handled (yet)
break;
}
// Target layouts (new)
// Destination access mask controls the dependency for the new image layout
switch (newLayout)
{
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
// Image will be used as a transfer destination
// Make sure any writes to the image have been finished
imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
// Image will be used as a transfer source
// Make sure any reads from the image have been finished
imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
// Image will be used as a color attachment
// Make sure any writes to the color buffer have been finished
imageMemoryBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
// Image layout will be used as a depth/stencil attachment
// Make sure any writes to depth/stencil buffer have been finished
imageMemoryBarrier.dstAccessMask = imageMemoryBarrier.dstAccessMask | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
// Image will be read in a shader (sampler, input attachment)
// Make sure any writes to the image have been finished
if (imageMemoryBarrier.srcAccessMask == 0)
{
imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
}
imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
break;
default:
// Other source layouts aren't handled (yet)
break;
}
vkCmdPipelineBarrier(
commandBuffer,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier);
layout = newLayout;
}
}
|
{
"pile_set_name": "Github"
}
|
/*
*
* Bluetooth low-complexity, subband codec (SBC) library
*
* Copyright (C) 2008-2010 Nokia Corporation
* Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org>
* Copyright (C) 2004-2005 Henryk Ploetz <henryk@ploetzli.ch>
* Copyright (C) 2005-2006 Brad Midgley <bmidgley@xmission.com>
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <stdint.h>
#include <limits.h>
#include "sbc.h"
#include "sbc_math.h"
#include "sbc_tables.h"
#include "sbc_primitives_neon.h"
/*
* ARM NEON optimizations
*/
#ifdef SBC_BUILD_WITH_NEON_SUPPORT
static inline void _sbc_analyze_four_neon(const int16_t *in, int32_t *out,
const FIXED_T *consts)
{
/* TODO: merge even and odd cases (or even merge all four calls to this
* function) in order to have only aligned reads from 'in' array
* and reduce number of load instructions */
asm volatile (
"vld1.16 {d4, d5}, [%0, :64]!\n"
"vld1.16 {d8, d9}, [%1, :128]!\n"
"vmull.s16 q0, d4, d8\n"
"vld1.16 {d6, d7}, [%0, :64]!\n"
"vmull.s16 q1, d5, d9\n"
"vld1.16 {d10, d11}, [%1, :128]!\n"
"vmlal.s16 q0, d6, d10\n"
"vld1.16 {d4, d5}, [%0, :64]!\n"
"vmlal.s16 q1, d7, d11\n"
"vld1.16 {d8, d9}, [%1, :128]!\n"
"vmlal.s16 q0, d4, d8\n"
"vld1.16 {d6, d7}, [%0, :64]!\n"
"vmlal.s16 q1, d5, d9\n"
"vld1.16 {d10, d11}, [%1, :128]!\n"
"vmlal.s16 q0, d6, d10\n"
"vld1.16 {d4, d5}, [%0, :64]!\n"
"vmlal.s16 q1, d7, d11\n"
"vld1.16 {d8, d9}, [%1, :128]!\n"
"vmlal.s16 q0, d4, d8\n"
"vmlal.s16 q1, d5, d9\n"
"vpadd.s32 d0, d0, d1\n"
"vpadd.s32 d1, d2, d3\n"
"vrshrn.s32 d0, q0, %3\n"
"vld1.16 {d2, d3, d4, d5}, [%1, :128]!\n"
"vdup.i32 d1, d0[1]\n" /* TODO: can be eliminated */
"vdup.i32 d0, d0[0]\n" /* TODO: can be eliminated */
"vmull.s16 q3, d2, d0\n"
"vmull.s16 q4, d3, d0\n"
"vmlal.s16 q3, d4, d1\n"
"vmlal.s16 q4, d5, d1\n"
"vpadd.s32 d0, d6, d7\n" /* TODO: can be eliminated */
"vpadd.s32 d1, d8, d9\n" /* TODO: can be eliminated */
"vst1.32 {d0, d1}, [%2, :128]\n"
: "+r" (in), "+r" (consts)
: "r" (out),
"i" (SBC_PROTO_FIXED4_SCALE)
: "memory",
"d0", "d1", "d2", "d3", "d4", "d5",
"d6", "d7", "d8", "d9", "d10", "d11");
}
static inline void _sbc_analyze_eight_neon(const int16_t *in, int32_t *out,
const FIXED_T *consts)
{
/* TODO: merge even and odd cases (or even merge all four calls to this
* function) in order to have only aligned reads from 'in' array
* and reduce number of load instructions */
asm volatile (
"vld1.16 {d4, d5}, [%0, :64]!\n"
"vld1.16 {d8, d9}, [%1, :128]!\n"
"vmull.s16 q6, d4, d8\n"
"vld1.16 {d6, d7}, [%0, :64]!\n"
"vmull.s16 q7, d5, d9\n"
"vld1.16 {d10, d11}, [%1, :128]!\n"
"vmull.s16 q8, d6, d10\n"
"vld1.16 {d4, d5}, [%0, :64]!\n"
"vmull.s16 q9, d7, d11\n"
"vld1.16 {d8, d9}, [%1, :128]!\n"
"vmlal.s16 q6, d4, d8\n"
"vld1.16 {d6, d7}, [%0, :64]!\n"
"vmlal.s16 q7, d5, d9\n"
"vld1.16 {d10, d11}, [%1, :128]!\n"
"vmlal.s16 q8, d6, d10\n"
"vld1.16 {d4, d5}, [%0, :64]!\n"
"vmlal.s16 q9, d7, d11\n"
"vld1.16 {d8, d9}, [%1, :128]!\n"
"vmlal.s16 q6, d4, d8\n"
"vld1.16 {d6, d7}, [%0, :64]!\n"
"vmlal.s16 q7, d5, d9\n"
"vld1.16 {d10, d11}, [%1, :128]!\n"
"vmlal.s16 q8, d6, d10\n"
"vld1.16 {d4, d5}, [%0, :64]!\n"
"vmlal.s16 q9, d7, d11\n"
"vld1.16 {d8, d9}, [%1, :128]!\n"
"vmlal.s16 q6, d4, d8\n"
"vld1.16 {d6, d7}, [%0, :64]!\n"
"vmlal.s16 q7, d5, d9\n"
"vld1.16 {d10, d11}, [%1, :128]!\n"
"vmlal.s16 q8, d6, d10\n"
"vld1.16 {d4, d5}, [%0, :64]!\n"
"vmlal.s16 q9, d7, d11\n"
"vld1.16 {d8, d9}, [%1, :128]!\n"
"vmlal.s16 q6, d4, d8\n"
"vld1.16 {d6, d7}, [%0, :64]!\n"
"vmlal.s16 q7, d5, d9\n"
"vld1.16 {d10, d11}, [%1, :128]!\n"
"vmlal.s16 q8, d6, d10\n"
"vmlal.s16 q9, d7, d11\n"
"vpadd.s32 d0, d12, d13\n"
"vpadd.s32 d1, d14, d15\n"
"vpadd.s32 d2, d16, d17\n"
"vpadd.s32 d3, d18, d19\n"
"vrshr.s32 q0, q0, %3\n"
"vrshr.s32 q1, q1, %3\n"
"vmovn.s32 d0, q0\n"
"vmovn.s32 d1, q1\n"
"vdup.i32 d3, d1[1]\n" /* TODO: can be eliminated */
"vdup.i32 d2, d1[0]\n" /* TODO: can be eliminated */
"vdup.i32 d1, d0[1]\n" /* TODO: can be eliminated */
"vdup.i32 d0, d0[0]\n" /* TODO: can be eliminated */
"vld1.16 {d4, d5}, [%1, :128]!\n"
"vmull.s16 q6, d4, d0\n"
"vld1.16 {d6, d7}, [%1, :128]!\n"
"vmull.s16 q7, d5, d0\n"
"vmull.s16 q8, d6, d0\n"
"vmull.s16 q9, d7, d0\n"
"vld1.16 {d4, d5}, [%1, :128]!\n"
"vmlal.s16 q6, d4, d1\n"
"vld1.16 {d6, d7}, [%1, :128]!\n"
"vmlal.s16 q7, d5, d1\n"
"vmlal.s16 q8, d6, d1\n"
"vmlal.s16 q9, d7, d1\n"
"vld1.16 {d4, d5}, [%1, :128]!\n"
"vmlal.s16 q6, d4, d2\n"
"vld1.16 {d6, d7}, [%1, :128]!\n"
"vmlal.s16 q7, d5, d2\n"
"vmlal.s16 q8, d6, d2\n"
"vmlal.s16 q9, d7, d2\n"
"vld1.16 {d4, d5}, [%1, :128]!\n"
"vmlal.s16 q6, d4, d3\n"
"vld1.16 {d6, d7}, [%1, :128]!\n"
"vmlal.s16 q7, d5, d3\n"
"vmlal.s16 q8, d6, d3\n"
"vmlal.s16 q9, d7, d3\n"
"vpadd.s32 d0, d12, d13\n" /* TODO: can be eliminated */
"vpadd.s32 d1, d14, d15\n" /* TODO: can be eliminated */
"vpadd.s32 d2, d16, d17\n" /* TODO: can be eliminated */
"vpadd.s32 d3, d18, d19\n" /* TODO: can be eliminated */
"vst1.32 {d0, d1, d2, d3}, [%2, :128]\n"
: "+r" (in), "+r" (consts)
: "r" (out),
"i" (SBC_PROTO_FIXED8_SCALE)
: "memory",
"d0", "d1", "d2", "d3", "d4", "d5",
"d6", "d7", "d8", "d9", "d10", "d11",
"d12", "d13", "d14", "d15", "d16", "d17",
"d18", "d19");
}
static inline void sbc_analyze_4b_4s_neon(int16_t *x,
int32_t *out, int out_stride)
{
/* Analyze blocks */
_sbc_analyze_four_neon(x + 12, out, analysis_consts_fixed4_simd_odd);
out += out_stride;
_sbc_analyze_four_neon(x + 8, out, analysis_consts_fixed4_simd_even);
out += out_stride;
_sbc_analyze_four_neon(x + 4, out, analysis_consts_fixed4_simd_odd);
out += out_stride;
_sbc_analyze_four_neon(x + 0, out, analysis_consts_fixed4_simd_even);
}
static inline void sbc_analyze_4b_8s_neon(int16_t *x,
int32_t *out, int out_stride)
{
/* Analyze blocks */
_sbc_analyze_eight_neon(x + 24, out, analysis_consts_fixed8_simd_odd);
out += out_stride;
_sbc_analyze_eight_neon(x + 16, out, analysis_consts_fixed8_simd_even);
out += out_stride;
_sbc_analyze_eight_neon(x + 8, out, analysis_consts_fixed8_simd_odd);
out += out_stride;
_sbc_analyze_eight_neon(x + 0, out, analysis_consts_fixed8_simd_even);
}
static void sbc_calc_scalefactors_neon(
int32_t sb_sample_f[16][2][8],
uint32_t scale_factor[2][8],
int blocks, int channels, int subbands)
{
int ch, sb;
for (ch = 0; ch < channels; ch++) {
for (sb = 0; sb < subbands; sb += 4) {
int blk = blocks;
int32_t *in = &sb_sample_f[0][ch][sb];
asm volatile (
"vmov.s32 q0, #0\n"
"vmov.s32 q1, %[c1]\n"
"vmov.s32 q14, #1\n"
"vmov.s32 q15, %[c2]\n"
"vadd.s32 q1, q1, q14\n"
"1:\n"
"vld1.32 {d16, d17}, [%[in], :128], %[inc]\n"
"vabs.s32 q8, q8\n"
"vld1.32 {d18, d19}, [%[in], :128], %[inc]\n"
"vabs.s32 q9, q9\n"
"vld1.32 {d20, d21}, [%[in], :128], %[inc]\n"
"vabs.s32 q10, q10\n"
"vld1.32 {d22, d23}, [%[in], :128], %[inc]\n"
"vabs.s32 q11, q11\n"
"vmax.s32 q0, q0, q8\n"
"vmax.s32 q1, q1, q9\n"
"vmax.s32 q0, q0, q10\n"
"vmax.s32 q1, q1, q11\n"
"subs %[blk], %[blk], #4\n"
"bgt 1b\n"
"vmax.s32 q0, q0, q1\n"
"vsub.s32 q0, q0, q14\n"
"vclz.s32 q0, q0\n"
"vsub.s32 q0, q15, q0\n"
"vst1.32 {d0, d1}, [%[out], :128]\n"
:
[blk] "+r" (blk),
[in] "+r" (in)
:
[inc] "r" ((char *) &sb_sample_f[1][0][0] -
(char *) &sb_sample_f[0][0][0]),
[out] "r" (&scale_factor[ch][sb]),
[c1] "i" (1 << SCALE_OUT_BITS),
[c2] "i" (31 - SCALE_OUT_BITS)
: "d0", "d1", "d2", "d3", "d16", "d17", "d18", "d19",
"d20", "d21", "d22", "d23", "d24", "d25", "d26",
"d27", "d28", "d29", "d30", "d31", "cc", "memory");
}
}
}
int sbc_calc_scalefactors_j_neon(
int32_t sb_sample_f[16][2][8],
uint32_t scale_factor[2][8],
int blocks, int subbands)
{
static SBC_ALIGNED int32_t joint_bits_mask[8] = {
8, 4, 2, 1, 128, 64, 32, 16
};
int joint, i;
int32_t *in0, *in1;
int32_t *in = &sb_sample_f[0][0][0];
uint32_t *out0, *out1;
uint32_t *out = &scale_factor[0][0];
int32_t *consts = joint_bits_mask;
i = subbands;
asm volatile (
/*
* constants: q13 = (31 - SCALE_OUT_BITS), q14 = 1
* input: q0 = ((1 << SCALE_OUT_BITS) + 1)
* %[in0] - samples for channel 0
* %[in1] - samples for shannel 1
* output: q0, q1 - scale factors without joint stereo
* q2, q3 - scale factors with joint stereo
* q15 - joint stereo selection mask
*/
".macro calc_scalefactors\n"
"vmov.s32 q1, q0\n"
"vmov.s32 q2, q0\n"
"vmov.s32 q3, q0\n"
"mov %[i], %[blocks]\n"
"1:\n"
"vld1.32 {d18, d19}, [%[in1], :128], %[inc]\n"
"vbic.s32 q11, q9, q14\n"
"vld1.32 {d16, d17}, [%[in0], :128], %[inc]\n"
"vhadd.s32 q10, q8, q11\n"
"vhsub.s32 q11, q8, q11\n"
"vabs.s32 q8, q8\n"
"vabs.s32 q9, q9\n"
"vabs.s32 q10, q10\n"
"vabs.s32 q11, q11\n"
"vmax.s32 q0, q0, q8\n"
"vmax.s32 q1, q1, q9\n"
"vmax.s32 q2, q2, q10\n"
"vmax.s32 q3, q3, q11\n"
"subs %[i], %[i], #1\n"
"bgt 1b\n"
"vsub.s32 q0, q0, q14\n"
"vsub.s32 q1, q1, q14\n"
"vsub.s32 q2, q2, q14\n"
"vsub.s32 q3, q3, q14\n"
"vclz.s32 q0, q0\n"
"vclz.s32 q1, q1\n"
"vclz.s32 q2, q2\n"
"vclz.s32 q3, q3\n"
"vsub.s32 q0, q13, q0\n"
"vsub.s32 q1, q13, q1\n"
"vsub.s32 q2, q13, q2\n"
"vsub.s32 q3, q13, q3\n"
".endm\n"
/*
* constants: q14 = 1
* input: q15 - joint stereo selection mask
* %[in0] - value set by calc_scalefactors macro
* %[in1] - value set by calc_scalefactors macro
*/
".macro update_joint_stereo_samples\n"
"sub %[out1], %[in1], %[inc]\n"
"sub %[out0], %[in0], %[inc]\n"
"sub %[in1], %[in1], %[inc], asl #1\n"
"sub %[in0], %[in0], %[inc], asl #1\n"
"vld1.32 {d18, d19}, [%[in1], :128]\n"
"vbic.s32 q11, q9, q14\n"
"vld1.32 {d16, d17}, [%[in0], :128]\n"
"vld1.32 {d2, d3}, [%[out1], :128]\n"
"vbic.s32 q3, q1, q14\n"
"vld1.32 {d0, d1}, [%[out0], :128]\n"
"vhsub.s32 q10, q8, q11\n"
"vhadd.s32 q11, q8, q11\n"
"vhsub.s32 q2, q0, q3\n"
"vhadd.s32 q3, q0, q3\n"
"vbif.s32 q10, q9, q15\n"
"vbif.s32 d22, d16, d30\n"
"sub %[inc], %[zero], %[inc], asl #1\n"
"sub %[i], %[blocks], #2\n"
"2:\n"
"vbif.s32 d23, d17, d31\n"
"vst1.32 {d20, d21}, [%[in1], :128], %[inc]\n"
"vbif.s32 d4, d2, d30\n"
"vld1.32 {d18, d19}, [%[in1], :128]\n"
"vbif.s32 d5, d3, d31\n"
"vst1.32 {d22, d23}, [%[in0], :128], %[inc]\n"
"vbif.s32 d6, d0, d30\n"
"vld1.32 {d16, d17}, [%[in0], :128]\n"
"vbif.s32 d7, d1, d31\n"
"vst1.32 {d4, d5}, [%[out1], :128], %[inc]\n"
"vbic.s32 q11, q9, q14\n"
"vld1.32 {d2, d3}, [%[out1], :128]\n"
"vst1.32 {d6, d7}, [%[out0], :128], %[inc]\n"
"vbic.s32 q3, q1, q14\n"
"vld1.32 {d0, d1}, [%[out0], :128]\n"
"vhsub.s32 q10, q8, q11\n"
"vhadd.s32 q11, q8, q11\n"
"vhsub.s32 q2, q0, q3\n"
"vhadd.s32 q3, q0, q3\n"
"vbif.s32 q10, q9, q15\n"
"vbif.s32 d22, d16, d30\n"
"subs %[i], %[i], #2\n"
"bgt 2b\n"
"sub %[inc], %[zero], %[inc], asr #1\n"
"vbif.s32 d23, d17, d31\n"
"vst1.32 {d20, d21}, [%[in1], :128]\n"
"vbif.s32 q2, q1, q15\n"
"vst1.32 {d22, d23}, [%[in0], :128]\n"
"vbif.s32 q3, q0, q15\n"
"vst1.32 {d4, d5}, [%[out1], :128]\n"
"vst1.32 {d6, d7}, [%[out0], :128]\n"
".endm\n"
"vmov.s32 q14, #1\n"
"vmov.s32 q13, %[c2]\n"
"cmp %[i], #4\n"
"bne 8f\n"
"4:\n" /* 4 subbands */
"add %[in0], %[in], #0\n"
"add %[in1], %[in], #32\n"
"add %[out0], %[out], #0\n"
"add %[out1], %[out], #32\n"
"vmov.s32 q0, %[c1]\n"
"vadd.s32 q0, q0, q14\n"
"calc_scalefactors\n"
/* check whether to use joint stereo for subbands 0, 1, 2 */
"vadd.s32 q15, q0, q1\n"
"vadd.s32 q9, q2, q3\n"
"vmov.s32 d31[1], %[zero]\n" /* last subband -> no joint */
"vld1.32 {d16, d17}, [%[consts], :128]!\n"
"vcgt.s32 q15, q15, q9\n"
/* calculate and save to memory 'joint' variable */
/* update and save scale factors to memory */
" vand.s32 q8, q8, q15\n"
"vbit.s32 q0, q2, q15\n"
" vpadd.s32 d16, d16, d17\n"
"vbit.s32 q1, q3, q15\n"
" vpadd.s32 d16, d16, d16\n"
"vst1.32 {d0, d1}, [%[out0], :128]\n"
"vst1.32 {d2, d3}, [%[out1], :128]\n"
" vst1.32 {d16[0]}, [%[joint]]\n"
"update_joint_stereo_samples\n"
"b 9f\n"
"8:\n" /* 8 subbands */
"add %[in0], %[in], #16\n\n"
"add %[in1], %[in], #48\n"
"add %[out0], %[out], #16\n\n"
"add %[out1], %[out], #48\n"
"vmov.s32 q0, %[c1]\n"
"vadd.s32 q0, q0, q14\n"
"calc_scalefactors\n"
/* check whether to use joint stereo for subbands 4, 5, 6 */
"vadd.s32 q15, q0, q1\n"
"vadd.s32 q9, q2, q3\n"
"vmov.s32 d31[1], %[zero]\n" /* last subband -> no joint */
"vld1.32 {d16, d17}, [%[consts], :128]!\n"
"vcgt.s32 q15, q15, q9\n"
/* calculate part of 'joint' variable and save it to d24 */
/* update and save scale factors to memory */
" vand.s32 q8, q8, q15\n"
"vbit.s32 q0, q2, q15\n"
" vpadd.s32 d16, d16, d17\n"
"vbit.s32 q1, q3, q15\n"
"vst1.32 {d0, d1}, [%[out0], :128]\n"
"vst1.32 {d2, d3}, [%[out1], :128]\n"
" vpadd.s32 d24, d16, d16\n"
"update_joint_stereo_samples\n"
"add %[in0], %[in], #0\n"
"add %[in1], %[in], #32\n"
"add %[out0], %[out], #0\n\n"
"add %[out1], %[out], #32\n"
"vmov.s32 q0, %[c1]\n"
"vadd.s32 q0, q0, q14\n"
"calc_scalefactors\n"
/* check whether to use joint stereo for subbands 0, 1, 2, 3 */
"vadd.s32 q15, q0, q1\n"
"vadd.s32 q9, q2, q3\n"
"vld1.32 {d16, d17}, [%[consts], :128]!\n"
"vcgt.s32 q15, q15, q9\n"
/* combine last part of 'joint' with d24 and save to memory */
/* update and save scale factors to memory */
" vand.s32 q8, q8, q15\n"
"vbit.s32 q0, q2, q15\n"
" vpadd.s32 d16, d16, d17\n"
"vbit.s32 q1, q3, q15\n"
" vpadd.s32 d16, d16, d16\n"
"vst1.32 {d0, d1}, [%[out0], :128]\n"
" vadd.s32 d16, d16, d24\n"
"vst1.32 {d2, d3}, [%[out1], :128]\n"
" vst1.32 {d16[0]}, [%[joint]]\n"
"update_joint_stereo_samples\n"
"9:\n"
".purgem calc_scalefactors\n"
".purgem update_joint_stereo_samples\n"
:
[i] "+&r" (i),
[in] "+&r" (in),
[in0] "=&r" (in0),
[in1] "=&r" (in1),
[out] "+&r" (out),
[out0] "=&r" (out0),
[out1] "=&r" (out1),
[consts] "+&r" (consts)
:
[inc] "r" ((char *) &sb_sample_f[1][0][0] -
(char *) &sb_sample_f[0][0][0]),
[blocks] "r" (blocks),
[joint] "r" (&joint),
[c1] "i" (1 << SCALE_OUT_BITS),
[c2] "i" (31 - SCALE_OUT_BITS),
[zero] "r" (0)
: "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
"d16", "d17", "d18", "d19", "d20", "d21", "d22",
"d23", "d24", "d25", "d26", "d27", "d28", "d29",
"d30", "d31", "cc", "memory");
return joint;
}
#define PERM_BE(a, b, c, d) { \
(a * 2) + 1, (a * 2) + 0, \
(b * 2) + 1, (b * 2) + 0, \
(c * 2) + 1, (c * 2) + 0, \
(d * 2) + 1, (d * 2) + 0 \
}
#define PERM_LE(a, b, c, d) { \
(a * 2) + 0, (a * 2) + 1, \
(b * 2) + 0, (b * 2) + 1, \
(c * 2) + 0, (c * 2) + 1, \
(d * 2) + 0, (d * 2) + 1 \
}
static SBC_ALWAYS_INLINE int sbc_enc_process_input_4s_neon_internal(
int position,
const uint8_t *pcm, int16_t X[2][SBC_X_BUFFER_SIZE],
int nsamples, int nchannels, int big_endian)
{
static SBC_ALIGNED uint8_t perm_be[2][8] = {
PERM_BE(7, 3, 6, 4),
PERM_BE(0, 2, 1, 5)
};
static SBC_ALIGNED uint8_t perm_le[2][8] = {
PERM_LE(7, 3, 6, 4),
PERM_LE(0, 2, 1, 5)
};
/* handle X buffer wraparound */
if (position < nsamples) {
int16_t *dst = &X[0][SBC_X_BUFFER_SIZE - 40];
int16_t *src = &X[0][position];
asm volatile (
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0}, [%[src], :64]!\n"
"vst1.16 {d0}, [%[dst], :64]!\n"
:
[dst] "+r" (dst),
[src] "+r" (src)
: : "memory", "d0", "d1", "d2", "d3");
if (nchannels > 1) {
dst = &X[1][SBC_X_BUFFER_SIZE - 40];
src = &X[1][position];
asm volatile (
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0}, [%[src], :64]!\n"
"vst1.16 {d0}, [%[dst], :64]!\n"
:
[dst] "+r" (dst),
[src] "+r" (src)
: : "memory", "d0", "d1", "d2", "d3");
}
position = SBC_X_BUFFER_SIZE - 40;
}
if ((nchannels > 1) && ((uintptr_t)pcm & 1)) {
/* poor 'pcm' alignment */
int16_t *x = &X[0][position];
int16_t *y = &X[1][position];
asm volatile (
"vld1.8 {d0, d1}, [%[perm], :128]\n"
"1:\n"
"sub %[x], %[x], #16\n"
"sub %[y], %[y], #16\n"
"sub %[position], %[position], #8\n"
"vld1.8 {d4, d5}, [%[pcm]]!\n"
"vuzp.16 d4, d5\n"
"vld1.8 {d20, d21}, [%[pcm]]!\n"
"vuzp.16 d20, d21\n"
"vswp d5, d20\n"
"vtbl.8 d16, {d4, d5}, d0\n"
"vtbl.8 d17, {d4, d5}, d1\n"
"vtbl.8 d18, {d20, d21}, d0\n"
"vtbl.8 d19, {d20, d21}, d1\n"
"vst1.16 {d16, d17}, [%[x], :128]\n"
"vst1.16 {d18, d19}, [%[y], :128]\n"
"subs %[nsamples], %[nsamples], #8\n"
"bgt 1b\n"
:
[x] "+r" (x),
[y] "+r" (y),
[pcm] "+r" (pcm),
[nsamples] "+r" (nsamples),
[position] "+r" (position)
:
[perm] "r" (big_endian ? perm_be : perm_le)
: "cc", "memory", "d0", "d1", "d2", "d3", "d4",
"d5", "d6", "d7", "d16", "d17", "d18", "d19",
"d20", "d21", "d22", "d23");
} else if (nchannels > 1) {
/* proper 'pcm' alignment */
int16_t *x = &X[0][position];
int16_t *y = &X[1][position];
asm volatile (
"vld1.8 {d0, d1}, [%[perm], :128]\n"
"1:\n"
"sub %[x], %[x], #16\n"
"sub %[y], %[y], #16\n"
"sub %[position], %[position], #8\n"
"vld2.16 {d4, d5}, [%[pcm]]!\n"
"vld2.16 {d20, d21}, [%[pcm]]!\n"
"vswp d5, d20\n"
"vtbl.8 d16, {d4, d5}, d0\n"
"vtbl.8 d17, {d4, d5}, d1\n"
"vtbl.8 d18, {d20, d21}, d0\n"
"vtbl.8 d19, {d20, d21}, d1\n"
"vst1.16 {d16, d17}, [%[x], :128]\n"
"vst1.16 {d18, d19}, [%[y], :128]\n"
"subs %[nsamples], %[nsamples], #8\n"
"bgt 1b\n"
:
[x] "+r" (x),
[y] "+r" (y),
[pcm] "+r" (pcm),
[nsamples] "+r" (nsamples),
[position] "+r" (position)
:
[perm] "r" (big_endian ? perm_be : perm_le)
: "cc", "memory", "d0", "d1", "d2", "d3", "d4",
"d5", "d6", "d7", "d16", "d17", "d18", "d19",
"d20", "d21", "d22", "d23");
} else {
int16_t *x = &X[0][position];
asm volatile (
"vld1.8 {d0, d1}, [%[perm], :128]\n"
"1:\n"
"sub %[x], %[x], #16\n"
"sub %[position], %[position], #8\n"
"vld1.8 {d4, d5}, [%[pcm]]!\n"
"vtbl.8 d16, {d4, d5}, d0\n"
"vtbl.8 d17, {d4, d5}, d1\n"
"vst1.16 {d16, d17}, [%[x], :128]\n"
"subs %[nsamples], %[nsamples], #8\n"
"bgt 1b\n"
:
[x] "+r" (x),
[pcm] "+r" (pcm),
[nsamples] "+r" (nsamples),
[position] "+r" (position)
:
[perm] "r" (big_endian ? perm_be : perm_le)
: "cc", "memory", "d0", "d1", "d2", "d3", "d4",
"d5", "d6", "d7", "d16", "d17", "d18", "d19");
}
return position;
}
static SBC_ALWAYS_INLINE int sbc_enc_process_input_8s_neon_internal(
int position,
const uint8_t *pcm, int16_t X[2][SBC_X_BUFFER_SIZE],
int nsamples, int nchannels, int big_endian)
{
static SBC_ALIGNED uint8_t perm_be[4][8] = {
PERM_BE(15, 7, 14, 8),
PERM_BE(13, 9, 12, 10),
PERM_BE(11, 3, 6, 0),
PERM_BE(5, 1, 4, 2)
};
static SBC_ALIGNED uint8_t perm_le[4][8] = {
PERM_LE(15, 7, 14, 8),
PERM_LE(13, 9, 12, 10),
PERM_LE(11, 3, 6, 0),
PERM_LE(5, 1, 4, 2)
};
/* handle X buffer wraparound */
if (position < nsamples) {
int16_t *dst = &X[0][SBC_X_BUFFER_SIZE - 72];
int16_t *src = &X[0][position];
asm volatile (
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0, d1}, [%[src], :128]!\n"
"vst1.16 {d0, d1}, [%[dst], :128]!\n"
:
[dst] "+r" (dst),
[src] "+r" (src)
: : "memory", "d0", "d1", "d2", "d3");
if (nchannels > 1) {
dst = &X[1][SBC_X_BUFFER_SIZE - 72];
src = &X[1][position];
asm volatile (
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0, d1, d2, d3}, [%[src], :128]!\n"
"vst1.16 {d0, d1, d2, d3}, [%[dst], :128]!\n"
"vld1.16 {d0, d1}, [%[src], :128]!\n"
"vst1.16 {d0, d1}, [%[dst], :128]!\n"
:
[dst] "+r" (dst),
[src] "+r" (src)
: : "memory", "d0", "d1", "d2", "d3");
}
position = SBC_X_BUFFER_SIZE - 72;
}
if ((nchannels > 1) && ((uintptr_t)pcm & 1)) {
/* poor 'pcm' alignment */
int16_t *x = &X[0][position];
int16_t *y = &X[1][position];
asm volatile (
"vld1.8 {d0, d1, d2, d3}, [%[perm], :128]\n"
"1:\n"
"sub %[x], %[x], #32\n"
"sub %[y], %[y], #32\n"
"sub %[position], %[position], #16\n"
"vld1.8 {d4, d5, d6, d7}, [%[pcm]]!\n"
"vuzp.16 q2, q3\n"
"vld1.8 {d20, d21, d22, d23}, [%[pcm]]!\n"
"vuzp.16 q10, q11\n"
"vswp q3, q10\n"
"vtbl.8 d16, {d4, d5, d6, d7}, d0\n"
"vtbl.8 d17, {d4, d5, d6, d7}, d1\n"
"vtbl.8 d18, {d4, d5, d6, d7}, d2\n"
"vtbl.8 d19, {d4, d5, d6, d7}, d3\n"
"vst1.16 {d16, d17, d18, d19}, [%[x], :128]\n"
"vtbl.8 d16, {d20, d21, d22, d23}, d0\n"
"vtbl.8 d17, {d20, d21, d22, d23}, d1\n"
"vtbl.8 d18, {d20, d21, d22, d23}, d2\n"
"vtbl.8 d19, {d20, d21, d22, d23}, d3\n"
"vst1.16 {d16, d17, d18, d19}, [%[y], :128]\n"
"subs %[nsamples], %[nsamples], #16\n"
"bgt 1b\n"
:
[x] "+r" (x),
[y] "+r" (y),
[pcm] "+r" (pcm),
[nsamples] "+r" (nsamples),
[position] "+r" (position)
:
[perm] "r" (big_endian ? perm_be : perm_le)
: "cc", "memory", "d0", "d1", "d2", "d3", "d4",
"d5", "d6", "d7", "d16", "d17", "d18", "d19",
"d20", "d21", "d22", "d23");
} else if (nchannels > 1) {
/* proper 'pcm' alignment */
int16_t *x = &X[0][position];
int16_t *y = &X[1][position];
asm volatile (
"vld1.8 {d0, d1, d2, d3}, [%[perm], :128]\n"
"1:\n"
"sub %[x], %[x], #32\n"
"sub %[y], %[y], #32\n"
"sub %[position], %[position], #16\n"
"vld2.16 {d4, d5, d6, d7}, [%[pcm]]!\n"
"vld2.16 {d20, d21, d22, d23}, [%[pcm]]!\n"
"vswp q3, q10\n"
"vtbl.8 d16, {d4, d5, d6, d7}, d0\n"
"vtbl.8 d17, {d4, d5, d6, d7}, d1\n"
"vtbl.8 d18, {d4, d5, d6, d7}, d2\n"
"vtbl.8 d19, {d4, d5, d6, d7}, d3\n"
"vst1.16 {d16, d17, d18, d19}, [%[x], :128]\n"
"vtbl.8 d16, {d20, d21, d22, d23}, d0\n"
"vtbl.8 d17, {d20, d21, d22, d23}, d1\n"
"vtbl.8 d18, {d20, d21, d22, d23}, d2\n"
"vtbl.8 d19, {d20, d21, d22, d23}, d3\n"
"vst1.16 {d16, d17, d18, d19}, [%[y], :128]\n"
"subs %[nsamples], %[nsamples], #16\n"
"bgt 1b\n"
:
[x] "+r" (x),
[y] "+r" (y),
[pcm] "+r" (pcm),
[nsamples] "+r" (nsamples),
[position] "+r" (position)
:
[perm] "r" (big_endian ? perm_be : perm_le)
: "cc", "memory", "d0", "d1", "d2", "d3", "d4",
"d5", "d6", "d7", "d16", "d17", "d18", "d19",
"d20", "d21", "d22", "d23");
} else {
int16_t *x = &X[0][position];
asm volatile (
"vld1.8 {d0, d1, d2, d3}, [%[perm], :128]\n"
"1:\n"
"sub %[x], %[x], #32\n"
"sub %[position], %[position], #16\n"
"vld1.8 {d4, d5, d6, d7}, [%[pcm]]!\n"
"vtbl.8 d16, {d4, d5, d6, d7}, d0\n"
"vtbl.8 d17, {d4, d5, d6, d7}, d1\n"
"vtbl.8 d18, {d4, d5, d6, d7}, d2\n"
"vtbl.8 d19, {d4, d5, d6, d7}, d3\n"
"vst1.16 {d16, d17, d18, d19}, [%[x], :128]\n"
"subs %[nsamples], %[nsamples], #16\n"
"bgt 1b\n"
:
[x] "+r" (x),
[pcm] "+r" (pcm),
[nsamples] "+r" (nsamples),
[position] "+r" (position)
:
[perm] "r" (big_endian ? perm_be : perm_le)
: "cc", "memory", "d0", "d1", "d2", "d3", "d4",
"d5", "d6", "d7", "d16", "d17", "d18", "d19");
}
return position;
}
#undef PERM_BE
#undef PERM_LE
static int sbc_enc_process_input_4s_be_neon(int position, const uint8_t *pcm,
int16_t X[2][SBC_X_BUFFER_SIZE],
int nsamples, int nchannels)
{
return sbc_enc_process_input_4s_neon_internal(
position, pcm, X, nsamples, nchannels, 1);
}
static int sbc_enc_process_input_4s_le_neon(int position, const uint8_t *pcm,
int16_t X[2][SBC_X_BUFFER_SIZE],
int nsamples, int nchannels)
{
return sbc_enc_process_input_4s_neon_internal(
position, pcm, X, nsamples, nchannels, 0);
}
static int sbc_enc_process_input_8s_be_neon(int position, const uint8_t *pcm,
int16_t X[2][SBC_X_BUFFER_SIZE],
int nsamples, int nchannels)
{
return sbc_enc_process_input_8s_neon_internal(
position, pcm, X, nsamples, nchannels, 1);
}
static int sbc_enc_process_input_8s_le_neon(int position, const uint8_t *pcm,
int16_t X[2][SBC_X_BUFFER_SIZE],
int nsamples, int nchannels)
{
return sbc_enc_process_input_8s_neon_internal(
position, pcm, X, nsamples, nchannels, 0);
}
void sbc_init_primitives_neon(struct sbc_encoder_state *state)
{
state->sbc_analyze_4b_4s = sbc_analyze_4b_4s_neon;
state->sbc_analyze_4b_8s = sbc_analyze_4b_8s_neon;
state->sbc_calc_scalefactors = sbc_calc_scalefactors_neon;
state->sbc_calc_scalefactors_j = sbc_calc_scalefactors_j_neon;
state->sbc_enc_process_input_4s_le = sbc_enc_process_input_4s_le_neon;
state->sbc_enc_process_input_4s_be = sbc_enc_process_input_4s_be_neon;
state->sbc_enc_process_input_8s_le = sbc_enc_process_input_8s_le_neon;
state->sbc_enc_process_input_8s_be = sbc_enc_process_input_8s_be_neon;
state->implementation_info = "NEON";
}
#endif
|
{
"pile_set_name": "Github"
}
|
/***************************************************
This is an example sketch for our optical Fingerprint sensor
Designed specifically to work with the Adafruit Fingerprint sensor
----> http://www.adafruit.com/products/751
These displays use TTL Serial to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include <Adafruit_Fingerprint.h>
#if (defined(__AVR__) || defined(ESP8266)) && !defined(__AVR_ATmega2560__)
// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino (WHITE wire)
// Set up the serial port to use softwareserial..
SoftwareSerial mySerial(2, 3);
#else
// On Leonardo/M0/etc, others with hardware serial, use hardware serial!
// #0 is green wire, #1 is white
#define mySerial Serial1
#endif
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
void setup()
{
Serial.begin(9600);
while (!Serial); // For Yun/Leo/Micro/Zero/...
delay(100);
Serial.println("\n\nDelete Finger");
// set the data rate for the sensor serial port
finger.begin(57600);
if (finger.verifyPassword()) {
Serial.println("Found fingerprint sensor!");
} else {
Serial.println("Did not find fingerprint sensor :(");
while (1);
}
}
uint8_t readnumber(void) {
uint8_t num = 0;
while (num == 0) {
while (! Serial.available());
num = Serial.parseInt();
}
return num;
}
void loop() // run over and over again
{
Serial.println("Please type in the ID # (from 1 to 127) you want to delete...");
uint8_t id = readnumber();
if (id == 0) {// ID #0 not allowed, try again!
return;
}
Serial.print("Deleting ID #");
Serial.println(id);
deleteFingerprint(id);
}
uint8_t deleteFingerprint(uint8_t id) {
uint8_t p = -1;
p = finger.deleteModel(id);
if (p == FINGERPRINT_OK) {
Serial.println("Deleted!");
} else if (p == FINGERPRINT_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FINGERPRINT_BADLOCATION) {
Serial.println("Could not delete in that location");
return p;
} else if (p == FINGERPRINT_FLASHERR) {
Serial.println("Error writing to flash");
return p;
} else {
Serial.print("Unknown error: 0x"); Serial.println(p, HEX);
return p;
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- qtsingleapplication-2.6_1-opensource/examples/loader/loader.qdoc -->
<head>
<title>Loading Documents</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
</tr></table><h1 class="title">Loading Documents<br /><span class="subtitle"></span>
</h1>
<p>The application in this example loads or prints the documents passed as commandline parameters to further instances of this application.</p>
<pre><span class="comment"> /****************************************************************************
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of a Qt Solutions component.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third
** Party Software they are using.
**
** If you are unsure which license is appropriate for your use, please
** contact Nokia at qt-info@nokia.com.
**
****************************************************************************/</span>
#include <qtsingleapplication.h>
#include <QtCore/QFile>
#include <QtGui/QMainWindow>
#include <QtGui/QPrinter>
#include <QtGui/QPainter>
#include <QtGui/QTextEdit>
#include <QtGui/QMdiArea>
#include <QtCore/QTextStream>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
public slots:
void handleMessage(const QString& message);
signals:
void needToShow();
private:
QMdiArea *workspace;
};</pre>
<p>The user interface in this application is a <a href="http://qt.nokia.com/doc/4.5/qmainwindow.html">QMainWindow</a> subclass with a <a href="http://qt.nokia.com/doc/4.5/qmdiarea.html">QMdiArea</a> as the central widget. It implements a slot <tt>handleMessage()</tt> that will be connected to the messageReceived() signal of the <a href="qtsingleapplication.html">QtSingleApplication</a> class.</p>
<pre> MainWindow::MainWindow()
{
workspace = new QMdiArea(this);
setCentralWidget(workspace);
}</pre>
<p>The <a href="http://qt.nokia.com/doc/4.5/designer-to-know.html">MainWindow</a> constructor creates a minimal user interface.</p>
<pre> void MainWindow::handleMessage(const QString& message)
{
enum Action {
Nothing,
Open,
Print
} action;
action = Nothing;
QString filename = message;
if (message.toLower().startsWith("/print ")) {
filename = filename.mid(7);
action = Print;
} else if (!message.isEmpty()) {
action = Open;
}
if (action == Nothing) {
emit needToShow();
return;
}
QFile file(filename);
QString contents;
if (file.open(QIODevice::ReadOnly))
contents = file.readAll();
else
contents = "[[Error: Could not load file " + filename + "]]";
QTextEdit *view = new QTextEdit;
view->setPlainText(contents);
switch(action) {</pre>
<p>The handleMessage() slot interprets the message passed in as a filename that can be prepended with <i>/print</i> to indicate that the file should just be printed rather than loaded.</p>
<pre> case Print:
{
QPrinter printer;
view->print(&printer);
delete view;
}
break;
case Open:
{
workspace->addSubWindow(view);
view->setWindowTitle(message);
view->show();
emit needToShow();
}
break;
default:
break;
};
}</pre>
<p>Loading the file will also activate the window.</p>
<pre> #include "main.moc"
int main(int argc, char **argv)
{
QtSingleApplication instance("File loader QtSingleApplication example", argc, argv);
QString message;
for (int a = 1; a < argc; ++a) {
message += argv[a];
if (a < argc-1)
message += " ";
}
if (instance.sendMessage(message))
return 0;</pre>
<p>The <tt>main</tt> entry point function creates a <a href="qtsingleapplication.html">QtSingleApplication</a> object, and creates a message to send to a running instance of the application. If the message was sent successfully the process exits immediately.</p>
<pre> MainWindow mw;
mw.handleMessage(message);
mw.show();
QObject::connect(&instance, SIGNAL(messageReceived(const QString&)),
&mw, SLOT(handleMessage(const QString&)));
instance.setActivationWindow(&mw, false);
QObject::connect(&mw, SIGNAL(needToShow()), &instance, SLOT(activateWindow()));
return instance.exec();
}</pre>
<p>If the message could not be sent the application starts up. Note that <tt>false</tt> is passed to the call to setActivationWindow() to prevent automatic activation for every message received, e.g. when the application should just print a file. Instead, the message handling function determines whether activation is requested, and signals that by emitting the needToShow() signal. This is then simply connected directly to <a href="qtsingleapplication.html">QtSingleApplication</a>'s activateWindow() slot.</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%" align="left">Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies)</td>
<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
</tr></table></div></address></body>
</html>
|
{
"pile_set_name": "Github"
}
|
#if !defined(AFX_MYFRAME_H__C71BE42C_F09F_458C_BB9C_33FC5544FFB9__INCLUDED_)
#define AFX_MYFRAME_H__C71BE42C_F09F_458C_BB9C_33FC5544FFB9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// MyFrame.h : header file
//
#define IMAGE_WIDTH 176
#define IMAGE_HEIGHT 144
/////////////////////////////////////////////////////////////////////////////
// CMyFrame window
class CMyFrame : public CStatic
{
// Construction
public:
CMyFrame();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMyFrame)
//}}AFX_VIRTUAL
// Implementation
public:
void DrawOneFrame(LPBITMAPINFO pInfo, LPVOID pData);
virtual ~CMyFrame();
void SaveFrame();
BOOL SaveBitmapToFile(HBITMAP hBitmap , CString lpFileName);
HBITMAP hBitmap;
// Generated message map functions
protected:
//{{AFX_MSG(CMyFrame)
afx_msg void OnPaint();
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MYFRAME_H__C71BE42C_F09F_458C_BB9C_33FC5544FFB9__INCLUDED_)
|
{
"pile_set_name": "Github"
}
|
// Copyright 2017 ZhongAn Information Technology Services Co.,Ltd.
//
// 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.
package types
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/dappledger/AnnChain/gemmill/utils"
)
var (
ErrFileNotFound = errors.New("priv_validator.json not found")
ErrBranchIsUsed = errors.New("priv_validator:branch name is used")
ErrPVRevertFromBackup = errors.New("priv_validator:revert from backup, not find data")
)
const (
PRIV_FILE_NAME = "priv_validator.json"
)
type PrivValidatorTool struct {
dir string
pv *PrivValidator
}
func (pt *PrivValidatorTool) Init(dir string) error {
var err error
pt.pv, err = LoadPrivValidator(dir)
if err != nil {
return err
}
if pt.pv == nil {
return ErrFileNotFound
}
return nil
}
func (pt *PrivValidatorTool) backupName(branchName string) string {
return fmt.Sprintf("%v/%v-%v.json", filepath.Dir(pt.pv.filePath), PRIV_FILE_NAME, branchName)
}
func (pt *PrivValidatorTool) BackupData(branchName string) error {
bkName := pt.backupName(branchName)
find, err := utils.PathExists(bkName)
if err != nil {
return err
}
if find {
return ErrBranchIsUsed
}
preDir := pt.pv.filePath
pt.pv.SetFile(bkName)
pt.pv.Save()
pt.pv.SetFile(preDir)
return nil
}
func (pt *PrivValidatorTool) RevertFromBackup(branchName string) error {
bkName := pt.backupName(branchName)
find, err := utils.PathExists(bkName)
if err != nil {
return err
}
if !find {
return ErrPVRevertFromBackup
}
utils.CopyFile(pt.pv.filePath, bkName)
return nil
}
func (pt *PrivValidatorTool) DelBackup(branchName string) {
os.Remove(pt.backupName(branchName))
}
func (pt *PrivValidatorTool) SaveNewPrivV(toHeight int64) error {
pt.pv.LastHeight = toHeight
pt.pv.LastRound = 0
pt.pv.LastStep = 0
pt.pv.LastSignature = nil
pt.pv.LastSignBytes = make([]byte, 0)
pt.pv.Save()
return nil
}
|
{
"pile_set_name": "Github"
}
|
from __future__ import absolute_import
import cython
from Cython.Plex.Actions cimport Action
cdef class Scanner:
cdef public lexicon
cdef public stream
cdef public name
cdef public unicode buffer
cdef public Py_ssize_t buf_start_pos
cdef public Py_ssize_t next_pos
cdef public Py_ssize_t cur_pos
cdef public Py_ssize_t cur_line
cdef public Py_ssize_t cur_line_start
cdef public Py_ssize_t start_pos
cdef public Py_ssize_t start_line
cdef public Py_ssize_t start_col
cdef public text
cdef public initial_state # int?
cdef public state_name
cdef public list queue
cdef public bint trace
cdef public cur_char
cdef public long input_state
cdef public level
@cython.locals(input_state=long)
cdef next_char(self)
@cython.locals(action=Action)
cpdef tuple read(self)
cdef tuple scan_a_token(self)
cdef tuple position(self)
@cython.locals(cur_pos=Py_ssize_t, cur_line=Py_ssize_t, cur_line_start=Py_ssize_t,
input_state=long, next_pos=Py_ssize_t, state=dict,
buf_start_pos=Py_ssize_t, buf_len=Py_ssize_t, buf_index=Py_ssize_t,
trace=bint, discard=Py_ssize_t, data=unicode, buffer=unicode)
cdef run_machine_inlined(self)
cdef begin(self, state)
cdef produce(self, value, text = *)
|
{
"pile_set_name": "Github"
}
|
#import "PNAPICallBuilder.h"
#import "PNStructures.h"
#pragma mark Class forward
@class PNAPNSModificationAPICallBuilder, PNAPNSAuditAPICallBuilder;
NS_ASSUME_NONNULL_BEGIN
/**
* @brief APNS API call builder.
*
* @author Serhii Mamontov
* @version 4.12.0
* @since 4.5.4
* @copyright © 2010-2019 PubNub, Inc.
*/
@interface PNAPNSAPICallBuilder : PNAPICallBuilder
#pragma mark - APNS state manipulation
/**
* @brief Push notifications state manipulation API access builder block.
*
* @return API call configuration builder.
*
* @since 4.5.4
*/
@property (nonatomic, readonly, strong) PNAPNSModificationAPICallBuilder * (^enable)(void);
/**
* @brief Push notifications state manipulation API access builder block.
*
* @return API call configuration builder.
*
* @since 4.5.4
*/
@property (nonatomic, readonly, strong) PNAPNSModificationAPICallBuilder * (^disable)(void);
/**
* @brief Push notifications state manipulation API access builder block.
*
* @return API call configuration builder.
*
* @since 4.12.0
*/
@property (nonatomic, readonly, strong) PNAPNSModificationAPICallBuilder * (^disableAll)(void);
#pragma mark - APNS state audition
/**
* @brief Push notifications state audition API access builder block.
*
* @return API call configuration builder.
*
* @since 4.5.4
*/
@property (nonatomic, readonly, strong) PNAPNSAuditAPICallBuilder * (^audit)(void);
#pragma mark -
@end
NS_ASSUME_NONNULL_END
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Copyright (c) 2010 International Business Machines Corporation and others. All rights reserved.
-->
<!DOCTYPE ldml SYSTEM "http://www.unicode.org/repos/cldr/trunk/common/dtd/ldml.dtd">
<ldml>
<identity>
<version number="$Revision: 1.1 $"/>
<generation date="$Date: 2009/03/24 17:39:34 $"/>
<language type="et"/>
</identity>
</ldml>
|
{
"pile_set_name": "Github"
}
|
//
// AVAssetCatalogCreatorTests.swift
// AVAssetCatalogCreatorTests
//
// Created by Angel Vasa on 23/04/16.
// Copyright © 2016 Angel Vasa. All rights reserved.
//
import XCTest
@testable import AVAssetCatalogCreator
class AVAssetCatalogCreatorTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
|
{
"pile_set_name": "Github"
}
|
/* CacheFiles extended attribute management
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/fsnotify.h>
#include <linux/quotaops.h>
#include <linux/xattr.h>
#include <linux/slab.h>
#include "internal.h"
static const char cachefiles_xattr_cache[] =
XATTR_USER_PREFIX "CacheFiles.cache";
/*
* check the type label on an object
* - done using xattrs
*/
int cachefiles_check_object_type(struct cachefiles_object *object)
{
struct dentry *dentry = object->dentry;
char type[3], xtype[3];
int ret;
ASSERT(dentry);
ASSERT(d_backing_inode(dentry));
if (!object->fscache.cookie)
strcpy(type, "C3");
else
snprintf(type, 3, "%02x", object->fscache.cookie->def->type);
_enter("%p{%s}", object, type);
/* attempt to install a type label directly */
ret = vfs_setxattr(dentry, cachefiles_xattr_cache, type, 2,
XATTR_CREATE);
if (ret == 0) {
_debug("SET"); /* we succeeded */
goto error;
}
if (ret != -EEXIST) {
pr_err("Can't set xattr on %pd [%lu] (err %d)\n",
dentry, d_backing_inode(dentry)->i_ino,
-ret);
goto error;
}
/* read the current type label */
ret = vfs_getxattr(dentry, cachefiles_xattr_cache, xtype, 3);
if (ret < 0) {
if (ret == -ERANGE)
goto bad_type_length;
pr_err("Can't read xattr on %pd [%lu] (err %d)\n",
dentry, d_backing_inode(dentry)->i_ino,
-ret);
goto error;
}
/* check the type is what we're expecting */
if (ret != 2)
goto bad_type_length;
if (xtype[0] != type[0] || xtype[1] != type[1])
goto bad_type;
ret = 0;
error:
_leave(" = %d", ret);
return ret;
bad_type_length:
pr_err("Cache object %lu type xattr length incorrect\n",
d_backing_inode(dentry)->i_ino);
ret = -EIO;
goto error;
bad_type:
xtype[2] = 0;
pr_err("Cache object %pd [%lu] type %s not %s\n",
dentry, d_backing_inode(dentry)->i_ino,
xtype, type);
ret = -EIO;
goto error;
}
/*
* set the state xattr on a cache file
*/
int cachefiles_set_object_xattr(struct cachefiles_object *object,
struct cachefiles_xattr *auxdata)
{
struct dentry *dentry = object->dentry;
int ret;
ASSERT(dentry);
_enter("%p,#%d", object, auxdata->len);
/* attempt to install the cache metadata directly */
_debug("SET #%u", auxdata->len);
clear_bit(FSCACHE_COOKIE_AUX_UPDATED, &object->fscache.cookie->flags);
ret = vfs_setxattr(dentry, cachefiles_xattr_cache,
&auxdata->type, auxdata->len,
XATTR_CREATE);
if (ret < 0 && ret != -ENOMEM)
cachefiles_io_error_obj(
object,
"Failed to set xattr with error %d", ret);
_leave(" = %d", ret);
return ret;
}
/*
* update the state xattr on a cache file
*/
int cachefiles_update_object_xattr(struct cachefiles_object *object,
struct cachefiles_xattr *auxdata)
{
struct dentry *dentry = object->dentry;
int ret;
if (!dentry)
return -ESTALE;
_enter("%p,#%d", object, auxdata->len);
/* attempt to install the cache metadata directly */
_debug("SET #%u", auxdata->len);
clear_bit(FSCACHE_COOKIE_AUX_UPDATED, &object->fscache.cookie->flags);
ret = vfs_setxattr(dentry, cachefiles_xattr_cache,
&auxdata->type, auxdata->len,
XATTR_REPLACE);
if (ret < 0 && ret != -ENOMEM)
cachefiles_io_error_obj(
object,
"Failed to update xattr with error %d", ret);
_leave(" = %d", ret);
return ret;
}
/*
* check the consistency between the backing cache and the FS-Cache cookie
*/
int cachefiles_check_auxdata(struct cachefiles_object *object)
{
struct cachefiles_xattr *auxbuf;
enum fscache_checkaux validity;
struct dentry *dentry = object->dentry;
ssize_t xlen;
int ret;
ASSERT(dentry);
ASSERT(d_backing_inode(dentry));
ASSERT(object->fscache.cookie->def->check_aux);
auxbuf = kmalloc(sizeof(struct cachefiles_xattr) + 512, GFP_KERNEL);
if (!auxbuf)
return -ENOMEM;
xlen = vfs_getxattr(dentry, cachefiles_xattr_cache,
&auxbuf->type, 512 + 1);
ret = -ESTALE;
if (xlen < 1 ||
auxbuf->type != object->fscache.cookie->def->type)
goto error;
xlen--;
validity = fscache_check_aux(&object->fscache, &auxbuf->data, xlen,
i_size_read(d_backing_inode(dentry)));
if (validity != FSCACHE_CHECKAUX_OKAY)
goto error;
ret = 0;
error:
kfree(auxbuf);
return ret;
}
/*
* check the state xattr on a cache file
* - return -ESTALE if the object should be deleted
*/
int cachefiles_check_object_xattr(struct cachefiles_object *object,
struct cachefiles_xattr *auxdata)
{
struct cachefiles_xattr *auxbuf;
struct dentry *dentry = object->dentry;
int ret;
_enter("%p,#%d", object, auxdata->len);
ASSERT(dentry);
ASSERT(d_backing_inode(dentry));
auxbuf = kmalloc(sizeof(struct cachefiles_xattr) + 512, cachefiles_gfp);
if (!auxbuf) {
_leave(" = -ENOMEM");
return -ENOMEM;
}
/* read the current type label */
ret = vfs_getxattr(dentry, cachefiles_xattr_cache,
&auxbuf->type, 512 + 1);
if (ret < 0) {
if (ret == -ENODATA)
goto stale; /* no attribute - power went off
* mid-cull? */
if (ret == -ERANGE)
goto bad_type_length;
cachefiles_io_error_obj(object,
"Can't read xattr on %lu (err %d)",
d_backing_inode(dentry)->i_ino, -ret);
goto error;
}
/* check the on-disk object */
if (ret < 1)
goto bad_type_length;
if (auxbuf->type != auxdata->type)
goto stale;
auxbuf->len = ret;
/* consult the netfs */
if (object->fscache.cookie->def->check_aux) {
enum fscache_checkaux result;
unsigned int dlen;
dlen = auxbuf->len - 1;
_debug("checkaux %s #%u",
object->fscache.cookie->def->name, dlen);
result = fscache_check_aux(&object->fscache,
&auxbuf->data, dlen,
i_size_read(d_backing_inode(dentry)));
switch (result) {
/* entry okay as is */
case FSCACHE_CHECKAUX_OKAY:
goto okay;
/* entry requires update */
case FSCACHE_CHECKAUX_NEEDS_UPDATE:
break;
/* entry requires deletion */
case FSCACHE_CHECKAUX_OBSOLETE:
goto stale;
default:
BUG();
}
/* update the current label */
ret = vfs_setxattr(dentry, cachefiles_xattr_cache,
&auxdata->type, auxdata->len,
XATTR_REPLACE);
if (ret < 0) {
cachefiles_io_error_obj(object,
"Can't update xattr on %lu"
" (error %d)",
d_backing_inode(dentry)->i_ino, -ret);
goto error;
}
}
okay:
ret = 0;
error:
kfree(auxbuf);
_leave(" = %d", ret);
return ret;
bad_type_length:
pr_err("Cache object %lu xattr length incorrect\n",
d_backing_inode(dentry)->i_ino);
ret = -EIO;
goto error;
stale:
ret = -ESTALE;
goto error;
}
/*
* remove the object's xattr to mark it stale
*/
int cachefiles_remove_object_xattr(struct cachefiles_cache *cache,
struct dentry *dentry)
{
int ret;
ret = vfs_removexattr(dentry, cachefiles_xattr_cache);
if (ret < 0) {
if (ret == -ENOENT || ret == -ENODATA)
ret = 0;
else if (ret != -ENOMEM)
cachefiles_io_error(cache,
"Can't remove xattr from %lu"
" (error %d)",
d_backing_inode(dentry)->i_ino, -ret);
}
_leave(" = %d", ret);
return ret;
}
|
{
"pile_set_name": "Github"
}
|
--TEST--
Test pclose() function : usage variation
--CREDITS--
Dave Kelsey <d_kelsey@uk.ibm.com>
--FILE--
<?php
/* Prototype : int pclose(resource fp)
* Description: Close a file pointer opened by popen()
* Source code: ext/standard/file.c
* Alias to functions:
*/
echo "*** Testing pclose() : usage variation ***\n";
// Define error handler
function test_error_handler($err_no, $err_msg, $filename, $linenum, $vars) {
if (error_reporting() != 0) {
// report non-silenced errors
echo "Error: $err_no - $err_msg, $filename($linenum)\n";
}
}
set_error_handler('test_error_handler');
// Initialise function arguments not being substituted (if any)
//get an unset variable
$unset_var = 10;
unset ($unset_var);
// define some classes
class classWithToString
{
public function __toString() {
return "Class A object";
}
}
class classWithoutToString
{
}
// heredoc string
$heredoc = <<<EOT
hello world
EOT;
// add arrays
$index_array = array (1, 2, 3);
$assoc_array = array ('one' => 1, 'two' => 2);
//array of values to iterate over
$inputs = array(
// int data
'int 0' => 0,
'int 1' => 1,
'int 12345' => 12345,
'int -12345' => -2345,
// float data
'float 10.5' => 10.5,
'float -10.5' => -10.5,
'float 12.3456789000e10' => 12.3456789000e10,
'float -12.3456789000e10' => -12.3456789000e10,
'float .5' => .5,
// array data
'empty array' => array(),
'int indexed array' => $index_array,
'associative array' => $assoc_array,
'nested arrays' => array('foo', $index_array, $assoc_array),
// null data
'uppercase NULL' => NULL,
'lowercase null' => null,
// boolean data
'lowercase true' => true,
'lowercase false' =>false,
'uppercase TRUE' =>TRUE,
'uppercase FALSE' =>FALSE,
// empty data
'empty string DQ' => "",
'empty string SQ' => '',
// string data
'string DQ' => "string",
'string SQ' => 'string',
'mixed case string' => "sTrInG",
'heredoc' => $heredoc,
// object data
'instance of classWithToString' => new classWithToString(),
'instance of classWithoutToString' => new classWithoutToString(),
// undefined data
'undefined var' => @$undefined_var,
// unset data
'unset var' => @$unset_var,
);
// loop through each element of the array for fp
foreach($inputs as $key =>$value) {
echo "\n--$key--\n";
var_dump( pclose($value) );
};
?>
===DONE===
--EXPECTF--
*** Testing pclose() : usage variation ***
--int 0--
Error: 2 - pclose() expects parameter 1 to be resource, integer given, %s(%d)
bool(false)
--int 1--
Error: 2 - pclose() expects parameter 1 to be resource, integer given, %s(%d)
bool(false)
--int 12345--
Error: 2 - pclose() expects parameter 1 to be resource, integer given, %s(%d)
bool(false)
--int -12345--
Error: 2 - pclose() expects parameter 1 to be resource, integer given, %s(%d)
bool(false)
--float 10.5--
Error: 2 - pclose() expects parameter 1 to be resource, double given, %s(%d)
bool(false)
--float -10.5--
Error: 2 - pclose() expects parameter 1 to be resource, double given, %s(%d)
bool(false)
--float 12.3456789000e10--
Error: 2 - pclose() expects parameter 1 to be resource, double given, %s(%d)
bool(false)
--float -12.3456789000e10--
Error: 2 - pclose() expects parameter 1 to be resource, double given, %s(%d)
bool(false)
--float .5--
Error: 2 - pclose() expects parameter 1 to be resource, double given, %s(%d)
bool(false)
--empty array--
Error: 2 - pclose() expects parameter 1 to be resource, array given, %s(%d)
bool(false)
--int indexed array--
Error: 2 - pclose() expects parameter 1 to be resource, array given, %s(%d)
bool(false)
--associative array--
Error: 2 - pclose() expects parameter 1 to be resource, array given, %s(%d)
bool(false)
--nested arrays--
Error: 2 - pclose() expects parameter 1 to be resource, array given, %s(%d)
bool(false)
--uppercase NULL--
Error: 2 - pclose() expects parameter 1 to be resource, null given, %s(%d)
bool(false)
--lowercase null--
Error: 2 - pclose() expects parameter 1 to be resource, null given, %s(%d)
bool(false)
--lowercase true--
Error: 2 - pclose() expects parameter 1 to be resource, boolean given, %s(%d)
bool(false)
--lowercase false--
Error: 2 - pclose() expects parameter 1 to be resource, boolean given, %s(%d)
bool(false)
--uppercase TRUE--
Error: 2 - pclose() expects parameter 1 to be resource, boolean given, %s(%d)
bool(false)
--uppercase FALSE--
Error: 2 - pclose() expects parameter 1 to be resource, boolean given, %s(%d)
bool(false)
--empty string DQ--
Error: 2 - pclose() expects parameter 1 to be resource, string given, %s(%d)
bool(false)
--empty string SQ--
Error: 2 - pclose() expects parameter 1 to be resource, string given, %s(%d)
bool(false)
--string DQ--
Error: 2 - pclose() expects parameter 1 to be resource, string given, %s(%d)
bool(false)
--string SQ--
Error: 2 - pclose() expects parameter 1 to be resource, string given, %s(%d)
bool(false)
--mixed case string--
Error: 2 - pclose() expects parameter 1 to be resource, string given, %s(%d)
bool(false)
--heredoc--
Error: 2 - pclose() expects parameter 1 to be resource, string given, %s(%d)
bool(false)
--instance of classWithToString--
Error: 2 - pclose() expects parameter 1 to be resource, object given, %s(%d)
bool(false)
--instance of classWithoutToString--
Error: 2 - pclose() expects parameter 1 to be resource, object given, %s(%d)
bool(false)
--undefined var--
Error: 2 - pclose() expects parameter 1 to be resource, null given, %s(%d)
bool(false)
--unset var--
Error: 2 - pclose() expects parameter 1 to be resource, null given, %s(%d)
bool(false)
===DONE===
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Globalization;
namespace NuGetGallery
{
[Serializable]
public class EntityException : Exception
{
public EntityException(string message)
: base(message)
{
}
public EntityException(
string message,
params object[] args)
: base(String.Format(CultureInfo.CurrentCulture, message, args))
{
}
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<monster name="Yalahari" nameDescription="a Yalahari" race="blood" experience="5" speed="200">
<health now="150" max="150" />
<look type="309" corpse="20550" />
<targetchange interval="5000" chance="8" />
<flags>
<flag summonable="0" />
<flag attackable="1" />
<flag hostile="0" />
<flag illusionable="0" />
<flag convinceable="0" />
<flag pushable="0" />
<flag canpushitems="1" />
<flag canpushcreatures="0" />
<flag targetdistance="1" />
<flag staticattack="90" />
<flag runonhealth="0" />
</flags>
<defenses armor="0" defense="0" />
<immunities>
<immunity earth="1" />
<immunity physical="1" />
<immunity death="1" />
</immunities>
<voices interval="5000" chance="11">
<voice sentence="Welcome to Yalahar, outsider." />
<voice sentence="Hail Yalahar." />
<voice sentence="You can learn a lot from us." />
<voice sentence="Our wisdom and knowledge are unequalled in this world." />
<voice sentence="That knowledge would overburden your fragile mind." />
<voice sentence="I wouldn't expect you to understand." />
<voice sentence="One day Yalahar will return to its former glory." />
</voices>
</monster>
|
{
"pile_set_name": "Github"
}
|
/**
* MediaWiki style sheet for common core styles on interfaces
*
* Styles for the Monobook/Vector pattern of laying out common interfaces.
* These ids/classes are not built into the system,
* they are outputted by the actual MonoBook/Vector code by convention.
*/
/* stylelint-disable selector-class-pattern */
/* Categories */
.catlinks {
border: 1px solid #a2a9b1;
background-color: #f8f9fa;
padding: 5px;
margin-top: 1em;
clear: both;
}
textarea {
/* Support: Firefox */
/* Border rule required to override system appearance on Linux (T136415) */
border: 1px solid #c8ccd1;
}
.editOptions {
background-color: #eaecf0;
color: #202122;
border: 1px solid #c8ccd1;
border-top: 0;
padding: 1em 1em 1.5em 1em;
margin-bottom: 2em;
}
.usermessage {
background-color: #ffce7b;
border: 1px solid #ffa500;
color: #000;
font-weight: bold;
margin: 2em 0 1em;
padding: 0.5em 1em;
vertical-align: middle;
}
#siteNotice {
position: relative;
text-align: center;
margin: 0;
}
#localNotice {
margin-bottom: 0.9em;
}
/* Sub-navigation */
#siteSub {
display: none;
}
#contentSub,
#contentSub2 {
font-size: 84%;
line-height: 1.2em;
margin: 0 0 1.4em 1em;
color: #54595d;
width: auto;
}
span.subpages {
display: block;
}
/**
* Hide empty portlets. Controlled by mw.util.(show|hide)Portlet.
*
* Note: Historically this class was provided by the skins themselves but in
* I2ba68122fd82a254a5ad0e45157f095508f6fa39 was moved into core to formalize
* the behaviour of hidden portlets.
*/
.emptyPortlet {
display: none;
}
/* Hide links which require JavaScript to work */
.client-nojs #t-print {
display: none; /* T167956 */
}
|
{
"pile_set_name": "Github"
}
|
import { LinearGradient } from 'expo-linear-gradient';
import React from 'react';
import {
Dimensions,
Image,
StyleSheet,
TouchableOpacity,
TouchableWithoutFeedback,
View,
} from 'react-native';
import { connect } from 'react-redux';
import dispatch from '../../rematch/dispatch';
import Indicator from './Indicator';
// import Image from 'react-native-image-progress';
// import CircleSnail from 'react-native-progress/CircleSnail';
// indicator={CircleSnail}
const ENABLE_TOUCHABLES = true;
const circleSnailProps = { thickness: 1, color: '#ddd', size: 80 };
const { width, height } = Dimensions.get('window');
class Story extends React.Component {
render() {
const { story } = this.props;
if (!ENABLE_TOUCHABLES) {
return (
<View style={{ flex: 1 }}>
<Image
source={story.items[story.idx]}
style={styles.deck}
indicatorProps={circleSnailProps}
/>
{this.renderIndicators()}
{this.renderCloseButton()}
{this.renderBackButton()}
</View>
);
}
return (
<TouchableOpacity
onPress={() => {
dispatch().stories.onNextItem();
}}
delayPressIn={200}
onPressIn={() => {
dispatch().stories.pause();
}}
>
<View style={{ flex: 1 }}>
<Image
source={story.items[story.idx]}
style={styles.deck}
indicatorProps={circleSnailProps}
/>
{this.renderIndicators()}
{this.renderCloseButton()}
{this.renderBackButton()}
</View>
</TouchableOpacity>
);
}
renderCloseButton() {
return (
<TouchableWithoutFeedback
onPress={() => {
dispatch().stories.dismissCarousel();
}}
>
<View style={styles.closeButton}>
<View
style={[styles.closeCross, { transform: [{ rotate: '45deg' }] }]}
/>
<View
style={[styles.closeCross, { transform: [{ rotate: '-45deg' }] }]}
/>
</View>
</TouchableWithoutFeedback>
);
}
renderIndicators() {
const { story, currentDeck } = this.props;
return (
<View style={styles.indicatorWrap}>
<LinearGradient
colors={['rgba(0,0,0,0.33)', 'transparent']}
locations={[0, 0.95]}
style={styles.indicatorBg}
/>
<View style={styles.indicators}>
{story.items.map((item, i) => (
<Indicator
key={i}
i={i}
animate={currentDeck && story.idx == i}
story={story}
/>
))}
</View>
</View>
);
}
renderBackButton() {
const { backOpacity } = this.props;
return (
<TouchableWithoutFeedback
onPress={() => {
dispatch().stories.onPrevItem();
}}
onPressIn={() => dispatch().stories.setBackOpacity(1)}
onLongPress={() => dispatch().stories.setBackOpacity(0)}
>
<LinearGradient
colors={['rgba(0,0,0,0.33)', 'transparent']}
locations={[0, 0.85]}
start={[0, 0]}
end={[1, 0]}
style={[
styles.back,
{
opacity: backOpacity,
},
]}
/>
</TouchableWithoutFeedback>
);
}
}
export default connect(({ stories }) => ({ ...stories }))(Story);
const styles = StyleSheet.create({
deck: {
width,
height,
backgroundColor: 'black',
},
progressIndicator: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
},
indicatorWrap: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
},
indicators: {
height: 30,
alignItems: 'center',
paddingHorizontal: 8,
flexDirection: 'row',
},
indicatorBg: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: 50,
},
back: {
backgroundColor: 'transparent',
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
width: 90,
},
closeButton: {
position: 'absolute',
top: 0,
right: 0,
width: 70,
height: 70,
zIndex: 1,
},
closeCross: {
position: 'absolute',
top: 32,
right: 8,
width: 20,
height: 1,
backgroundColor: '#fff',
},
});
|
{
"pile_set_name": "Github"
}
|
---
-api-id: P:Windows.UI.Xaml.UIElement.Clip
-api-type: winrt property
---
<!-- Property syntax
public Windows.UI.Xaml.Media.RectangleGeometry Clip { get; set; }
-->
# Windows.UI.Xaml.UIElement.Clip
## -description
Gets or sets the [RectangleGeometry](../windows.ui.xaml.media/rectanglegeometry.md) used to define the outline of the contents of a [UIElement](uielement.md).
## -xaml-syntax
```xaml
<uiElement>
<uiElement.Clip>
rectangleGeometry
</uiElement.Clip>
</uiElement>
```
## -property-value
The rectangle geometry to be used for clipping area sizing. The default value is **null** (no clipping).
## -remarks
The clipping geometry for UIElement.Clip in the Windows Runtime API must be a [RectangleGeometry](../windows.ui.xaml.media/rectanglegeometry.md). You can't specify a non-rectangular geometry, as is permitted in some XAML frameworks like Microsoft Silverlight.
The clipped area is the "outside" of the geometry. In other words, the content that is shown (not clipped) is the area of the rectangle that is drawn with [Fill](../windows.ui.xaml.shapes/shape_fill.md) if the geometry were used as data for a [Path](../windows.ui.xaml.shapes/path.md) rather than for clipping. The clipped area is any area that falls outside the rectangle. The clipped area isn't hit-testable.
## -examples
This example is simple XAML markup that specifies a Clip using an inline [RectangleGeometry](../windows.ui.xaml.media/rectanglegeometry.md) that specifies its dimensions through an attribute syntax.
[!code-xaml[GeometryOvw4](../windows.ui.xaml/code/geometries_snip/csharp/GeometryOvw4.xaml#SnippetGeometryOvw4)]
## -see-also
|
{
"pile_set_name": "Github"
}
|
.text
.type _aesni_ctr32_ghash_6x,@function
.align 32
_aesni_ctr32_ghash_6x:
vmovdqu 32(%r11),%xmm2
subq $6,%rdx
vpxor %xmm4,%xmm4,%xmm4
vmovdqu 0-128(%rcx),%xmm15
vpaddb %xmm2,%xmm1,%xmm10
vpaddb %xmm2,%xmm10,%xmm11
vpaddb %xmm2,%xmm11,%xmm12
vpaddb %xmm2,%xmm12,%xmm13
vpaddb %xmm2,%xmm13,%xmm14
vpxor %xmm15,%xmm1,%xmm9
vmovdqu %xmm4,16+8(%rsp)
jmp .Loop6x
.align 32
.Loop6x:
addl $100663296,%ebx
jc .Lhandle_ctr32
vmovdqu 0-32(%r9),%xmm3
vpaddb %xmm2,%xmm14,%xmm1
vpxor %xmm15,%xmm10,%xmm10
vpxor %xmm15,%xmm11,%xmm11
.Lresume_ctr32:
vmovdqu %xmm1,(%r8)
vpclmulqdq $0x10,%xmm3,%xmm7,%xmm5
vpxor %xmm15,%xmm12,%xmm12
vmovups 16-128(%rcx),%xmm2
vpclmulqdq $0x01,%xmm3,%xmm7,%xmm6
xorq %r12,%r12
cmpq %r14,%r15
vaesenc %xmm2,%xmm9,%xmm9
vmovdqu 48+8(%rsp),%xmm0
vpxor %xmm15,%xmm13,%xmm13
vpclmulqdq $0x00,%xmm3,%xmm7,%xmm1
vaesenc %xmm2,%xmm10,%xmm10
vpxor %xmm15,%xmm14,%xmm14
setnc %r12b
vpclmulqdq $0x11,%xmm3,%xmm7,%xmm7
vaesenc %xmm2,%xmm11,%xmm11
vmovdqu 16-32(%r9),%xmm3
negq %r12
vaesenc %xmm2,%xmm12,%xmm12
vpxor %xmm5,%xmm6,%xmm6
vpclmulqdq $0x00,%xmm3,%xmm0,%xmm5
vpxor %xmm4,%xmm8,%xmm8
vaesenc %xmm2,%xmm13,%xmm13
vpxor %xmm5,%xmm1,%xmm4
andq $0x60,%r12
vmovups 32-128(%rcx),%xmm15
vpclmulqdq $0x10,%xmm3,%xmm0,%xmm1
vaesenc %xmm2,%xmm14,%xmm14
vpclmulqdq $0x01,%xmm3,%xmm0,%xmm2
leaq (%r14,%r12,1),%r14
vaesenc %xmm15,%xmm9,%xmm9
vpxor 16+8(%rsp),%xmm8,%xmm8
vpclmulqdq $0x11,%xmm3,%xmm0,%xmm3
vmovdqu 64+8(%rsp),%xmm0
vaesenc %xmm15,%xmm10,%xmm10
movbeq 88(%r14),%r13
vaesenc %xmm15,%xmm11,%xmm11
movbeq 80(%r14),%r12
vaesenc %xmm15,%xmm12,%xmm12
movq %r13,32+8(%rsp)
vaesenc %xmm15,%xmm13,%xmm13
movq %r12,40+8(%rsp)
vmovdqu 48-32(%r9),%xmm5
vaesenc %xmm15,%xmm14,%xmm14
vmovups 48-128(%rcx),%xmm15
vpxor %xmm1,%xmm6,%xmm6
vpclmulqdq $0x00,%xmm5,%xmm0,%xmm1
vaesenc %xmm15,%xmm9,%xmm9
vpxor %xmm2,%xmm6,%xmm6
vpclmulqdq $0x10,%xmm5,%xmm0,%xmm2
vaesenc %xmm15,%xmm10,%xmm10
vpxor %xmm3,%xmm7,%xmm7
vpclmulqdq $0x01,%xmm5,%xmm0,%xmm3
vaesenc %xmm15,%xmm11,%xmm11
vpclmulqdq $0x11,%xmm5,%xmm0,%xmm5
vmovdqu 80+8(%rsp),%xmm0
vaesenc %xmm15,%xmm12,%xmm12
vaesenc %xmm15,%xmm13,%xmm13
vpxor %xmm1,%xmm4,%xmm4
vmovdqu 64-32(%r9),%xmm1
vaesenc %xmm15,%xmm14,%xmm14
vmovups 64-128(%rcx),%xmm15
vpxor %xmm2,%xmm6,%xmm6
vpclmulqdq $0x00,%xmm1,%xmm0,%xmm2
vaesenc %xmm15,%xmm9,%xmm9
vpxor %xmm3,%xmm6,%xmm6
vpclmulqdq $0x10,%xmm1,%xmm0,%xmm3
vaesenc %xmm15,%xmm10,%xmm10
movbeq 72(%r14),%r13
vpxor %xmm5,%xmm7,%xmm7
vpclmulqdq $0x01,%xmm1,%xmm0,%xmm5
vaesenc %xmm15,%xmm11,%xmm11
movbeq 64(%r14),%r12
vpclmulqdq $0x11,%xmm1,%xmm0,%xmm1
vmovdqu 96+8(%rsp),%xmm0
vaesenc %xmm15,%xmm12,%xmm12
movq %r13,48+8(%rsp)
vaesenc %xmm15,%xmm13,%xmm13
movq %r12,56+8(%rsp)
vpxor %xmm2,%xmm4,%xmm4
vmovdqu 96-32(%r9),%xmm2
vaesenc %xmm15,%xmm14,%xmm14
vmovups 80-128(%rcx),%xmm15
vpxor %xmm3,%xmm6,%xmm6
vpclmulqdq $0x00,%xmm2,%xmm0,%xmm3
vaesenc %xmm15,%xmm9,%xmm9
vpxor %xmm5,%xmm6,%xmm6
vpclmulqdq $0x10,%xmm2,%xmm0,%xmm5
vaesenc %xmm15,%xmm10,%xmm10
movbeq 56(%r14),%r13
vpxor %xmm1,%xmm7,%xmm7
vpclmulqdq $0x01,%xmm2,%xmm0,%xmm1
vpxor 112+8(%rsp),%xmm8,%xmm8
vaesenc %xmm15,%xmm11,%xmm11
movbeq 48(%r14),%r12
vpclmulqdq $0x11,%xmm2,%xmm0,%xmm2
vaesenc %xmm15,%xmm12,%xmm12
movq %r13,64+8(%rsp)
vaesenc %xmm15,%xmm13,%xmm13
movq %r12,72+8(%rsp)
vpxor %xmm3,%xmm4,%xmm4
vmovdqu 112-32(%r9),%xmm3
vaesenc %xmm15,%xmm14,%xmm14
vmovups 96-128(%rcx),%xmm15
vpxor %xmm5,%xmm6,%xmm6
vpclmulqdq $0x10,%xmm3,%xmm8,%xmm5
vaesenc %xmm15,%xmm9,%xmm9
vpxor %xmm1,%xmm6,%xmm6
vpclmulqdq $0x01,%xmm3,%xmm8,%xmm1
vaesenc %xmm15,%xmm10,%xmm10
movbeq 40(%r14),%r13
vpxor %xmm2,%xmm7,%xmm7
vpclmulqdq $0x00,%xmm3,%xmm8,%xmm2
vaesenc %xmm15,%xmm11,%xmm11
movbeq 32(%r14),%r12
vpclmulqdq $0x11,%xmm3,%xmm8,%xmm8
vaesenc %xmm15,%xmm12,%xmm12
movq %r13,80+8(%rsp)
vaesenc %xmm15,%xmm13,%xmm13
movq %r12,88+8(%rsp)
vpxor %xmm5,%xmm6,%xmm6
vaesenc %xmm15,%xmm14,%xmm14
vpxor %xmm1,%xmm6,%xmm6
vmovups 112-128(%rcx),%xmm15
vpslldq $8,%xmm6,%xmm5
vpxor %xmm2,%xmm4,%xmm4
vmovdqu 16(%r11),%xmm3
vaesenc %xmm15,%xmm9,%xmm9
vpxor %xmm8,%xmm7,%xmm7
vaesenc %xmm15,%xmm10,%xmm10
vpxor %xmm5,%xmm4,%xmm4
movbeq 24(%r14),%r13
vaesenc %xmm15,%xmm11,%xmm11
movbeq 16(%r14),%r12
vpalignr $8,%xmm4,%xmm4,%xmm0
vpclmulqdq $0x10,%xmm3,%xmm4,%xmm4
movq %r13,96+8(%rsp)
vaesenc %xmm15,%xmm12,%xmm12
movq %r12,104+8(%rsp)
vaesenc %xmm15,%xmm13,%xmm13
vmovups 128-128(%rcx),%xmm1
vaesenc %xmm15,%xmm14,%xmm14
vaesenc %xmm1,%xmm9,%xmm9
vmovups 144-128(%rcx),%xmm15
vaesenc %xmm1,%xmm10,%xmm10
vpsrldq $8,%xmm6,%xmm6
vaesenc %xmm1,%xmm11,%xmm11
vpxor %xmm6,%xmm7,%xmm7
vaesenc %xmm1,%xmm12,%xmm12
vpxor %xmm0,%xmm4,%xmm4
movbeq 8(%r14),%r13
vaesenc %xmm1,%xmm13,%xmm13
movbeq 0(%r14),%r12
vaesenc %xmm1,%xmm14,%xmm14
vmovups 160-128(%rcx),%xmm1
cmpl $11,%ebp
jb .Lenc_tail
vaesenc %xmm15,%xmm9,%xmm9
vaesenc %xmm15,%xmm10,%xmm10
vaesenc %xmm15,%xmm11,%xmm11
vaesenc %xmm15,%xmm12,%xmm12
vaesenc %xmm15,%xmm13,%xmm13
vaesenc %xmm15,%xmm14,%xmm14
vaesenc %xmm1,%xmm9,%xmm9
vaesenc %xmm1,%xmm10,%xmm10
vaesenc %xmm1,%xmm11,%xmm11
vaesenc %xmm1,%xmm12,%xmm12
vaesenc %xmm1,%xmm13,%xmm13
vmovups 176-128(%rcx),%xmm15
vaesenc %xmm1,%xmm14,%xmm14
vmovups 192-128(%rcx),%xmm1
je .Lenc_tail
vaesenc %xmm15,%xmm9,%xmm9
vaesenc %xmm15,%xmm10,%xmm10
vaesenc %xmm15,%xmm11,%xmm11
vaesenc %xmm15,%xmm12,%xmm12
vaesenc %xmm15,%xmm13,%xmm13
vaesenc %xmm15,%xmm14,%xmm14
vaesenc %xmm1,%xmm9,%xmm9
vaesenc %xmm1,%xmm10,%xmm10
vaesenc %xmm1,%xmm11,%xmm11
vaesenc %xmm1,%xmm12,%xmm12
vaesenc %xmm1,%xmm13,%xmm13
vmovups 208-128(%rcx),%xmm15
vaesenc %xmm1,%xmm14,%xmm14
vmovups 224-128(%rcx),%xmm1
jmp .Lenc_tail
.align 32
.Lhandle_ctr32:
vmovdqu (%r11),%xmm0
vpshufb %xmm0,%xmm1,%xmm6
vmovdqu 48(%r11),%xmm5
vpaddd 64(%r11),%xmm6,%xmm10
vpaddd %xmm5,%xmm6,%xmm11
vmovdqu 0-32(%r9),%xmm3
vpaddd %xmm5,%xmm10,%xmm12
vpshufb %xmm0,%xmm10,%xmm10
vpaddd %xmm5,%xmm11,%xmm13
vpshufb %xmm0,%xmm11,%xmm11
vpxor %xmm15,%xmm10,%xmm10
vpaddd %xmm5,%xmm12,%xmm14
vpshufb %xmm0,%xmm12,%xmm12
vpxor %xmm15,%xmm11,%xmm11
vpaddd %xmm5,%xmm13,%xmm1
vpshufb %xmm0,%xmm13,%xmm13
vpshufb %xmm0,%xmm14,%xmm14
vpshufb %xmm0,%xmm1,%xmm1
jmp .Lresume_ctr32
.align 32
.Lenc_tail:
vaesenc %xmm15,%xmm9,%xmm9
vmovdqu %xmm7,16+8(%rsp)
vpalignr $8,%xmm4,%xmm4,%xmm8
vaesenc %xmm15,%xmm10,%xmm10
vpclmulqdq $0x10,%xmm3,%xmm4,%xmm4
vpxor 0(%rdi),%xmm1,%xmm2
vaesenc %xmm15,%xmm11,%xmm11
vpxor 16(%rdi),%xmm1,%xmm0
vaesenc %xmm15,%xmm12,%xmm12
vpxor 32(%rdi),%xmm1,%xmm5
vaesenc %xmm15,%xmm13,%xmm13
vpxor 48(%rdi),%xmm1,%xmm6
vaesenc %xmm15,%xmm14,%xmm14
vpxor 64(%rdi),%xmm1,%xmm7
vpxor 80(%rdi),%xmm1,%xmm3
vmovdqu (%r8),%xmm1
vaesenclast %xmm2,%xmm9,%xmm9
vmovdqu 32(%r11),%xmm2
vaesenclast %xmm0,%xmm10,%xmm10
vpaddb %xmm2,%xmm1,%xmm0
movq %r13,112+8(%rsp)
leaq 96(%rdi),%rdi
vaesenclast %xmm5,%xmm11,%xmm11
vpaddb %xmm2,%xmm0,%xmm5
movq %r12,120+8(%rsp)
leaq 96(%rsi),%rsi
vmovdqu 0-128(%rcx),%xmm15
vaesenclast %xmm6,%xmm12,%xmm12
vpaddb %xmm2,%xmm5,%xmm6
vaesenclast %xmm7,%xmm13,%xmm13
vpaddb %xmm2,%xmm6,%xmm7
vaesenclast %xmm3,%xmm14,%xmm14
vpaddb %xmm2,%xmm7,%xmm3
addq $0x60,%r10
subq $0x6,%rdx
jc .L6x_done
vmovups %xmm9,-96(%rsi)
vpxor %xmm15,%xmm1,%xmm9
vmovups %xmm10,-80(%rsi)
vmovdqa %xmm0,%xmm10
vmovups %xmm11,-64(%rsi)
vmovdqa %xmm5,%xmm11
vmovups %xmm12,-48(%rsi)
vmovdqa %xmm6,%xmm12
vmovups %xmm13,-32(%rsi)
vmovdqa %xmm7,%xmm13
vmovups %xmm14,-16(%rsi)
vmovdqa %xmm3,%xmm14
vmovdqu 32+8(%rsp),%xmm7
jmp .Loop6x
.L6x_done:
vpxor 16+8(%rsp),%xmm8,%xmm8
vpxor %xmm4,%xmm8,%xmm8
.byte 0xf3,0xc3
.size _aesni_ctr32_ghash_6x,.-_aesni_ctr32_ghash_6x
.globl aesni_gcm_decrypt
.type aesni_gcm_decrypt,@function
.align 32
aesni_gcm_decrypt:
.cfi_startproc
xorq %r10,%r10
cmpq $0x60,%rdx
jb .Lgcm_dec_abort
leaq (%rsp),%rax
.cfi_def_cfa_register %rax
pushq %rbx
.cfi_offset %rbx,-16
pushq %rbp
.cfi_offset %rbp,-24
pushq %r12
.cfi_offset %r12,-32
pushq %r13
.cfi_offset %r13,-40
pushq %r14
.cfi_offset %r14,-48
pushq %r15
.cfi_offset %r15,-56
vzeroupper
vmovdqu (%r8),%xmm1
addq $-128,%rsp
movl 12(%r8),%ebx
leaq .Lbswap_mask(%rip),%r11
leaq -128(%rcx),%r14
movq $0xf80,%r15
vmovdqu (%r9),%xmm8
andq $-128,%rsp
vmovdqu (%r11),%xmm0
leaq 128(%rcx),%rcx
leaq 32+32(%r9),%r9
movl 240-128(%rcx),%ebp
vpshufb %xmm0,%xmm8,%xmm8
andq %r15,%r14
andq %rsp,%r15
subq %r14,%r15
jc .Ldec_no_key_aliasing
cmpq $768,%r15
jnc .Ldec_no_key_aliasing
subq %r15,%rsp
.Ldec_no_key_aliasing:
vmovdqu 80(%rdi),%xmm7
leaq (%rdi),%r14
vmovdqu 64(%rdi),%xmm4
leaq -192(%rdi,%rdx,1),%r15
vmovdqu 48(%rdi),%xmm5
shrq $4,%rdx
xorq %r10,%r10
vmovdqu 32(%rdi),%xmm6
vpshufb %xmm0,%xmm7,%xmm7
vmovdqu 16(%rdi),%xmm2
vpshufb %xmm0,%xmm4,%xmm4
vmovdqu (%rdi),%xmm3
vpshufb %xmm0,%xmm5,%xmm5
vmovdqu %xmm4,48(%rsp)
vpshufb %xmm0,%xmm6,%xmm6
vmovdqu %xmm5,64(%rsp)
vpshufb %xmm0,%xmm2,%xmm2
vmovdqu %xmm6,80(%rsp)
vpshufb %xmm0,%xmm3,%xmm3
vmovdqu %xmm2,96(%rsp)
vmovdqu %xmm3,112(%rsp)
call _aesni_ctr32_ghash_6x
vmovups %xmm9,-96(%rsi)
vmovups %xmm10,-80(%rsi)
vmovups %xmm11,-64(%rsi)
vmovups %xmm12,-48(%rsi)
vmovups %xmm13,-32(%rsi)
vmovups %xmm14,-16(%rsi)
vpshufb (%r11),%xmm8,%xmm8
vmovdqu %xmm8,-64(%r9)
vzeroupper
movq -48(%rax),%r15
.cfi_restore %r15
movq -40(%rax),%r14
.cfi_restore %r14
movq -32(%rax),%r13
.cfi_restore %r13
movq -24(%rax),%r12
.cfi_restore %r12
movq -16(%rax),%rbp
.cfi_restore %rbp
movq -8(%rax),%rbx
.cfi_restore %rbx
leaq (%rax),%rsp
.cfi_def_cfa_register %rsp
.Lgcm_dec_abort:
movq %r10,%rax
.byte 0xf3,0xc3
.cfi_endproc
.size aesni_gcm_decrypt,.-aesni_gcm_decrypt
.type _aesni_ctr32_6x,@function
.align 32
_aesni_ctr32_6x:
vmovdqu 0-128(%rcx),%xmm4
vmovdqu 32(%r11),%xmm2
leaq -1(%rbp),%r13
vmovups 16-128(%rcx),%xmm15
leaq 32-128(%rcx),%r12
vpxor %xmm4,%xmm1,%xmm9
addl $100663296,%ebx
jc .Lhandle_ctr32_2
vpaddb %xmm2,%xmm1,%xmm10
vpaddb %xmm2,%xmm10,%xmm11
vpxor %xmm4,%xmm10,%xmm10
vpaddb %xmm2,%xmm11,%xmm12
vpxor %xmm4,%xmm11,%xmm11
vpaddb %xmm2,%xmm12,%xmm13
vpxor %xmm4,%xmm12,%xmm12
vpaddb %xmm2,%xmm13,%xmm14
vpxor %xmm4,%xmm13,%xmm13
vpaddb %xmm2,%xmm14,%xmm1
vpxor %xmm4,%xmm14,%xmm14
jmp .Loop_ctr32
.align 16
.Loop_ctr32:
vaesenc %xmm15,%xmm9,%xmm9
vaesenc %xmm15,%xmm10,%xmm10
vaesenc %xmm15,%xmm11,%xmm11
vaesenc %xmm15,%xmm12,%xmm12
vaesenc %xmm15,%xmm13,%xmm13
vaesenc %xmm15,%xmm14,%xmm14
vmovups (%r12),%xmm15
leaq 16(%r12),%r12
decl %r13d
jnz .Loop_ctr32
vmovdqu (%r12),%xmm3
vaesenc %xmm15,%xmm9,%xmm9
vpxor 0(%rdi),%xmm3,%xmm4
vaesenc %xmm15,%xmm10,%xmm10
vpxor 16(%rdi),%xmm3,%xmm5
vaesenc %xmm15,%xmm11,%xmm11
vpxor 32(%rdi),%xmm3,%xmm6
vaesenc %xmm15,%xmm12,%xmm12
vpxor 48(%rdi),%xmm3,%xmm8
vaesenc %xmm15,%xmm13,%xmm13
vpxor 64(%rdi),%xmm3,%xmm2
vaesenc %xmm15,%xmm14,%xmm14
vpxor 80(%rdi),%xmm3,%xmm3
leaq 96(%rdi),%rdi
vaesenclast %xmm4,%xmm9,%xmm9
vaesenclast %xmm5,%xmm10,%xmm10
vaesenclast %xmm6,%xmm11,%xmm11
vaesenclast %xmm8,%xmm12,%xmm12
vaesenclast %xmm2,%xmm13,%xmm13
vaesenclast %xmm3,%xmm14,%xmm14
vmovups %xmm9,0(%rsi)
vmovups %xmm10,16(%rsi)
vmovups %xmm11,32(%rsi)
vmovups %xmm12,48(%rsi)
vmovups %xmm13,64(%rsi)
vmovups %xmm14,80(%rsi)
leaq 96(%rsi),%rsi
.byte 0xf3,0xc3
.align 32
.Lhandle_ctr32_2:
vpshufb %xmm0,%xmm1,%xmm6
vmovdqu 48(%r11),%xmm5
vpaddd 64(%r11),%xmm6,%xmm10
vpaddd %xmm5,%xmm6,%xmm11
vpaddd %xmm5,%xmm10,%xmm12
vpshufb %xmm0,%xmm10,%xmm10
vpaddd %xmm5,%xmm11,%xmm13
vpshufb %xmm0,%xmm11,%xmm11
vpxor %xmm4,%xmm10,%xmm10
vpaddd %xmm5,%xmm12,%xmm14
vpshufb %xmm0,%xmm12,%xmm12
vpxor %xmm4,%xmm11,%xmm11
vpaddd %xmm5,%xmm13,%xmm1
vpshufb %xmm0,%xmm13,%xmm13
vpxor %xmm4,%xmm12,%xmm12
vpshufb %xmm0,%xmm14,%xmm14
vpxor %xmm4,%xmm13,%xmm13
vpshufb %xmm0,%xmm1,%xmm1
vpxor %xmm4,%xmm14,%xmm14
jmp .Loop_ctr32
.size _aesni_ctr32_6x,.-_aesni_ctr32_6x
.globl aesni_gcm_encrypt
.type aesni_gcm_encrypt,@function
.align 32
aesni_gcm_encrypt:
.cfi_startproc
xorq %r10,%r10
cmpq $288,%rdx
jb .Lgcm_enc_abort
leaq (%rsp),%rax
.cfi_def_cfa_register %rax
pushq %rbx
.cfi_offset %rbx,-16
pushq %rbp
.cfi_offset %rbp,-24
pushq %r12
.cfi_offset %r12,-32
pushq %r13
.cfi_offset %r13,-40
pushq %r14
.cfi_offset %r14,-48
pushq %r15
.cfi_offset %r15,-56
vzeroupper
vmovdqu (%r8),%xmm1
addq $-128,%rsp
movl 12(%r8),%ebx
leaq .Lbswap_mask(%rip),%r11
leaq -128(%rcx),%r14
movq $0xf80,%r15
leaq 128(%rcx),%rcx
vmovdqu (%r11),%xmm0
andq $-128,%rsp
movl 240-128(%rcx),%ebp
andq %r15,%r14
andq %rsp,%r15
subq %r14,%r15
jc .Lenc_no_key_aliasing
cmpq $768,%r15
jnc .Lenc_no_key_aliasing
subq %r15,%rsp
.Lenc_no_key_aliasing:
leaq (%rsi),%r14
leaq -192(%rsi,%rdx,1),%r15
shrq $4,%rdx
call _aesni_ctr32_6x
vpshufb %xmm0,%xmm9,%xmm8
vpshufb %xmm0,%xmm10,%xmm2
vmovdqu %xmm8,112(%rsp)
vpshufb %xmm0,%xmm11,%xmm4
vmovdqu %xmm2,96(%rsp)
vpshufb %xmm0,%xmm12,%xmm5
vmovdqu %xmm4,80(%rsp)
vpshufb %xmm0,%xmm13,%xmm6
vmovdqu %xmm5,64(%rsp)
vpshufb %xmm0,%xmm14,%xmm7
vmovdqu %xmm6,48(%rsp)
call _aesni_ctr32_6x
vmovdqu (%r9),%xmm8
leaq 32+32(%r9),%r9
subq $12,%rdx
movq $192,%r10
vpshufb %xmm0,%xmm8,%xmm8
call _aesni_ctr32_ghash_6x
vmovdqu 32(%rsp),%xmm7
vmovdqu (%r11),%xmm0
vmovdqu 0-32(%r9),%xmm3
vpunpckhqdq %xmm7,%xmm7,%xmm1
vmovdqu 32-32(%r9),%xmm15
vmovups %xmm9,-96(%rsi)
vpshufb %xmm0,%xmm9,%xmm9
vpxor %xmm7,%xmm1,%xmm1
vmovups %xmm10,-80(%rsi)
vpshufb %xmm0,%xmm10,%xmm10
vmovups %xmm11,-64(%rsi)
vpshufb %xmm0,%xmm11,%xmm11
vmovups %xmm12,-48(%rsi)
vpshufb %xmm0,%xmm12,%xmm12
vmovups %xmm13,-32(%rsi)
vpshufb %xmm0,%xmm13,%xmm13
vmovups %xmm14,-16(%rsi)
vpshufb %xmm0,%xmm14,%xmm14
vmovdqu %xmm9,16(%rsp)
vmovdqu 48(%rsp),%xmm6
vmovdqu 16-32(%r9),%xmm0
vpunpckhqdq %xmm6,%xmm6,%xmm2
vpclmulqdq $0x00,%xmm3,%xmm7,%xmm5
vpxor %xmm6,%xmm2,%xmm2
vpclmulqdq $0x11,%xmm3,%xmm7,%xmm7
vpclmulqdq $0x00,%xmm15,%xmm1,%xmm1
vmovdqu 64(%rsp),%xmm9
vpclmulqdq $0x00,%xmm0,%xmm6,%xmm4
vmovdqu 48-32(%r9),%xmm3
vpxor %xmm5,%xmm4,%xmm4
vpunpckhqdq %xmm9,%xmm9,%xmm5
vpclmulqdq $0x11,%xmm0,%xmm6,%xmm6
vpxor %xmm9,%xmm5,%xmm5
vpxor %xmm7,%xmm6,%xmm6
vpclmulqdq $0x10,%xmm15,%xmm2,%xmm2
vmovdqu 80-32(%r9),%xmm15
vpxor %xmm1,%xmm2,%xmm2
vmovdqu 80(%rsp),%xmm1
vpclmulqdq $0x00,%xmm3,%xmm9,%xmm7
vmovdqu 64-32(%r9),%xmm0
vpxor %xmm4,%xmm7,%xmm7
vpunpckhqdq %xmm1,%xmm1,%xmm4
vpclmulqdq $0x11,%xmm3,%xmm9,%xmm9
vpxor %xmm1,%xmm4,%xmm4
vpxor %xmm6,%xmm9,%xmm9
vpclmulqdq $0x00,%xmm15,%xmm5,%xmm5
vpxor %xmm2,%xmm5,%xmm5
vmovdqu 96(%rsp),%xmm2
vpclmulqdq $0x00,%xmm0,%xmm1,%xmm6
vmovdqu 96-32(%r9),%xmm3
vpxor %xmm7,%xmm6,%xmm6
vpunpckhqdq %xmm2,%xmm2,%xmm7
vpclmulqdq $0x11,%xmm0,%xmm1,%xmm1
vpxor %xmm2,%xmm7,%xmm7
vpxor %xmm9,%xmm1,%xmm1
vpclmulqdq $0x10,%xmm15,%xmm4,%xmm4
vmovdqu 128-32(%r9),%xmm15
vpxor %xmm5,%xmm4,%xmm4
vpxor 112(%rsp),%xmm8,%xmm8
vpclmulqdq $0x00,%xmm3,%xmm2,%xmm5
vmovdqu 112-32(%r9),%xmm0
vpunpckhqdq %xmm8,%xmm8,%xmm9
vpxor %xmm6,%xmm5,%xmm5
vpclmulqdq $0x11,%xmm3,%xmm2,%xmm2
vpxor %xmm8,%xmm9,%xmm9
vpxor %xmm1,%xmm2,%xmm2
vpclmulqdq $0x00,%xmm15,%xmm7,%xmm7
vpxor %xmm4,%xmm7,%xmm4
vpclmulqdq $0x00,%xmm0,%xmm8,%xmm6
vmovdqu 0-32(%r9),%xmm3
vpunpckhqdq %xmm14,%xmm14,%xmm1
vpclmulqdq $0x11,%xmm0,%xmm8,%xmm8
vpxor %xmm14,%xmm1,%xmm1
vpxor %xmm5,%xmm6,%xmm5
vpclmulqdq $0x10,%xmm15,%xmm9,%xmm9
vmovdqu 32-32(%r9),%xmm15
vpxor %xmm2,%xmm8,%xmm7
vpxor %xmm4,%xmm9,%xmm6
vmovdqu 16-32(%r9),%xmm0
vpxor %xmm5,%xmm7,%xmm9
vpclmulqdq $0x00,%xmm3,%xmm14,%xmm4
vpxor %xmm9,%xmm6,%xmm6
vpunpckhqdq %xmm13,%xmm13,%xmm2
vpclmulqdq $0x11,%xmm3,%xmm14,%xmm14
vpxor %xmm13,%xmm2,%xmm2
vpslldq $8,%xmm6,%xmm9
vpclmulqdq $0x00,%xmm15,%xmm1,%xmm1
vpxor %xmm9,%xmm5,%xmm8
vpsrldq $8,%xmm6,%xmm6
vpxor %xmm6,%xmm7,%xmm7
vpclmulqdq $0x00,%xmm0,%xmm13,%xmm5
vmovdqu 48-32(%r9),%xmm3
vpxor %xmm4,%xmm5,%xmm5
vpunpckhqdq %xmm12,%xmm12,%xmm9
vpclmulqdq $0x11,%xmm0,%xmm13,%xmm13
vpxor %xmm12,%xmm9,%xmm9
vpxor %xmm14,%xmm13,%xmm13
vpalignr $8,%xmm8,%xmm8,%xmm14
vpclmulqdq $0x10,%xmm15,%xmm2,%xmm2
vmovdqu 80-32(%r9),%xmm15
vpxor %xmm1,%xmm2,%xmm2
vpclmulqdq $0x00,%xmm3,%xmm12,%xmm4
vmovdqu 64-32(%r9),%xmm0
vpxor %xmm5,%xmm4,%xmm4
vpunpckhqdq %xmm11,%xmm11,%xmm1
vpclmulqdq $0x11,%xmm3,%xmm12,%xmm12
vpxor %xmm11,%xmm1,%xmm1
vpxor %xmm13,%xmm12,%xmm12
vxorps 16(%rsp),%xmm7,%xmm7
vpclmulqdq $0x00,%xmm15,%xmm9,%xmm9
vpxor %xmm2,%xmm9,%xmm9
vpclmulqdq $0x10,16(%r11),%xmm8,%xmm8
vxorps %xmm14,%xmm8,%xmm8
vpclmulqdq $0x00,%xmm0,%xmm11,%xmm5
vmovdqu 96-32(%r9),%xmm3
vpxor %xmm4,%xmm5,%xmm5
vpunpckhqdq %xmm10,%xmm10,%xmm2
vpclmulqdq $0x11,%xmm0,%xmm11,%xmm11
vpxor %xmm10,%xmm2,%xmm2
vpalignr $8,%xmm8,%xmm8,%xmm14
vpxor %xmm12,%xmm11,%xmm11
vpclmulqdq $0x10,%xmm15,%xmm1,%xmm1
vmovdqu 128-32(%r9),%xmm15
vpxor %xmm9,%xmm1,%xmm1
vxorps %xmm7,%xmm14,%xmm14
vpclmulqdq $0x10,16(%r11),%xmm8,%xmm8
vxorps %xmm14,%xmm8,%xmm8
vpclmulqdq $0x00,%xmm3,%xmm10,%xmm4
vmovdqu 112-32(%r9),%xmm0
vpxor %xmm5,%xmm4,%xmm4
vpunpckhqdq %xmm8,%xmm8,%xmm9
vpclmulqdq $0x11,%xmm3,%xmm10,%xmm10
vpxor %xmm8,%xmm9,%xmm9
vpxor %xmm11,%xmm10,%xmm10
vpclmulqdq $0x00,%xmm15,%xmm2,%xmm2
vpxor %xmm1,%xmm2,%xmm2
vpclmulqdq $0x00,%xmm0,%xmm8,%xmm5
vpclmulqdq $0x11,%xmm0,%xmm8,%xmm7
vpxor %xmm4,%xmm5,%xmm5
vpclmulqdq $0x10,%xmm15,%xmm9,%xmm6
vpxor %xmm10,%xmm7,%xmm7
vpxor %xmm2,%xmm6,%xmm6
vpxor %xmm5,%xmm7,%xmm4
vpxor %xmm4,%xmm6,%xmm6
vpslldq $8,%xmm6,%xmm1
vmovdqu 16(%r11),%xmm3
vpsrldq $8,%xmm6,%xmm6
vpxor %xmm1,%xmm5,%xmm8
vpxor %xmm6,%xmm7,%xmm7
vpalignr $8,%xmm8,%xmm8,%xmm2
vpclmulqdq $0x10,%xmm3,%xmm8,%xmm8
vpxor %xmm2,%xmm8,%xmm8
vpalignr $8,%xmm8,%xmm8,%xmm2
vpclmulqdq $0x10,%xmm3,%xmm8,%xmm8
vpxor %xmm7,%xmm2,%xmm2
vpxor %xmm2,%xmm8,%xmm8
vpshufb (%r11),%xmm8,%xmm8
vmovdqu %xmm8,-64(%r9)
vzeroupper
movq -48(%rax),%r15
.cfi_restore %r15
movq -40(%rax),%r14
.cfi_restore %r14
movq -32(%rax),%r13
.cfi_restore %r13
movq -24(%rax),%r12
.cfi_restore %r12
movq -16(%rax),%rbp
.cfi_restore %rbp
movq -8(%rax),%rbx
.cfi_restore %rbx
leaq (%rax),%rsp
.cfi_def_cfa_register %rsp
.Lgcm_enc_abort:
movq %r10,%rax
.byte 0xf3,0xc3
.cfi_endproc
.size aesni_gcm_encrypt,.-aesni_gcm_encrypt
.align 64
.Lbswap_mask:
.byte 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0
.Lpoly:
.byte 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0xc2
.Lone_msb:
.byte 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1
.Ltwo_lsb:
.byte 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
.Lone_lsb:
.byte 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
.byte 65,69,83,45,78,73,32,71,67,77,32,109,111,100,117,108,101,32,102,111,114,32,120,56,54,95,54,52,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
.align 64
|
{
"pile_set_name": "Github"
}
|
<!--
Copyright 2012 The Android Open Source Project
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.
-->
<resources>
<!--
These action bar item IDs (menu item IDs) are defined here for
programmatic use. Normally, IDs are created using the "@+id/foo"
syntax, but since these IDs aren't created in menu XML, rather
used for programmatically-instantiated action bar items, they
are defined here.
-->
<item type="id" name="action_next" />
<item type="id" name="action_flip" />
</resources>
|
{
"pile_set_name": "Github"
}
|
# Generated by Django 2.2.10 on 2020-05-07 09:37
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='TaskInfo',
fields=[
('task_id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('user_id', models.IntegerField(verbose_name='任务创建用户 ID')),
('task_name', models.CharField(max_length=255, verbose_name='任务名称')),
('task_status', models.IntegerField(default=1)),
('task_start_date', models.DateTimeField(auto_now_add=True, verbose_name='任务创建时间')),
('task_end_date', models.DateTimeField(null=True, verbose_name='任务结束时间')),
('operation_type', models.CharField(max_length=255, verbose_name='执行操作名称')),
('operation_args', models.TextField(default='', verbose_name='执行操作参数')),
('task_msg', models.TextField(default='', verbose_name='任务执行消息')),
('is_show', models.BooleanField(default=False, verbose_name='任务是否被查看')),
('create_date', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
('update_date', models.DateTimeField(auto_now=True, verbose_name='更新时间')),
],
options={
'db_table': 'task_info',
},
),
]
|
{
"pile_set_name": "Github"
}
|
id: 0 protocol: \[\] ip_source: \[\] port_source: \[\] ip_dest: \[\] port_dest: \[\] action: deny
|
{
"pile_set_name": "Github"
}
|
apiVersion: v1
appVersion: "1.0"
name: flowing-retail-zeebe-simple-monitor-db
version: 0.1.0
|
{
"pile_set_name": "Github"
}
|
{
"parent": "builtin/generated",
"textures": {
"layer0": "mcpatcher/cit/potions/blank",
"layer1": "mcpatcher/cit/potions/splash/farming_s"
},
"display": {
"thirdperson": {
"rotation": [ -90, 0, 0 ],
"translation": [ 0, 1, -3 ],
"scale": [ 0.55, 0.55, 0.55 ]
},
"firstperson": {
"rotation": [ 0, -135, 25 ],
"translation": [ 0, 4, 2 ],
"scale": [ 1.7, 1.7, 1.7 ]
}
}
}
|
{
"pile_set_name": "Github"
}
|
'use strict'
// When writing files on Windows, translate the characters to their
// 0xf000 higher-encoded versions.
const raw = [
'|',
'<',
'>',
'?',
':'
]
const win = raw.map(char =>
String.fromCharCode(0xf000 + char.charCodeAt(0)))
const toWin = new Map(raw.map((char, i) => [char, win[i]]))
const toRaw = new Map(win.map((char, i) => [char, raw[i]]))
module.exports = {
encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s),
decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s)
}
|
{
"pile_set_name": "Github"
}
|
import common.Node;
import common.TreeNode;
// https://leetcode-cn.com/problems/longest-arithmetic-subsequence-of-given-difference/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class L1218_Longest_Arithmetic_Subsequence_of_Given_Difference {
public TreeNode lcaDeepestLeaves(TreeNode root) {
if (root == null) {
return null;
}
int left = depth(root.left);
int right = depth(root.right);
if (left == right) {
return root;
}
return left > right ? lcaDeepestLeaves(root.left) : lcaDeepestLeaves(root.right);
}
private int depth(TreeNode root) {
if (root == null) {
return 0;
}
int left = depth(root.left);
int right = depth(root.right);
return Math.max(left, right) + 1;
}
}
|
{
"pile_set_name": "Github"
}
|
#include "inmemorysessionstore.h"
#include "state/LocalStorageProtocol.pb.h"
#include <iostream>
#include <vector>
InMemorySessionStore::InMemorySessionStore()
{
}
SessionRecord *InMemorySessionStore::loadSession(uint64_t recipientId, int deviceId)
{
SessionsKeyPair key(recipientId, deviceId);
if (sessions.find(key) != sessions.end()) {
return new SessionRecord(sessions.at(key));
}
else {
return new SessionRecord();
}
}
std::vector<int> InMemorySessionStore::getSubDeviceSessions(uint64_t recipientId)
{
std::vector<int> deviceIds;
for (auto it: sessions) {
if (it.first.first == recipientId) {
deviceIds.push_back(it.first.second);
}
}
return deviceIds;
}
void InMemorySessionStore::storeSession(uint64_t recipientId, int deviceId, SessionRecord *record)
{
SessionsKeyPair key(recipientId, deviceId);
ByteArray serialized = record->serialize();
sessions.emplace(key, serialized);
}
bool InMemorySessionStore::containsSession(uint64_t recipientId, int deviceId)
{
SessionsKeyPair key(recipientId, deviceId);
return sessions.find(key) != sessions.end();
}
void InMemorySessionStore::deleteSession(uint64_t recipientId, int deviceId)
{
SessionsKeyPair key(recipientId, deviceId);
sessions.erase(key);
}
void InMemorySessionStore::deleteAllSessions(uint64_t recipientId)
{
bool modified;
do {
modified = false;
for (auto & key: sessions) {
if (key.first.first == recipientId) {
sessions.erase(key.first);
modified = true;
break;
}
}
} while (modified);
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.0//EN"
"http://www.puppycrawl.com/dtds/suppressions_1_0.dtd">
<suppressions>
<suppress checks="MemberName"
files="AccessTokenResponse.java"
lines="1-9999"/>
<suppress checks="MethodName"
files="AccessTokenResponse.java"
lines="1-9999"/>
<suppress checks="MemberName"
files="IdToken.java"
lines="1-9999"/>
<suppress checks="MethodName"
files="IdToken.java"
lines="1-9999"/>
</suppressions>
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Schedule Typescript Component</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<meta name="description" content="Typescript UI Controls" />
<meta name="author" content="Syncfusion" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="../css/material.css" />
<script data-main="views" src="../../node_modules/requirejs/require.js"></script>
<script src="require.config.js"></script>
</head>
<body>
<div class="container-fluid" style="margin-top:15px;">
<div class="row">
<div class="col-md-12">
<div id="schedule">
</div>
</div>
</div>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/rvagg/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_IMPLEMENTATION_12_INL_H_
#define NAN_IMPLEMENTATION_12_INL_H_
//==============================================================================
// node v0.11 implementation
//==============================================================================
#if defined(_MSC_VER)
# pragma warning( disable : 4530 )
# include <string>
# pragma warning( default : 4530 )
#else
# include <string>
#endif
namespace NanIntern {
//=== Array ====================================================================
Factory<v8::Array>::return_t
Factory<v8::Array>::New() {
return v8::Array::New(v8::Isolate::GetCurrent());
}
Factory<v8::Array>::return_t
Factory<v8::Array>::New(int length) {
return v8::Array::New(v8::Isolate::GetCurrent(), length);
}
//=== Boolean ==================================================================
Factory<v8::Boolean>::return_t
Factory<v8::Boolean>::New(bool value) {
return v8::Boolean::New(v8::Isolate::GetCurrent(), value);
}
//=== Boolean Object ===========================================================
Factory<v8::BooleanObject>::return_t
Factory<v8::BooleanObject>::New(bool value) {
return v8::BooleanObject::New(value).As<v8::BooleanObject>();
}
//=== Context ==================================================================
Factory<v8::Context>::return_t
Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
, v8::Handle<v8::ObjectTemplate> tmpl
, v8::Handle<v8::Value> obj) {
return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj);
}
//=== Date =====================================================================
Factory<v8::Date>::return_t
Factory<v8::Date>::New(double value) {
return v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>();
}
//=== External =================================================================
Factory<v8::External>::return_t
Factory<v8::External>::New(void * value) {
return v8::External::New(v8::Isolate::GetCurrent(), value);
}
//=== Function =================================================================
Factory<v8::Function>::return_t
Factory<v8::Function>::New( NanFunctionCallback callback
, v8::Handle<v8::Value> data) {
return v8::Function::New( v8::Isolate::GetCurrent()
, callback
, data);
}
//=== Function Template ========================================================
Factory<v8::FunctionTemplate>::return_t
Factory<v8::FunctionTemplate>::New( NanFunctionCallback callback
, v8::Handle<v8::Value> data
, v8::Handle<v8::Signature> signature) {
return v8::FunctionTemplate::New( v8::Isolate::GetCurrent()
, callback
, data
, signature);
}
//=== Number ===================================================================
Factory<v8::Number>::return_t
Factory<v8::Number>::New(double value) {
return v8::Number::New(v8::Isolate::GetCurrent(), value);
}
//=== Number Object ============================================================
Factory<v8::NumberObject>::return_t
Factory<v8::NumberObject>::New(double value) {
return v8::NumberObject::New( v8::Isolate::GetCurrent()
, value).As<v8::NumberObject>();
}
//=== Integer, Int32 and Uint32 ================================================
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(int32_t value) {
return To<T>(T::New(v8::Isolate::GetCurrent(), value));
}
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(uint32_t value) {
return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(int32_t value) {
return To<v8::Uint32>(
v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(uint32_t value) {
return To<v8::Uint32>(
v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
//=== Object ===================================================================
Factory<v8::Object>::return_t
Factory<v8::Object>::New() {
return v8::Object::New(v8::Isolate::GetCurrent());
}
//=== Object Template ==========================================================
Factory<v8::ObjectTemplate>::return_t
Factory<v8::ObjectTemplate>::New() {
return v8::ObjectTemplate::New(v8::Isolate::GetCurrent());
}
//=== RegExp ===================================================================
Factory<v8::RegExp>::return_t
Factory<v8::RegExp>::New(
v8::Handle<v8::String> pattern
, v8::RegExp::Flags flags) {
return v8::RegExp::New(pattern, flags);
}
//=== Script ===================================================================
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src);
}
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src);
}
//=== Signature ================================================================
Factory<v8::Signature>::return_t
Factory<v8::Signature>::New( Factory<v8::Signature>::FTH receiver
, int argc
, Factory<v8::Signature>::FTH argv[]) {
return v8::Signature::New(v8::Isolate::GetCurrent(), receiver, argc, argv);
}
//=== String ===================================================================
Factory<v8::String>::return_t
Factory<v8::String>::New() {
return v8::String::Empty(v8::Isolate::GetCurrent());
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const char * value, int length) {
return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value,
v8::String::kNormalString, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(std::string const& value) {
assert(value.size() <= INT_MAX && "string too long");
return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),
value.data(), v8::String::kNormalString, static_cast<int>(value.size()));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint8_t * value, int length) {
return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
v8::String::kNormalString, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint16_t * value, int length) {
return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value,
v8::String::kNormalString, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
return v8::String::NewExternal(v8::Isolate::GetCurrent(), value);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(NanExternalOneByteStringResource * value) {
return v8::String::NewExternal(v8::Isolate::GetCurrent(), value);
}
//=== String Object ============================================================
Factory<v8::StringObject>::return_t
Factory<v8::StringObject>::New(v8::Handle<v8::String> value) {
return v8::StringObject::New(value).As<v8::StringObject>();
}
//=== Unbound Script ===========================================================
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src);
}
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src);
}
} // end of namespace NanIntern
//=== Presistents and Handles ==================================================
template <typename T>
inline v8::Local<T> NanNew(v8::Handle<T> h) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), h);
}
template <typename T>
inline v8::Local<T> NanNew(v8::Persistent<T> const& p) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
}
#endif // NAN_IMPLEMENTATION_12_INL_H_
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.datafactory.v2018_06_01;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* Sftp write settings.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = SftpWriteSettings.class)
@JsonTypeName("SftpWriteSettings")
public class SftpWriteSettings extends StoreWriteSettings {
/**
* Specifies the timeout for writing each chunk to SFTP server. Default
* value: 01:00:00 (one hour). Type: string (or Expression with resultType
* string).
*/
@JsonProperty(value = "operationTimeout")
private Object operationTimeout;
/**
* Upload to temporary file(s) and rename. Disable this option if your SFTP
* server doesn't support rename operation. Type: boolean (or Expression
* with resultType boolean).
*/
@JsonProperty(value = "useTempFileRename")
private Object useTempFileRename;
/**
* Get specifies the timeout for writing each chunk to SFTP server. Default value: 01:00:00 (one hour). Type: string (or Expression with resultType string).
*
* @return the operationTimeout value
*/
public Object operationTimeout() {
return this.operationTimeout;
}
/**
* Set specifies the timeout for writing each chunk to SFTP server. Default value: 01:00:00 (one hour). Type: string (or Expression with resultType string).
*
* @param operationTimeout the operationTimeout value to set
* @return the SftpWriteSettings object itself.
*/
public SftpWriteSettings withOperationTimeout(Object operationTimeout) {
this.operationTimeout = operationTimeout;
return this;
}
/**
* Get upload to temporary file(s) and rename. Disable this option if your SFTP server doesn't support rename operation. Type: boolean (or Expression with resultType boolean).
*
* @return the useTempFileRename value
*/
public Object useTempFileRename() {
return this.useTempFileRename;
}
/**
* Set upload to temporary file(s) and rename. Disable this option if your SFTP server doesn't support rename operation. Type: boolean (or Expression with resultType boolean).
*
* @param useTempFileRename the useTempFileRename value to set
* @return the SftpWriteSettings object itself.
*/
public SftpWriteSettings withUseTempFileRename(Object useTempFileRename) {
this.useTempFileRename = useTempFileRename;
return this;
}
}
|
{
"pile_set_name": "Github"
}
|
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* linux/sound/soc/pxa/pxa2xx-i2s.h
*/
#ifndef _PXA2XX_I2S_H
#define _PXA2XX_I2S_H
/* I2S clock */
#define PXA2XX_I2S_SYSCLK 0
#endif
|
{
"pile_set_name": "Github"
}
|
commandlinefu_id: 5243
translator:
weibo: ''
hide: true
command: |-
:!pylint -e %
summary: |-
check python syntax in vim
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0"?>
<!DOCTYPE OpenGLAPI SYSTEM "gl_API.dtd">
<!-- Note: no GLX protocol info yet. -->
<OpenGLAPI>
<category name="GL_ARB_texture_storage_multisample" number="141">
<function name="TexStorage2DMultisample" es2="3.1">
<param name="target" type="GLenum"/>
<param name="samples" type="GLsizei"/>
<param name="internalformat" type="GLenum"/>
<param name="width" type="GLsizei"/>
<param name="height" type="GLsizei"/>
<param name="fixedsamplelocations" type="GLboolean"/>
</function>
<function name="TexStorage3DMultisample" es2="3.2">
<param name="target" type="GLenum"/>
<param name="samples" type="GLsizei"/>
<param name="internalformat" type="GLenum"/>
<param name="width" type="GLsizei"/>
<param name="height" type="GLsizei"/>
<param name="depth" type="GLsizei"/>
<param name="fixedsamplelocations" type="GLboolean"/>
</function>
<function name="TextureStorage2DMultisampleEXT">
<param name="texture" type="GLuint"/>
<param name="target" type="GLenum"/>
<param name="samples" type="GLsizei"/>
<param name="internalformat" type="GLenum"/>
<param name="width" type="GLsizei"/>
<param name="height" type="GLsizei"/>
<param name="fixedsamplelocations" type="GLboolean"/>
</function>
<function name="TextureStorage3DMultisampleEXT">
<param name="texture" type="GLuint"/>
<param name="target" type="GLenum"/>
<param name="samples" type="GLsizei"/>
<param name="internalformat" type="GLenum"/>
<param name="width" type="GLsizei"/>
<param name="height" type="GLsizei"/>
<param name="depth" type="GLsizei"/>
<param name="fixedsamplelocations" type="GLboolean"/>
</function>
</category>
</OpenGLAPI>
|
{
"pile_set_name": "Github"
}
|
SUMMARY="Python signature tools"
DESCRIPTION="Python function signatures from PEP362 for Python 2.6, 2.7 and 3.2+."
HOMEPAGE="http://funcsigs.readthedocs.org"
SOURCE_URI="https://pypi.python.org/packages/94/4a/db842e7a0545de1cdb0439bb80e6e42dfe82aaeaadd4072f2263a4fbed23/funcsigs-1.0.2.tar.gz"
REVISION="2"
LICENSE="Apache v2"
COPYRIGHT="2013 Aaron Iles"
CHECKSUM_SHA256="a7bb0f2cf3a3fd1ab2732cb49eba4252c2af4240442415b4abce3b87022a8f50"
ARCHITECTURES="any"
PROVIDES="
funcsigs=$portVersion
"
REQUIRES="
haiku
"
BUILD_REQUIRES="
haiku_devel
"
PYTHON_PACKAGES=(python python36 python3)
PYTHON_VERSIONS=(2.7 3.6 3.7)
for i in "${!PYTHON_PACKAGES[@]}"; do
pythonPackage=${PYTHON_PACKAGES[i]}
pythonVersion=${PYTHON_VERSIONS[$i]}
eval "PROVIDES_${pythonPackage}=\"\
${portName}_$pythonPackage = $portVersion\
\"; \
REQUIRES_$pythonPackage=\"\
haiku\n\
cmd:python$pythonVersion\
\""
BUILD_REQUIRES="$BUILD_REQUIRES
setuptools_$pythonPackage"
BUILD_PREREQUIRES="$BUILD_PREREQUIRES
cmd:python$pythonVersion
"
done
INSTALL()
{
for i in "${!PYTHON_PACKAGES[@]}"; do
pythonPackage=${PYTHON_PACKAGES[i]}
pythonVersion=${PYTHON_VERSIONS[$i]}
python=python$pythonVersion
installLocation=$prefix/lib/$python/vendor-packages/
export PYTHONPATH=$installLocation:$PYTHONPATH
mkdir -p $installLocation
rm -rf build
$python setup.py build install \
--root=/ --prefix=$prefix
packageEntries $pythonPackage \
$prefix/lib/python*
done
}
|
{
"pile_set_name": "Github"
}
|
/* poppler-qt.h: qt interface to poppler
* Copyright (C) 2005, Net Integration Technologies, Inc.
* Copyright (C) 2005, 2007, Brad Hards <bradh@frogmouth.net>
* Copyright (C) 2005-2010, Albert Astals Cid <aacid@kde.org>
* Copyright (C) 2005, Stefan Kebekus <stefan.kebekus@math.uni-koeln.de>
* Copyright (C) 2006-2010, Pino Toscano <pino@kde.org>
* Copyright (C) 2009 Shawn Rutledge <shawn.t.rutledge@gmail.com>
* Copyright (C) 2010 Suzuki Toshiya <mpsuzuki@hiroshima-u.ac.jp>
* Copyright (C) 2010 Matthias Fauconneau <matthias.fauconneau@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __POPPLER_QT_H__
#define __POPPLER_QT_H__
#include "poppler-annotation.h"
#include "poppler-link.h"
#include "poppler-optcontent.h"
#include "poppler-page-transition.h"
#include <QtCore/QByteArray>
#include <QtCore/QDateTime>
#include <QtCore/QSet>
#include <QtXml/QDomDocument>
#include "poppler-export.h"
class EmbFile;
class Sound;
class AnnotMovie;
/**
The %Poppler Qt4 binding.
*/
namespace Poppler {
class Document;
class DocumentData;
class PageData;
class FormField;
class TextBoxData;
class PDFConverter;
class PSConverter;
/**
Debug/error function.
This function type is used for debugging & error output;
the first parameter is the actual message, the second is the unaltered
closure argument which was passed to the setDebugErrorFunction call.
\since 0.16
*/
typedef void (*PopplerDebugFunc)(const QString & /*message*/, const QVariant & /*closure*/);
/**
Set a new debug/error output function.
If not set, by default error and debug messages will be sent to the
Qt \p qDebug() function.
\param debugFunction the new debug function
\param closure user data which will be passes as-is to the debug function
\since 0.16
*/
POPPLER_QT4_EXPORT void setDebugErrorFunction(PopplerDebugFunc debugFunction, const QVariant &closure);
/**
Describes the physical location of text on a document page
This very simple class describes the physical location of text
on the page. It consists of
- a QString that contains the text
- a QRectF that gives a box that describes where on the page
the text is found.
*/
class POPPLER_QT4_EXPORT TextBox {
friend class Page;
public:
/**
The default constructor sets the \p text and the rectangle that
contains the text. Coordinated for the \p bBox are in points =
1/72 of an inch.
*/
TextBox(const QString& text, const QRectF &bBox);
/**
Destructor.
*/
~TextBox();
/**
Returns the text of this text box
*/
QString text() const;
/**
Returns the position of the text, in point, i.e., 1/72 of
an inch
\since 0.8
*/
QRectF boundingBox() const;
/**
Returns the pointer to the next text box, if there is one.
Otherwise, it returns a null pointer.
*/
TextBox *nextWord() const;
/**
Returns the bounding box of the \p i -th characted of the word.
*/
QRectF charBoundingBox(int i) const;
/**
Returns whether there is a space character after this text box
*/
bool hasSpaceAfter() const;
private:
Q_DISABLE_COPY(TextBox)
TextBoxData *m_data;
};
class FontInfoData;
/**
Container class for information about a font within a PDF
document
*/
class POPPLER_QT4_EXPORT FontInfo {
friend class Document;
public:
/**
The type of font.
*/
enum Type {
unknown,
Type1,
Type1C,
Type1COT,
Type3,
TrueType,
TrueTypeOT,
CIDType0,
CIDType0C,
CIDType0COT,
CIDTrueType,
CIDTrueTypeOT
};
/// \cond PRIVATE
/**
Create a new font information container.
*/
FontInfo();
/**
Create a new font information container.
*/
FontInfo( const FontInfoData &fid );
/// \endcond
/**
Copy constructor.
*/
FontInfo( const FontInfo &fi );
/**
Destructor.
*/
~FontInfo();
/**
The name of the font. Can be QString::null if the font has no name
*/
QString name() const;
/**
The path of the font file used to represent this font on this system,
or a null string is the font is embedded
*/
QString file() const;
/**
Whether the font is embedded in the file, or not
\return true if the font is embedded
*/
bool isEmbedded() const;
/**
Whether the font provided is only a subset of the full
font or not. This only has meaning if the font is embedded.
\return true if the font is only a subset
*/
bool isSubset() const;
/**
The type of font encoding
\return a enumerated value corresponding to the font encoding used
\sa typeName for a string equivalent
*/
Type type() const;
/**
The name of the font encoding used
\note if you are looking for the name of the font (as opposed to the
encoding format used), you probably want name().
\sa type for a enumeration version
*/
QString typeName() const;
/**
Standard assignment operator
*/
FontInfo& operator=( const FontInfo &fi );
private:
FontInfoData *m_data;
};
class FontIteratorData;
/**
Iterator for reading the fonts in a document.
FontIterator provides a Java-style iterator for reading the fonts in a
document.
You can use it in the following way:
\code
Poppler::FontIterator* it = doc->newFontIterator();
while (it->hasNext()) {
QList<Poppler::FontInfo> fonts = it->next();
// do something with the fonts
}
// after doing the job, the iterator must be freed
delete it;
\endcode
\since 0.12
*/
class POPPLER_QT4_EXPORT FontIterator {
friend class Document;
friend class DocumentData;
public:
/**
Destructor.
*/
~FontIterator();
/**
Returns the fonts of the current page and then advances the iterator
to the next page.
*/
QList<FontInfo> next();
/**
Checks whether there is at least one more page to iterate, ie returns
false when the iterator is beyond the last page.
*/
bool hasNext() const;
/**
Returns the current page where the iterator is.
*/
int currentPage() const;
private:
Q_DISABLE_COPY( FontIterator )
FontIterator( int, DocumentData *dd );
FontIteratorData *d;
};
class EmbeddedFileData;
/**
Container class for an embedded file with a PDF document
*/
class POPPLER_QT4_EXPORT EmbeddedFile {
public:
/// \cond PRIVATE
EmbeddedFile(EmbFile *embfile);
/// \endcond
/**
Destructor.
*/
~EmbeddedFile();
/**
The name associated with the file
*/
QString name() const;
/**
The description associated with the file, if any.
This will return an empty QString if there is no description element
*/
QString description() const;
/**
The size of the file.
This will return < 0 if there is no size element
*/
int size() const;
/**
The modification date for the embedded file, if known.
*/
QDateTime modDate() const;
/**
The creation date for the embedded file, if known.
*/
QDateTime createDate() const;
/**
The MD5 checksum of the file.
This will return an empty QByteArray if there is no checksum element.
*/
QByteArray checksum() const;
/**
The MIME type of the file, if known.
\since 0.8
*/
QString mimeType() const;
/**
The data as a byte array
*/
QByteArray data();
/**
Is the embedded file valid?
\since 0.12
*/
bool isValid() const;
/**
A QDataStream for the actual data?
*/
//QDataStream dataStream() const;
private:
Q_DISABLE_COPY(EmbeddedFile)
EmbeddedFileData *m_embeddedFile;
};
/**
\brief A page in a document.
The Page class represents a single page within a PDF document.
You cannot construct a Page directly, but you have to use the Document
functions that return a new Page out of an index or a label.
*/
class POPPLER_QT4_EXPORT Page {
friend class Document;
public:
/**
Destructor.
*/
~Page();
/**
The type of rotation to apply for an operation
*/
enum Rotation { Rotate0 = 0, ///< Do not rotate
Rotate90 = 1, ///< Rotate 90 degrees clockwise
Rotate180 = 2, ///< Rotate 180 degrees
Rotate270 = 3 ///< Rotate 270 degrees clockwise (90 degrees counterclockwise)
};
/**
The kinds of page actions
*/
enum PageAction {
Opening, ///< The action when a page is "opened"
Closing ///< The action when a page is "closed"
};
/**
How the text is going to be returned
\since 0.16
*/
enum TextLayout {
PhysicalLayout, ///< The text is layouted to resemble the real page layout
RawOrderLayout ///< The text is returned without any type of processing
};
/**
Additional flags for the renderToPainter method
\since 0.16
*/
enum PainterFlag {
/**
Do not save/restore the caller-owned painter.
renderToPainter() by default preserves, using save() + restore(),
the state of the painter specified; if this is not needed, this
flag can avoid this job
*/
DontSaveAndRestore = 0x00000001
};
Q_DECLARE_FLAGS( PainterFlags, PainterFlag )
/**
Render the page to a QImage using the current
\link Document::renderBackend() Document renderer\endlink.
If \p x = \p y = \p w = \p h = -1, the method will automatically
compute the size of the image from the horizontal and vertical
resolutions specified in \p xres and \p yres. Otherwise, the
method renders only a part of the page, specified by the
parameters (\p x, \p y, \p w, \p h) in pixel coordinates. The returned
QImage then has size (\p w, \p h), independent of the page
size.
\param x specifies the left x-coordinate of the box, in
pixels.
\param y specifies the top y-coordinate of the box, in
pixels.
\param w specifies the width of the box, in pixels.
\param h specifies the height of the box, in pixels.
\param xres horizontal resolution of the graphics device,
in dots per inch
\param yres vertical resolution of the graphics device, in
dots per inch
\param rotate how to rotate the page
\warning The parameter (\p x, \p y, \p w, \p h) are not
well-tested. Unusual or meaningless parameters may lead to
rather unexpected results.
\returns a QImage of the page, or a null image on failure.
\since 0.6
*/
QImage renderToImage(double xres=72.0, double yres=72.0, int x=-1, int y=-1, int w=-1, int h=-1, Rotation rotate = Rotate0) const;
/**
Render the page to the specified QPainter using the current
\link Document::renderBackend() Document renderer\endlink.
If \p x = \p y = \p w = \p h = -1, the method will automatically
compute the size of the page area from the horizontal and vertical
resolutions specified in \p xres and \p yres. Otherwise, the
method renders only a part of the page, specified by the
parameters (\p x, \p y, \p w, \p h) in pixel coordinates.
\param painter the painter to paint on
\param x specifies the left x-coordinate of the box, in
pixels.
\param y specifies the top y-coordinate of the box, in
pixels.
\param w specifies the width of the box, in pixels.
\param h specifies the height of the box, in pixels.
\param xres horizontal resolution of the graphics device,
in dots per inch
\param yres vertical resolution of the graphics device, in
dots per inch
\param rotate how to rotate the page
\param flags additional painter flags
\warning The parameter (\p x, \p y, \p w, \p h) are not
well-tested. Unusual or meaningless parameters may lead to
rather unexpected results.
\returns whether the painting succeeded
\note This method is only supported for Arthur
\since 0.16
*/
bool renderToPainter(QPainter* painter, double xres=72.0, double yres=72.0, int x=-1, int y=-1, int w=-1, int h=-1,
Rotation rotate = Rotate0, PainterFlags flags = 0) const;
/**
Get the page thumbnail if it exists.
\return a QImage of the thumbnail, or a null image
if the PDF does not contain one for this page
\since 0.12
*/
QImage thumbnail() const;
/**
Returns the text that is inside a specified rectangle
\param rect the rectangle specifying the area of interest,
with coordinates given in points, i.e., 1/72th of an inch.
If rect is null, all text on the page is given
\since 0.16
**/
QString text(const QRectF &rect, TextLayout textLayout) const;
/**
Returns the text that is inside a specified rectangle.
The text is returned using the physical layout of the page
\param rect the rectangle specifying the area of interest,
with coordinates given in points, i.e., 1/72th of an inch.
If rect is null, all text on the page is given
**/
QString text(const QRectF &rect) const;
/**
The starting point for a search
*/
enum SearchDirection { FromTop, ///< Start sorting at the top of the document
NextResult, ///< Find the next result, moving "down the page"
PreviousResult ///< Find the previous result, moving "up the page"
};
/**
The type of search to perform
*/
enum SearchMode { CaseSensitive, ///< Case differences cause no match in searching
CaseInsensitive ///< Case differences are ignored in matching
};
/**
Returns true if the specified text was found.
\param text the text the search
\param rect in all directions is used to return where the text was found, for NextResult and PreviousResult
indicates where to continue searching for
\param direction in which direction do the search
\param caseSensitive be case sensitive?
\param rotate the rotation to apply for the search order
**/
Q_DECL_DEPRECATED bool search(const QString &text, QRectF &rect, SearchDirection direction, SearchMode caseSensitive, Rotation rotate = Rotate0) const;
/**
Returns true if the specified text was found.
\param text the text the search
\param rectXXX in all directions is used to return where the text was found, for NextResult and PreviousResult
indicates where to continue searching for
\param direction in which direction do the search
\param caseSensitive be case sensitive?
\param rotate the rotation to apply for the search order
\since 0.14
**/
bool search(const QString &text, double &rectLeft, double &rectTop, double &rectRight, double &rectBottom, SearchDirection direction, SearchMode caseSensitive, Rotation rotate = Rotate0) const;
/**
Returns a list of text of the page
This method returns a QList of TextBoxes that contain all
the text of the page, with roughly one text word of text
per TextBox item.
For text written in western languages (left-to-right and
up-to-down), the QList contains the text in the proper
order.
\note The caller owns the text boxes and they should
be deleted when no longer required.
\warning This method is not tested with Asian scripts
*/
QList<TextBox*> textList(Rotation rotate = Rotate0) const;
/**
\return The dimensions (cropbox) of the page, in points (i.e. 1/72th on an inch)
*/
QSizeF pageSizeF() const;
/**
\return The dimensions (cropbox) of the page, in points (i.e. 1/72th on an inch)
*/
QSize pageSize() const;
/**
Returns the transition of this page
\returns a pointer to a PageTransition structure that
defines how transition to this page shall be performed.
\note The PageTransition structure is owned by this page, and will
automatically be destroyed when this page class is
destroyed.
**/
PageTransition *transition() const;
/**
Gets the page action specified, or NULL if there is no action.
\since 0.6
**/
Link *action( PageAction act ) const;
/**
Types of orientations that are possible
*/
enum Orientation {
Landscape, ///< Landscape orientation (portrait, with 90 degrees clockwise rotation )
Portrait, ///< Normal portrait orientation
Seascape, ///< Seascape orientation (portrait, with 270 degrees clockwise rotation)
UpsideDown ///< Upside down orientation (portrait, with 180 degrees rotation)
};
/**
The orientation of the page
*/
Orientation orientation() const;
/**
The default CTM
*/
void defaultCTM(double *CTM, double dpiX, double dpiY, int rotate, bool upsideDown);
/**
Gets the links of the page
*/
QList<Link*> links() const;
/**
Returns the annotations of the page
*/
QList<Annotation*> annotations() const;
/**
Returns the form fields on the page
\since 0.6
*/
QList<FormField*> formFields() const;
/**
Returns the page duration. That is the time, in seconds, that the page
should be displayed before the presentation automatically advances to the next page.
Returns < 0 if duration is not set.
\since 0.6
*/
double duration() const;
/**
Returns the label of the page, or a null string is the page has no label.
\since 0.6
**/
QString label() const;
private:
Q_DISABLE_COPY(Page)
Page(DocumentData *doc, int index);
PageData *m_page;
};
/**
\brief PDF document.
The Document class represents a PDF document: its pages, and all the global
properties, metadata, etc.
\section ownership Ownership of the returned objects
All the functions that returns class pointers create new object, and the
responsability of those is given to the callee.
The only exception is \link Poppler::Page::transition() Page::transition()\endlink.
\section document-loading Loading
To get a Document, you have to load it via the load() & loadFromData()
functions.
In all the functions that have passwords as arguments, they \b must be Latin1
encoded. If you have a password that is a UTF-8 string, you need to use
QString::toLatin1() (or similar) to convert the password first.
If you have a UTF-8 character array, consider converting it to a QString first
(QString::fromUtf8(), or similar) before converting to Latin1 encoding.
\section document-rendering Rendering
To render pages of a document, you have different Document functions to set
various options.
\subsection document-rendering-backend Backends
%Poppler offers a different backends for rendering the pages. Currently
there are two backends (see #RenderBackend), but only the Splash engine works
well and has been tested.
The available rendering backends can be discovered via availableRenderBackends().
The current rendering backend can be changed using setRenderBackend().
Please note that setting a backend not listed in the available ones
will always result in null QImage's.
\section document-cms Color management support
%Poppler, if compiled with this support, provides functions to handle color
profiles.
To know whether the %Poppler version you are using has support for color
management, you can query Poppler::isCmsAvailable(). In case it is not
avilable, all the color management-related functions will either do nothing
or return null.
*/
class POPPLER_QT4_EXPORT Document {
friend class Page;
friend class DocumentData;
public:
/**
The page mode
*/
enum PageMode {
UseNone, ///< No mode - neither document outline nor thumbnail images are visible
UseOutlines, ///< Document outline visible
UseThumbs, ///< Thumbnail images visible
FullScreen, ///< Fullscreen mode (no menubar, windows controls etc)
UseOC, ///< Optional content group panel visible
UseAttach ///< Attachments panel visible
};
/**
The page layout
*/
enum PageLayout {
NoLayout, ///< Layout not specified
SinglePage, ///< Display a single page
OneColumn, ///< Display a single column of pages
TwoColumnLeft, ///< Display the pages in two columns, with odd-numbered pages on the left
TwoColumnRight, ///< Display the pages in two columns, with odd-numbered pages on the right
TwoPageLeft, ///< Display the pages two at a time, with odd-numbered pages on the left
TwoPageRight ///< Display the pages two at a time, with odd-numbered pages on the right
};
/**
The render backends available
\since 0.6
*/
enum RenderBackend {
SplashBackend, ///< Splash backend
ArthurBackend ///< Arthur (Qt4) backend
};
/**
The render hints available
\since 0.6
*/
enum RenderHint {
Antialiasing = 0x00000001, ///< Antialiasing for graphics
TextAntialiasing = 0x00000002, ///< Antialiasing for text
TextHinting = 0x00000004 ///< Hinting for text \since 0.12.1
};
Q_DECLARE_FLAGS( RenderHints, RenderHint )
/**
Set a color display profile for the current document.
\param outputProfileA is a \c cmsHPROFILE of the LCMS library.
\since 0.12
*/
void setColorDisplayProfile(void *outputProfileA);
/**
Set a color display profile for the current document.
\param name is the name of the display profile to set.
\since 0.12
*/
void setColorDisplayProfileName(const QString &name);
/**
Return the current RGB profile.
\return a \c cmsHPROFILE of the LCMS library.
\since 0.12
*/
void* colorRgbProfile() const;
/**
Return the current display profile.
\return a \c cmsHPROFILE of the LCMS library.
\since 0.12
*/
void *colorDisplayProfile() const;
/**
Load the document from a file on disk
\param filePath the name (and path, if required) of the file to load
\param ownerPassword the Latin1-encoded owner password to use in
loading the file
\param userPassword the Latin1-encoded user ("open") password
to use in loading the file
\return the loaded document, or NULL on error
\note The caller owns the pointer to Document, and this should
be deleted when no longer required.
\warning The returning document may be locked if a password is required
to open the file, and one is not provided (as the userPassword).
*/
static Document *load(const QString & filePath,
const QByteArray &ownerPassword=QByteArray(),
const QByteArray &userPassword=QByteArray());
/**
Load the document from memory
\param fileContents the file contents. They are copied so there is no need
to keep the byte array around for the full life time of
the document.
\param ownerPassword the Latin1-encoded owner password to use in
loading the file
\param userPassword the Latin1-encoded user ("open") password
to use in loading the file
\return the loaded document, or NULL on error
\note The caller owns the pointer to Document, and this should
be deleted when no longer required.
\warning The returning document may be locked if a password is required
to open the file, and one is not provided (as the userPassword).
\since 0.6
*/
static Document *loadFromData(const QByteArray &fileContents,
const QByteArray &ownerPassword=QByteArray(),
const QByteArray &userPassword=QByteArray());
/**
Get a specified Page
Note that this follows the PDF standard of being zero based - if you
want the first page, then you need an index of zero.
The caller gets the ownership of the returned object.
\param index the page number index
*/
Page *page(int index) const;
/**
\overload
The intent is that you can pass in a label like \c "ix" and
get the page with that label (which might be in the table of
contents), or pass in \c "1" and get the page that the user
expects (which might not be the first page, if there is a
title page and a table of contents).
\param label the page label
*/
Page *page(const QString &label) const;
/**
The number of pages in the document
*/
int numPages() const;
/**
The type of mode that should be used by the application
when the document is opened. Note that while this is
called page mode, it is really viewer application mode.
*/
PageMode pageMode() const;
/**
The layout that pages should be shown in when the document
is first opened. This basically describes how pages are
shown relative to each other.
*/
PageLayout pageLayout() const;
/**
Provide the passwords required to unlock the document
\param ownerPassword the Latin1-encoded owner password to use in
loading the file
\param userPassword the Latin1-encoded user ("open") password
to use in loading the file
*/
bool unlock(const QByteArray &ownerPassword, const QByteArray &userPassword);
/**
Determine if the document is locked
*/
bool isLocked() const;
/**
The date associated with the document
You would use this method with something like:
\code
QDateTime created = m_doc->date("CreationDate");
QDateTime modified = m_doc->date("ModDate");
\endcode
The available dates are:
- CreationDate: the date of creation of the document
- ModDate: the date of the last change in the document
\param data the type of date that is required
*/
QDateTime date( const QString & data ) const;
/**
Get specified information associated with the document
You would use this method with something like:
\code
QString title = m_doc->info("Title");
QString subject = m_doc->info("Subject");
\endcode
In addition to \c Title and \c Subject, other information that may
be available include \c Author, \c Keywords, \c Creator and \c Producer.
\param data the information that is required
\sa infoKeys() to get a list of the available keys
*/
QString info( const QString & data ) const;
/**
Obtain a list of the available string information keys.
*/
QStringList infoKeys() const;
/**
Test if the document is encrypted
*/
bool isEncrypted() const;
/**
Test if the document is linearised
In some cases, this is called "fast web view", since it
is mostly an optimisation for viewing over the Web.
*/
bool isLinearized() const;
/**
Test if the permissions on the document allow it to be
printed
*/
bool okToPrint() const;
/**
Test if the permissions on the document allow it to be
printed at high resolution
*/
bool okToPrintHighRes() const;
/**
Test if the permissions on the document allow it to be
changed.
\note depending on the type of change, it may be more
appropriate to check other properties as well.
*/
bool okToChange() const;
/**
Test if the permissions on the document allow the
contents to be copied / extracted
*/
bool okToCopy() const;
/**
Test if the permissions on the document allow annotations
to be added or modified, and interactive form fields (including
signature fields) to be completed.
*/
bool okToAddNotes() const;
/**
Test if the permissions on the document allow interactive
form fields (including signature fields) to be completed.
\note this can be true even if okToAddNotes() is false - this
means that only form completion is permitted.
*/
bool okToFillForm() const;
/**
Test if the permissions on the document allow interactive
form fields (including signature fields) to be set, created and
modified
*/
bool okToCreateFormFields() const;
/**
Test if the permissions on the document allow content extraction
(text and perhaps other content) for accessibility usage (eg for
a screen reader)
*/
bool okToExtractForAccessibility() const;
/**
Test if the permissions on the document allow it to be
"assembled" - insertion, rotation and deletion of pages;
or creation of bookmarks and thumbnail images.
\note this can be true even if okToChange() is false
*/
bool okToAssemble() const;
/**
The version of the PDF specification that the document
conforms to
\deprecated use getPdfVersion and avoid float point
comparisons/handling
*/
Q_DECL_DEPRECATED double pdfVersion() const;
/**
The version of the PDF specification that the document
conforms to
\param major an optional pointer to a variable where store the
"major" number of the version
\param minor an optional pointer to a variable where store the
"minor" number of the version
\since 0.12
*/
void getPdfVersion(int *major, int *minor) const;
/**
The fonts within the PDF document.
This is a shorthand for getting all the fonts at once.
\note this can take a very long time to run with a large
document. You may wish to use a FontIterator if you have more
than say 20 pages
\see newFontIterator()
*/
QList<FontInfo> fonts() const;
/**
Scans for fonts within the PDF document.
\param numPages the number of pages to scan
\param fontList pointer to the list where the font information
should be placed
\note with this method you can scan for fonts only \em once for each
document; once the end is reached, no more scanning with this method
can be done
\return false if the end of the document has been reached
\deprecated this function is quite limited in its job (see note),
better use fonts() or newFontIterator()
\see fonts(), newFontIterator()
*/
Q_DECL_DEPRECATED bool scanForFonts( int numPages, QList<FontInfo> *fontList ) const;
/**
Creates a new FontIterator object for font scanning.
The new iterator can be used for reading the font information of the
document, reading page by page.
The caller is responsible for the returned object, ie it should freed
it when no more useful.
\param startPage the initial page from which start reading fonts
\see fonts()
\since 0.12
*/
FontIterator* newFontIterator( int startPage = 0 ) const;
/**
The font data if the font is an embedded one.
\since 0.10
*/
QByteArray fontData(const FontInfo &font) const;
/**
The documents embedded within the PDF document.
\note there are two types of embedded document - this call
only accesses documents that are embedded at the document level.
*/
QList<EmbeddedFile*> embeddedFiles() const;
/**
Whether there are any documents embedded in this PDF document.
*/
bool hasEmbeddedFiles() const;
/**
Gets the table of contents (TOC) of the Document.
The caller is responsable for the returned object.
In the tree the tag name is the 'screen' name of the entry. A tag can have
attributes. Here follows the list of tag attributes with meaning:
- Destination: A string description of the referred destination
- DestinationName: A 'named reference' to the viewport
- ExternalFileName: A link to a external filename
- Open: A bool value that tells whether the subbranch of the item is open or not
Resolving the final destination for each item can be done in the following way:
- first, checking for 'Destination': if not empty, then a LinkDestination
can be constructed straight with it
- as second step, if the 'DestinationName' is not empty, then the destination
can be resolved using linkDestination()
Note also that if 'ExternalFileName' is not emtpy, then the destination refers
to that document (and not to the current one).
\returns the TOC, or NULL if the Document does not have one
*/
QDomDocument *toc() const;
/**
Tries to resolve the named destination \p name.
\note this operation starts a search through the whole document
\returns a new LinkDestination object if the named destination was
actually found, or NULL otherwise
*/
LinkDestination *linkDestination( const QString &name );
/**
Sets the paper color
\param color the new paper color
*/
void setPaperColor(const QColor &color);
/**
The paper color
The default color is white.
*/
QColor paperColor() const;
/**
Sets the backend used to render the pages.
\param backend the new rendering backend
\since 0.6
*/
void setRenderBackend( RenderBackend backend );
/**
The currently set render backend
The default backend is \ref SplashBackend
\since 0.6
*/
RenderBackend renderBackend() const;
/**
The available rendering backends.
\since 0.6
*/
static QSet<RenderBackend> availableRenderBackends();
/**
Sets the render \p hint .
\note some hints may not be supported by some rendering backends.
\param on whether the flag should be added or removed.
\since 0.6
*/
void setRenderHint( RenderHint hint, bool on = true );
/**
The currently set render hints.
\since 0.6
*/
RenderHints renderHints() const;
/**
Gets a new PS converter for this document.
The caller gets the ownership of the returned converter.
\since 0.6
*/
PSConverter *psConverter() const;
/**
Gets a new PDF converter for this document.
The caller gets the ownership of the returned converter.
\since 0.8
*/
PDFConverter *pdfConverter() const;
/**
Gets the metadata stream contents
\since 0.6
*/
QString metadata() const;
/**
Test whether this document has "optional content".
Optional content is used to optionally turn on (display)
and turn off (not display) some elements of the document.
The most common use of this is for layers in design
applications, but it can be used for a range of things,
such as not including some content in printing, and
displaying content in the appropriate language.
\since 0.8
*/
bool hasOptionalContent() const;
/**
Itemviews model for optional content.
The model is owned by the document.
\since 0.8
*/
OptContentModel *optionalContentModel();
/**
Document-level JavaScript scripts.
Returns the list of document level JavaScript scripts to be always
executed before any other script.
\since 0.10
*/
QStringList scripts() const;
/**
The PDF identifiers.
\param permanentId an optional pointer to a variable where store the
permanent ID of the document
\param updateId an optional pointer to a variable where store the
update ID of the document
\return whether the document has the IDs
\since 0.16
*/
bool getPdfId(QByteArray *permanentId, QByteArray *updateId) const;
/**
Destructor.
*/
~Document();
private:
Q_DISABLE_COPY(Document)
DocumentData *m_doc;
Document(DocumentData *dataA);
};
class BaseConverterPrivate;
class PSConverterPrivate;
class PDFConverterPrivate;
/**
\brief Base converter.
This is the base class for the converters.
\since 0.8
*/
class POPPLER_QT4_EXPORT BaseConverter
{
friend class Document;
public:
/**
Destructor.
*/
virtual ~BaseConverter();
/** Sets the output file name. You must set this or the output device. */
void setOutputFileName(const QString &outputFileName);
/**
* Sets the output device. You must set this or the output file name.
*
* \since 0.8
*/
void setOutputDevice(QIODevice *device);
/**
Does the conversion.
\return whether the conversion succeeded
*/
virtual bool convert() = 0;
enum Error
{
NoError,
FileLockedError,
OpenOutputError,
NotSupportedInputFileError
};
/**
Returns the last error
\since 0.12.1
*/
Error lastError() const;
protected:
/// \cond PRIVATE
BaseConverter(BaseConverterPrivate &dd);
Q_DECLARE_PRIVATE(BaseConverter)
BaseConverterPrivate *d_ptr;
/// \endcond
private:
Q_DISABLE_COPY(BaseConverter)
};
/**
Converts a PDF to PS
Sizes have to be in Points (1/72 inch)
If you are using QPrinter you can get paper size by doing:
\code
QPrinter dummy(QPrinter::PrinterResolution);
dummy.setFullPage(true);
dummy.setPageSize(myPageSize);
width = dummy.width();
height = dummy.height();
\endcode
\since 0.6
*/
class POPPLER_QT4_EXPORT PSConverter : public BaseConverter
{
friend class Document;
public:
/**
Options for the PS export.
\since 0.10
*/
enum PSOption {
Printing = 0x00000001, ///< The PS is generated for priting purpouses
StrictMargins = 0x00000002,
ForceRasterization = 0x00000004
};
Q_DECLARE_FLAGS( PSOptions, PSOption )
/**
Destructor.
*/
~PSConverter();
/** Sets the list of pages to print. Mandatory. */
void setPageList(const QList<int> &pageList);
/**
Sets the title of the PS Document. Optional
*/
void setTitle(const QString &title);
/**
Sets the horizontal DPI. Defaults to 72.0
*/
void setHDPI(double hDPI);
/**
Sets the vertical DPI. Defaults to 72.0
*/
void setVDPI(double vDPI);
/**
Sets the rotate. Defaults to not rotated
*/
void setRotate(int rotate);
/**
Sets the output paper width. Has to be set.
*/
void setPaperWidth(int paperWidth);
/**
Sets the output paper height. Has to be set.
*/
void setPaperHeight(int paperHeight);
/**
Sets the output right margin. Defaults to 0
*/
void setRightMargin(int marginRight);
/**
Sets the output bottom margin. Defaults to 0
*/
void setBottomMargin(int marginBottom);
/**
Sets the output left margin. Defaults to 0
*/
void setLeftMargin(int marginLeft);
/**
Sets the output top margin. Defaults to 0
*/
void setTopMargin(int marginTop);
/**
Defines if margins have to be strictly followed (even if that
means changing aspect ratio), or if the margins can be adapted
to keep aspect ratio.
Defaults to false.
*/
void setStrictMargins(bool strictMargins);
/** Defines if the page will be rasterized to an image before printing. Defaults to false */
void setForceRasterize(bool forceRasterize);
/**
Sets the options for the PS export.
\since 0.10
*/
void setPSOptions(PSOptions options);
/**
The currently set options for the PS export.
The default flags are: Printing.
\since 0.10
*/
PSOptions psOptions() const;
/**
Sets a function that will be called each time a page is converted.
The payload belongs to the caller.
\since 0.16
*/
void setPageConvertedCallback(void (* callback)(int page, void *payload), void *payload);
bool convert();
private:
Q_DECLARE_PRIVATE(PSConverter)
Q_DISABLE_COPY(PSConverter)
PSConverter(DocumentData *document);
};
/**
Converts a PDF to PDF (thus saves a copy of the document).
\since 0.8
*/
class POPPLER_QT4_EXPORT PDFConverter : public BaseConverter
{
friend class Document;
public:
/**
Options for the PDF export.
*/
enum PDFOption {
WithChanges = 0x00000001 ///< The changes done to the document are saved as well
};
Q_DECLARE_FLAGS( PDFOptions, PDFOption )
/**
Destructor.
*/
virtual ~PDFConverter();
/**
Sets the options for the PDF export.
*/
void setPDFOptions(PDFOptions options);
/**
The currently set options for the PDF export.
*/
PDFOptions pdfOptions() const;
bool convert();
private:
Q_DECLARE_PRIVATE(PDFConverter)
Q_DISABLE_COPY(PDFConverter)
PDFConverter(DocumentData *document);
};
/**
Conversion from PDF date string format to QDateTime
*/
POPPLER_QT4_EXPORT QDateTime convertDate( char *dateString );
/**
Whether the color management functions are available.
\since 0.12
*/
POPPLER_QT4_EXPORT bool isCmsAvailable();
class SoundData;
/**
Container class for a sound file in a PDF document.
A sound can be either External (in that case should be loaded the file
whose url is represented by url() ), or Embedded, and the player has to
play the data contained in data().
\since 0.6
*/
class POPPLER_QT4_EXPORT SoundObject {
public:
/**
The type of sound
*/
enum SoundType {
External, ///< The real sound file is external
Embedded ///< The sound is contained in the data
};
/**
The encoding format used for the sound
*/
enum SoundEncoding {
Raw, ///< Raw encoding, with unspecified or unsigned values in the range [ 0, 2^B - 1 ]
Signed, ///< Twos-complement values
muLaw, ///< mu-law-encoded samples
ALaw ///< A-law-encoded samples
};
/// \cond PRIVATE
SoundObject(Sound *popplersound);
/// \endcond
~SoundObject();
/**
Is the sound embedded (SoundObject::Embedded) or external (SoundObject::External)?
*/
SoundType soundType() const;
/**
The URL of the sound file to be played, in case of SoundObject::External
*/
QString url() const;
/**
The data of the sound, in case of SoundObject::Embedded
*/
QByteArray data() const;
/**
The sampling rate of the sound
*/
double samplingRate() const;
/**
The number of sound channels to use to play the sound
*/
int channels() const;
/**
The number of bits per sample value per channel
*/
int bitsPerSample() const;
/**
The encoding used for the sound
*/
SoundEncoding soundEncoding() const;
private:
Q_DISABLE_COPY(SoundObject)
SoundData *m_soundData;
};
class MovieData;
/**
Container class for a movie object in a PDF document.
\since 0.10
*/
class POPPLER_QT4_EXPORT MovieObject {
friend class Page;
public:
/**
The play mode for playing the movie
*/
enum PlayMode {
PlayOnce, ///< Play the movie once, closing the movie controls at the end
PlayOpen, ///< Like PlayOnce, but leaving the controls open
PlayRepeat, ///< Play continuously until stopped
PlayPalindrome ///< Play forward, then backward, then again foward and so on until stopped
};
~MovieObject();
/**
The URL of the movie to be played
*/
QString url() const;
/**
The size of the movie
*/
QSize size() const;
/**
The rotation (either 0, 90, 180, or 270 degrees clockwise) for the movie,
*/
int rotation() const;
/**
Whether show a bar with movie controls
*/
bool showControls() const;
/**
How to play the movie
*/
PlayMode playMode() const;
private:
/// \cond PRIVATE
MovieObject( AnnotMovie *ann );
/// \endcond
Q_DISABLE_COPY(MovieObject)
MovieData *m_movieData;
};
}
Q_DECLARE_OPERATORS_FOR_FLAGS(Poppler::Page::PainterFlags)
Q_DECLARE_OPERATORS_FOR_FLAGS(Poppler::Document::RenderHints)
Q_DECLARE_OPERATORS_FOR_FLAGS(Poppler::PDFConverter::PDFOptions)
Q_DECLARE_OPERATORS_FOR_FLAGS(Poppler::PSConverter::PSOptions)
#endif
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2012 Catalin Badea
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
#include <set>
#include <QDate>
#include <Swift/Controllers/UIInterfaces/HistoryWindow.h>
#include <Swift/QtUI/QtTabbable.h>
#include <Swift/QtUI/ui_QtHistoryWindow.h>
namespace Swift {
class QtTabbable;
class QtTreeWidget;
class QtWebKitChatView;
class QtChatTheme;
class SettingsProvider;
class UIEventStream;
class QtHistoryWindow : public QtTabbable, public HistoryWindow {
Q_OBJECT
public:
QtHistoryWindow(SettingsProvider*, UIEventStream*);
~QtHistoryWindow();
void activate();
void setRosterModel(Roster*);
void addMessage(const std::string& message, const std::string& senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop);
void resetConversationView();
void resetConversationViewTopInsertPoint();
void setDate(const boost::gregorian::date& date);
void closeEvent(QCloseEvent* event);
void showEvent(QShowEvent* event);
std::string getSearchBoxText();
boost::gregorian::date getLastVisibleDate();
virtual std::string getID() const;
signals:
void fontResized(int);
public slots:
void handleFontResized(int fontSizeSteps);
protected slots:
void handleScrollRequested(int pos);
void handleScrollReachedTop();
void handleScrollReachedBottom();
void handleReturnPressed();
void handleCalendarClicked(const QDate& date);
void handlePreviousButtonClicked();
void handleNextButtonClicked();
private:
void handleSomethingSelectedChanged(RosterItem* item);
Ui::QtHistoryWindow ui_;
QtChatTheme* theme_;
QtWebKitChatView* conversation_;
QtTreeWidget* conversationRoster_;
std::set<QDate> dates_;
int idCounter_;
bool previousTopMessageWasSelf_;
QString previousTopSenderName_;
bool previousBottomMessageWasSelf_;
QString previousBottomSenderName_;
};
}
|
{
"pile_set_name": "Github"
}
|
(function() {
var dfs = {"am_pm":["နံနက်","ညနေ"],"day_name":["တနင်္ဂနွေ","တနင်္လာ","အင်္ဂါ","ဗုဒ္ဓဟူး","ကြာသပတေး","သောကြာ","စနေ"],"day_short":["နွေ","လာ","ဂါ","ဟူး","တေး","ကြာ","နေ"],"era":["ဘီစီ","အေဒီ"],"era_name":["ခရစ်တော် မပေါ်မီကာလ","ခရစ်တော် ပေါ်ထွန်းပြီးကာလ"],"month_name":["ဇန်နဝါရီ","ဖေဖော်ဝါရီ","မတ်","ဧပြီ","မေ","ဇွန်","ဇူလိုင်","ဩဂုတ်","စက်တင်ဘာ","အောက်တိုဘာ","နိုဝင်ဘာ","ဒီဇင်ဘာ"],"month_short":["ဇန်","ဖေ","မတ်","ဧ","မေ","ဇွန်","ဇူ","ဩ","စက်","အောက်","နို","ဒီ"],"order_full":"MDY","order_long":"MDY","order_medium":"MDY","order_short":"MDY"};
var nfs = {"decimal_separator":".","grouping_separator":",","minus":"-"};
var df = {SHORT_PADDED_CENTURY:function(d){if(d){return(((d.getMonth()+101)+'').substring(1)+'/'+((d.getDate()+101)+'').substring(1)+'/'+d.getFullYear());}},SHORT:function(d){if(d){return((d.getMonth()+1)+'/'+d.getDate()+'/'+(d.getFullYear()+'').substring(2));}},SHORT_NOYEAR:function(d){if(d){return((d.getMonth()+1)+'/'+d.getDate());}},SHORT_NODAY:function(d){if(d){return((d.getMonth()+1)+' '+(d.getFullYear()+'').substring(2));}},MEDIUM:function(d){if(d){return(dfs.month_short[d.getMonth()]+' '+d.getDate()+','+' '+d.getFullYear());}},MEDIUM_NOYEAR:function(d){if(d){return(dfs.month_short[d.getMonth()]+' '+d.getDate());}},MEDIUM_WEEKDAY_NOYEAR:function(d){if(d){return(dfs.day_short[d.getDay()]+' '+dfs.month_short[d.getMonth()]+' '+d.getDate());}},LONG_NODAY:function(d){if(d){return(dfs.month_name[d.getMonth()]+' '+d.getFullYear());}},LONG:function(d){if(d){return(dfs.month_name[d.getMonth()]+' '+d.getDate()+','+' '+d.getFullYear());}},FULL:function(d){if(d){return(dfs.day_name[d.getDay()]+','+' '+dfs.month_name[d.getMonth()]+' '+d.getDate()+','+' '+d.getFullYear());}}};
window.icu = window.icu || new Object();
var icu = window.icu;
icu.getCountry = function() { return "MM" };
icu.getCountryName = function() { return "မြန်မာ" };
icu.getDateFormat = function(formatCode) { var retVal = {}; retVal.format = df[formatCode]; return retVal; };
icu.getDateFormats = function() { return df; };
icu.getDateFormatSymbols = function() { return dfs; };
icu.getDecimalFormat = function(places) { var retVal = {}; retVal.format = function(n) { var ns = n < 0 ? Math.abs(n).toFixed(places) : n.toFixed(places); var ns2 = ns.split('.'); s = ns2[0]; var d = ns2[1]; var rgx = /(\d+)(\d{3})/;while(rgx.test(s)){s = s.replace(rgx, '$1' + nfs["grouping_separator"] + '$2');} return (n < 0 ? nfs["minus"] : "") + s + nfs["decimal_separator"] + d;}; return retVal; };
icu.getDecimalFormatSymbols = function() { return nfs; };
icu.getIntegerFormat = function() { var retVal = {}; retVal.format = function(i) { var s = i < 0 ? Math.abs(i).toString() : i.toString(); var rgx = /(\d+)(\d{3})/;while(rgx.test(s)){s = s.replace(rgx, '$1' + nfs["grouping_separator"] + '$2');} return i < 0 ? nfs["minus"] + s : s;}; return retVal; };
icu.getLanguage = function() { return "my" };
icu.getLanguageName = function() { return "ဗမာ" };
icu.getLocale = function() { return "my-MM" };
icu.getLocaleName = function() { return "ဗမာ (မြန်မာ)" };
})();
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---------------------------------------------------------------------------
//
// The contents of this file must follow a specific format in order to
// support the CEF translator tool. See the translator.README.txt file in the
// tools directory for more information.
//
// THIS FILE IS FOR TESTING PURPOSES ONLY.
//
// The APIs defined in this file are for testing purposes only. They should only
// be included from unit test targets.
//
#ifndef CEF_INCLUDE_TEST_CEF_TEST_H_
#define CEF_INCLUDE_TEST_CEF_TEST_H_
#pragma once
#if !defined(BUILDING_CEF_SHARED) && !defined(WRAPPING_CEF_SHARED) && \
!defined(UNIT_TEST)
#error This file can be included for unit tests only
#endif
#include <map>
#include <vector>
#include "include/cef_base.h"
class CefTranslatorTestRefPtrClient;
class CefTranslatorTestRefPtrClientChild;
class CefTranslatorTestRefPtrLibrary;
class CefTranslatorTestRefPtrLibraryChild;
class CefTranslatorTestScopedClient;
class CefTranslatorTestScopedClientChild;
class CefTranslatorTestScopedLibrary;
class CefTranslatorTestScopedLibraryChild;
// Test values.
#define TEST_INT_VAL 5
#define TEST_INT_VAL2 60
#define TEST_BOOL_VAL true
#define TEST_DOUBLE_VAL 4.543
#define TEST_LONG_VAL -65
#define TEST_SIZET_VAL 3U
#define TEST_STRING_VAL "My test string"
#define TEST_STRING_VAL2 "My 2nd test string"
#define TEST_STRING_VAL3 "My 3rd test string"
#define TEST_STRING_KEY "key0"
#define TEST_STRING_KEY2 "key1"
#define TEST_STRING_KEY3 "key2"
#define TEST_X_VAL 44
#define TEST_Y_VAL 754
#define TEST_X_VAL2 900
#define TEST_Y_VAL2 300
///
// Class for testing all of the possible data transfer types.
///
/*--cef(source=library)--*/
class CefTranslatorTest : public CefBaseRefCounted {
public:
///
// Create the test object.
///
/*--cef()--*/
static CefRefPtr<CefTranslatorTest> Create();
// PRIMITIVE VALUES
///
// Return a void value.
///
/*--cef()--*/
virtual void GetVoid() =0;
///
// Return a bool value.
///
/*--cef()--*/
virtual bool GetBool() =0;
///
// Return an int value.
///
/*--cef()--*/
virtual int GetInt() =0;
///
// Return a double value.
///
/*--cef()--*/
virtual double GetDouble() =0;
///
// Return a long value.
///
/*--cef()--*/
virtual long GetLong() =0;
///
// Return a size_t value.
///
/*--cef()--*/
virtual size_t GetSizet() =0;
///
// Set a void value.
///
/*--cef()--*/
virtual bool SetVoid() =0;
///
// Set a bool value.
///
/*--cef()--*/
virtual bool SetBool(bool val) =0;
///
// Set an int value.
///
/*--cef()--*/
virtual bool SetInt(int val) =0;
///
// Set a double value.
///
/*--cef()--*/
virtual bool SetDouble(double val) =0;
///
// Set a long value.
///
/*--cef()--*/
virtual bool SetLong(long val) =0;
///
// Set a size_t value.
///
/*--cef()--*/
virtual bool SetSizet(size_t val) =0;
// PRIMITIVE LIST VALUES
// Test both with and without a typedef.
typedef std::vector<int> IntList;
///
// Set a int list value.
///
/*--cef()--*/
virtual bool SetIntList(const std::vector<int>& val) =0;
///
// Return an int list value by out-param.
///
/*--cef(count_func=val:GetIntListSize)--*/
virtual bool GetIntListByRef(IntList& val) =0;
///
// Return the number of points that will be output above.
///
/*--cef()--*/
virtual size_t GetIntListSize() = 0;
// STRING VALUES
///
// Return a string value.
///
/*--cef()--*/
virtual CefString GetString() =0;
///
// Set a string value.
///
/*--cef()--*/
virtual bool SetString(const CefString& val) =0;
///
// Return a string value by out-param.
///
/*--cef()--*/
virtual void GetStringByRef(CefString& val) =0;
// STRING LIST VALUES
// Test both with and without a typedef.
typedef std::vector<CefString> StringList;
///
// Set a string list value.
///
/*--cef()--*/
virtual bool SetStringList(const std::vector<CefString>& val) =0;
///
// Return a string list value by out-param.
///
/*--cef()--*/
virtual bool GetStringListByRef(StringList& val) =0;
// STRING MAP VALUES
// Test both with and without a typedef.
typedef std::map<CefString, CefString> StringMap;
///
// Set a string map value.
///
/*--cef()--*/
virtual bool SetStringMap(const StringMap& val) =0;
///
// Return a string map value by out-param.
///
/*--cef()--*/
virtual bool GetStringMapByRef(std::map<CefString, CefString>& val) =0;
// STRING MULTIMAP VALUES
// Test both with and without a typedef.
typedef std::multimap<CefString, CefString> StringMultimap;
///
// Set a string multimap value.
///
/*--cef()--*/
virtual bool SetStringMultimap(
const std::multimap<CefString, CefString>& val) =0;
///
// Return a string multimap value by out-param.
///
/*--cef()--*/
virtual bool GetStringMultimapByRef(StringMultimap& val) =0;
// STRUCT VALUES
///
// Return a point value.
///
/*--cef()--*/
virtual CefPoint GetPoint() =0;
///
// Set a point value.
///
/*--cef()--*/
virtual bool SetPoint(const CefPoint& val) =0;
///
// Return a point value by out-param.
///
/*--cef()--*/
virtual void GetPointByRef(CefPoint& val) =0;
// STRUCT LIST VALUES
// Test both with and without a typedef.
typedef std::vector<CefPoint> PointList;
///
// Set a point list vlaue.
///
/*--cef()--*/
virtual bool SetPointList(const std::vector<CefPoint>& val) =0;
///
// Return a point list value by out-param.
///
/*--cef(count_func=val:GetPointListSize)--*/
virtual bool GetPointListByRef(PointList& val) =0;
///
// Return the number of points that will be output above.
///
/*--cef()--*/
virtual size_t GetPointListSize() = 0;
// LIBRARY-SIDE REFPTR VALUES
///
// Return an new library-side object.
///
/*--cef()--*/
virtual CefRefPtr<CefTranslatorTestRefPtrLibrary> GetRefPtrLibrary(
int val) =0;
///
// Set an object. Returns the value from
// CefTranslatorTestRefPtrLibrary::GetValue().
// This tests input and execution of a library-side object type.
///
/*--cef()--*/
virtual int SetRefPtrLibrary(
CefRefPtr<CefTranslatorTestRefPtrLibrary> val) =0;
///
// Set an object. Returns the object passed in. This tests input and output
// of a library-side object type.
///
/*--cef()--*/
virtual CefRefPtr<CefTranslatorTestRefPtrLibrary> SetRefPtrLibraryAndReturn(
CefRefPtr<CefTranslatorTestRefPtrLibrary> val) =0;
///
// Set a child object. Returns the value from
// CefTranslatorTestRefPtrLibrary::GetValue(). This tests input of a library-
// side child object type and execution as the parent type.
///
/*--cef()--*/
virtual int SetChildRefPtrLibrary(
CefRefPtr<CefTranslatorTestRefPtrLibraryChild> val) =0;
///
// Set a child object. Returns the object as the parent type. This tests input
// of a library-side child object type and return as the parent type.
///
/*--cef()--*/
virtual CefRefPtr<CefTranslatorTestRefPtrLibrary>
SetChildRefPtrLibraryAndReturnParent(
CefRefPtr<CefTranslatorTestRefPtrLibraryChild> val) =0;
// LIBRARY-SIDE REFPTR LIST VALUES
// Test both with and without a typedef.
typedef std::vector<CefRefPtr<CefTranslatorTestRefPtrLibrary> >
RefPtrLibraryList;
///
// Set an object list vlaue.
///
/*--cef()--*/
virtual bool SetRefPtrLibraryList(
const std::vector<CefRefPtr<CefTranslatorTestRefPtrLibrary> >& val,
int val1, int val2) =0;
///
// Return an object list value by out-param.
///
/*--cef(count_func=val:GetRefPtrLibraryListSize)--*/
virtual bool GetRefPtrLibraryListByRef(RefPtrLibraryList& val, int val1,
int val2) =0;
///
// Return the number of object that will be output above.
///
/*--cef()--*/
virtual size_t GetRefPtrLibraryListSize() = 0;
// CLIENT-SIDE REFPTR VALUES
///
// Set an object. Returns the value from
// CefTranslatorTestRefPtrClient::GetValue().
// This tests input and execution of a client-side object type.
///
/*--cef()--*/
virtual int SetRefPtrClient(CefRefPtr<CefTranslatorTestRefPtrClient> val) =0;
///
// Set an object. Returns the handler passed in. This tests input and output
// of a client-side object type.
///
/*--cef()--*/
virtual CefRefPtr<CefTranslatorTestRefPtrClient> SetRefPtrClientAndReturn(
CefRefPtr<CefTranslatorTestRefPtrClient> val) =0;
///
// Set a child object. Returns the value from
// CefTranslatorTestRefPtrClient::GetValue(). This tests input of a client-
// side child object type and execution as the parent type.
///
/*--cef()--*/
virtual int SetChildRefPtrClient(
CefRefPtr<CefTranslatorTestRefPtrClientChild> val) =0;
///
// Set a child object. Returns the object as the parent type. This tests
// input of a client-side child object type and return as the parent type.
///
/*--cef()--*/
virtual CefRefPtr<CefTranslatorTestRefPtrClient>
SetChildRefPtrClientAndReturnParent(
CefRefPtr<CefTranslatorTestRefPtrClientChild> val) =0;
// CLIENT-SIDE REFPTR LIST VALUES
// Test both with and without a typedef.
typedef std::vector<CefRefPtr<CefTranslatorTestRefPtrClient> >
RefPtrClientList;
///
// Set an object list vlaue.
///
/*--cef()--*/
virtual bool SetRefPtrClientList(
const std::vector<CefRefPtr<CefTranslatorTestRefPtrClient> >& val,
int val1, int val2) =0;
///
// Return an object list value by out-param.
///
/*--cef(count_func=val:GetRefPtrLibraryListSize)--*/
virtual bool GetRefPtrClientListByRef(
RefPtrClientList& val,
CefRefPtr<CefTranslatorTestRefPtrClient> val1,
CefRefPtr<CefTranslatorTestRefPtrClient> val2) =0;
///
// Return the number of object that will be output above.
///
/*--cef()--*/
virtual size_t GetRefPtrClientListSize() = 0;
// LIBRARY-SIDE OWNPTR VALUES
///
// Return an new library-side object.
///
/*--cef()--*/
virtual CefOwnPtr<CefTranslatorTestScopedLibrary> GetOwnPtrLibrary(
int val) =0;
///
// Set an object. Returns the value from
// CefTranslatorTestScopedLibrary::GetValue().
// This tests input and execution of a library-side object type.
///
/*--cef()--*/
virtual int SetOwnPtrLibrary(
CefOwnPtr<CefTranslatorTestScopedLibrary> val) =0;
///
// Set an object. Returns the object passed in. This tests input and output
// of a library-side object type.
///
/*--cef()--*/
virtual CefOwnPtr<CefTranslatorTestScopedLibrary> SetOwnPtrLibraryAndReturn(
CefOwnPtr<CefTranslatorTestScopedLibrary> val) =0;
///
// Set a child object. Returns the value from
// CefTranslatorTestScopedLibrary::GetValue(). This tests input of a library-
// side child object type and execution as the parent type.
///
/*--cef()--*/
virtual int SetChildOwnPtrLibrary(
CefOwnPtr<CefTranslatorTestScopedLibraryChild> val) =0;
///
// Set a child object. Returns the object as the parent type. This tests input
// of a library-side child object type and return as the parent type.
///
/*--cef()--*/
virtual CefOwnPtr<CefTranslatorTestScopedLibrary>
SetChildOwnPtrLibraryAndReturnParent(
CefOwnPtr<CefTranslatorTestScopedLibraryChild> val) =0;
// CLIENT-SIDE OWNPTR VALUES
///
// Set an object. Returns the value from
// CefTranslatorTestScopedClient::GetValue().
// This tests input and execution of a client-side object type.
///
/*--cef()--*/
virtual int SetOwnPtrClient(CefOwnPtr<CefTranslatorTestScopedClient> val) =0;
///
// Set an object. Returns the handler passed in. This tests input and output
// of a client-side object type.
///
/*--cef()--*/
virtual CefOwnPtr<CefTranslatorTestScopedClient> SetOwnPtrClientAndReturn(
CefOwnPtr<CefTranslatorTestScopedClient> val) =0;
///
// Set a child object. Returns the value from
// CefTranslatorTestScopedClient::GetValue(). This tests input of a client-
// side child object type and execution as the parent type.
///
/*--cef()--*/
virtual int SetChildOwnPtrClient(
CefOwnPtr<CefTranslatorTestScopedClientChild> val) =0;
///
// Set a child object. Returns the object as the parent type. This tests
// input of a client-side child object type and return as the parent type.
///
/*--cef()--*/
virtual CefOwnPtr<CefTranslatorTestScopedClient>
SetChildOwnPtrClientAndReturnParent(
CefOwnPtr<CefTranslatorTestScopedClientChild> val) =0;
// LIBRARY-SIDE RAWPTR VALUES
///
// Set an object. Returns the value from
// CefTranslatorTestScopedLibrary::GetValue().
// This tests input and execution of a library-side object type.
///
/*--cef()--*/
virtual int SetRawPtrLibrary(
CefRawPtr<CefTranslatorTestScopedLibrary> val) =0;
///
// Set a child object. Returns the value from
// CefTranslatorTestScopedLibrary::GetValue(). This tests input of a library-
// side child object type and execution as the parent type.
///
/*--cef()--*/
virtual int SetChildRawPtrLibrary(
CefRawPtr<CefTranslatorTestScopedLibraryChild> val) =0;
// LIBRARY-SIDE RAWPTR LIST VALUES
// Test both with and without a typedef.
typedef std::vector<CefRawPtr<CefTranslatorTestScopedLibrary> >
RawPtrLibraryList;
///
// Set an object list vlaue.
///
/*--cef()--*/
virtual bool SetRawPtrLibraryList(
const std::vector<CefRawPtr<CefTranslatorTestScopedLibrary> >& val,
int val1, int val2) =0;
// CLIENT-SIDE RAWPTR VALUES
///
// Set an object. Returns the value from
// CefTranslatorTestScopedClient::GetValue().
// This tests input and execution of a client-side object type.
///
/*--cef()--*/
virtual int SetRawPtrClient(CefRawPtr<CefTranslatorTestScopedClient> val) =0;
///
// Set a child object. Returns the value from
// CefTranslatorTestScopedClient::GetValue(). This tests input of a client-
// side child object type and execution as the parent type.
///
/*--cef()--*/
virtual int SetChildRawPtrClient(
CefRawPtr<CefTranslatorTestScopedClientChild> val) =0;
// CLIENT-SIDE RAWPTR LIST VALUES
// Test both with and without a typedef.
typedef std::vector<CefRawPtr<CefTranslatorTestScopedClient> >
RawPtrClientList;
///
// Set an object list vlaue.
///
/*--cef()--*/
virtual bool SetRawPtrClientList(
const std::vector<CefRawPtr<CefTranslatorTestScopedClient> >& val,
int val1, int val2) =0;
};
///
// Library-side test object for RefPtr.
///
/*--cef(source=library)--*/
class CefTranslatorTestRefPtrLibrary : public CefBaseRefCounted {
public:
///
// Create the test object.
///
/*--cef()--*/
static CefRefPtr<CefTranslatorTestRefPtrLibrary> Create(int value);
///
// Return a value.
///
/*--cef()--*/
virtual int GetValue() =0;
///
// Set a value.
///
/*--cef()--*/
virtual void SetValue(int value) =0;
};
///
// Library-side child test object for RefPtr.
///
/*--cef(source=library)--*/
class CefTranslatorTestRefPtrLibraryChild :
public CefTranslatorTestRefPtrLibrary {
public:
///
// Create the test object.
///
/*--cef()--*/
static CefRefPtr<CefTranslatorTestRefPtrLibraryChild> Create(
int value,
int other_value);
///
// Return a value.
///
/*--cef()--*/
virtual int GetOtherValue() =0;
///
// Set a value.
///
/*--cef()--*/
virtual void SetOtherValue(int value) =0;
};
///
// Another library-side child test object for RefPtr.
///
/*--cef(source=library)--*/
class CefTranslatorTestRefPtrLibraryChildChild :
public CefTranslatorTestRefPtrLibraryChild {
public:
///
// Create the test object.
///
/*--cef()--*/
static CefRefPtr<CefTranslatorTestRefPtrLibraryChildChild> Create(
int value,
int other_value,
int other_other_value);
///
// Return a value.
///
/*--cef()--*/
virtual int GetOtherOtherValue() =0;
///
// Set a value.
///
/*--cef()--*/
virtual void SetOtherOtherValue(int value) =0;
};
///
// Client-side test object for RefPtr.
///
/*--cef(source=client)--*/
class CefTranslatorTestRefPtrClient : public virtual CefBaseRefCounted {
public:
///
// Return a value.
///
/*--cef()--*/
virtual int GetValue() =0;
};
///
// Client-side child test object for RefPtr.
///
/*--cef(source=client)--*/
class CefTranslatorTestRefPtrClientChild :
public CefTranslatorTestRefPtrClient {
public:
///
// Return a value.
///
/*--cef()--*/
virtual int GetOtherValue() =0;
};
///
// Library-side test object for OwnPtr/RawPtr.
///
/*--cef(source=library)--*/
class CefTranslatorTestScopedLibrary : public CefBaseScoped {
public:
///
// Create the test object.
///
/*--cef()--*/
static CefOwnPtr<CefTranslatorTestScopedLibrary> Create(int value);
///
// Return a value.
///
/*--cef()--*/
virtual int GetValue() =0;
///
// Set a value.
///
/*--cef()--*/
virtual void SetValue(int value) =0;
};
///
// Library-side child test object for OwnPtr/RawPtr.
///
/*--cef(source=library)--*/
class CefTranslatorTestScopedLibraryChild :
public CefTranslatorTestScopedLibrary {
public:
///
// Create the test object.
///
/*--cef()--*/
static CefOwnPtr<CefTranslatorTestScopedLibraryChild> Create(
int value,
int other_value);
///
// Return a value.
///
/*--cef()--*/
virtual int GetOtherValue() =0;
///
// Set a value.
///
/*--cef()--*/
virtual void SetOtherValue(int value) =0;
};
///
// Another library-side child test object for OwnPtr/RawPtr.
///
/*--cef(source=library)--*/
class CefTranslatorTestScopedLibraryChildChild :
public CefTranslatorTestScopedLibraryChild {
public:
///
// Create the test object.
///
/*--cef()--*/
static CefOwnPtr<CefTranslatorTestScopedLibraryChildChild> Create(
int value,
int other_value,
int other_other_value);
///
// Return a value.
///
/*--cef()--*/
virtual int GetOtherOtherValue() =0;
///
// Set a value.
///
/*--cef()--*/
virtual void SetOtherOtherValue(int value) =0;
};
///
// Client-side test object for OwnPtr/RawPtr.
///
/*--cef(source=client)--*/
class CefTranslatorTestScopedClient : public virtual CefBaseScoped {
public:
///
// Return a value.
///
/*--cef()--*/
virtual int GetValue() =0;
};
///
// Client-side child test object for OwnPtr/RawPtr.
///
/*--cef(source=client)--*/
class CefTranslatorTestScopedClientChild :
public CefTranslatorTestScopedClient {
public:
///
// Return a value.
///
/*--cef()--*/
virtual int GetOtherValue() =0;
};
#endif // CEF_INCLUDE_TEST_CEF_TEST_H_
|
{
"pile_set_name": "Github"
}
|
# -*- encoding: binary -*-
require_relative '../../../spec_helper'
require 'zlib'
describe "Zlib::Inflate#set_dictionary" do
it "sets the inflate dictionary" do
deflated = "x\273\024\341\003\313KLJNIMK\317\310\314\002\000\025\206\003\370"
i = Zlib::Inflate.new
begin
i << deflated
flunk 'Zlib::NeedDict not raised'
rescue Zlib::NeedDict
i.set_dictionary 'aaaaaaaaaa'
end
i.finish.should == 'abcdefghij'
end
end
|
{
"pile_set_name": "Github"
}
|
# This is a part of the Microsoft Foundation Classes C++ library.
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is only intended as a supplement to the
# Microsoft Foundation Classes Reference and related
# electronic documentation provided with the library.
# See these sources for detailed information regarding the
# Microsoft Foundation Classes product.
PROJ=MAKEHM
OBJS=makehm.obj makehm.res
CONSOLE=1
NO_PCH=1
UNICODE=0
!include <mfcsamps.mak>
|
{
"pile_set_name": "Github"
}
|
## PGLowLatencyAudio Plugin for BlackBerry10, using Cordova.
Plays audio .wav files using openAL, ALUT, Qdir, and QtCore libraries.
For a sample application demonstrating the use of this API, please see the [LowLatencySequencer](https://github.com/blackberry/Cordova-Samples/tree/master/LowLatencySequencer)
## Version History
1.0.0 Initial Release
1.0.1 Shutsdown audio channels when not in use
## Installation
The plugin can be installed from source or NPM using one of the following commands in your Cordova project location:
NPM:
cordova plugin add cordova-plugin-bb-nativeaudio
Source:
cordova plugin add path-to-plugin/PGLowLatencyAudio
To start off, in the directory PGLowLatencyAudio/www contains the API. Every function is called using PGLowLatencyAudio, and we have the follow functions:
preloadAudio: function (data, path, voices, success, fail) {
exec(success, fail, service, "preloadAudio", { data: data, path: path, voices: voices });
},
unload: function (data, success, fail) {
exec(success, fail, service, "unload", { data: data });
},
play: function (data, success, fail) {
exec(success, fail, service, "play", { data: data });
},
stop: function (data, success, fail) {
exec(success, fail, service, "stop", { data: data });
},
getDuration: function (data, success, fail) {
exec(success, fail, service, "getDuration", { data: data });
},
loop: function (data, success, fail) {
exec(success, fail, service, "loop", { data: data });
}
Note: In the exampled below we use the success call back to display messages for debugging purposes. To remove these messages, simply remove 'alert(echoValue)' from the function call, however if you do run into troubles, these call backs should provide useful information to debug. If you wanted you could include a fail function to each of these, for example your fail function could be function(){alert("FAIL")};
## Examples:
If in our Cordova Applications www application folder, we have the path assets/sounds, to our sound location we can do the following:
----------------------------------------------------------------------------------
### preloadAudio
Preloads an audio file into a buffer so it can be played automatically without loading. Takes in three parameters, the file name, the path to the sounds, and how many unique voices it can have. Voices are how many simultaneous sounds that can be played at once.
Example:
PGLowLatencyAudio.preloadAudio("bounce.wav", "assets/sounds/", 1, function(echoValue) {
alert(echoValue);},
});
----------------------------------------------------------------------------------
### unload
Unloads an audio file from the current buffer it holds up. Used to free and allocate space in openAL. Takes in one parameter, file name.
Example:
PGLowLatencyAudio.unload("bounce.wav", function(echoValue) {
alert(echoValue);
});
----------------------------------------------------------------------------------
### play
Plays an audio file using openAL. Takes in one parameter, file name.
Example:
PGLowLatencyAudio.play("bounce.wav", function(echoValue) {
alert(echoValue);
});
----------------------------------------------------------------------------------
### stop
Stops an audio file from playing or looping. Takes one parameter, file name.
Example:
PGLowLatencyAudio.stop("bounce.wav", function(echoValue) {
alert(echoValue);
});
----------------------------------------------------------------------------------
### getDuration
Get the duration of a file. Takes one parameter, file name.
Example:
PGLowLatencyAudio.getDuration("bounce.wav", function(duration) {
if (duration > 6.0) {
alert(“Greater than 6”);
} else {
alert(“Less than 6”);
}
});
----------------------------------------------------------------------------------
### loop
Loops an audio file indefinitely until either unloaded or stopped. Takes in one parameter, file name.
Example:
PGLowLatencyAudio.loop("background.wav", function(echoValue) {
alert(echoValue);
});
----------------------------------------------------------------------------------
The Native portion of the plugin is called using JNEXT.invoke, and inputting either of the following strings, 'load', 'unload', 'play', 'stop', 'loop'.
For more information about how to run and build Cordova applications, refer to:
https://github.com/blackberry/cordova-blackberry/tree/master/blackberry10
## Disclaimer
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
{
"pile_set_name": "Github"
}
|
@comment $NetBSD: PLIST,v 1.1.1.1 2010/03/09 22:05:53 snj Exp $
lib/ioquake3/baseq3/pak1.pk3
lib/ioquake3/baseq3/pak2.pk3
lib/ioquake3/baseq3/pak3.pk3
lib/ioquake3/baseq3/pak4.pk3
lib/ioquake3/baseq3/pak5.pk3
lib/ioquake3/baseq3/pak6.pk3
lib/ioquake3/baseq3/pak7.pk3
lib/ioquake3/baseq3/pak8.pk3
lib/ioquake3/missionpack/pak1.pk3
lib/ioquake3/missionpack/pak2.pk3
lib/ioquake3/missionpack/pak3.pk3
|
{
"pile_set_name": "Github"
}
|
<Type Name="FilterInputStream" FullName="GLib.FilterInputStream">
<TypeSignature Language="C#" Value="public class FilterInputStream : GLib.InputStream" />
<TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit FilterInputStream extends GLib.InputStream" />
<AssemblyInfo>
<AssemblyName>gio-sharp</AssemblyName>
</AssemblyInfo>
<Base>
<BaseTypeName>GLib.InputStream</BaseTypeName>
</Base>
<Interfaces />
<Docs>
<summary>To be added.</summary>
<remarks>To be added.</remarks>
<since version="Gtk# 2.14" />
</Docs>
<Members>
<Member MemberName=".ctor">
<MemberSignature Language="C#" Value="protected FilterInputStream ();" />
<MemberSignature Language="ILAsm" Value=".method familyhidebysig specialname rtspecialname instance void .ctor() cil managed" />
<MemberType>Constructor</MemberType>
<Parameters />
<Docs>
<summary>To be added.</summary>
<remarks>To be added.</remarks>
<since version="Gtk# 2.14" />
</Docs>
</Member>
<Member MemberName=".ctor">
<MemberSignature Language="C#" Value="public FilterInputStream (IntPtr raw);" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(native int raw) cil managed" />
<MemberType>Constructor</MemberType>
<Parameters>
<Parameter Name="raw" Type="System.IntPtr" />
</Parameters>
<Docs>
<param name="raw">Native object pointer.</param>
<summary>Internal constructor</summary>
<remarks>This is not typically used by C# code. Exposed primarily for use by language bindings to wrap native object instances.</remarks>
<since version="Gtk# 2.14" />
</Docs>
</Member>
<Member MemberName="BaseStream">
<MemberSignature Language="C#" Value="public GLib.InputStream BaseStream { get; }" />
<MemberSignature Language="ILAsm" Value=".property instance class GLib.InputStream BaseStream" />
<MemberType>Property</MemberType>
<Attributes>
<Attribute>
<AttributeName>GLib.Property("base-stream")</AttributeName>
</Attribute>
</Attributes>
<ReturnValue>
<ReturnType>GLib.InputStream</ReturnType>
</ReturnValue>
<Docs>
<summary>To be added.</summary>
<value>To be added.</value>
<remarks>To be added.</remarks>
<since version="Gtk# 2.14" />
</Docs>
</Member>
<Member MemberName="CloseBaseStream">
<MemberSignature Language="C#" Value="public bool CloseBaseStream { get; set; }" />
<MemberSignature Language="ILAsm" Value=".property instance bool CloseBaseStream" />
<MemberType>Property</MemberType>
<Attributes>
<Attribute>
<AttributeName>GLib.Property("close-base-stream")</AttributeName>
</Attribute>
</Attributes>
<ReturnValue>
<ReturnType>System.Boolean</ReturnType>
</ReturnValue>
<Docs>
<summary>To be added.</summary>
<value>To be added.</value>
<remarks>To be added.</remarks>
<since version="Gtk# 3.0" />
</Docs>
</Member>
<Member MemberName="GType">
<MemberSignature Language="C#" Value="public static GLib.GType GType { get; }" />
<MemberSignature Language="ILAsm" Value=".property valuetype GLib.GType GType" />
<MemberType>Property</MemberType>
<ReturnValue>
<ReturnType>GLib.GType</ReturnType>
</ReturnValue>
<Docs>
<summary>GType Property.</summary>
<value>The native <see cref="T:GLib.GType" /> value.</value>
<remarks>Returns the native <see cref="T:GLib.GType" /> value for <see cref="T:GLib.FilterInputStream" />.</remarks>
<since version="Gtk# 2.14" />
</Docs>
</Member>
</Members>
</Type>
|
{
"pile_set_name": "Github"
}
|
/*
* File: engine_common.h
* Author: cl
*
* Created on June 10, 2011, 8:38 PM
*/
#ifndef ENGINE_COMMON_H
#define ENGINE_COMMON_H
#define COLOR_TEXTURE_UNIT GL_TEXTURE0
#define COLOR_TEXTURE_UNIT_INDEX 0
#define SHADOW_TEXTURE_UNIT GL_TEXTURE1
#define SHADOW_TEXTURE_UNIT_INDEX 1
#define NORMAL_TEXTURE_UNIT GL_TEXTURE2
#define NORMAL_TEXTURE_UNIT_INDEX 2
#define RANDOM_TEXTURE_UNIT GL_TEXTURE3
#define RANDOM_TEXTURE_UNIT_INDEX 3
#define DISPLACEMENT_TEXTURE_UNIT GL_TEXTURE4
#define DISPLACEMENT_TEXTURE_UNIT_INDEX 4
#endif /* ENGINE_COMMON_H */
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.