text
stringlengths 2
99.9k
| meta
dict |
|---|---|
/*
* Copyright (C) 2014 The Guava Authors
*
* 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 com.google_voltpatches.common.util.concurrent;
import static com.google_voltpatches.common.base.Preconditions.checkNotNull;
import com.google_voltpatches.common.annotations.GwtCompatible;
import com.google_voltpatches.j2objc.annotations.WeakOuter;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.RunnableFuture;
import javax.annotation_voltpatches.Nullable;
/**
* A {@link RunnableFuture} that also implements the {@link ListenableFuture} interface.
*
* <p>This should be used in preference to {@link ListenableFutureTask} when possible for
* performance reasons.
*/
@GwtCompatible
class TrustedListenableFutureTask<V> extends AbstractFuture.TrustedFuture<V>
implements RunnableFuture<V> {
/**
* Creates a {@code ListenableFutureTask} that will upon running, execute the given
* {@code Callable}.
*
* @param callable the callable task
*/
static <V> TrustedListenableFutureTask<V> create(Callable<V> callable) {
return new TrustedListenableFutureTask<V>(callable);
}
/**
* Creates a {@code ListenableFutureTask} that will upon running, execute the given
* {@code Runnable}, and arrange that {@code get} will return the given result on successful
* completion.
*
* @param runnable the runnable task
* @param result the result to return on successful completion. If you don't need a particular
* result, consider using constructions of the form:
* {@code ListenableFuture<?> f = ListenableFutureTask.create(runnable,
* null)}
*/
static <V> TrustedListenableFutureTask<V> create(Runnable runnable, @Nullable V result) {
return new TrustedListenableFutureTask<V>(Executors.callable(runnable, result));
}
/*
* In certain circumstances, this field might theoretically not be visible to an afterDone() call
* triggered by cancel(). For details, see the comments on the fields of TimeoutFuture.
*/
private TrustedFutureInterruptibleTask task;
TrustedListenableFutureTask(Callable<V> callable) {
this.task = new TrustedFutureInterruptibleTask(callable);
}
@Override
public void run() {
TrustedFutureInterruptibleTask localTask = task;
if (localTask != null) {
localTask.run();
}
}
@Override
protected void afterDone() {
super.afterDone();
if (wasInterrupted()) {
TrustedFutureInterruptibleTask localTask = task;
if (localTask != null) {
localTask.interruptTask();
}
}
this.task = null;
}
@Override
public String toString() {
return super.toString() + " (delegate = " + task + ")";
}
@WeakOuter
private final class TrustedFutureInterruptibleTask extends InterruptibleTask {
private final Callable<V> callable;
TrustedFutureInterruptibleTask(Callable<V> callable) {
this.callable = checkNotNull(callable);
}
@Override
void runInterruptibly() {
// Ensure we haven't been cancelled or already run.
if (!isDone()) {
try {
set(callable.call());
} catch (Throwable t) {
setException(t);
}
}
}
@Override
boolean wasInterrupted() {
return TrustedListenableFutureTask.this.wasInterrupted();
}
@Override
public String toString() {
return callable.toString();
}
}
}
|
{
"pile_set_name": "Github"
}
|
*> \brief \b CCKGSV
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
* Definition:
* ===========
*
* SUBROUTINE CCKGSV( NM, MVAL, PVAL, NVAL, NMATS, ISEED, THRESH,
* NMAX, A, AF, B, BF, U, V, Q, ALPHA, BETA, R,
* IWORK, WORK, RWORK, NIN, NOUT, INFO )
*
* .. Scalar Arguments ..
* INTEGER INFO, NIN, NM, NMATS, NMAX, NOUT
* REAL THRESH
* ..
* .. Array Arguments ..
* INTEGER ISEED( 4 ), IWORK( * ), MVAL( * ), NVAL( * ),
* $ PVAL( * )
* REAL ALPHA( * ), BETA( * ), RWORK( * )
* COMPLEX A( * ), AF( * ), B( * ), BF( * ), Q( * ),
* $ R( * ), U( * ), V( * ), WORK( * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> CCKGSV tests CGGSVD:
*> the GSVD for M-by-N matrix A and P-by-N matrix B.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] NM
*> \verbatim
*> NM is INTEGER
*> The number of values of M contained in the vector MVAL.
*> \endverbatim
*>
*> \param[in] MVAL
*> \verbatim
*> MVAL is INTEGER array, dimension (NM)
*> The values of the matrix row dimension M.
*> \endverbatim
*>
*> \param[in] PVAL
*> \verbatim
*> PVAL is INTEGER array, dimension (NP)
*> The values of the matrix row dimension P.
*> \endverbatim
*>
*> \param[in] NVAL
*> \verbatim
*> NVAL is INTEGER array, dimension (NN)
*> The values of the matrix column dimension N.
*> \endverbatim
*>
*> \param[in] NMATS
*> \verbatim
*> NMATS is INTEGER
*> The number of matrix types to be tested for each combination
*> of matrix dimensions. If NMATS >= NTYPES (the maximum
*> number of matrix types), then all the different types are
*> generated for testing. If NMATS < NTYPES, another input line
*> is read to get the numbers of the matrix types to be used.
*> \endverbatim
*>
*> \param[in,out] ISEED
*> \verbatim
*> ISEED is INTEGER array, dimension (4)
*> On entry, the seed of the random number generator. The array
*> elements should be between 0 and 4095, otherwise they will be
*> reduced mod 4096, and ISEED(4) must be odd.
*> On exit, the next seed in the random number sequence after
*> all the test matrices have been generated.
*> \endverbatim
*>
*> \param[in] THRESH
*> \verbatim
*> THRESH is REAL
*> The threshold value for the test ratios. A result is
*> included in the output file if RESULT >= THRESH. To have
*> every test ratio printed, use THRESH = 0.
*> \endverbatim
*>
*> \param[in] NMAX
*> \verbatim
*> NMAX is INTEGER
*> The maximum value permitted for M or N, used in dimensioning
*> the work arrays.
*> \endverbatim
*>
*> \param[out] A
*> \verbatim
*> A is COMPLEX array, dimension (NMAX*NMAX)
*> \endverbatim
*>
*> \param[out] AF
*> \verbatim
*> AF is COMPLEX array, dimension (NMAX*NMAX)
*> \endverbatim
*>
*> \param[out] B
*> \verbatim
*> B is COMPLEX array, dimension (NMAX*NMAX)
*> \endverbatim
*>
*> \param[out] BF
*> \verbatim
*> BF is COMPLEX array, dimension (NMAX*NMAX)
*> \endverbatim
*>
*> \param[out] U
*> \verbatim
*> U is COMPLEX array, dimension (NMAX*NMAX)
*> \endverbatim
*>
*> \param[out] V
*> \verbatim
*> V is COMPLEX array, dimension (NMAX*NMAX)
*> \endverbatim
*>
*> \param[out] Q
*> \verbatim
*> Q is COMPLEX array, dimension (NMAX*NMAX)
*> \endverbatim
*>
*> \param[out] ALPHA
*> \verbatim
*> ALPHA is REAL array, dimension (NMAX)
*> \endverbatim
*>
*> \param[out] BETA
*> \verbatim
*> BETA is REAL array, dimension (NMAX)
*> \endverbatim
*>
*> \param[out] R
*> \verbatim
*> R is COMPLEX array, dimension (NMAX*NMAX)
*> \endverbatim
*>
*> \param[out] IWORK
*> \verbatim
*> IWORK is INTEGER array, dimension (NMAX)
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*> WORK is COMPLEX array, dimension (NMAX*NMAX)
*> \endverbatim
*>
*> \param[out] RWORK
*> \verbatim
*> RWORK is REAL array, dimension (NMAX)
*> \endverbatim
*>
*> \param[in] NIN
*> \verbatim
*> NIN is INTEGER
*> The unit number for input.
*> \endverbatim
*>
*> \param[in] NOUT
*> \verbatim
*> NOUT is INTEGER
*> The unit number for output.
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*> INFO is INTEGER
*> = 0 : successful exit
*> > 0 : If CLATMS returns an error code, the absolute value
*> of it is returned.
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date December 2016
*
*> \ingroup complex_eig
*
* =====================================================================
SUBROUTINE CCKGSV( NM, MVAL, PVAL, NVAL, NMATS, ISEED, THRESH,
$ NMAX, A, AF, B, BF, U, V, Q, ALPHA, BETA, R,
$ IWORK, WORK, RWORK, NIN, NOUT, INFO )
*
* -- LAPACK test routine (version 3.7.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* December 2016
*
* .. Scalar Arguments ..
INTEGER INFO, NIN, NM, NMATS, NMAX, NOUT
REAL THRESH
* ..
* .. Array Arguments ..
INTEGER ISEED( 4 ), IWORK( * ), MVAL( * ), NVAL( * ),
$ PVAL( * )
REAL ALPHA( * ), BETA( * ), RWORK( * )
COMPLEX A( * ), AF( * ), B( * ), BF( * ), Q( * ),
$ R( * ), U( * ), V( * ), WORK( * )
* ..
*
* =====================================================================
*
* .. Parameters ..
INTEGER NTESTS
PARAMETER ( NTESTS = 12 )
INTEGER NTYPES
PARAMETER ( NTYPES = 8 )
* ..
* .. Local Scalars ..
LOGICAL FIRSTT
CHARACTER DISTA, DISTB, TYPE
CHARACTER*3 PATH
INTEGER I, IINFO, IM, IMAT, KLA, KLB, KUA, KUB, LDA,
$ LDB, LDQ, LDR, LDU, LDV, LWORK, M, MODEA,
$ MODEB, N, NFAIL, NRUN, NT, P
REAL ANORM, BNORM, CNDNMA, CNDNMB
* ..
* .. Local Arrays ..
LOGICAL DOTYPE( NTYPES )
REAL RESULT( NTESTS )
* ..
* .. External Subroutines ..
EXTERNAL ALAHDG, ALAREQ, ALASUM, CLATMS, SLATB9, CGSVTS3
* ..
* .. Intrinsic Functions ..
INTRINSIC ABS
* ..
* .. Executable Statements ..
*
* Initialize constants and the random number seed.
*
PATH( 1: 3 ) = 'GSV'
INFO = 0
NRUN = 0
NFAIL = 0
FIRSTT = .TRUE.
CALL ALAREQ( PATH, NMATS, DOTYPE, NTYPES, NIN, NOUT )
LDA = NMAX
LDB = NMAX
LDU = NMAX
LDV = NMAX
LDQ = NMAX
LDR = NMAX
LWORK = NMAX*NMAX
*
* Do for each value of M in MVAL.
*
DO 30 IM = 1, NM
M = MVAL( IM )
P = PVAL( IM )
N = NVAL( IM )
*
DO 20 IMAT = 1, NTYPES
*
* Do the tests only if DOTYPE( IMAT ) is true.
*
IF( .NOT.DOTYPE( IMAT ) )
$ GO TO 20
*
* Set up parameters with SLATB9 and generate test
* matrices A and B with CLATMS.
*
CALL SLATB9( PATH, IMAT, M, P, N, TYPE, KLA, KUA, KLB, KUB,
$ ANORM, BNORM, MODEA, MODEB, CNDNMA, CNDNMB,
$ DISTA, DISTB )
*
* Generate M by N matrix A
*
CALL CLATMS( M, N, DISTA, ISEED, TYPE, RWORK, MODEA, CNDNMA,
$ ANORM, KLA, KUA, 'No packing', A, LDA, WORK,
$ IINFO )
IF( IINFO.NE.0 ) THEN
WRITE( NOUT, FMT = 9999 )IINFO
INFO = ABS( IINFO )
GO TO 20
END IF
*
* Generate P by N matrix B
*
CALL CLATMS( P, N, DISTB, ISEED, TYPE, RWORK, MODEB, CNDNMB,
$ BNORM, KLB, KUB, 'No packing', B, LDB, WORK,
$ IINFO )
IF( IINFO.NE.0 ) THEN
WRITE( NOUT, FMT = 9999 )IINFO
INFO = ABS( IINFO )
GO TO 20
END IF
*
NT = 6
*
CALL CGSVTS3( M, P, N, A, AF, LDA, B, BF, LDB, U, LDU, V,
$ LDV, Q, LDQ, ALPHA, BETA, R, LDR, IWORK, WORK,
$ LWORK, RWORK, RESULT )
*
* Print information about the tests that did not
* pass the threshold.
*
DO 10 I = 1, NT
IF( RESULT( I ).GE.THRESH ) THEN
IF( NFAIL.EQ.0 .AND. FIRSTT ) THEN
FIRSTT = .FALSE.
CALL ALAHDG( NOUT, PATH )
END IF
WRITE( NOUT, FMT = 9998 )M, P, N, IMAT, I,
$ RESULT( I )
NFAIL = NFAIL + 1
END IF
10 CONTINUE
NRUN = NRUN + NT
*
20 CONTINUE
30 CONTINUE
*
* Print a summary of the results.
*
CALL ALASUM( PATH, NOUT, NFAIL, NRUN, 0 )
*
9999 FORMAT( ' CLATMS in CCKGSV INFO = ', I5 )
9998 FORMAT( ' M=', I4, ' P=', I4, ', N=', I4, ', type ', I2,
$ ', test ', I2, ', ratio=', G13.6 )
RETURN
*
* End of CCKGSV
*
END
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>mattzanchelli.${PRODUCT_NAME:rfc1034identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIMainStoryboardFile</key>
<string>Main_iPhone</string>
<key>UIMainStoryboardFile~ipad</key>
<string>Main_iPad</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
|
{
"pile_set_name": "Github"
}
|
/*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Derived from IRIX <sys/SN/nmi.h>, Revision 1.5.
*
* Copyright (C) 1992 - 1997 Silicon Graphics, Inc.
*/
#ifndef __ASM_SN_NMI_H
#define __ASM_SN_NMI_H
#include <asm/sn/addrs.h>
/*
* The launch data structure resides at a fixed place in each node's memory
* and is used to communicate between the master processor and the slave
* processors.
*
* The master stores launch parameters in the launch structure
* corresponding to a target processor that is in a slave loop, then sends
* an interrupt to the slave processor. The slave calls the desired
* function, followed by an optional rendezvous function, then returns to
* the slave loop. The master does not wait for the slaves before
* returning.
*
* There is an array of launch structures, one per CPU on the node. One
* interrupt level is used per CPU.
*/
#define NMI_MAGIC 0x48414d4d455201
#define NMI_SIZEOF 0x40
#define NMI_OFF_MAGIC 0x00 /* Struct offsets for assembly */
#define NMI_OFF_FLAGS 0x08
#define NMI_OFF_CALL 0x10
#define NMI_OFF_CALLC 0x18
#define NMI_OFF_CALLPARM 0x20
#define NMI_OFF_GMASTER 0x28
/*
* The NMI routine is called only if the complement address is
* correct.
*
* Before control is transferred to a routine, the complement address
* is zeroed (invalidated) to prevent an accidental call from a spurious
* interrupt.
*
*/
#ifndef __ASSEMBLY__
typedef struct nmi_s {
volatile unsigned long magic; /* Magic number */
volatile unsigned long flags; /* Combination of flags above */
volatile void *call_addr; /* Routine for slave to call */
volatile void *call_addr_c; /* 1's complement of address */
volatile void *call_parm; /* Single parm passed to call */
volatile unsigned long gmaster; /* Flag true only on global master*/
} nmi_t;
#endif /* !__ASSEMBLY__ */
/* Following definitions are needed both in the prom & the kernel
* to identify the format of the nmi cpu register save area in the
* low memory on each node.
*/
#ifndef __ASSEMBLY__
struct reg_struct {
unsigned long gpr[32];
unsigned long sr;
unsigned long cause;
unsigned long epc;
unsigned long badva;
unsigned long error_epc;
unsigned long cache_err;
unsigned long nmi_sr;
};
#endif /* !__ASSEMBLY__ */
/* These are the assembly language offsets into the reg_struct structure */
#define R0_OFF 0x0
#define R1_OFF 0x8
#define R2_OFF 0x10
#define R3_OFF 0x18
#define R4_OFF 0x20
#define R5_OFF 0x28
#define R6_OFF 0x30
#define R7_OFF 0x38
#define R8_OFF 0x40
#define R9_OFF 0x48
#define R10_OFF 0x50
#define R11_OFF 0x58
#define R12_OFF 0x60
#define R13_OFF 0x68
#define R14_OFF 0x70
#define R15_OFF 0x78
#define R16_OFF 0x80
#define R17_OFF 0x88
#define R18_OFF 0x90
#define R19_OFF 0x98
#define R20_OFF 0xa0
#define R21_OFF 0xa8
#define R22_OFF 0xb0
#define R23_OFF 0xb8
#define R24_OFF 0xc0
#define R25_OFF 0xc8
#define R26_OFF 0xd0
#define R27_OFF 0xd8
#define R28_OFF 0xe0
#define R29_OFF 0xe8
#define R30_OFF 0xf0
#define R31_OFF 0xf8
#define SR_OFF 0x100
#define CAUSE_OFF 0x108
#define EPC_OFF 0x110
#define BADVA_OFF 0x118
#define ERROR_EPC_OFF 0x120
#define CACHE_ERR_OFF 0x128
#define NMISR_OFF 0x130
#endif /* __ASM_SN_NMI_H */
|
{
"pile_set_name": "Github"
}
|
# CVS $Revision: $ $Author: $ -- Fri Apr 1 08:57:13 2005 -- reformated by prettylst.pl v1.34 (build 455)
SOURCELONG:d20Talislanta SOURCESHORT:d20Tal SOURCEWEB:http://www.talislanta.com
# Orginal Entry By: Loyal
# Deity Name Domains Desciption of Deity/Title Holy Item Deity Weapon Source Page
Creator DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Aa DOMAINS:ALL DESC:the All-Seeing SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Aqus (ocean deity) DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Arial (spirit of the wind) DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Avar (Gold God) DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Beast-God DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Borean DOMAINS:ALL DESC:God of the North Wind SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Creator DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Danu (War God) DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Death DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Fortuna DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Jakar DOMAINS:ALL DESC:Lord of the Beasts SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Jamba DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Kagan DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Khadun (Death) DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Kron DOMAINS:ALL DESC:the Mighty SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Makk (spirit of the sea) DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Manik DOMAINS:ALL DESC:the Mad God SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Moorg (Mud God) DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Noman DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Paradoxy DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Satha (Dragon Goddess) DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Sham DOMAINS:ALL DESC:King of Lies SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Taryx DOMAINS:ALL DESC:Scavenger of Souls SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Terra (Great Mother) DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
The Duality DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Transcendency DOMAINS:ALL DESC:None SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
Zoriah DOMAINS:ALL DESC:Red God of War SYMBOL:None DEITYWEAP:ALL SOURCEPAGE:244
None DOMAINS:ANY DESC:For No Deity Choices FACT:Symbol|None DEITYWEAP:ANY GROUP:UNSELECTED
|
{
"pile_set_name": "Github"
}
|
//
// FileGenerator.h
// UrlProtector
//
// Created by Pichaya Srifar on 10/12/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface FileGenerator : NSObject
+ (void)genFileWithUrl:(NSString *)url;
+ (void)genFileWithUrl:(NSString *)url number:(NSString *)num;
@end
|
{
"pile_set_name": "Github"
}
|
lithtech
========
The engine code is from the apparent GPL release of the Jupiter Ex engine before Touchdown Entertainment disappeared. The GPL release was of the PC Enterprise Edition Build 69. Included were the game code and assets from NOLF2 and the game code from Tron 2.0. The code from the other games are from their respective public releases.
Goal
----
I found the GPL release of the Jupiter Engine and couldn't find anyone else who had really seemed to do anything with it. I wanted to see how hard it would be to adapt it into a modern, multi-platform source port. I also wanted to see if it would be possible to port the other Lithtech release game code to the GPL release of the engine. Both have turned out to be much more work than I originally envisioned. Even though the effort is initially *extremely* rough, I thought I would put it up on GitHub so that I have a backup of my work and that no matter how far (or not) I get, my work will not disappear with me.
Status
------
Currently the engine and NOLF2 game code will build.
There are a few reasons why I am implementing a new build system:
* All code releases were either using VC++ 6 or Visual Studio 2003 (VC++ 7.1). Neither type of project file converted that well in VS2010.
* Since the ultimate goal is a source port, I would like to be able to build the games on Linux and OS X as well. There was a homegrown converter for VC++ 7.1 project files to makefiles, but given then problems converting between versions of Visual Studio, I decided against it.
* I don't want to require someone to use Visual Studio on Windows. It should at least be buildable by MinGW as well (if not OpenWatcom too).
I can get NOLF2 running. Interestingly enough, a release build seems to run okay, but a debug build will trigger exceptions in the standard library. All the problem seem to have to do with Microsoft's secure CRT. Either things had slightly different semantics between compilers or certain iterator usages were technically not correct in the original code. I fixed maybe two of these. There are still probably another handful left. There also seems to be some differences in the NOLF2 retail data files and those supplied with the GPL release. I am not 100% certain of this, but I need to investigate more.
I also started an effort to port the Shogo source (originally from a really old version of the engine) to the engine in the GPL release. I have made a *ton* of changes, but it still doesn't compile completely. I decided to focus on getting a single tree build and debug version of NOLF2 running first.
TODO
----
* Have a way to build the engine with any or all of the game source code. (I think most of the infrastructure for this is in place.)
* Fix the secure standard library exceptions so that a Debug build under VS2010 will run.
* Port/adapt all the game code to run on the GPL engine. Each game was written to a different version of the engine. So, theoretically this is possible, but it could take a substantial amount of work.
* Remove the Windows dependencies. The engine is heavily oriented towards Windows (even though there is a bit of Linux code).
* Replace the usage of MFC with wxWidgets in the tools. (MFC and wxWidgets are close enough that it shouldn't be too painful.)
* Replace DirectInput and other Windows specific code with SDL.
* Create a new audio driver based on SDL and/or OpenAL.
* Create a new OpenGL renderer.
* Long term, it might be cool to bring back something similar to the renderer DLLs that Shogo used. In this version of the engine, the renderer is statically linked to the engine.
Games I want to support and the order to work on them
-----------------------------------------------------
1. No One Lives Forever 2: A Spy in H.A.R.M.'s Way
2. Tron 2.0 (if I can find a copy)
3. Shogo
4. The Operative: No One Lives Forever
5. F.E.A.R.
6. Blood II: The Chosen (if I can find a copy)
These are all the Lithtech I am aware of that had a public source release. If there are more out there, I want to eventually support them too.
|
{
"pile_set_name": "Github"
}
|
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V26.Segment;
using NHapi.Model.V26.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V26.Group
{
///<summary>
///Represents the RQA_I08_INSURANCE Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: IN1 (Insurance) </li>
///<li>1: IN2 (Insurance Additional Information) optional </li>
///<li>2: IN3 (Insurance Additional Information, Certification) optional </li>
///</ol>
///</summary>
[Serializable]
public class RQA_I08_INSURANCE : AbstractGroup {
///<summary>
/// Creates a new RQA_I08_INSURANCE Group.
///</summary>
public RQA_I08_INSURANCE(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(IN1), true, false);
this.add(typeof(IN2), false, false);
this.add(typeof(IN3), false, false);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating RQA_I08_INSURANCE - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns IN1 (Insurance) - creates it if necessary
///</summary>
public IN1 IN1 {
get{
IN1 ret = null;
try {
ret = (IN1)this.GetStructure("IN1");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns IN2 (Insurance Additional Information) - creates it if necessary
///</summary>
public IN2 IN2 {
get{
IN2 ret = null;
try {
ret = (IN2)this.GetStructure("IN2");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns IN3 (Insurance Additional Information, Certification) - creates it if necessary
///</summary>
public IN3 IN3 {
get{
IN3 ret = null;
try {
ret = (IN3)this.GetStructure("IN3");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
-- lock.test
--
-- execsql { DELETE FROM t4 }
DELETE FROM t4
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<CommandTable xmlns="http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- This is the file that defines the actual layout and type of the commands.
It is divided in different sections (e.g. command definition, command
placement, ...), with each defining a specific set of properties.
See the comment before each section for more details about how to
use it. -->
<!-- The VSCT compiler (the tool that translates this file into the binary
format that VisualStudio will consume) has the ability to run a preprocessor
on the vsct file; this preprocessor is (usually) the C++ preprocessor, so
it is possible to define includes and macros with the same syntax used
in C++ files. Using this ability of the compiler here, we include some files
defining some of the constants that we will use inside the file. -->
<!--This is the file that defines the IDs for all the commands exposed by VisualStudio. -->
<Extern href="stdidcmd.h" />
<!--This header contains the command ids for the menus provided by the shell. -->
<Extern href="vsshlids.h" />
<!--The Commands section is where we the commands, menus and menu groups are defined.
This section uses a Guid to identify the package that provides the command defined inside it. -->
<Commands package="guidCreate_HandleCommandsPkg">
<!-- Inside this section we have different sub-sections: one for the menus, another
for the menu groups, one for the buttons (the actual commands), one for the combos
and the last one for the bitmaps used. Each element is identified by a command id that
is a unique pair of guid and numeric identifier; the guid part of the identifier is usually
called "command set" and is used to group different command inside a logically related
group; your package should define its own command set in order to avoid collisions
with command ids defined by other packages. -->
<!-- In this section you can define new menu groups. A menu group is a container for
other menus or buttons (commands); from a visual point of view you can see the
group as the part of a menu contained between two lines. The parent of a group
must be a menu. -->
<Groups>
<Group guid="guidCreate_HandleCommandsCmdSet" id="MyMenuGroup" priority="0x0600">
<Parent guid="guidSHLMainMenu" id="IDM_VS_MENU_TOOLS" />
</Group>
</Groups>
<!--Buttons section. -->
<!--This section defines the elements the user can interact with, like a menu command or a button
or combo box in a toolbar. -->
<Buttons>
<!--To define a menu group you have to specify its ID, the parent menu and its display priority.
The command is visible and enabled by default. If you need to change the visibility, status, etc, you can use
the CommandFlag node.
You can add more than one CommandFlag node e.g.:
<CommandFlag>DefaultInvisible</CommandFlag>
<CommandFlag>DynamicVisibility</CommandFlag>
If you do not want an image next to your command, remove the Icon node or set it to <Icon guid="guidOfficeIcon" id="msotcidNoIcon" /> -->
</Buttons>
<!--The bitmaps section is used to define the bitmaps that are used for the commands.-->
<Bitmaps>
<!-- The bitmap id is defined in a way that is a little bit different from the others:
the declaration starts with a guid for the bitmap strip, then there is the resource id of the
bitmap strip containing the bitmaps and then there are the numeric ids of the elements used
inside a button definition. An important aspect of this declaration is that the element id
must be the actual index (1-based) of the bitmap inside the bitmap strip. -->
</Bitmaps>
</Commands>
<Symbols>
<!-- This is the package guid. -->
<GuidSymbol name="guidCreate_HandleCommandsPkg" value="{2813fc1f-3b2c-4bb5-a166-c35d38508171}" />
<!-- This is the guid used to group the menu commands together -->
<GuidSymbol name="guidCreate_HandleCommandsCmdSet" value="{a355053a-8a80-4142-98bc-9a7b0e14eee2}">
<IDSymbol name="MyMenuGroup" value="0x1020" />
<IDSymbol name="cmdidMyCommand" value="0x0100" />
</GuidSymbol>
</Symbols>
</CommandTable>
|
{
"pile_set_name": "Github"
}
|
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import {
AccessTokenRpcClientService,
RolesRpcClientService,
} from '../services';
import { GqlExecutionContext } from '@nestjs/graphql';
@Injectable()
export class PermissionsInterceptor implements NestInterceptor {
constructor(
public readonly access: AccessTokenRpcClientService,
public readonly role: RolesRpcClientService,
) {}
async intercept(
context: ExecutionContext,
next: CallHandler<any>,
): Promise<Observable<any>> {
const ctx = GqlExecutionContext.create(context).getContext();
console.log('Before...');
const now = Date.now();
return next
.handle()
.pipe(tap(() => console.log(`After... ${Date.now() - now}ms`)));
}
}
|
{
"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 arm,linux
package unix
import (
"unsafe"
)
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: int32(sec), Nsec: int32(nsec)}
}
func setTimeval(sec, usec int64) Timeval {
return Timeval{Sec: int32(sec), Usec: int32(usec)}
}
//sysnb pipe(p *[2]_C_int) (err error)
func Pipe(p []int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
// Try pipe2 first for Android O, then try pipe for kernel 2.6.23.
err = pipe2(&pp, 0)
if err == ENOSYS {
err = pipe(&pp)
}
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
func Pipe2(p []int, flags int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe2(&pp, flags)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
newoffset, errno := seek(fd, offset, whence)
if errno != 0 {
return 0, errno
}
return newoffset, nil
}
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error) = SYS_GETGROUPS32
//sysnb setgroups(n int, list *_Gid_t) (err error) = SYS_SETGROUPS32
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb socketpair(domain int, typ int, flags int, fd *[2]int32) (err error)
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
// 64-bit file system and 32-bit uid calls
// (16-bit uid calls are not always supported in newer kernels)
//sys dup2(oldfd int, newfd int) (err error)
//sysnb EpollCreate(size int) (fd int, err error)
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
//sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32
//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64
//sysnb Getegid() (egid int) = SYS_GETEGID32
//sysnb Geteuid() (euid int) = SYS_GETEUID32
//sysnb Getgid() (gid int) = SYS_GETGID32
//sysnb Getuid() (uid int) = SYS_GETUID32
//sysnb InotifyInit() (fd int, err error)
//sys Lchown(path string, uid int, gid int) (err error) = SYS_LCHOWN32
//sys Listen(s int, n int) (err error)
//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64
//sys Pause() (err error)
//sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT
//sys setfsgid(gid int) (prev int, err error) = SYS_SETFSGID32
//sys setfsuid(uid int) (prev int, err error) = SYS_SETFSUID32
//sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32
//sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32
//sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32
//sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32
//sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64
//sys Ustat(dev int, ubuf *Ustat_t) (err error)
//sys futimesat(dirfd int, path string, times *[2]Timeval) (err error)
//sysnb Gettimeofday(tv *Timeval) (err error)
func Time(t *Time_t) (Time_t, error) {
var tv Timeval
err := Gettimeofday(&tv)
if err != nil {
return 0, err
}
if t != nil {
*t = Time_t(tv.Sec)
}
return Time_t(tv.Sec), nil
}
func Utime(path string, buf *Utimbuf) error {
tv := []Timeval{
{Sec: buf.Actime},
{Sec: buf.Modtime},
}
return Utimes(path, tv)
}
//sys utimes(path string, times *[2]Timeval) (err error)
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
//sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64
//sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64
func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
_, _, e1 := Syscall6(SYS_ARM_FADVISE64_64, uintptr(fd), uintptr(advice), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
//sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error)
func Fstatfs(fd int, buf *Statfs_t) (err error) {
_, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
if e != 0 {
err = e
}
return
}
func Statfs(path string, buf *Statfs_t) (err error) {
pathp, err := BytePtrFromString(path)
if err != nil {
return err
}
_, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
if e != 0 {
err = e
}
return
}
func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
page := uintptr(offset / 4096)
if offset != int64(page)*4096 {
return 0, EINVAL
}
return mmap2(addr, length, prot, flags, fd, page)
}
type rlimit32 struct {
Cur uint32
Max uint32
}
//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_UGETRLIMIT
const rlimInf32 = ^uint32(0)
const rlimInf64 = ^uint64(0)
func Getrlimit(resource int, rlim *Rlimit) (err error) {
err = prlimit(0, resource, nil, rlim)
if err != ENOSYS {
return err
}
rl := rlimit32{}
err = getrlimit(resource, &rl)
if err != nil {
return
}
if rl.Cur == rlimInf32 {
rlim.Cur = rlimInf64
} else {
rlim.Cur = uint64(rl.Cur)
}
if rl.Max == rlimInf32 {
rlim.Max = rlimInf64
} else {
rlim.Max = uint64(rl.Max)
}
return
}
//sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT
func Setrlimit(resource int, rlim *Rlimit) (err error) {
err = prlimit(0, resource, rlim, nil)
if err != ENOSYS {
return err
}
rl := rlimit32{}
if rlim.Cur == rlimInf64 {
rl.Cur = rlimInf32
} else if rlim.Cur < uint64(rlimInf32) {
rl.Cur = uint32(rlim.Cur)
} else {
return EINVAL
}
if rlim.Max == rlimInf64 {
rl.Max = rlimInf32
} else if rlim.Max < uint64(rlimInf32) {
rl.Max = uint32(rlim.Max)
} else {
return EINVAL
}
return setrlimit(resource, &rl)
}
func (r *PtraceRegs) PC() uint64 { return uint64(r.Uregs[15]) }
func (r *PtraceRegs) SetPC(pc uint64) { r.Uregs[15] = uint32(pc) }
func (iov *Iovec) SetLen(length int) {
iov.Len = uint32(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 poll(fds *PollFd, nfds int, timeout int) (n int, err error)
func Poll(fds []PollFd, timeout int) (n int, err error) {
if len(fds) == 0 {
return poll(nil, 0, timeout)
}
return poll(&fds[0], len(fds), timeout)
}
//sys armSyncFileRange(fd int, flags int, off int64, n int64) (err error) = SYS_ARM_SYNC_FILE_RANGE
func SyncFileRange(fd int, off int64, n int64, flags int) error {
// The sync_file_range and arm_sync_file_range syscalls differ only in the
// order of their arguments.
return armSyncFileRange(fd, flags, off, n)
}
//sys kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error)
func KexecFileLoad(kernelFd int, initrdFd int, cmdline string, flags int) error {
cmdlineLen := len(cmdline)
if cmdlineLen > 0 {
// Account for the additional NULL byte added by
// BytePtrFromString in kexecFileLoad. The kexec_file_load
// syscall expects a NULL-terminated string.
cmdlineLen++
}
return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags)
}
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2019 Alachisoft
//
// 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
using Alachisoft.NCache.Runtime.Serialization;
using Alachisoft.NCache.Runtime.Serialization.IO;
namespace Alachisoft.NCache.Caching.Topologies.Clustered.Results
{
class WriteToStreamResult : ClusterOperationResult,ICompactSerializable
{
#region ICompactSerializable Members
void ICompactSerializable.Deserialize(CompactReader reader)
{
base.Deserialize(reader);
}
void ICompactSerializable.Serialize(CompactWriter writer)
{
base.Serialize(writer);
}
#endregion
}
}
|
{
"pile_set_name": "Github"
}
|
<#
.SYNOPSIS
Populate Maintenance Windows collections in ConfigMgr with devices sourced from Service Manager
.DESCRIPTION
This script will populate Maintenance Windows collections in ConfigMgr with devices that have a specific Maintenance Window set in Service Manager.
The Maintenance Window name defined on the server asset in Service Manager, needs to match the name of a Maintenance Window collection, otherwise the population
of that server asset will not occur.
This script also has logic to determining servers missing, including such that does not belong to a Maintenance Window collection. It does this by comparing
current members in the Maintenance Windows collection with members that should be added sourced from Service Manager.
To use this script, the Cireson.AssetManagement.HardwareAsset class needs to exist in Service Manager. Maintenance Window is determined from a ServiceWindow
property on the objects in Service Manager.
It's also required to have the SMLets module installed on the system where this script will be executed on.
.PARAMETER SiteServer
Site server where the SMS Provider is installed.
.PARAMETER SMDefaultComputer
Value for the Service Manager target server.
.PARAMETER MaintenanceWindowNamePrefix
Set a prefix used for filtering Maintenance Windows device collections.
.PARAMETER ShowProgress
Show a progressbar displaying the current operation.
.EXAMPLE
Populate devices from Service Manager in corresponding Maintenance Windows collections in ConfigMgr:
Invoke-CMPopulateMaintenanceWindowsDeviceMembers.ps1 -SiteServer CM01 -SMDefaultComputer SCSM01 -ShowProgress
.NOTES
FileName: Invoke-CMPopulateMaintenanceWindowsDeviceMembers.ps1
Author: Nickolaj Andersen
Contact: @NickolajA
Created: 2016-04-05
Updated: 2016-04-18
Version: 1.0.1
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[parameter(Mandatory=$true, HelpMessage="Site server where the SMS Provider is installed.")]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Connection -ComputerName $_ -Count 1 -Quiet})]
[string]$SiteServer,
[parameter(Mandatory=$true, HelpMessage="Value for the Service Manager target server.")]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Connection -ComputerName $_ -Count 1 -Quiet})]
[string]$SMDefaultComputer,
[parameter(Mandatory=$false, HelpMessage="Set a prefix used for filtering Maintenance Windows device collections.")]
[ValidateNotNullOrEmpty()]
[string]$MaintenanceWindowNamePrefix = "MWS -",
[parameter(Mandatory=$false, HelpMessage="Show a progressbar displaying the current operation.")]
[switch]$ShowProgress
)
Begin {
# Determine SiteCode from WMI
try {
Write-Verbose -Message "Determining Site Code for Site server: '$($SiteServer)'"
$SiteCodeObjects = Get-WmiObject -Namespace "root\SMS" -Class SMS_ProviderLocation -ComputerName $SiteServer -ErrorAction Stop
foreach ($SiteCodeObject in $SiteCodeObjects) {
if ($SiteCodeObject.ProviderForLocalSite -eq $true) {
$SiteCode = $SiteCodeObject.SiteCode
Write-Verbose -Message "Site Code: $($SiteCode)"
}
}
}
catch [System.UnauthorizedAccessException] {
Write-Warning -Message "Access denied" ; break
}
catch [System.Exception] {
Write-Warning -Message "Unable to determine Site Code" ; break
}
# Load ConfigMgr module
try {
$SiteDrive = $SiteCode + ":"
Import-Module -Name ConfigurationManager -ErrorAction Stop -Verbose:$false
}
catch [System.UnauthorizedAccessException] {
Write-Warning -Message "Access denied" ; break
}
catch [System.Exception] {
try {
Import-Module -Name (Join-Path -Path (($env:SMS_ADMIN_UI_PATH).Substring(0,$env:SMS_ADMIN_UI_PATH.Length-5)) -ChildPath "\ConfigurationManager.psd1") -Force -ErrorAction Stop -Verbose:$false
if ((Get-PSDrive -Name $SiteCode -ErrorAction SilentlyContinue | Measure-Object).Count -ne 1) {
New-PSDrive -Name $SiteCode -PSProvider "AdminUI.PS.Provider\CMSite" -Root $SiteServer -ErrorAction Stop -Verbose:$false | Out-Null
}
}
catch [System.UnauthorizedAccessException] {
Write-Warning -Message "Access denied" ; break
}
catch [System.Exception] {
Write-Warning -Message "$($_.Exception.Message). Line: $($_.InvocationInfo.ScriptLineNumber)" ; break
}
}
# Load SMLets
try {
Import-Module -Name SMLets -ErrorAction Stop -Verbose:$false
}
catch [System.UnauthorizedAccessException] {
Write-Warning -Message "Access denied" ; break
}
catch [System.Exception] {
Write-Warning -Message "$($_.Exception.Message). Line: $($_.InvocationInfo.ScriptLineNumber)" ; break
}
# Determine current location
$CurrentLocation = $PSScriptRoot
}
Process {
# Functions
function Write-EventLogEntry {
param(
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$LogName,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Source,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[int]$EventID,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidateSet("Information","Warning","Error")]
[string]$EntryType,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Message
)
# Create event log if not exist
if ([System.Diagnostics.EventLog]::Exists($LogName) -eq $false) {
try {
New-EventLog -LogName $LogName -Source $Source -ErrorAction Stop -Verbose:$false | Out-Null
}
catch [System.Exception] {
Write-Warning -Message "$($_.Exception.Message). Line: $($_.InvocationInfo.ScriptLineNumber)" ; break
}
}
# Write event log entry
try {
Write-EventLog -LogName $LogName -Source $Source -EntryType $EntryType -EventId $EventID -Message $Message -ErrorAction Stop
}
catch [System.Exception] {
Write-Warning -Message "$($_.Exception.Message). Line: $($_.InvocationInfo.ScriptLineNumber)" ; break
}
}
function New-DirectMembershipRule {
param(
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$RuleName,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$ResourceID
)
# Create a new SMS_CollectionRuleDirect instance and return it
$DirectMembershipRuleInstance = ([WmiClass]"\\$($SiteServer)\root\SMS\site_$($SiteCode):SMS_CollectionRuleDirect").CreateInstance()
$DirectMembershipRuleInstance.ResourceClassName = "SMS_R_System"
$DirectMembershipRuleInstance.ResourceID = $ResourceID
$DirectMembershipRuleInstance.RuleName = $RuleName
return $DirectMembershipRuleInstance
}
if ($PSBoundParameters["ShowProgress"]) {
$ProgressCount = 0
}
# Begin processing
Write-EventLogEntry -LogName "ConfigMgr Maintenance Windows" -Source "Maintenance Window Populator" -EventID 1000 -EntryType Information -Message "Initialize processing of server maintenance window memberships."
# Determine Maintenance Window names from ConfigMgr
try {
$MaintenanceWindowCollectionList = New-Object -TypeName System.Collections.ArrayList
$MaintenanceWindowCollections = Get-WmiObject -Namespace "root\SMS\site_$($SiteCode)" -Class SMS_Collection -ComputerName $SiteServer -Filter "Name like '$($MaintenanceWindowNamePrefix)%'" -ErrorAction Stop | Select-Object -Property Name, CollectionID
if ($MaintenanceWindowCollections -ne $null) {
$MaintenanceWindowCollectionList.AddRange(@($MaintenanceWindowCollections))
}
else {
Write-EventLogEntry -LogName "ConfigMgr Maintenance Windows" -Source "Maintenance Window Populator" -EventID 1001 -EntryType Warning -Message "Query for Maintenance Windows collections returned no results, aborting current operation."
}
}
catch [System.Exception] {
Write-Warning -Message "$($_.Exception.Message). Line: $($_.InvocationInfo.ScriptLineNumber)" ; break
}
# Process members for each Maintenance Window
if ($MaintenanceWindowCollectionList -ne $null) {
# Get the Cireson HardwareAsset class object
try {
$SCSMClass = Get-SCSMClass -Name Cireson.AssetManagement.HardwareAsset -ErrorAction Stop -Verbose:$false
}
catch [System.Exception] {
Write-Warning -Message "$($_.Exception.Message). Line: $($_.InvocationInfo.ScriptLineNumber)" ; break
}
# Get Maintenance Windows count
$MaintenanceWindowsCount = ($MaintenanceWindowCollectionList | Measure-Object).Count
foreach ($MaintenanceWindowCollection in $MaintenanceWindowCollectionList) {
# Execution start time
$StartTime = (Get-Date)
# Write event log information with beginning of current Maintenance Window
Write-EventLogEntry -LogName "ConfigMgr Maintenance Windows" -Source "Maintenance Window Populator" -EventID 1002 -EntryType Information -Message "Processing current Maintenance Window collection: $($MaintenanceWindowCollection.Name)"
# Show progressbar
if ($PSBoundParameters["ShowProgress"]) {
$ProgressCount++
Write-Progress -Activity "Processing Maintenance Window collections" -Id 1 -Status "$($ProgressCount) / $($MaintenanceWindowsCount)" -PercentComplete (($ProgressCount / $MaintenanceWindowsCount) * 100)
}
# Determine server objects to either be added or removed from Maintenance Window
$ServiceWindowID = Get-SCSMEnumeration -ErrorAction Stop -Verbose:$false | Where-Object { $_.DisplayName -eq $MaintenanceWindowCollection.Name } | Select-Object -ExpandProperty ID
if ($ServiceWindowID -ne $null) {
$SCSMServers = Get-SCSMObject -Class $SCSMClass -Filter "ServiceWindow -eq $($ServiceWindowID)" | Select-Object -ExpandProperty DisplayName
$ConfigMgrServers = Get-WmiObject -Namespace "root\SMS\site_$($SiteCode)" -Class SMS_FullCollectionMembership -ComputerName $SiteServer -Filter "CollectionID like '$($MaintenanceWindowCollection.CollectionID)'" | Select-Object -ExpandProperty Name
if ($SCSMServers -ne $null) {
# Compare servers in Maintenance Window with what's set in SCSM
$ComparedResults = Compare-Object -ReferenceObject $SCSMServers -DifferenceObject $ConfigMgrServers
if (($ComparedResults | Measure-Object).Count -ge 1) {
$AddToMaintenanceWindow = $ComparedResults | Where-Object { $_.SideIndicator -like "<=" } | Select-Object -ExpandProperty InputObject
$RemoveFromMaintenanceWindow = $ComparedResults | Where-Object { $_.SideIndicator -like "=>" } | Select-Object -ExpandProperty InputObject
# Get current Maintenance Window object
try {
$CurrentMaintenanceWindowCollection = Get-WmiObject -Namespace "root\SMS\site_$($SiteCode)" -Class SMS_Collection -ComputerName $SiteServer -Filter "Name like '$($MaintenanceWindowCollection.Name)'"
$CurrentMaintenanceWindowCollection.Get()
}
catch [System.Exception] {
Write-EventLogEntry -LogName "ConfigMgr Maintenance Windows" -Source "Maintenance Window Populator" -EventID 1003 -EntryType Warning -Message "Server '$($SCSMServer.DisplayName)' was not found in Configuration Manager, will not attemp to add resource to Maintenance Window collection."
}
# Add missing servers to Maintenance Window
if ($AddToMaintenanceWindow -ne $null) {
# Determine current CollectionRules objects and add them to an ArrayList
$DirectMembershipRulesList = New-Object -TypeName System.Collections.ArrayList
$DirectMembershipRulesList.AddRange(@($CurrentMaintenanceWindowCollection.CollectionRules))
# Handle each server that should be added to the Maintenance Window collection
foreach ($SCSMServer in $AddToMaintenanceWindow) {
try {
$DeviceResourceID = Get-WmiObject -Namespace "root\SMS\site_$($SiteCode)" -Class SMS_R_System -ComputerName $SiteServer -Filter "Name like '$($SCSMServer)'" -ErrorAction Stop | Select-Object -ExpandProperty ResourceID
$DirectMembershipRulesList.Add((New-DirectMembershipRule -RuleName $SCSMServer -ResourceID $DeviceResourceID)) | Out-Null
}
catch [System.Exception] {
Write-EventLogEntry -LogName "ConfigMgr Maintenance Windows" -Source "Maintenance Window Populator" -EventID 1004 -EntryType Warning -Message "Server '$($SCSMServer.DisplayName)' was not found in Configuration Manager, will not attemp to add resource to Maintenance Window collection."
}
}
# Update Maintenance Window collection object
$CurrentMaintenanceWindowCollection.CollectionRules = $DirectMembershipRulesList
$CurrentMaintenanceWindowCollection.Put() | Out-Null
Write-EventLogEntry -LogName "ConfigMgr Maintenance Windows" -Source "Maintenance Window Populator" -EventID 1005 -EntryType Information -Message "Successfully populated Maintenance Window '$($MaintenanceWindowCollection.Name)' with $(($AddToMaintenanceWindow | Measure-Object).Count) servers sourced from Service Manager."
}
# Remove servers from Maintenance Window
if ($RemoveFromMaintenanceWindow -ne $null) {
# Determine current CollectionRules objects and add them to an ArrayList
$DirectMembershipRulesList = New-Object -TypeName System.Collections.ArrayList
$DirectMembershipRulesList.AddRange(@($CurrentMaintenanceWindowCollection.CollectionRules))
# Handle each server that should be removed from the Maintenance Windows collection
foreach ($SCSMServer in $RemoveFromMaintenanceWindow) {
if ($SCSMServer -in $DirectMembershipRulesList.RuleName) {
$DirectMembershipRulesList.RemoveAt($DirectMembershipRulesList.RuleName.IndexOf($SCSMServer))
}
}
# Update Maintenance Window collection object
$CurrentMaintenanceWindowCollection.CollectionRules = $DirectMembershipRulesList
$CurrentMaintenanceWindowCollection.Put() | Out-Null
Write-EventLogEntry -LogName "ConfigMgr Maintenance Windows" -Source "Maintenance Window Populator" -EventID 1006 -EntryType Information -Message "Successfully removed $(($RemoveFromMaintenanceWindow | Measure-Object).Count) servers from Maintenance Window '$($MaintenanceWindowCollection.Name)'."
}
# Refresh
$CurrentMaintenanceWindowCollection.RequestRefresh() | Out-Null
}
else {
Write-EventLogEntry -LogName "ConfigMgr Maintenance Windows" -Source "Maintenance Window Populator" -EventID 1007 -EntryType Information -Message "Current Maintenance Window collection '$($MaintenanceWindowCollection.Name)' does not have any changes."
}
}
}
# End execution time
$ExecutionTime = (Get-Date) - $StartTime
# Write event log information for end of current Maintenance Window
Write-EventLogEntry -LogName "ConfigMgr Maintenance Windows" -Source "Maintenance Window Populator" -EventID 1008 -EntryType Information -Message "Finished processing current Maintenance Window collection: $($MaintenanceWindowCollection.Name). Operation took $($ExecutionTime.Minutes) min $($ExecutionTime.Seconds) sec."
}
}
}
End {
# Begin processing
Write-EventLogEntry -LogName "ConfigMgr Maintenance Windows" -Source "Maintenance Window Populator" -EventID 1009 -EntryType Information -Message "Successfully processed server maintenance window collection memberships."
# Set location to script root
Set-Location -Path $CurrentLocation
}
|
{
"pile_set_name": "Github"
}
|
package com.almasb.fxglgames.tictactoe;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.entity.EntityFactory;
import com.almasb.fxgl.entity.SpawnData;
import com.almasb.fxgl.entity.Spawns;
import com.almasb.fxgl.physics.BoundingShape;
import com.almasb.fxgl.physics.HitBox;
import javafx.scene.input.MouseEvent;
import static com.almasb.fxgl.dsl.FXGL.entityBuilder;
import static com.almasb.fxgl.dsl.FXGL.getAppWidth;
/**
* @author Almas Baimagambetov (almaslvl@gmail.com)
*/
public class TicTacToeFactory implements EntityFactory {
@Spawns("tile")
public Entity newTile(SpawnData data) {
var tile = entityBuilder()
.from(data)
.bbox(new HitBox(BoundingShape.box(getAppWidth() / 3, getAppWidth() / 3)))
.with(new TileViewComponent())
.build();
tile.getViewComponent().addEventHandler(MouseEvent.MOUSE_CLICKED, e -> FXGL.<TicTacToeApp>getAppCast().onUserMove(tile));
return tile;
}
}
|
{
"pile_set_name": "Github"
}
|
package tests.library
import testSupport.PipelineSpockTestBase
/**
* How to unit test some vars DSL like shared code
*/
class helloMessageTestSpec extends PipelineSpockTestBase {
def "test shared library code"() {
given:
def helloMessageBody = {
message = 'This is a test message'
}
when:
def script = loadScript('pipelineLibrary/vars/helloMessage.groovy')
script.call(helloMessageBody)
then:
printCallStack()
assertJobStatusSuccess()
}
}
|
{
"pile_set_name": "Github"
}
|
arithmetic integer primitives
primitiveBitAnd
<inline: false>
<var: 'integerArgumentValue' type: #usqInt>
<var: 'integerReceiverValue' type: #usqInt>
| integerArgumentValue integerReceiverValue |
"Note no short-cut for SmallIntegers. Either the inline interpreter bytecode or the JIT primitive will handle this case."
integerArgumentValue := self positiveMachineIntegerValueOf: self stackTop.
integerReceiverValue := self positiveMachineIntegerValueOf: (self stackValue: 1).
self successful ifTrue:
[self pop: 2 thenPush: (self positiveMachineIntegerFor: (integerArgumentValue bitAnd: integerReceiverValue))]
|
{
"pile_set_name": "Github"
}
|
0.0.3 / 2012-10-15
==================
* package: added `component` namespace (fixes #1)
0.0.2 / 2012-09-20
==================
* add code smell to `.merge()`
|
{
"pile_set_name": "Github"
}
|
# RUN: not llvm-mca -mtriple=x86_64-unknown-unknown -mcpu=btver2 %s 2>&1 | FileCheck %s
# LLVM-MCA-BEGIN foo
add %eax, %eax
# LLVM-MCA-BEGIN foo
add %eax, %eax
# CHECK: llvm-mca-markers-11.s:5:2: error: overlapping regions cannot have the same name
# CHECK-NEXT: # LLVM-MCA-BEGIN foo
# CHECK-NEXT: ^
# CHECK-NEXT: llvm-mca-markers-11.s:3:2: note: region foo was previously defined here
# CHECK-NEXT: # LLVM-MCA-BEGIN foo
# CHECK-NEXT: ^
|
{
"pile_set_name": "Github"
}
|
# $OpenBSD: Makefile.inc,v 1.11 2016/03/16 20:02:12 naddy Exp $
DIST_SUBDIR= xfce4
MAINTAINER?= Landry Breuil <landry@openbsd.org>
# those can't be defined in a MODULE
CONFIGURE_STYLE?=gnu
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
type = "1"
version = "2.0">
<Breakpoints>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "No"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "KVOTests/KVOTests.swift"
timestampString = "466153069.014465"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "27"
endingLineNumber = "27"
landmarkName = "tearDown()"
landmarkType = "5">
</BreakpointContent>
</BreakpointProxy>
</Breakpoints>
</Bucket>
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
*
* Copyright (c) 2017-2019 PX4 Development Team. 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 PX4 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.
*
****************************************************************************/
#include "MPL3115A2.hpp"
#include <px4_platform_common/getopt.h>
#include <px4_platform_common/module.h>
void
MPL3115A2::print_usage()
{
PRINT_MODULE_USAGE_NAME("mpl3115a2", "driver");
PRINT_MODULE_USAGE_SUBCATEGORY("baro");
PRINT_MODULE_USAGE_COMMAND("start");
PRINT_MODULE_USAGE_PARAMS_I2C_SPI_DRIVER(true, false);
PRINT_MODULE_USAGE_DEFAULT_COMMANDS();
}
I2CSPIDriverBase *MPL3115A2::instantiate(const BusCLIArguments &cli, const BusInstanceIterator &iterator,
int runtime_instance)
{
MPL3115A2 *dev = new MPL3115A2(iterator.configuredBusOption(), iterator.bus(), cli.bus_frequency);
if (dev == nullptr) {
return nullptr;
}
if (OK != dev->init()) {
delete dev;
return nullptr;
}
return dev;
}
extern "C" int mpl3115a2_main(int argc, char *argv[])
{
using ThisDriver = MPL3115A2;
BusCLIArguments cli{true, false};
cli.default_i2c_frequency = 400000;
const char *verb = cli.parseDefaultArguments(argc, argv);
if (!verb) {
ThisDriver::print_usage();
return -1;
}
BusInstanceIterator iterator(MODULE_NAME, cli, DRV_BARO_DEVTYPE_MPL3115A2);
if (!strcmp(verb, "start")) {
return ThisDriver::module_start(cli, iterator);
}
if (!strcmp(verb, "stop")) {
return ThisDriver::module_stop(iterator);
}
if (!strcmp(verb, "status")) {
return ThisDriver::module_status(iterator);
}
ThisDriver::print_usage();
return -1;
}
|
{
"pile_set_name": "Github"
}
|
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2020 iText Group NV
Authors: iText Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the iText software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping iText with a closed
source product.
For more information, please contact iText Software Corp. at this
address: sales@itextpdf.com
*/
package com.itextpdf.svg.renderers.impl;
import com.itextpdf.svg.renderers.SvgIntegrationTest;
import com.itextpdf.test.ITextTest;
import com.itextpdf.test.annotations.type.IntegrationTest;
import java.io.IOException;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.ExpectedException;
@Category(IntegrationTest.class)
public class NestedSvgTagSvgNodeRendererIntegrationTest extends SvgIntegrationTest {
@Rule
public ExpectedException junitExpectedException = ExpectedException.none();
private static final String SOURCE_FOLDER = "./src/test/resources/com/itextpdf/svg/renderers/impl/RootSvgNodeRendererTest/nested/";
private static final String DESTINATION_FOLDER = "./target/test/com/itextpdf/svg/renderers/impl/RootSvgNodeRendererTest/nested/";
@BeforeClass
public static void beforeClass() {
ITextTest.createDestinationFolder(DESTINATION_FOLDER);
}
@Test
public void singleNestedSvgTest() throws IOException, InterruptedException {
convertAndCompare(SOURCE_FOLDER, DESTINATION_FOLDER, "singleNested");
}
@Test
public void doubleNestedSvgTest() throws IOException, InterruptedException {
convertAndCompare(SOURCE_FOLDER, DESTINATION_FOLDER,"doubleNested");
}
@Test
public void twoNestedSvgTest() throws IOException, InterruptedException {
convertAndCompare(SOURCE_FOLDER, DESTINATION_FOLDER,"twoNested");
}
@Test
public void emptySvgTest() throws IOException, InterruptedException {
convertAndCompare(SOURCE_FOLDER, DESTINATION_FOLDER,"empty");
}
@Test
public void translatedSvgTest() throws IOException, InterruptedException {
convertAndCompareSinglePage(SOURCE_FOLDER, DESTINATION_FOLDER,"translated");
}
}
|
{
"pile_set_name": "Github"
}
|
// check-pass
#![feature(associated_type_defaults)]
// Having a cycle in assoc. type defaults is okay, as long as there's no impl
// that retains it.
trait Tr {
type A = Vec<Self::B>;
type B = Box<Self::A>;
fn f();
}
// An impl has to break the cycle to be accepted.
impl Tr for u8 {
type A = u8;
fn f() {
// Check that the type propagates as expected (seen from inside the impl)
let _: Self::A = 0u8;
let _: Self::B = Box::new(0u8);
}
}
impl Tr for String {
type B = ();
fn f() {
// Check that the type propagates as expected (seen from inside the impl)
let _: Self::A = Vec::<()>::new();
let _: Self::B = ();
}
}
impl Tr for () {
type A = Vec<()>;
type B = u8;
fn f() {
// Check that the type propagates as expected (seen from inside the impl)
let _: Self::A = Vec::<()>::new();
let _: Self::B = 0u8;
}
}
fn main() {
// Check that both impls now have the right types (seen from outside the impls)
let _: <u8 as Tr>::A = 0u8;
let _: <u8 as Tr>::B = Box::new(0u8);
let _: <String as Tr>::A = Vec::<()>::new();
let _: <String as Tr>::B = ();
let _: <() as Tr>::A = Vec::<()>::new();
let _: <() as Tr>::B = 0u8;
}
|
{
"pile_set_name": "Github"
}
|
from typing import Any, Optional, Text
from werkzeug.exceptions import HTTPException
def parse_converter_args(argstr): ...
def parse_rule(rule): ...
class RoutingException(Exception): ...
class RequestRedirect(HTTPException, RoutingException):
code: Any
new_url: Any
def __init__(self, new_url): ...
def get_response(self, environ): ...
class RequestSlash(RoutingException): ...
class RequestAliasRedirect(RoutingException):
matched_values: Any
def __init__(self, matched_values): ...
class BuildError(RoutingException, LookupError):
endpoint: Any
values: Any
method: Any
adapter: Optional[MapAdapter]
def __init__(self, endpoint, values, method, adapter: Optional[MapAdapter] = ...) -> None: ...
@property
def suggested(self) -> Optional[Rule]: ...
def closest_rule(self, adapter: Optional[MapAdapter]) -> Optional[Rule]: ...
class ValidationError(ValueError): ...
class RuleFactory:
def get_rules(self, map): ...
class Subdomain(RuleFactory):
subdomain: Any
rules: Any
def __init__(self, subdomain, rules): ...
def get_rules(self, map): ...
class Submount(RuleFactory):
path: Any
rules: Any
def __init__(self, path, rules): ...
def get_rules(self, map): ...
class EndpointPrefix(RuleFactory):
prefix: Any
rules: Any
def __init__(self, prefix, rules): ...
def get_rules(self, map): ...
class RuleTemplate:
rules: Any
def __init__(self, rules): ...
def __call__(self, *args, **kwargs): ...
class RuleTemplateFactory(RuleFactory):
rules: Any
context: Any
def __init__(self, rules, context): ...
def get_rules(self, map): ...
class Rule(RuleFactory):
rule: Any
is_leaf: Any
map: Any
strict_slashes: Any
subdomain: Any
host: Any
defaults: Any
build_only: Any
alias: Any
methods: Any
endpoint: Any
redirect_to: Any
arguments: Any
def __init__(
self,
string,
defaults: Optional[Any] = ...,
subdomain: Optional[Any] = ...,
methods: Optional[Any] = ...,
build_only: bool = ...,
endpoint: Optional[Any] = ...,
strict_slashes: Optional[Any] = ...,
redirect_to: Optional[Any] = ...,
alias: bool = ...,
host: Optional[Any] = ...,
): ...
def empty(self): ...
def get_empty_kwargs(self): ...
def get_rules(self, map): ...
def refresh(self): ...
def bind(self, map, rebind: bool = ...): ...
def get_converter(self, variable_name, converter_name, args, kwargs): ...
def compile(self): ...
def match(self, path, method: Optional[Any] = ...): ...
def build(self, values, append_unknown: bool = ...): ...
def provides_defaults_for(self, rule): ...
def suitable_for(self, values, method: Optional[Any] = ...): ...
def match_compare_key(self): ...
def build_compare_key(self): ...
def __eq__(self, other): ...
def __ne__(self, other): ...
class BaseConverter:
regex: Any
weight: Any
map: Any
def __init__(self, map): ...
def to_python(self, value): ...
def to_url(self, value): ...
class UnicodeConverter(BaseConverter):
regex: Any
def __init__(self, map, minlength: int = ..., maxlength: Optional[Any] = ..., length: Optional[Any] = ...): ...
class AnyConverter(BaseConverter):
regex: Any
def __init__(self, map, *items): ...
class PathConverter(BaseConverter):
regex: Any
weight: Any
class NumberConverter(BaseConverter):
weight: Any
fixed_digits: Any
min: Any
max: Any
def __init__(self, map, fixed_digits: int = ..., min: Optional[Any] = ..., max: Optional[Any] = ...): ...
def to_python(self, value): ...
def to_url(self, value): ...
class IntegerConverter(NumberConverter):
regex: Any
num_convert: Any
class FloatConverter(NumberConverter):
regex: Any
num_convert: Any
def __init__(self, map, min: Optional[Any] = ..., max: Optional[Any] = ...): ...
class UUIDConverter(BaseConverter):
regex: Any
def to_python(self, value): ...
def to_url(self, value): ...
DEFAULT_CONVERTERS: Any
class Map:
default_converters: Any
default_subdomain: Any
charset: Text
encoding_errors: Text
strict_slashes: Any
redirect_defaults: Any
host_matching: Any
converters: Any
sort_parameters: Any
sort_key: Any
def __init__(
self,
rules: Optional[Any] = ...,
default_subdomain: str = ...,
charset: Text = ...,
strict_slashes: bool = ...,
redirect_defaults: bool = ...,
converters: Optional[Any] = ...,
sort_parameters: bool = ...,
sort_key: Optional[Any] = ...,
encoding_errors: Text = ...,
host_matching: bool = ...,
): ...
def is_endpoint_expecting(self, endpoint, *arguments): ...
def iter_rules(self, endpoint: Optional[Any] = ...): ...
def add(self, rulefactory): ...
def bind(
self,
server_name,
script_name: Optional[Any] = ...,
subdomain: Optional[Any] = ...,
url_scheme: str = ...,
default_method: str = ...,
path_info: Optional[Any] = ...,
query_args: Optional[Any] = ...,
): ...
def bind_to_environ(self, environ, server_name: Optional[Any] = ..., subdomain: Optional[Any] = ...): ...
def update(self): ...
class MapAdapter:
map: Any
server_name: Any
script_name: Any
subdomain: Any
url_scheme: Any
path_info: Any
default_method: Any
query_args: Any
def __init__(
self, map, server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args: Optional[Any] = ...
): ...
def dispatch(
self, view_func, path_info: Optional[Any] = ..., method: Optional[Any] = ..., catch_http_exceptions: bool = ...
): ...
def match(
self,
path_info: Optional[Any] = ...,
method: Optional[Any] = ...,
return_rule: bool = ...,
query_args: Optional[Any] = ...,
): ...
def test(self, path_info: Optional[Any] = ..., method: Optional[Any] = ...): ...
def allowed_methods(self, path_info: Optional[Any] = ...): ...
def get_host(self, domain_part): ...
def get_default_redirect(self, rule, method, values, query_args): ...
def encode_query_args(self, query_args): ...
def make_redirect_url(self, path_info, query_args: Optional[Any] = ..., domain_part: Optional[Any] = ...): ...
def make_alias_redirect_url(self, path, endpoint, values, method, query_args): ...
def build(
self,
endpoint,
values: Optional[Any] = ...,
method: Optional[Any] = ...,
force_external: bool = ...,
append_unknown: bool = ...,
): ...
|
{
"pile_set_name": "Github"
}
|
/* Script for ld -r: link without relocation */
OUTPUT_FORMAT("elf32-avr","elf32-avr","elf32-avr")
OUTPUT_ARCH(avr:31)
MEMORY
{
text (rx) : ORIGIN = 0, LENGTH = 128K
data (rw!x) : ORIGIN = , LENGTH = 0xffa0
eeprom (rw!x) : ORIGIN = 0x810000, LENGTH = 64K
fuse (rw!x) : ORIGIN = 0x820000, LENGTH = 1K
lock (rw!x) : ORIGIN = 0x830000, LENGTH = 1K
signature (rw!x) : ORIGIN = 0x840000, LENGTH = 1K
}
SECTIONS
{
/* Read-only sections, merged into text segment: */
.hash 0 : { *(.hash) }
.dynsym 0 : { *(.dynsym) }
.dynstr 0 : { *(.dynstr) }
.gnu.version 0 : { *(.gnu.version) }
.gnu.version_d 0 : { *(.gnu.version_d) }
.gnu.version_r 0 : { *(.gnu.version_r) }
.rel.init 0 : { *(.rel.init) }
.rela.init 0 : { *(.rela.init) }
.rel.text 0 :
{
*(.rel.text)
}
.rela.text 0 :
{
*(.rela.text)
}
.rel.fini 0 : { *(.rel.fini) }
.rela.fini 0 : { *(.rela.fini) }
.rel.rodata 0 :
{
*(.rel.rodata)
}
.rela.rodata 0 :
{
*(.rela.rodata)
}
.rel.data 0 :
{
*(.rel.data)
}
.rela.data 0 :
{
*(.rela.data)
}
.rel.ctors 0 : { *(.rel.ctors) }
.rela.ctors 0 : { *(.rela.ctors) }
.rel.dtors 0 : { *(.rel.dtors) }
.rela.dtors 0 : { *(.rela.dtors) }
.rel.got 0 : { *(.rel.got) }
.rela.got 0 : { *(.rela.got) }
.rel.bss 0 : { *(.rel.bss) }
.rela.bss 0 : { *(.rela.bss) }
.rel.plt 0 : { *(.rel.plt) }
.rela.plt 0 : { *(.rela.plt) }
/* Internal text space or external memory. */
.text 0 :
{
*(.vectors)
KEEP(*(.vectors))
/* For data that needs to reside in the lower 64k of progmem. */
*(.progmem.gcc*)
*(.progmem*)
/* The jump trampolines for the 16-bit limited relocs will reside here. */
*(.trampolines)
*(.trampolines*)
/* For future tablejump instruction arrays for 3 byte pc devices.
We don't relax jump/call instructions within these sections. */
*(.jumptables)
*(.jumptables*)
/* For code that needs to reside in the lower 128k progmem. */
*(.lowtext)
*(.lowtext*)
KEEP(SORT(*)(.ctors))
KEEP(SORT(*)(.dtors))
/* From this point on, we don't bother about wether the insns are
below or above the 16 bits boundary. */
*(.init0) /* Start here after reset. */
KEEP (*(.init0))
*(.init1)
KEEP (*(.init1))
*(.init2) /* Clear __zero_reg__, set up stack pointer. */
KEEP (*(.init2))
*(.init3)
KEEP (*(.init3))
*(.init4) /* Initialize data and BSS. */
KEEP (*(.init4))
*(.init5)
KEEP (*(.init5))
*(.init6) /* C++ constructors. */
KEEP (*(.init6))
*(.init7)
KEEP (*(.init7))
*(.init8)
KEEP (*(.init8))
*(.init9) /* Call main(). */
KEEP (*(.init9))
*(.text)
*(.text.*)
*(.fini9) /* _exit() starts here. */
KEEP (*(.fini9))
*(.fini8)
KEEP (*(.fini8))
*(.fini7)
KEEP (*(.fini7))
*(.fini6) /* C++ destructors. */
KEEP (*(.fini6))
*(.fini5)
KEEP (*(.fini5))
*(.fini4)
KEEP (*(.fini4))
*(.fini3)
KEEP (*(.fini3))
*(.fini2)
KEEP (*(.fini2))
*(.fini1)
KEEP (*(.fini1))
*(.fini0) /* Infinite loop after program termination. */
KEEP (*(.fini0))
}
.data 0 :
{
*(.data)
*(.data*)
*(.rodata) /* We need to include .rodata here if gcc is used */
*(.rodata*) /* with -fdata-sections. */
*(.gnu.linkonce.d*)
}
.bss 0 :
{
*(.bss)
*(.bss*)
*(COMMON)
}
/* Global data not cleared after reset. */
.noinit 0:
{
*(.noinit*)
}
.eeprom 0:
{
*(.eeprom*)
}
.fuse 0:
{
KEEP(*(.fuse))
KEEP(*(.lfuse))
KEEP(*(.hfuse))
KEEP(*(.efuse))
}
.lock 0:
{
KEEP(*(.lock*))
}
.signature 0:
{
KEEP(*(.signature*))
}
/* Stabs debugging sections. */
.stab 0 : { *(.stab) }
.stabstr 0 : { *(.stabstr) }
.stab.excl 0 : { *(.stab.excl) }
.stab.exclstr 0 : { *(.stab.exclstr) }
.stab.index 0 : { *(.stab.index) }
.stab.indexstr 0 : { *(.stab.indexstr) }
.comment 0 : { *(.comment) }
/* DWARF debug sections.
Symbols in the DWARF debugging sections are relative to the beginning
of the section so we begin them at 0. */
/* DWARF 1 */
.debug 0 : { *(.debug) }
.line 0 : { *(.line) }
/* GNU DWARF 1 extensions */
.debug_srcinfo 0 : { *(.debug_srcinfo) }
.debug_sfnames 0 : { *(.debug_sfnames) }
/* DWARF 1.1 and DWARF 2 */
.debug_aranges 0 : { *(.debug_aranges) }
.debug_pubnames 0 : { *(.debug_pubnames) }
/* DWARF 2 */
.debug_info 0 : { *(.debug_info) *(.gnu.linkonce.wi.*) }
.debug_abbrev 0 : { *(.debug_abbrev) }
.debug_line 0 : { *(.debug_line) }
.debug_frame 0 : { *(.debug_frame) }
.debug_str 0 : { *(.debug_str) }
.debug_loc 0 : { *(.debug_loc) }
.debug_macinfo 0 : { *(.debug_macinfo) }
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 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.
*/
package org.smssecure.smssecure.contacts;
import org.smssecure.smssecure.R;
import org.smssecure.smssecure.recipients.RecipientsFormatter;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.text.Annotation;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
/**
* This adapter is used to filter contacts on both name and number.
*/
public class RecipientsAdapter extends ResourceCursorAdapter {
public static final int CONTACT_ID_INDEX = 1;
public static final int TYPE_INDEX = 2;
public static final int NUMBER_INDEX = 3;
public static final int LABEL_INDEX = 4;
public static final int NAME_INDEX = 5;
private final Context mContext;
private final ContentResolver mContentResolver;
private ContactAccessor mContactAccessor;
public RecipientsAdapter(Context context) {
super(context, R.layout.recipient_filter_item, null);
mContext = context;
mContentResolver = context.getContentResolver();
mContactAccessor = ContactAccessor.getInstance();
}
@Override
public final CharSequence convertToString(Cursor cursor) {
String name = cursor.getString(RecipientsAdapter.NAME_INDEX);
int type = cursor.getInt(RecipientsAdapter.TYPE_INDEX);
String number = cursor.getString(RecipientsAdapter.NUMBER_INDEX).trim();
String label = cursor.getString(RecipientsAdapter.LABEL_INDEX);
CharSequence displayLabel = mContactAccessor.phoneTypeToString(mContext, type, label);
if (number.length() == 0) {
return number;
}
if (name == null) {
name = "";
} else {
// Names with commas are the bane of the recipient editor's existence.
// We've worked around them by using spans, but there are edge cases
// where the spans get deleted. Furthermore, having commas in names
// can be confusing to the user since commas are used as separators
// between recipients. The best solution is to simply remove commas
// from names.
name = name.replace(", ", " ")
.replace(",", " "); // Make sure we leave a space between parts of names.
}
String nameAndNumber = RecipientsFormatter.formatNameAndNumber(name, number);
SpannableString out = new SpannableString(nameAndNumber);
int len = out.length();
if (!TextUtils.isEmpty(name)) {
out.setSpan(new Annotation("name", name), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
out.setSpan(new Annotation("name", number), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
String person_id = cursor.getString(RecipientsAdapter.CONTACT_ID_INDEX);
out.setSpan(new Annotation("person_id", person_id), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
out.setSpan(new Annotation("label", displayLabel.toString()), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
out.setSpan(new Annotation("number", number), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return out;
}
@Override
public final void bindView(View view, Context context, Cursor cursor) {
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(cursor.getString(NAME_INDEX));
TextView label = (TextView) view.findViewById(R.id.label);
int type = cursor.getInt(TYPE_INDEX);
label.setText(mContactAccessor.phoneTypeToString(mContext, type, cursor.getString(LABEL_INDEX)));
TextView number = (TextView) view.findViewById(R.id.number);
number.setText("(" + cursor.getString(NUMBER_INDEX) + ")");
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
return mContactAccessor.getCursorForRecipientFilter( constraint, mContentResolver );
}
/**
* Returns true if all the characters are meaningful as digits
* in a phone number -- letters, digits, and a few punctuation marks.
*/
public static boolean usefulAsDigits(CharSequence cons) {
int len = cons.length();
for (int i = 0; i < len; i++) {
char c = cons.charAt(i);
if ((c >= '0') && (c <= '9')) {
continue;
}
if ((c == ' ') || (c == '-') || (c == '(') || (c == ')') || (c == '.') || (c == '+')
|| (c == '#') || (c == '*')) {
continue;
}
if ((c >= 'A') && (c <= 'Z')) {
continue;
}
if ((c >= 'a') && (c <= 'z')) {
continue;
}
return false;
}
return true;
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (C) 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 xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="account_phone" msgid="4804592866198643905">"టాబ్లెట్-మాత్రమే, సమకాలీకరించబడని"</string>
<string name="composer_has_no_exportable_contact" msgid="441543908614399381">"ఎగుమతి చేయదగిన పరిచయాలు ఏవీ లేవు. మీరు మీ టాబ్లెట్లో పరిచయాలు కలిగి ఉన్నప్పటికీ, కొందరు డేటా ప్రదాతలు పరిచయాలను టాబ్లెట్ నుండి ఎగుమతి చేయడానికి అనుమతించకపోవచ్చు."</string>
</resources>
|
{
"pile_set_name": "Github"
}
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "AudioMixerPlatformAndroid.h"
#include "ModuleManager.h"
#include "AudioMixer.h"
#include "AudioMixerDevice.h"
#include "CoreGlobals.h"
#include "Misc/ConfigCacheIni.h"
#include "VorbisAudioInfo.h"
#include "ADPCMAudioInfo.h"
#include <SLES/OpenSLES.h>
#include "SLES/OpenSLES_Android.h"
DECLARE_LOG_CATEGORY_EXTERN(LogAudioMixerAndroid, Log, All);
DEFINE_LOG_CATEGORY(LogAudioMixerAndroid);
#define UNREAL_AUDIO_TEST_WHITE_NOISE 0
// Macro to check result for XAudio2 failure, get string version, log, and return false
#define OPENSLES_RETURN_ON_FAIL(Result) \
if (Result != SL_RESULT_SUCCESS) \
{ \
const TCHAR* ErrorString = GetErrorString(Result); \
AUDIO_PLATFORM_ERROR(ErrorString); \
return false; \
}
#define OPENSLES_CHECK_ON_FAIL(Result) \
if (Result != SL_RESULT_SUCCESS) \
{ \
const TCHAR* ErrorString = GetErrorString(Result); \
AUDIO_PLATFORM_ERROR(ErrorString); \
check(false); \
}
#define OPENSLES_LOG_ON_FAIL(Result) \
if (Result != SL_RESULT_SUCCESS) \
{ \
const TCHAR* ErrorString = GetErrorString(Result); \
AUDIO_PLATFORM_ERROR(ErrorString); \
}
extern int32 AndroidThunkCpp_GetMetaDataInt(const FString& Key);
namespace Audio
{
FMixerPlatformAndroid::FMixerPlatformAndroid()
: bSuspended(false)
, bInitialized(false)
, bInCallback(false)
{
}
FMixerPlatformAndroid::~FMixerPlatformAndroid()
{
if (bInitialized)
{
TeardownHardware();
}
}
const TCHAR* FMixerPlatformAndroid::GetErrorString(SLresult Result)
{
switch (Result)
{
case SL_RESULT_PRECONDITIONS_VIOLATED: return TEXT("SL_RESULT_PRECONDITIONS_VIOLATED");
case SL_RESULT_PARAMETER_INVALID: return TEXT("SL_RESULT_PARAMETER_INVALID");
case SL_RESULT_MEMORY_FAILURE: return TEXT("SL_RESULT_MEMORY_FAILURE");
case SL_RESULT_RESOURCE_ERROR: return TEXT("SL_RESULT_RESOURCE_ERROR");
case SL_RESULT_RESOURCE_LOST: return TEXT("SL_RESULT_RESOURCE_LOST");
case SL_RESULT_IO_ERROR: return TEXT("SL_RESULT_IO_ERROR");
case SL_RESULT_BUFFER_INSUFFICIENT: return TEXT("SL_RESULT_BUFFER_INSUFFICIENT");
case SL_RESULT_CONTENT_CORRUPTED: return TEXT("SL_RESULT_CONTENT_CORRUPTED");
case SL_RESULT_CONTENT_UNSUPPORTED: return TEXT("SL_RESULT_CONTENT_UNSUPPORTED");
case SL_RESULT_CONTENT_NOT_FOUND: return TEXT("SL_RESULT_CONTENT_NOT_FOUND");
case SL_RESULT_PERMISSION_DENIED: return TEXT("SL_RESULT_PERMISSION_DENIED");
case SL_RESULT_FEATURE_UNSUPPORTED: return TEXT("SL_RESULT_FEATURE_UNSUPPORTED");
case SL_RESULT_INTERNAL_ERROR: return TEXT("SL_RESULT_INTERNAL_ERROR");
case SL_RESULT_OPERATION_ABORTED: return TEXT("SL_RESULT_OPERATION_ABORTED");
case SL_RESULT_CONTROL_LOST: return TEXT("SL_RESULT_CONTROL_LOST");
default:
case SL_RESULT_UNKNOWN_ERROR: return TEXT("SL_RESULT_UNKNOWN_ERROR");
}
}
bool FMixerPlatformAndroid::InitializeHardware()
{
if (bInitialized)
{
return false;
}
SLresult Result;
SLEngineOption EngineOption[] = { {(SLuint32) SL_ENGINEOPTION_THREADSAFE, (SLuint32) SL_BOOLEAN_TRUE} };
// Create engine
Result = slCreateEngine( &SL_EngineObject, 1, EngineOption, 0, NULL, NULL);
OPENSLES_CHECK_ON_FAIL(Result);
// Realize the engine
Result = (*SL_EngineObject)->Realize(SL_EngineObject, SL_BOOLEAN_FALSE);
OPENSLES_CHECK_ON_FAIL(Result);
// get the engine interface, which is needed in order to create other objects
Result = (*SL_EngineObject)->GetInterface(SL_EngineObject, SL_IID_ENGINE, &SL_EngineEngine);
OPENSLES_CHECK_ON_FAIL(Result);
// create output mix
Result = (*SL_EngineEngine)->CreateOutputMix(SL_EngineEngine, &SL_OutputMixObject, 0, NULL, NULL );
OPENSLES_CHECK_ON_FAIL(Result);
// realize the output mix
Result = (*SL_OutputMixObject)->Realize(SL_OutputMixObject, SL_BOOLEAN_FALSE);
OPENSLES_CHECK_ON_FAIL(Result);
bInitialized = true;
return true;
}
bool FMixerPlatformAndroid::TeardownHardware()
{
if(!bInitialized)
{
return true;
}
// Teardown OpenSLES..
// Destroy the SLES objects in reverse order of creation:
if (SL_OutputMixObject)
{
(*SL_OutputMixObject)->Destroy(SL_OutputMixObject);
SL_OutputMixObject = nullptr;
}
if (SL_EngineObject)
{
(*SL_EngineObject)->Destroy(SL_EngineObject);
SL_EngineObject = nullptr;
SL_EngineEngine = nullptr;
}
bInitialized = false;
return true;
}
bool FMixerPlatformAndroid::IsInitialized() const
{
return bInitialized;
}
bool FMixerPlatformAndroid::GetNumOutputDevices(uint32& OutNumOutputDevices)
{
OutNumOutputDevices = 1;
return true;
}
bool FMixerPlatformAndroid::GetOutputDeviceInfo(const uint32 InDeviceIndex, FAudioPlatformDeviceInfo& OutInfo)
{
OutInfo.Name = TEXT("Android Audio Device");
OutInfo.DeviceId = 0;
OutInfo.bIsSystemDefault = true;
OutInfo.SampleRate = AndroidThunkCpp_GetMetaDataInt(TEXT("audiomanager.optimalSampleRate"));
OutInfo.NumChannels = 2; // Android doesn't support surround sound
OutInfo.Format = EAudioMixerStreamDataFormat::Int16;
OutInfo.OutputChannelArray.SetNum(2);
OutInfo.OutputChannelArray[0] = EAudioMixerChannel::FrontLeft;
OutInfo.OutputChannelArray[1] = EAudioMixerChannel::FrontRight;
return true;
}
bool FMixerPlatformAndroid::GetDefaultOutputDeviceIndex(uint32& OutDefaultDeviceIndex) const
{
OutDefaultDeviceIndex = 0;
return true;
}
bool FMixerPlatformAndroid::OpenAudioStream(const FAudioMixerOpenStreamParams& Params)
{
if (!bInitialized || AudioStreamInfo.StreamState != EAudioOutputStreamState::Closed)
{
return false;
}
OpenStreamParams = Params;
AudioStreamInfo.Reset();
AudioStreamInfo.OutputDeviceIndex = 0;
AudioStreamInfo.NumOutputFrames = OpenStreamParams.NumFrames;
AudioStreamInfo.NumBuffers = OpenStreamParams.NumBuffers;
AudioStreamInfo.AudioMixer = OpenStreamParams.AudioMixer;
if (!GetOutputDeviceInfo(AudioStreamInfo.OutputDeviceIndex, AudioStreamInfo.DeviceInfo))
{
return false;
}
SLresult Result;
// data info
SLDataLocator_AndroidSimpleBufferQueue LocationBuffer = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 1};
// PCM Info
SLDataFormat_PCM PCM_Format = {
SL_DATAFORMAT_PCM,
(SLuint32)AudioStreamInfo.DeviceInfo.NumChannels,
(SLuint32)(AudioStreamInfo.DeviceInfo.SampleRate * 1000), // NOTE: OpenSLES has sample rates specified in millihertz.
SL_PCMSAMPLEFORMAT_FIXED_16,
SL_PCMSAMPLEFORMAT_FIXED_16,
SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT,
SL_BYTEORDER_LITTLEENDIAN
};
SLDataSource SoundDataSource = { &LocationBuffer, &PCM_Format };
// configure audio sink
SLDataLocator_OutputMix OutputMix = { SL_DATALOCATOR_OUTPUTMIX, SL_OutputMixObject };
SLDataSink AudioSink = { &OutputMix, nullptr };
// create audio player
const SLInterfaceID InterfaceIds[] = {SL_IID_BUFFERQUEUE, SL_IID_VOLUME};
const SLboolean Req[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
Result = (*SL_EngineEngine)->CreateAudioPlayer(SL_EngineEngine, &SL_PlayerObject, &SoundDataSource, &AudioSink, sizeof(InterfaceIds) / sizeof(SLInterfaceID), InterfaceIds, Req);
OPENSLES_RETURN_ON_FAIL(Result);
// realize the player
Result = (*SL_PlayerObject)->Realize(SL_PlayerObject, SL_BOOLEAN_FALSE);
OPENSLES_RETURN_ON_FAIL(Result);
// get the play interface
Result = (*SL_PlayerObject)->GetInterface(SL_PlayerObject, SL_IID_PLAY, &SL_PlayerPlayInterface);
OPENSLES_RETURN_ON_FAIL(Result);
// buffer system
Result = (*SL_PlayerObject)->GetInterface(SL_PlayerObject, SL_IID_BUFFERQUEUE, &SL_PlayerBufferQueue);
OPENSLES_RETURN_ON_FAIL(Result);
Result = (*SL_PlayerBufferQueue)->RegisterCallback(SL_PlayerBufferQueue, OpenSLBufferQueueCallback, (void*)this);
OPENSLES_RETURN_ON_FAIL(Result);
AudioStreamInfo.StreamState = EAudioOutputStreamState::Open;
return true;
}
bool FMixerPlatformAndroid::CloseAudioStream()
{
if (!bInitialized || (AudioStreamInfo.StreamState != EAudioOutputStreamState::Open && AudioStreamInfo.StreamState != EAudioOutputStreamState::Stopped))
{
return false;
}
SLresult Result =(*SL_PlayerBufferQueue)->RegisterCallback(SL_PlayerBufferQueue, nullptr, nullptr);
(*SL_PlayerObject)->Destroy(SL_PlayerObject);
SL_PlayerObject = nullptr;
SL_PlayerPlayInterface = nullptr;
SL_PlayerBufferQueue = nullptr;
AudioStreamInfo.StreamState = EAudioOutputStreamState::Closed;
return true;
}
bool FMixerPlatformAndroid::StartAudioStream()
{
BeginGeneratingAudio();
// set the player's state to playing
SLresult Result = (*SL_PlayerPlayInterface)->SetPlayState(SL_PlayerPlayInterface, SL_PLAYSTATE_PLAYING);
OPENSLES_CHECK_ON_FAIL(Result);
return true;
}
bool FMixerPlatformAndroid::StopAudioStream()
{
if(!bInitialized || AudioStreamInfo.StreamState != EAudioOutputStreamState::Running)
{
return false;
}
if (AudioStreamInfo.StreamState != EAudioOutputStreamState::Stopped)
{
// set the player's state to stopped
SLresult Result = (*SL_PlayerPlayInterface)->SetPlayState(SL_PlayerPlayInterface, SL_PLAYSTATE_STOPPED);
OPENSLES_CHECK_ON_FAIL(Result);
if (AudioStreamInfo.StreamState == EAudioOutputStreamState::Running)
{
StopGeneratingAudio();
}
check(AudioStreamInfo.StreamState == EAudioOutputStreamState::Stopped);
}
return true;
}
FAudioPlatformDeviceInfo FMixerPlatformAndroid::GetPlatformDeviceInfo() const
{
return AudioStreamInfo.DeviceInfo;
}
FAudioPlatformSettings FMixerPlatformAndroid::GetPlatformSettings() const
{
FAudioPlatformSettings PlatformSettings = FAudioPlatformSettings::GetPlatformSettings(TEXT("/Script/AndroidRuntimeSettings.AndroidRuntimeSettings"));
// Override with platform-specific frames per buffer size
int32 MinFramesPerBuffer = AndroidThunkCpp_GetMetaDataInt(TEXT("audiomanager.framesPerBuffer"));
int32 BufferSizeToUse = MinFramesPerBuffer;
while (BufferSizeToUse < PlatformSettings.CallbackBufferFrameSize)
{
BufferSizeToUse += MinFramesPerBuffer;
}
PlatformSettings.CallbackBufferFrameSize = BufferSizeToUse;
return PlatformSettings;
}
static bool bSuspended = false;
void FMixerPlatformAndroid::SuspendContext()
{
if (!bSuspended)
{
bSuspended = true;
// set the player's state to paused
SLresult result = (*SL_PlayerPlayInterface)->SetPlayState(SL_PlayerPlayInterface, SL_PLAYSTATE_PAUSED);
check(SL_RESULT_SUCCESS == result);
}
}
void FMixerPlatformAndroid::ResumeContext()
{
// set the player's state to paused
if (bSuspended)
{
bSuspended = false;
SLresult result = (*SL_PlayerPlayInterface)->SetPlayState(SL_PlayerPlayInterface, SL_PLAYSTATE_PLAYING);
check(SL_RESULT_SUCCESS == result);
}
}
void FMixerPlatformAndroid::SubmitBuffer(const uint8* Buffer)
{
SLresult Result = (*SL_PlayerBufferQueue)->Enqueue(SL_PlayerBufferQueue, Buffer, AudioStreamInfo.NumOutputFrames * AudioStreamInfo.DeviceInfo.NumChannels * sizeof(int16));
OPENSLES_LOG_ON_FAIL(Result);
}
FName FMixerPlatformAndroid::GetRuntimeFormat(USoundWave* InSoundWave)
{
#if WITH_OGGVORBIS
static FName NAME_OGG(TEXT("OGG"));
if (InSoundWave->HasCompressedData(NAME_OGG))
{
return NAME_OGG;
}
#endif
static FName NAME_ADPCM(TEXT("ADPCM"));
return NAME_ADPCM;
}
bool FMixerPlatformAndroid::HasCompressedAudioInfoClass(USoundWave* InSoundWave)
{
#if WITH_OGGVORBIS
if (InSoundWave->bStreaming)
{
return true;
}
static FName NAME_OGG(TEXT("OGG"));
if (InSoundWave->HasCompressedData(NAME_OGG))
{
return true;
}
#endif
if (InSoundWave->bStreaming)
{
return true;
}
static FName NAME_ADPCM(TEXT("ADPCM"));
if (InSoundWave->HasCompressedData(NAME_ADPCM))
{
return true;
}
return false;
}
ICompressedAudioInfo* FMixerPlatformAndroid::CreateCompressedAudioInfo(USoundWave* InSoundWave)
{
#if WITH_OGGVORBIS
static FName NAME_OGG(TEXT("OGG"));
if (InSoundWave->bStreaming || InSoundWave->HasCompressedData(NAME_OGG))
{
return new FVorbisAudioInfo();
}
#endif
static FName NAME_ADPCM(TEXT("ADPCM"));
if (InSoundWave->bStreaming || InSoundWave->HasCompressedData(NAME_ADPCM))
{
return new FADPCMAudioInfo();
}
return nullptr;
}
FString FMixerPlatformAndroid::GetDefaultDeviceName()
{
return FString();
}
void FMixerPlatformAndroid::OpenSLBufferQueueCallback(SLAndroidSimpleBufferQueueItf InQueueInterface, void* pContext)
{
FMixerPlatformAndroid* MixerPlatformAndroid = (FMixerPlatformAndroid*)pContext;
if (MixerPlatformAndroid != nullptr)
{
MixerPlatformAndroid->ReadNextBuffer();
}
}
}
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Configuration;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text;
namespace Microsoft.WCF.Documentation
{
class HostApplication
{
static void Main()
{
HostApplication app = new HostApplication();
app.Run();
}
private void Run()
{
// Create a ServiceHost for the service type and use the base address from configuration.
using (ServiceHost serviceHost = new ServiceHost(typeof(SampleService)))
{
try
{
// Open the ServiceHostBase to create listeners and start listening for messages.
serviceHost.Open();
// The service can now be accessed.
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
serviceHost.Close();
}
catch (TimeoutException timeProblem)
{
Console.WriteLine("The service operation timed out. " + timeProblem.Message);
Console.ReadLine();
serviceHost.Abort();
}
catch (CommunicationException commProblem)
{
Console.WriteLine("There was a communication problem. " + commProblem.Message);
Console.ReadLine();
serviceHost.Abort();
}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
return array(
'grabber' => array(
'%.*%' => array(
'test_url' => 'http://science.slashdot.org/story/15/04/20/0528253/pull-top-can-tabs-at-50-reach-historic-archaeological-status',
'body' => array(
'//article/div[@class="body"] | //article[@class="layout-article"]/div[@class="elips"]', ),
'strip' => array(),
),
),
);
|
{
"pile_set_name": "Github"
}
|
version 1.0;
ns junos = "http://xml.juniper.net/junos/*/junos";
ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";
ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";
ns ext = "http://xmlsoft.org/XSLT/namespace";
ns exsl = "http://exslt.org/math";
ns func extension = "http://exslt.org/functions";
ns dyn extension = "http://exslt.org/dynamic";
import "../import/junos.xsl";
import "../import/lib-util.slax";
/*
* This script maintains common config groups among a set of routers.
* Each group to be shared contains a list of targets to which the
* contents of the group a copied. The contents of this group on
* remote machines are completely replaced by the incoming data.
*
* The script detects which addresses are assigned to the local device
* and will skip such addresses, so the local device can be listed among
* the targets, allowing the config to be updated and shared from any
* device on the list.
*
* The share-data script can be invoked in two ways. With no
* arguments, the script looks for any group containing an
* apply-macro named "share-data". The contents of the macro are
* a list of targets to which the shared data should be copied.
*
* In addition, the share-data script can be invoked with a set of
* command line arguments to detail the exact data (by config group
* using the "group" parameter) and targets to which that data should
* be copied (using the "target" parameter with a space-separated
* list of targets).
*
* The "database" argument can tell the script to use the "candidate"
* configuration database, which allows uncommitted data to be shared.
* The default behavior is to use the committed configuration.
*
* "transform": Each target listed in the "share-data" macro can
* contain (as its value (in the name/value pairing)) the name of
* a func:function that can be called with the contents of the config
* group to be shared, and returns the data to be shipped to that
* target. This allows all manner of transformations to be implemented
* inside his framework.
*/
/*
* Future work: It would be great to have a "generation" number that
* is monotonically increasing, and can be used to avoid clobbering
* data when the config has been changed and not shared.
*/
var $arguments = {
<argument> {
<name> "group";
<description> "Name of config group to share";
}
<argument> {
<name> "database";
<description> "Database for configuration ('candidate' or 'committed')";
}
<argument> {
<name> "target";
<description> "Target for transfer (one or space-delimited list)";
}
}
param $group;
param $database = "candidate";
param $target;
param $debug;
param $macro = "share-data";
param $transform;
match / {
/*
* Standard op script fodder; make the top-level element all op
* scripts need (op-script-results), and an element to keep
* our output together (out). This script really only makes
* <output> data, so this isn't needed, but can still be useful
* for dumping data. Well, okay, I tend to use jcs:dump() for
* dumping data, so the script will really not make any interesting
* output, but we still follow the JUNOScript rules and emit these
* tags to play by the rules.
*/
<op-script-results> {
<out> {
call main;
}
}
}
/**
* main: start by getting the configuration for all groups. Then
* call share to either the one group chosen by command line argument'
* or for all groups with the share-data macro.
*/
template main {
var $rpc = {
<get-configuration database=$database> {
<configuration> {
<groups> {
if ($group) {
<name> $group;
}
}
}
}
}
var $config = jcs:invoke($rpc);
if ($debug) {
call jcs:dump($name = "config", $out = $config);
}
if ($config/xnm:error) {
<xsl:message terminate="yes"> {
expr "error: " _ $config/xnm:error/message;
}
}
var $rpc2 = <get-configuration database=$database> {
<configuration> {
<apply-groups>;
}
}
var $apply = jcs:invoke($rpc2);
if ($debug) {
call jcs:dump($name = "apply", $out = $apply);
}
/*
* Check to see if we need to add this group locally
*/
if ($group) {
call check-apply($apply, $names = $config/groups);
if ($config/groups/name) {
call share($config = $config/groups, $group);
} else {
expr jcs:output("no configuration to transfer");
}
} else {
var $names = $config/groups[apply-macro[name == $macro]
&& not(@inactive)];
if ($names) {
call check-apply($apply, $names);
for-each ($config/groups[apply-macro[name == $macro]]) {
call share($config = ., $group = name);
}
} else {
expr jcs:output("no share-data configuration groups found");
}
}
}
/*
* Determine whether the group has been applied locally
*/
template check-apply ($apply, $names)
{
var $missing := {
for-each ($names/name) {
var $this = .;
if (not(../@inactive) && not($apply/apply-groups[. == $this])) {
<missing> $this;
}
}
}
if (count($missing/node()) > 0) {
expr jcs:output("The following group(s) are not applied locally:");
for-each ($missing) {
expr jcs:output(" ", .);
}
var $prompt = "Apply locally now?";
var $response := { call promptyesno($prompt); }
if ($response == "yes") {
var $configuration := <configuration> {
for-each ($missing) {
<apply-groups> .;
}
}
if ($debug) {
call jcs:dump($name = "new", $out = $configuration);
}
var $conn = jcs:open();
if ($conn) {
var $results := {
call jcs:load-configuration($connection = $conn,
$configuration,
$action = "merge");
}
if ($results/node()) {
call jcs:dump($name = "results", $out = $results);
} else {
expr jcs:output(" successfully committed locally");
}
expr jcs:close($conn);
}
}
}
}
/*
* Share the group's config. Calls transfer() to do the real work. If
* a specific set of targets was given on the command line, use those.
* Otherwise use the targets given in the macro, avoiding those which
* belong to the current device.
*
* The logic to decide if the address is our's (local or (direct and
* next-hop is lo0.0) was confirmed by rpd-hackers, so hopefully it's
* valid for all cases. If not, please let me know.
*/
template share ($config, $group)
{
expr jcs:output("sharing group '", $group, "'");
if ($debug > 1) {
call jcs:dump($name = "config", $out = $config);
}
if ($target) {
var $targets = jcs:split(" ", $target);
for-each ($targets) {
call transfer($config, $target = ., $transform);
}
} else {
var $mac = $config/apply-macro[name == $macro];
for-each ($mac/data/name) {
var $target = .;
expr jcs:output(" target: ", $target);
var $rpc = <get-route-information> {
<destination> $target;
}
var $res = jcs:invoke($rpc);
var $rt = $res/route-table/rt/rt-entry[current-active];
var $proto = $rt/protocol-name;
if ($res/xnm:error) {
expr jcs:output(" error: ", $res/xnm:error/message);
} else if ($proto == "Local"
|| ($proto == "Direct" && $rt/nh/via == "lo0.0")) {
expr jcs:output(" skipping local address");
} else {
call transfer($config, $target, $transform = ../value);
}
}
}
}
/*
* Transfer (load replace and commit) the configuration on the
* remote target.
*/
template transfer ($config, $target, $transform)
{
/*
* If there is a transformation defined, we call it, passing in
* the config and getting back the post-transform config.
*/
var $trans-config := {
if ($transform) {
var $tpath = $transform _ "($config)";
expr jcs:output(" transforming ", $target);
var $new = dyn:evaluate($tpath);
copy-of $new;
}
}
expr jcs:output(" connecting to ", $target);
var $conn = jcs:open($target);
if ($conn) {
expr jcs:output(" connected; transfering group ", $config/name);
var $configuration = <configuration> {
<groups replace="replace"> {
if ($transform) {
<name> $config/name;
copy-of $trans-config;
} else {
copy-of $config/node();
}
}
<apply-groups> $config/name;
}
var $results := {
call jcs:load-configuration($connection = $conn, $configuration,
$action = "replace");
}
if ($results/node()) {
call jcs:dump($name = "results", $out = $results);
} else {
expr jcs:output(" successfully committed on ", $target);
}
expr jcs:close($conn);
} else {
expr jcs:output(" failed to connect");
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2018 Google LLC.
//
// 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 com.google.firestore
import org.junit.Test
import org.junit.Before
import org.junit.After
import org.junit.Assert
import org.hamcrest.CoreMatchers.containsString
import java.io.ByteArrayOutputStream
import java.io.PrintStream
internal class FirestoreTest {
private val outContent = ByteArrayOutputStream()
private val originalOut = System.out!!
private val collection = "test-collection"
@Before
fun `setup streams`() {
System.setOut(PrintStream(outContent))
}
@After
fun `restore streams`() {
System.setOut(originalOut)
}
@Test
fun `fetch non-existing`() {
main(collection, "non-existing")
Assert.assertEquals("non-existing: not found\n", outContent.toString())
}
@Test
fun `set and fetch value`() {
// Generate a key based on the current time (so it shouldn't exist)
val key = System.currentTimeMillis().toString()
// ensure key doesn't currently exist
main(collection, key)
Assert.assertEquals("$key: not found\n", outContent.toString())
// set the key to "some value"
main(collection, key, "some value")
Assert.assertThat(outContent.toString(), containsString("Updated collection: "))
// ensure key exists now (and reset the output stream)
outContent.reset()
main(collection, key)
Assert.assertEquals("$key: some value\n", outContent.toString())
}
@Test(expected = Exception::class)
fun `too few arguments`() {
main()
}
@Test(expected = Exception::class)
fun `too many arguments`() {
main("arg1", "arg2", "arg3", "arg4")
}
}
|
{
"pile_set_name": "Github"
}
|
// List Icons
// -------------------------
.#{$fa-css-prefix}-ul {
padding-left: 0;
margin-left: $fa-li-width;
list-style-type: none;
> li { position: relative; }
}
.#{$fa-css-prefix}-li {
position: absolute;
left: -$fa-li-width;
width: $fa-li-width;
top: (2em / 14);
text-align: center;
&.#{$fa-css-prefix}-lg {
left: -$fa-li-width + (4em / 14);
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* File...........: linux/drivers/s390/block/dasd_int.h
* Author(s)......: Holger Smolinski <Holger.Smolinski@de.ibm.com>
* Horst Hummel <Horst.Hummel@de.ibm.com>
* Martin Schwidefsky <schwidefsky@de.ibm.com>
* Bugreports.to..: <Linux390@de.ibm.com>
* Copyright IBM Corp. 1999, 2009
*/
#ifndef DASD_INT_H
#define DASD_INT_H
#ifdef __KERNEL__
/* we keep old device allocation scheme; IOW, minors are still in 0..255 */
#define DASD_PER_MAJOR (1U << (MINORBITS - DASD_PARTN_BITS))
#define DASD_PARTN_MASK ((1 << DASD_PARTN_BITS) - 1)
/*
* States a dasd device can have:
* new: the dasd_device structure is allocated.
* known: the discipline for the device is identified.
* basic: the device can do basic i/o.
* unfmt: the device could not be analyzed (format is unknown).
* ready: partition detection is done and the device is can do block io.
* online: the device accepts requests from the block device queue.
*
* Things to do for startup state transitions:
* new -> known: find discipline for the device and create devfs entries.
* known -> basic: request irq line for the device.
* basic -> ready: do the initial analysis, e.g. format detection,
* do block device setup and detect partitions.
* ready -> online: schedule the device tasklet.
* Things to do for shutdown state transitions:
* online -> ready: just set the new device state.
* ready -> basic: flush requests from the block device layer, clear
* partition information and reset format information.
* basic -> known: terminate all requests and free irq.
* known -> new: remove devfs entries and forget discipline.
*/
#define DASD_STATE_NEW 0
#define DASD_STATE_KNOWN 1
#define DASD_STATE_BASIC 2
#define DASD_STATE_UNFMT 3
#define DASD_STATE_READY 4
#define DASD_STATE_ONLINE 5
#include <linux/module.h>
#include <linux/wait.h>
#include <linux/blkdev.h>
#include <linux/genhd.h>
#include <linux/hdreg.h>
#include <linux/interrupt.h>
#include <linux/log2.h>
#include <asm/ccwdev.h>
#include <linux/workqueue.h>
#include <asm/debug.h>
#include <asm/dasd.h>
#include <asm/idals.h>
/* DASD discipline magic */
#define DASD_ECKD_MAGIC 0xC5C3D2C4
#define DASD_DIAG_MAGIC 0xC4C9C1C7
#define DASD_FBA_MAGIC 0xC6C2C140
/*
* SECTION: Type definitions
*/
struct dasd_device;
struct dasd_block;
/* BIT DEFINITIONS FOR SENSE DATA */
#define DASD_SENSE_BIT_0 0x80
#define DASD_SENSE_BIT_1 0x40
#define DASD_SENSE_BIT_2 0x20
#define DASD_SENSE_BIT_3 0x10
/* BIT DEFINITIONS FOR SIM SENSE */
#define DASD_SIM_SENSE 0x0F
#define DASD_SIM_MSG_TO_OP 0x03
#define DASD_SIM_LOG 0x0C
/*
* SECTION: MACROs for klogd and s390 debug feature (dbf)
*/
#define DBF_DEV_EVENT(d_level, d_device, d_str, d_data...) \
do { \
debug_sprintf_event(d_device->debug_area, \
d_level, \
d_str "\n", \
d_data); \
} while(0)
#define DBF_DEV_EXC(d_level, d_device, d_str, d_data...) \
do { \
debug_sprintf_exception(d_device->debug_area, \
d_level, \
d_str "\n", \
d_data); \
} while(0)
#define DBF_EVENT(d_level, d_str, d_data...)\
do { \
debug_sprintf_event(dasd_debug_area, \
d_level,\
d_str "\n", \
d_data); \
} while(0)
#define DBF_EVENT_DEVID(d_level, d_cdev, d_str, d_data...) \
do { \
struct ccw_dev_id __dev_id; \
ccw_device_get_id(d_cdev, &__dev_id); \
debug_sprintf_event(dasd_debug_area, \
d_level, \
"0.%x.%04x " d_str "\n", \
__dev_id.ssid, __dev_id.devno, d_data); \
} while (0)
#define DBF_EXC(d_level, d_str, d_data...)\
do { \
debug_sprintf_exception(dasd_debug_area, \
d_level,\
d_str "\n", \
d_data); \
} while(0)
/* limit size for an errorstring */
#define ERRORLENGTH 30
/* definition of dbf debug levels */
#define DBF_EMERG 0 /* system is unusable */
#define DBF_ALERT 1 /* action must be taken immediately */
#define DBF_CRIT 2 /* critical conditions */
#define DBF_ERR 3 /* error conditions */
#define DBF_WARNING 4 /* warning conditions */
#define DBF_NOTICE 5 /* normal but significant condition */
#define DBF_INFO 6 /* informational */
#define DBF_DEBUG 6 /* debug-level messages */
/* messages to be written via klogd and dbf */
#define DEV_MESSAGE(d_loglevel,d_device,d_string,d_args...)\
do { \
printk(d_loglevel PRINTK_HEADER " %s: " d_string "\n", \
dev_name(&d_device->cdev->dev), d_args); \
DBF_DEV_EVENT(DBF_ALERT, d_device, d_string, d_args); \
} while(0)
#define MESSAGE(d_loglevel,d_string,d_args...)\
do { \
printk(d_loglevel PRINTK_HEADER " " d_string "\n", d_args); \
DBF_EVENT(DBF_ALERT, d_string, d_args); \
} while(0)
/* messages to be written via klogd only */
#define DEV_MESSAGE_LOG(d_loglevel,d_device,d_string,d_args...)\
do { \
printk(d_loglevel PRINTK_HEADER " %s: " d_string "\n", \
dev_name(&d_device->cdev->dev), d_args); \
} while(0)
#define MESSAGE_LOG(d_loglevel,d_string,d_args...)\
do { \
printk(d_loglevel PRINTK_HEADER " " d_string "\n", d_args); \
} while(0)
struct dasd_ccw_req {
unsigned int magic; /* Eye catcher */
struct list_head devlist; /* for dasd_device request queue */
struct list_head blocklist; /* for dasd_block request queue */
/* Where to execute what... */
struct dasd_block *block; /* the originating block device */
struct dasd_device *memdev; /* the device used to allocate this */
struct dasd_device *startdev; /* device the request is started on */
void *cpaddr; /* address of ccw or tcw */
unsigned char cpmode; /* 0 = cmd mode, 1 = itcw */
char status; /* status of this request */
short retries; /* A retry counter */
unsigned long flags; /* flags of this request */
/* ... and how */
unsigned long starttime; /* jiffies time of request start */
int expires; /* expiration period in jiffies */
char lpm; /* logical path mask */
void *data; /* pointer to data area */
/* these are important for recovering erroneous requests */
int intrc; /* internal error, e.g. from start_IO */
struct irb irb; /* device status in case of an error */
struct dasd_ccw_req *refers; /* ERP-chain queueing. */
void *function; /* originating ERP action */
/* these are for statistics only */
unsigned long long buildclk; /* TOD-clock of request generation */
unsigned long long startclk; /* TOD-clock of request start */
unsigned long long stopclk; /* TOD-clock of request interrupt */
unsigned long long endclk; /* TOD-clock of request termination */
/* Callback that is called after reaching final status. */
void (*callback)(struct dasd_ccw_req *, void *data);
void *callback_data;
};
/*
* dasd_ccw_req -> status can be:
*/
#define DASD_CQR_FILLED 0x00 /* request is ready to be processed */
#define DASD_CQR_DONE 0x01 /* request is completed successfully */
#define DASD_CQR_NEED_ERP 0x02 /* request needs recovery action */
#define DASD_CQR_IN_ERP 0x03 /* request is in recovery */
#define DASD_CQR_FAILED 0x04 /* request is finally failed */
#define DASD_CQR_TERMINATED 0x05 /* request was stopped by driver */
#define DASD_CQR_QUEUED 0x80 /* request is queued to be processed */
#define DASD_CQR_IN_IO 0x81 /* request is currently in IO */
#define DASD_CQR_ERROR 0x82 /* request is completed with error */
#define DASD_CQR_CLEAR_PENDING 0x83 /* request is clear pending */
#define DASD_CQR_CLEARED 0x84 /* request was cleared */
#define DASD_CQR_SUCCESS 0x85 /* request was successful */
/* per dasd_ccw_req flags */
#define DASD_CQR_FLAGS_USE_ERP 0 /* use ERP for this request */
#define DASD_CQR_FLAGS_FAILFAST 1 /* FAILFAST */
/* Signature for error recovery functions. */
typedef struct dasd_ccw_req *(*dasd_erp_fn_t) (struct dasd_ccw_req *);
/*
* the struct dasd_discipline is
* sth like a table of virtual functions, if you think of dasd_eckd
* inheriting dasd...
* no, currently we are not planning to reimplement the driver in C++
*/
struct dasd_discipline {
struct module *owner;
char ebcname[8]; /* a name used for tagging and printks */
char name[8]; /* a name used for tagging and printks */
int max_blocks; /* maximum number of blocks to be chained */
struct list_head list; /* used for list of disciplines */
/*
* Device recognition functions. check_device is used to verify
* the sense data and the information returned by read device
* characteristics. It returns 0 if the discipline can be used
* for the device in question. uncheck_device is called during
* device shutdown to deregister a device from its discipline.
*/
int (*check_device) (struct dasd_device *);
void (*uncheck_device) (struct dasd_device *);
/*
* do_analysis is used in the step from device state "basic" to
* state "accept". It returns 0 if the device can be made ready,
* it returns -EMEDIUMTYPE if the device can't be made ready or
* -EAGAIN if do_analysis started a ccw that needs to complete
* before the analysis may be repeated.
*/
int (*do_analysis) (struct dasd_block *);
/*
* Last things to do when a device is set online, and first things
* when it is set offline.
*/
int (*ready_to_online) (struct dasd_device *);
int (*online_to_ready) (struct dasd_device *);
/*
* Device operation functions. build_cp creates a ccw chain for
* a block device request, start_io starts the request and
* term_IO cancels it (e.g. in case of a timeout). format_device
* returns a ccw chain to be used to format the device.
* handle_terminated_request allows to examine a cqr and prepare
* it for retry.
*/
struct dasd_ccw_req *(*build_cp) (struct dasd_device *,
struct dasd_block *,
struct request *);
int (*start_IO) (struct dasd_ccw_req *);
int (*term_IO) (struct dasd_ccw_req *);
void (*handle_terminated_request) (struct dasd_ccw_req *);
struct dasd_ccw_req *(*format_device) (struct dasd_device *,
struct format_data_t *);
int (*free_cp) (struct dasd_ccw_req *, struct request *);
/*
* Error recovery functions. examine_error() returns a value that
* indicates what to do for an error condition. If examine_error()
* returns 'dasd_era_recover' erp_action() is called to create a
* special error recovery ccw. erp_postaction() is called after
* an error recovery ccw has finished its execution. dump_sense
* is called for every error condition to print the sense data
* to the console.
*/
dasd_erp_fn_t(*erp_action) (struct dasd_ccw_req *);
dasd_erp_fn_t(*erp_postaction) (struct dasd_ccw_req *);
void (*dump_sense) (struct dasd_device *, struct dasd_ccw_req *,
struct irb *);
void (*dump_sense_dbf) (struct dasd_device *, struct irb *, char *);
void (*handle_unsolicited_interrupt) (struct dasd_device *,
struct irb *);
/* i/o control functions. */
int (*fill_geometry) (struct dasd_block *, struct hd_geometry *);
int (*fill_info) (struct dasd_device *, struct dasd_information2_t *);
int (*ioctl) (struct dasd_block *, unsigned int, void __user *);
/* suspend/resume functions */
int (*freeze) (struct dasd_device *);
int (*restore) (struct dasd_device *);
};
extern struct dasd_discipline *dasd_diag_discipline_pointer;
/*
* Unique identifier for dasd device.
*/
#define UA_NOT_CONFIGURED 0x00
#define UA_BASE_DEVICE 0x01
#define UA_BASE_PAV_ALIAS 0x02
#define UA_HYPER_PAV_ALIAS 0x03
struct dasd_uid {
__u8 type;
char vendor[4];
char serial[15];
__u16 ssid;
__u8 real_unit_addr;
__u8 base_unit_addr;
char vduit[33];
};
/*
* Notification numbers for extended error reporting notifications:
* The DASD_EER_DISABLE notification is sent before a dasd_device (and it's
* eer pointer) is freed. The error reporting module needs to do all necessary
* cleanup steps.
* The DASD_EER_TRIGGER notification sends the actual error reports (triggers).
*/
#define DASD_EER_DISABLE 0
#define DASD_EER_TRIGGER 1
/* Trigger IDs for extended error reporting DASD_EER_TRIGGER notification */
#define DASD_EER_FATALERROR 1
#define DASD_EER_NOPATH 2
#define DASD_EER_STATECHANGE 3
#define DASD_EER_PPRCSUSPEND 4
struct dasd_device {
/* Block device stuff. */
struct dasd_block *block;
unsigned int devindex;
unsigned long flags; /* per device flags */
unsigned short features; /* copy of devmap-features (read-only!) */
/* extended error reporting stuff (eer) */
struct dasd_ccw_req *eer_cqr;
/* Device discipline stuff. */
struct dasd_discipline *discipline;
struct dasd_discipline *base_discipline;
char *private;
/* Device state and target state. */
int state, target;
int stopped; /* device (ccw_device_start) was stopped */
/* reference count. */
atomic_t ref_count;
/* ccw queue and memory for static ccw/erp buffers. */
struct list_head ccw_queue;
spinlock_t mem_lock;
void *ccw_mem;
void *erp_mem;
struct list_head ccw_chunks;
struct list_head erp_chunks;
atomic_t tasklet_scheduled;
struct tasklet_struct tasklet;
struct work_struct kick_work;
struct work_struct restore_device;
struct timer_list timer;
debug_info_t *debug_area;
struct ccw_device *cdev;
/* hook for alias management */
struct list_head alias_list;
};
struct dasd_block {
/* Block device stuff. */
struct gendisk *gdp;
struct request_queue *request_queue;
spinlock_t request_queue_lock;
struct block_device *bdev;
atomic_t open_count;
unsigned long long blocks; /* size of volume in blocks */
unsigned int bp_block; /* bytes per block */
unsigned int s2b_shift; /* log2 (bp_block/512) */
struct dasd_device *base;
struct list_head ccw_queue;
spinlock_t queue_lock;
atomic_t tasklet_scheduled;
struct tasklet_struct tasklet;
struct timer_list timer;
#ifdef CONFIG_DASD_PROFILE
struct dasd_profile_info_t profile;
#endif
};
/* reasons why device (ccw_device_start) was stopped */
#define DASD_STOPPED_NOT_ACC 1 /* not accessible */
#define DASD_STOPPED_QUIESCE 2 /* Quiesced */
#define DASD_STOPPED_PENDING 4 /* long busy */
#define DASD_STOPPED_DC_WAIT 8 /* disconnected, wait */
#define DASD_STOPPED_SU 16 /* summary unit check handling */
#define DASD_STOPPED_PM 32 /* pm state transition */
#define DASD_UNRESUMED_PM 64 /* pm resume failed state */
/* per device flags */
#define DASD_FLAG_OFFLINE 3 /* device is in offline processing */
#define DASD_FLAG_EER_SNSS 4 /* A SNSS is required */
#define DASD_FLAG_EER_IN_USE 5 /* A SNSS request is running */
void dasd_put_device_wake(struct dasd_device *);
/*
* Reference count inliners
*/
static inline void
dasd_get_device(struct dasd_device *device)
{
atomic_inc(&device->ref_count);
}
static inline void
dasd_put_device(struct dasd_device *device)
{
if (atomic_dec_return(&device->ref_count) == 0)
dasd_put_device_wake(device);
}
/*
* The static memory in ccw_mem and erp_mem is managed by a sorted
* list of free memory chunks.
*/
struct dasd_mchunk
{
struct list_head list;
unsigned long size;
} __attribute__ ((aligned(8)));
static inline void
dasd_init_chunklist(struct list_head *chunk_list, void *mem,
unsigned long size)
{
struct dasd_mchunk *chunk;
INIT_LIST_HEAD(chunk_list);
chunk = (struct dasd_mchunk *) mem;
chunk->size = size - sizeof(struct dasd_mchunk);
list_add(&chunk->list, chunk_list);
}
static inline void *
dasd_alloc_chunk(struct list_head *chunk_list, unsigned long size)
{
struct dasd_mchunk *chunk, *tmp;
size = (size + 7L) & -8L;
list_for_each_entry(chunk, chunk_list, list) {
if (chunk->size < size)
continue;
if (chunk->size > size + sizeof(struct dasd_mchunk)) {
char *endaddr = (char *) (chunk + 1) + chunk->size;
tmp = (struct dasd_mchunk *) (endaddr - size) - 1;
tmp->size = size;
chunk->size -= size + sizeof(struct dasd_mchunk);
chunk = tmp;
} else
list_del(&chunk->list);
return (void *) (chunk + 1);
}
return NULL;
}
static inline void
dasd_free_chunk(struct list_head *chunk_list, void *mem)
{
struct dasd_mchunk *chunk, *tmp;
struct list_head *p, *left;
chunk = (struct dasd_mchunk *)
((char *) mem - sizeof(struct dasd_mchunk));
/* Find out the left neighbour in chunk_list. */
left = chunk_list;
list_for_each(p, chunk_list) {
if (list_entry(p, struct dasd_mchunk, list) > chunk)
break;
left = p;
}
/* Try to merge with right neighbour = next element from left. */
if (left->next != chunk_list) {
tmp = list_entry(left->next, struct dasd_mchunk, list);
if ((char *) (chunk + 1) + chunk->size == (char *) tmp) {
list_del(&tmp->list);
chunk->size += tmp->size + sizeof(struct dasd_mchunk);
}
}
/* Try to merge with left neighbour. */
if (left != chunk_list) {
tmp = list_entry(left, struct dasd_mchunk, list);
if ((char *) (tmp + 1) + tmp->size == (char *) chunk) {
tmp->size += chunk->size + sizeof(struct dasd_mchunk);
return;
}
}
__list_add(&chunk->list, left, left->next);
}
/*
* Check if bsize is in { 512, 1024, 2048, 4096 }
*/
static inline int
dasd_check_blocksize(int bsize)
{
if (bsize < 512 || bsize > 4096 || !is_power_of_2(bsize))
return -EMEDIUMTYPE;
return 0;
}
/* externals in dasd.c */
#define DASD_PROFILE_ON 1
#define DASD_PROFILE_OFF 0
extern debug_info_t *dasd_debug_area;
extern struct dasd_profile_info_t dasd_global_profile;
extern unsigned int dasd_profile_level;
extern const struct block_device_operations dasd_device_operations;
extern struct kmem_cache *dasd_page_cache;
struct dasd_ccw_req *
dasd_kmalloc_request(int , int, int, struct dasd_device *);
struct dasd_ccw_req *
dasd_smalloc_request(int , int, int, struct dasd_device *);
void dasd_kfree_request(struct dasd_ccw_req *, struct dasd_device *);
void dasd_sfree_request(struct dasd_ccw_req *, struct dasd_device *);
static inline int
dasd_kmalloc_set_cda(struct ccw1 *ccw, void *cda, struct dasd_device *device)
{
return set_normalized_cda(ccw, cda);
}
struct dasd_device *dasd_alloc_device(void);
void dasd_free_device(struct dasd_device *);
struct dasd_block *dasd_alloc_block(void);
void dasd_free_block(struct dasd_block *);
void dasd_enable_device(struct dasd_device *);
void dasd_set_target_state(struct dasd_device *, int);
void dasd_kick_device(struct dasd_device *);
void dasd_restore_device(struct dasd_device *);
void dasd_add_request_head(struct dasd_ccw_req *);
void dasd_add_request_tail(struct dasd_ccw_req *);
int dasd_start_IO(struct dasd_ccw_req *);
int dasd_term_IO(struct dasd_ccw_req *);
void dasd_schedule_device_bh(struct dasd_device *);
void dasd_schedule_block_bh(struct dasd_block *);
int dasd_sleep_on(struct dasd_ccw_req *);
int dasd_sleep_on_immediatly(struct dasd_ccw_req *);
int dasd_sleep_on_interruptible(struct dasd_ccw_req *);
void dasd_device_set_timer(struct dasd_device *, int);
void dasd_device_clear_timer(struct dasd_device *);
void dasd_block_set_timer(struct dasd_block *, int);
void dasd_block_clear_timer(struct dasd_block *);
int dasd_cancel_req(struct dasd_ccw_req *);
int dasd_flush_device_queue(struct dasd_device *);
int dasd_generic_probe (struct ccw_device *, struct dasd_discipline *);
void dasd_generic_remove (struct ccw_device *cdev);
int dasd_generic_set_online(struct ccw_device *, struct dasd_discipline *);
int dasd_generic_set_offline (struct ccw_device *cdev);
int dasd_generic_notify(struct ccw_device *, int);
void dasd_generic_handle_state_change(struct dasd_device *);
int dasd_generic_pm_freeze(struct ccw_device *);
int dasd_generic_restore_device(struct ccw_device *);
int dasd_generic_read_dev_chars(struct dasd_device *, int, void *, int);
char *dasd_get_sense(struct irb *);
void dasd_device_set_stop_bits(struct dasd_device *, int);
void dasd_device_remove_stop_bits(struct dasd_device *, int);
/* externals in dasd_devmap.c */
extern int dasd_max_devindex;
extern int dasd_probeonly;
extern int dasd_autodetect;
extern int dasd_nopav;
extern int dasd_nofcx;
int dasd_devmap_init(void);
void dasd_devmap_exit(void);
struct dasd_device *dasd_create_device(struct ccw_device *);
void dasd_delete_device(struct dasd_device *);
int dasd_get_uid(struct ccw_device *, struct dasd_uid *);
int dasd_set_uid(struct ccw_device *, struct dasd_uid *);
int dasd_get_feature(struct ccw_device *, int);
int dasd_set_feature(struct ccw_device *, int, int);
int dasd_add_sysfs_files(struct ccw_device *);
void dasd_remove_sysfs_files(struct ccw_device *);
struct dasd_device *dasd_device_from_cdev(struct ccw_device *);
struct dasd_device *dasd_device_from_cdev_locked(struct ccw_device *);
struct dasd_device *dasd_device_from_devindex(int);
int dasd_parse(void);
int dasd_busid_known(const char *);
/* externals in dasd_gendisk.c */
int dasd_gendisk_init(void);
void dasd_gendisk_exit(void);
int dasd_gendisk_alloc(struct dasd_block *);
void dasd_gendisk_free(struct dasd_block *);
int dasd_scan_partitions(struct dasd_block *);
void dasd_destroy_partitions(struct dasd_block *);
/* externals in dasd_ioctl.c */
int dasd_ioctl(struct block_device *, fmode_t, unsigned int, unsigned long);
/* externals in dasd_proc.c */
int dasd_proc_init(void);
void dasd_proc_exit(void);
/* externals in dasd_erp.c */
struct dasd_ccw_req *dasd_default_erp_action(struct dasd_ccw_req *);
struct dasd_ccw_req *dasd_default_erp_postaction(struct dasd_ccw_req *);
struct dasd_ccw_req *dasd_alloc_erp_request(char *, int, int,
struct dasd_device *);
void dasd_free_erp_request(struct dasd_ccw_req *, struct dasd_device *);
void dasd_log_sense(struct dasd_ccw_req *, struct irb *);
void dasd_log_sense_dbf(struct dasd_ccw_req *cqr, struct irb *irb);
/* externals in dasd_3990_erp.c */
struct dasd_ccw_req *dasd_3990_erp_action(struct dasd_ccw_req *);
void dasd_3990_erp_handle_sim(struct dasd_device *, char *);
/* externals in dasd_eer.c */
#ifdef CONFIG_DASD_EER
int dasd_eer_init(void);
void dasd_eer_exit(void);
int dasd_eer_enable(struct dasd_device *);
void dasd_eer_disable(struct dasd_device *);
void dasd_eer_write(struct dasd_device *, struct dasd_ccw_req *cqr,
unsigned int id);
void dasd_eer_snss(struct dasd_device *);
static inline int dasd_eer_enabled(struct dasd_device *device)
{
return device->eer_cqr != NULL;
}
#else
#define dasd_eer_init() (0)
#define dasd_eer_exit() do { } while (0)
#define dasd_eer_enable(d) (0)
#define dasd_eer_disable(d) do { } while (0)
#define dasd_eer_write(d,c,i) do { } while (0)
#define dasd_eer_snss(d) do { } while (0)
#define dasd_eer_enabled(d) (0)
#endif /* CONFIG_DASD_ERR */
#endif /* __KERNEL__ */
#endif /* DASD_H */
|
{
"pile_set_name": "Github"
}
|
package fr.xephi.authme.command.executable.authme.debug;
import fr.xephi.authme.data.limbo.LimboPlayer;
import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.data.limbo.persistence.LimboPersistence;
import fr.xephi.authme.permission.DebugSectionPermissions;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.service.BukkitService;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import static fr.xephi.authme.command.executable.authme.debug.DebugSectionUtils.applyToLimboPlayersMap;
import static fr.xephi.authme.command.executable.authme.debug.DebugSectionUtils.formatLocation;
/**
* Shows the data stored in LimboPlayers and the equivalent properties on online players.
*/
class LimboPlayerViewer implements DebugSection {
@Inject
private LimboService limboService;
@Inject
private LimboPersistence limboPersistence;
@Inject
private BukkitService bukkitService;
@Inject
private PermissionsManager permissionsManager;
@Override
public String getName() {
return "limbo";
}
@Override
public String getDescription() {
return "View LimboPlayers and player's \"limbo stats\"";
}
@Override
public void execute(CommandSender sender, List<String> arguments) {
if (arguments.isEmpty()) {
sender.sendMessage(ChatColor.BLUE + "AuthMe limbo viewer");
sender.sendMessage("/authme debug limbo <player>: show a player's limbo info");
sender.sendMessage("Available limbo records: " + applyToLimboPlayersMap(limboService, Map::keySet));
return;
}
LimboPlayer memoryLimbo = limboService.getLimboPlayer(arguments.get(0));
Player player = bukkitService.getPlayerExact(arguments.get(0));
LimboPlayer diskLimbo = player != null ? limboPersistence.getLimboPlayer(player) : null;
if (memoryLimbo == null && player == null) {
sender.sendMessage(ChatColor.BLUE + "No AuthMe limbo data");
sender.sendMessage("No limbo data and no player online with name '" + arguments.get(0) + "'");
return;
}
sender.sendMessage(ChatColor.BLUE + "Player / limbo / disk limbo info for '" + arguments.get(0) + "'");
new InfoDisplayer(sender, player, memoryLimbo, diskLimbo)
.sendEntry("Is op", Player::isOp, LimboPlayer::isOperator)
.sendEntry("Walk speed", Player::getWalkSpeed, LimboPlayer::getWalkSpeed)
.sendEntry("Can fly", Player::getAllowFlight, LimboPlayer::isCanFly)
.sendEntry("Fly speed", Player::getFlySpeed, LimboPlayer::getFlySpeed)
.sendEntry("Location", p -> formatLocation(p.getLocation()), l -> formatLocation(l.getLocation()))
.sendEntry("Prim. group",
p -> permissionsManager.hasGroupSupport() ? permissionsManager.getPrimaryGroup(p) : "N/A",
LimboPlayer::getGroups);
}
@Override
public PermissionNode getRequiredPermission() {
return DebugSectionPermissions.LIMBO_PLAYER_VIEWER;
}
/**
* Displays the info for the given LimboPlayer and Player to the provided CommandSender.
*/
private static final class InfoDisplayer {
private final CommandSender sender;
private final Optional<Player> player;
private final Optional<LimboPlayer> memoryLimbo;
private final Optional<LimboPlayer> diskLimbo;
/**
* Constructor.
*
* @param sender command sender to send the information to
* @param player the player to get data from
* @param memoryLimbo the limbo player to get data from
*/
InfoDisplayer(CommandSender sender, Player player, LimboPlayer memoryLimbo, LimboPlayer diskLimbo) {
this.sender = sender;
this.player = Optional.ofNullable(player);
this.memoryLimbo = Optional.ofNullable(memoryLimbo);
this.diskLimbo = Optional.ofNullable(diskLimbo);
if (memoryLimbo == null) {
sender.sendMessage("Note: no Limbo information available");
}
if (player == null) {
sender.sendMessage("Note: player is not online");
} else if (diskLimbo == null) {
sender.sendMessage("Note: no Limbo on disk available");
}
}
/**
* Displays a piece of information to the command sender.
*
* @param title the designation of the piece of information
* @param playerGetter getter for data retrieval on Player
* @param limboGetter getter for data retrieval on the LimboPlayer
* @param <T> the data type
* @return this instance (for chaining)
*/
<T> InfoDisplayer sendEntry(String title,
Function<Player, T> playerGetter,
Function<LimboPlayer, T> limboGetter) {
sender.sendMessage(
title + ": "
+ getData(player, playerGetter)
+ " / "
+ getData(memoryLimbo, limboGetter)
+ " / "
+ getData(diskLimbo, limboGetter));
return this;
}
static <E, T> String getData(Optional<E> entity, Function<E, T> getter) {
return entity.map(getter).map(String::valueOf).orElse(" -- ");
}
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NEventStore" version="4.0.0.15" targetFramework="net40" />
</packages>
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* libretroshare/src/util: rstime.cc *
* *
* libretroshare: retroshare core library *
* *
* Copyright 2013-2013 by Cyril Soler <csoler@users.sourceforge.net> *
* *
* This program 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 3 of the *
* License, 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include <iostream>
#include <thread>
#include <sys/time.h>
#include <unistd.h>
#include "rstime.h"
namespace rstime {
int rs_usleep(uint32_t micro_seconds)
{
while(micro_seconds >= 1000000)
{
// usleep cannot be called with 1000000 or more.
usleep(500000) ;
usleep(500000) ;
micro_seconds -= 1000000 ;
}
usleep(micro_seconds) ;
return 0 ;
}
RsScopeTimer::RsScopeTimer(const std::string& name)
{
_name = name ;
start();
}
RsScopeTimer::~RsScopeTimer()
{
if (!_name.empty())
{
std::cerr << "Time for \"" << _name << "\": " << duration() << std::endl;
}
}
double RsScopeTimer::currentTime()
{
timeval tv ;
gettimeofday(&tv,NULL) ;
return (tv.tv_sec % 10000) + tv.tv_usec/1000000.0f ; // the %1000 is here to allow double precision to cover the decimals.
}
void RsScopeTimer::start()
{
_seconds = currentTime();
}
double RsScopeTimer::duration()
{
return currentTime() - _seconds;
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Twenty Eleven functions and definitions
*
* Sets up the theme and provides some helper functions. Some helper functions
* are used in the theme as custom template tags. Others are attached to action and
* filter hooks in WordPress to change core functionality.
*
* The first function, twentyeleven_setup(), sets up the theme by registering support
* for various features in WordPress, such as post thumbnails, navigation menus, and the like.
*
* When using a child theme you can override certain functions (those wrapped
* in a function_exists() call) by defining them first in your child theme's
* functions.php file. The child theme's functions.php file is included before
* the parent theme's file, so the child theme functions would be used.
*
* @link https://developer.wordpress.org/themes/basics/theme-functions/
* @link https://developer.wordpress.org/themes/advanced-topics/child-themes/
*
* Functions that are not pluggable (not wrapped in function_exists()) are instead attached
* to a filter or action hook. The hook can be removed by using remove_action() or
* remove_filter() and you can attach your own function to the hook.
*
* We can remove the parent theme's hook only after it is attached, which means we need to
* wait until setting up the child theme:
*
* <code>
* add_action( 'after_setup_theme', 'my_child_theme_setup' );
* function my_child_theme_setup() {
* // We are providing our own filter for excerpt_length (or using the unfiltered value).
* remove_filter( 'excerpt_length', 'twentyeleven_excerpt_length' );
* ...
* }
* </code>
*
* For more information on hooks, actions, and filters, see https://developer.wordpress.org/plugins/.
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
// Set the content width based on the theme's design and stylesheet.
if ( ! isset( $content_width ) ) {
$content_width = 584;
}
/*
* Tell WordPress to run twentyeleven_setup() when the 'after_setup_theme' hook is run.
*/
add_action( 'after_setup_theme', 'twentyeleven_setup' );
if ( ! function_exists( 'twentyeleven_setup' ) ) :
/**
* Set up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which runs
* before the init hook. The init hook is too late for some features, such as indicating
* support post thumbnails.
*
* To override twentyeleven_setup() in a child theme, add your own twentyeleven_setup to your child theme's
* functions.php file.
*
* @uses load_theme_textdomain() For translation/localization support.
* @uses add_editor_style() To style the visual editor.
* @uses add_theme_support() To add support for post thumbnails, automatic feed links, custom headers
* and backgrounds, and post formats.
* @uses register_nav_menus() To add support for navigation menus.
* @uses register_default_headers() To register the default custom header images provided with the theme.
* @uses set_post_thumbnail_size() To set a custom post thumbnail size.
*
* @since Twenty Eleven 1.0
*/
function twentyeleven_setup() {
/*
* Make Twenty Eleven available for translation.
* Translations can be added to the /languages/ directory.
* If you're building a theme based on Twenty Eleven, use
* a find and replace to change 'twentyeleven' to the name
* of your theme in all the template files.
*/
load_theme_textdomain( 'twentyeleven', get_template_directory() . '/languages' );
// This theme styles the visual editor with editor-style.css to match the theme style.
add_editor_style();
// Load regular editor styles into the new block-based editor.
add_theme_support( 'editor-styles' );
// Load default block styles.
add_theme_support( 'wp-block-styles' );
// Add support for responsive embeds.
add_theme_support( 'responsive-embeds' );
// Add support for custom color scheme.
add_theme_support(
'editor-color-palette',
array(
array(
'name' => __( 'Blue', 'twentyeleven' ),
'slug' => 'blue',
'color' => '#1982d1',
),
array(
'name' => __( 'Black', 'twentyeleven' ),
'slug' => 'black',
'color' => '#000',
),
array(
'name' => __( 'Dark Gray', 'twentyeleven' ),
'slug' => 'dark-gray',
'color' => '#373737',
),
array(
'name' => __( 'Medium Gray', 'twentyeleven' ),
'slug' => 'medium-gray',
'color' => '#666',
),
array(
'name' => __( 'Light Gray', 'twentyeleven' ),
'slug' => 'light-gray',
'color' => '#e2e2e2',
),
array(
'name' => __( 'White', 'twentyeleven' ),
'slug' => 'white',
'color' => '#fff',
),
)
);
// Load up our theme options page and related code.
require get_template_directory() . '/inc/theme-options.php';
// Grab Twenty Eleven's Ephemera widget.
require get_template_directory() . '/inc/widgets.php';
// Add default posts and comments RSS feed links to <head>.
add_theme_support( 'automatic-feed-links' );
// This theme uses wp_nav_menu() in one location.
register_nav_menu( 'primary', __( 'Primary Menu', 'twentyeleven' ) );
// Add support for a variety of post formats.
add_theme_support( 'post-formats', array( 'aside', 'link', 'gallery', 'status', 'quote', 'image' ) );
$theme_options = twentyeleven_get_theme_options();
if ( 'dark' === $theme_options['color_scheme'] ) {
$default_background_color = '1d1d1d';
} else {
$default_background_color = 'e2e2e2';
}
// Add support for custom backgrounds.
add_theme_support(
'custom-background',
array(
/*
* Let WordPress know what our default background color is.
* This is dependent on our current color scheme.
*/
'default-color' => $default_background_color,
)
);
// This theme uses Featured Images (also known as post thumbnails) for per-post/per-page Custom Header images.
add_theme_support( 'post-thumbnails' );
// Add support for custom headers.
$custom_header_support = array(
// The default header text color.
'default-text-color' => '000',
// The height and width of our custom header.
/**
* Filters the Twenty Eleven default header image width.
*
* @since Twenty Eleven 1.0
*
* @param int The default header image width in pixels. Default 1000.
*/
'width' => apply_filters( 'twentyeleven_header_image_width', 1000 ),
/**
* Filters the Twenty Eleven default header image height.
*
* @since Twenty Eleven 1.0
*
* @param int The default header image height in pixels. Default 288.
*/
'height' => apply_filters( 'twentyeleven_header_image_height', 288 ),
// Support flexible heights.
'flex-height' => true,
// Random image rotation by default.
'random-default' => true,
// Callback for styling the header.
'wp-head-callback' => 'twentyeleven_header_style',
// Callback for styling the header preview in the admin.
'admin-head-callback' => 'twentyeleven_admin_header_style',
// Callback used to display the header preview in the admin.
'admin-preview-callback' => 'twentyeleven_admin_header_image',
);
add_theme_support( 'custom-header', $custom_header_support );
if ( ! function_exists( 'get_custom_header' ) ) {
// This is all for compatibility with versions of WordPress prior to 3.4.
define( 'HEADER_TEXTCOLOR', $custom_header_support['default-text-color'] );
define( 'HEADER_IMAGE', '' );
define( 'HEADER_IMAGE_WIDTH', $custom_header_support['width'] );
define( 'HEADER_IMAGE_HEIGHT', $custom_header_support['height'] );
add_custom_image_header( $custom_header_support['wp-head-callback'], $custom_header_support['admin-head-callback'], $custom_header_support['admin-preview-callback'] );
add_custom_background();
}
/*
* We'll be using post thumbnails for custom header images on posts and pages.
* We want them to be the size of the header image that we just defined.
* Larger images will be auto-cropped to fit, smaller ones will be ignored. See header.php.
*/
set_post_thumbnail_size( $custom_header_support['width'], $custom_header_support['height'], true );
/*
* Add Twenty Eleven's custom image sizes.
* Used for large feature (header) images.
*/
add_image_size( 'large-feature', $custom_header_support['width'], $custom_header_support['height'], true );
// Used for featured posts if a large-feature doesn't exist.
add_image_size( 'small-feature', 500, 300 );
// Default custom headers packaged with the theme. %s is a placeholder for the theme template directory URI.
register_default_headers(
array(
'wheel' => array(
'url' => '%s/images/headers/wheel.jpg',
'thumbnail_url' => '%s/images/headers/wheel-thumbnail.jpg',
/* translators: Header image description. */
'description' => __( 'Wheel', 'twentyeleven' ),
),
'shore' => array(
'url' => '%s/images/headers/shore.jpg',
'thumbnail_url' => '%s/images/headers/shore-thumbnail.jpg',
/* translators: Header image description. */
'description' => __( 'Shore', 'twentyeleven' ),
),
'trolley' => array(
'url' => '%s/images/headers/trolley.jpg',
'thumbnail_url' => '%s/images/headers/trolley-thumbnail.jpg',
/* translators: Header image description. */
'description' => __( 'Trolley', 'twentyeleven' ),
),
'pine-cone' => array(
'url' => '%s/images/headers/pine-cone.jpg',
'thumbnail_url' => '%s/images/headers/pine-cone-thumbnail.jpg',
/* translators: Header image description. */
'description' => __( 'Pine Cone', 'twentyeleven' ),
),
'chessboard' => array(
'url' => '%s/images/headers/chessboard.jpg',
'thumbnail_url' => '%s/images/headers/chessboard-thumbnail.jpg',
/* translators: Header image description. */
'description' => __( 'Chessboard', 'twentyeleven' ),
),
'lanterns' => array(
'url' => '%s/images/headers/lanterns.jpg',
'thumbnail_url' => '%s/images/headers/lanterns-thumbnail.jpg',
/* translators: Header image description. */
'description' => __( 'Lanterns', 'twentyeleven' ),
),
'willow' => array(
'url' => '%s/images/headers/willow.jpg',
'thumbnail_url' => '%s/images/headers/willow-thumbnail.jpg',
/* translators: Header image description. */
'description' => __( 'Willow', 'twentyeleven' ),
),
'hanoi' => array(
'url' => '%s/images/headers/hanoi.jpg',
'thumbnail_url' => '%s/images/headers/hanoi-thumbnail.jpg',
/* translators: Header image description. */
'description' => __( 'Hanoi Plant', 'twentyeleven' ),
),
)
);
// Indicate widget sidebars can use selective refresh in the Customizer.
add_theme_support( 'customize-selective-refresh-widgets' );
}
endif; // twentyeleven_setup()
/**
* Enqueue scripts and styles for front end.
*
* @since Twenty Eleven 2.9
*/
function twentyeleven_scripts_styles() {
// Theme block stylesheet.
wp_enqueue_style( 'twentyeleven-block-style', get_template_directory_uri() . '/blocks.css', array(), '20190102' );
}
add_action( 'wp_enqueue_scripts', 'twentyeleven_scripts_styles' );
/**
* Enqueue styles for the block-based editor.
*
* @since Twenty Eleven 2.9
*/
function twentyeleven_block_editor_styles() {
// Block styles.
wp_enqueue_style( 'twentyeleven-block-editor-style', get_template_directory_uri() . '/editor-blocks.css', array(), '20190102' );
}
add_action( 'enqueue_block_editor_assets', 'twentyeleven_block_editor_styles' );
if ( ! function_exists( 'twentyeleven_header_style' ) ) :
/**
* Styles the header image and text displayed on the blog.
*
* @since Twenty Eleven 1.0
*/
function twentyeleven_header_style() {
$text_color = get_header_textcolor();
// If no custom options for text are set, let's bail.
if ( HEADER_TEXTCOLOR == $text_color ) {
return;
}
// If we get this far, we have custom styles. Let's do this.
?>
<style type="text/css" id="twentyeleven-header-css">
<?php
// Has the text been hidden?
if ( 'blank' === $text_color ) :
?>
#site-title,
#site-description {
position: absolute;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
}
<?php
// If the user has set a custom color for the text, use that.
else :
?>
#site-title a,
#site-description {
color: #<?php echo $text_color; ?>;
}
<?php endif; ?>
</style>
<?php
}
endif; // twentyeleven_header_style()
if ( ! function_exists( 'twentyeleven_admin_header_style' ) ) :
/**
* Styles the header image displayed on the Appearance > Header admin panel.
*
* Referenced via add_theme_support('custom-header') in twentyeleven_setup().
*
* @since Twenty Eleven 1.0
*/
function twentyeleven_admin_header_style() {
?>
<style type="text/css" id="twentyeleven-admin-header-css">
.appearance_page_custom-header #headimg {
border: none;
}
#headimg h1,
#desc {
font-family: "Helvetica Neue", Arial, Helvetica, "Nimbus Sans L", sans-serif;
}
#headimg h1 {
margin: 0;
}
#headimg h1 a {
font-size: 32px;
line-height: 36px;
text-decoration: none;
}
#desc {
font-size: 14px;
line-height: 23px;
padding: 0 0 3em;
}
<?php
// If the user has set a custom color for the text, use that.
if ( get_header_textcolor() != HEADER_TEXTCOLOR ) :
?>
#site-title a,
#site-description {
color: #<?php echo get_header_textcolor(); ?>;
}
<?php endif; ?>
#headimg img {
max-width: 1000px;
height: auto;
width: 100%;
}
</style>
<?php
}
endif; // twentyeleven_admin_header_style()
if ( ! function_exists( 'twentyeleven_admin_header_image' ) ) :
/**
* Custom header image markup displayed on the Appearance > Header admin panel.
*
* Referenced via add_theme_support('custom-header') in twentyeleven_setup().
*
* @since Twenty Eleven 1.0
*/
function twentyeleven_admin_header_image() {
?>
<div id="headimg">
<?php
$color = get_header_textcolor();
$image = get_header_image();
$style = 'display: none;';
if ( $color && 'blank' !== $color ) {
$style = 'color: #' . $color . ';';
}
?>
<h1 class="displaying-header-text"><a id="name" style="<?php echo esc_attr( $style ); ?>" onclick="return false;" href="<?php echo esc_url( home_url( '/' ) ); ?>" tabindex="-1"><?php bloginfo( 'name' ); ?></a></h1>
<div id="desc" class="displaying-header-text" style="<?php echo esc_attr( $style ); ?>"><?php bloginfo( 'description' ); ?></div>
<?php if ( $image ) : ?>
<img src="<?php echo esc_url( $image ); ?>" alt="" />
<?php endif; ?>
</div>
<?php
}
endif; // twentyeleven_admin_header_image()
/**
* Set the post excerpt length to 40 words.
*
* To override this length in a child theme, remove
* the filter and add your own function tied to
* the excerpt_length filter hook.
*
* @since Twenty Eleven 1.0
*
* @param int $length The number of excerpt characters.
* @return int The filtered number of characters.
*/
function twentyeleven_excerpt_length( $length ) {
return 40;
}
add_filter( 'excerpt_length', 'twentyeleven_excerpt_length' );
if ( ! function_exists( 'twentyeleven_continue_reading_link' ) ) :
/**
* Return a "Continue Reading" link for excerpts
*
* @since Twenty Eleven 1.0
*
* @return string The "Continue Reading" HTML link.
*/
function twentyeleven_continue_reading_link() {
return ' <a href="' . esc_url( get_permalink() ) . '">' . __( 'Continue reading <span class="meta-nav">→</span>', 'twentyeleven' ) . '</a>';
}
endif; // twentyeleven_continue_reading_link()
/**
* Replace "[...]" in the Read More link with an ellipsis.
*
* The "[...]" is appended to automatically generated excerpts.
*
* To override this in a child theme, remove the filter and add your own
* function tied to the excerpt_more filter hook.
*
* @since Twenty Eleven 1.0
*
* @param string $more The Read More text.
* @return The filtered Read More text.
*/
function twentyeleven_auto_excerpt_more( $more ) {
if ( ! is_admin() ) {
return ' …' . twentyeleven_continue_reading_link();
}
return $more;
}
add_filter( 'excerpt_more', 'twentyeleven_auto_excerpt_more' );
/**
* Add a pretty "Continue Reading" link to custom post excerpts.
*
* To override this link in a child theme, remove the filter and add your own
* function tied to the get_the_excerpt filter hook.
*
* @since Twenty Eleven 1.0
*
* @param string $output The "Continue Reading" link.
* @return string The filtered "Continue Reading" link.
*/
function twentyeleven_custom_excerpt_more( $output ) {
if ( has_excerpt() && ! is_attachment() && ! is_admin() ) {
$output .= twentyeleven_continue_reading_link();
}
return $output;
}
add_filter( 'get_the_excerpt', 'twentyeleven_custom_excerpt_more' );
/**
* Show a home link for the wp_nav_menu() fallback, wp_page_menu().
*
* @since Twenty Eleven 1.0
*
* @param array $args The page menu arguments. @see wp_page_menu()
* @return array The filtered page menu arguments.
*/
function twentyeleven_page_menu_args( $args ) {
if ( ! isset( $args['show_home'] ) ) {
$args['show_home'] = true;
}
return $args;
}
add_filter( 'wp_page_menu_args', 'twentyeleven_page_menu_args' );
/**
* Register sidebars and widgetized areas.
*
* Also register the default Epherma widget.
*
* @since Twenty Eleven 1.0
*/
function twentyeleven_widgets_init() {
register_widget( 'Twenty_Eleven_Ephemera_Widget' );
register_sidebar(
array(
'name' => __( 'Main Sidebar', 'twentyeleven' ),
'id' => 'sidebar-1',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
)
);
register_sidebar(
array(
'name' => __( 'Showcase Sidebar', 'twentyeleven' ),
'id' => 'sidebar-2',
'description' => __( 'The sidebar for the optional Showcase Template', 'twentyeleven' ),
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
)
);
register_sidebar(
array(
'name' => __( 'Footer Area One', 'twentyeleven' ),
'id' => 'sidebar-3',
'description' => __( 'An optional widget area for your site footer', 'twentyeleven' ),
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
)
);
register_sidebar(
array(
'name' => __( 'Footer Area Two', 'twentyeleven' ),
'id' => 'sidebar-4',
'description' => __( 'An optional widget area for your site footer', 'twentyeleven' ),
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
)
);
register_sidebar(
array(
'name' => __( 'Footer Area Three', 'twentyeleven' ),
'id' => 'sidebar-5',
'description' => __( 'An optional widget area for your site footer', 'twentyeleven' ),
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
)
);
}
add_action( 'widgets_init', 'twentyeleven_widgets_init' );
if ( ! function_exists( 'twentyeleven_content_nav' ) ) :
/**
* Display navigation to next/previous pages when applicable.
*
* @since Twenty Eleven 1.0
*
* @param string $html_id The HTML id attribute.
*/
function twentyeleven_content_nav( $html_id ) {
global $wp_query;
if ( $wp_query->max_num_pages > 1 ) :
?>
<nav id="<?php echo esc_attr( $html_id ); ?>">
<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentyeleven' ); ?></h3>
<div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">←</span> Older posts', 'twentyeleven' ) ); ?></div>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?></div>
</nav><!-- #nav-above -->
<?php
endif;
}
endif; // twentyeleven_content_nav()
/**
* Return the first link from the post content. If none found, the
* post permalink is used as a fallback.
*
* @since Twenty Eleven 1.0
*
* @uses get_url_in_content() to get the first URL from the post content.
*
* @return string The first link.
*/
function twentyeleven_get_first_url() {
$content = get_the_content();
$has_url = function_exists( 'get_url_in_content' ) ? get_url_in_content( $content ) : false;
if ( ! $has_url ) {
$has_url = twentyeleven_url_grabber();
}
/** This filter is documented in wp-includes/link-template.php */
return ( $has_url ) ? $has_url : apply_filters( 'the_permalink', get_permalink() );
}
/**
* Return the URL for the first link found in the post content.
*
* @since Twenty Eleven 1.0
*
* @return string|bool URL or false when no link is present.
*/
function twentyeleven_url_grabber() {
if ( ! preg_match( '/<a\s[^>]*?href=[\'"](.+?)[\'"]/is', get_the_content(), $matches ) ) {
return false;
}
return esc_url_raw( $matches[1] );
}
/**
* Count the number of footer sidebars to enable dynamic classes for the footer.
*
* @since Twenty Eleven 1.0
*/
function twentyeleven_footer_sidebar_class() {
$count = 0;
if ( is_active_sidebar( 'sidebar-3' ) ) {
$count++;
}
if ( is_active_sidebar( 'sidebar-4' ) ) {
$count++;
}
if ( is_active_sidebar( 'sidebar-5' ) ) {
$count++;
}
$class = '';
switch ( $count ) {
case '1':
$class = 'one';
break;
case '2':
$class = 'two';
break;
case '3':
$class = 'three';
break;
}
if ( $class ) {
echo 'class="' . esc_attr( $class ) . '"';
}
}
if ( ! function_exists( 'twentyeleven_comment' ) ) :
/**
* Template for comments and pingbacks.
*
* To override this walker in a child theme without modifying the comments template
* simply create your own twentyeleven_comment(), and that function will be used instead.
*
* Used as a callback by wp_list_comments() for displaying the comments.
*
* @since Twenty Eleven 1.0
*
* @param object $comment The comment object.
* @param array $args An array of comment arguments. @see get_comment_reply_link()
* @param int $depth The depth of the comment.
*/
function twentyeleven_comment( $comment, $args, $depth ) {
$GLOBALS['comment'] = $comment;
switch ( $comment->comment_type ) :
case 'pingback':
case 'trackback':
?>
<li class="post pingback">
<p><?php _e( 'Pingback:', 'twentyeleven' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); ?></p>
<?php
break;
default:
?>
<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
<article id="comment-<?php comment_ID(); ?>" class="comment">
<footer class="comment-meta">
<div class="comment-author vcard">
<?php
$avatar_size = 68;
if ( '0' != $comment->comment_parent ) {
$avatar_size = 39;
}
echo get_avatar( $comment, $avatar_size );
printf(
/* translators: 1: Comment author, 2: Date and time. */
__( '%1$s on %2$s <span class="says">said:</span>', 'twentyeleven' ),
sprintf( '<span class="fn">%s</span>', get_comment_author_link() ),
sprintf(
'<a href="%1$s"><time datetime="%2$s">%3$s</time></a>',
esc_url( get_comment_link( $comment->comment_ID ) ),
get_comment_time( 'c' ),
/* translators: 1: Date, 2: Time. */
sprintf( __( '%1$s at %2$s', 'twentyeleven' ), get_comment_date(), get_comment_time() )
)
);
?>
<?php edit_comment_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); ?>
</div><!-- .comment-author .vcard -->
<?php
$commenter = wp_get_current_commenter();
if ( $commenter['comment_author_email'] ) {
$moderation_note = __( 'Your comment is awaiting moderation.', 'twentyeleven' );
} else {
$moderation_note = __( 'Your comment is awaiting moderation. This is a preview; your comment will be visible after it has been approved.', 'twentyeleven' );
}
?>
<?php if ( '0' == $comment->comment_approved ) : ?>
<em class="comment-awaiting-moderation"><?php echo $moderation_note; ?></em>
<br />
<?php endif; ?>
</footer>
<div class="comment-content"><?php comment_text(); ?></div>
<div class="reply">
<?php
comment_reply_link(
array_merge(
$args,
array(
'reply_text' => __( 'Reply <span>↓</span>', 'twentyeleven' ),
'depth' => $depth,
'max_depth' => $args['max_depth'],
)
)
);
?>
</div><!-- .reply -->
</article><!-- #comment-## -->
<?php
break;
endswitch;
}
endif; // twentyeleven_comment()
if ( ! function_exists( 'twentyeleven_posted_on' ) ) :
/**
* Print HTML with meta information for the current post-date/time and author.
*
* Create your own twentyeleven_posted_on to override in a child theme
*
* @since Twenty Eleven 1.0
*/
function twentyeleven_posted_on() {
printf(
/* translators: 1: The permalink, 2: Time, 3: Date and time, 4: Date and time, 5: Author posts, 6: Author post link text, 7: Author display name. */
__( '<span class="sep">Posted on </span><a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s">%4$s</time></a><span class="by-author"> <span class="sep"> by </span> <span class="author vcard"><a class="url fn n" href="%5$s" title="%6$s" rel="author">%7$s</a></span></span>', 'twentyeleven' ),
esc_url( get_permalink() ),
esc_attr( get_the_time() ),
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
/* translators: %s: Author display name. */
esc_attr( sprintf( __( 'View all posts by %s', 'twentyeleven' ), get_the_author() ) ),
get_the_author()
);
}
endif;
/**
* Add two classes to the array of body classes.
*
* The first is if the site has only had one author with published posts.
* The second is if a singular post being displayed
*
* @since Twenty Eleven 1.0
*
* @param array $classes Existing body classes.
* @return array The filtered array of body classes.
*/
function twentyeleven_body_classes( $classes ) {
if ( function_exists( 'is_multi_author' ) && ! is_multi_author() ) {
$classes[] = 'single-author';
}
if ( is_singular() && ! is_home() && ! is_page_template( 'showcase.php' ) && ! is_page_template( 'sidebar-page.php' ) ) {
$classes[] = 'singular';
}
return $classes;
}
add_filter( 'body_class', 'twentyeleven_body_classes' );
/**
* Retrieve the IDs for images in a gallery.
*
* @uses get_post_galleries() First, if available. Falls back to shortcode parsing,
* then as last option uses a get_posts() call.
*
* @since Twenty Eleven 1.6
*
* @return array List of image IDs from the post gallery.
*/
function twentyeleven_get_gallery_images() {
$images = array();
if ( function_exists( 'get_post_galleries' ) ) {
$galleries = get_post_galleries( get_the_ID(), false );
if ( isset( $galleries[0]['ids'] ) ) {
$images = explode( ',', $galleries[0]['ids'] );
}
} else {
$pattern = get_shortcode_regex();
preg_match( "/$pattern/s", get_the_content(), $match );
$atts = shortcode_parse_atts( $match[3] );
if ( isset( $atts['ids'] ) ) {
$images = explode( ',', $atts['ids'] );
}
}
if ( ! $images ) {
$images = get_posts(
array(
'fields' => 'ids',
'numberposts' => 999,
'order' => 'ASC',
'orderby' => 'menu_order',
'post_mime_type' => 'image',
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
)
);
}
return $images;
}
/**
* Modifies tag cloud widget arguments to display all tags in the same font size
* and use list format for better accessibility.
*
* @since Twenty Eleven 2.7
*
* @param array $args Arguments for tag cloud widget.
* @return array The filtered arguments for tag cloud widget.
*/
function twentyeleven_widget_tag_cloud_args( $args ) {
$args['largest'] = 22;
$args['smallest'] = 8;
$args['unit'] = 'pt';
$args['format'] = 'list';
return $args;
}
add_filter( 'widget_tag_cloud_args', 'twentyeleven_widget_tag_cloud_args' );
if ( ! function_exists( 'wp_body_open' ) ) :
/**
* Fire the wp_body_open action.
*
* Added for backward compatibility to support pre-5.2.0 WordPress versions.
*
* @since Twenty Eleven 3.3
*/
function wp_body_open() {
/**
* Triggered after the opening <body> tag.
*
* @since Twenty Eleven 3.3
*/
do_action( 'wp_body_open' );
}
endif;
/**
* Include a skip to content link at the top of the page so that users can bypass the menu.
*
* @since Twenty Eleven 3.4
*/
function twentyeleven_skip_link() {
echo '<div class="skip-link"><a class="assistive-text" href="#content">' . esc_html__( 'Skip to primary content', 'twentyeleven' ) . '</a></div>';
if ( ! is_singular() ) {
echo '<div class="skip-link"><a class="assistive-text" href="#secondary">' . esc_html__( 'Skip to secondary content', 'twentyeleven' ) . '</a></div>';
}
}
add_action( 'wp_body_open', 'twentyeleven_skip_link', 5 );
|
{
"pile_set_name": "Github"
}
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.scalaxb</groupId>
<artifactId>itp02-noop</artifactId>
<version>0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>@project.groupId@</groupId>
<artifactId>@project.artifactId@</artifactId>
<version>@project.version@</version>
<executions>
<execution>
<id>scalaxb</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.GlobalFlowStateAnalysis
{
using GlobalFlowStateAnalysisData = DictionaryAnalysisData<AnalysisEntity, GlobalFlowStateAnalysisValueSet>;
/// <summary>
/// Result from execution of <see cref="GlobalFlowStateAnalysis"/> on a basic block.
/// It store GlobalFlowState value at the start and end of the basic block.
/// </summary>
internal sealed class GlobalFlowStateBlockAnalysisResult : AbstractBlockAnalysisResult
{
internal GlobalFlowStateBlockAnalysisResult(BasicBlock basicBlock, GlobalFlowStateAnalysisData blockAnalysisData)
: base(basicBlock)
{
Data = blockAnalysisData?.ToImmutableDictionary() ?? ImmutableDictionary<AnalysisEntity, GlobalFlowStateAnalysisValueSet>.Empty;
}
public ImmutableDictionary<AnalysisEntity, GlobalFlowStateAnalysisValueSet> Data { get; }
}
}
|
{
"pile_set_name": "Github"
}
|
#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif
#ifndef __MIOVERLAY_H
#define __MIOVERLAY_H
typedef void (*miOverlayTransFunc) (ScreenPtr, int, BoxPtr);
typedef Bool (*miOverlayInOverlayFunc) (WindowPtr);
extern _X_EXPORT Bool
miInitOverlay(ScreenPtr pScreen,
miOverlayInOverlayFunc inOverlay, miOverlayTransFunc trans);
extern _X_EXPORT Bool
miOverlayGetPrivateClips(WindowPtr pWin,
RegionPtr *borderClip, RegionPtr *clipList);
extern _X_EXPORT Bool miOverlayCollectUnderlayRegions(WindowPtr, RegionPtr *);
extern _X_EXPORT void miOverlayComputeCompositeClip(GCPtr, WindowPtr);
extern _X_EXPORT Bool miOverlayCopyUnderlay(ScreenPtr);
extern _X_EXPORT void miOverlaySetTransFunction(ScreenPtr, miOverlayTransFunc);
extern _X_EXPORT void miOverlaySetRootClip(ScreenPtr, Bool);
#endif /* __MIOVERLAY_H */
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import "TBulkRenameFormatterController.h"
@class NSPopUpButton, NSTextField;
@interface TBulkRenameAddTextController : TBulkRenameFormatterController
{
NSPopUpButton *_whereBtn;
NSTextField *_textToAddFld;
struct TNotificationCenterObserver _textToAddTextDidChangeObserver;
}
- (id).cxx_construct;
- (void).cxx_destruct;
- (id)reformat:(id)arg1 row:(unsigned long long)arg2;
- (void)whereChanged:(id)arg1;
- (_Bool)resetCounterForEachFile;
- (_Bool)allowRename;
- (id)displayName;
- (int)formatterType;
- (void)aboutToTearDown;
- (void)viewLoaded;
@end
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the
* @author tags. See the copyright.txt file in the distribution for a full
* listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package org.zanata.model;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PostPersist;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.FieldBridge;
import org.hibernate.search.annotations.SortableField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zanata.hibernate.search.DateBridge;
import com.google.common.annotations.VisibleForTesting;
@EntityListeners({ ModelEntityBase.EntityListener.class })
@MappedSuperclass
public class ModelEntityBase implements Serializable {
private static final org.slf4j.Logger log =
org.slf4j.LoggerFactory.getLogger(ModelEntityBase.class);
private static final long serialVersionUID = -6139220551322868743L;
protected Long id;
protected Date creationDate;
protected Date lastChanged;
protected Integer versionNum;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
@VisibleForTesting
protected void setId(Long id) {
this.id = id;
}
@Version
@Column(nullable = false)
public Integer getVersionNum() {
return versionNum;
}
public void setVersionNum(Integer versionNum) {
this.versionNum = versionNum;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false)
public Date getCreationDate() {
return creationDate != null ? new Date(creationDate.getTime()) :
null;
}
public void setCreationDate(Date creationDate) {
this.creationDate =
creationDate != null ? new Date(creationDate.getTime()) :
null;
}
// TODO extract lastChanged from ModelEntityBase and use with @Embedded
// NB: also used in HSimpleComment
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false)
@Field(analyze = Analyze.NO)
@FieldBridge(impl = DateBridge.class)
@SortableField
public Date getLastChanged() {
return lastChanged != null ? new Date(lastChanged.getTime()) :
null;
}
public void setLastChanged(Date lastChanged) {
this.lastChanged =
lastChanged != null ? new Date(lastChanged.getTime()) :
null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (getCreationDate() != null ? getCreationDate().hashCode() : 0);
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + (getLastChanged() != null ? getLastChanged().hashCode() : 0);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
// Subclasses *must* override equals to check that their class is a
// match for the object they are comparing. Simple comparison of the
// result of getClass() is not possible here because the compared object
// may be a Hibernate proxy. Hibernate proxies are a subclass of the
// class that they are proxying.
assert overridesEquals(this);
assert overridesEquals(obj);
ModelEntityBase other = (ModelEntityBase) obj;
if (!Objects.equals(getCreationDate(), other.getCreationDate()))
return false;
if (getId() == null) {
if (other.getId() != null)
return false;
} else if (!getId().equals(other.getId()))
return false;
if (!Objects.equals(getLastChanged(), other.getLastChanged()))
return false;
return true;
}
private boolean overridesEquals(Object obj) {
try {
obj.getClass().getDeclaredMethod("equals", Object.class);
return true;
} catch (NoSuchMethodException e) {
log.error("class does not override equals: {}", obj.getClass(), e);
return false;
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "@"
+ Integer.toHexString(hashCode()) + "[id=" + id + ",versionNum="
+ versionNum + "]";
}
protected boolean logPersistence() {
return true;
}
public static class EntityListener {
@PrePersist
private void onPersist(ModelEntityBase meb) {
Date now = new Date();
if (meb.creationDate == null) {
meb.creationDate = now;
}
if (meb.lastChanged == null) {
meb.lastChanged = now;
}
}
@PostPersist
private void postPersist(ModelEntityBase meb) {
if (meb.logPersistence()) {
Logger log = LoggerFactory.getLogger(meb.getClass());
log.info("persist entity: {}", meb);
}
}
@PreUpdate
private void onUpdate(ModelEntityBase meb) {
meb.lastChanged = new Date();
}
@PreRemove
private void onRemove(ModelEntityBase meb) {
if (meb.logPersistence()) {
Logger log = LoggerFactory.getLogger(meb.getClass());
log.info("remove entity: {}", meb);
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./cstyle").FoldMode;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
/**
* Inheriting cstyle folding because it handles the region comment folding
* and special block comment folding appropriately.
*
* Cstyle's getCommentRegionBlock() contains the sql comment characters '--' for end region block.
*/
this.foldingStartMarker = /(\bCASE\b|\bBEGIN\b)|^\s*(\/\*)/i;
// this.foldingStopMarker = /(\bEND\b)|^[\s\*]*(\*\/)/i;
this.startRegionRe = /^\s*(\/\*|--)#?region\b/;
this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
var line = session.getLine(row);
if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1]) return this.getBeginEndBlock(session, row, i, match[1]);
var range = session.getCommentFoldRange(row, i + match[0].length, 1);
if (range && !range.isMultiLine()) {
if (forceMultiline) {
range = this.getSectionRange(session, row);
}
else if (foldStyle != "all") range = null;
}
return range;
}
if (foldStyle === "markbegin") return;
//TODO: add support for end folding markers
return;
};
/**
* @returns {range} folding block for sequence that starts with 'CASE' or 'BEGIN' and ends with 'END'
* @param {string} matchSequence - the sequence of charaters that started the fold widget, which should remain visible when the fold widget is folded
*/
this.getBeginEndBlock = function(session, row, column, matchSequence) {
var start = {
row: row,
column: column + matchSequence.length
};
var maxRow = session.getLength();
var line;
var depth = 1;
var re = /(\bCASE\b|\bBEGIN\b)|(\bEND\b)/i;
while (++row < maxRow) {
line = session.getLine(row);
var m = re.exec(line);
if (!m) continue;
if (m[1]) depth++;
else depth--;
if (!depth) break;
}
var endRow = row;
if (endRow > start.row) {
return new Range(start.row, start.column, endRow, line.length);
}
};
}).call(FoldMode.prototype);
});
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* Copyright (c) 2015, 2018 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
package org.openj9.test.jsr335.interfacePrivateMethod;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_ABSTRACT;
import static org.objectweb.asm.Opcodes.ACC_INTERFACE;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ARETURN;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.V1_8;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
/* This class is used to generate bytecodes for the required interfaces from their respective ASM dumps, and return the bytecodes to
* the calling classloaders in the form of byte arrays.
*
* The method makeClassFile returns as byte array the bytecodes for interface ITest
*/
public class GenerateInterfaceFromASM {
public static byte[] makeClassFile () {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
MethodVisitor mv;
cw.visit(V1_8, ACC_ABSTRACT + ACC_INTERFACE, "ITest", null, "java/lang/Object", null);
{
mv = cw.visitMethod(ACC_PRIVATE + ACC_STATIC, "private_static_method", "()Ljava/lang/String;", null, null);
mv.visitCode();
mv.visitLdcInsn("private_static_method");
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 0);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PRIVATE, "private_non_static_method", "()Ljava/lang/String;", null, null);
mv.visitCode();
mv.visitLdcInsn("private_non_static_method");
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "RunTest_private_static_method_with_InvokeStatic", "()Ljava/lang/String;", null, null);
mv.visitCode();
mv.visitMethodInsn(INVOKESTATIC, "ITest", "private_static_method", "()Ljava/lang/String;", true);
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 0);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "RunTest_private_non_static_method_with_InvokeStatic", "()Ljava/lang/String;", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, "ITest", "private_non_static_method", "()Ljava/lang/String;", true);
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "RunTest_private_static_method_with_InvokeVirtual", "(LITest;)Ljava/lang/String;", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, "ITest", "private_static_method", "()Ljava/lang/String;", false);
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "RunTest_private_non_static_method_with_InvokeVirtual", "(LITest;)Ljava/lang/String;", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, "ITest", "private_non_static_method", "()Ljava/lang/String;", false);
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 2);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "RunTest_private_static_method_with_InvokeSpecial", "(LITest;)Ljava/lang/String;", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "ITest", "private_static_method", "()Ljava/lang/String;", true);
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "RunTest_private_non_static_method_with_InvokeSpecial", "(LITest;)Ljava/lang/String;", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "ITest", "private_non_static_method", "()Ljava/lang/String;", true);
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 2);
mv.visitEnd();
}
cw.visitInnerClass("java/lang/invoke/MethodHandles$Lookup", "java/lang/invoke/MethodHandles", "Lookup", ACC_PUBLIC + ACC_FINAL + ACC_STATIC);
{
mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "getLookup", "()Ljava/lang/invoke/MethodHandles$Lookup;", null, null);
mv.visitCode();
mv.visitMethodInsn(INVOKESTATIC, "java/lang/invoke/MethodHandles", "lookup", "()Ljava/lang/invoke/MethodHandles$Lookup;", false);
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
cw.visitEnd();
return cw.toByteArray();
}
}
|
{
"pile_set_name": "Github"
}
|
// Normally sequences are evaluated lazily. In this case,
// the sequence is created from a list, which is not evaluated
// lazily. Therefore, without Seq.delay, the elements would be
// evaluated at the time of the call to makeSequence.
let makeSequence function1 maxNumber = Seq.delay (fun () ->
let rec loop n acc =
printfn "Evaluating %d." n
match n with
| 0 -> acc
| n -> (function1 n) :: loop (n - 1) acc
loop maxNumber []
|> Seq.ofList)
printfn "Calling makeSequence."
let seqSquares = makeSequence (fun x -> x * x) 4
let seqCubes = makeSequence (fun x -> x * x * x) 4
printfn "Printing sequences."
printfn "Squares:"
seqSquares |> Seq.iter (fun x -> printf "%d " x)
printfn "\nCubes:"
seqCubes |> Seq.iter (fun x -> printf "%d " x)
|
{
"pile_set_name": "Github"
}
|
{
"images": [
{
"filename": "ic_fluent_communication_24_filled.pdf",
"idiom": "universal"
}
],
"info": {
"author": "xcode",
"version": 1
},
"properties": {
"preserves-vector-representation": true,
"template-rendering-intent": "template"
}
}
|
{
"pile_set_name": "Github"
}
|
---
title: "Update externalitem"
description: "Update the properties of an externalitem."
localization_priority: Normal
author: "snlraju-msft"
ms.prod: "search"
doc_type: "apiPageType"
---
# Update externalitem
Namespace: microsoft.graph
[!INCLUDE [beta-disclaimer](../../includes/beta-disclaimer.md)]
Update the properties of an [externalitem](../resources/externalitem.md).
[!INCLUDE [search-api-preview](../../includes/search-api-preview-signup.md)]
## Permissions
One of the following permissions is required to call this API. To learn more, including how to choose permissions, see [Permissions](/graph/permissions-reference).
| Permission type | Permissions (from least to most privileged) |
|:---------------------------------------|:--------------------------------------------|
| Delegated (work or school account) | Not supported. |
| Delegated (personal Microsoft account) | Not supported. |
| Application | ExternalItem.ReadWrite.All |
## HTTP request
<!-- { "blockType": "ignored" } -->
```http
PATCH /external/connections/{connection-id}/items/{item-id}
```
## Path parameters
| Parameter | Type | Description |
|:--------------|:-------|:----------------------------------------------------|
| connection-id | string | The `id` property of the containing [externalConnection](../resources/externalconnection.md) |
| item-id | string | The developer-provided `id` property of the [externalItem](../resources/externalitem.md). |
## Request headers
| Name | Description |
|:--------------|:----------------------------|
| Authorization | Bearer {token}. Required. |
| Content-Type | application/json. Required. |
## Request body
In the request body, supply the values for relevant fields that should be updated. Existing properties (excluding properties inside the `properties` object) that are not included in the request body will maintain their previous values or be recalculated based on changes to other property values. For best performance, don't include existing values that haven't changed. The following properties can be updated.
| Property | Type | Description |
|:-----------|:--------------------------------------|:--------------------------|
| acl | [acl](../resources/acl.md) collection | An array of access control entries. Each entry specifies the access granted to a user or group. |
| content | [externalItemContent](../resources/externalitemcontent.md) | A plain-text representation of the contents of the item. The text in this property is full-text indexed. |
| properties | Object | A property bag with the properties of the item. The properties MUST conform to the [schema](../resources/schema.md) defined for the [externalConnection](../resources/externalconnection.md). |
### Updating the acl collection
If the `acl` property is included in an update request, the existing ACL collection is overwritten with the collection included in the request.
### Updating the properties object
If the `properties` property is included in an update request, the existing property bag is overwritten with the value included in the request.
## Response
If successful, this method returns a `200 OK` response code and an updated [externalItem](../resources/externalitem.md) object in the response body.
## Examples
### Request
The following is an example of the request.
# [HTTP](#tab/http)
<!-- {
"blockType": "request",
"name": "update_externalitem"
}-->
```http
PATCH https://graph.microsoft.com/beta/connections/contosohr/items/TSP228082938
Content-type: application/json
{
"acl": [
{
"type": "everyone",
"value": "67a141d8-cf4e-4528-ba07-bed21bfacd2d",
"accessType": "grant",
"identitySource": "azureActiveDirectory"
}
]
}
```
# [C#](#tab/csharp)
[!INCLUDE [sample-code](../includes/snippets/csharp/update-externalitem-csharp-snippets.md)]
[!INCLUDE [sdk-documentation](../includes/snippets/snippets-sdk-documentation-link.md)]
# [JavaScript](#tab/javascript)
[!INCLUDE [sample-code](../includes/snippets/javascript/update-externalitem-javascript-snippets.md)]
[!INCLUDE [sdk-documentation](../includes/snippets/snippets-sdk-documentation-link.md)]
# [Objective-C](#tab/objc)
[!INCLUDE [sample-code](../includes/snippets/objc/update-externalitem-objc-snippets.md)]
[!INCLUDE [sdk-documentation](../includes/snippets/snippets-sdk-documentation-link.md)]
---
<!-- markdownlint-disable MD024 -->
### Response
<!-- markdownlint-enable MD024 -->
The following is an example of the response.
<!-- {
"blockType": "response",
"truncated": true,
"@odata.type": "microsoft.graph.externalItem"
} -->
```http
HTTP/1.1 200 OK
Content-type: application/json
{
"id": "TSP228082938",
"acl": [
{
"type": "user",
"value": "49103559-feac-4575-8b94-254814dfca72",
"accessType": "grant",
"identitySource": "azureActiveDirectory"
}
],
"properties": {
"title": "Error in the payment gateway",
"priority": 1,
"assignee": "john@contoso.com"
},
"content": {
"value": "<h1>Error in payment gateway</h1><p>Error details...</p>",
"type": "html"
}
}
```
<!-- uuid: 16cd6b66-4b1a-43a1-adaf-3a886856ed98
2019-02-04 14:57:30 UTC -->
<!-- {
"type": "#page.annotation",
"description": "Update externalitem",
"keywords": "",
"section": "documentation",
"tocPath": "",
"suppressions": [
"Error: update_externalitem/properties:\r\n Referenced type microsoft.graph.object is not defined in the doc set! Potential suggestion: microsoft.graph.directoryObject"
]
}-->
|
{
"pile_set_name": "Github"
}
|
using System.Reflection;
using System.Runtime.InteropServices;
// [assembly: AssemblyTitle("sfml-system")]
//[assembly: AssemblyDescription("System module of the SFML library")]
[assembly: Guid("f0cec342-7361-41cd-acb4-7ef2461af7f0")]
|
{
"pile_set_name": "Github"
}
|
/*
Copyright (C) GridGain Systems. All Rights Reserved.
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 org.gridgain.grid.kernal.ggfs.hadoop;
import org.apache.commons.logging.*;
import org.gridgain.grid.*;
import org.gridgain.grid.kernal.ggfs.common.*;
import org.jetbrains.annotations.*;
import java.io.*;
/**
* GGFS Hadoop output stream implementation.
*/
public class GridGgfsHadoopOutputStream extends OutputStream implements GridGgfsHadoopStreamEventListener {
/** Log instance. */
private Log log;
/** Client logger. */
private GridGgfsLogger clientLog;
/** Log stream ID. */
private long logStreamId;
/** Server stream delegate. */
private GridGgfsHadoopStreamDelegate delegate;
/** Closed flag. */
private volatile boolean closed;
/** Flag set if stream was closed due to connection breakage. */
private boolean connBroken;
/** Error message. */
private volatile String errMsg;
/** Read time. */
private long writeTime;
/** User time. */
private long userTime;
/** Last timestamp. */
private long lastTs;
/** Amount of written bytes. */
private long total;
/**
* Creates light output stream.
*
* @param delegate Server stream delegate.
* @param log Logger to use.
* @param clientLog Client logger.
*/
public GridGgfsHadoopOutputStream(GridGgfsHadoopStreamDelegate delegate, Log log,
GridGgfsLogger clientLog, long logStreamId) {
this.delegate = delegate;
this.log = log;
this.clientLog = clientLog;
this.logStreamId = logStreamId;
lastTs = System.nanoTime();
delegate.hadoop().addEventListener(delegate, this);
}
/**
* Read start.
*/
private void writeStart() {
long now = System.nanoTime();
userTime += now - lastTs;
lastTs = now;
}
/**
* Read end.
*/
private void writeEnd() {
long now = System.nanoTime();
writeTime += now - lastTs;
lastTs = now;
}
/** {@inheritDoc} */
@Override public void write(@NotNull byte[] b, int off, int len) throws IOException {
check();
writeStart();
try {
delegate.hadoop().writeData(delegate, b, off, len);
total += len;
}
finally {
writeEnd();
}
}
/** {@inheritDoc} */
@Override public void write(int b) throws IOException {
write(new byte[] {(byte)b});
total++;
}
/** {@inheritDoc} */
@Override public void flush() throws IOException {
delegate.hadoop().flush(delegate);
}
/** {@inheritDoc} */
@Override public void close() throws IOException {
if (!closed) {
if (log.isDebugEnabled())
log.debug("Closing output stream: " + delegate);
writeStart();
delegate.hadoop().closeStream(delegate);
markClosed(false);
writeEnd();
if (clientLog.isLogEnabled())
clientLog.logCloseOut(logStreamId, userTime, writeTime, total);
if (log.isDebugEnabled())
log.debug("Closed output stream [delegate=" + delegate + ", writeTime=" + writeTime / 1000 +
", userTime=" + userTime / 1000 + ']');
}
else if(connBroken)
throw new IOException(
"Failed to close stream, because connection was broken (data could have been lost).");
}
/**
* Marks stream as closed.
*
* @param connBroken {@code True} if connection with server was lost.
*/
private void markClosed(boolean connBroken) {
// It is ok to have race here.
if (!closed) {
closed = true;
delegate.hadoop().removeEventListener(delegate);
this.connBroken = connBroken;
}
}
/**
* @throws IOException If check failed.
*/
private void check() throws IOException {
String errMsg0 = errMsg;
if (errMsg0 != null)
throw new IOException(errMsg0);
if (closed) {
if (connBroken)
throw new IOException("Server connection was lost.");
else
throw new IOException("Stream is closed.");
}
}
/** {@inheritDoc} */
@Override public void onClose() throws GridException {
markClosed(true);
}
/** {@inheritDoc} */
@Override public void onError(String errMsg) {
this.errMsg = errMsg;
}
}
|
{
"pile_set_name": "Github"
}
|
<component name="libraryTable">
<library name="Maven: org.json:json:20160810">
<CLASSES>
<root url="jar://$USER_HOME$/.m2/repository/org/json/json/20160810/json-20160810.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$USER_HOME$/.m2/repository/org/json/json/20160810/json-20160810-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$USER_HOME$/.m2/repository/org/json/json/20160810/json-20160810-sources.jar!/" />
</SOURCES>
</library>
</component>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2014 Google Inc.
*
* 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 com.google.caliper.bridge;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.io.BaseEncoding;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Serializes and deserializes {@link WorkerRequest}s as base64 encoded strings so they can be
* passed on the command line to the worker.
*
* <p>Java serialization is a appropriate in this use-case because there are no compatibility
* concerns. The messages encoded/decoded by this class are only used to communicate with another
* JVM that is running with the same version of the java classes. Also, it should be lighter weight
* and faster than other common serialization solutions.
*/
public final class CommandLineSerializer {
private CommandLineSerializer() {}
/** Returns the given serializable object as a base64 encoded String. */
public static String render(WorkerRequest message) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try {
ObjectOutputStream out = new ObjectOutputStream(bytes);
out.writeObject(message);
out.close();
return BaseEncoding.base64().encode(bytes.toByteArray());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** Parses the given base64 encoded string as an object of the given type. */
public static WorkerRequest parse(String arg) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(BaseEncoding.base64().decode(arg));
ObjectInputStream in = new ObjectInputStream(bais);
WorkerRequest instance = (WorkerRequest) in.readObject();
in.close();
checkState(bais.read() == -1, "Message %s contains more than one object.", arg);
return instance;
} catch (IOException e) {
throw new RuntimeException(e); // assertion error?
} catch (ClassNotFoundException e) {
throw new RuntimeException("cannot decode message", e);
}
}
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Emojicode: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Emojicode
 <span id="projectnumber">0.6</span>
</div>
<div id="projectbrief">World’s only programming language that’s bursting with emojis</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.14 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespace_emojicode_compiler.html">EmojicodeCompiler</a></li><li class="navelem"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_operator_assignment.html">ASTOperatorAssignment</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">EmojicodeCompiler::ASTOperatorAssignment Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="class_emojicode_compiler_1_1_a_s_t_operator_assignment.html">EmojicodeCompiler::ASTOperatorAssignment</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>AccessesAnyVariable</b>(std::u32string name) (defined in <a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">explicit</span><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>AccessesAnyVariable</b>(bool inInstanceScope, VariableID id, Type type) (defined in <a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>analyse</b>(FunctionAnalyser *analyser) override (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_assignment.html">EmojicodeCompiler::ASTVariableAssignment</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_assignment.html">EmojicodeCompiler::ASTVariableAssignment</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>analyseMemoryFlow</b>(MFFunctionAnalyser *analyser) override (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_assignment.html">EmojicodeCompiler::ASTVariableAssignment</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_assignment.html">EmojicodeCompiler::ASTVariableAssignment</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ASTNode</b>(SourcePosition p) (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_statement.html">EmojicodeCompiler::ASTStatement</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_statement.html">EmojicodeCompiler::ASTStatement</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">explicit</span><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>ASTNode</b>(SourcePosition p) (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_node.html">EmojicodeCompiler::ASTNode</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_node.html">EmojicodeCompiler::ASTNode</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">explicit</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ASTOperatorAssignment</b>(std::u32string name, const std::shared_ptr< ASTExpr > &e, const SourcePosition &p, OperatorType opType) (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_operator_assignment.html">EmojicodeCompiler::ASTOperatorAssignment</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_operator_assignment.html">EmojicodeCompiler::ASTOperatorAssignment</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>ASTVariableAssignment</b>(std::u32string name, const std::shared_ptr< ASTExpr > &e, const SourcePosition &p) (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_assignment.html">EmojicodeCompiler::ASTVariableAssignment</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_assignment.html">EmojicodeCompiler::ASTVariableAssignment</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ASTVariableAssignment</b>(std::u32string name, const std::shared_ptr< ASTExpr > &e, const SourcePosition &p, bool declare) (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_assignment.html">EmojicodeCompiler::ASTVariableAssignment</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_assignment.html">EmojicodeCompiler::ASTVariableAssignment</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>ASTVariableInit</b>(std::shared_ptr< ASTExpr > e, const SourcePosition &p, std::u32string name, bool declare) (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_init.html">EmojicodeCompiler::ASTVariableInit</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_init.html">EmojicodeCompiler::ASTVariableInit</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>expr_</b> (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_init.html">EmojicodeCompiler::ASTVariableInit</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_init.html">EmojicodeCompiler::ASTVariableInit</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>generateAssignment</b>(FunctionCodeGenerator *) const final (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_assignment.html">EmojicodeCompiler::ASTVariableAssignment</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_assignment.html">EmojicodeCompiler::ASTVariableAssignment</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>id</b>() const (defined in <a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>inInstanceScope</b>() const (defined in <a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html#ab6cbc14d63d7879377041cc1161c18d0">instanceVariablePointer</a>(FunctionCodeGenerator *fg) const</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>managementValue</b>(FunctionCodeGenerator *fg) const (defined in <a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html#afe3e418c36141428ba9476009311a851">name</a>() const</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>paragraph</b>() const (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_statement.html">EmojicodeCompiler::ASTStatement</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_statement.html">EmojicodeCompiler::ASTStatement</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>paragraph_</b> (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_statement.html">EmojicodeCompiler::ASTStatement</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_statement.html">EmojicodeCompiler::ASTStatement</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_node.html#a169020f6c66090c16b98247e339ac255">position</a>() const</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_node.html">EmojicodeCompiler::ASTNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html#abf406155e5b21853253c0c14a1401f89">release</a>(FunctionCodeGenerator *fg) const</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>setParagraph</b>() (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_statement.html">EmojicodeCompiler::ASTStatement</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_statement.html">EmojicodeCompiler::ASTStatement</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>setVariableAccess</b>(const ResolvedVariable &var, FunctionAnalyser *analyser) (defined in <a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_operator_assignment.html#abe0d26532f02be5013cdb0dac10f982a">toCode</a>(PrettyStream &pretty) const override</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_operator_assignment.html">EmojicodeCompiler::ASTOperatorAssignment</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_init.html#a290d0da58280e5d04b8eb57624021d94">variablePointer</a>(FunctionCodeGenerator *fg) const</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_variable_init.html">EmojicodeCompiler::ASTVariableInit</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>variableType</b>() const (defined in <a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_accesses_any_variable.html">EmojicodeCompiler::AccessesAnyVariable</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>~ASTNode</b>()=default (defined in <a class="el" href="class_emojicode_compiler_1_1_a_s_t_node.html">EmojicodeCompiler::ASTNode</a>)</td><td class="entry"><a class="el" href="class_emojicode_compiler_1_1_a_s_t_node.html">EmojicodeCompiler::ASTNode</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.14
</small></address>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
/*
C++ Big Integer Library
(see ChangeLog for version)
http://mattmccutchen.net/bigint/
Written and maintained by Matt McCutchen <matt@mattmccutchen.net>
Legal
-----
I, Matt McCutchen, the sole author of the original Big Integer Library, waive my
copyright to it, placing it in the public domain. The library comes with
absolutely no warranty.
*/
// This header file includes all of the library header files.
#include "NumberlikeArray.hh"
#include "BigUnsigned.hh"
#include "BigInteger.hh"
#include "BigIntegerAlgorithms.hh"
#include "BigUnsignedInABase.hh"
#include "BigIntegerUtils.hh"
|
{
"pile_set_name": "Github"
}
|
The default is to install the binary and man page into /usr and to look for
the global config in /etc.
If you wish to install entirely into /usr/local, do the following:
make PREFIX=/usr/local CONF=/usr/local/etc/ondirrc install
To install to a "package root" do this:
make DESTDIR=/tmp/ondir.pkg install
Once you have installed OnDir, add either scripts.sh or scripts.tcsh to your
startup. This will execute ondir whenever you change directories at the shell.
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Nexmo Client Library for PHP
*
* @copyright Copyright (c) 2016 Nexmo, Inc. (http://nexmo.com)
* @license https://github.com/Nexmo/nexmo-php/blob/master/LICENSE.txt MIT License
*/
namespace Nexmo\Call;
use Nexmo\Client\ClientAwareInterface;
use Nexmo\Client\ClientAwareTrait;
use Nexmo\Conversations\Conversation;
use Nexmo\Entity\EntityInterface;
use Nexmo\Entity\JsonResponseTrait;
use Nexmo\Entity\JsonSerializableTrait;
use Nexmo\Entity\JsonUnserializableInterface;
use Nexmo\Entity\NoRequestResponseTrait;
use Psr\Http\Message\ResponseInterface;
use Nexmo\Client\Exception;
use Zend\Diactoros\Request;
/**
* Class Call
*
* @property \Nexmo\Call\Stream $stream
* @property \Nexmo\Call\Talk $talk
* @property \Nexmo\Call\Dtmf $dtmf
*
* @method \Nexmo\Call\Stream stream()
* @method \Nexmo\Call\Talk talk()
* @method \Nexmo\Call\Dtmf dtmf()
*/
class Call implements EntityInterface, \JsonSerializable, JsonUnserializableInterface, ClientAwareInterface
{
use NoRequestResponseTrait;
use JsonSerializableTrait;
use JsonResponseTrait;
use ClientAwareTrait;
const WEBHOOK_ANSWER = 'answer';
const WEBHOOK_EVENT = 'event';
const TIMER_LENGTH = 'length';
const TIMER_RINGING = 'ringing';
const TIMEOUT_MACHINE = 'machine';
protected $id;
protected $to;
protected $from;
/**
* @var Webhook[]
*/
protected $webhooks = [];
protected $data = [];
protected $subresources = [];
public function __construct($id = null)
{
$this->id = $id;
}
public function get()
{
$request = new Request(
$this->getClient()->getApiUrl() . Collection::getCollectionPath() . '/' . $this->getId()
,'GET'
);
$response = $this->getClient()->send($request);
if($response->getStatusCode() != '200'){
throw $this->getException($response);
}
$data = json_decode($response->getBody()->getContents(), true);
$this->jsonUnserialize($data);
return $this;
}
protected function getException(ResponseInterface $response)
{
$body = json_decode($response->getBody()->getContents(), true);
$status = $response->getStatusCode();
if($status >= 400 AND $status < 500) {
$e = new Exception\Request($body['error_title'], $status);
} elseif($status >= 500 AND $status < 600) {
$e = new Exception\Server($body['error_title'], $status);
} else {
$e = new Exception\Exception('Unexpected HTTP Status Code');
}
return $e;
}
public function put($payload)
{
$request = new Request(
$this->getClient()->getApiUrl() . Collection::getCollectionPath() . '/' . $this->getId()
,'PUT',
'php://temp',
['content-type' => 'application/json']
);
$request->getBody()->write(json_encode($payload));
$response = $this->client->send($request);
$responseCode = $response->getStatusCode();
if($responseCode != '200' && $responseCode != '204'){
throw $this->getException($response);
}
return $this;
}
public function getId()
{
return $this->id;
}
public function setTo($endpoint)
{
if(!($endpoint instanceof Endpoint)){
$endpoint = new Endpoint($endpoint);
}
$this->to = $endpoint;
return $this;
}
/**
* @return Endpoint
*/
public function getTo()
{
if($this->lazyLoad()){
return new Endpoint($this->data['to']['number'], $this->data['to']['type']);
}
return $this->to;
}
public function setFrom($endpoint)
{
if(!($endpoint instanceof Endpoint)){
$endpoint = new Endpoint($endpoint);
}
$this->from = $endpoint;
return $this;
}
/**
* @return Endpoint
*/
public function getFrom()
{
if($this->lazyLoad()){
return new Endpoint($this->data['from']['number'], $this->data['from']['type']);
}
return $this->from;
}
public function setWebhook($type, $url = null, $method = null)
{
if($type instanceof Webhook){
$this->webhooks[$type->getType()] = $type;
return $this;
}
if(is_null($url)){
throw new \InvalidArgumentException('must provide `Nexmo\Call\Webhook` object, or a type and url: missing url' );
}
$this->webhooks[$type] = new Webhook($type, $url, $method);
return $this;
}
public function setTimer($type, $length)
{
$this->data[$type . '_timer'] = $length;
}
public function setTimeout($type, $length)
{
$this->data[$type . '_timeout'] = $length;
}
public function setNcco($ncco) {
$this->data['ncco'] = $ncco;
return $this;
}
public function getStatus()
{
if($this->lazyLoad()){
return $this->data['status'];
}
}
public function getDirection()
{
if($this->lazyLoad()){
return $this->data['direction'];
}
}
public function getConversation()
{
if($this->lazyLoad()){
return new Conversation($this->data['conversation_uuid']);
}
}
/**
* Returns true if the resource data is loaded.
*
* Will attempt to load the data if it's not already.
*
* @return bool
*/
protected function lazyLoad()
{
if(!empty($this->data)){
return true;
}
if(isset($this->id)){
$this->get($this);
return true;
}
return false;
}
public function __get($name)
{
switch($name){
case 'stream':
case 'talk':
case 'dtmf':
return $this->lazySubresource(ucfirst($name));
default:
throw new \RuntimeException('property does not exist: ' . $name);
}
}
public function __call($name, $arguments)
{
switch($name){
case 'stream':
case 'talk':
case 'dtmf':
$entity = $this->lazySubresource(ucfirst($name));
return call_user_func_array($entity, $arguments);
default:
throw new \RuntimeException('method does not exist: ' . $name);
}
}
protected function lazySubresource($type)
{
if(!isset($this->subresources[$type])){
$class = 'Nexmo\Call\\' . $type;
$instance = new $class($this->getId());
$instance->setClient($this->getClient());
$this->subresources[$type] = $instance;
}
return $this->subresources[$type];
}
public function jsonSerialize()
{
$data = $this->data;
if(isset($this->to)){
$data['to'] = [$this->to->jsonSerialize()];
}
if(isset($this->from)){
$data['from'] = $this->from->jsonSerialize();
}
foreach($this->webhooks as $webhook){
$data = array_merge($data, $webhook->jsonSerialize());
}
return $data;
}
public function jsonUnserialize(array $json)
{
$this->data = $json;
$this->id = $json['uuid'];
}
}
|
{
"pile_set_name": "Github"
}
|
/***********************************************************************
*
* Copyright (C) 2016 wereturtle
*
* 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
*
***********************************************************************/
#ifndef TIMELABEL_H
#define TIMELABEL_H
#include <QLabel>
class QTimer;
/**
* A simple QLabel that displays the current time of day (HH:MM).
*/
class TimeLabel : public QLabel
{
Q_OBJECT
public:
explicit TimeLabel(QWidget *parent = 0);
virtual ~TimeLabel();
private slots:
void updateTimeOfDay();
private:
QTimer* timer;
};
#endif // TIMELABEL_H
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 2015 The Kubernetes Authors.
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
// UID is a type that holds unique ID values, including UUIDs. Because we
// don't ONLY use UUIDs, this is an alias to string. Being a type captures
// intent and helps make sure that UIDs and names do not get conflated.
type UID string
|
{
"pile_set_name": "Github"
}
|
/*
* Tencent is pleased to support the open source community by making TKEStack
* available.
*
* Copyright (C) 2012-2019 Tencent. All Rights Reserved.
*
* 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
*
* https://opensource.org/licenses/Apache-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 OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package machine
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
genericregistry "k8s.io/apiserver/pkg/registry/generic"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/apiserver/pkg/storage"
"k8s.io/apiserver/pkg/storage/names"
platforminternalclient "tkestack.io/tke/api/client/clientset/internalversion/typed/platform/internalversion"
"tkestack.io/tke/api/platform"
"tkestack.io/tke/api/platform/validation"
"tkestack.io/tke/pkg/apiserver/authentication"
"tkestack.io/tke/pkg/util"
"tkestack.io/tke/pkg/util/log"
namesutil "tkestack.io/tke/pkg/util/names"
)
// Strategy implements verification logic for machine.
type Strategy struct {
runtime.ObjectTyper
names.NameGenerator
platformClient platforminternalclient.PlatformInterface
}
// NewStrategy creates a strategy that is the default logic that applies when
// creating and updating machine objects.
func NewStrategy(platformClient platforminternalclient.PlatformInterface) *Strategy {
return &Strategy{platform.Scheme, namesutil.Generator, platformClient}
}
// DefaultGarbageCollectionPolicy returns the default garbage collection behavior.
func (Strategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy {
return rest.Unsupported
}
// PrepareForUpdate is invoked on update before validation to normalize the
// object.
func (Strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
oldMachine := old.(*platform.Machine)
machine, _ := obj.(*platform.Machine)
_, tenantID := authentication.UsernameAndTenantID(ctx)
if len(tenantID) != 0 {
if oldMachine.Spec.TenantID != tenantID {
log.Panic("Unauthorized update machine information", log.String("oldTenantID", oldMachine.Spec.TenantID), log.String("newTenantID", machine.Spec.TenantID), log.String("userTenantID", tenantID))
}
machine.Spec.TenantID = tenantID
}
}
// NamespaceScoped is false for machines
func (Strategy) NamespaceScoped() bool {
return false
}
// Export strips fields that can not be set by the user.
func (Strategy) Export(ctx context.Context, obj runtime.Object, exact bool) error {
return nil
}
// PrepareForCreate is invoked on create before validation to normalize
// the object.
func (s *Strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
_, tenantID := authentication.UsernameAndTenantID(ctx)
machine, _ := obj.(*platform.Machine)
if len(tenantID) != 0 {
machine.Spec.TenantID = tenantID
}
if machine.Name == "" && machine.GenerateName == "" {
machine.GenerateName = "mc-"
}
machine.Spec.Finalizers = []platform.FinalizerName{
platform.MachineFinalize,
}
}
// Validate validates a new machine
func (s *Strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
return validation.ValidateMachine(ctx, obj.(*platform.Machine), s.platformClient)
}
// AllowCreateOnUpdate is false for machines
func (Strategy) AllowCreateOnUpdate() bool {
return false
}
// AllowUnconditionalUpdate returns true if the object can be updated
// unconditionally (irrespective of the latest resource version), when there is
// no resource version specified in the object.
func (Strategy) AllowUnconditionalUpdate() bool {
return false
}
// Canonicalize normalizes the object after validation.
func (Strategy) Canonicalize(obj runtime.Object) {
}
// ValidateUpdate is the default update validation for an end cluster.
func (s *Strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
return validation.ValidateMachineUpdate(ctx, obj.(*platform.Machine), old.(*platform.Machine))
}
// GetAttrs returns labels and fields of a given object for filtering purposes.
func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {
machine, ok := obj.(*platform.Machine)
if !ok {
return nil, nil, fmt.Errorf("not a machine")
}
return machine.ObjectMeta.Labels, ToSelectableFields(machine), nil
}
// SelectionPredicate returns a generic matcher for a given label and field selector.
func SelectionPredicate(label labels.Selector, field fields.Selector) storage.SelectionPredicate {
return storage.SelectionPredicate{
Label: label,
Field: field,
GetAttrs: GetAttrs,
IndexFields: []string{
"spec.tenantID", "spec.clusterName", "spec.type", "spec.ip", "status.locked", "status.phase"},
}
}
// ToSelectableFields returns a field set that represents the object
func ToSelectableFields(machine *platform.Machine) fields.Set {
objectMetaFieldsSet := genericregistry.ObjectMetaFieldsSet(&machine.ObjectMeta, false)
specificFieldsSet := fields.Set{
"spec.tenantID": machine.Spec.TenantID,
"spec.clusterName": machine.Spec.ClusterName,
"spec.type": machine.Spec.Type,
"spec.ip": machine.Spec.IP,
"status.locked": util.BoolPointerToSelectField(machine.Status.Locked),
"status.phase": string(machine.Status.Phase),
}
return genericregistry.MergeFieldsSets(objectMetaFieldsSet, specificFieldsSet)
}
// StatusStrategy implements verification logic for status of Machine.
type StatusStrategy struct {
*Strategy
}
var _ rest.RESTUpdateStrategy = &StatusStrategy{}
// NewStatusStrategy create the StatusStrategy object by given strategy.
func NewStatusStrategy(strategy *Strategy) *StatusStrategy {
return &StatusStrategy{strategy}
}
// PrepareForUpdate is invoked on update before validation to normalize
// the object. For example: remove fields that are not to be persisted,
// sort order-insensitive list fields, etc. This should not remove fields
// whose presence would be considered a validation error.
func (StatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
newMachine := obj.(*platform.Machine)
oldMachine := old.(*platform.Machine)
newMachine.Spec = oldMachine.Spec
}
// ValidateUpdate is invoked after default fields in the object have been
// filled in before the object is persisted. This method should not mutate
// the object.
func (s *StatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
return field.ErrorList{}
}
// FinalizeStrategy implements finalizer logic for Machine.
type FinalizeStrategy struct {
*Strategy
}
var _ rest.RESTUpdateStrategy = &FinalizeStrategy{}
// NewFinalizerStrategy create the FinalizeStrategy object by given strategy.
func NewFinalizerStrategy(strategy *Strategy) *FinalizeStrategy {
return &FinalizeStrategy{strategy}
}
// PrepareForUpdate is invoked on update before validation to normalize
// the object. For example: remove fields that are not to be persisted,
// sort order-insensitive list fields, etc. This should not remove fields
// whose presence would be considered a validation error.
func (FinalizeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
newMachine := obj.(*platform.Machine)
oldMachine := old.(*platform.Machine)
newMachine.Status = oldMachine.Status
}
// ValidateUpdate is invoked after default fields in the object have been
// filled in before the object is persisted. This method should not mutate
// the object.
func (s *FinalizeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
return nil
}
|
{
"pile_set_name": "Github"
}
|
.class Landroid/support/v4/util/ContainerHelpers;
.super Ljava/lang/Object;
.source "ContainerHelpers.java"
# static fields
.field static final EMPTY_INTS:[I
.field static final EMPTY_LONGS:[J
.field static final EMPTY_OBJECTS:[Ljava/lang/Object;
# direct methods
.method static constructor <clinit>()V
.locals 2
.prologue
const/4 v1, 0x0
.line 20
new-array v0, v1, [I
sput-object v0, Landroid/support/v4/util/ContainerHelpers;->EMPTY_INTS:[I
.line 21
new-array v0, v1, [J
sput-object v0, Landroid/support/v4/util/ContainerHelpers;->EMPTY_LONGS:[J
.line 22
new-array v0, v1, [Ljava/lang/Object;
sput-object v0, Landroid/support/v4/util/ContainerHelpers;->EMPTY_OBJECTS:[Ljava/lang/Object;
return-void
.end method
.method constructor <init>()V
.locals 0
.prologue
.line 19
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
.method static binarySearch([III)I
.locals 5
.param p0, "array" # [I
.param p1, "size" # I
.param p2, "value" # I
.prologue
.line 46
const/4 v1, 0x0
.line 47
.local v1, "lo":I
add-int/lit8 v0, p1, -0x1
.line 49
.local v0, "hi":I
:goto_0
if-gt v1, v0, :cond_1
.line 50
add-int v4, v1, v0
ushr-int/lit8 v2, v4, 0x1
.line 51
.local v2, "mid":I
aget v3, p0, v2
.line 53
.local v3, "midVal":I
if-ge v3, p2, :cond_0
.line 54
add-int/lit8 v1, v2, 0x1
goto :goto_0
.line 55
:cond_0
if-le v3, p2, :cond_2
.line 56
add-int/lit8 v0, v2, -0x1
goto :goto_0
.line 61
.end local v2 # "mid":I
.end local v3 # "midVal":I
:cond_1
xor-int/lit8 v2, v1, -0x1
:cond_2
return v2
.end method
.method static binarySearch([JIJ)I
.locals 6
.param p0, "array" # [J
.param p1, "size" # I
.param p2, "value" # J
.prologue
.line 65
const/4 v1, 0x0
.line 66
.local v1, "lo":I
add-int/lit8 v0, p1, -0x1
.line 68
.local v0, "hi":I
:goto_0
if-gt v1, v0, :cond_1
.line 69
add-int v3, v1, v0
ushr-int/lit8 v2, v3, 0x1
.line 70
.local v2, "mid":I
aget-wide v4, p0, v2
.line 72
.local v4, "midVal":J
cmp-long v3, v4, p2
if-gez v3, :cond_0
.line 73
add-int/lit8 v1, v2, 0x1
goto :goto_0
.line 74
:cond_0
cmp-long v3, v4, p2
if-lez v3, :cond_2
.line 75
add-int/lit8 v0, v2, -0x1
goto :goto_0
.line 80
.end local v2 # "mid":I
.end local v4 # "midVal":J
:cond_1
xor-int/lit8 v2, v1, -0x1
:cond_2
return v2
.end method
.method public static equal(Ljava/lang/Object;Ljava/lang/Object;)Z
.locals 1
.param p0, "a" # Ljava/lang/Object;
.param p1, "b" # Ljava/lang/Object;
.prologue
.line 41
if-eq p0, p1, :cond_0
if-eqz p0, :cond_1
invoke-virtual {p0, p1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z
move-result v0
if-eqz v0, :cond_1
:cond_0
const/4 v0, 0x1
:goto_0
return v0
:cond_1
const/4 v0, 0x0
goto :goto_0
.end method
.method public static idealByteArraySize(I)I
.locals 3
.param p0, "need" # I
.prologue
const/4 v2, 0x1
.line 33
const/4 v0, 0x4
.local v0, "i":I
:goto_0
const/16 v1, 0x20
if-ge v0, v1, :cond_0
.line 34
shl-int v1, v2, v0
add-int/lit8 v1, v1, -0xc
if-gt p0, v1, :cond_1
.line 35
shl-int v1, v2, v0
add-int/lit8 p0, v1, -0xc
.line 37
.end local p0 # "need":I
:cond_0
return p0
.line 33
.restart local p0 # "need":I
:cond_1
add-int/lit8 v0, v0, 0x1
goto :goto_0
.end method
.method public static idealIntArraySize(I)I
.locals 1
.param p0, "need" # I
.prologue
.line 25
mul-int/lit8 v0, p0, 0x4
invoke-static {v0}, Landroid/support/v4/util/ContainerHelpers;->idealByteArraySize(I)I
move-result v0
div-int/lit8 v0, v0, 0x4
return v0
.end method
.method public static idealLongArraySize(I)I
.locals 1
.param p0, "need" # I
.prologue
.line 29
mul-int/lit8 v0, p0, 0x8
invoke-static {v0}, Landroid/support/v4/util/ContainerHelpers;->idealByteArraySize(I)I
move-result v0
div-int/lit8 v0, v0, 0x8
return v0
.end method
|
{
"pile_set_name": "Github"
}
|
package de.gsi.dataset.utils.trees;
import java.util.NavigableMap;
/**
* User: Vitaly Sazanovich Date: 07/02/13 Time: 19:28 Email: Vitaly.Sazanovich@gmail.com
*
* @param <K> generic key
* @param <V> generic value
*/
public interface IndexedNavigableMap<K, V> extends NavigableMap<K, V> {
/**
* Returns a key-value mapping associated with the key located at the index offset from the beginning of the sorted
* map
*
* @param index index of the key
* @return the entry with the key {@code key} located at the index (@code index) offset from the beginning of the
* sorted map
* @throws ArrayIndexOutOfBoundsException if the specified index is less than 0 or greater than size-1
*/
Entry<K, V> exactEntry(int index);
/**
* Returns the key located at the index offset from the beginning of the sorted map
*
* @param index index of the key
* @return the key {@code key} located at the index (@code index) offset from the beginning of the sorted map
* @throws ArrayIndexOutOfBoundsException if the specified index is less than 0 or greater than size-1
*/
K exactKey(int index);
/**
* Searches the specified tree map for the specified key using the put algorithm. Calculates its offset from the
* beginning of the sorted map using weights.
*
* @param k the key
* @return index of the search key, if it is contained in the tree map; otherwise a NullPointerException is thrown
* @throws NullPointerException if the specified key is null or does not exist
*/
int keyIndex(K k);
}
|
{
"pile_set_name": "Github"
}
|
package amazonstorage
import (
"encoding/xml"
)
type Amazonstorage struct {
}
const (
debug = false
legacyAPIVersion = "2011-12-15"
vpcAPIVersion = "2013-10-15"
)
type CreateVolume struct {
AvailZone string
SnapshotId string
VolumeType string
VolumeSize int
Encrypted bool
IOPS int64
}
type Volume struct {
Id string `xml:"volumeId"`
Size int `xml:"size"`
SnapshotId string `xml:"snapshotId"`
Status string `xml:"status"`
IOPS int64 `xml:"iops"`
AvailZone string `xml:"availabilityZone"`
CreateTime string `xml:"createTime"`
VolumeType string `xml:"volumeType"`
Encrypted bool `xml:"encrypted"`
Tags []Tag `xml:"tagSet>item"`
Attachments []VolumeAttachment `xml:"attachmentSet>item"`
}
type Tag struct {
Key string `xml:"key"`
Value string `xml:"value"`
}
type VolumeAttachment struct {
VolumeId string `xml:"volumeId"`
Device string `xml:"device"`
InstanceId string `xml:"instanceId"`
Status string `xml:"status"`
DeleteOnTermination bool `xml:"deleteOnTermination"`
}
type CreateVolumeResp struct {
RequestId string `xml:"requestId"`
Volume
}
type SimpleResp struct {
XMLName xml.Name
RequestId string `xml:"requestId"`
}
type VolumeAttachmentResp struct {
RequestId string `xml:"requestId"`
VolumeId string `xml:"volumeId"`
Device string `xml:"device"`
InstanceId string `xml:"instanceId"`
Status string `xml:"status"`
AttachTime string `xml:"attachTime"`
}
type SnapshotsResp struct {
RequestId string `xml:"requestId"`
Snapshots []Snapshot `xml:"snapshotSet>item"`
}
type Snapshot struct {
Id string `xml:"snapshotId"`
VolumeId string `xml:"volumeId"`
VolumeSize string `xml:"volumeSize"`
Status string `xml:"status"`
StartTime string `xml:"startTime"`
Description string `xml:"description"`
Progress string `xml:"progress"`
OwnerId string `xml:"ownerId"`
OwnerAlias string `xml:"ownerAlias"`
Tags []Tag `xml:"tagSet>item"`
}
type CreateSnapshotResp struct {
RequestId string `xml:"requestId"`
Snapshot
}
|
{
"pile_set_name": "Github"
}
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import os
import json
import codecs
from yaml import safe_load, YAMLError
from six import string_types
from ansible_runner.exceptions import ConfigurationError
from ansible_runner.output import debug
class ArtifactLoader(object):
'''
Handles loading and caching file contents from disk
This class will load the file contents and attempt to deserialize the
contents as either JSON or YAML. If the file contents cannot be
deserialized, the contents will be returned to the caller as a string.
The deserialized file contents are stored as a cached object in the
instance to avoid any additional reads from disk for subsequent calls
to load the same file.
'''
def __init__(self, base_path):
self._cache = {}
self.base_path = base_path
def _load_json(self, contents):
'''
Attempts to deserialize the contents of a JSON object
Args:
contents (string): The contents to deserialize
Returns:
dict: If the contents are JSON serialized
None: If the contents are not JSON serialized
'''
try:
return json.loads(contents)
except ValueError:
pass
def _load_yaml(self, contents):
'''
Attempts to deserialize the contents of a YAML object
Args:
contents (string): The contents to deserialize
Returns:
dict: If the contents are YAML serialized
None: If the contents are not YAML serialized
'''
try:
return safe_load(contents)
except YAMLError:
pass
def get_contents(self, path):
'''
Loads the contents of the file specified by path
Args:
path (string): The relative or absolute path to the file to
be loaded. If the path is relative, then it is combined
with the base_path to generate a full path string
Returns:
string: The contents of the file as a string
Raises:
ConfigurationError: If the file cannot be loaded
'''
try:
if not os.path.exists(path):
raise ConfigurationError('specified path does not exist %s' % path)
with codecs.open(path, encoding='utf-8') as f:
data = f.read()
return data
except (IOError, OSError) as exc:
raise ConfigurationError('error trying to load file contents: %s' % exc)
def abspath(self, path):
'''
Transform the path to an absolute path
Args:
path (string): The path to transform to an absolute path
Returns:
string: The absolute path to the file
'''
if not path.startswith(os.path.sep) or path.startswith('~'):
path = os.path.expanduser(os.path.join(self.base_path, path))
return path
def isfile(self, path):
'''
Check if the path is a file
:params path: The path to the file to check. If the path is relative
it will be exanded to an absolute path
:returns: boolean
'''
return os.path.isfile(self.abspath(path))
def load_file(self, path, objtype=None, encoding='utf-8'):
'''
Load the file specified by path
This method will first try to load the file contents from cache and
if there is a cache miss, it will load the contents from disk
Args:
path (string): The full or relative path to the file to be loaded
encoding (string): The file contents text encoding
objtype (object): The object type of the file contents. This
is used to type check the deserialized content against the
contents loaded from disk.
Ignore serializing if objtype is string_types
Returns:
object: The deserialized file contents which could be either a
string object or a dict object
Raises:
ConfigurationError:
'''
path = self.abspath(path)
debug('file path is %s' % path)
if path in self._cache:
return self._cache[path]
try:
debug('cache miss, attempting to load file from disk: %s' % path)
contents = parsed_data = self.get_contents(path)
if encoding:
parsed_data = contents.encode(encoding)
except ConfigurationError as exc:
debug(exc)
raise
except UnicodeEncodeError:
raise ConfigurationError('unable to encode file contents')
if objtype is not string_types:
for deserializer in (self._load_json, self._load_yaml):
parsed_data = deserializer(contents)
if parsed_data:
break
if objtype and not isinstance(parsed_data, objtype):
debug('specified file %s is not of type %s' % (path, objtype))
raise ConfigurationError('invalid file serialization type for contents')
self._cache[path] = parsed_data
return parsed_data
|
{
"pile_set_name": "Github"
}
|
# Copyright 2017 ProjectQ-Framework (www.projectq.ch)
#
# 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.
def insert_engine(prev_engine, engine_to_insert):
"""
Inserts an engine into the singly-linked list of engines.
It also sets the correct main_engine for engine_to_insert.
Args:
prev_engine (projectq.cengines.BasicEngine):
The engine just before the insertion point.
engine_to_insert (projectq.cengines.BasicEngine):
The engine to insert at the insertion point.
"""
engine_to_insert.main_engine = prev_engine.main_engine
engine_to_insert.next_engine = prev_engine.next_engine
prev_engine.next_engine = engine_to_insert
def drop_engine_after(prev_engine):
"""
Removes an engine from the singly-linked list of engines.
Args:
prev_engine (projectq.cengines.BasicEngine):
The engine just before the engine to drop.
Returns:
Engine: The dropped engine.
"""
dropped_engine = prev_engine.next_engine
prev_engine.next_engine = dropped_engine.next_engine
dropped_engine.next_engine = None
dropped_engine.main_engine = None
return dropped_engine
|
{
"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@magento.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.magento.com for more information.
*
* @category design
* @package base_default
* @copyright Copyright (c) 2006-2020 Magento, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
?>
<?php if ($this->getAuthenticationStart()):?>
<div class="centinel" id="centinel_authenticate_block">
<h3><?php echo $this->__('Card Verification')?></h3>
<p><?php echo $this->__('Please verify the card with the issuer bank:') ?></p>
<div class="authentication">
<iframe id="centinel_authenticate_iframe" frameborder="0" border="0" src=""></iframe>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
CentinelAuthenticateController = new CentinelAuthenticate('centinel_authenticate_block', 'centinel_authenticate_iframe');
<?php foreach ($this->getRelatedBlocks() as $relatedBlockId):?>
CentinelAuthenticateController.addRelatedBlock('<?php echo $relatedBlockId ?>');
<?php endforeach;?>
<?php if ($this->getAuthenticationStartMode() == 'instant'): ?>
CentinelAuthenticateController.start('<?php echo $this->getFrameUrl() ?>');
<?php elseif ($this->getAuthenticationStartMode() == 'window'):?>
Event.observe(window, 'load', function(){CentinelAuthenticateController.start('<?php echo $this->getFrameUrl() ?>');});
<?php endif;?>
//]]>
</script>
<?php else:?>
<script type="text/javascript">
//<![CDATA[
if (typeof CentinelAuthenticateController != 'undefined') {
CentinelAuthenticateController.cancel();
}
//]]>
</script>
<?php endif;?>
|
{
"pile_set_name": "Github"
}
|
/* ******************************************************************************
* Copyright (c) 2006-2012 XMind Ltd. and others.
*
* This file is a part of XMind 3. XMind releases 3 and
* above are dual-licensed under the Eclipse Public License (EPL),
* which is available at http://www.eclipse.org/legal/epl-v10.html
* and the GNU Lesser General Public License (LGPL),
* which is available at http://www.gnu.org/licenses/lgpl.html
* See https://www.xmind.net/license.html for details.
*
* Contributors:
* XMind Ltd. - initial API and implementation
*******************************************************************************/
package org.xmind.ui.datepicker;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
private static final String BUNDLE_NAME = "org.xmind.ui.datepicker.messages"; //$NON-NLS-1$
// Full name of each month
public static String January;
public static String Feburary;
public static String March;
public static String April;
public static String May;
public static String June;
public static String July;
public static String August;
public static String September;
public static String October;
public static String November;
public static String December;
// Abbr name of each week day
public static String Monday;
public static String Tuesday;
public static String Wednesday;
public static String Thursday;
public static String Friday;
public static String Saturday;
public static String Sunday;
public static String TodayPattern;
public static String None;
public static String Illegal;
public static String TimeCheckInvalid_label;
public static String TimeCheckInvalidSmall_message;
public static String TimeCheckInvalidBig_message;
public static String DatePicker_Time_AM_text;
public static String DatePicker_Time_PM_text;
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
private Messages() {
}
}
|
{
"pile_set_name": "Github"
}
|
<project name="freeplane_remote_client" default="dist" basedir=".." xmlns:ivy="antlib:org.apache.ivy.ant">
<property name="workspace" location=".." />
<property name="src" value="src" />
<property name="resources" value="resources" />
<property name="root" value="." />
<property name="osgimanifest" value="${root}/META-INF/MANIFEST.MF" />
<property file="${workspace}/freeplane_framework/ant/ant.properties" />
<property file="${workspace}/freeplane/ant/ant.properties" />
<property file="ant/ant.properties" />
<property name="build" value="${root}/build" />
<property name="lib" value="${root}/lib" />
<property name="dist" value="${root}/dist" />
<property name="dist.osgi.dir" value="${dist}/org.freeplane.plugin.remote.client" />
<property name="freeplaneplugin.jar" value="${dist}/org.freeplane.plugin.remote.client.jar" />
<property name="debug" value="on" />
<property name="java_source_version" value="1.5" />
<property name="java_target_version" value="1.5" />
<property name="build.compiler" value="modern" />
<property name="classpath" value="${framework.jar}:${freeplane.jars}:${services.jar}:${core.jar}:${workspace.jar}:${dependencies.jars}:${client-libs}" />
<property name="ivy.jar.dir" value="${basedir}/ivy" />
<property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar" />
<property name="build.dir" value="build" />
<property name="src.dir" value="src" />
<property name="JOrtho_0.4_freeplane.location" value="${root}/../JOrtho_0.4_freeplane" />
<property name="freeplane.location" value="${root}/../freeplane" />
<property name="freeplane.remote.shared.location" value="${root}/../freeplane_plugin_remote_shared" />
<path id="JOrtho_0.4_freeplane.classpath">
<pathelement location="${JOrtho_0.4_freeplane.location}/bin" />
</path>
<path id="freeplane.classpath">
<fileset dir="${freeplane.location}/lib/" includes="**.jar" />
<pathelement location="${freeplane.location}/bin/classes" />
<path refid="JOrtho_0.4_freeplane.classpath" />
</path>
<path id="freeplane_plugin_remote_client.classpath">
<pathelement location="bin" />
<pathelement location="ivy/ivy.jar" />
<fileset dir="${root}/lib/" includes="**.jar" />
<path refid="freeplane.classpath" />
</path>
<target name="install-ivy" description="adds ivy ant module to ant">
<path id="ivy.lib.path">
<fileset dir="${ivy.jar.dir}" includes="*.jar" />
</path>
<taskdef resource="org/apache/ivy/ant/antlib.xml" uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path" />
</target>
<target name="resolve-remote-shared" description="retrieve freeplane_remote_shared.jar">
<copy file="${root}/../freeplane_plugin_remote_shared/lib/freeplane_remote_shared.jar" todir="${root}/lib" />
</target>
<target name="resolve" description="retrieve dependencies with ivy" depends="install-ivy">
<ivy:retrieve />
</target>
<target name="build" depends="resolve-remote-shared,lib_fileset,git.revision">
<mkdir dir="${build}" />
<javac srcdir="${src}" destdir="${build}" debug="${debug}" source="${java_source_version}" target="${java_target_version}" encoding="utf8">
<classpath>
<fileset dir="lib">
<include name="**/*.jar" />
</fileset>
<pathelement path="${classpath}/" />
</classpath>
</javac>
</target>
<target name="lib_fileset" depends="resolve">
<fileset id="resolved_jars" dir="lib">
<include name="*.jar" />
</fileset>
<pathconvert pathsep=",${line.separator} " property="resolved.jars.path" refid="resolved_jars">
<map from="${basedir}/" to="" />
</pathconvert>
<delete file="${basedir}/META-INF/MANIFEST.MF" quiet="true"/>
<copy tofile="${basedir}/META-INF/MANIFEST.MF" file="${basedir}/META-INF/MANIFEST.MF.template">
<filterset>
<filter token="DEPENDENCY_JARS" value="${resolved.jars.path}" />
</filterset>
</copy>
<echo message="resolved"></echo>
</target>
<target name="dist" depends="build">
<jar jarfile="lib/plugin.jar">
<fileset dir="${build}" />
<fileset dir="${resources}" />
<fileset dir="${src}">
<include name="**/*.xml" />
<include name="**/*.properties" />
<include name="**/*.txt" />
</fileset>
</jar>
<delete dir="${dist.osgi.dir}" quiet="true" />
<mkdir dir="${dist.osgi.dir}" />
<copy todir="${dist.osgi.dir}">
<fileset dir="${root}">
<include name="lib/**" />
</fileset>
</copy>
<mkdir dir="${dist.osgi.dir}/META-INF" />
<copy tofile="${dist.osgi.dir}/META-INF/MANIFEST.MF" file="${osgimanifest}">
</copy>
<delete file="lib/plugin.jar" quiet="true" />
</target>
<target name="osgi_dist_as_jar" depends="dist">
<jar jarfile="${freeplaneplugin.jar}">
<fileset dir="${dist.osgi.dir}">
<include name="**" />
</fileset>
</jar>
</target>
<target name="clean">
<delete dir="${build}" quiet="true" />
<delete dir="${dist}" quiet="true" />
<delete dir="${lib}" quiet="true" />
<delete>
<fileset defaultexcludes="no" dir="${src}" includes="**/*~" />
</delete>
</target>
<available file="../.git" type="dir" property="git.present"/>
<target name="git.revision" if="git.present">
<exec executable="git" outputproperty="git.revision" failifexecutionfails="false" errorproperty="">
<arg value="rev-parse"/>
<arg value="HEAD"/>
</exec>
<condition property="repository.version" value="${git.revision}" else="unknown">
<and>
<isset property="git.revision"/>
<length string="${git.revision}" trim="yes" length="0" when="greater"/>
</and>
</condition>
<mkdir dir="${build}" />
<touch file="${build}/git.commit"/>
<propertyfile file="${build}/git.commit">
<entry key="commit" value="${repository.version}"/>
</propertyfile>
</target>
</project>
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 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.
-->
<android.support.v7.internal.view.menu.ActionMenuView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:divider="?attr/actionBarDivider"
app:dividerPadding="12dip"
android:gravity="center_vertical"/>
|
{
"pile_set_name": "Github"
}
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/PassKitCore.framework/PassKitCore
*/
@interface PKPaymentDevice : NSObject <CLLocationManagerDelegate> {
NSObject<OS_dispatch_queue> * _callbackQueue;
PKPaymentDeviceConfigurationData * _configurationData;
NSObject<OS_dispatch_queue> * _internalQueue;
NSObject<OS_dispatch_source> * _locationFixTimeout;
CLLocationManager * _locationManager;
NSMutableArray * _provisioningCompletions;
PKPaymentDeviceProvisioningData * _provisioningData;
PKSecureElement * _secureElement;
bool _skipLocationCheck;
NSTimer * _timer;
}
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (readonly) unsigned long long hash;
@property (nonatomic) bool skipLocationCheck;
@property (readonly) Class superclass;
+ (id)clientHardwarePlatformInfoHTTPHeader;
+ (id)clientInfoHTTPHeader;
- (void).cxx_destruct;
- (void)SEPParingInformationWithCompletion:(id /* block */)arg1;
- (void)_executeProvisioningCompletionHandlers;
- (void)_finishLocationFixWithLocation:(id)arg1;
- (id)configurationData;
- (void)configurationDataWithCompletionHandler:(id /* block */)arg1;
- (void)dealloc;
- (void)deleteApplicationWithAID:(id)arg1;
- (id)init;
- (id)initWithCallbackQueue:(id)arg1;
- (void)locationManager:(id)arg1 didFailWithError:(id)arg2;
- (void)locationManager:(id)arg1 didUpdateLocations:(id)arg2;
- (id)primarySecureElementIdentifier;
- (void)provisioningDataWithCompletionHandler:(id /* block */)arg1;
- (void)queueConnectionToTrustedServiceManagerForPushTopic:(id)arg1 withCompletion:(id /* block */)arg2;
- (void)queueConnectionToTrustedServiceManagerWithCompletion:(id /* block */)arg1;
- (void)registrationDataWithAuthToken:(id)arg1 completionHandler:(id /* block */)arg2;
- (id)rewrapDataWithDeviceIdentifier:(id)arg1 certificates:(id)arg2;
- (void)setRegistrationRegionMap:(id)arg1 primaryRegionTopic:(id)arg2;
- (void)setSkipLocationCheck:(bool)arg1;
- (void)signData:(id)arg1 signatureEntanglementMode:(unsigned long long)arg2 withCompletionHandler:(id /* block */)arg3;
- (bool)skipLocationCheck;
@end
|
{
"pile_set_name": "Github"
}
|
{
"ActivityBlock.classActivityLabel": "Hoạt động lớp",
"ActivityBlock.noActivityLabel": "Không có hoạt động trong lớp của bạn",
"Answer.correct": "Câu trả lời đúng được đưa ra",
"Answer.error": "Xảy ra lỗi không xác định",
"Answer.hint": "Học viên đã yêu cầu gợi ý",
"Answer.incorrect": "Câu trả lời sai được đưa ra",
"Answer.noAttempt": "Học viên không trả lời",
"AssessmentQuestionListItem.moveExerciseDown": "Di chuyển bài tập này xuống một vị trí",
"AssessmentQuestionListItem.moveExerciseUp": "Di chuyển bài tập này lên một vị trí",
"AssignmentCopyModal.currentClass": "{ name } (lớp hiện tại)",
"AssignmentCopyModal.destinationExplanation": "Sẽ được sao chép vào '{classroomName}'",
"AverageScoreTooltip.visibleToLearnersTooltipMessage": "Chỉ tính từ những bài kiểm tra đã hoàn tất",
"CoachClassListPage.classPageSubheader": "Xem tiến bộ của học viên và kết quả lớp học",
"CoachClassListPage.noAssignedClassesDetails": "Vui lòng tham khảo quản trị viên Kolibri để được chỉ định vào một lớp học",
"CoachClassListPage.noClassesDetailsForAdmin": "Tạo mở một lớp học và ghi danh học viên",
"CoachClassListPage.noClassesDetailsForFacilityCoach": "Vui lòng tham khảo quản trị viên Kolibri",
"CoachExamsPage.noActiveExams": "Không có bài kiểm tra nào được kích hoạt",
"CoachExamsPage.noExams": "Bạn không có bất kỳ bài kiểm tra nào",
"CoachExamsPage.noInactiveExams": "Không có bài kiểm tra nào không được kích hoạt",
"CommonCoachStrings.activeLabel": "Được kích hoạt",
"CommonCoachStrings.activeQuizzesLabel": "Các bài kiểm tra được kích hoạt",
"CommonCoachStrings.activityLabel": "Hoạt động",
"CommonCoachStrings.activityListEmptyState": "Không có hoạt động nào",
"CommonCoachStrings.allQuizzesLabel": "Tất cả bài kiểm tra",
"CommonCoachStrings.avgQuizScoreLabel": "Điểm trung bình của bài kiểm tra",
"CommonCoachStrings.avgScoreLabel": "Điểm trung bình",
"CommonCoachStrings.avgTimeSpentLabel": "Thời gian làm bài trung bình",
"CommonCoachStrings.backToLessonLabel": "Quay về '{lesson}'",
"CommonCoachStrings.classLabel": "Lớp",
"CommonCoachStrings.classesLabel": "Lớp học",
"CommonCoachStrings.closeQuizLabel": "Kết thúc bài kiểm tra",
"CommonCoachStrings.closeQuizModalDetail": "Tất cả học viên sẽ nhận được điểm số cuối cùng và báo cáo bài kiểm tra. Những câu hỏi chưa xong sẽ bị coi là sai.",
"CommonCoachStrings.coachLabel": "Giáo viên",
"CommonCoachStrings.coachLabelWithOneName": "Giáo viên – {name}",
"CommonCoachStrings.coachLabelWithOneTwoNames": "Giáo viên – {name1} – {name2}",
"CommonCoachStrings.copyAction": "Sao chép",
"CommonCoachStrings.createdNotification": "Đã tạo",
"CommonCoachStrings.deletedNotification": "Đã xóa",
"CommonCoachStrings.descriptionLabel": "Mô tả",
"CommonCoachStrings.descriptionMissingLabel": "Không có mô tả",
"CommonCoachStrings.detailsLabel": "Chi tiết",
"CommonCoachStrings.difficultQuestionsLabel": "Các câu hỏi khó",
"CommonCoachStrings.entireClassLabel": "Cả lớp",
"CommonCoachStrings.exercisesCompletedLabel": "Các bài tập đã hoàn thành",
"CommonCoachStrings.exportCSVAction": "Xuất ra CSV",
"CommonCoachStrings.groupListEmptyState": "Không có nhóm nào",
"CommonCoachStrings.groupNameLabel": "Tên nhóm",
"CommonCoachStrings.groupsLabel": "Nhóm ",
"CommonCoachStrings.helpNeededLabel": "Cần giúp đỡ",
"CommonCoachStrings.inactiveLabel": "Không kích hoạt",
"CommonCoachStrings.inactiveQuizzesLabel": "Các bài kiểm tra không được kích hoạt",
"CommonCoachStrings.integer": "{value, number, integer}",
"CommonCoachStrings.lastActivityLabel": "Hoạt động lần cuối",
"CommonCoachStrings.learnerListEmptyState": "Không có học viên nào",
"CommonCoachStrings.learnersLabel": "Học viên",
"CommonCoachStrings.lessonDuplicateTitleError": "Đã có tên bài học này rồi",
"CommonCoachStrings.lessonLabel": "Bài học",
"CommonCoachStrings.lessonListEmptyState": "Không có bài học nào",
"CommonCoachStrings.lessonNotVisibleToLearnersLabel": "Bài học không được hiển thị cho học viên",
"CommonCoachStrings.lessonVisibleToLearnersLabel": "Bài học được hiển thị cho học viên",
"CommonCoachStrings.lessonsAssignedLabel": "Các bài học đã chỉ định",
"CommonCoachStrings.lessonsLabel": "Bài học",
"CommonCoachStrings.manageResourcesAction": "Quản lý nguồn tài liệu",
"CommonCoachStrings.masteryModelLabel": "Yêu cầu hoàn thành",
"CommonCoachStrings.membersLabel": "Thành viên",
"CommonCoachStrings.nameLabel": "Tên",
"CommonCoachStrings.newLessonAction": "Bài học mới",
"CommonCoachStrings.newQuizAction": "Bài kiểm tra mới",
"CommonCoachStrings.noResourcesInLessonLabel": "Không có nguồn tài liệu nào trong bài học này",
"CommonCoachStrings.nthExerciseName": "{name} ({number, number, integer})",
"CommonCoachStrings.numberOfLearners": "{value, number, integer} {value, plural, one {học viên} other {các học viên}}",
"CommonCoachStrings.numberOfQuestions": "{value, number, integer} {value, plural, one {câu hỏi} other {các câu hỏi}}",
"CommonCoachStrings.numberOfResources": "{value, number, integer} {value, plural, one {nguồn tài liệu} other {các nguồn tài liệu}}",
"CommonCoachStrings.openQuizLabel": "Bắt đầu bài kiểm tra",
"CommonCoachStrings.openQuizModalDetail": "Khi bắt đầu bài kiểm tra, học viên sẽ thấy bài kiểm tra và sẽ được trả lời câu hỏi",
"CommonCoachStrings.orderFixedDescription": "Mỗi học viên đều thấy thứ tự câu hỏi giống nhau",
"CommonCoachStrings.orderFixedLabel": "Được sắp xếp cố định",
"CommonCoachStrings.orderRandomDescription": "Mỗi học viên đều thấy thứ tự câu hỏi khác nhau",
"CommonCoachStrings.orderRandomLabel": "Được sắp xếp ngẫu nhiên",
"CommonCoachStrings.overallLabel": "Tổng thể",
"CommonCoachStrings.percentage": "{value, number, percent}",
"CommonCoachStrings.previewAction": "Xem trước",
"CommonCoachStrings.previewLabel": "Xem trước",
"CommonCoachStrings.printReportAction": "In báo cáo",
"CommonCoachStrings.questionLabel": "Câu hỏi",
"CommonCoachStrings.questionListEmptyState": "Không có câu hỏi nào",
"CommonCoachStrings.questionOrderLabel": "Thứ tự câu hỏi",
"CommonCoachStrings.questionsLabel": "Câu hỏi",
"CommonCoachStrings.quizClosedLabel": "Bài kiểm tra kết thúc",
"CommonCoachStrings.quizClosedMessage": "Bài kiểm tra kết thúc",
"CommonCoachStrings.quizDuplicateTitleError": "Đã có một bài kiểm tra mang tên này rồi",
"CommonCoachStrings.quizFailedToCloseMessage": "Xảy ra lỗi khi kết thúc bài kiểm tra. Bài kiểm tra chưa kết thúc.",
"CommonCoachStrings.quizFailedToOpenMessage": "Xảy ra lỗi khi bắt đầu bài kiểm tra. Bài kiểm tra chưa bắt đầu.",
"CommonCoachStrings.quizListEmptyState": "Không có bài kiểm tra nào",
"CommonCoachStrings.quizNotVisibleToLearners": "Báo cáo bài kiểm tra không được hiển thị cho học viên",
"CommonCoachStrings.quizOpenedMessage": "Bài kiểm tra bắt đầu",
"CommonCoachStrings.quizVisibleToLearners": "Học viên thấy báo cáo bài kiểm tra",
"CommonCoachStrings.quizzesAssignedLabel": "Các bài kiểm tra được chỉ định",
"CommonCoachStrings.quizzesLabel": "Bài kiểm tra",
"CommonCoachStrings.ratioShort": "{value, number, integer} trong số {total, number, integer}",
"CommonCoachStrings.recipientsLabel": "Người nhận",
"CommonCoachStrings.renameAction": "Đổi tên",
"CommonCoachStrings.reportLabel": "Báo cáo",
"CommonCoachStrings.reportVisibleLabel": "Báo cáo hiển thị",
"CommonCoachStrings.reportsLabel": "Báo cáo",
"CommonCoachStrings.resourcesViewedLabel": "Nguồn tài liệu đã xem",
"CommonCoachStrings.scoreLabel": "Điểm",
"CommonCoachStrings.showMoreAction": "Hiển thị thêm",
"CommonCoachStrings.startedLabel": "Đã bắt đầu",
"CommonCoachStrings.statusLabel": "Trạng thái",
"CommonCoachStrings.timeSpentLabel": "Thời gian làm",
"CommonCoachStrings.titleLabel": "Tiêu đề",
"CommonCoachStrings.ungroupedLearnersLabel": "Học viên không nhóm",
"CommonCoachStrings.updatedNotification": "Đã cập nhật",
"CommonCoachStrings.viewAllAction": "Xem tất cả",
"CommonCoachStrings.viewByGroupsLabel": "Xem theo nhóm",
"ContentCardList.selectAllCheckboxLabel": "Chọn tất cả",
"CreateExamPage.chooseExercises": "Chọn chủ đề hoặc bài tập",
"CreateExamPage.createNewExamLabel": "Soạn bài kiểm tra mới",
"CreateExamPage.exitSearchButtonLabel": "Thoát tìm kiếm",
"CreateExamPage.noneSelected": "Không chọn bài tập nào",
"CreateExamPage.numQuestions": "Số câu hỏi",
"CreateExamPage.numQuestionsBetween": "Nhập một số từ 1 đến 50",
"CreateExamPage.numQuestionsExceed": "Số lượng câu hỏi tối đa dựa trên bài tập bạn chọn, {maxQuestionsFromSelection}. Chọn thêm nhiều bài tập để đạt {inputNumQuestions} câu hỏi hoặc giảm số lượng câu hỏi còn {maxQuestionsFromSelection}.",
"CreateExamPage.selectionInformation": "{count, number, integer} / {total, number, integer} {total, plural, other {nguồn tài liệu được chọn}}",
"CreateExamPreview.appBarLabel": "Chọn bài tập",
"CreateExamPreview.numQuestions": "Số câu hỏi",
"CreateExamPreview.numQuestionsBetween": "Nhập một số từ 1 đến 50",
"CreateExamPreview.numQuestionsExceed": "Số lượng câu hỏi tối đa dựa trên bài tập bạn chọn, {maxQuestionsFromSelection}. Chọn thêm nhiều bài tập để đạt {inputNumQuestions} câu hỏi hoặc giảm số lượng câu hỏi còn {maxQuestionsFromSelection}.",
"CreateExamPreview.preview": "Xem trước bài kiểm tra",
"CreateExamPreview.questionsLabel": "Câu hỏi",
"CreateExamPreview.randomize": "Chọn một bộ câu hỏi khác",
"CreateExamPreview.title": "Chọn câu hỏi",
"CreateGroupModal.duplicateName": "Đã có tên nhóm này rồi",
"CreateGroupModal.newLearnerGroup": "Tạo nhóm mới",
"DeleteGroupModal.areYouSure": "Bạn chắc chắn muốn xóa '{ groupName }'?",
"DeleteGroupModal.deleteLearnerGroup": "Xóa nhóm",
"EditDetailsResourceListTable.moveResourceDownButtonDescription": "Di chuyển nguồn tài liệu này xuống dưới một vị trí trong bài học này",
"EditDetailsResourceListTable.moveResourceUpButtonDescription": "Di chuyển nguồn tài liệu này lên trên một vị trí trong bài học này",
"EditDetailsResourceListTable.multipleResourceRemovalsConfirmationMessage": "Đã loại bỏ { numberOfRemovals } nguồn tài liệu",
"EditDetailsResourceListTable.parentChannelLabel": "Kênh chính:",
"EditDetailsResourceListTable.singleResourceRemovalConfirmationMessage": "Đã loại bỏ '{resourceTitle}'",
"EditDetailsResourceListTable.undoActionPrompt": "Hoàn tác",
"ExamReportPageTitles.examReportTitle": "Báo cáo {examTitle}",
"ExerciseStatusCompleted.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {bài tập đã hoàn thành}}",
"ExerciseStatusCompleted.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đã hoàn thành}}",
"ExerciseStatusCompleted.count": "{count, number, integer} {count, plural, one {bài tập đã hoàn thành} other {các bài tập đã hoàn thành}}",
"ExerciseStatusCompleted.countShort": "{count, number, integer} {count, plural, other {đã hoàn thành}}",
"ExerciseStatusCompleted.label": "{count, plural, one {Bài tập đã hoàn thành} other {Các bài tập đã hoàn thành}}",
"ExerciseStatusCompleted.labelShort": "{count, plural, other {Đã hoàn thành}}",
"ExerciseStatusCompleted.ratio": "{count, number, integer} trong số {total, number, integer} {total, plural, one {bài tập} other {các bài tập}} {count, plural, other {đã hoàn thành}}",
"ExerciseStatusCompleted.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đã hoàn thành}}",
"ExerciseStatusDifficult.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {bài tập đều khó}}",
"ExerciseStatusDifficult.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đều khó}}",
"ExerciseStatusDifficult.count": "{count, number, integer} {count, plural, one {bài tập khó} other {các bài tập khó}}",
"ExerciseStatusDifficult.countShort": "{count, number, integer} {count, plural, one {khó} other {khó}}",
"ExerciseStatusDifficult.label": "{count, plural, one {Bài tập khó} other {Các Bài tập khó}}",
"ExerciseStatusDifficult.labelShort": "{count, plural, other {Khó}}",
"ExerciseStatusDifficult.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {bài tập} other {các bài tập}} {count, plural, one {khó} other {khó}}",
"ExerciseStatusDifficult.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, one {khó} other {khó}}",
"ExerciseStatusInProgress.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {bài tập đang làm}}",
"ExerciseStatusInProgress.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đang làm}}",
"ExerciseStatusInProgress.count": "{count, number, integer} {count, plural, one {bài tập đang làm} other {các bài tập đang làm}}",
"ExerciseStatusInProgress.countShort": "{count, number, integer} {count, plural, other {đang làm}}",
"ExerciseStatusInProgress.label": "{count, plural, one {Bài tập đang làm} other {Các bài tập đang làm}}",
"ExerciseStatusInProgress.labelShort": "{count, plural, other {Đang làm}}",
"ExerciseStatusInProgress.ratio": "{count, number, integer} trong số {total, number, integer} {total, plural, one {bài tập} other {các bài tập}} {count, plural, other {đang làm}}",
"ExerciseStatusInProgress.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đang làm}}",
"ExerciseStatusNotStarted.count": "{count, number, integer} {count, plural, one {bài tập chưa làm} other {các bài tập chưa làm}}",
"ExerciseStatusNotStarted.countShort": "{count, number, integer} {count, plural, other {chưa làm}}",
"ExerciseStatusNotStarted.label": "{count, plural, one {Bài tập chưa làm} other {Các bài tập chưa làm}}",
"ExerciseStatusNotStarted.labelShort": "{count, plural, other {Chưa làm}}",
"ExerciseStatusNotStarted.ratio": "{count, number, integer} trong số {total, number, integer} {total, plural, one {bài tập} other {các bài tập}} {count, plural, other {chưa làm}}",
"ExerciseStatusNotStarted.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {chưa bắt đầu}}",
"FieldsMixinStrings.allLearners": "Tất cả học viên",
"FieldsMixinStrings.groupsAndIndividuals": "Cả học viên cá nhân và nhóm học viên",
"FieldsMixinStrings.questionsAnswered": "Câu hỏi đã trả lời",
"FieldsMixinStrings.questionsCorrect": "Câu hỏi trả lời đúng",
"FieldsMixinStrings.questionsTotal": "Tổng số câu hỏi",
"FieldsMixinStrings.recipientType": "Được giao cho",
"FieldsMixinStrings.wholeClass": "Cả lớp",
"GroupEnrollPage.allUsersAlready": "Tất cả người dùng đã ghi danh lớp học này",
"GroupEnrollPage.learnerGroups": "Nhóm hiện tại",
"GroupEnrollPage.nextResults": "Kết quả tiếp theo",
"GroupEnrollPage.noUsersMatch": "Không có người dùng nào trùng khớp",
"GroupEnrollPage.pageHeader": "Ghi danh học viên vào '{className}'",
"GroupEnrollPage.pagination": "{ visibleStartRange, number } - { visibleEndRange, number } trong số { numFilteredUsers, number }",
"GroupEnrollPage.previousResults": "Kết quả trước",
"GroupEnrollPage.searchForUser": "Tìm kiếm người dùng",
"GroupEnrollPage.userTableLabel": "Danh Sách Người Dùng",
"GroupMembersPage.back": "Tất cả các nhóm",
"GroupMembersPage.enrollButton": "Ghi danh học viên",
"GroupMembersPage.groupDoesNotExist": "Nhóm này không tồn tại",
"GroupMembersPage.noLearnersInGroup": "Không có học viên nào trong nhóm này",
"GroupsPage.newGroupAction": "Nhóm mới ",
"GroupsPage.noGroups": "Bạn không tham gia vào bất kỳ nhóm nào",
"HomeActivityPage.back": "Trang chủ lớp",
"HomeActivityPage.noActivityLabel": "Không có hoạt động trong lớp của bạn",
"IndividualLearnerSelector.individualLearnersLabel": "Từng cá nhân học viên",
"IndividualLearnerSelector.noUsersMatch": "Không có người dùng nào trùng khớp",
"IndividualLearnerSelector.onlyShowingEnrolledLabel": "Chỉ hiện thị các học viên đã đăng ký vào lớp học này",
"IndividualLearnerSelector.searchPlaceholder": "Tìm kiếm người dùng…",
"IndividualLearnerSelector.selectAllLabel": "Chọn tất cả trên trang",
"IndividualLearnerSelector.selectedIndividualLearnersLabel": "Chọn ra từng cá nhân học viên",
"LearnerQuizReport.noAttemptsInExam": "Câu đố này vẫn chưa bắt đầu",
"LearnersCompleted.allOfMoreThanTwo": "Được hoàn thành bởi tất cả {total, number, integer} {total, plural, one {học viên} other {các học viên}}",
"LearnersCompleted.allOfMoreThanTwoShort": "Được hoàn thành bởi tất cả {total, number, integer}",
"LearnersCompleted.count": "{count, plural, other {Được hoàn thành bởi}} {count, number, integer} {count, plural, one {học viên} other {các học viên}}",
"LearnersCompleted.countShort": "{count, number, integer} {count, plural, other {đã hoàn thành}}",
"LearnersCompleted.label": "{count, plural, one {Được hoàn thành bởi học viên} other {Được hoàn thành bởi các học viên}}",
"LearnersCompleted.labelShort": "{count, plural, other {Đã hoàn thành}}",
"LearnersCompleted.ratio": "{count, plural, other {Được hoàn thành bởi}} {count, number, integer} trên {total, number, integer} {total, plural, one {học viên} other {các học viên}}",
"LearnersCompleted.ratioShort": "{count, plural, other {Được hoàn thành bởi}} {count, number, integer} trên {total, number, integer}",
"LearnersDidNotStart.count": "{count, number, integer} {count, plural, one {học viên chưa bắt đầu} other {các học viên chưa bắt đầu}}",
"LearnersDidNotStart.countShort": "{count, number, integer} {count, plural, one {chưa bắt đầu} other {chưa bắt đầu}}",
"LearnersDidNotStart.label": "{count, plural, one {Học viên chưa bắt đầu} other {Các học viên chưa bắt đầu}}",
"LearnersDidNotStart.labelShort": "{count, plural, one {Chưa bắt đầu} other {Chưa bắt đầu}}",
"LearnersDidNotStart.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {học viên} other {học viên}} {count, plural, one {chưa bắt đầu} other {chưa bắt đầu}}",
"LearnersDidNotStart.ratioShort": "{count, number, integer} trên {total, number, integer} {count, plural, one {chưa bắt đầu} other {chưa bắt đầu}}",
"LearnersNeedHelp.allOfMoreThanTwo": "Tất cả {total, number, integer} học viên cần giúp đỡ",
"LearnersNeedHelp.allOfMoreThanTwoShort": "Tất cả {total, number, integer} cần giúp đỡ",
"LearnersNeedHelp.count": "{count, number, integer} {count, plural, one {học viên cần giúp đỡ} other {các học viên cần giúp đỡ}}",
"LearnersNeedHelp.countShort": "{count, number, integer} {count, plural, one {cần giúp đỡ} other {cần giúp đỡ}}",
"LearnersNeedHelp.label": "{count, plural, one {Học viên cần giúp đỡ} other {Các học viên cần giúp đỡ}}",
"LearnersNeedHelp.labelShort": "{count, plural, one {Cần giúp đỡ} other {Cần giúp đỡ}}",
"LearnersNeedHelp.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {học viên} other {các học viên}} {count, plural, one {cần giúp đỡ} other {cần giúp đỡ}}",
"LearnersNeedHelp.ratioShort": "{count, number, integer} trên {total, number, integer} {count, plural, one {cần giúp đỡ} other {cần giúp đỡ}}",
"LearnersStarted.allOfMoreThanTwo": "Tất cả {total, number, integer} học viên đã bắt đầu",
"LearnersStarted.allOfMoreThanTwoShort": "Tất cả {total, number, integer} đã bắt đầu",
"LearnersStarted.count": "Được bắt đầu bởi {count, number, integer} {count, plural, one {học viên} other {các học viên}}",
"LearnersStarted.countShort": "{count, number, integer} {count, plural, other {đã bắt đầu}}",
"LearnersStarted.label": "{count, plural, one {Học viên đã bắt đầu} other {Các học viên đã bắt đầu}}",
"LearnersStarted.labelShort": "{count, plural, other {Đã bắt đầu}}",
"LearnersStarted.questionsStarted": "Đã trả lời {answeredQuestionsCount} trên {totalQuestionsCount}",
"LearnersStarted.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {học viên} other {các học viên}} {count, plural, one {đã bắt đầu} other {đã bắt đầu}}",
"LearnersStarted.ratioShort": "{count, number, integer} trên {total, number, integer} {count, plural, one {đã bắt đầu} other {đã bắt đầu}}",
"LessonActive.lessonActiveLabel": "Được kích hoạt",
"LessonActive.lessonInactiveLabel": "Không kích hoạt",
"LessonContentCard.viewLabel": "Xem",
"LessonContentPreviewPage.authorDataHeader": "Tác giả",
"LessonContentPreviewPage.completionRequirements": "Hoàn thành: {correct, number} trong số {total, number} câu trả lời đúng",
"LessonContentPreviewPage.copyrightHolderDataHeader": "Chủ sở hữu bản quyền",
"LessonContentPreviewPage.licenseDataHeader": "Giấy phép",
"LessonEditDetailsPage.appBarTitle": "Sửa chi tiết bài học",
"LessonEditDetailsPage.pageTitle": "Sửa chi tiết bài học trong '{title}'",
"LessonEditDetailsPage.submitErrorMessage": "Đã có lỗi xảy ra khi lưu thay đổi",
"LessonOptionsDropdownMenu.copyLessonAction": "Sao chép bài học",
"LessonResourceSelectionPage.documentTitle": "Quản lý nguồn tài liệu trong '{lessonName}'",
"LessonResourceSelectionPage.exitSearchButtonLabel": "Thoát tìm kiếm",
"LessonResourceSelectionPage.manageResourcesAction": "Quản lý tài liệu bài học",
"LessonResourceSelectionPage.resourcesChangedErrorSnackbarText": "Đã có lỗi xảy ra khi cập nhật bài học này",
"LessonResourceSelectionPage.saveBeforeExitSnackbarText": "Đang lưu thay đổi…",
"LessonResourceSelectionPage.selectionInformation": "{count, number, integer} trong số {total, number, integer} nguồn tài liệu được chọn",
"LessonResourceSelectionPage.totalResourcesSelected": "Có {total, number, integer} {total, plural, one {nguồn tài liệu} other {các nguồn tài liệu}} trong bài học này",
"LessonRootActionTexts.newLessonCreated": "Bài học mới đã được soạn",
"LessonStatus.visibleToLearnersLabel": "Hiển thị cho học viên",
"LessonStatusCompleted.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {bài học đã hoàn thành}}",
"LessonStatusCompleted.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đã hoàn thành}}",
"LessonStatusCompleted.count": "{count, number, integer} {count, plural, one {bài học đã hoàn thành} other {các bài học đã hoàn thành}}",
"LessonStatusCompleted.countShort": "{count, number, integer} {count, plural, other {đã hoàn thành}}",
"LessonStatusCompleted.label": "{count, plural, one {Bài học đã hoàn thành} other {Các bài học đã hoàn thành}}",
"LessonStatusCompleted.labelShort": "{count, plural, other {Đã hoàn thành}}",
"LessonStatusCompleted.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {bài học} other {các bài học}} {count, plural, other {đã hoàn thành}}",
"LessonStatusCompleted.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đã hoàn thành}}",
"LessonStatusDifficult.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {bài học đều khó}}",
"LessonStatusDifficult.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đều khó}}",
"LessonStatusDifficult.count": "{count, number, integer} {count, plural, one {bài học khó} other {các bài học khó}}",
"LessonStatusDifficult.countShort": "{count, number, integer} {count, plural, one {khó} other {khó}}",
"LessonStatusDifficult.label": "{count, plural, one {Bài học khó} other {Các bài học khó}}",
"LessonStatusDifficult.labelShort": "{count, plural, other {Khó}}",
"LessonStatusDifficult.ratio": "{count, number, integer} trong số {total, number, integer} {total, plural, one {bài học} other {các bài học}} {count, plural, one {khó} other {khó}}",
"LessonStatusDifficult.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, one {khó} other {khó}}",
"LessonStatusInProgress.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {bài học đang tiến hành}}",
"LessonStatusInProgress.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đang làm}}",
"LessonStatusInProgress.count": "{count, number, integer} {count, plural, one {bài học đang tiến hành} other {bài học đang tiến hành}}",
"LessonStatusInProgress.countShort": "{count, number, integer} {count, plural, other {đang làm}}",
"LessonStatusInProgress.label": "{count, plural, one {Bài học đang tiến hành} other {Bài học đang tiến hành}}",
"LessonStatusInProgress.labelShort": "{count, plural, other {Đang làm}}",
"LessonStatusInProgress.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {bài học} other {các bài học}} {count, plural, other {đang tiến hành}}",
"LessonStatusInProgress.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đang làm}}",
"LessonStatusNotStarted.count": "{count, number, integer} {count, plural, one {bài học chưa bắt đầu} other {các bài học chưa bắt đầu}}",
"LessonStatusNotStarted.countShort": "{count, number, integer} {count, plural, other {chưa làm}}",
"LessonStatusNotStarted.label": "{count, plural, one {Bài học chưa bắt đầu} other {Các bài học chưa bắt đầu}}",
"LessonStatusNotStarted.labelShort": "{count, plural, other {Chưa làm}}",
"LessonStatusNotStarted.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {bài học} other {các bài học}} {count, plural, other {chưa bắt đầu}}",
"LessonStatusNotStarted.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {chưa bắt đầu}}",
"LessonsRootPage.activeLessons": "Bài học được kích hoạt",
"LessonsRootPage.allLessons": "Tất cả bài học",
"LessonsRootPage.duplicateTitle": "Đã có tên bài học này rồi",
"LessonsRootPage.inactiveLessons": "Bài học không được kích hoạt",
"LessonsRootPage.newLessonModalTitle": "Tạo bài học mới",
"LessonsRootPage.noActiveLessons": "Không có bài học được kích hoạt",
"LessonsRootPage.noInactiveLessons": "Không có bài học không được kích hoạt",
"LessonsRootPage.noLessons": "Bạn không có bất kỳ bài học nào",
"LessonsRootPage.saveLessonError": "Đã có lỗi xảy ra khi lưu bài học này",
"LessonsRootPage.size": "Kích cỡ",
"LessonsRootPage.visibleToLearnersLabel": "Hiển thị cho học viên",
"LessonsSearchBox.clearButtonLabel": "Xóa",
"LessonsSearchBox.startSearchButtonLabel": "Bắt đầu tìm kiếm",
"LessonsSearchFilters.audio": "Âm thanh",
"LessonsSearchFilters.channelFilterLabel": "Kênh:",
"LessonsSearchFilters.coachResourcesLabel": "Nguồn tài liệu dành cho giáo viên:",
"LessonsSearchFilters.contentKindFilterLabel": "Loại:",
"LessonsSearchFilters.documents": "Tài liệu",
"LessonsSearchFilters.exercises": "Bài tập",
"LessonsSearchFilters.hideAction": "Ẩn",
"LessonsSearchFilters.html5": "Ứng dụng",
"LessonsSearchFilters.noSearchResultsMessage": "Không có kết quả cho '{searchTerm}'",
"LessonsSearchFilters.searchResultsMessage": "Kết quả cho '{searchTerm}'",
"LessonsSearchFilters.topics": "Chủ đề",
"LessonsSearchFilters.videos": "Video",
"ManageExamModals.assignmentQuestion": "Chỉ định bài kiểm tra đến",
"ManageExamModals.copyExamTitle": "Sao chép bài kiểm tra đến",
"ManageExamModals.copyOfExam": "Bản sao của { examTitle }",
"ManageExamModals.deleteExamConfirmation": "Tất cả tiến bộ làm bài kiểm tra này của học viên sẽ bị mất.",
"ManageExamModals.deleteExamDescription": "Bạn có chắc chắn muốn xóa '{ title }'?",
"ManageExamModals.deleteExamTitle": "Xóa bài kiểm tra",
"ManageLessonModals.assignmentQuestion": "Chỉ định bài học cho",
"ManageLessonModals.copyLessonTitle": "Sao chép bài học đến",
"ManageLessonModals.copyOfLesson": "Bản sao của { lessonTitle }",
"ManageLessonModals.deleteLessonConfirmation": "Bạn có chắc chắn muốn xóa '{ title }'?",
"ManageLessonModals.deleteLessonTitle": "Xóa bài học",
"ManageLessonModals.uniqueTitleError": "Bài học có tên '{title}' đã tồn tại trong '{className}'",
"MasteryModel.doAll": "Trả lời đúng mọi câu hỏi",
"MasteryModel.mOfN": "Trả lời đúng {M, number, integer} trên {N, number, integer} câu hỏi mới đây",
"MasteryModel.one": "Trả lời đúng một câu hỏi",
"MasteryModel.streak": "Trả lời đúng liên tục {count, number, integer} câu hỏi",
"MasteryModel.unknown": "Mẫu chuẩn thành thạo chưa rõ",
"MissingContentStrings.resourceNotFoundOnDevice": "Nguồn tài liệu không được tìm thấy trên thiết bị",
"MissingContentStrings.resourcesUnavailableP1": "Một số dữ liệu báo cáo bị thiếu, có thể vì không tìm thấy nguồn trên thiết bị, hoặc vì nguồn không tương thích với phiên bản Kolibri của bạn",
"MissingContentStrings.resourcesUnavailableP2": "Hãy hỏi người điều hành để được hướng dẫn, hoặc dùng một tài khoản với sự cho phép của thiết bị để quản lý nội dung các kênh",
"MissingContentStrings.resourcesUnavailableTitle": "Nguồn tài liệu không có sẵn",
"MissingContentStrings.someResourcesMissingOrNotSupported": "Một số nguồn tài liệu bị thiếu hoặc không được hỗ trợ",
"MissingContentStrings.upgradeKolibriLinkText": "Đi đến trang tải xuống",
"MissingContentStrings.upgradeKolibriP1": "Một số nguồn tài liệu không được hỗ trợ bởi phiên bản Kolibri này. Có lẽ bạn cần nâng cấp để xem chúng.",
"MissingContentStrings.upgradeKolibriTitle": "Nâng cấp Kolibri để xem tài liệu",
"NotificationStrings.everyoneCompleted": "Mọi người đã hoàn thành '{itemName}'",
"NotificationStrings.everyoneStarted": "Mọi người đã bắt đầu '{itemName}'",
"NotificationStrings.individualCompleted": "{learnerName} đã hoàn thành '{itemName}'",
"NotificationStrings.individualNeedsHelp": "{learnerName} cần giúp đỡ làm '{itemName}'",
"NotificationStrings.individualStarted": "{learnerName} đã bắt đầu '{itemName}'",
"NotificationStrings.multipleCompleted": "{learnerName} và {numOthers, number} {numOthers, plural, one {người khác} other {các người khác}} đã hoàn thành '{itemName}'",
"NotificationStrings.multipleNeedHelp": "{learnerName} và {numOthers, number} {numOthers, plural, one {người khác} other {các người khác}} cần giúp đỡ làm '{itemName}'",
"NotificationStrings.multipleStarted": "{learnerName} và {numOthers, number} {numOthers, plural, one {người khác} other {các người khác}} đã bắt đầu '{itemName}'",
"NotificationStrings.wholeClassCompleted": "Mọi người đã hoàn thành '{itemName}'",
"NotificationStrings.wholeClassStarted": "Mọi người đã bắt đầu '{itemName}'",
"NotificationStrings.wholeGroupCompleted": "Mọi người trong '{groupName}' đã hoàn thành '{itemName}'",
"NotificationStrings.wholeGroupStarted": "Mọi người trong '{groupName}' đã bắt đầu '{itemName}'",
"NotificationsFilter.appsLabel": "Ứng dụng",
"NotificationsFilter.audioLabel": "Âm thanh",
"NotificationsFilter.documentsLabel": "Tài liệu",
"NotificationsFilter.exercisesLabel": "Bài tập",
"NotificationsFilter.progressTypeLabel": "Loại tiến độ",
"NotificationsFilter.resourceTypeLabel": "Loại nguồn tài liệu",
"NotificationsFilter.videosLabel": "Video",
"OverviewBlock.allClassesLabel": "Tất cả lớp học",
"OverviewBlock.coach": "{count, plural, one {Giáo viên} other {Các giáo viên}}",
"OverviewBlock.learner": "{count, plural, one {Học viên} other {Các học viên}}",
"PlanHeader.home": "Trang chủ lớp",
"PlanHeader.planYourClassDescription": "Soạn và quản lý bài học, bài kiểm tra và nhóm của bạn",
"PlanHeader.planYourClassLabel": "Lên kế hoạch cho lớp của bạn",
"PlanLessonSelectionContentPreview.lessonLabel": "Bài học",
"PlanLessonSelectionContentPreview.resourcesAddedSnackbarText": "Đã thêm {count, number, integer} {count, plural, one {nguồn tài liệu} other {các nguồn tài liệu}} vào bài học",
"PlanLessonSelectionContentPreview.resourcesRemovedSnackbarText": "Đã xóa {count, number, integer} {count, plural, one {nguồn tài liệu} other {các nguồn tài liệu}} khỏi bài học",
"PlanQuizPreviewPage.added": "Đã thêm '{item}'",
"PlanQuizPreviewPage.removed": "Đã loại bỏ '{item}'",
"QuestionList.questionListHeader": "{numOfQuestions, number} Câu hỏi",
"QuestionStatusCompleted.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {câu hỏi đã hoàn thành}}",
"QuestionStatusCompleted.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đã hoàn thành}}",
"QuestionStatusCompleted.count": "{count, number, integer} {count, plural, one {câu hỏi đã hoàn thành} other {các câu hỏi đã hoàn thành}}",
"QuestionStatusCompleted.countShort": "{count, number, integer} {count, plural, other {đã hoàn thành}}",
"QuestionStatusCompleted.label": "{count, plural, one {Câu hỏi đã hoàn thành} other {Các câu hỏi đã hoàn thành}}",
"QuestionStatusCompleted.labelShort": "{count, plural, other {Đã hoàn thành}}",
"QuestionStatusCompleted.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {câu hỏi} other {các câu hỏi}} {count, plural, other {đã hoàn thành}}",
"QuestionStatusCompleted.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đã hoàn thành}}",
"QuestionStatusDifficult.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {câu hỏi đều khó}}",
"QuestionStatusDifficult.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đều khó}}",
"QuestionStatusDifficult.count": "{count, number, integer} {count, plural, one {câu hỏi khó} other {các câu hỏi khó}}",
"QuestionStatusDifficult.countShort": "{count, number, integer} {count, plural, one {khó} other {khó}}",
"QuestionStatusDifficult.label": "{count, plural, one {Câu hỏi khó} other {Các câu hỏi khó}}",
"QuestionStatusDifficult.labelShort": "{count, plural, other {Khó}}",
"QuestionStatusDifficult.ratio": "{count, number, integer} trong số {total, number, integer} {total, plural, one {câu hỏi} other {các câu hỏi}} {count, plural, one {khó} other {khó}}",
"QuestionStatusDifficult.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, one {khó} other {khó}}",
"QuestionStatusInProgress.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {câu hỏi đang trả lời}}",
"QuestionStatusInProgress.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đang làm}}",
"QuestionStatusInProgress.count": "{count, number, integer} {count, plural, one {câu hỏi đang trả lời} other {các câu hỏi đang trả lời}}",
"QuestionStatusInProgress.countShort": "{count, number, integer} {count, plural, other {đang làm}}",
"QuestionStatusInProgress.label": "{count, plural, one {Câu hỏi đang trả lời} other {Các câu hỏi đang trả lời}}",
"QuestionStatusInProgress.labelShort": "{count, plural, other {Đang làm}}",
"QuestionStatusInProgress.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {câu hỏi} other {các câu hỏi}} {count, plural, other {đang trả lời}}",
"QuestionStatusInProgress.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đang làm}}",
"QuestionStatusNotStarted.count": "{count, number, integer} {count, plural, one {câu hỏi chưa trả lời} other {các câu hỏi chưa trả lời}}",
"QuestionStatusNotStarted.countShort": "{count, number, integer} {count, plural, other {chưa làm}}",
"QuestionStatusNotStarted.label": "{count, plural, one {Câu hỏi chưa trả lời} other {Các câu hỏi chưa trả lời}}",
"QuestionStatusNotStarted.labelShort": "{count, plural, other {Chưa làm}}",
"QuestionStatusNotStarted.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {câu hỏi} other {các câu hỏi}} {count, plural, other {chưa trả lời}}",
"QuestionStatusNotStarted.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {chưa bắt đầu}}",
"QuizActive.activeQuizLabel": "Được kích hoạt",
"QuizActive.inactiveQuizLabel": "Không kích hoạt",
"QuizEditDetailsPage.appBarTitle": "Sửa chi tiết bài kiểm tra",
"QuizEditDetailsPage.pageTitle": "Sửa chi tiết bài kiểm tra trong '{title}'",
"QuizEditDetailsPage.submitErrorMessage": "Đã có lỗi xảy ra khi lưu thay đổi",
"QuizOptionsDropdownMenu.copyQuizAction": "Sao chép bài kiểm tra",
"QuizStatus.questionOrderLabel": "Thứ tự câu hỏi",
"QuizStatus.reportVisibleToLearnersLabel": "Báo cáo được hiển thị cho học viên",
"QuizStatusCompleted.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {bài kiểm tra đã hoàn thành}}",
"QuizStatusCompleted.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đã hoàn thành}}",
"QuizStatusCompleted.count": "{count, number, integer} {count, plural, one {bài kiểm tra đã hoàn thành} other {các bài kiểm tra đã hoàn thành}}",
"QuizStatusCompleted.countShort": "{count, number, integer} {count, plural, other {đã hoàn thành}}",
"QuizStatusCompleted.label": "{count, plural, one {Bài kiểm tra đã hoàn thành} other {Các bài kiểm tra đã hoàn thành}}",
"QuizStatusCompleted.labelShort": "{count, plural, other {Đã hoàn thành}}",
"QuizStatusCompleted.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {bài kiểm tra} other {các bài kiểm tra}} {count, plural, other {đã hoàn thành}}",
"QuizStatusCompleted.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đã hoàn thành}}",
"QuizStatusDifficult.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {bài kiểm tra khó}}",
"QuizStatusDifficult.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đều khó}}",
"QuizStatusDifficult.count": "{count, number, integer} {count, plural, one {bài kiểm tra khó} other {các bài kiểm tra khó}}",
"QuizStatusDifficult.countShort": "{count, number, integer} {count, plural, one {khó} other {khó}}",
"QuizStatusDifficult.label": "{count, plural, one {Bài kiểm tra khó} other {Các bài kiểm tra khó}}",
"QuizStatusDifficult.labelShort": "{count, plural, other {Khó}}",
"QuizStatusDifficult.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {bài kiểm tra} other {các bài kiểm tra}} {count, plural, one {khó} other {khó}}",
"QuizStatusDifficult.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, one {khó} other {khó}}",
"QuizStatusInProgress.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {bài kiểm tra đang làm}}",
"QuizStatusInProgress.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đang làm}}",
"QuizStatusInProgress.count": "{count, number, integer} {count, plural, one {bài kiểm tra đang làm} other {các bài kiểm tra đang làm}}",
"QuizStatusInProgress.countShort": "{count, number, integer} {count, plural, other {đang làm}}",
"QuizStatusInProgress.label": "{count, plural, one {Bài kiểm tra đang làm} other {Các bài kiểm tra đang làm}}",
"QuizStatusInProgress.labelShort": "{count, plural, other {Đang làm}}",
"QuizStatusInProgress.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {bài kiểm tra} other {các bài kiểm tra}} {count, plural, other {đang làm}}",
"QuizStatusInProgress.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đang làm}}",
"QuizStatusNotStarted.count": "{count, number, integer} {count, plural, one {bài kiểm tra chưa làm} other {các bài kiểm tra chưa làm}}",
"QuizStatusNotStarted.countShort": "{count, number, integer} {count, plural, other {chưa làm}}",
"QuizStatusNotStarted.label": "{count, plural, one {Bài kiểm tra chưa làm} other {Các bài kiểm tra chưa làm}}",
"QuizStatusNotStarted.labelShort": "{count, plural, other {Chưa làm}}",
"QuizStatusNotStarted.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {bài kiểm tra} other {các bài kiểm tra}} {count, plural, other {chưa làm}}",
"QuizStatusNotStarted.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {chưa bắt đầu}}",
"QuizSummaryPage.uniqueTitleError": "Bài kiểm tra có tên '{title}' đã tồn tại trong '{className}'",
"Recipients.noOne": "Không có ai",
"RemoveFromGroupModal.confirmation": "Bạn có chắc chắn muốn loại bỏ '{ username }' khỏi '{ classname }'?",
"RemoveFromGroupModal.modalTitle": "Loại bỏ người dùng",
"RenameGroupModal.duplicateName": "Đã có tên nhóm này rồi",
"RenameGroupModal.renameLearnerGroup": "Đổi tên nhóm",
"ReportsGroupHeader.back": "Tất cả các nhóm",
"ReportsGroupListPage.printLabel": "Nhóm {className}",
"ReportsGroupReportLessonPage.lessonProgressLabel": "Tiến độ '{lesson}'",
"ReportsHeader.description": "Xem báo cáo dành cho học viên và tài liệu lớp học của bạn",
"ReportsHeader.home": "Trang chủ lớp",
"ReportsLearnerHeader.back": "Tất cả học viên",
"ReportsLearnerListPage.printLabel": "Học viên {className}",
"ReportsLessonListPage.activeLessons": "Bài học được kích hoạt",
"ReportsLessonListPage.inactiveLessons": "Bài học không được kích hoạt",
"ReportsLessonListPage.noActiveLessons": "Không có bài học được kích hoạt",
"ReportsLessonListPage.noInactiveLessons": "Không có bài học không được kích hoạt",
"ReportsLessonListPage.printLabel": "Bài học {className}",
"ReportsLessonListPage.visibleToLearnersLabel": "Hiển thị cho học viên",
"ReportsQuizBaseListPage.activeQuizzes": "Các bài kiểm tra được kích hoạt",
"ReportsQuizBaseListPage.allQuizzes": "Tất cả bài kiểm tra",
"ReportsQuizBaseListPage.inactiveQuizzes": "Các bài kiểm tra không được kích hoạt",
"ReportsQuizLearnerListPage.activeQuizzes": "Các bài kiểm tra được kích hoạt",
"ReportsQuizLearnerListPage.allQuestionsAnswered": "Đã trả lời tất cả câu hỏi",
"ReportsQuizLearnerListPage.allQuizzes": "Tất cả bài kiểm tra",
"ReportsQuizLearnerListPage.inactiveQuizzes": "Các bài kiểm tra không được kích hoạt",
"ReportsQuizLearnerListPage.questionsCompletedRatioLabel": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đã hoàn thành}}",
"ReportsQuizListPage.noActiveExams": "Không có bài kiểm tra nào được kích hoạt",
"ReportsQuizListPage.noInactiveExams": "Không có bài kiểm tra nào không được kích hoạt",
"ReportsQuizListPage.printLabel": "Bài kiểm tra {className}",
"ReportsQuizPreviewPage.pageTitle": "Xem trước bài kiểm tra '{title}'",
"ResourceListTable.moveResourceDownButtonDescription": "Di chuyển nguồn tài liệu này xuống dưới một vị trí trong bài học này",
"ResourceListTable.moveResourceUpButtonDescription": "Di chuyển nguồn tài liệu này lên trên một vị trí trong bài học này",
"ResourceListTable.parentChannelLabel": "Kênh chính:",
"ResourceListTable.undoActionPrompt": "Hoàn tác",
"ResourceStatusCompleted.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {nguồn tài liệu đã hoàn thành}}",
"ResourceStatusCompleted.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đã hoàn thành}}",
"ResourceStatusCompleted.count": "{count, number, integer} {count, plural, one {nguồn tài liệu đã hoàn thành} other {các nguồn tài liệu đã hoàn thành}}",
"ResourceStatusCompleted.countShort": "{count, number, integer} {count, plural, other {đã hoàn thành}}",
"ResourceStatusCompleted.label": "{count, plural, one {Nguồn tài liệu đã hoàn thành} other {Các nguồn tài liệu đã hoàn thành}}",
"ResourceStatusCompleted.labelShort": "{count, plural, other {Đã hoàn thành}}",
"ResourceStatusCompleted.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {nguồn tài liệu} other {các nguồn tài liệu}} {count, plural, other {đã hoàn thành}}",
"ResourceStatusCompleted.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đã hoàn thành}}",
"ResourceStatusDifficult.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {tài liệu đều khó}}",
"ResourceStatusDifficult.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đều khó}}",
"ResourceStatusDifficult.count": "{count, number, integer} {count, plural, one {nguồn tài liệu khó} other {các nguồn tài liệu khó}}",
"ResourceStatusDifficult.countShort": "{count, number, integer} {count, plural, one {khó} other {khó}}",
"ResourceStatusDifficult.label": "{count, plural, one {Nguồn tài liệu khó} other {Các nguồn tài liệu khó}}",
"ResourceStatusDifficult.labelShort": "{count, plural, other {Khó}}",
"ResourceStatusDifficult.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {nguồn tài liệu} other {các nguồn tài liệu}} {count, plural, one {khó} other {khó}}",
"ResourceStatusDifficult.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, one {khó} other {khó}}",
"ResourceStatusInProgress.allOfMoreThanTwo": "Tất cả {count, number, integer} {count, plural, other {nguồn tài liệu đang mở xem}}",
"ResourceStatusInProgress.allOfMoreThanTwoShort": "Tất cả {count, number, integer} {count, plural, other {đang làm}}",
"ResourceStatusInProgress.count": "{count, number, integer} {count, plural, one {nguồn tài liệu đang mở xem} other {các nguồn tài liệu đang mở xem}}",
"ResourceStatusInProgress.countShort": "{count, number, integer} {count, plural, other {đang làm}}",
"ResourceStatusInProgress.label": "{count, plural, one {Nguồn tài liệu đang mở xem} other {Các nguồn tài liệu đang mở xem}}",
"ResourceStatusInProgress.labelShort": "{count, plural, other {Đang làm}}",
"ResourceStatusInProgress.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {nguồn tài liệu} other {các nguồn tài liệu}} {count, plural, other {đang xem}}",
"ResourceStatusInProgress.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {đang làm}}",
"ResourceStatusNotStarted.count": "{count, number, integer} {count, plural, one {nguồn tài liệu chưa xem} other {các nguồn tài liệu chưa xem}}",
"ResourceStatusNotStarted.countShort": "{count, number, integer} {count, plural, other {chưa làm}}",
"ResourceStatusNotStarted.label": "{count, plural, one {Nguồn tài liệu chưa xem} other {Các nguồn tài liệu chưa xem}}",
"ResourceStatusNotStarted.labelShort": "{count, plural, other {Chưa làm}}",
"ResourceStatusNotStarted.ratio": "{count, number, integer} trên {total, number, integer} {total, plural, one {nguồn tài liệu} other {các nguồn tài liệu}} {count, plural, other {chưa xem}}",
"ResourceStatusNotStarted.ratioShort": "{count, number, integer} trong số {total, number, integer} {count, plural, other {chưa bắt đầu}}",
"SelectOptions.addButtonLabel": "Thêm",
"SelectOptions.addedIndicator": "Đã được thêm vào",
"StatusElapsedTime.closedDaysAgo": "Đã kết thúc {days} {days, plural, one {ngày} other {ngày}} trước",
"StatusElapsedTime.closedHoursAgo": "Đã kết thúc {hours} {hours, plural, one {giờ} other {giờ}} trước",
"StatusElapsedTime.closedMinutesAgo": "Đã kết thúc {minutes} {minutes, plural, one {phút} other {phút}} trước",
"StatusElapsedTime.closedSecondsAgo": "Đã kết thúc {seconds} {seconds, plural, one {giây} other {giây}} trước",
"StatusElapsedTime.createdDaysAgo": "Đã tạo {days} {days, plural, one {ngày} other {ngày}} trước",
"StatusElapsedTime.createdHoursAgo": "Đã tạo {hours} {hours, plural, one {giờ} other {giờ}} trước",
"StatusElapsedTime.createdMinutesAgo": "Đã tạo {minutes} {minutes, plural, one {phút} other {phút}} trước",
"StatusElapsedTime.createdSecondsAgo": "Đã tạo {seconds} {seconds, plural, one {giây} other {giây}} trước",
"StatusElapsedTime.openedDaysAgo": "Đã bắt đầu {days} {days, plural, one {ngày} other {ngày}} trước",
"StatusElapsedTime.openedHoursAgo": "Đã bắt đầu {hours} {hours, plural, one {giờ} other {giờ}} trước",
"StatusElapsedTime.openedMinutesAgo": "Đã bắt đầu {minutes} {minutes, plural, one {phút} other {phút}} trước",
"StatusElapsedTime.openedSecondsAgo": "Đã bắt đầu {seconds} {seconds, plural, one {giây} other {giây}} trước",
"TimeDuration.days": "{value, number, integer} {value, plural, one {ngày} other {các ngày}}",
"TimeDuration.hours": "{value, number, integer} {value, plural, one {giờ} other {các giờ}}",
"TimeDuration.minutes": "{value, number, integer} {value, plural, one {phút} other {các phút}}",
"TimeDuration.seconds": "{value, number, integer} {value, plural, one {giây} other {các giây}}",
"TopNavbar.home": "Trang chủ lớp",
"TopNavbar.plan": "Kế hoạch",
"TruncatedItemList.manyItems": "{item1}, {item2}, và {count, number, integer} khác",
"TruncatedItemList.threeItems": "{item1}, {item2}, {item3}",
"TruncatedItemList.twoItems": "{item1}, {item2}",
"UserTable.role": "Vai trò",
"UserTable.selectAllLabel": "Chọn tất cả",
"UserTable.userActionsColumnHeader": "Hành động",
"UserTable.userCheckboxLabel": "Chọn người dùng"
}
|
{
"pile_set_name": "Github"
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <fstream>
#include <fstream>
#include "test_macros.h"
#ifndef _LIBCPP_VERSION
#error _LIBCPP_VERSION not defined
#endif
int main(int, char**)
{
return 0;
}
|
{
"pile_set_name": "Github"
}
|
// Scintilla source code edit control
/** @file PlatWin.cxx
** Implementation of platform facilities on Windows.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <Platform.h>
#include <Scintilla.h>
#include <scintilla-internal.h>
#pragma hdrstop
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#undef WINVER
#define WINVER 0x0500
#include <windowsx.h>
#if defined(NTDDI_WIN7) && !defined(DISABLE_D2D)
#define USE_D2D 1
#endif
#if defined(USE_D2D)
#include <d2d1.h>
#include <dwrite.h>
#endif
//#include "XPM.h"
//#include "FontQuality.h"
#ifndef IDC_HAND
#define IDC_HAND MAKEINTRESOURCE(32649)
#endif
#ifndef SPI_GETFONTSMOOTHINGCONTRAST
#define SPI_GETFONTSMOOTHINGCONTRAST 0x200C
#endif
static void * PointerFromWindow(HWND hWnd)
{
return reinterpret_cast<void *>(::GetWindowLongPtr(hWnd, 0));
}
static void SetWindowPointer(HWND hWnd, void * ptr)
{
::SetWindowLongPtr(hWnd, 0, reinterpret_cast<LONG_PTR>(ptr));
}
extern UINT CodePageFromCharSet(DWORD characterSet, UINT documentCodePage);
// Declarations needed for functions dynamically loaded as not available on all Windows versions.
typedef BOOL (WINAPI *AlphaBlendSig)(HDC, int, int, int, int, HDC, int, int, int, int, BLENDFUNCTION);
typedef HMONITOR (WINAPI *MonitorFromPointSig)(POINT, DWORD);
typedef HMONITOR (WINAPI *MonitorFromRectSig)(LPCRECT, DWORD);
typedef BOOL (WINAPI *GetMonitorInfoSig)(HMONITOR, LPMONITORINFO);
static CRITICAL_SECTION crPlatformLock;
static HINSTANCE hinstPlatformRes = 0;
static HMODULE hDLLImage = 0;
static AlphaBlendSig AlphaBlendFn = 0;
static HMODULE hDLLUser32 = 0;
static HMONITOR (WINAPI * MonitorFromPointFn)(POINT, DWORD) = 0;
static HMONITOR (WINAPI * MonitorFromRectFn)(LPCRECT, DWORD) = 0;
static BOOL (WINAPI * GetMonitorInfoFn)(HMONITOR, LPMONITORINFO) = 0;
static HCURSOR reverseArrowCursor = NULL;
#ifdef SCI_NAMESPACE
namespace Scintilla {
#endif
//static
Point FASTCALL Point::FromInts(int x_, int y_)
{
return Point(static_cast<XYPOSITION>(x_), static_cast<XYPOSITION>(y_));
}
Point FASTCALL Point::FromLong(long lpoint)
{
return Point(static_cast<short>(LOWORD(lpoint)), static_cast<short>(HIWORD(lpoint)));
}
static RECT RectFromPRectangle(PRectangle prc)
{
RECT rc = { static_cast<LONG>(prc.left), static_cast<LONG>(prc.top), static_cast<LONG>(prc.right), static_cast<LONG>(prc.bottom) };
return rc;
}
#if defined(USE_D2D)
IDWriteFactory * pIDWriteFactory = 0;
ID2D1Factory * pD2DFactory = 0;
IDWriteRenderingParams * defaultRenderingParams = 0;
IDWriteRenderingParams * customClearTypeRenderingParams = 0;
static HMODULE hDLLD2D = NULL;
static HMODULE hDLLDWrite = NULL;
bool LoadD2D()
{
static bool triedLoadingD2D = false;
if(!triedLoadingD2D) {
typedef HRESULT (WINAPI *D2D1CFSig)(D2D1_FACTORY_TYPE factoryType, REFIID riid, CONST D2D1_FACTORY_OPTIONS * pFactoryOptions, IUnknown ** factory);
typedef HRESULT (WINAPI *DWriteCFSig)(DWRITE_FACTORY_TYPE factoryType, REFIID iid, IUnknown ** factory);
hDLLD2D = ::LoadLibraryEx(TEXT("D2D1.DLL"), 0, 0x00000800 /*LOAD_LIBRARY_SEARCH_SYSTEM32*/);
if(hDLLD2D) {
D2D1CFSig fnD2DCF = (D2D1CFSig) ::GetProcAddress(hDLLD2D, "D2D1CreateFactory");
if(fnD2DCF) {
// A single threaded factory as Scintilla always draw on the GUI thread
fnD2DCF(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory), 0, reinterpret_cast<IUnknown**>(&pD2DFactory));
}
}
hDLLDWrite = ::LoadLibraryEx(TEXT("DWRITE.DLL"), 0, 0x00000800 /*LOAD_LIBRARY_SEARCH_SYSTEM32*/);
if(hDLLDWrite) {
DWriteCFSig fnDWCF = (DWriteCFSig) ::GetProcAddress(hDLLDWrite, "DWriteCreateFactory");
if(fnDWCF) {
fnDWCF(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown**>(&pIDWriteFactory));
}
}
if(pIDWriteFactory) {
HRESULT hr = pIDWriteFactory->CreateRenderingParams(&defaultRenderingParams);
if(SUCCEEDED(hr)) {
uint clearTypeContrast;
if(::SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &clearTypeContrast, 0)) {
FLOAT gamma;
if(clearTypeContrast >= 1000 && clearTypeContrast <= 2200)
gamma = static_cast<FLOAT>(clearTypeContrast) / 1000.0f;
else
gamma = defaultRenderingParams->GetGamma();
pIDWriteFactory->CreateCustomRenderingParams(gamma,
defaultRenderingParams->GetEnhancedContrast(), defaultRenderingParams->GetClearTypeLevel(),
defaultRenderingParams->GetPixelGeometry(),
defaultRenderingParams->GetRenderingMode(), &customClearTypeRenderingParams);
}
}
}
}
triedLoadingD2D = true;
return pIDWriteFactory && pD2DFactory;
}
#endif
struct FormatAndMetrics {
int technology;
HFONT hfont;
#if defined(USE_D2D)
IDWriteTextFormat * pTextFormat;
#endif
int extraFontFlag;
int characterSet;
FLOAT yAscent;
FLOAT yDescent;
FLOAT yInternalLeading;
FormatAndMetrics(HFONT hfont_, int extraFontFlag_, int characterSet_) : technology(SCWIN_TECH_GDI), hfont(hfont_),
#if defined(USE_D2D)
pTextFormat(0),
#endif
extraFontFlag(extraFontFlag_), characterSet(characterSet_), yAscent(2), yDescent(1), yInternalLeading(0)
{
}
#if defined(USE_D2D)
FormatAndMetrics(IDWriteTextFormat * pTextFormat_, int extraFontFlag_, int characterSet_, FLOAT yAscent_, FLOAT yDescent_, FLOAT yInternalLeading_) :
technology(SCWIN_TECH_DIRECTWRITE), hfont(0), pTextFormat(pTextFormat_), extraFontFlag(extraFontFlag_), characterSet(characterSet_),
yAscent(yAscent_), yDescent(yDescent_), yInternalLeading(yInternalLeading_)
{
}
#endif
~FormatAndMetrics()
{
if(hfont)
::DeleteObject(hfont);
#if defined(USE_D2D)
CALLPTRMEMB(pTextFormat, Release());
pTextFormat = 0;
#endif
extraFontFlag = 0;
characterSet = 0;
yAscent = 2;
yDescent = 1;
yInternalLeading = 0;
}
HFONT HFont();
};
HFONT FormatAndMetrics::HFont()
{
LOGFONTW lf = {};
#if defined(USE_D2D)
if(technology == SCWIN_TECH_GDI) {
if(0 == ::GetObjectW(hfont, sizeof(lf), &lf)) {
return 0;
}
}
else {
HRESULT hr = pTextFormat->GetFontFamilyName(lf.lfFaceName, LF_FACESIZE);
if(!SUCCEEDED(hr)) {
return 0;
}
lf.lfWeight = pTextFormat->GetFontWeight();
lf.lfItalic = pTextFormat->GetFontStyle() == DWRITE_FONT_STYLE_ITALIC;
lf.lfHeight = -static_cast<int>(pTextFormat->GetFontSize());
}
#else
if(0 == ::GetObjectW(hfont, sizeof(lf), &lf)) {
return 0;
}
#endif
return ::CreateFontIndirectW(&lf);
}
#ifndef CLEARTYPE_QUALITY
#define CLEARTYPE_QUALITY 5
#endif
static BYTE FASTCALL Win32MapFontQuality(int extraFontFlag)
{
switch(extraFontFlag & SC_EFF_QUALITY_MASK) {
case SC_EFF_QUALITY_NON_ANTIALIASED: return NONANTIALIASED_QUALITY;
case SC_EFF_QUALITY_ANTIALIASED: return ANTIALIASED_QUALITY;
case SC_EFF_QUALITY_LCD_OPTIMIZED: return CLEARTYPE_QUALITY;
default: return SC_EFF_QUALITY_DEFAULT;
}
}
#if defined(USE_D2D)
static D2D1_TEXT_ANTIALIAS_MODE DWriteMapFontQuality(int extraFontFlag)
{
switch(extraFontFlag & SC_EFF_QUALITY_MASK) {
case SC_EFF_QUALITY_NON_ANTIALIASED: return D2D1_TEXT_ANTIALIAS_MODE_ALIASED;
case SC_EFF_QUALITY_ANTIALIASED: return D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE;
case SC_EFF_QUALITY_LCD_OPTIMIZED: return D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE;
default: return D2D1_TEXT_ANTIALIAS_MODE_DEFAULT;
}
}
#endif
static void SetLogFont(LOGFONTW &lf, const char * faceName, int characterSet, float size, int weight, bool italic, int extraFontFlag)
{
lf = LOGFONTW();
// The negative is to allow for leading
lf.lfHeight = -(abs(static_cast<int>(size + 0.5)));
lf.lfWeight = weight;
lf.lfItalic = static_cast<BYTE>(italic ? 1 : 0);
lf.lfCharSet = static_cast<BYTE>(characterSet);
lf.lfQuality = Win32MapFontQuality(extraFontFlag);
UTF16FromUTF8(faceName, sstrlen(faceName)+1, lf.lfFaceName, LF_FACESIZE);
}
/**
* Create a hash from the parameters for a font to allow easy checking for identity.
* If one font is the same as another, its hash will be the same, but if the hash is the
* same then they may still be different.
*/
static int HashFont(const FontParameters &fp)
{
return
static_cast<int>(fp.size) ^
(fp.characterSet << 10) ^
((fp.extraFontFlag & SC_EFF_QUALITY_MASK) << 9) ^
((fp.weight/100) << 12) ^
(fp.italic ? 0x20000000 : 0) ^
(fp.technology << 15) ^
fp.faceName[0];
}
class FontCached : Font {
public:
static FontID FindOrCreate(const FontParameters &fp);
static void ReleaseId(FontID fid_);
private:
explicit FontCached(const FontParameters &fp);
~FontCached()
{
}
bool SameAs(const FontParameters &fp);
virtual void Release();
static FontCached * first;
FontCached * next;
int usage;
float size;
LOGFONTW lf;
int technology;
int hash;
};
FontCached * FontCached::first = 0;
FontCached::FontCached(const FontParameters &fp) : next(0), usage(0), size(1.0), hash(0)
{
SetLogFont(lf, fp.faceName, fp.characterSet, fp.size, fp.weight, fp.italic, fp.extraFontFlag);
technology = fp.technology;
hash = HashFont(fp);
fid = 0;
if(technology == SCWIN_TECH_GDI) {
HFONT hfont = ::CreateFontIndirectW(&lf);
fid = static_cast<void *>(new FormatAndMetrics(hfont, fp.extraFontFlag, fp.characterSet));
}
else {
#if defined(USE_D2D)
IDWriteTextFormat * pTextFormat;
const int faceSize = 200;
WCHAR wszFace[faceSize];
UTF16FromUTF8(fp.faceName, sstrlen(fp.faceName)+1, wszFace, faceSize);
FLOAT fHeight = fp.size;
DWRITE_FONT_STYLE style = fp.italic ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
HRESULT hr = pIDWriteFactory->CreateTextFormat(wszFace, NULL, static_cast<DWRITE_FONT_WEIGHT>(fp.weight), style, DWRITE_FONT_STRETCH_NORMAL, fHeight, L"en-us", &pTextFormat);
if(SUCCEEDED(hr)) {
pTextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
const int maxLines = 2;
DWRITE_LINE_METRICS lineMetrics[maxLines];
UINT32 lineCount = 0;
FLOAT yAscent = 1.0f;
FLOAT yDescent = 1.0f;
FLOAT yInternalLeading = 0.0f;
IDWriteTextLayout * pTextLayout = 0;
hr = pIDWriteFactory->CreateTextLayout(L"X", 1, pTextFormat, 100.0f, 100.0f, &pTextLayout);
if(SUCCEEDED(hr)) {
hr = pTextLayout->GetLineMetrics(lineMetrics, maxLines, &lineCount);
if(SUCCEEDED(hr)) {
yAscent = lineMetrics[0].baseline;
yDescent = lineMetrics[0].height - lineMetrics[0].baseline;
FLOAT emHeight;
hr = pTextLayout->GetFontSize(0, &emHeight);
if(SUCCEEDED(hr)) {
yInternalLeading = lineMetrics[0].height - emHeight;
}
}
pTextLayout->Release();
pTextFormat->SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM,
lineMetrics[0].height, lineMetrics[0].baseline);
}
fid = static_cast<void *>(new FormatAndMetrics(pTextFormat, fp.extraFontFlag, fp.characterSet, yAscent, yDescent, yInternalLeading));
}
#endif
}
usage = 1;
}
bool FontCached::SameAs(const FontParameters &fp)
{
if(
(size == fp.size) &&
(lf.lfWeight == fp.weight) &&
(lf.lfItalic == static_cast<BYTE>(fp.italic ? 1 : 0)) &&
(lf.lfCharSet == fp.characterSet) &&
(lf.lfQuality == Win32MapFontQuality(fp.extraFontFlag)) &&
(technology == fp.technology)) {
wchar_t wszFace[LF_FACESIZE];
UTF16FromUTF8(fp.faceName, sstrlen(fp.faceName)+1, wszFace, LF_FACESIZE);
return 0 == wcscmp(lf.lfFaceName, wszFace);
}
return false;
}
void FontCached::Release()
{
delete static_cast<FormatAndMetrics *>(fid);
fid = 0;
}
FontID FontCached::FindOrCreate(const FontParameters &fp)
{
FontID ret = 0;
::EnterCriticalSection(&crPlatformLock);
int hashFind = HashFont(fp);
for(FontCached * cur = first; cur; cur = cur->next) {
if((cur->hash == hashFind) &&
cur->SameAs(fp)) {
cur->usage++;
ret = cur->fid;
}
}
if(!ret) {
FontCached * fc = new FontCached(fp);
fc->next = first;
first = fc;
ret = fc->fid;
}
::LeaveCriticalSection(&crPlatformLock);
return ret;
}
void FontCached::ReleaseId(FontID fid_)
{
::EnterCriticalSection(&crPlatformLock);
FontCached ** pcur = &first;
for(FontCached * cur = first; cur; cur = cur->next) {
if(cur->fid == fid_) {
cur->usage--;
if(cur->usage == 0) {
*pcur = cur->next;
cur->Release();
cur->next = 0;
delete cur;
}
break;
}
pcur = &cur->next;
}
::LeaveCriticalSection(&crPlatformLock);
}
FontParameters::FontParameters(const char * faceName_, float size_, int weight_,
bool italic_, int extraFontFlag_, int technology_, int characterSet_) :
faceName(faceName_), size(size_), weight(weight_), italic(italic_), extraFontFlag(extraFontFlag_),
technology(technology_), characterSet(characterSet_)
{
}
Font::Font()
{
fid = 0;
}
Font::~Font()
{
}
#define FONTS_CACHED
void Font::Create(const FontParameters &fp)
{
Release();
if(fp.faceName)
fid = FontCached::FindOrCreate(fp);
}
void Font::Release()
{
if(fid)
FontCached::ReleaseId(fid);
fid = 0;
}
// Buffer to hold strings and string position arrays without always allocating on heap.
// May sometimes have string too long to allocate on stack. So use a fixed stack-allocated buffer
// when less than safe size otherwise allocate on heap and free automatically.
template <typename T, int lengthStandard> class VarBuffer {
T bufferStandard[lengthStandard];
// Private so VarBuffer objects can not be copied
VarBuffer(const VarBuffer &);
VarBuffer & operator = (const VarBuffer &);
public:
T * buffer;
explicit VarBuffer(size_t length) : buffer(0)
{
buffer = (length > lengthStandard) ? new T[length] : bufferStandard;
}
~VarBuffer()
{
if(buffer != bufferStandard) {
delete []buffer;
buffer = 0;
}
}
};
const int stackBufferLength = 1000;
class TextWide : public VarBuffer<wchar_t, stackBufferLength> {
public:
int tlen;
TextWide(const char * s, int len, bool unicodeMode, int codePage = 0) : VarBuffer<wchar_t, stackBufferLength>(len)
{
if(unicodeMode) {
tlen = static_cast<int>(UTF16FromUTF8(s, len, buffer, len));
}
else {
// Support Asian string display in 9x English
tlen = ::MultiByteToWideChar(codePage, 0, s, len, buffer, len);
}
}
};
typedef VarBuffer<XYPOSITION, stackBufferLength> TextPositions;
class SurfaceGDI : public Surface {
bool unicodeMode;
HDC hdc;
bool hdcOwned;
HPEN pen;
HPEN penOld;
HBRUSH brush;
HBRUSH brushOld;
HFONT font;
HFONT fontOld;
HBITMAP bitmap;
HBITMAP bitmapOld;
int maxWidthMeasure;
int maxLenText;
int codePage;
void BrushColor(ColourDesired back);
void SetFont(Font &font_);
// Private so SurfaceGDI objects can not be copied
SurfaceGDI(const SurfaceGDI &);
SurfaceGDI & operator = (const SurfaceGDI &);
public:
SurfaceGDI();
virtual ~SurfaceGDI();
void Init(WindowID wid);
void Init(SurfaceID sid, WindowID wid);
void InitPixMap(int width, int height, Surface * surface_, WindowID wid);
void Release();
bool Initialised();
void PenColour(ColourDesired fore);
int LogPixelsY();
int DeviceHeightFont(int points);
void MoveTo(int x_, int y_);
void LineTo(int x_, int y_);
void Polygon(Point * pts, int npts, ColourDesired fore, ColourDesired back);
void RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back);
void FillRectangle(PRectangle rc, ColourDesired back);
void FillRectangle(PRectangle rc, Surface &surfacePattern);
void RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back);
void AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill, ColourDesired outline, int alphaOutline, int flags);
void DrawRGBAImage(PRectangle rc, int width, int height, const uchar * pixelsImage);
void Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back);
void Copy(PRectangle rc, Point from, Surface &surfaceSource);
void DrawTextCommon(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len, UINT fuOptions);
void DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len, ColourDesired fore, ColourDesired back);
void DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len, ColourDesired fore, ColourDesired back);
void DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len, ColourDesired fore);
void MeasureWidths(Font &font_, const char * s, int len, XYPOSITION * positions);
XYPOSITION WidthText(Font &font_, const char * s, int len);
XYPOSITION WidthChar(Font &font_, char ch);
XYPOSITION Ascent(Font &font_);
XYPOSITION Descent(Font &font_);
XYPOSITION InternalLeading(Font &font_);
XYPOSITION ExternalLeading(Font &font_);
XYPOSITION Height(Font &font_);
XYPOSITION AverageCharWidth(Font &font_);
void SetClip(PRectangle rc);
void FlushCachedState();
void SetUnicodeMode(bool unicodeMode_);
void SetDBCSMode(int codePage_);
};
SurfaceGDI::SurfaceGDI() : unicodeMode(false), hdc(0), hdcOwned(false), pen(0), penOld(0), brush(0), brushOld(0), font(0), fontOld(0), bitmap(0), bitmapOld(0)
{
maxWidthMeasure = INT_MAX;
// There appears to be a 16 bit string length limit in GDI on NT.
maxLenText = 65535;
codePage = 0;
}
SurfaceGDI::~SurfaceGDI()
{
Release();
}
void SurfaceGDI::Release()
{
if(penOld) {
::SelectObject(hdc, penOld);
::DeleteObject(pen);
penOld = 0;
}
pen = 0;
if(brushOld) {
::SelectObject(hdc, brushOld);
::DeleteObject(brush);
brushOld = 0;
}
brush = 0;
if(fontOld) {
// Fonts are not deleted as they are owned by a Font object
::SelectObject(hdc, fontOld);
fontOld = 0;
}
font = 0;
if(bitmapOld) {
::SelectObject(hdc, bitmapOld);
::DeleteObject(bitmap);
bitmapOld = 0;
}
bitmap = 0;
if(hdcOwned) {
::DeleteDC(hdc);
hdc = 0;
hdcOwned = false;
}
}
bool SurfaceGDI::Initialised()
{
return hdc != 0;
}
void SurfaceGDI::Init(WindowID)
{
Release();
hdc = ::CreateCompatibleDC(NULL);
hdcOwned = true;
::SetTextAlign(hdc, TA_BASELINE);
}
void SurfaceGDI::Init(SurfaceID sid, WindowID)
{
Release();
hdc = static_cast<HDC>(sid);
::SetTextAlign(hdc, TA_BASELINE);
}
void SurfaceGDI::InitPixMap(int width, int height, Surface * surface_, WindowID)
{
Release();
SurfaceGDI * psurfOther = static_cast<SurfaceGDI *>(surface_);
hdc = ::CreateCompatibleDC(psurfOther->hdc);
hdcOwned = true;
bitmap = ::CreateCompatibleBitmap(psurfOther->hdc, width, height);
bitmapOld = static_cast<HBITMAP>(::SelectObject(hdc, bitmap));
::SetTextAlign(hdc, TA_BASELINE);
SetUnicodeMode(psurfOther->unicodeMode);
SetDBCSMode(psurfOther->codePage);
}
void SurfaceGDI::PenColour(ColourDesired fore)
{
if(pen) {
::SelectObject(hdc, penOld);
::DeleteObject(pen);
pen = 0;
penOld = 0;
}
pen = ::CreatePen(0, 1, fore.AsLong());
penOld = static_cast<HPEN>(::SelectObject(hdc, pen));
}
void SurfaceGDI::BrushColor(ColourDesired back)
{
if(brush) {
::SelectObject(hdc, brushOld);
::DeleteObject(brush);
brush = 0;
brushOld = 0;
}
// Only ever want pure, non-dithered brushes
ColourDesired colourNearest = ::GetNearestColor(hdc, back.AsLong());
brush = ::CreateSolidBrush(colourNearest.AsLong());
brushOld = static_cast<HBRUSH>(::SelectObject(hdc, brush));
}
void SurfaceGDI::SetFont(Font &font_)
{
if(font_.GetID() != font) {
FormatAndMetrics * pfm = static_cast<FormatAndMetrics *>(font_.GetID());
PLATFORM_ASSERT(pfm->technology == SCWIN_TECH_GDI);
if(fontOld) {
::SelectObject(hdc, pfm->hfont);
}
else {
fontOld = static_cast<HFONT>(::SelectObject(hdc, pfm->hfont));
}
font = pfm->hfont;
}
}
int SurfaceGDI::LogPixelsY()
{
return ::GetDeviceCaps(hdc, LOGPIXELSY);
}
int SurfaceGDI::DeviceHeightFont(int points)
{
return ::MulDiv(points, LogPixelsY(), 72);
}
void SurfaceGDI::MoveTo(int x_, int y_)
{
::MoveToEx(hdc, x_, y_, 0);
}
void SurfaceGDI::LineTo(int x_, int y_)
{
::LineTo(hdc, x_, y_);
}
void SurfaceGDI::Polygon(Point * pts, int npts, ColourDesired fore, ColourDesired back)
{
PenColour(fore);
BrushColor(back);
std::vector<POINT> outline;
for(int i = 0; i<npts; i++) {
POINT pt = {static_cast<LONG>(pts[i].x), static_cast<LONG>(pts[i].y)};
outline.push_back(pt);
}
::Polygon(hdc, &outline[0], npts);
}
void SurfaceGDI::RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back)
{
PenColour(fore);
BrushColor(back);
const RECT rcw = RectFromPRectangle(rc);
::Rectangle(hdc, rcw.left, rcw.top, rcw.right, rcw.bottom);
}
void SurfaceGDI::FillRectangle(PRectangle rc, ColourDesired back)
{
// Using ExtTextOut rather than a FillRect ensures that no dithering occurs.
// There is no need to allocate a brush either.
RECT rcw = RectFromPRectangle(rc);
::SetBkColor(hdc, back.AsLong());
::ExtTextOut(hdc, rcw.left, rcw.top, ETO_OPAQUE, &rcw, TEXT(""), 0, 0);
}
void SurfaceGDI::FillRectangle(PRectangle rc, Surface &surfacePattern)
{
HBRUSH br;
if(static_cast<SurfaceGDI &>(surfacePattern).bitmap)
br = ::CreatePatternBrush(static_cast<SurfaceGDI &>(surfacePattern).bitmap);
else // Something is wrong so display in red
br = ::CreateSolidBrush(RGB(0xff, 0, 0));
RECT rcw = RectFromPRectangle(rc);
::FillRect(hdc, &rcw, br);
::DeleteObject(br);
}
void SurfaceGDI::RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back)
{
PenColour(fore);
BrushColor(back);
const RECT rcw = RectFromPRectangle(rc);
::RoundRect(hdc, rcw.left + 1, rcw.top, rcw.right - 1, rcw.bottom, 8, 8);
}
// Plot a point into a DWORD buffer symmetrically to all 4 quadrants
static void AllFour(DWORD * pixels, int width, int height, int x, int y, DWORD val)
{
pixels[y*width+x] = val;
pixels[y*width+width-1-x] = val;
pixels[(height-1-y)*width+x] = val;
pixels[(height-1-y)*width+width-1-x] = val;
}
#ifndef AC_SRC_OVER
#define AC_SRC_OVER 0x00
#endif
#ifndef AC_SRC_ALPHA
#define AC_SRC_ALPHA 0x01
#endif
static DWORD dwordFromBGRA(byte b, byte g, byte r, byte a)
{
union {
byte pixVal[4];
DWORD val;
} converter;
converter.pixVal[0] = b;
converter.pixVal[1] = g;
converter.pixVal[2] = r;
converter.pixVal[3] = a;
return converter.val;
}
void SurfaceGDI::AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill,
ColourDesired outline, int alphaOutline, int /* flags*/)
{
const RECT rcw = RectFromPRectangle(rc);
if(AlphaBlendFn && rc.Width() > 0) {
HDC hMemDC = ::CreateCompatibleDC(hdc);
int width = static_cast<int>(rc.Width());
int height = static_cast<int>(rc.Height());
// Ensure not distorted too much by corners when small
cornerSize = smin(cornerSize, (smin(width, height) / 2) - 2);
BITMAPINFO bpih = {{sizeof(BITMAPINFOHEADER), width, height, 1, 32, BI_RGB, 0, 0, 0, 0, 0}};
void * image = 0;
HBITMAP hbmMem = CreateDIBSection(hMemDC, &bpih, DIB_RGB_COLORS, &image, NULL, 0);
if(hbmMem) {
HBITMAP hbmOld = SelectBitmap(hMemDC, hbmMem);
DWORD valEmpty = dwordFromBGRA(0, 0, 0, 0);
DWORD valFill = dwordFromBGRA(
static_cast<byte>(GetBValue(fill.AsLong()) * alphaFill / 255),
static_cast<byte>(GetGValue(fill.AsLong()) * alphaFill / 255),
static_cast<byte>(GetRValue(fill.AsLong()) * alphaFill / 255),
static_cast<byte>(alphaFill));
DWORD valOutline = dwordFromBGRA(
static_cast<byte>(GetBValue(outline.AsLong()) * alphaOutline / 255),
static_cast<byte>(GetGValue(outline.AsLong()) * alphaOutline / 255),
static_cast<byte>(GetRValue(outline.AsLong()) * alphaOutline / 255),
static_cast<byte>(alphaOutline));
DWORD * pixels = static_cast<DWORD *>(image);
for(int y = 0; y<height; y++) {
for(int x = 0; x<width; x++) {
if((x==0) || (x==width-1) || (y == 0) || (y == height-1)) {
pixels[y*width+x] = valOutline;
}
else {
pixels[y*width+x] = valFill;
}
}
}
for(int c = 0; c<cornerSize; c++) {
for(int x = 0; x<c+1; x++) {
AllFour(pixels, width, height, x, c-x, valEmpty);
}
}
for(int x = 1; x<cornerSize; x++) {
AllFour(pixels, width, height, x, cornerSize-x, valOutline);
}
BLENDFUNCTION merge = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
AlphaBlendFn(hdc, rcw.left, rcw.top, width, height, hMemDC, 0, 0, width, height, merge);
SelectBitmap(hMemDC, hbmOld);
::DeleteObject(hbmMem);
}
::DeleteDC(hMemDC);
}
else {
BrushColor(outline);
FrameRect(hdc, &rcw, brush);
}
}
void SurfaceGDI::DrawRGBAImage(PRectangle rc, int width, int height, const uchar * pixelsImage)
{
if(AlphaBlendFn && rc.Width() > 0) {
HDC hMemDC = ::CreateCompatibleDC(hdc);
if(rc.Width() > width)
rc.left += static_cast<int>((rc.Width() - width) / 2);
rc.right = rc.left + width;
if(rc.Height() > height)
rc.top += static_cast<int>((rc.Height() - height) / 2);
rc.bottom = rc.top + height;
BITMAPINFO bpih = {{sizeof(BITMAPINFOHEADER), width, height, 1, 32, BI_RGB, 0, 0, 0, 0, 0}};
uchar * image = 0;
HBITMAP hbmMem = CreateDIBSection(hMemDC, &bpih, DIB_RGB_COLORS, reinterpret_cast<void **>(&image), NULL, 0);
if(hbmMem) {
HBITMAP hbmOld = SelectBitmap(hMemDC, hbmMem);
for(int y = height-1; y>=0; y--) {
for(int x = 0; x<width; x++) {
uchar * pixel = image + (y*width+x) * 4;
uchar alpha = pixelsImage[3];
// Input is RGBA, output is BGRA with premultiplied alpha
pixel[2] = static_cast<uchar>((*pixelsImage++) * alpha / 255);
pixel[1] = static_cast<uchar>((*pixelsImage++) * alpha / 255);
pixel[0] = static_cast<uchar>((*pixelsImage++) * alpha / 255);
pixel[3] = static_cast<uchar>(*pixelsImage++);
}
}
BLENDFUNCTION merge = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
AlphaBlendFn(hdc, static_cast<int>(rc.left), static_cast<int>(rc.top),
static_cast<int>(rc.Width()), static_cast<int>(rc.Height()), hMemDC, 0, 0, width, height, merge);
SelectBitmap(hMemDC, hbmOld);
::DeleteObject(hbmMem);
}
::DeleteDC(hMemDC);
}
}
void SurfaceGDI::Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back)
{
PenColour(fore);
BrushColor(back);
const RECT rcw = RectFromPRectangle(rc);
::Ellipse(hdc, rcw.left, rcw.top, rcw.right, rcw.bottom);
}
void SurfaceGDI::Copy(PRectangle rc, Point from, Surface &surfaceSource)
{
::BitBlt(hdc,
static_cast<int>(rc.left), static_cast<int>(rc.top),
static_cast<int>(rc.Width()), static_cast<int>(rc.Height()),
static_cast<SurfaceGDI &>(surfaceSource).hdc,
static_cast<int>(from.x), static_cast<int>(from.y), SRCCOPY);
}
typedef VarBuffer<int, stackBufferLength> TextPositionsI;
void SurfaceGDI::DrawTextCommon(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len, UINT fuOptions)
{
SetFont(font_);
const RECT rcw = RectFromPRectangle(rc);
const int x = static_cast<int>(rc.left);
const int yBaseInt = static_cast<int>(ybase);
if(unicodeMode) {
const TextWide tbuf(s, len, unicodeMode, codePage);
::ExtTextOutW(hdc, x, yBaseInt, fuOptions, &rcw, tbuf.buffer, tbuf.tlen, 0);
}
else {
::ExtTextOutA(hdc, x, yBaseInt, fuOptions, &rcw, s, len, 0);
}
}
void SurfaceGDI::DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len,
ColourDesired fore, ColourDesired back)
{
::SetTextColor(hdc, fore.AsLong());
::SetBkColor(hdc, back.AsLong());
DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE);
}
void SurfaceGDI::DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len,
ColourDesired fore, ColourDesired back)
{
::SetTextColor(hdc, fore.AsLong());
::SetBkColor(hdc, back.AsLong());
DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE | ETO_CLIPPED);
}
void SurfaceGDI::DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len,
ColourDesired fore)
{
// Avoid drawing spaces in transparent mode
for(int i = 0; i<len; i++) {
if(s[i] != ' ') {
::SetTextColor(hdc, fore.AsLong());
::SetBkMode(hdc, TRANSPARENT);
DrawTextCommon(rc, font_, ybase, s, len, 0);
::SetBkMode(hdc, OPAQUE);
return;
}
}
}
XYPOSITION SurfaceGDI::WidthText(Font &font_, const char * s, int len)
{
SetFont(font_);
SIZE sz = {0, 0};
if(!unicodeMode) {
::GetTextExtentPoint32A(hdc, s, smin(len, maxLenText), &sz);
}
else {
const TextWide tbuf(s, len, unicodeMode, codePage);
::GetTextExtentPoint32W(hdc, tbuf.buffer, tbuf.tlen, &sz);
}
return static_cast<XYPOSITION>(sz.cx);
}
void SurfaceGDI::MeasureWidths(Font &font_, const char * s, int len, XYPOSITION * positions)
{
// Zero positions to avoid random behaviour on failure.
std::fill(positions, positions + len, 0.0f);
SetFont(font_);
SIZE sz = {0, 0};
int fit = 0;
int i = 0;
if(unicodeMode) {
const TextWide tbuf(s, len, unicodeMode, codePage);
TextPositionsI poses(tbuf.tlen);
if(!::GetTextExtentExPointW(hdc, tbuf.buffer, tbuf.tlen, maxWidthMeasure, &fit, poses.buffer, &sz)) {
// Failure
return;
}
// Map the widths given for UTF-16 characters back onto the UTF-8 input string
for(int ui = 0; ui < fit; ui++) {
uint lenChar = UTF8BytesOfLead[static_cast<uchar>(s[i])];
if(lenChar == 4) { // Non-BMP
ui++;
}
for(uint bytePos = 0; (bytePos<lenChar) && (i<len); bytePos++) {
positions[i++] = static_cast<XYPOSITION>(poses.buffer[ui]);
}
}
}
else {
TextPositionsI poses(len);
if(!::GetTextExtentExPointA(hdc, s, len, maxWidthMeasure, &fit, poses.buffer, &sz)) {
// Eeek - a NULL DC or other foolishness could cause this.
return;
}
while(i<fit) {
positions[i] = static_cast<XYPOSITION>(poses.buffer[i]);
i++;
}
}
// If any positions not filled in then use the last position for them
const XYPOSITION lastPos = (fit > 0) ? positions[fit - 1] : 0.0f;
std::fill(positions+i, positions + len, lastPos);
}
XYPOSITION SurfaceGDI::WidthChar(Font &font_, char ch)
{
SetFont(font_);
SIZE sz;
::GetTextExtentPoint32A(hdc, &ch, 1, &sz);
return static_cast<XYPOSITION>(sz.cx);
}
XYPOSITION SurfaceGDI::Ascent(Font &font_)
{
SetFont(font_);
TEXTMETRIC tm;
::GetTextMetrics(hdc, &tm);
return static_cast<XYPOSITION>(tm.tmAscent);
}
XYPOSITION SurfaceGDI::Descent(Font &font_)
{
SetFont(font_);
TEXTMETRIC tm;
::GetTextMetrics(hdc, &tm);
return static_cast<XYPOSITION>(tm.tmDescent);
}
XYPOSITION SurfaceGDI::InternalLeading(Font &font_)
{
SetFont(font_);
TEXTMETRIC tm;
::GetTextMetrics(hdc, &tm);
return static_cast<XYPOSITION>(tm.tmInternalLeading);
}
XYPOSITION SurfaceGDI::ExternalLeading(Font &font_)
{
SetFont(font_);
TEXTMETRIC tm;
::GetTextMetrics(hdc, &tm);
return static_cast<XYPOSITION>(tm.tmExternalLeading);
}
XYPOSITION SurfaceGDI::Height(Font &font_)
{
SetFont(font_);
TEXTMETRIC tm;
::GetTextMetrics(hdc, &tm);
return static_cast<XYPOSITION>(tm.tmHeight);
}
XYPOSITION SurfaceGDI::AverageCharWidth(Font &font_)
{
SetFont(font_);
TEXTMETRIC tm;
::GetTextMetrics(hdc, &tm);
return static_cast<XYPOSITION>(tm.tmAveCharWidth);
}
void SurfaceGDI::SetClip(PRectangle rc)
{
::IntersectClipRect(hdc, static_cast<int>(rc.left), static_cast<int>(rc.top),
static_cast<int>(rc.right), static_cast<int>(rc.bottom));
}
void SurfaceGDI::FlushCachedState()
{
pen = 0;
brush = 0;
font = 0;
}
void SurfaceGDI::SetUnicodeMode(bool unicodeMode_)
{
unicodeMode = unicodeMode_;
}
void SurfaceGDI::SetDBCSMode(int codePage_)
{
// No action on window as automatically handled by system.
codePage = codePage_;
}
#if defined(USE_D2D)
class SurfaceD2D : public Surface {
public:
SurfaceD2D();
virtual ~SurfaceD2D();
void SetScale();
void Init(WindowID wid);
void Init(SurfaceID sid, WindowID wid);
void InitPixMap(int width, int height, Surface * surface_, WindowID wid);
void Release();
bool Initialised();
HRESULT FlushDrawing();
void PenColour(ColourDesired fore);
void D2DPenColour(ColourDesired fore, int alpha = 255);
int LogPixelsY();
int DeviceHeightFont(int points);
void MoveTo(int x_, int y_);
void LineTo(int x_, int y_);
void Polygon(Point * pts, int npts, ColourDesired fore, ColourDesired back);
void RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back);
void FillRectangle(PRectangle rc, ColourDesired back);
void FillRectangle(PRectangle rc, Surface &surfacePattern);
void RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back);
void AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill, ColourDesired outline, int alphaOutline, int flags);
void DrawRGBAImage(PRectangle rc, int width, int height, const uchar * pixelsImage);
void Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back);
void Copy(PRectangle rc, Point from, Surface &surfaceSource);
void DrawTextCommon(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len, UINT fuOptions);
void DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len, ColourDesired fore, ColourDesired back);
void DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len, ColourDesired fore, ColourDesired back);
void DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len, ColourDesired fore);
void MeasureWidths(Font &font_, const char * s, int len, XYPOSITION * positions);
XYPOSITION WidthText(Font &font_, const char * s, int len);
XYPOSITION WidthChar(Font &font_, char ch);
XYPOSITION Ascent(Font &font_);
XYPOSITION Descent(Font &font_);
XYPOSITION InternalLeading(Font &font_);
XYPOSITION ExternalLeading(Font &font_);
XYPOSITION Height(Font &font_);
XYPOSITION AverageCharWidth(Font &font_);
void SetClip(PRectangle rc);
void FlushCachedState();
void SetUnicodeMode(bool unicodeMode_);
void SetDBCSMode(int codePage_);
private:
int x, y;
int codePage;
int codePageText;
ID2D1RenderTarget * pRenderTarget;
int clipsActive;
IDWriteTextFormat * pTextFormat;
FLOAT yAscent;
FLOAT yDescent;
FLOAT yInternalLeading;
ID2D1SolidColorBrush * pBrush;
int logPixelsY;
float dpiScaleX;
float dpiScaleY;
bool unicodeMode;
bool ownRenderTarget;
uint8 Reserve[2]; // @alignment
void SetFont(Font &font_);
// Private so SurfaceD2D objects can not be copied
SurfaceD2D(const SurfaceD2D &);
SurfaceD2D &operator=(const SurfaceD2D &);
};
SurfaceD2D::SurfaceD2D() : x(0), y(0), codePage(0), codePageText(0), pRenderTarget(NULL), unicodeMode(false), ownRenderTarget(false),
clipsActive(0), pTextFormat(NULL), yAscent(2), yDescent(1), yInternalLeading(0), pBrush(NULL), logPixelsY(72), dpiScaleX(1.0f), dpiScaleY(1.0f)
{
}
SurfaceD2D::~SurfaceD2D()
{
Release();
}
void SurfaceD2D::Release()
{
if(pBrush) {
pBrush->Release();
pBrush = 0;
}
if(pRenderTarget) {
while(clipsActive) {
pRenderTarget->PopAxisAlignedClip();
clipsActive--;
}
if(ownRenderTarget) {
pRenderTarget->Release();
}
pRenderTarget = 0;
}
}
void SurfaceD2D::SetScale()
{
HDC hdcMeasure = ::CreateCompatibleDC(NULL);
logPixelsY = ::GetDeviceCaps(hdcMeasure, LOGPIXELSY);
dpiScaleX = ::GetDeviceCaps(hdcMeasure, LOGPIXELSX) / 96.0f;
dpiScaleY = logPixelsY / 96.0f;
::DeleteDC(hdcMeasure);
}
bool SurfaceD2D::Initialised()
{
return pRenderTarget != 0;
}
HRESULT SurfaceD2D::FlushDrawing()
{
return pRenderTarget->Flush();
}
void SurfaceD2D::Init(WindowID /* wid */)
{
Release();
SetScale();
}
void SurfaceD2D::Init(SurfaceID sid, WindowID)
{
Release();
SetScale();
pRenderTarget = static_cast<ID2D1RenderTarget *>(sid);
}
void SurfaceD2D::InitPixMap(int width, int height, Surface * surface_, WindowID)
{
Release();
SetScale();
SurfaceD2D * psurfOther = static_cast<SurfaceD2D *>(surface_);
ID2D1BitmapRenderTarget * pCompatibleRenderTarget = NULL;
D2D1_SIZE_F desiredSize = D2D1::SizeF(static_cast<float>(width), static_cast<float>(height));
D2D1_PIXEL_FORMAT desiredFormat;
#ifdef __MINGW32__
desiredFormat.format = DXGI_FORMAT_UNKNOWN;
#else
desiredFormat = psurfOther->pRenderTarget->GetPixelFormat();
#endif
desiredFormat.alphaMode = D2D1_ALPHA_MODE_IGNORE;
HRESULT hr = psurfOther->pRenderTarget->CreateCompatibleRenderTarget(
&desiredSize, NULL, &desiredFormat, D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_NONE, &pCompatibleRenderTarget);
if(SUCCEEDED(hr)) {
pRenderTarget = pCompatibleRenderTarget;
pRenderTarget->BeginDraw();
ownRenderTarget = true;
}
SetUnicodeMode(psurfOther->unicodeMode);
SetDBCSMode(psurfOther->codePage);
}
void SurfaceD2D::PenColour(ColourDesired fore)
{
D2DPenColour(fore);
}
void SurfaceD2D::D2DPenColour(ColourDesired fore, int alpha)
{
if(pRenderTarget) {
D2D_COLOR_F col;
col.r = (fore.AsLong() & 0xff) / 255.0f;
col.g = ((fore.AsLong() & 0xff00) >> 8) / 255.0f;
col.b = (fore.AsLong() >> 16) / 255.0f;
col.a = alpha / 255.0f;
if(pBrush) {
pBrush->SetColor(col);
}
else {
HRESULT hr = pRenderTarget->CreateSolidColorBrush(col, &pBrush);
if(!SUCCEEDED(hr) && pBrush) {
pBrush->Release();
pBrush = 0;
}
}
}
}
void SurfaceD2D::SetFont(Font &font_)
{
FormatAndMetrics * pfm = static_cast<FormatAndMetrics *>(font_.GetID());
PLATFORM_ASSERT(pfm->technology == SCWIN_TECH_DIRECTWRITE);
pTextFormat = pfm->pTextFormat;
yAscent = pfm->yAscent;
yDescent = pfm->yDescent;
yInternalLeading = pfm->yInternalLeading;
codePageText = codePage;
if(pfm->characterSet) {
codePageText = CodePageFromCharSet(pfm->characterSet, codePage);
}
if(pRenderTarget) {
D2D1_TEXT_ANTIALIAS_MODE aaMode;
aaMode = DWriteMapFontQuality(pfm->extraFontFlag);
if(aaMode == D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE && customClearTypeRenderingParams)
pRenderTarget->SetTextRenderingParams(customClearTypeRenderingParams);
else if(defaultRenderingParams)
pRenderTarget->SetTextRenderingParams(defaultRenderingParams);
pRenderTarget->SetTextAntialiasMode(aaMode);
}
}
int SurfaceD2D::LogPixelsY()
{
return logPixelsY;
}
int SurfaceD2D::DeviceHeightFont(int points)
{
return ::MulDiv(points, LogPixelsY(), 72);
}
void SurfaceD2D::MoveTo(int x_, int y_)
{
x = x_;
y = y_;
}
static int Delta(int difference)
{
if(difference < 0)
return -1;
else if(difference > 0)
return 1;
else
return 0;
}
static float RoundFloat(float f)
{
return float(int(f+0.5f));
}
void SurfaceD2D::LineTo(int x_, int y_)
{
if(pRenderTarget) {
int xDiff = x_ - x;
int xDelta = Delta(xDiff);
int yDiff = y_ - y;
int yDelta = Delta(yDiff);
if((xDiff == 0) || (yDiff == 0)) {
// Horizontal or vertical lines can be more precisely drawn as a filled rectangle
int xEnd = x_ - xDelta;
int left = smin(x, xEnd);
int width = abs(x - xEnd) + 1;
int yEnd = y_ - yDelta;
int top = smin(y, yEnd);
int height = abs(y - yEnd) + 1;
D2D1_RECT_F rectangle1 = D2D1::RectF(static_cast<float>(left), static_cast<float>(top),
static_cast<float>(left+width), static_cast<float>(top+height));
pRenderTarget->FillRectangle(&rectangle1, pBrush);
}
else if((abs(xDiff) == abs(yDiff))) {
// 45 degree slope
pRenderTarget->DrawLine(D2D1::Point2F(x + 0.5f, y + 0.5f),
D2D1::Point2F(x_ + 0.5f - xDelta, y_ + 0.5f - yDelta), pBrush);
}
else {
// Line has a different slope so difficult to avoid last pixel
pRenderTarget->DrawLine(D2D1::Point2F(x + 0.5f, y + 0.5f),
D2D1::Point2F(x_ + 0.5f, y_ + 0.5f), pBrush);
}
x = x_;
y = y_;
}
}
void SurfaceD2D::Polygon(Point * pts, int npts, ColourDesired fore, ColourDesired back)
{
if(pRenderTarget) {
ID2D1Factory * pFactory = 0;
pRenderTarget->GetFactory(&pFactory);
ID2D1PathGeometry * geometry = 0;
HRESULT hr = pFactory->CreatePathGeometry(&geometry);
if(SUCCEEDED(hr)) {
ID2D1GeometrySink * sink = 0;
hr = geometry->Open(&sink);
if(SUCCEEDED(hr)) {
sink->BeginFigure(D2D1::Point2F(pts[0].x + 0.5f, pts[0].y + 0.5f), D2D1_FIGURE_BEGIN_FILLED);
for(size_t i = 1; i<static_cast<size_t>(npts); i++) {
sink->AddLine(D2D1::Point2F(pts[i].x + 0.5f, pts[i].y + 0.5f));
}
sink->EndFigure(D2D1_FIGURE_END_CLOSED);
sink->Close();
sink->Release();
D2DPenColour(back);
pRenderTarget->FillGeometry(geometry, pBrush);
D2DPenColour(fore);
pRenderTarget->DrawGeometry(geometry, pBrush);
}
geometry->Release();
}
}
}
void SurfaceD2D::RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back)
{
if(pRenderTarget) {
D2D1_RECT_F rectangle1 = D2D1::RectF(RoundFloat(rc.left) + 0.5f, rc.top+0.5f, RoundFloat(rc.right) - 0.5f, rc.bottom-0.5f);
D2DPenColour(back);
pRenderTarget->FillRectangle(&rectangle1, pBrush);
D2DPenColour(fore);
pRenderTarget->DrawRectangle(&rectangle1, pBrush);
}
}
void SurfaceD2D::FillRectangle(PRectangle rc, ColourDesired back)
{
if(pRenderTarget) {
D2DPenColour(back);
D2D1_RECT_F rectangle1 = D2D1::RectF(RoundFloat(rc.left), rc.top, RoundFloat(rc.right), rc.bottom);
pRenderTarget->FillRectangle(&rectangle1, pBrush);
}
}
void SurfaceD2D::FillRectangle(PRectangle rc, Surface &surfacePattern)
{
SurfaceD2D &surfOther = static_cast<SurfaceD2D &>(surfacePattern);
surfOther.FlushDrawing();
ID2D1Bitmap * pBitmap = NULL;
ID2D1BitmapRenderTarget * pCompatibleRenderTarget = reinterpret_cast<ID2D1BitmapRenderTarget *>(
surfOther.pRenderTarget);
HRESULT hr = pCompatibleRenderTarget->GetBitmap(&pBitmap);
if(SUCCEEDED(hr)) {
ID2D1BitmapBrush * pBitmapBrush = NULL;
D2D1_BITMAP_BRUSH_PROPERTIES brushProperties =
D2D1::BitmapBrushProperties(D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP,
D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR);
// Create the bitmap brush.
hr = pRenderTarget->CreateBitmapBrush(pBitmap, brushProperties, &pBitmapBrush);
pBitmap->Release();
if(SUCCEEDED(hr)) {
pRenderTarget->FillRectangle(
D2D1::RectF(rc.left, rc.top, rc.right, rc.bottom),
pBitmapBrush);
pBitmapBrush->Release();
}
}
}
void SurfaceD2D::RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back)
{
if(pRenderTarget) {
D2D1_ROUNDED_RECT roundedRectFill = {
D2D1::RectF(rc.left+1.0f, rc.top+1.0f, rc.right-1.0f, rc.bottom-1.0f),
4, 4
};
D2DPenColour(back);
pRenderTarget->FillRoundedRectangle(roundedRectFill, pBrush);
D2D1_ROUNDED_RECT roundedRect = {
D2D1::RectF(rc.left + 0.5f, rc.top+0.5f, rc.right - 0.5f, rc.bottom-0.5f),
4, 4
};
D2DPenColour(fore);
pRenderTarget->DrawRoundedRectangle(roundedRect, pBrush);
}
}
void SurfaceD2D::AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill,
ColourDesired outline, int alphaOutline, int /* flags*/)
{
if(pRenderTarget) {
if(cornerSize == 0) {
// When corner size is zero, draw square rectangle to prevent blurry pixels at corners
D2D1_RECT_F rectFill = D2D1::RectF(RoundFloat(rc.left) + 1.0f, rc.top + 1.0f, RoundFloat(
rc.right) - 1.0f, rc.bottom - 1.0f);
D2DPenColour(fill, alphaFill);
pRenderTarget->FillRectangle(rectFill, pBrush);
D2D1_RECT_F rectOutline = D2D1::RectF(RoundFloat(rc.left) + 0.5f, rc.top + 0.5f, RoundFloat(
rc.right) - 0.5f, rc.bottom - 0.5f);
D2DPenColour(outline, alphaOutline);
pRenderTarget->DrawRectangle(rectOutline, pBrush);
}
else {
const float cornerSizeF = static_cast<float>(cornerSize);
D2D1_ROUNDED_RECT roundedRectFill = {
D2D1::RectF(RoundFloat(rc.left) + 1.0f, rc.top + 1.0f, RoundFloat(rc.right) - 1.0f, rc.bottom - 1.0f),
cornerSizeF, cornerSizeF
};
D2DPenColour(fill, alphaFill);
pRenderTarget->FillRoundedRectangle(roundedRectFill, pBrush);
D2D1_ROUNDED_RECT roundedRect = {
D2D1::RectF(RoundFloat(rc.left) + 0.5f, rc.top + 0.5f, RoundFloat(rc.right) - 0.5f, rc.bottom - 0.5f),
cornerSizeF, cornerSizeF
};
D2DPenColour(outline, alphaOutline);
pRenderTarget->DrawRoundedRectangle(roundedRect, pBrush);
}
}
}
void SurfaceD2D::DrawRGBAImage(PRectangle rc, int width, int height, const uchar * pixelsImage)
{
if(pRenderTarget) {
if(rc.Width() > width)
rc.left += static_cast<int>((rc.Width() - width) / 2);
rc.right = rc.left + width;
if(rc.Height() > height)
rc.top += static_cast<int>((rc.Height() - height) / 2);
rc.bottom = rc.top + height;
std::vector<uchar> image(height * width * 4);
for(int yPixel = 0; yPixel<height; yPixel++) {
for(int xPixel = 0; xPixel<width; xPixel++) {
uchar * pixel = &image[0] + (yPixel*width + xPixel) * 4;
uchar alpha = pixelsImage[3];
// Input is RGBA, output is BGRA with premultiplied alpha
pixel[2] = (*pixelsImage++) * alpha / 255;
pixel[1] = (*pixelsImage++) * alpha / 255;
pixel[0] = (*pixelsImage++) * alpha / 255;
pixel[3] = *pixelsImage++;
}
}
ID2D1Bitmap * bitmap = 0;
D2D1_SIZE_U size = D2D1::SizeU(width, height);
D2D1_BITMAP_PROPERTIES props = {{DXGI_FORMAT_B8G8R8A8_UNORM,
D2D1_ALPHA_MODE_PREMULTIPLIED}, 72.0, 72.0};
HRESULT hr = pRenderTarget->CreateBitmap(size, &image[0],
width * 4, &props, &bitmap);
if(SUCCEEDED(hr)) {
D2D1_RECT_F rcDestination = {rc.left, rc.top, rc.right, rc.bottom};
pRenderTarget->DrawBitmap(bitmap, rcDestination);
bitmap->Release();
}
}
}
void SurfaceD2D::Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back)
{
if(pRenderTarget) {
FLOAT radius = rc.Width() / 2.0f;
D2D1_ELLIPSE ellipse = {
D2D1::Point2F((rc.left + rc.right) / 2.0f, (rc.top + rc.bottom) / 2.0f),
radius, radius
};
PenColour(back);
pRenderTarget->FillEllipse(ellipse, pBrush);
PenColour(fore);
pRenderTarget->DrawEllipse(ellipse, pBrush);
}
}
void SurfaceD2D::Copy(PRectangle rc, Point from, Surface &surfaceSource)
{
SurfaceD2D &surfOther = static_cast<SurfaceD2D &>(surfaceSource);
surfOther.FlushDrawing();
ID2D1BitmapRenderTarget * pCompatibleRenderTarget = reinterpret_cast<ID2D1BitmapRenderTarget *>(
surfOther.pRenderTarget);
ID2D1Bitmap * pBitmap = NULL;
HRESULT hr = pCompatibleRenderTarget->GetBitmap(&pBitmap);
if(SUCCEEDED(hr)) {
D2D1_RECT_F rcDestination = {rc.left, rc.top, rc.right, rc.bottom};
D2D1_RECT_F rcSource = {from.x, from.y, from.x + rc.Width(), from.y + rc.Height()};
pRenderTarget->DrawBitmap(pBitmap, rcDestination, 1.0f,
D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, rcSource);
hr = pRenderTarget->Flush();
if(FAILED(hr)) {
Platform::DebugPrintf("Failed Flush 0x%x\n", hr);
}
pBitmap->Release();
}
}
void SurfaceD2D::DrawTextCommon(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len, UINT fuOptions)
{
SetFont(font_);
// Use Unicode calls
const TextWide tbuf(s, len, unicodeMode, codePageText);
if(pRenderTarget && pTextFormat && pBrush) {
if(fuOptions & ETO_CLIPPED) {
D2D1_RECT_F rcClip = {rc.left, rc.top, rc.right, rc.bottom};
pRenderTarget->PushAxisAlignedClip(rcClip, D2D1_ANTIALIAS_MODE_ALIASED);
}
// Explicitly creating a text layout appears a little faster
IDWriteTextLayout * pTextLayout;
HRESULT hr = pIDWriteFactory->CreateTextLayout(tbuf.buffer, tbuf.tlen, pTextFormat,
rc.Width(), rc.Height(), &pTextLayout);
if(SUCCEEDED(hr)) {
D2D1_POINT_2F origin = {rc.left, ybase-yAscent};
pRenderTarget->DrawTextLayout(origin, pTextLayout, pBrush, D2D1_DRAW_TEXT_OPTIONS_NONE);
pTextLayout->Release();
}
if(fuOptions & ETO_CLIPPED) {
pRenderTarget->PopAxisAlignedClip();
}
}
}
void SurfaceD2D::DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len,
ColourDesired fore, ColourDesired back)
{
if(pRenderTarget) {
FillRectangle(rc, back);
D2DPenColour(fore);
DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE);
}
}
void SurfaceD2D::DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len,
ColourDesired fore, ColourDesired back)
{
if(pRenderTarget) {
FillRectangle(rc, back);
D2DPenColour(fore);
DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE | ETO_CLIPPED);
}
}
void SurfaceD2D::DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char * s, int len,
ColourDesired fore)
{
// Avoid drawing spaces in transparent mode
for(int i = 0; i<len; i++) {
if(s[i] != ' ') {
if(pRenderTarget) {
D2DPenColour(fore);
DrawTextCommon(rc, font_, ybase, s, len, 0);
}
return;
}
}
}
XYPOSITION SurfaceD2D::WidthText(Font &font_, const char * s, int len)
{
FLOAT width = 1.0;
SetFont(font_);
const TextWide tbuf(s, len, unicodeMode, codePageText);
if(pIDWriteFactory && pTextFormat) {
// Create a layout
IDWriteTextLayout * pTextLayout = 0;
HRESULT hr = pIDWriteFactory->CreateTextLayout(tbuf.buffer, tbuf.tlen, pTextFormat, 1000.0, 1000.0, &pTextLayout);
if(SUCCEEDED(hr)) {
DWRITE_TEXT_METRICS textMetrics;
if(SUCCEEDED(pTextLayout->GetMetrics(&textMetrics)))
width = textMetrics.widthIncludingTrailingWhitespace;
pTextLayout->Release();
}
}
return width;
}
void SurfaceD2D::MeasureWidths(Font &font_, const char * s, int len, XYPOSITION * positions)
{
SetFont(font_);
int fit = 0;
const TextWide tbuf(s, len, unicodeMode, codePageText);
TextPositions poses(tbuf.tlen);
fit = tbuf.tlen;
const int clusters = 1000;
DWRITE_CLUSTER_METRICS clusterMetrics[clusters];
UINT32 count = 0;
if(pIDWriteFactory && pTextFormat) {
SetFont(font_);
// Create a layout
IDWriteTextLayout * pTextLayout = 0;
HRESULT hr = pIDWriteFactory->CreateTextLayout(tbuf.buffer, tbuf.tlen, pTextFormat, 10000.0, 1000.0, &pTextLayout);
if(!SUCCEEDED(hr))
return;
if(!SUCCEEDED(pTextLayout->GetClusterMetrics(clusterMetrics, clusters, &count)))
return;
// A cluster may be more than one WCHAR, such as for "ffi" which is a ligature in the Candara font
FLOAT position = 0.0f;
size_t ti = 0;
for(size_t ci = 0; ci<count; ci++) {
for(size_t inCluster = 0; inCluster<clusterMetrics[ci].length; inCluster++) {
poses.buffer[ti++] = position + clusterMetrics[ci].width * (inCluster + 1) / clusterMetrics[ci].length;
}
position += clusterMetrics[ci].width;
}
PLATFORM_ASSERT(ti == static_cast<size_t>(tbuf.tlen));
pTextLayout->Release();
}
if(unicodeMode) {
// Map the widths given for UTF-16 characters back onto the UTF-8 input string
int ui = 0;
const uchar * us = reinterpret_cast<const uchar *>(s);
int i = 0;
while(ui<fit) {
uchar uch = us[i];
uint lenChar = 1;
if(uch >= (0x80 + 0x40 + 0x20 + 0x10)) {
lenChar = 4;
ui++;
}
else if(uch >= (0x80 + 0x40 + 0x20)) {
lenChar = 3;
}
else if(uch >= (0x80)) {
lenChar = 2;
}
for(uint bytePos = 0; (bytePos<lenChar) && (i<len); bytePos++) {
positions[i++] = poses.buffer[ui];
}
ui++;
}
XYPOSITION lastPos = 0.0f;
if(i > 0)
lastPos = positions[i-1];
while(i<len) {
positions[i++] = lastPos;
}
}
else if(codePageText == 0) {
// One character per position
PLATFORM_ASSERT(len == tbuf.tlen);
for(size_t kk = 0; kk<static_cast<size_t>(len); kk++) {
positions[kk] = poses.buffer[kk];
}
}
else {
// May be more than one byte per position
uint ui = 0;
FLOAT position = 0.0f;
for(int i = 0; i<len; ) {
if(ui < count)
position = poses.buffer[ui];
if(Platform::IsDBCSLeadByte(codePageText, s[i])) {
positions[i] = position;
positions[i+1] = position;
i += 2;
}
else {
positions[i] = position;
i++;
}
ui++;
}
}
}
XYPOSITION SurfaceD2D::WidthChar(Font &font_, char ch)
{
FLOAT width = 1.0;
SetFont(font_);
if(pIDWriteFactory && pTextFormat) {
// Create a layout
IDWriteTextLayout * pTextLayout = 0;
const WCHAR wch = ch;
HRESULT hr = pIDWriteFactory->CreateTextLayout(&wch, 1, pTextFormat, 1000.0, 1000.0, &pTextLayout);
if(SUCCEEDED(hr)) {
DWRITE_TEXT_METRICS textMetrics;
if(SUCCEEDED(pTextLayout->GetMetrics(&textMetrics)))
width = textMetrics.widthIncludingTrailingWhitespace;
pTextLayout->Release();
}
}
return width;
}
XYPOSITION SurfaceD2D::Ascent(Font &font_)
{
SetFont(font_);
return ceil(yAscent);
}
XYPOSITION SurfaceD2D::Descent(Font &font_)
{
SetFont(font_);
return ceil(yDescent);
}
XYPOSITION SurfaceD2D::InternalLeading(Font &font_)
{
SetFont(font_);
return floor(yInternalLeading);
}
XYPOSITION SurfaceD2D::ExternalLeading(Font &)
{
// Not implemented, always return one
return 1;
}
XYPOSITION SurfaceD2D::Height(Font &font_)
{
return Ascent(font_) + Descent(font_);
}
XYPOSITION SurfaceD2D::AverageCharWidth(Font &font_)
{
FLOAT width = 1.0;
SetFont(font_);
if(pIDWriteFactory && pTextFormat) {
// Create a layout
IDWriteTextLayout * pTextLayout = 0;
const WCHAR wszAllAlpha[] = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const size_t lenAllAlpha = wcslen(wszAllAlpha);
HRESULT hr = pIDWriteFactory->CreateTextLayout(wszAllAlpha, static_cast<UINT32>(lenAllAlpha),
pTextFormat, 1000.0, 1000.0, &pTextLayout);
if(SUCCEEDED(hr)) {
DWRITE_TEXT_METRICS textMetrics;
if(SUCCEEDED(pTextLayout->GetMetrics(&textMetrics)))
width = textMetrics.width / lenAllAlpha;
pTextLayout->Release();
}
}
return width;
}
void SurfaceD2D::SetClip(PRectangle rc)
{
if(pRenderTarget) {
D2D1_RECT_F rcClip = {rc.left, rc.top, rc.right, rc.bottom};
pRenderTarget->PushAxisAlignedClip(rcClip, D2D1_ANTIALIAS_MODE_ALIASED);
clipsActive++;
}
}
void SurfaceD2D::FlushCachedState()
{
}
void SurfaceD2D::SetUnicodeMode(bool unicodeMode_)
{
unicodeMode = unicodeMode_;
}
void SurfaceD2D::SetDBCSMode(int codePage_)
{
// No action on window as automatically handled by system.
codePage = codePage_;
}
#endif
Surface * FASTCALL Surface::Allocate(int technology)
{
#if defined(USE_D2D)
if(technology == SCWIN_TECH_GDI)
return new SurfaceGDI;
else
return new SurfaceD2D;
#else
return new SurfaceGDI;
#endif
}
Window::Window() : wid(0), cursorLast(cursorInvalid)
{
}
Window::Window(const Window &source) : wid(source.wid), cursorLast(cursorInvalid)
{
}
Window::~Window()
{
}
void Window::Destroy()
{
if(wid)
::DestroyWindow(static_cast<HWND>(wid));
wid = 0;
}
bool Window::HasFocus()
{
return ::GetFocus() == wid;
}
PRectangle Window::GetPosition()
{
RECT rc;
::GetWindowRect(static_cast<HWND>(wid), &rc);
return PRectangle::FromInts(rc.left, rc.top, rc.right, rc.bottom);
}
void Window::SetPosition(PRectangle rc)
{
::SetWindowPos(static_cast<HWND>(wid),
0, static_cast<int>(rc.left), static_cast<int>(rc.top),
static_cast<int>(rc.Width()), static_cast<int>(rc.Height()), SWP_NOZORDER | SWP_NOACTIVATE);
}
static RECT RectFromMonitor(HMONITOR hMonitor)
{
if(GetMonitorInfoFn) {
MONITORINFO mi = {0};
mi.cbSize = sizeof(mi);
if(GetMonitorInfoFn(hMonitor, &mi)) {
return mi.rcWork;
}
}
RECT rc = {0, 0, 0, 0};
if(::SystemParametersInfoA(SPI_GETWORKAREA, 0, &rc, 0) == 0) {
rc.left = 0;
rc.top = 0;
rc.right = 0;
rc.bottom = 0;
}
return rc;
}
void Window::SetPositionRelative(PRectangle rc, Window w)
{
LONG style = ::GetWindowLong(static_cast<HWND>(wid), GWL_STYLE);
if(style & WS_POPUP) {
POINT ptOther = {0, 0};
::ClientToScreen(static_cast<HWND>(w.GetID()), &ptOther);
rc.Move(static_cast<XYPOSITION>(ptOther.x), static_cast<XYPOSITION>(ptOther.y));
RECT rcMonitor = RectFromPRectangle(rc);
HMONITOR hMonitor = NULL;
if(MonitorFromRectFn)
hMonitor = MonitorFromRectFn(&rcMonitor, MONITOR_DEFAULTTONEAREST);
// If hMonitor is NULL, that's just the main screen anyways.
//::GetMonitorInfo(hMonitor, &mi);
RECT rcWork = RectFromMonitor(hMonitor);
if(rcWork.left < rcWork.right) {
// Now clamp our desired rectangle to fit inside the work area
// This way, the menu will fit wholly on one screen. An improvement even
// if you don't have a second monitor on the left... Menu's appears half on
// one screen and half on the other are just U.G.L.Y.!
if(rc.right > rcWork.right)
rc.Move(rcWork.right - rc.right, 0);
if(rc.bottom > rcWork.bottom)
rc.Move(0, rcWork.bottom - rc.bottom);
if(rc.left < rcWork.left)
rc.Move(rcWork.left - rc.left, 0);
if(rc.top < rcWork.top)
rc.Move(0, rcWork.top - rc.top);
}
}
SetPosition(rc);
}
PRectangle Window::GetClientPosition()
{
RECT rc = {0, 0, 0, 0};
if(wid)
::GetClientRect(static_cast<HWND>(wid), &rc);
return PRectangle::FromInts(rc.left, rc.top, rc.right, rc.bottom);
}
void Window::Show(bool show)
{
::ShowWindow(static_cast<HWND>(wid), show ? SW_SHOWNOACTIVATE : SW_HIDE);
}
void Window::InvalidateAll()
{
::InvalidateRect(static_cast<HWND>(wid), NULL, FALSE);
}
void Window::InvalidateRectangle(PRectangle rc)
{
RECT rcw = RectFromPRectangle(rc);
::InvalidateRect(static_cast<HWND>(wid), &rcw, FALSE);
}
static LRESULT Window_SendMessage(Window * w, UINT msg, WPARAM wParam = 0, LPARAM lParam = 0)
{
return ::SendMessage(static_cast<HWND>(w->GetID()), msg, wParam, lParam);
}
void Window::SetFont(Font &font)
{
Window_SendMessage(this, WM_SETFONT, reinterpret_cast<WPARAM>(font.GetID()), 0);
}
static void FlipBitmap(HBITMAP bitmap, int width, int height)
{
HDC hdc = ::CreateCompatibleDC(NULL);
if(hdc != NULL) {
HGDIOBJ prevBmp = ::SelectObject(hdc, bitmap);
::StretchBlt(hdc, width - 1, 0, -width, height, hdc, 0, 0, width, height, SRCCOPY);
::SelectObject(hdc, prevBmp);
::DeleteDC(hdc);
}
}
static HCURSOR GetReverseArrowCursor()
{
if(reverseArrowCursor != NULL)
return reverseArrowCursor;
::EnterCriticalSection(&crPlatformLock);
HCURSOR cursor = reverseArrowCursor;
if(cursor == NULL) {
cursor = ::LoadCursor(NULL, IDC_ARROW);
ICONINFO info;
if(::GetIconInfo(cursor, &info)) {
BITMAP bmp;
if(::GetObject(info.hbmMask, sizeof(bmp), &bmp)) {
FlipBitmap(info.hbmMask, bmp.bmWidth, bmp.bmHeight);
if(info.hbmColor != NULL)
FlipBitmap(info.hbmColor, bmp.bmWidth, bmp.bmHeight);
info.xHotspot = (DWORD)bmp.bmWidth - 1 - info.xHotspot;
reverseArrowCursor = ::CreateIconIndirect(&info);
if(reverseArrowCursor != NULL)
cursor = reverseArrowCursor;
}
::DeleteObject(info.hbmMask);
if(info.hbmColor != NULL)
::DeleteObject(info.hbmColor);
}
}
::LeaveCriticalSection(&crPlatformLock);
return cursor;
}
void Window::SetCursor(Cursor curs)
{
switch(curs) {
case cursorText:
::SetCursor(::LoadCursor(NULL, IDC_IBEAM));
break;
case cursorUp:
::SetCursor(::LoadCursor(NULL, IDC_UPARROW));
break;
case cursorWait:
::SetCursor(::LoadCursor(NULL, IDC_WAIT));
break;
case cursorHoriz:
::SetCursor(::LoadCursor(NULL, IDC_SIZEWE));
break;
case cursorVert:
::SetCursor(::LoadCursor(NULL, IDC_SIZENS));
break;
case cursorHand:
::SetCursor(::LoadCursor(NULL, IDC_HAND));
break;
case cursorReverseArrow:
::SetCursor(GetReverseArrowCursor());
break;
case cursorArrow:
case cursorInvalid: // Should not occur, but just in case.
::SetCursor(::LoadCursor(NULL, IDC_ARROW));
break;
}
}
void Window::SetTitle(const char * s)
{
::SetWindowTextA(static_cast<HWND>(wid), s);
}
//
// Returns rectangle of monitor pt is on, both rect and pt are in Window's coordinates
//
PRectangle Window::GetMonitorRect(Point pt)
{
// MonitorFromPoint and GetMonitorInfo are not available on Windows 95 and NT 4.
PRectangle rcPosition = GetPosition();
POINT ptDesktop = { static_cast<LONG>(pt.x + rcPosition.left), static_cast<LONG>(pt.y + rcPosition.top)};
HMONITOR hMonitor = NULL;
if(MonitorFromPointFn)
hMonitor = MonitorFromPointFn(ptDesktop, MONITOR_DEFAULTTONEAREST);
RECT rcWork = RectFromMonitor(hMonitor);
if(rcWork.left < rcWork.right) {
PRectangle rcMonitor(rcWork.left - rcPosition.left, rcWork.top - rcPosition.top, rcWork.right - rcPosition.left, rcWork.bottom - rcPosition.top);
return rcMonitor;
}
else
return PRectangle();
}
struct ListItemData {
const char * text;
int pixId;
};
class LineToItem {
public:
LineToItem()
{
}
~LineToItem()
{
Clear();
}
void Clear()
{
words.clear();
data.clear();
}
ListItemData Get(int index) const
{
if(index >= 0 && index < static_cast<int>(data.size())) {
return data[index];
}
else {
ListItemData missing = {"", -1};
return missing;
}
}
int Count() const
{
return static_cast<int>(data.size());
}
void AllocItem(const char * text, int pixId)
{
ListItemData lid = { text, pixId };
data.push_back(lid);
}
char * SetWords(const char * s)
{
words = std::vector<char>(s, s+sstrlen(s)+1);
return &words[0];
}
private:
std::vector<char> words;
std::vector<ListItemData> data;
};
const TCHAR ListBoxX_ClassName[] = TEXT("ListBoxX");
ListBox::ListBox()
{
}
ListBox::~ListBox()
{
}
class ListBoxX : public ListBox {
public:
ListBoxX() : lineHeight(10), fontCopy(0), technology(0), lb(0), unicodeMode(false),
desiredVisibleRows(5), maxItemCharacters(0), aveCharWidth(8),
parent(NULL), ctrlID(0), doubleClickAction(NULL), doubleClickActionData(NULL),
widestItem(NULL), maxCharWidth(1), resizeHit(0), wheelDelta(0)
{
}
virtual ~ListBoxX()
{
if(fontCopy) {
::DeleteObject(fontCopy);
fontCopy = 0;
}
}
virtual void SetFont(Font &font);
virtual void Create(Window &parent_, int ctrlID_, Point location_, int lineHeight_, bool unicodeMode_, int technology_);
virtual void SetAverageCharWidth(int width);
virtual void SetVisibleRows(int rows);
virtual int GetVisibleRows() const;
virtual PRectangle GetDesiredRect();
virtual int CaretFromEdge();
virtual void Clear();
virtual void Append(char * s, int type = -1);
virtual int Length();
virtual void Select(int n);
virtual int GetSelection();
virtual int Find(const char * prefix);
virtual void GetValue(int n, char * value, int len);
virtual void RegisterImage(int type, const char * xpm_data);
virtual void RegisterRGBAImage(int type, int width, int height, const uchar * pixelsImage);
virtual void ClearRegisteredImages();
virtual void SetDoubleClickAction(CallBackAction action, void * data)
{
doubleClickAction = action;
doubleClickActionData = data;
}
virtual void SetList(const char * list, char separator, char typesep);
void Draw(DRAWITEMSTRUCT * pDrawItem);
LRESULT WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
static LRESULT PASCAL StaticWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
private:
int lineHeight;
FontID fontCopy;
int technology;
RGBAImageSet images;
LineToItem lti;
HWND lb;
bool unicodeMode;
int desiredVisibleRows;
uint maxItemCharacters;
uint aveCharWidth;
Window * parent;
int ctrlID;
CallBackAction doubleClickAction;
void * doubleClickActionData;
const char * widestItem;
uint maxCharWidth;
int resizeHit;
PRectangle rcPreSize;
Point dragOffset;
Point location; // Caret location at which the list is opened
int wheelDelta; // mouse wheel residue
HWND GetHWND() const;
void AppendListItem(const char * text, const char * numword);
static void AdjustWindowRect(PRectangle * rc);
int ItemHeight() const;
int MinClientWidth() const;
int TextOffset() const;
POINT GetClientExtent() const;
POINT MinTrackSize() const;
POINT MaxTrackSize() const;
void SetRedraw(bool on);
void OnDoubleClick();
void ResizeToCursor();
void StartResize(WPARAM);
LRESULT NcHitTest(WPARAM, LPARAM) const;
void CentreItem(int n);
void Paint(HDC);
static LRESULT PASCAL ControlWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
static const Point ItemInset; // Padding around whole item
static const Point TextInset; // Padding around text
static const Point ImageInset; // Padding around image
};
const Point ListBoxX::ItemInset(0, 0);
const Point ListBoxX::TextInset(2, 0);
const Point ListBoxX::ImageInset(1, 0);
ListBox * ListBox::Allocate()
{
ListBoxX * lb = new ListBoxX();
return lb;
}
void ListBoxX::Create(Window &parent_, int ctrlID_, Point location_, int lineHeight_, bool unicodeMode_, int technology_)
{
parent = &parent_;
ctrlID = ctrlID_;
location = location_;
lineHeight = lineHeight_;
unicodeMode = unicodeMode_;
technology = technology_;
HWND hwndParent = static_cast<HWND>(parent->GetID());
HINSTANCE hinstanceParent = GetWindowInstance(hwndParent);
// Window created as popup so not clipped within parent client area
wid = ::CreateWindowEx(WS_EX_WINDOWEDGE, ListBoxX_ClassName, TEXT(""),
WS_POPUP | WS_THICKFRAME, 100, 100, 150, 80, hwndParent, NULL, hinstanceParent, this);
POINT locationw = {static_cast<LONG>(location.x), static_cast<LONG>(location.y)};
::MapWindowPoints(hwndParent, NULL, &locationw, 1);
location = Point::FromInts(locationw.x, locationw.y);
}
void ListBoxX::SetFont(Font &font)
{
if(font.GetID()) {
if(fontCopy) {
::DeleteObject(fontCopy);
fontCopy = 0;
}
FormatAndMetrics * pfm = static_cast<FormatAndMetrics *>(font.GetID());
fontCopy = pfm->HFont();
::SendMessage(lb, WM_SETFONT, reinterpret_cast<WPARAM>(fontCopy), 0);
}
}
void ListBoxX::SetAverageCharWidth(int width)
{
aveCharWidth = width;
}
void ListBoxX::SetVisibleRows(int rows)
{
desiredVisibleRows = rows;
}
int ListBoxX::GetVisibleRows() const
{
return desiredVisibleRows;
}
HWND ListBoxX::GetHWND() const
{
return static_cast<HWND>(GetID());
}
PRectangle ListBoxX::GetDesiredRect()
{
PRectangle rcDesired = GetPosition();
int rows = Length();
if((rows == 0) || (rows > desiredVisibleRows))
rows = desiredVisibleRows;
rcDesired.bottom = rcDesired.top + ItemHeight() * rows;
int width = MinClientWidth();
HDC hdc = ::GetDC(lb);
HFONT oldFont = SelectFont(hdc, fontCopy);
SIZE textSize = {0, 0};
int len = 0;
if(widestItem) {
len = static_cast<int>(sstrlen(widestItem));
if(unicodeMode) {
const TextWide tbuf(widestItem, len, unicodeMode);
::GetTextExtentPoint32W(hdc, tbuf.buffer, tbuf.tlen, &textSize);
}
else {
::GetTextExtentPoint32A(hdc, widestItem, len, &textSize);
}
}
TEXTMETRIC tm;
::GetTextMetrics(hdc, &tm);
maxCharWidth = tm.tmMaxCharWidth;
SelectFont(hdc, oldFont);
::ReleaseDC(lb, hdc);
int widthDesired = smax(textSize.cx, (len+1) * tm.tmAveCharWidth);
if(width < widthDesired)
width = widthDesired;
rcDesired.right = rcDesired.left + TextOffset() + width + (TextInset.x * 2);
if(Length() > rows)
rcDesired.right += ::GetSystemMetrics(SM_CXVSCROLL);
AdjustWindowRect(&rcDesired);
return rcDesired;
}
int ListBoxX::TextOffset() const
{
int pixWidth = images.GetWidth();
return static_cast<int>(pixWidth == 0 ? ItemInset.x : ItemInset.x + pixWidth + (ImageInset.x * 2));
}
int ListBoxX::CaretFromEdge()
{
PRectangle rc;
AdjustWindowRect(&rc);
return TextOffset() + static_cast<int>(TextInset.x + (0 - rc.left) - 1);
}
void ListBoxX::Clear()
{
::SendMessage(lb, LB_RESETCONTENT, 0, 0);
maxItemCharacters = 0;
widestItem = NULL;
lti.Clear();
}
void ListBoxX::Append(char *, int)
{
// This method is no longer called in Scintilla
PLATFORM_ASSERT(false);
}
int ListBoxX::Length()
{
return lti.Count();
}
void ListBoxX::Select(int n)
{
// We are going to scroll to centre on the new selection and then select it, so disable
// redraw to avoid flicker caused by a painting new selection twice in unselected and then
// selected states
SetRedraw(false);
CentreItem(n);
::SendMessage(lb, LB_SETCURSEL, n, 0);
SetRedraw(true);
}
int ListBoxX::GetSelection()
{
return static_cast<int>(::SendMessage(lb, LB_GETCURSEL, 0, 0));
}
// This is not actually called at present
int ListBoxX::Find(const char *)
{
return LB_ERR;
}
void ListBoxX::GetValue(int n, char * value, int len)
{
ListItemData item = lti.Get(n);
strncpy(value, item.text, len);
value[len-1] = '\0';
}
void ListBoxX::RegisterImage(int type, const char * xpm_data)
{
XPM xpmImage(xpm_data);
images.Add(type, new RGBAImage(xpmImage));
}
void ListBoxX::RegisterRGBAImage(int type, int width, int height, const uchar * pixelsImage)
{
images.Add(type, new RGBAImage(width, height, 1.0, pixelsImage));
}
void ListBoxX::ClearRegisteredImages()
{
images.Clear();
}
void ListBoxX::Draw(DRAWITEMSTRUCT * pDrawItem)
{
if((pDrawItem->itemAction == ODA_SELECT) || (pDrawItem->itemAction == ODA_DRAWENTIRE)) {
RECT rcBox = pDrawItem->rcItem;
rcBox.left += TextOffset();
if(pDrawItem->itemState & ODS_SELECTED) {
RECT rcImage = pDrawItem->rcItem;
rcImage.right = rcBox.left;
// The image is not highlighted
::FillRect(pDrawItem->hDC, &rcImage, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1));
::FillRect(pDrawItem->hDC, &rcBox, reinterpret_cast<HBRUSH>(COLOR_HIGHLIGHT+1));
::SetBkColor(pDrawItem->hDC, ::GetSysColor(COLOR_HIGHLIGHT));
::SetTextColor(pDrawItem->hDC, ::GetSysColor(COLOR_HIGHLIGHTTEXT));
}
else {
::FillRect(pDrawItem->hDC, &pDrawItem->rcItem, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1));
::SetBkColor(pDrawItem->hDC, ::GetSysColor(COLOR_WINDOW));
::SetTextColor(pDrawItem->hDC, ::GetSysColor(COLOR_WINDOWTEXT));
}
ListItemData item = lti.Get(pDrawItem->itemID);
int pixId = item.pixId;
const char * text = item.text;
int len = static_cast<int>(sstrlen(text));
RECT rcText = rcBox;
::InsetRect(&rcText, static_cast<int>(TextInset.x), static_cast<int>(TextInset.y));
if(unicodeMode) {
const TextWide tbuf(text, len, unicodeMode);
::DrawTextW(pDrawItem->hDC, tbuf.buffer, tbuf.tlen, &rcText, DT_NOPREFIX|DT_END_ELLIPSIS|DT_SINGLELINE|DT_NOCLIP);
}
else {
::DrawTextA(pDrawItem->hDC, text, len, &rcText, DT_NOPREFIX|DT_END_ELLIPSIS|DT_SINGLELINE|DT_NOCLIP);
}
if(pDrawItem->itemState & ODS_SELECTED) {
::DrawFocusRect(pDrawItem->hDC, &rcBox);
}
// Draw the image, if any
RGBAImage * pimage = images.Get(pixId);
if(pimage) {
Surface * surfaceItem = Surface::Allocate(technology);
if(surfaceItem) {
if(technology == SCWIN_TECH_GDI) {
surfaceItem->Init(pDrawItem->hDC, pDrawItem->hwndItem);
long left = pDrawItem->rcItem.left + static_cast<int>(ItemInset.x + ImageInset.x);
PRectangle rcImage = PRectangle::FromInts(left, pDrawItem->rcItem.top,
left + images.GetWidth(), pDrawItem->rcItem.bottom);
surfaceItem->DrawRGBAImage(rcImage,
pimage->GetWidth(), pimage->GetHeight(), pimage->Pixels());
delete surfaceItem;
::SetTextAlign(pDrawItem->hDC, TA_TOP);
}
else {
#if defined(USE_D2D)
D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
D2D1_RENDER_TARGET_TYPE_DEFAULT,
D2D1::PixelFormat(
DXGI_FORMAT_B8G8R8A8_UNORM,
D2D1_ALPHA_MODE_IGNORE),
0,
0,
D2D1_RENDER_TARGET_USAGE_NONE,
D2D1_FEATURE_LEVEL_DEFAULT
);
ID2D1DCRenderTarget * pDCRT = 0;
HRESULT hr = pD2DFactory->CreateDCRenderTarget(&props, &pDCRT);
if(SUCCEEDED(hr)) {
RECT rcWindow;
GetClientRect(pDrawItem->hwndItem, &rcWindow);
hr = pDCRT->BindDC(pDrawItem->hDC, &rcWindow);
if(SUCCEEDED(hr)) {
surfaceItem->Init(pDCRT, pDrawItem->hwndItem);
pDCRT->BeginDraw();
long left = pDrawItem->rcItem.left + static_cast<long>(ItemInset.x + ImageInset.x);
PRectangle rcImage = PRectangle::FromInts(left, pDrawItem->rcItem.top,
left + images.GetWidth(), pDrawItem->rcItem.bottom);
surfaceItem->DrawRGBAImage(rcImage,
pimage->GetWidth(), pimage->GetHeight(), pimage->Pixels());
delete surfaceItem;
pDCRT->EndDraw();
pDCRT->Release();
}
else
delete surfaceItem;
}
else
delete surfaceItem;
#endif
}
}
}
}
}
void ListBoxX::AppendListItem(const char * text, const char * numword)
{
int pixId = -1;
if(numword) {
pixId = 0;
char ch;
while((ch = *++numword) != '\0') {
pixId = 10 * pixId + (ch - '0');
}
}
lti.AllocItem(text, pixId);
uint len = static_cast<uint>(sstrlen(text));
if(maxItemCharacters < len) {
maxItemCharacters = len;
widestItem = text;
}
}
void ListBoxX::SetList(const char * list, char separator, char typesep)
{
// Turn off redraw while populating the list - this has a significant effect, even if
// the listbox is not visible.
SetRedraw(false);
Clear();
size_t size = sstrlen(list);
char * words = lti.SetWords(list);
char * startword = words;
char * numword = NULL;
for(size_t i = 0; i < size; i++) {
if(words[i] == separator) {
words[i] = '\0';
ASSIGN_PTR(numword, '\0');
AppendListItem(startword, numword);
startword = words + i + 1;
numword = NULL;
}
else if(words[i] == typesep) {
numword = words + i;
}
}
if(startword) {
ASSIGN_PTR(numword, '\0');
AppendListItem(startword, numword);
}
// Finally populate the listbox itself with the correct number of items
int count = lti.Count();
::SendMessage(lb, LB_INITSTORAGE, count, 0);
for(int j = 0; j<count; j++) {
::SendMessage(lb, LB_ADDSTRING, 0, j+1);
}
SetRedraw(true);
}
void ListBoxX::AdjustWindowRect(PRectangle * rc)
{
RECT rcw = RectFromPRectangle(*rc);
::AdjustWindowRectEx(&rcw, WS_THICKFRAME, false, WS_EX_WINDOWEDGE);
*rc = PRectangle::FromInts(rcw.left, rcw.top, rcw.right, rcw.bottom);
}
int ListBoxX::ItemHeight() const
{
int itemHeight = lineHeight + (static_cast<int>(TextInset.y) * 2);
int pixHeight = images.GetHeight() + (static_cast<int>(ImageInset.y) * 2);
if(itemHeight < pixHeight) {
itemHeight = pixHeight;
}
return itemHeight;
}
int ListBoxX::MinClientWidth() const
{
return 12 * (aveCharWidth+aveCharWidth/3);
}
POINT ListBoxX::MinTrackSize() const
{
PRectangle rc = PRectangle::FromInts(0, 0, MinClientWidth(), ItemHeight());
AdjustWindowRect(&rc);
POINT ret = {static_cast<LONG>(rc.Width()), static_cast<LONG>(rc.Height())};
return ret;
}
POINT ListBoxX::MaxTrackSize() const
{
PRectangle rc = PRectangle::FromInts(0, 0, smax(MinClientWidth(),
static_cast<int>(maxCharWidth * maxItemCharacters) + static_cast<int>(TextInset.x) * 2 + TextOffset() + ::GetSystemMetrics(SM_CXVSCROLL)),
ItemHeight() * lti.Count());
AdjustWindowRect(&rc);
POINT ret = {static_cast<LONG>(rc.Width()), static_cast<LONG>(rc.Height())};
return ret;
}
void ListBoxX::SetRedraw(bool on)
{
::SendMessage(lb, WM_SETREDRAW, static_cast<BOOL>(on), 0);
if(on)
::InvalidateRect(lb, NULL, TRUE);
}
/*
static XYPOSITION XYMinimum(XYPOSITION a, XYPOSITION b)
{
if(a < b)
return a;
else
return b;
}
static XYPOSITION XYMaximum(XYPOSITION a, XYPOSITION b)
{
if(a > b)
return a;
else
return b;
}
*/
void ListBoxX::ResizeToCursor()
{
PRectangle rc = GetPosition();
POINT ptw;
::GetCursorPos(&ptw);
Point pt = Point::FromInts(ptw.x, ptw.y);
pt.x += dragOffset.x;
pt.y += dragOffset.y;
switch(resizeHit) {
case HTLEFT:
rc.left = pt.x;
break;
case HTRIGHT:
rc.right = pt.x;
break;
case HTTOP:
rc.top = pt.y;
break;
case HTTOPLEFT:
rc.top = pt.y;
rc.left = pt.x;
break;
case HTTOPRIGHT:
rc.top = pt.y;
rc.right = pt.x;
break;
case HTBOTTOM:
rc.bottom = pt.y;
break;
case HTBOTTOMLEFT:
rc.bottom = pt.y;
rc.left = pt.x;
break;
case HTBOTTOMRIGHT:
rc.bottom = pt.y;
rc.right = pt.x;
break;
}
POINT ptMin = MinTrackSize();
POINT ptMax = MaxTrackSize();
//
// We don't allow the left edge to move at present, but just in case
//
//rc.left = XYMaximum(XYMinimum(rc.left, rcPreSize.right - ptMin.x), rcPreSize.right - ptMax.x);
//rc.top = XYMaximum(XYMinimum(rc.top, rcPreSize.bottom - ptMin.y), rcPreSize.bottom - ptMax.y);
//rc.right = XYMaximum(XYMinimum(rc.right, rcPreSize.left + ptMax.x), rcPreSize.left + ptMin.x);
//rc.bottom = XYMaximum(XYMinimum(rc.bottom, rcPreSize.top + ptMax.y), rcPreSize.top + ptMin.y);
rc.left = smax(smin(rc.left, rcPreSize.right - ptMin.x), rcPreSize.right - ptMax.x);
rc.top = smax(smin(rc.top, rcPreSize.bottom - ptMin.y), rcPreSize.bottom - ptMax.y);
rc.right = smax(smin(rc.right, rcPreSize.left + ptMax.x), rcPreSize.left + ptMin.x);
rc.bottom = smax(smin(rc.bottom, rcPreSize.top + ptMax.y), rcPreSize.top + ptMin.y);
SetPosition(rc);
}
void ListBoxX::StartResize(WPARAM hitCode)
{
rcPreSize = GetPosition();
POINT cursorPos;
::GetCursorPos(&cursorPos);
switch(hitCode) {
case HTRIGHT:
case HTBOTTOM:
case HTBOTTOMRIGHT:
dragOffset.x = rcPreSize.right - cursorPos.x;
dragOffset.y = rcPreSize.bottom - cursorPos.y;
break;
case HTTOPRIGHT:
dragOffset.x = rcPreSize.right - cursorPos.x;
dragOffset.y = rcPreSize.top - cursorPos.y;
break;
// Note that the current hit test code prevents the left edge cases ever firing
// as we don't want the left edge to be moveable
case HTLEFT:
case HTTOP:
case HTTOPLEFT:
dragOffset.x = rcPreSize.left - cursorPos.x;
dragOffset.y = rcPreSize.top - cursorPos.y;
break;
case HTBOTTOMLEFT:
dragOffset.x = rcPreSize.left - cursorPos.x;
dragOffset.y = rcPreSize.bottom - cursorPos.y;
break;
default:
return;
}
::SetCapture(GetHWND());
resizeHit = static_cast<int>(hitCode);
}
LRESULT ListBoxX::NcHitTest(WPARAM wParam, LPARAM lParam) const
{
Window win = *this; // Copy HWND to avoid const problems
const PRectangle rc = win.GetPosition();
LRESULT hit = ::DefWindowProc(GetHWND(), WM_NCHITTEST, wParam, lParam);
// There is an apparent bug in the DefWindowProc hit test code whereby it will
// return HTTOPXXX if the window in question is shorter than the default
// window caption height + frame, even if one is hovering over the bottom edge of
// the frame, so workaround that here
if(hit >= HTTOP && hit <= HTTOPRIGHT) {
int minHeight = GetSystemMetrics(SM_CYMINTRACK);
int yPos = GET_Y_LPARAM(lParam);
if((rc.Height() < minHeight) && (yPos > ((rc.top + rc.bottom)/2))) {
hit += HTBOTTOM - HTTOP;
}
}
// Nerver permit resizing that moves the left edge. Allow movement of top or bottom edge
// depending on whether the list is above or below the caret
switch(hit) {
case HTLEFT:
case HTTOPLEFT:
case HTBOTTOMLEFT:
hit = HTERROR;
break;
case HTTOP:
case HTTOPRIGHT: {
// Valid only if caret below list
if(location.y < rc.top)
hit = HTERROR;
}
break;
case HTBOTTOM:
case HTBOTTOMRIGHT: {
// Valid only if caret above list
if(rc.bottom <= location.y)
hit = HTERROR;
}
break;
}
return hit;
}
void ListBoxX::OnDoubleClick()
{
if(doubleClickAction)
doubleClickAction(doubleClickActionData);
}
POINT ListBoxX::GetClientExtent() const
{
Window win = *this; // Copy HWND to avoid const problems
const PRectangle rc = win.GetPosition();
POINT ret;
ret.x = static_cast<LONG>(rc.Width());
ret.y = static_cast<LONG>(rc.Height());
return ret;
}
void ListBoxX::CentreItem(int n)
{
// If below mid point, scroll up to centre, but with more items below if uneven
if(n >= 0) {
POINT extent = GetClientExtent();
int visible = extent.y/ItemHeight();
if(visible < Length()) {
LRESULT top = ::SendMessage(lb, LB_GETTOPINDEX, 0, 0);
int half = (visible - 1) / 2;
if(n > (top + half))
::SendMessage(lb, LB_SETTOPINDEX, n - half, 0);
}
}
}
// Performs a double-buffered paint operation to avoid flicker
void ListBoxX::Paint(HDC hDC)
{
POINT extent = GetClientExtent();
HBITMAP hBitmap = ::CreateCompatibleBitmap(hDC, extent.x, extent.y);
HDC bitmapDC = ::CreateCompatibleDC(hDC);
HBITMAP hBitmapOld = SelectBitmap(bitmapDC, hBitmap);
// The list background is mainly erased during painting, but can be a small
// unpainted area when at the end of a non-integrally sized list with a
// vertical scroll bar
RECT rc = { 0, 0, extent.x, extent.y };
::FillRect(bitmapDC, &rc, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1));
// Paint the entire client area and vertical scrollbar
::SendMessage(lb, WM_PRINT, reinterpret_cast<WPARAM>(bitmapDC), PRF_CLIENT|PRF_NONCLIENT);
::BitBlt(hDC, 0, 0, extent.x, extent.y, bitmapDC, 0, 0, SRCCOPY);
// Select a stock brush to prevent warnings from BoundsChecker
::SelectObject(bitmapDC, GetStockFont(WHITE_BRUSH));
SelectBitmap(bitmapDC, hBitmapOld);
::DeleteDC(bitmapDC);
::DeleteObject(hBitmap);
}
LRESULT PASCAL ListBoxX::ControlWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
try {
switch(uMsg) {
case WM_ERASEBKGND:
return TRUE;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hDC = ::BeginPaint(hWnd, &ps);
ListBoxX * lbx = static_cast<ListBoxX *>(PointerFromWindow(::GetParent(hWnd)));
CALLPTRMEMB(lbx, Paint(hDC));
::EndPaint(hWnd, &ps);
}
return 0;
case WM_MOUSEACTIVATE:
// This prevents the view activating when the scrollbar is clicked
return MA_NOACTIVATE;
case WM_LBUTTONDOWN:
{
// We must take control of selection to prevent the ListBox activating
// the popup
LRESULT lResult = ::SendMessage(hWnd, LB_ITEMFROMPOINT, 0, lParam);
int item = LOWORD(lResult);
if(HIWORD(lResult) == 0 && item >= 0) {
::SendMessage(hWnd, LB_SETCURSEL, item, 0);
}
}
return 0;
case WM_LBUTTONUP:
return 0;
case WM_LBUTTONDBLCLK:
{
ListBoxX * lbx = static_cast<ListBoxX *>(PointerFromWindow(::GetParent(hWnd)));
CALLPTRMEMB(lbx, OnDoubleClick());
}
return 0;
case WM_MBUTTONDOWN:
// disable the scroll wheel button click action
return 0;
}
WNDPROC prevWndProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
if(prevWndProc) {
return ::CallWindowProc(prevWndProc, hWnd, uMsg, wParam, lParam);
}
else {
return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
}
} catch(...) {
}
return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
}
LRESULT ListBoxX::WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
switch(iMessage) {
case WM_CREATE:
{
HINSTANCE hinstanceParent = GetWindowInstance(static_cast<HWND>(parent->GetID()));
// Note that LBS_NOINTEGRALHEIGHT is specified to fix cosmetic issue when resizing the list
// but has useful side effect of speeding up list population significantly
lb = ::CreateWindowEx(0, TEXT("listbox"), TEXT(""), WS_CHILD|WS_VSCROLL|WS_VISIBLE|LBS_OWNERDRAWFIXED|LBS_NODATA|LBS_NOINTEGRALHEIGHT,
0, 0, 150, 80, hWnd, reinterpret_cast<HMENU>(static_cast<ptrdiff_t>(ctrlID)), hinstanceParent, 0);
WNDPROC prevWndProc = reinterpret_cast<WNDPROC>(::SetWindowLongPtr(lb, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(ControlWndProc)));
::SetWindowLongPtr(lb, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(prevWndProc));
}
break;
case WM_SIZE:
if(lb) {
SetRedraw(false);
::SetWindowPos(lb, 0, 0, 0, LOWORD(lParam), HIWORD(lParam), SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOMOVE);
// Ensure the selection remains visible
CentreItem(GetSelection());
SetRedraw(true);
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
::BeginPaint(hWnd, &ps);
::EndPaint(hWnd, &ps);
}
break;
case WM_COMMAND:
// This is not actually needed now - the registered double click action is used
// directly to action a choice from the list.
::SendMessage(static_cast<HWND>(parent->GetID()), iMessage, wParam, lParam);
break;
case WM_MEASUREITEM:
{
MEASUREITEMSTRUCT * pMeasureItem = reinterpret_cast<MEASUREITEMSTRUCT *>(lParam);
pMeasureItem->itemHeight = static_cast<uint>(ItemHeight());
}
break;
case WM_DRAWITEM:
Draw(reinterpret_cast<DRAWITEMSTRUCT *>(lParam));
break;
case WM_DESTROY:
lb = 0;
::SetWindowLong(hWnd, 0, 0);
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
case WM_ERASEBKGND:
// To reduce flicker we can elide background erasure since this window is
// completely covered by its child.
return TRUE;
case WM_GETMINMAXINFO:
{
MINMAXINFO * minMax = reinterpret_cast<MINMAXINFO*>(lParam);
minMax->ptMaxTrackSize = MaxTrackSize();
minMax->ptMinTrackSize = MinTrackSize();
}
break;
case WM_MOUSEACTIVATE:
return MA_NOACTIVATE;
case WM_NCHITTEST:
return NcHitTest(wParam, lParam);
case WM_NCLBUTTONDOWN:
// We have to implement our own window resizing because the DefWindowProc
// implementation insists on activating the resized window
StartResize(wParam);
return 0;
case WM_MOUSEMOVE:
if(resizeHit == 0) {
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
else {
ResizeToCursor();
}
break;
case WM_LBUTTONUP:
case WM_CANCELMODE:
if(resizeHit != 0) {
resizeHit = 0;
::ReleaseCapture();
}
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
case WM_MOUSEWHEEL:
wheelDelta -= static_cast<short>(HIWORD(wParam));
if(abs(wheelDelta) >= WHEEL_DELTA) {
int nRows = GetVisibleRows();
int linesToScroll = 1;
if(nRows > 1) {
linesToScroll = nRows - 1;
}
if(linesToScroll > 3) {
linesToScroll = 3;
}
linesToScroll *= (wheelDelta / WHEEL_DELTA);
LRESULT top = ::SendMessage(lb, LB_GETTOPINDEX, 0, 0) + linesToScroll;
SETMAX(top, 0);
::SendMessage(lb, LB_SETTOPINDEX, top, 0);
// update wheel delta residue
wheelDelta = (wheelDelta >= 0) ? (wheelDelta % WHEEL_DELTA) : -(-wheelDelta % WHEEL_DELTA);
}
break;
default:
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
return 0;
}
LRESULT PASCAL ListBoxX::StaticWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
if(iMessage == WM_CREATE) {
CREATESTRUCT * pCreate = reinterpret_cast<CREATESTRUCT *>(lParam);
SetWindowPointer(hWnd, pCreate->lpCreateParams);
}
// Find C++ object associated with window.
ListBoxX * lbx = static_cast<ListBoxX *>(PointerFromWindow(hWnd));
if(lbx) {
return lbx->WndProc(hWnd, iMessage, wParam, lParam);
}
else {
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
}
static bool ListBoxX_Register()
{
WNDCLASSEX wndclassc;
wndclassc.cbSize = sizeof(wndclassc);
// We need CS_HREDRAW and CS_VREDRAW because of the ellipsis that might be drawn for
// truncated items in the list and the appearance/disappearance of the vertical scroll bar.
// The list repaint is double-buffered to avoid the flicker this would otherwise cause.
wndclassc.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
wndclassc.cbClsExtra = 0;
wndclassc.cbWndExtra = sizeof(ListBoxX *);
wndclassc.hInstance = hinstPlatformRes;
wndclassc.hIcon = NULL;
wndclassc.hbrBackground = NULL;
wndclassc.lpszMenuName = NULL;
wndclassc.lpfnWndProc = ListBoxX::StaticWndProc;
wndclassc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
wndclassc.lpszClassName = ListBoxX_ClassName;
wndclassc.hIconSm = 0;
return ::RegisterClassEx(&wndclassc) != 0;
}
bool ListBoxX_Unregister()
{
return ::UnregisterClass(ListBoxX_ClassName, hinstPlatformRes) != 0;
}
Menu::Menu() : mid(0)
{
}
void Menu::CreatePopUp()
{
Destroy();
mid = ::CreatePopupMenu();
}
void Menu::Destroy()
{
if(mid)
::DestroyMenu(static_cast<HMENU>(mid));
mid = 0;
}
void Menu::Show(Point pt, Window &w)
{
::TrackPopupMenu(static_cast<HMENU>(mid), TPM_RIGHTBUTTON, static_cast<int>(pt.x - 4), static_cast<int>(pt.y), 0, static_cast<HWND>(w.GetID()), 0);
Destroy();
}
static bool initialisedET = false;
static bool usePerformanceCounter = false;
static LARGE_INTEGER frequency;
ElapsedTime::ElapsedTime()
{
if(!initialisedET) {
usePerformanceCounter = ::QueryPerformanceFrequency(&frequency) != 0;
initialisedET = true;
}
if(usePerformanceCounter) {
LARGE_INTEGER timeVal;
::QueryPerformanceCounter(&timeVal);
bigBit = timeVal.HighPart;
littleBit = timeVal.LowPart;
}
else {
bigBit = clock();
littleBit = 0;
}
}
double ElapsedTime::Duration(bool reset)
{
double result;
long endBigBit;
long endLittleBit;
if(usePerformanceCounter) {
LARGE_INTEGER lEnd;
::QueryPerformanceCounter(&lEnd);
endBigBit = lEnd.HighPart;
endLittleBit = lEnd.LowPart;
LARGE_INTEGER lBegin;
lBegin.HighPart = bigBit;
lBegin.LowPart = littleBit;
double elapsed = static_cast<double>(lEnd.QuadPart - lBegin.QuadPart);
result = elapsed / static_cast<double>(frequency.QuadPart);
}
else {
endBigBit = clock();
endLittleBit = 0;
double elapsed = endBigBit - bigBit;
result = elapsed / CLOCKS_PER_SEC;
}
if(reset) {
bigBit = endBigBit;
littleBit = endLittleBit;
}
return result;
}
class DynamicLibraryImpl : public DynamicLibrary {
protected:
HMODULE h;
public:
explicit DynamicLibraryImpl(const char * modulePath)
{
h = ::LoadLibraryA(modulePath);
}
virtual ~DynamicLibraryImpl()
{
if(h)
::FreeLibrary(h);
}
// Use GetProcAddress to get a pointer to the relevant function.
virtual Function FindFunction(const char * name)
{
if(h) {
// C++ standard doesn't like casts between function pointers and void pointers so use a union
union {
FARPROC fp;
Function f;
} fnConv;
fnConv.fp = ::GetProcAddress(h, name);
return fnConv.f;
}
else {
return NULL;
}
}
virtual bool IsValid()
{
return h != NULL;
}
};
DynamicLibrary * DynamicLibrary::Load(const char * modulePath)
{
return static_cast<DynamicLibrary *>(new DynamicLibraryImpl(modulePath));
}
ColourDesired Platform::Chrome()
{
return ::GetSysColor(COLOR_3DFACE);
}
ColourDesired Platform::ChromeHighlight()
{
return ::GetSysColor(COLOR_3DHIGHLIGHT);
}
const char * Platform::DefaultFont()
{
return "Verdana";
}
int Platform::DefaultFontSize()
{
return 8;
}
uint Platform::DoubleClickTime()
{
return ::GetDoubleClickTime();
}
bool Platform::MouseButtonBounce()
{
return false;
}
void Platform::DebugDisplay(const char * s)
{
::OutputDebugStringA(s);
}
bool Platform::IsKeyDown(int key)
{
return (::GetKeyState(key) & 0x80000000) != 0;
}
long Platform::SendScintilla(WindowID w, uint msg, ulong wParam, long lParam)
{
// This should never be called - its here to satisfy an old interface
return static_cast<long>(::SendMessage(static_cast<HWND>(w), msg, wParam, lParam));
}
long Platform::SendScintillaPointer(WindowID w, uint msg, ulong wParam, void * lParam)
{
// This should never be called - its here to satisfy an old interface
return static_cast<long>(::SendMessage(static_cast<HWND>(w), msg, wParam,
reinterpret_cast<LPARAM>(lParam)));
}
bool Platform::IsDBCSLeadByte(int codePage, char ch)
{
// Byte ranges found in Wikipedia articles with relevant search strings in each case
uchar uch = static_cast<uchar>(ch);
switch(codePage) {
case 932:
// Shift_jis
return ((uch >= 0x81) && (uch <= 0x9F)) || ((uch >= 0xE0) && (uch <= 0xEF));
case 936:
// GBK
return (uch >= 0x81) && (uch <= 0xFE);
case 949:
// Korean Wansung KS C-5601-1987
return (uch >= 0x81) && (uch <= 0xFE);
case 950:
// Big5
return (uch >= 0x81) && (uch <= 0xFE);
case 1361:
// Korean Johab KS C-5601-1992
return ((uch >= 0x84) && (uch <= 0xD3)) || ((uch >= 0xD8) && (uch <= 0xDE)) || ((uch >= 0xE0) && (uch <= 0xF9));
}
return false;
}
int Platform::DBCSCharLength(int codePage, const char * s)
{
return oneof5(codePage, 932, 936, 949, 950, 1361) ? (Platform::IsDBCSLeadByte(codePage, s[0]) ? 2 : 1) : 1;
}
int Platform::DBCSCharMaxLength()
{
return 2;
}
// These are utility functions not really tied to a platform
/* @sobolev (replaced with smin and smax respectively)
int Platform::Minimum(int a, int b) { return (a < b) ? a : b; }
int Platform::Maximum(int a, int b) { return (a > b) ? a : b; }
*/
//#define TRACE
#ifdef TRACE
void Platform::DebugPrintf(const char * format, ...)
{
char buffer[2000];
va_list pArguments;
va_start(pArguments, format);
vsprintf(buffer, format, pArguments);
va_end(pArguments);
Platform::DebugDisplay(buffer);
}
#else
void Platform::DebugPrintf(const char *, ...)
{
}
#endif
static bool assertionPopUps = true;
bool Platform::ShowAssertionPopUps(bool assertionPopUps_)
{
bool ret = assertionPopUps;
assertionPopUps = assertionPopUps_;
return ret;
}
void Platform::Assert(const char * c, const char * file, int line)
{
char buffer[2000];
sprintf(buffer, "Assertion [%s] failed at %s %d%s", c, file, line, assertionPopUps ? "" : "\r\n");
if(assertionPopUps) {
int idButton = ::MessageBoxA(0, buffer, "Assertion failure",
MB_ABORTRETRYIGNORE|MB_ICONHAND|MB_SETFOREGROUND|MB_TASKMODAL);
if(idButton == IDRETRY) {
::DebugBreak();
}
else if(idButton == IDIGNORE) {
// all OK
}
else {
abort();
}
}
else {
Platform::DebugDisplay(buffer);
::DebugBreak();
abort();
}
}
/* @sobolev @20200511 int Platform::Clamp(int val, int minVal, int maxVal)
{
if(val > maxVal)
val = maxVal;
if(val < minVal)
val = minVal;
return val;
}*/
void Platform_Initialise(void * hInstance)
{
::InitializeCriticalSection(&crPlatformLock);
hinstPlatformRes = static_cast<HINSTANCE>(hInstance);
// This may be called from DllMain, in which case the call to LoadLibrary
// is bad because it can upset the DLL load order.
if(SETIFZ(hDLLImage, ::LoadLibrary(TEXT("Msimg32")))) {
AlphaBlendFn = reinterpret_cast<AlphaBlendSig>(::GetProcAddress(hDLLImage, "AlphaBlend"));
}
if(SETIFZ(hDLLUser32, ::LoadLibrary(TEXT("User32")))) {
MonitorFromPointFn = reinterpret_cast<MonitorFromPointSig>(::GetProcAddress(hDLLUser32, "MonitorFromPoint"));
MonitorFromRectFn = reinterpret_cast<MonitorFromRectSig>(::GetProcAddress(hDLLUser32, "MonitorFromRect"));
GetMonitorInfoFn = reinterpret_cast<GetMonitorInfoSig>(::GetProcAddress(hDLLUser32, "GetMonitorInfoA"));
}
ListBoxX_Register();
}
void Platform_Finalise(bool fromDllMain)
{
#if defined(USE_D2D)
if(!fromDllMain) {
if(defaultRenderingParams) {
defaultRenderingParams->Release();
defaultRenderingParams = 0;
}
if(customClearTypeRenderingParams) {
customClearTypeRenderingParams->Release();
customClearTypeRenderingParams = 0;
}
if(pIDWriteFactory) {
pIDWriteFactory->Release();
pIDWriteFactory = 0;
}
if(pD2DFactory) {
pD2DFactory->Release();
pD2DFactory = 0;
}
if(hDLLDWrite) {
FreeLibrary(hDLLDWrite);
hDLLDWrite = NULL;
}
if(hDLLD2D) {
FreeLibrary(hDLLD2D);
hDLLD2D = NULL;
}
}
#endif
if(reverseArrowCursor != NULL)
::DestroyCursor(reverseArrowCursor);
ListBoxX_Unregister();
::DeleteCriticalSection(&crPlatformLock);
if(hDLLUser32) {
FreeLibrary(hDLLUser32);
hDLLUser32 = NULL;
}
if(hDLLImage) {
FreeLibrary(hDLLImage);
hDLLImage = NULL;
}
}
#ifdef SCI_NAMESPACE
}
#endif
|
{
"pile_set_name": "Github"
}
|
/* SPDX-License-Identifier: GPL-2.0 */
#ifdef DEFINE_DWARF_REGSTR_TABLE
/* This is included in perf/util/dwarf-regs.c */
static const char * const s390_regstr_tbl[] = {
"%r0", "%r1", "%r2", "%r3", "%r4", "%r5", "%r6", "%r7",
"%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15",
};
#endif
|
{
"pile_set_name": "Github"
}
|
# /* Copyright (C) 2001
# * Housemarque Oy
# * http://www.housemarque.com
# *
# * 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)
# */
#
# /* Revised by Paul Mensonides (2002) */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_LIST_REST_N_HPP
# define BOOST_PREPROCESSOR_LIST_REST_N_HPP
#
# include <boost/preprocessor/arithmetic/dec.hpp>
# include <boost/preprocessor/config/config.hpp>
# include <boost/preprocessor/control/while.hpp>
# include <boost/preprocessor/list/adt.hpp>
# include <boost/preprocessor/tuple/elem.hpp>
#
# /* BOOST_PP_LIST_REST_N */
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
# define BOOST_PP_LIST_REST_N(count, list) BOOST_PP_TUPLE_ELEM(2, 0, BOOST_PP_WHILE(BOOST_PP_LIST_REST_N_P, BOOST_PP_LIST_REST_N_O, (list, count)))
# else
# define BOOST_PP_LIST_REST_N(count, list) BOOST_PP_LIST_REST_N_I(count, list)
# define BOOST_PP_LIST_REST_N_I(count, list) BOOST_PP_TUPLE_ELEM(2, 0, BOOST_PP_WHILE(BOOST_PP_LIST_REST_N_P, BOOST_PP_LIST_REST_N_O, (list, count)))
# endif
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
# define BOOST_PP_LIST_REST_N_P(d, lc) BOOST_PP_TUPLE_ELEM(2, 1, lc)
# else
# define BOOST_PP_LIST_REST_N_P(d, lc) BOOST_PP_LIST_REST_N_P_I lc
# define BOOST_PP_LIST_REST_N_P_I(list, count) count
# endif
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
# define BOOST_PP_LIST_REST_N_O(d, lc) (BOOST_PP_LIST_REST(BOOST_PP_TUPLE_ELEM(2, 0, lc)), BOOST_PP_DEC(BOOST_PP_TUPLE_ELEM(2, 1, lc)))
# else
# define BOOST_PP_LIST_REST_N_O(d, lc) BOOST_PP_LIST_REST_N_O_I lc
# define BOOST_PP_LIST_REST_N_O_I(list, count) (BOOST_PP_LIST_REST(list), BOOST_PP_DEC(count))
# endif
#
# /* BOOST_PP_LIST_REST_N_D */
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
# define BOOST_PP_LIST_REST_N_D(d, count, list) BOOST_PP_TUPLE_ELEM(2, 0, BOOST_PP_WHILE_ ## d(BOOST_PP_LIST_REST_N_P, BOOST_PP_LIST_REST_N_O, (list, count)))
# else
# define BOOST_PP_LIST_REST_N_D(d, count, list) BOOST_PP_LIST_REST_N_D_I(d, count, list)
# define BOOST_PP_LIST_REST_N_D_I(d, count, list) BOOST_PP_TUPLE_ELEM(2, 0, BOOST_PP_WHILE_ ## d(BOOST_PP_LIST_REST_N_P, BOOST_PP_LIST_REST_N_O, (list, count)))
# endif
#
# endif
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* @package Gantry5
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2017 RocketTheme, LLC
* @license GNU/GPLv2 and later
*
* http://www.gnu.org/licenses/gpl-2.0.html
*/
namespace Gantry\Joomla\Assignments;
use Gantry\Component\Assignments\AssignmentsInterface;
use Gantry\Framework\Gantry;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
class AssignmentsStyle implements AssignmentsInterface
{
public $type = 'style';
public $priority = 2;
/**
* Returns list of rules which apply to the current page.
*
* @return array
*/
public function getRules()
{
static $rules;
if (!isset($rules)) {
$rules = [];
$template = \JFactory::getApplication()->getTemplate(true);
$theme = $template->template;
$outline = $template->params->get('configuration', !empty($template->id) ? $template->id : $template->params->get('preset', null));
if (JDEBUG) {
GANTRY_DEBUGGER && \Gantry\Debugger::addMessage('Template Style:', 'debug') && \Gantry\Debugger::addMessage($template, 'debug');
if (!$outline) {
\JFactory::getApplication()->enqueueMessage('JApplicationSite::getTemplate() was overridden with no specified Gantry 5 outline.', 'debug');
}
}
/** @var UniformResourceLocator $locator */
$locator = Gantry::instance()['locator'];
if ($outline && is_dir($locator("gantry-themes://{$theme}/custom/config/{$outline}"))) {
$rules = ['id' => [$outline => $this->priority]];
}
}
return $rules;
}
/**
* List all the rules available.
*
* @param string $configuration
* @return array
*/
public function listRules($configuration)
{
return [];
}
}
|
{
"pile_set_name": "Github"
}
|
// Code generated by smithy-go-codegen DO NOT EDIT.
package cognitoidentityprovider
import (
"context"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/retry"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
smithy "github.com/awslabs/smithy-go"
"github.com/awslabs/smithy-go/middleware"
smithyhttp "github.com/awslabs/smithy-go/transport/http"
)
// Creates a new Amazon Cognito user pool and sets the password policy for the
// pool.
func (c *Client) CreateUserPool(ctx context.Context, params *CreateUserPoolInput, optFns ...func(*Options)) (*CreateUserPoolOutput, error) {
stack := middleware.NewStack("CreateUserPool", smithyhttp.NewStackRequest)
options := c.options.Copy()
for _, fn := range optFns {
fn(&options)
}
addawsAwsjson11_serdeOpCreateUserPoolMiddlewares(stack)
awsmiddleware.AddRequestInvocationIDMiddleware(stack)
smithyhttp.AddContentLengthMiddleware(stack)
AddResolveEndpointMiddleware(stack, options)
v4.AddComputePayloadSHA256Middleware(stack)
retry.AddRetryMiddlewares(stack, options)
addHTTPSignerV4Middleware(stack, options)
awsmiddleware.AddAttemptClockSkewMiddleware(stack)
addClientUserAgent(stack)
smithyhttp.AddErrorCloseResponseBodyMiddleware(stack)
smithyhttp.AddCloseResponseBodyMiddleware(stack)
addOpCreateUserPoolValidationMiddleware(stack)
stack.Initialize.Add(newServiceMetadataMiddleware_opCreateUserPool(options.Region), middleware.Before)
addRequestIDRetrieverMiddleware(stack)
addResponseErrorMiddleware(stack)
for _, fn := range options.APIOptions {
if err := fn(stack); err != nil {
return nil, err
}
}
handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack)
result, metadata, err := handler.Handle(ctx, params)
if err != nil {
return nil, &smithy.OperationError{
ServiceID: ServiceID,
OperationName: "CreateUserPool",
Err: err,
}
}
out := result.(*CreateUserPoolOutput)
out.ResultMetadata = metadata
return out, nil
}
// Represents the request to create a user pool.
type CreateUserPoolInput struct {
// The email configuration.
EmailConfiguration *types.EmailConfigurationType
// The configuration for AdminCreateUser requests.
AdminCreateUserConfig *types.AdminCreateUserConfigType
// A string representing the email verification message.
EmailVerificationMessage *string
// The device configuration.
DeviceConfiguration *types.DeviceConfigurationType
// The SMS configuration.
SmsConfiguration *types.SmsConfigurationType
// The tag keys and values to assign to the user pool. A tag is a label that you
// can use to categorize and manage user pools in different ways, such as by
// purpose, owner, environment, or other criteria.
UserPoolTags map[string]*string
// A string representing the email verification subject.
EmailVerificationSubject *string
// Used to enable advanced security risk detection. Set the key
// AdvancedSecurityMode to the value "AUDIT".
UserPoolAddOns *types.UserPoolAddOnsType
// The policies associated with the new user pool.
Policies *types.UserPoolPolicyType
// An array of schema attributes for the new user pool. These attributes can be
// standard or custom attributes.
Schema []*types.SchemaAttributeType
// The attributes to be auto-verified. Possible values: email, phone_number.
AutoVerifiedAttributes []types.VerifiedAttributeType
// A string representing the SMS authentication message.
SmsAuthenticationMessage *string
// Use this setting to define which verified available method a user can use to
// recover their password when they call ForgotPassword. It allows you to define a
// preferred method when a user has more than one method available. With this
// setting, SMS does not qualify for a valid password recovery mechanism if the
// user also has SMS MFA enabled. In the absence of this setting, Cognito uses the
// legacy behavior to determine the recovery method where SMS is preferred over
// email. Starting February 1, 2020, the value of AccountRecoverySetting will
// default to verified_email first and verified_phone_number as the second option
// for newly created user pools if no value is provided.
AccountRecoverySetting *types.AccountRecoverySettingType
// Specifies whether email addresses or phone numbers can be specified as usernames
// when a user signs up.
UsernameAttributes []types.UsernameAttributeType
// The Lambda trigger configuration information for the new user pool. In a push
// model, event sources (such as Amazon S3 and custom applications) need permission
// to invoke a function. So you will need to make an extra call to add permission
// for these event sources to invoke your Lambda function. For more information on
// using the Lambda API to add permission, see AddPermission
// (https://docs.aws.amazon.com/lambda/latest/dg/API_AddPermission.html). For
// adding permission using the AWS CLI, see add-permission
// (https://docs.aws.amazon.com/cli/latest/reference/lambda/add-permission.html).
LambdaConfig *types.LambdaConfigType
// The template for the verification message that the user sees when the app
// requests permission to access the user's information.
VerificationMessageTemplate *types.VerificationMessageTemplateType
// A string used to name the user pool.
PoolName *string
// You can choose to set case sensitivity on the username input for the selected
// sign-in option. For example, when this is set to False, users will be able to
// sign in using either "username" or "Username". This configuration is immutable
// once it has been set. For more information, see .
UsernameConfiguration *types.UsernameConfigurationType
// Attributes supported as an alias for this user pool. Possible values:
// phone_number, email, or preferred_username.
AliasAttributes []types.AliasAttributeType
// A string representing the SMS verification message.
SmsVerificationMessage *string
// Specifies MFA configuration details.
MfaConfiguration types.UserPoolMfaType
}
// Represents the response from the server for the request to create a user pool.
type CreateUserPoolOutput struct {
// A container for the user pool details.
UserPool *types.UserPoolType
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
}
func addawsAwsjson11_serdeOpCreateUserPoolMiddlewares(stack *middleware.Stack) {
stack.Serialize.Add(&awsAwsjson11_serializeOpCreateUserPool{}, middleware.After)
stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateUserPool{}, middleware.After)
}
func newServiceMetadataMiddleware_opCreateUserPool(region string) awsmiddleware.RegisterServiceMetadata {
return awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "cognito-idp",
OperationName: "CreateUserPool",
}
}
|
{
"pile_set_name": "Github"
}
|
### YamlMime:ManagedReference
items:
- uid: EvilDICOM.CV.Image.MatrixHistogram
commentId: T:EvilDICOM.CV.Image.MatrixHistogram
id: MatrixHistogram
parent: EvilDICOM.CV.Image
children:
- EvilDICOM.CV.Image.MatrixHistogram.#ctor(EvilDICOM.CV.Image.Matrix,System.Int32)
- EvilDICOM.CV.Image.MatrixHistogram.AddSlice(OpenCvSharp.Mat)
- EvilDICOM.CV.Image.MatrixHistogram.Count(System.Single,System.Single)
- EvilDICOM.CV.Image.MatrixHistogram.Dispose
langs:
- csharp
- vb
name: MatrixHistogram
nameWithType: MatrixHistogram
fullName: EvilDICOM.CV.Image.MatrixHistogram
type: Class
source:
remote:
path: EvilDICOM/EvilDICOM.CV/Image/MatrixHistogram.cs
branch: master
repo: https://github.com/rexcardan/Evil-DICOM.git
id: MatrixHistogram
path: ../EvilDICOM.CV/Image/MatrixHistogram.cs
startLine: 10
assemblies:
- EvilDICOM.CV
namespace: EvilDICOM.CV.Image
syntax:
content: 'public class MatrixHistogram : IDisposable'
content.vb: >-
Public Class MatrixHistogram
Implements IDisposable
inheritance:
- System.Object
implements:
- System.IDisposable
inheritedMembers:
- System.Object.Equals(System.Object)
- System.Object.Equals(System.Object,System.Object)
- System.Object.GetHashCode
- System.Object.GetType
- System.Object.MemberwiseClone
- System.Object.ReferenceEquals(System.Object,System.Object)
- System.Object.ToString
modifiers.csharp:
- public
- class
modifiers.vb:
- Public
- Class
- uid: EvilDICOM.CV.Image.MatrixHistogram.#ctor(EvilDICOM.CV.Image.Matrix,System.Int32)
commentId: M:EvilDICOM.CV.Image.MatrixHistogram.#ctor(EvilDICOM.CV.Image.Matrix,System.Int32)
id: '#ctor(EvilDICOM.CV.Image.Matrix,System.Int32)'
parent: EvilDICOM.CV.Image.MatrixHistogram
langs:
- csharp
- vb
name: MatrixHistogram(Matrix, Int32)
nameWithType: MatrixHistogram.MatrixHistogram(Matrix, Int32)
fullName: EvilDICOM.CV.Image.MatrixHistogram.MatrixHistogram(EvilDICOM.CV.Image.Matrix, System.Int32)
type: Constructor
source:
remote:
path: EvilDICOM/EvilDICOM.CV/Image/MatrixHistogram.cs
branch: master
repo: https://github.com/rexcardan/Evil-DICOM.git
id: .ctor
path: ../EvilDICOM.CV/Image/MatrixHistogram.cs
startLine: 19
assemblies:
- EvilDICOM.CV
namespace: EvilDICOM.CV.Image
syntax:
content: public MatrixHistogram(Matrix m, int nBins)
parameters:
- id: m
type: EvilDICOM.CV.Image.Matrix
- id: nBins
type: System.Int32
content.vb: Public Sub New(m As Matrix, nBins As Integer)
overload: EvilDICOM.CV.Image.MatrixHistogram.#ctor*
modifiers.csharp:
- public
modifiers.vb:
- Public
- uid: EvilDICOM.CV.Image.MatrixHistogram.AddSlice(OpenCvSharp.Mat)
commentId: M:EvilDICOM.CV.Image.MatrixHistogram.AddSlice(OpenCvSharp.Mat)
id: AddSlice(OpenCvSharp.Mat)
parent: EvilDICOM.CV.Image.MatrixHistogram
langs:
- csharp
- vb
name: AddSlice(Mat)
nameWithType: MatrixHistogram.AddSlice(Mat)
fullName: EvilDICOM.CV.Image.MatrixHistogram.AddSlice(OpenCvSharp.Mat)
type: Method
source:
remote:
path: EvilDICOM/EvilDICOM.CV/Image/MatrixHistogram.cs
branch: master
repo: https://github.com/rexcardan/Evil-DICOM.git
id: AddSlice
path: ../EvilDICOM.CV/Image/MatrixHistogram.cs
startLine: 27
assemblies:
- EvilDICOM.CV
namespace: EvilDICOM.CV.Image
syntax:
content: public void AddSlice(Mat slice)
parameters:
- id: slice
type: OpenCvSharp.Mat
content.vb: Public Sub AddSlice(slice As Mat)
overload: EvilDICOM.CV.Image.MatrixHistogram.AddSlice*
modifiers.csharp:
- public
modifiers.vb:
- Public
- uid: EvilDICOM.CV.Image.MatrixHistogram.Count(System.Single,System.Single)
commentId: M:EvilDICOM.CV.Image.MatrixHistogram.Count(System.Single,System.Single)
id: Count(System.Single,System.Single)
parent: EvilDICOM.CV.Image.MatrixHistogram
langs:
- csharp
- vb
name: Count(Single, Single)
nameWithType: MatrixHistogram.Count(Single, Single)
fullName: EvilDICOM.CV.Image.MatrixHistogram.Count(System.Single, System.Single)
type: Method
source:
remote:
path: EvilDICOM/EvilDICOM.CV/Image/MatrixHistogram.cs
branch: master
repo: https://github.com/rexcardan/Evil-DICOM.git
id: Count
path: ../EvilDICOM.CV/Image/MatrixHistogram.cs
startLine: 39
assemblies:
- EvilDICOM.CV
namespace: EvilDICOM.CV.Image
summary: "\nCounts voxels between min and max\n"
example: []
syntax:
content: public int Count(float min, float max)
parameters:
- id: min
type: System.Single
description: ''
- id: max
type: System.Single
description: ''
return:
type: System.Int32
description: ''
content.vb: Public Function Count(min As Single, max As Single) As Integer
overload: EvilDICOM.CV.Image.MatrixHistogram.Count*
modifiers.csharp:
- public
modifiers.vb:
- Public
- uid: EvilDICOM.CV.Image.MatrixHistogram.Dispose
commentId: M:EvilDICOM.CV.Image.MatrixHistogram.Dispose
id: Dispose
parent: EvilDICOM.CV.Image.MatrixHistogram
langs:
- csharp
- vb
name: Dispose()
nameWithType: MatrixHistogram.Dispose()
fullName: EvilDICOM.CV.Image.MatrixHistogram.Dispose()
type: Method
source:
remote:
path: EvilDICOM/EvilDICOM.CV/Image/MatrixHistogram.cs
branch: master
repo: https://github.com/rexcardan/Evil-DICOM.git
id: Dispose
path: ../EvilDICOM.CV/Image/MatrixHistogram.cs
startLine: 60
assemblies:
- EvilDICOM.CV
namespace: EvilDICOM.CV.Image
syntax:
content: public void Dispose()
content.vb: Public Sub Dispose
overload: EvilDICOM.CV.Image.MatrixHistogram.Dispose*
implements:
- System.IDisposable.Dispose
modifiers.csharp:
- public
modifiers.vb:
- Public
references:
- uid: EvilDICOM.CV.Image
commentId: N:EvilDICOM.CV.Image
name: EvilDICOM.CV.Image
nameWithType: EvilDICOM.CV.Image
fullName: EvilDICOM.CV.Image
- uid: System.Object
commentId: T:System.Object
parent: System
isExternal: true
name: Object
nameWithType: Object
fullName: System.Object
- uid: System.IDisposable
commentId: T:System.IDisposable
parent: System
isExternal: true
name: IDisposable
nameWithType: IDisposable
fullName: System.IDisposable
- uid: System.Object.Equals(System.Object)
commentId: M:System.Object.Equals(System.Object)
parent: System.Object
isExternal: true
name: Equals(Object)
nameWithType: Object.Equals(Object)
fullName: System.Object.Equals(System.Object)
spec.csharp:
- uid: System.Object.Equals(System.Object)
name: Equals
nameWithType: Object.Equals
fullName: System.Object.Equals
isExternal: true
- name: (
nameWithType: (
fullName: (
- uid: System.Object
name: Object
nameWithType: Object
fullName: System.Object
isExternal: true
- name: )
nameWithType: )
fullName: )
spec.vb:
- uid: System.Object.Equals(System.Object)
name: Equals
nameWithType: Object.Equals
fullName: System.Object.Equals
isExternal: true
- name: (
nameWithType: (
fullName: (
- uid: System.Object
name: Object
nameWithType: Object
fullName: System.Object
isExternal: true
- name: )
nameWithType: )
fullName: )
- uid: System.Object.Equals(System.Object,System.Object)
commentId: M:System.Object.Equals(System.Object,System.Object)
parent: System.Object
isExternal: true
name: Equals(Object, Object)
nameWithType: Object.Equals(Object, Object)
fullName: System.Object.Equals(System.Object, System.Object)
spec.csharp:
- uid: System.Object.Equals(System.Object,System.Object)
name: Equals
nameWithType: Object.Equals
fullName: System.Object.Equals
isExternal: true
- name: (
nameWithType: (
fullName: (
- uid: System.Object
name: Object
nameWithType: Object
fullName: System.Object
isExternal: true
- name: ', '
nameWithType: ', '
fullName: ', '
- uid: System.Object
name: Object
nameWithType: Object
fullName: System.Object
isExternal: true
- name: )
nameWithType: )
fullName: )
spec.vb:
- uid: System.Object.Equals(System.Object,System.Object)
name: Equals
nameWithType: Object.Equals
fullName: System.Object.Equals
isExternal: true
- name: (
nameWithType: (
fullName: (
- uid: System.Object
name: Object
nameWithType: Object
fullName: System.Object
isExternal: true
- name: ', '
nameWithType: ', '
fullName: ', '
- uid: System.Object
name: Object
nameWithType: Object
fullName: System.Object
isExternal: true
- name: )
nameWithType: )
fullName: )
- uid: System.Object.GetHashCode
commentId: M:System.Object.GetHashCode
parent: System.Object
isExternal: true
name: GetHashCode()
nameWithType: Object.GetHashCode()
fullName: System.Object.GetHashCode()
spec.csharp:
- uid: System.Object.GetHashCode
name: GetHashCode
nameWithType: Object.GetHashCode
fullName: System.Object.GetHashCode
isExternal: true
- name: (
nameWithType: (
fullName: (
- name: )
nameWithType: )
fullName: )
spec.vb:
- uid: System.Object.GetHashCode
name: GetHashCode
nameWithType: Object.GetHashCode
fullName: System.Object.GetHashCode
isExternal: true
- name: (
nameWithType: (
fullName: (
- name: )
nameWithType: )
fullName: )
- uid: System.Object.GetType
commentId: M:System.Object.GetType
parent: System.Object
isExternal: true
name: GetType()
nameWithType: Object.GetType()
fullName: System.Object.GetType()
spec.csharp:
- uid: System.Object.GetType
name: GetType
nameWithType: Object.GetType
fullName: System.Object.GetType
isExternal: true
- name: (
nameWithType: (
fullName: (
- name: )
nameWithType: )
fullName: )
spec.vb:
- uid: System.Object.GetType
name: GetType
nameWithType: Object.GetType
fullName: System.Object.GetType
isExternal: true
- name: (
nameWithType: (
fullName: (
- name: )
nameWithType: )
fullName: )
- uid: System.Object.MemberwiseClone
commentId: M:System.Object.MemberwiseClone
parent: System.Object
isExternal: true
name: MemberwiseClone()
nameWithType: Object.MemberwiseClone()
fullName: System.Object.MemberwiseClone()
spec.csharp:
- uid: System.Object.MemberwiseClone
name: MemberwiseClone
nameWithType: Object.MemberwiseClone
fullName: System.Object.MemberwiseClone
isExternal: true
- name: (
nameWithType: (
fullName: (
- name: )
nameWithType: )
fullName: )
spec.vb:
- uid: System.Object.MemberwiseClone
name: MemberwiseClone
nameWithType: Object.MemberwiseClone
fullName: System.Object.MemberwiseClone
isExternal: true
- name: (
nameWithType: (
fullName: (
- name: )
nameWithType: )
fullName: )
- uid: System.Object.ReferenceEquals(System.Object,System.Object)
commentId: M:System.Object.ReferenceEquals(System.Object,System.Object)
parent: System.Object
isExternal: true
name: ReferenceEquals(Object, Object)
nameWithType: Object.ReferenceEquals(Object, Object)
fullName: System.Object.ReferenceEquals(System.Object, System.Object)
spec.csharp:
- uid: System.Object.ReferenceEquals(System.Object,System.Object)
name: ReferenceEquals
nameWithType: Object.ReferenceEquals
fullName: System.Object.ReferenceEquals
isExternal: true
- name: (
nameWithType: (
fullName: (
- uid: System.Object
name: Object
nameWithType: Object
fullName: System.Object
isExternal: true
- name: ', '
nameWithType: ', '
fullName: ', '
- uid: System.Object
name: Object
nameWithType: Object
fullName: System.Object
isExternal: true
- name: )
nameWithType: )
fullName: )
spec.vb:
- uid: System.Object.ReferenceEquals(System.Object,System.Object)
name: ReferenceEquals
nameWithType: Object.ReferenceEquals
fullName: System.Object.ReferenceEquals
isExternal: true
- name: (
nameWithType: (
fullName: (
- uid: System.Object
name: Object
nameWithType: Object
fullName: System.Object
isExternal: true
- name: ', '
nameWithType: ', '
fullName: ', '
- uid: System.Object
name: Object
nameWithType: Object
fullName: System.Object
isExternal: true
- name: )
nameWithType: )
fullName: )
- uid: System.Object.ToString
commentId: M:System.Object.ToString
parent: System.Object
isExternal: true
name: ToString()
nameWithType: Object.ToString()
fullName: System.Object.ToString()
spec.csharp:
- uid: System.Object.ToString
name: ToString
nameWithType: Object.ToString
fullName: System.Object.ToString
isExternal: true
- name: (
nameWithType: (
fullName: (
- name: )
nameWithType: )
fullName: )
spec.vb:
- uid: System.Object.ToString
name: ToString
nameWithType: Object.ToString
fullName: System.Object.ToString
isExternal: true
- name: (
nameWithType: (
fullName: (
- name: )
nameWithType: )
fullName: )
- uid: System
commentId: N:System
isExternal: true
name: System
nameWithType: System
fullName: System
- uid: EvilDICOM.CV.Image.MatrixHistogram.#ctor*
commentId: Overload:EvilDICOM.CV.Image.MatrixHistogram.#ctor
name: MatrixHistogram
nameWithType: MatrixHistogram.MatrixHistogram
fullName: EvilDICOM.CV.Image.MatrixHistogram.MatrixHistogram
- uid: EvilDICOM.CV.Image.Matrix
commentId: T:EvilDICOM.CV.Image.Matrix
parent: EvilDICOM.CV.Image
name: Matrix
nameWithType: Matrix
fullName: EvilDICOM.CV.Image.Matrix
- uid: System.Int32
commentId: T:System.Int32
parent: System
isExternal: true
name: Int32
nameWithType: Int32
fullName: System.Int32
- uid: EvilDICOM.CV.Image.MatrixHistogram.AddSlice*
commentId: Overload:EvilDICOM.CV.Image.MatrixHistogram.AddSlice
name: AddSlice
nameWithType: MatrixHistogram.AddSlice
fullName: EvilDICOM.CV.Image.MatrixHistogram.AddSlice
- uid: OpenCvSharp.Mat
commentId: T:OpenCvSharp.Mat
parent: OpenCvSharp
isExternal: true
name: Mat
nameWithType: Mat
fullName: OpenCvSharp.Mat
- uid: OpenCvSharp
commentId: N:OpenCvSharp
isExternal: true
name: OpenCvSharp
nameWithType: OpenCvSharp
fullName: OpenCvSharp
- uid: EvilDICOM.CV.Image.MatrixHistogram.Count*
commentId: Overload:EvilDICOM.CV.Image.MatrixHistogram.Count
name: Count
nameWithType: MatrixHistogram.Count
fullName: EvilDICOM.CV.Image.MatrixHistogram.Count
- uid: System.Single
commentId: T:System.Single
parent: System
isExternal: true
name: Single
nameWithType: Single
fullName: System.Single
- uid: EvilDICOM.CV.Image.MatrixHistogram.Dispose*
commentId: Overload:EvilDICOM.CV.Image.MatrixHistogram.Dispose
name: Dispose
nameWithType: MatrixHistogram.Dispose
fullName: EvilDICOM.CV.Image.MatrixHistogram.Dispose
- uid: System.IDisposable.Dispose
commentId: M:System.IDisposable.Dispose
parent: System.IDisposable
isExternal: true
name: Dispose()
nameWithType: IDisposable.Dispose()
fullName: System.IDisposable.Dispose()
spec.csharp:
- uid: System.IDisposable.Dispose
name: Dispose
nameWithType: IDisposable.Dispose
fullName: System.IDisposable.Dispose
isExternal: true
- name: (
nameWithType: (
fullName: (
- name: )
nameWithType: )
fullName: )
spec.vb:
- uid: System.IDisposable.Dispose
name: Dispose
nameWithType: IDisposable.Dispose
fullName: System.IDisposable.Dispose
isExternal: true
- name: (
nameWithType: (
fullName: (
- name: )
nameWithType: )
fullName: )
|
{
"pile_set_name": "Github"
}
|
# Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0,
# as published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# but not limited to OpenSSL) that is licensed under separate terms, as
# designated in a particular file or component or in included license
# documentation. The authors of MySQL hereby grant you an additional
# permission to link the program and your derivative works with the
# separately licensed software that they have included with MySQL.
# 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, version 2.0, 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 St, Fifth Floor, Boston, MA 02110-1301 USA
import mforms
class ToolBarManager:
def __init__(self):
self.toolbars = {}
def get_toolbar(self, name):
ret = None
if name in self.toolbars:
ret = self.toolbars[name]
else:
ret = mforms.newToolBar()
self.toolbars[name] = ret
return ret
|
{
"pile_set_name": "Github"
}
|
---
layout: base
title: 'Statistics of nummod in UD_Latin-LLCT'
udver: '2'
---
## Treebank Statistics: UD_Latin-LLCT: Relations: `nummod`
This relation is universal.
2165 nodes (1%) are attached to their parents as `nummod`.
1228 instances of `nummod` (57%) are right-to-left (child precedes parent).
Average distance between parent and child is 1.25773672055427.
The following 5 pairs of parts of speech are connected with `nummod`: <tt><a href="la_llct-pos-NOUN.html">NOUN</a></tt>-<tt><a href="la_llct-pos-NUM.html">NUM</a></tt> (2160; 100% instances), <tt><a href="la_llct-pos-VERB.html">VERB</a></tt>-<tt><a href="la_llct-pos-NUM.html">NUM</a></tt> (2; 0% instances), <tt><a href="la_llct-pos-ADJ.html">ADJ</a></tt>-<tt><a href="la_llct-pos-NUM.html">NUM</a></tt> (1; 0% instances), <tt><a href="la_llct-pos-DET.html">DET</a></tt>-<tt><a href="la_llct-pos-NUM.html">NUM</a></tt> (1; 0% instances), <tt><a href="la_llct-pos-PRON.html">PRON</a></tt>-<tt><a href="la_llct-pos-NUM.html">NUM</a></tt> (1; 0% instances).
~~~ conllu
# visual-style 4 bgColor:blue
# visual-style 4 fgColor:white
# visual-style 5 bgColor:blue
# visual-style 5 fgColor:white
# visual-style 5 4 nummod color:blue
1 unde unde ADV d|d|-|-|-|-|-|-|-|- PronType=Rel 9 advmod _ _
2 inter inter ADP r|r|-|-|-|-|-|-|-|- _ 3 case _ _
3 nos nos PRON p|p|1|p|-|-|-|m|a|- Case=Acc|Gender=Masc|Number=Plur|Person=1|PronType=Prs 8 obl _ _
4 duas duo NUM a|a|-|p|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Plur|NumType=Card 5 nummod _ _
5 cartulas chartula NOUN n|n|-|p|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Plur 8 obj _ _
6 Lopo lupus PROPN Propn|n|-|s|-|-|-|m|a|- Case=Acc|Gender=Masc|Number=Sing 8 nsubj _ _
7 notarium notarius NOUN n|n|-|s|-|-|-|m|a|- Case=Acc|Gender=Masc|Number=Sing 6 appos _ _
8 scribere scribo VERB v|v|-|-|p|n|a|-|-|- Aspect=Imp|Tense=Pres|VerbForm=Inf|Voice=Act 9 ccomp _ _
9 rogavimus rogo VERB v|v|1|p|r|i|a|-|-|- Aspect=Perf|Mood=Ind|Number=Plur|Person=1|Tense=Past|VerbForm=Fin|Voice=Act 0 root _ SpaceAfter=No
10 . . PUNCT Punc _ 9 punct _ _
~~~
~~~ conllu
# visual-style 14 bgColor:blue
# visual-style 14 fgColor:white
# visual-style 15 bgColor:blue
# visual-style 15 fgColor:white
# visual-style 15 14 nummod color:blue
1 Adelfredus Adalfridus PROPN Propn|n|-|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing 2 nsubj _ _
2 detinet detineo VERB v|v|3|s|p|i|a|-|-|- Aspect=Imp|Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin|Voice=Act 0 root _ _
3 eclesia ecclesia NOUN n|n|-|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing 2 obj _ _
4 sancte sanctus ADJ a|a|-|s|-|-|-|f|g|- Case=Gen|Gender=Fem|Number=Sing 5 amod _ _
5 Marie Maria PROPN Propn|n|-|s|-|-|-|f|g|- Case=Gen|Gender=Fem|Number=Sing 3 nmod _ _
6 in in ADP r|r|-|-|-|-|-|-|-|- _ 7 case _ _
7 Fereniano Ferronianum PROPN Propn|n|-|s|-|-|-|n|b|- Case=Abl|Gender=Neut|Number=Sing 3 nmod _ _
8 cum cum ADP r|r|-|-|-|-|-|-|-|- _ 9 case _ _
9 rebus res NOUN n|n|-|p|-|-|-|f|b|- Case=Abl|Gender=Fem|Number=Plur 3 nmod _ _
10 ad ad ADP r|r|-|-|-|-|-|-|-|- _ 11 case _ _
11 eam is PRON p|p|-|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing|Person=3|PronType=Dem,Prs 12 obl _ _
12 pertinentibus pertineo VERB t|t|-|p|p|p|a|f|b|- Aspect=Imp|Case=Abl|Gender=Fem|Number=Plur|Tense=Pres|VerbForm=Part|Voice=Act 9 acl _ _
13 et et CCONJ c|c|-|-|-|-|-|-|-|- _ 15 cc _ _
14 quinque quinque NUM m|m|-|-|-|-|-|-|-|- NumType=Card 15 nummod _ _
15 manentes maneo VERB t|t|-|p|p|p|a|m|a|- Aspect=Imp|Case=Acc|Gender=Masc|Number=Plur|Tense=Pres|VerbForm=Part|Voice=Act 3 conj _ _
16 in in ADP r|r|-|-|-|-|-|-|-|- _ 17 case _ _
17 Ciciano Cicianum PROPN Propn|n|-|s|-|-|-|n|b|- Case=Abl|Gender=Neut|Number=Sing 15 nmod _ SpaceAfter=No
18 ; ; PUNCT Punc _ 2 punct _ _
~~~
~~~ conllu
# visual-style 111 bgColor:blue
# visual-style 111 fgColor:white
# visual-style 112 bgColor:blue
# visual-style 112 fgColor:white
# visual-style 112 111 nummod color:blue
1 manifestu manifestus ADJ a|a|-|s|-|-|-|m|a|- Case=Acc|Gender=Masc|Number=Sing 0 root _ _
2 sum sum AUX v|v|1|s|p|i|a|-|-|- Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin|Voice=Act 1 cop _ _
3 ego ego PRON p|p|1|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing|Person=1|PronType=Prs 1 nsubj _ _
4 Liufridi Liutfridus PROPN Propn|n|-|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing 3 appos _ SpaceAfter=No
5 , , PUNCT Punc _ 6 punct _ _
6 filio filius NOUN n|n|-|s|-|-|-|m|a|- Case=Acc|Gender=Masc|Number=Sing 4 appos _ _
7 quondam quondam ADJ a|a|-|-|-|-|-|-|-|- _ 8 amod _ _
8 Donule Domnula PROPN Propn|n|-|s|-|-|-|f|g|- Case=Gen|Gender=Fem|Number=Sing 6 nmod _ SpaceAfter=No
9 , , PUNCT Punc _ 10 punct _ _
10 quia quia SCONJ c|c|-|-|-|-|-|-|-|- _ 32 mark _ _
11 tu tu PRON p|p|2|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing|Person=2|PronType=Prs 32 nsubj _ _
12 Ambrosius Ambrosius PROPN Propn|n|-|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing 11 appos _ SpaceAfter=No
13 , , PUNCT Punc _ 20 punct _ _
14 gratia gratia NOUN n|n|-|s|-|-|-|f|b|- Case=Abl|Gender=Fem|Number=Sing 20 nmod _ _
15 Dei Deus PROPN Propn|n|-|s|-|-|-|m|g|- Case=Gen|Gender=Masc|Number=Sing 14 nmod _ _
16 huius hic DET p|p|-|s|-|-|-|f|g|- Case=Gen|Gender=Fem|Number=Sing|PronType=Dem 19 det _ _
17 sancte sanctus ADJ a|a|-|s|-|-|-|f|g|- Case=Gen|Gender=Fem|Number=Sing 19 amod _ _
18 Lucane lucanus ADJ a|a|-|s|-|-|-|f|g|- Case=Gen|Gender=Fem|Number=Sing 19 amod _ _
19 ecclesie ecclesia NOUN n|n|-|s|-|-|-|f|g|- Case=Gen|Gender=Fem|Number=Sing 20 nmod _ _
20 episcopus episcopus NOUN n|n|-|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing 12 appos _ SpaceAfter=No
21 , , PUNCT Punc _ 11 punct _ _
22 per per ADP r|r|-|-|-|-|-|-|-|- _ 23 case _ _
23 cartula chartula NOUN n|n|-|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing 32 obl _ _
24 livellario libellarius ADJ a|a|-|s|-|-|-|m|b|- Case=Abl|Gender=Masc|Number=Sing 25 amod _ _
25 ordine ordo NOUN n|n|-|s|-|-|-|m|b|- Case=Abl|Gender=Masc|Number=Sing 32 obl _ _
26 ad ad ADP r|r|-|-|-|-|-|-|-|- _ 27 mark _ _
27 lavorandum laboro VERB t|t|-|s|p|d|p|n|a|- Aspect=Imp|Case=Acc|Gender=Neut|Number=Sing|Tense=Pres|VerbForm=Ger|Voice=Pass 32 advcl _ _
28 et et CCONJ c|c|-|-|-|-|-|-|-|- _ 29 cc _ _
29 gubernandum guberno VERB t|t|-|s|p|d|p|n|a|- Aspect=Imp|Case=Acc|Gender=Neut|Number=Sing|Tense=Pres|VerbForm=Ger|Voice=Pass 27 conj _ _
30 seo seu CCONJ c|c|-|-|-|-|-|-|-|- _ 31 cc _ _
31 meliorandum melioro VERB t|t|-|s|p|d|p|n|a|- Aspect=Imp|Case=Acc|Gender=Neut|Number=Sing|Tense=Pres|VerbForm=Ger|Voice=Pass 27 conj _ _
32 dedisti do VERB v|v|2|s|r|i|a|-|-|- Aspect=Perf|Mood=Ind|Number=Sing|Person=2|Tense=Past|VerbForm=Fin|Voice=Act 1 advcl _ _
33 mihi ego PRON p|p|1|s|-|-|-|m|d|- Case=Dat|Gender=Masc|Number=Sing|Person=1|PronType=Prs 32 obl:arg _ SpaceAfter=No
34 , , PUNCT Punc _ 37 punct _ _
35 id is PRON p|p|-|s|-|-|-|n|n|- Case=Nom|Gender=Neut|Number=Sing|Person=3|PronType=Dem,Prs 37 advmod:emph _ _
36 est sum VERB v|v|3|s|p|i|a|-|-|- Aspect=Imp|Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin|Voice=Act 35 fixed _ _
37 res res NOUN n|n|-|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing 32 obj _ _
38 mea meus DET a|a|1|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing|Number[psor]=Sing|Person=1|Poss=Yes|PronType=Prs 37 det _ _
39 illa ille DET p|p|-|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing|PronType=Dem 37 det _ _
40 pertenentes pertineo VERB t|t|-|s|p|p|a|f|a|- Aspect=Imp|Case=Acc|Gender=Fem|Number=Sing|Tense=Pres|VerbForm=Part|Voice=Act 37 acl _ _
41 ipsius ipse DET p|p|-|s|-|-|-|m|g|- Case=Gen|Gender=Masc|Number=Sing|PronType=Dem 42 det _ _
42 episcopatui episcopatus NOUN n|n|-|s|-|-|-|m|g|- Case=Gen|Gender=Masc|Number=Sing 40 obl:arg _ _
43 vestri uester DET a|a|2|s|-|-|-|m|g|- Case=Gen|Gender=Masc|Number=Sing|Number[psor]=Plur|Person=2|Poss=Yes|PronType=Prs 42 det _ _
44 sancti sanctus ADJ a|a|-|s|-|-|-|m|g|- Case=Gen|Gender=Masc|Number=Sing 45 amod _ _
45 Martini Martinus PROPN Propn|n|-|s|-|-|-|m|g|- Case=Gen|Gender=Masc|Number=Sing 42 nmod _ SpaceAfter=No
46 , , PUNCT Punc _ 49 punct _ _
47 qui qui PRON p|p|-|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing|PronType=Rel 49 nsubj:pass _ _
48 esse sum VERB v|v|-|-|p|n|a|-|-|- Aspect=Imp|Tense=Pres|VerbForm=Inf|Voice=Act 49 xcomp _ _
49 videtur uideo VERB v|v|3|s|p|i|p|-|-|- Aspect=Imp|Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin|Voice=Pass 37 acl:relcl _ _
50 in in ADP r|r|-|-|-|-|-|-|-|- _ 51 case _ _
51 loco locus NOUN n|n|-|s|-|-|-|m|b|- Case=Abl|Gender=Masc|Number=Sing 48 obl _ _
52 Orticaria Orticaria PROPN Propn|n|-|s|-|-|-|f|b|- Case=Abl|Gender=Fem|Number=Sing 51 flat _ SpaceAfter=No
53 , , PUNCT Punc _ 60 punct _ _
54 quas qui PRON p|p|-|p|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Plur|PronType=Rel 60 obj _ _
55 ego ego PRON p|p|1|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing|Person=1|PronType=Prs 60 nsubj _ _
56 ipsi ipse DET p|p|-|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing|PronType=Dem 55 det _ _
57 ad ad ADP r|r|-|-|-|-|-|-|-|- _ 58 case _ _
58 manus manus NOUN n|n|-|p|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Plur 60 obl _ _
59 mea meus DET a|a|1|p|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Plur|Number[psor]=Sing|Person=1|Poss=Yes|PronType=Prs 58 det _ _
60 abui habeo VERB v|v|1|s|r|i|a|-|-|- Aspect=Perf|Mood=Ind|Number=Sing|Person=1|Tense=Past|VerbForm=Fin|Voice=Act 37 acl:relcl _ SpaceAfter=No
61 , , PUNCT Punc _ 63 punct _ _
62 tam tam ADV d|d|-|-|-|-|-|-|-|- PronType=Dem 63 cc _ _
63 terris terra NOUN n|n|-|p|-|-|-|f|b|- Case=Abl|Gender=Fem|Number=Plur 37 conj _ SpaceAfter=No
64 , , PUNCT Punc _ 65 punct _ _
65 vineis uinea NOUN n|n|-|p|-|-|-|f|b|- Case=Abl|Gender=Fem|Number=Plur 63 conj _ SpaceAfter=No
66 , , PUNCT Punc _ 67 punct _ _
67 silvis silua NOUN n|n|-|p|-|-|-|f|b|- Case=Abl|Gender=Fem|Number=Plur 63 conj _ SpaceAfter=No
68 , , PUNCT Punc _ 69 punct _ _
69 virgareis uirgareum NOUN n|n|-|p|-|-|-|n|b|- Case=Abl|Gender=Neut|Number=Plur 63 conj _ SpaceAfter=No
70 , , PUNCT Punc _ 72 punct _ _
71 culta cultus ADJ a|a|-|s|-|-|-|f|b|- Case=Abl|Gender=Fem|Number=Sing 72 amod _ _
72 res res NOUN n|n|-|s|-|-|-|f|b|- Case=Abl|Gender=Fem|Number=Sing 63 conj _ _
73 vel uel CCONJ c|c|-|-|-|-|-|-|-|- _ 74 cc _ _
74 inculta incultus ADJ a|a|-|s|-|-|-|f|b|- Case=Abl|Gender=Fem|Number=Sing 71 conj _ SpaceAfter=No
75 , , PUNCT Punc _ 76 punct _ _
76 omnia omnis DET a|a|-|p|-|-|-|n|a|- Case=Acc|Gender=Neut|Number=Plur|PronType=Tot 32 dislocated:obj _ _
77 quantum quantum ADV d|d|-|-|-|-|-|-|-|- PronType=Rel 88 advmod _ _
78 in in ADP r|r|-|-|-|-|-|-|-|- _ 80 case _ _
79 ipso ipse DET p|p|-|s|-|-|-|m|b|- Case=Abl|Gender=Masc|Number=Sing|PronType=Dem 80 det _ _
80 loco locus NOUN n|n|-|s|-|-|-|m|b|- Case=Abl|Gender=Masc|Number=Sing 88 obl _ _
81 Orticaria Orticaria PROPN Propn|n|-|s|-|-|-|f|b|- Case=Abl|Gender=Fem|Number=Sing 80 flat _ _
82 ipsius ipse DET p|p|-|s|-|-|-|f|g|- Case=Gen|Gender=Fem|Number=Sing|PronType=Dem 83 det _ _
83 ecclesie ecclesia NOUN n|n|-|s|-|-|-|f|d|- Case=Dat|Gender=Fem|Number=Sing 88 obl:arg _ _
84 sancti sanctus ADJ a|a|-|s|-|-|-|m|g|- Case=Gen|Gender=Masc|Number=Sing 86 amod _ _
85 [--] missing^token PUNCT Punc _ 84 punct _ _
86 Martini Martinus PROPN Propn|n|-|s|-|-|-|m|g|- Case=Gen|Gender=Masc|Number=Sing 83 nmod _ _
87 est sum AUX v|v|3|s|p|i|a|-|-|- Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin|Voice=Act 88 cop _ _
88 pertenentes pertineo VERB t|t|-|s|p|p|a|f|a|- Aspect=Imp|Case=Acc|Gender=Fem|Number=Sing|Tense=Pres|VerbForm=Part|Voice=Act 76 acl:relcl _ SpaceAfter=No
89 , , PUNCT Punc _ 91 punct _ _
90 in in ADP r|r|-|-|-|-|-|-|-|- _ 91 case _ _
91 integrum integer ADJ a|a|-|s|-|-|-|n|a|- Case=Acc|Gender=Neut|Number=Sing 32 obl _ SpaceAfter=No
92 , , PUNCT Punc _ 94 punct _ _
93 tali talis DET a|a|-|s|-|-|-|m|b|- Case=Abl|Gender=Masc|Number=Sing|PronType=Dem 94 det _ _
94 ordine ordo NOUN n|n|-|s|-|-|-|m|b|- Case=Abl|Gender=Masc|Number=Sing 32 obl _ _
95 ut ut SCONJ c|c|-|-|-|-|-|-|-|- _ 105 mark _ _
96 infra infra ADP r|r|-|-|-|-|-|-|-|- _ 98 case _ _
97 ipsa ipse DET p|p|-|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing|PronType=Dem 98 det _ _
98 res res NOUN n|n|-|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing 100 obl _ _
99 casa casa NOUN n|n|-|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing 100 obj _ _
100 levare leuo VERB v|v|-|-|p|n|a|-|-|- Aspect=Imp|Tense=Pres|VerbForm=Inf|Voice=Act 105 xcomp _ _
101 et et CCONJ c|c|-|-|-|-|-|-|-|- _ 102 cc _ _
102 claudere claudo VERB v|v|-|-|p|n|a|-|-|- Aspect=Imp|Tense=Pres|VerbForm=Inf|Voice=Act 100 conj _ _
103 seo seu CCONJ c|c|-|-|-|-|-|-|-|- _ 104 cc _ _
104 coperire cooperio VERB v|v|-|-|p|n|a|-|-|- Aspect=Imp|Tense=Pres|VerbForm=Inf|Voice=Act 100 conj _ _
105 debeamus debeo VERB v|v|1|p|p|s|a|-|-|- Aspect=Imp|Mood=Sub|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin|VerbType=Mod|Voice=Act 94 acl _ _
106 de de ADP r|r|-|-|-|-|-|-|-|- _ 108 case _ _
107 triginta triginta NUM m|m|-|-|-|-|-|-|-|- NumType=Card 108 nummod _ _
108 pedes pes NOUN n|n|-|p|-|-|-|m|a|- Case=Acc|Gender=Masc|Number=Plur 109 nmod _ _
109 longas longus ADJ a|a|-|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing 99 amod _ _
110 et et CCONJ c|c|-|-|-|-|-|-|-|- _ 112 cc _ _
111 quindecim quindecim NUM m|m|-|-|-|-|-|-|-|- NumType=Card 112 nummod _ _
112 latas latus ADJ a|a|-|s|-|-|-|f|a|- Case=Acc|Gender=Fem|Number=Sing 109 conj _ _
113 infra infra ADP r|r|-|-|-|-|-|-|-|- _ 116 case _ _
114 isti iste DET p|p|-|p|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Plur|PronType=Dem 116 det _ _
115 tres tres NUM a|a|-|p|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Plur|NumType=Card 116 nummod _ _
116 anni annus NOUN n|n|-|p|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Plur 100 obl _ _
117 expleti expleo VERB t|t|-|p|r|p|p|m|n|- Aspect=Perf|Case=Nom|Gender=Masc|Number=Plur|Tense=Past|VerbForm=Part|Voice=Pass 116 acl _ _
118 proximi proximus ADJ a|a|-|p|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Plur 116 amod _ _
119 venturi uenio VERB t|t|-|p|f|p|a|m|n|- Aspect=Imp|Case=Nom|Gender=Masc|Number=Plur|Tense=Fut|VerbForm=Part|Voice=Act 116 acl _ _
120 tam tam ADV d|d|-|-|-|-|-|-|-|- PronType=Dem 121 cc _ _
121 ego ego PRON p|p|1|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing|Person=1|PronType=Prs 105 conj _ _
122 aut aut CCONJ c|c|-|-|-|-|-|-|-|- _ 123 cc _ _
123 filio filius NOUN n|n|-|s|-|-|-|m|a|- Case=Acc|Gender=Masc|Number=Sing 121 conj _ _
124 meo meus DET a|a|1|s|-|-|-|m|a|- Case=Acc|Gender=Masc|Number=Sing|Number[psor]=Sing|Person=1|Poss=Yes|PronType=Prs 123 det _ _
125 Vualfridi Walfridus PROPN Propn|n|-|s|-|-|-|m|n|- Case=Nom|Gender=Masc|Number=Sing 123 flat _ SpaceAfter=No
126 ; ; PUNCT Punc _ 1 punct _ _
~~~
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pyatv/mrp/protobuf/ProtocolMessage.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='pyatv/mrp/protobuf/ProtocolMessage.proto',
package='',
syntax='proto2',
serialized_options=None,
serialized_pb=b'\n(pyatv/mrp/protobuf/ProtocolMessage.proto\"\xe1\x14\n\tErrorCode\"\xd3\x14\n\x04\x45num\x12\x0b\n\x07NoError\x10\x00\x12\x10\n\x0cUnknownError\x10\x01\x12\x14\n\x10InvalidOperation\x10\x02\x12\x19\n\x15OperationNotPermitted\x10\x03\x12\x16\n\x12\x43lientDoesNotExist\x10\x04\x12\x16\n\x12OriginDoesNotExist\x10\x05\x12\x18\n\x14UnsupportedOperation\x10\x06\x12\x1a\n\x16\x46\x61iledToSetPickedRoute\x10\x07\x12 \n\x1c\x46\x61iledToRegisterCustomOrigin\x10\x08\x12\x1e\n\x1a\x46\x61iledToRemoveCustomOrigin\x10\t\x12&\n\"TheApplicationActivityDoesNotExist\x10\n\x12.\n*TheAppHasNotSetupABrowsableContentEndpoint\x10\x0b\x12\x41\n=TheRequestedBrowsableContentApiIsNotSupportedByTheApplication\x10\x0c\x12\x32\n.TheNotficationHasNotBeenWhitelistedByTheServer\x10\r\x12\x38\n4OperationRequiresAClientCallbackToHaveBeenRegistered\x10\x0e\x12:\n6OperationRequiresAClientDataSourceToHaveBeenRegistered\x10\x0f\x12\x35\n1RequestedDataIsOutOfDateAndShouldBeRequestedAgain\x10\x10\x12\x30\n,TheDevicesEnforcedVolumeLimitHasBeenExceeded\x10\x11\x12\x1b\n\x17VolumeValueIsOutOfRange\x10\x12\x12$\n VolumeIsAlreadyAtTheMaximumValue\x10\x13\x12\x18\n\x14VolumeIsAlreadyMuted\x10\x14\x12\"\n\x1eVoiceInputEndpointDoesNotExist\x10\x15\x12\x34\n0TheVoiceInputDeviceIsNotRegisteredOrDoesNotExist\x10\x16\x12\x15\n\x11\x45ncryptionFailure\x10\x17\x12\x18\n\x14\x45ndpointDoesNotExist\x10\x18\x12.\n*TheClientsApplicationCancelledTheOperation\x10\x19\x12\x18\n\x14TheOperationTimedOut\x10\x1a\x12*\n&TheSpecifiedPlayerPathObjectWasInvalid\x10\x1b\x12:\n6AddingOrRemovingDevicesFromTheAvOutputContextHasFailed\x10\x1c\x12,\n(CouldNotFindTheSpecifiedNowPlayingPlayer\x10\x1d\x12\'\n#TheSpecifiedContentItemDoesNotExist\x10\x1e\x12\x1f\n\x1bTheSpecifiedOffsetIsInvalid\x10\x1f\x12&\n\"TheSpecifiedOutputContextIsInvalid\x10 \x12\x32\n.OneOrMoreSpecifiedOutputDevicesAreNotGroupable\x10!\x12H\nDTheSpecifiedOutputContextDoesNotSupportAddingMoreThanOneOutputDevice\x10\"\x12,\n(CouldNotFindTheSpecifiedNowPlayingClient\x10#\x12P\nLEndpointVolumeControlIsOnlyPossibleIfTheEndpointIsPickedOrRemoteControllable\x10$\x12T\nPOutputDeviceVolumeControlIsOnlyPossibleIfTheEndpointIsPickedOrRemoteControllable\x10%\x12\"\n\x1e\x43oderMustSupportKeyValueCoding\x10&\x12$\n CouldNotFindTheGivenOutputdevice\x10\'\x12!\n\x1d\x46\x61iledToConnectToRemoteDevice\x10\x64\x12 \n\x1c\x41uthenticationTokenIsInvalid\x10\x65\x12\x33\n/RecordingSessionIsAlreadyInProgressOnThisDevice\x10\x66\x12$\n TheDeviceIsNotCurrentlyRecording\x10g\x12\x1c\n\x18TheClientHasDisconnected\x10h\x12\x1c\n\x18TheServerHasDisconnected\x10i\x12,\n(TheConnectionHasBeenCancelledByTheClient\x10j\x12\x34\n0PairingFunctionalityIsLockedDueToSecurityReasons\x10k\x12,\n(TheClientsOperatingSystemVersionIsTooOld\x10l\x12(\n$TheClientsApplicationVersionIsTooOld\x10m\x12\x18\n\x14TheDeviceIsNotPaired\x10n\x12?\n;ThePinPairingDialogWasRemovedByTheUserBeforePairingOccoured\x10o\x12@\n<ThePinPairingDialogWasRemovedByATimeoutBeforePairingOccoured\x10p\x12\x19\n\x15TheConnectionTimedout\x10q\x12\"\n\x1ePairingWithThisDeviceIsBlocked\x10r\x12\x1b\n\x17TheDeviceIsGoingToSleep\x10s\x12\x1d\n\x19\x43onnectionBlockedByServer\x10t\x12<\n8MravendpointWasDeallocatedWhileWaitingForDeviceToConnect\x10u\x12H\nCOutputContextModificationCausedADeviceToNoLongerBeAProxyGroupPlayer\x10\xc8\x01\x12\x44\n?OutputContextModificationCausedADeviceToBecomeAProxyGroupPlayer\x10\xc9\x01\x12\x37\n2OutputContextModificationRequestedNoTopologyChange\x10\xca\x01\x12\x16\n\x11OtherUnknownError\x10\xab\x02\"\xe9\x0e\n\x0fProtocolMessage\x12#\n\x04type\x18\x01 \x01(\x0e\x32\x15.ProtocolMessage.Type\x12\x12\n\nidentifier\x18\x02 \x01(\t\x12\x1b\n\x13\x61uthenticationToken\x18\x03 \x01(\t\x12\"\n\terrorCode\x18\x04 \x01(\x0e\x32\x0f.ErrorCode.Enum\x12\x11\n\ttimestamp\x18\x05 \x01(\x04\"\xbe\r\n\x04Type\x12\x13\n\x0fUNKNOWN_MESSAGE\x10\x00\x12\x18\n\x14SEND_COMMAND_MESSAGE\x10\x01\x12\x1f\n\x1bSEND_COMMAND_RESULT_MESSAGE\x10\x02\x12\x15\n\x11GET_STATE_MESSAGE\x10\x03\x12\x15\n\x11SET_STATE_MESSAGE\x10\x04\x12\x17\n\x13SET_ARTWORK_MESSAGE\x10\x05\x12\x1f\n\x1bREGISTER_HID_DEVICE_MESSAGE\x10\x06\x12&\n\"REGISTER_HID_DEVICE_RESULT_MESSAGE\x10\x07\x12\x1a\n\x16SEND_HID_EVENT_MESSAGE\x10\x08\x12\x1b\n\x17SEND_HID_REPORT_MESSAGE\x10\t\x12$\n SEND_VIRTUAL_TOUCH_EVENT_MESSAGE\x10\n\x12\x18\n\x14NOTIFICATION_MESSAGE\x10\x0b\x12.\n*CONTENT_ITEMS_CHANGED_NOTIFICATION_MESSAGE\x10\x0c\x12\x17\n\x13\x44\x45VICE_INFO_MESSAGE\x10\x0f\x12!\n\x1d\x43LIENT_UPDATES_CONFIG_MESSAGE\x10\x10\x12\'\n#VOLUME_CONTROL_AVAILABILITY_MESSAGE\x10\x11\x12\x1b\n\x17GAME_CONTROLLER_MESSAGE\x10\x12\x12$\n REGISTER_GAME_CONTROLLER_MESSAGE\x10\x13\x12-\n)REGISTER_GAME_CONTROLLER_RESPONSE_MESSAGE\x10\x14\x12&\n\"UNREGISTER_GAME_CONTROLLER_MESSAGE\x10\x15\x12/\n+REGISTER_FOR_GAME_CONTROLLER_EVENTS_MESSAGE\x10\x16\x12\x14\n\x10KEYBOARD_MESSAGE\x10\x17\x12 \n\x1cGET_KEYBOARD_SESSION_MESSAGE\x10\x18\x12\x16\n\x12TEXT_INPUT_MESSAGE\x10\x19\x12#\n\x1fGET_VOICE_INPUT_DEVICES_MESSAGE\x10\x1a\x12,\n(GET_VOICE_INPUT_DEVICES_RESPONSE_MESSAGE\x10\x1b\x12\'\n#REGISTER_VOICE_INPUT_DEVICE_MESSAGE\x10\x1c\x12\x30\n,REGISTER_VOICE_INPUT_DEVICE_RESPONSE_MESSAGE\x10\x1d\x12\x1f\n\x1bSET_RECORDING_STATE_MESSAGE\x10\x1e\x12\x1c\n\x18SEND_VOICE_INPUT_MESSAGE\x10\x1f\x12\"\n\x1ePLAYBACK_QUEUE_REQUEST_MESSAGE\x10 \x12\x17\n\x13TRANSACTION_MESSAGE\x10!\x12\x1a\n\x16\x43RYPTO_PAIRING_MESSAGE\x10\"\x12&\n\"GAME_CONTROLLER_PROPERTIES_MESSAGE\x10#\x12\x1b\n\x17SET_READY_STATE_MESSAGE\x10$\x12\x1e\n\x1a\x44\x45VICE_INFO_UPDATE_MESSAGE\x10%\x12 \n\x1cSET_CONNECTION_STATE_MESSAGE\x10&\x12\x15\n\x11SEND_BUTTON_EVENT\x10\'\x12\x1b\n\x17SET_HILITE_MODE_MESSAGE\x10(\x12\x17\n\x13WAKE_DEVICE_MESSAGE\x10)\x12\x13\n\x0fGENERIC_MESSAGE\x10*\x12+\n\'SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE\x10+\x12\x15\n\x11SEND_LYRICS_EVENT\x10,\x12\"\n\x1eSET_NOW_PLAYING_CLIENT_MESSAGE\x10.\x12\"\n\x1eSET_NOT_PLAYING_PLAYER_MESSAGE\x10/\x12\x19\n\x15REMOVE_CLIENT_MESSAGE\x10\x35\x12\x19\n\x15REMOVE_PLAYER_MESSAGE\x10\x36\x12\x19\n\x15UPDATE_CLIENT_MESSAGE\x10\x37\x12\x1f\n\x1bUPDATE_CONTENT_ITEM_MESSAGE\x10\x38\x12\x32\n.VOLUME_CONTROL_CAPABILITIES_DID_CHANGE_MESSAGE\x10@\x12 \n\x1cUPDATE_OUTPUT_DEVICE_MESSAGE\x10\x41\x12*\n&SET_DEFAULT_SUPPORTED_COMMANDS_MESSAGE\x10H*\x08\x08\x06\x10\x80\x80\x80\x80\x02'
)
_ERRORCODE_ENUM = _descriptor.EnumDescriptor(
name='Enum',
full_name='ErrorCode.Enum',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='NoError', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UnknownError', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='InvalidOperation', index=2, number=2,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OperationNotPermitted', index=3, number=3,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='ClientDoesNotExist', index=4, number=4,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OriginDoesNotExist', index=5, number=5,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UnsupportedOperation', index=6, number=6,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='FailedToSetPickedRoute', index=7, number=7,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='FailedToRegisterCustomOrigin', index=8, number=8,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='FailedToRemoveCustomOrigin', index=9, number=9,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheApplicationActivityDoesNotExist', index=10, number=10,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheAppHasNotSetupABrowsableContentEndpoint', index=11, number=11,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheRequestedBrowsableContentApiIsNotSupportedByTheApplication', index=12, number=12,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheNotficationHasNotBeenWhitelistedByTheServer', index=13, number=13,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OperationRequiresAClientCallbackToHaveBeenRegistered', index=14, number=14,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OperationRequiresAClientDataSourceToHaveBeenRegistered', index=15, number=15,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RequestedDataIsOutOfDateAndShouldBeRequestedAgain', index=16, number=16,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheDevicesEnforcedVolumeLimitHasBeenExceeded', index=17, number=17,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='VolumeValueIsOutOfRange', index=18, number=18,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='VolumeIsAlreadyAtTheMaximumValue', index=19, number=19,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='VolumeIsAlreadyMuted', index=20, number=20,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='VoiceInputEndpointDoesNotExist', index=21, number=21,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheVoiceInputDeviceIsNotRegisteredOrDoesNotExist', index=22, number=22,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='EncryptionFailure', index=23, number=23,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='EndpointDoesNotExist', index=24, number=24,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheClientsApplicationCancelledTheOperation', index=25, number=25,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheOperationTimedOut', index=26, number=26,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheSpecifiedPlayerPathObjectWasInvalid', index=27, number=27,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='AddingOrRemovingDevicesFromTheAvOutputContextHasFailed', index=28, number=28,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CouldNotFindTheSpecifiedNowPlayingPlayer', index=29, number=29,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheSpecifiedContentItemDoesNotExist', index=30, number=30,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheSpecifiedOffsetIsInvalid', index=31, number=31,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheSpecifiedOutputContextIsInvalid', index=32, number=32,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OneOrMoreSpecifiedOutputDevicesAreNotGroupable', index=33, number=33,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheSpecifiedOutputContextDoesNotSupportAddingMoreThanOneOutputDevice', index=34, number=34,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CouldNotFindTheSpecifiedNowPlayingClient', index=35, number=35,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='EndpointVolumeControlIsOnlyPossibleIfTheEndpointIsPickedOrRemoteControllable', index=36, number=36,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OutputDeviceVolumeControlIsOnlyPossibleIfTheEndpointIsPickedOrRemoteControllable', index=37, number=37,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CoderMustSupportKeyValueCoding', index=38, number=38,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CouldNotFindTheGivenOutputdevice', index=39, number=39,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='FailedToConnectToRemoteDevice', index=40, number=100,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='AuthenticationTokenIsInvalid', index=41, number=101,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RecordingSessionIsAlreadyInProgressOnThisDevice', index=42, number=102,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheDeviceIsNotCurrentlyRecording', index=43, number=103,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheClientHasDisconnected', index=44, number=104,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheServerHasDisconnected', index=45, number=105,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheConnectionHasBeenCancelledByTheClient', index=46, number=106,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='PairingFunctionalityIsLockedDueToSecurityReasons', index=47, number=107,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheClientsOperatingSystemVersionIsTooOld', index=48, number=108,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheClientsApplicationVersionIsTooOld', index=49, number=109,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheDeviceIsNotPaired', index=50, number=110,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='ThePinPairingDialogWasRemovedByTheUserBeforePairingOccoured', index=51, number=111,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='ThePinPairingDialogWasRemovedByATimeoutBeforePairingOccoured', index=52, number=112,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheConnectionTimedout', index=53, number=113,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='PairingWithThisDeviceIsBlocked', index=54, number=114,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TheDeviceIsGoingToSleep', index=55, number=115,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='ConnectionBlockedByServer', index=56, number=116,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='MravendpointWasDeallocatedWhileWaitingForDeviceToConnect', index=57, number=117,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OutputContextModificationCausedADeviceToNoLongerBeAProxyGroupPlayer', index=58, number=200,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OutputContextModificationCausedADeviceToBecomeAProxyGroupPlayer', index=59, number=201,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OutputContextModificationRequestedNoTopologyChange', index=60, number=202,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OtherUnknownError', index=61, number=299,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=59,
serialized_end=2702,
)
_sym_db.RegisterEnumDescriptor(_ERRORCODE_ENUM)
_PROTOCOLMESSAGE_TYPE = _descriptor.EnumDescriptor(
name='Type',
full_name='ProtocolMessage.Type',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNKNOWN_MESSAGE', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SEND_COMMAND_MESSAGE', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SEND_COMMAND_RESULT_MESSAGE', index=2, number=2,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='GET_STATE_MESSAGE', index=3, number=3,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SET_STATE_MESSAGE', index=4, number=4,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SET_ARTWORK_MESSAGE', index=5, number=5,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='REGISTER_HID_DEVICE_MESSAGE', index=6, number=6,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='REGISTER_HID_DEVICE_RESULT_MESSAGE', index=7, number=7,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SEND_HID_EVENT_MESSAGE', index=8, number=8,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SEND_HID_REPORT_MESSAGE', index=9, number=9,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SEND_VIRTUAL_TOUCH_EVENT_MESSAGE', index=10, number=10,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='NOTIFICATION_MESSAGE', index=11, number=11,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CONTENT_ITEMS_CHANGED_NOTIFICATION_MESSAGE', index=12, number=12,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='DEVICE_INFO_MESSAGE', index=13, number=15,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CLIENT_UPDATES_CONFIG_MESSAGE', index=14, number=16,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='VOLUME_CONTROL_AVAILABILITY_MESSAGE', index=15, number=17,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='GAME_CONTROLLER_MESSAGE', index=16, number=18,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='REGISTER_GAME_CONTROLLER_MESSAGE', index=17, number=19,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='REGISTER_GAME_CONTROLLER_RESPONSE_MESSAGE', index=18, number=20,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UNREGISTER_GAME_CONTROLLER_MESSAGE', index=19, number=21,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='REGISTER_FOR_GAME_CONTROLLER_EVENTS_MESSAGE', index=20, number=22,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='KEYBOARD_MESSAGE', index=21, number=23,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='GET_KEYBOARD_SESSION_MESSAGE', index=22, number=24,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TEXT_INPUT_MESSAGE', index=23, number=25,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='GET_VOICE_INPUT_DEVICES_MESSAGE', index=24, number=26,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='GET_VOICE_INPUT_DEVICES_RESPONSE_MESSAGE', index=25, number=27,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='REGISTER_VOICE_INPUT_DEVICE_MESSAGE', index=26, number=28,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='REGISTER_VOICE_INPUT_DEVICE_RESPONSE_MESSAGE', index=27, number=29,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SET_RECORDING_STATE_MESSAGE', index=28, number=30,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SEND_VOICE_INPUT_MESSAGE', index=29, number=31,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='PLAYBACK_QUEUE_REQUEST_MESSAGE', index=30, number=32,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TRANSACTION_MESSAGE', index=31, number=33,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CRYPTO_PAIRING_MESSAGE', index=32, number=34,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='GAME_CONTROLLER_PROPERTIES_MESSAGE', index=33, number=35,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SET_READY_STATE_MESSAGE', index=34, number=36,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='DEVICE_INFO_UPDATE_MESSAGE', index=35, number=37,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SET_CONNECTION_STATE_MESSAGE', index=36, number=38,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SEND_BUTTON_EVENT', index=37, number=39,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SET_HILITE_MODE_MESSAGE', index=38, number=40,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='WAKE_DEVICE_MESSAGE', index=39, number=41,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='GENERIC_MESSAGE', index=40, number=42,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE', index=41, number=43,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SEND_LYRICS_EVENT', index=42, number=44,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SET_NOW_PLAYING_CLIENT_MESSAGE', index=43, number=46,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SET_NOT_PLAYING_PLAYER_MESSAGE', index=44, number=47,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='REMOVE_CLIENT_MESSAGE', index=45, number=53,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='REMOVE_PLAYER_MESSAGE', index=46, number=54,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UPDATE_CLIENT_MESSAGE', index=47, number=55,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UPDATE_CONTENT_ITEM_MESSAGE', index=48, number=56,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='VOLUME_CONTROL_CAPABILITIES_DID_CHANGE_MESSAGE', index=49, number=64,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UPDATE_OUTPUT_DEVICE_MESSAGE', index=50, number=65,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SET_DEFAULT_SUPPORTED_COMMANDS_MESSAGE', index=51, number=72,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=2866,
serialized_end=4592,
)
_sym_db.RegisterEnumDescriptor(_PROTOCOLMESSAGE_TYPE)
_ERRORCODE = _descriptor.Descriptor(
name='ErrorCode',
full_name='ErrorCode',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
_ERRORCODE_ENUM,
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=45,
serialized_end=2702,
)
_PROTOCOLMESSAGE = _descriptor.Descriptor(
name='ProtocolMessage',
full_name='ProtocolMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='type', full_name='ProtocolMessage.type', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='identifier', full_name='ProtocolMessage.identifier', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='authenticationToken', full_name='ProtocolMessage.authenticationToken', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='errorCode', full_name='ProtocolMessage.errorCode', index=3,
number=4, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='timestamp', full_name='ProtocolMessage.timestamp', index=4,
number=5, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
_PROTOCOLMESSAGE_TYPE,
],
serialized_options=None,
is_extendable=True,
syntax='proto2',
extension_ranges=[(6, 536870912), ],
oneofs=[
],
serialized_start=2705,
serialized_end=4602,
)
_ERRORCODE_ENUM.containing_type = _ERRORCODE
_PROTOCOLMESSAGE.fields_by_name['type'].enum_type = _PROTOCOLMESSAGE_TYPE
_PROTOCOLMESSAGE.fields_by_name['errorCode'].enum_type = _ERRORCODE_ENUM
_PROTOCOLMESSAGE_TYPE.containing_type = _PROTOCOLMESSAGE
DESCRIPTOR.message_types_by_name['ErrorCode'] = _ERRORCODE
DESCRIPTOR.message_types_by_name['ProtocolMessage'] = _PROTOCOLMESSAGE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ErrorCode = _reflection.GeneratedProtocolMessageType('ErrorCode', (_message.Message,), {
'DESCRIPTOR' : _ERRORCODE,
'__module__' : 'pyatv.mrp.protobuf.ProtocolMessage_pb2'
# @@protoc_insertion_point(class_scope:ErrorCode)
})
_sym_db.RegisterMessage(ErrorCode)
ProtocolMessage = _reflection.GeneratedProtocolMessageType('ProtocolMessage', (_message.Message,), {
'DESCRIPTOR' : _PROTOCOLMESSAGE,
'__module__' : 'pyatv.mrp.protobuf.ProtocolMessage_pb2'
# @@protoc_insertion_point(class_scope:ProtocolMessage)
})
_sym_db.RegisterMessage(ProtocolMessage)
# @@protoc_insertion_point(module_scope)
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2005-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#pragma once
#include <map>
#include <string>
class CProfileManager;
// static class for path translation from our special:// URLs.
/* paths are as follows:
special://xbmc/ - the main XBMC folder (i.e. where the app resides).
special://home/ - a writeable version of the main XBMC folder
Linux: ~/.kodi/
OS X: ~/Library/Application Support/Kodi/
Win32: ~/Application Data/XBMC/
special://envhome/ - on posix systems this will be equal to the $HOME
special://userhome/ - a writable version of the user home directory
Linux, OS X: ~/.kodi
Win32: home directory of user
special://masterprofile/ - the master users userdata folder - usually special://home/userdata
Linux: ~/.kodi/userdata/
OS X: ~/Library/Application Support/Kodi/UserData/
Win32: ~/Application Data/XBMC/UserData/
special://profile/ - the current users userdata folder - usually special://masterprofile/profiles/<current_profile>
Linux: ~/.kodi/userdata/profiles/<current_profile>
OS X: ~/Library/Application Support/Kodi/UserData/profiles/<current_profile>
Win32: ~/Application Data/XBMC/UserData/profiles/<current_profile>
special://temp/ - the temporary directory.
Linux: ~/.kodi/temp
OS X: ~/
Win32: ~/Application Data/XBMC/cache
*/
class CURL;
class CSpecialProtocol
{
public:
static void RegisterProfileManager(const CProfileManager &profileManager);
static void UnregisterProfileManager();
static void SetProfilePath(const std::string &path);
static void SetXBMCPath(const std::string &path);
static void SetXBMCBinPath(const std::string &path);
static void SetXBMCBinAddonPath(const std::string &path);
static void SetXBMCAltBinAddonPath(const std::string &path);
static void SetXBMCFrameworksPath(const std::string &path);
static void SetHomePath(const std::string &path);
static void SetUserHomePath(const std::string &path);
static void SetEnvHomePath(const std::string &path);
static void SetMasterProfilePath(const std::string &path);
static void SetTempPath(const std::string &path);
static void SetLogPath(const std::string &dir);
static bool ComparePath(const std::string &path1, const std::string &path2);
static void LogPaths();
static std::string TranslatePath(const std::string &path);
static std::string TranslatePath(const CURL &url);
static std::string TranslatePathConvertCase(const std::string& path);
private:
static const CProfileManager *m_profileManager;
static void SetPath(const std::string &key, const std::string &path);
static std::string GetPath(const std::string &key);
static std::map<std::string, std::string> m_pathMap;
};
#ifdef TARGET_WINDOWS
#define PATH_SEPARATOR_CHAR '\\'
#define PATH_SEPARATOR_STRING "\\"
#else
#define PATH_SEPARATOR_CHAR '/'
#define PATH_SEPARATOR_STRING "/"
#endif
|
{
"pile_set_name": "Github"
}
|
using System;
using UIKit;
namespace NavigationBar
{
/// <summary>
/// UINavigationController subclass used for targeting appearance proxy changes in the Custom Back Button example.
/// </summary>
public partial class CustomBackButtonNavController : UINavigationController
{
public CustomBackButtonNavController(IntPtr handle) : base(handle) { }
}
}
|
{
"pile_set_name": "Github"
}
|
{
"type": "statement",
"variant": "list",
"statement": [
{
"type": "statement",
"variant": "pragma",
"target": {
"type": "identifier",
"variant": "pragma",
"name": "integrity_check"
},
"args": {
"type": "expression",
"variant": "list",
"expression": null
}
},
{
"type": "statement",
"variant": "select",
"result": [
{
"type": "function",
"name": {
"type": "identifier",
"variant": "function",
"name": "count"
},
"args": {
"type": "identifier",
"variant": "star",
"name": "*"
}
},
{
"type": "function",
"name": {
"type": "identifier",
"variant": "function",
"name": "md5sum"
},
"args": {
"type": "expression",
"variant": "list",
"expression": [
{
"type": "identifier",
"variant": "column",
"name": "a"
}
]
}
},
{
"type": "function",
"name": {
"type": "identifier",
"variant": "function",
"name": "md5sum"
},
"args": {
"type": "expression",
"variant": "list",
"expression": [
{
"type": "identifier",
"variant": "column",
"name": "b"
}
]
}
},
{
"type": "function",
"name": {
"type": "identifier",
"variant": "function",
"name": "md5sum"
},
"args": {
"type": "expression",
"variant": "list",
"expression": [
{
"type": "identifier",
"variant": "column",
"name": "c"
}
]
}
}
],
"from": {
"type": "identifier",
"variant": "table",
"name": "abc"
}
},
{
"type": "statement",
"variant": "insert",
"action": "insert",
"into": {
"type": "identifier",
"variant": "table",
"name": "abc"
},
"result": {
"type": "statement",
"variant": "select",
"result": [
{
"type": "identifier",
"variant": "star",
"name": "*"
}
],
"from": {
"type": "identifier",
"variant": "table",
"name": "abc"
}
}
},
{
"type": "statement",
"variant": "insert",
"action": "insert",
"into": {
"type": "identifier",
"variant": "table",
"name": "abc"
},
"result": {
"type": "statement",
"variant": "select",
"result": [
{
"type": "identifier",
"variant": "star",
"name": "*"
}
],
"from": {
"type": "identifier",
"variant": "table",
"name": "abc"
}
}
},
{
"type": "statement",
"variant": "insert",
"action": "insert",
"into": {
"type": "identifier",
"variant": "table",
"name": "abc"
},
"result": {
"type": "statement",
"variant": "select",
"result": [
{
"type": "identifier",
"variant": "star",
"name": "*"
}
],
"from": {
"type": "identifier",
"variant": "table",
"name": "abc"
}
}
},
{
"type": "statement",
"variant": "insert",
"action": "insert",
"into": {
"type": "identifier",
"variant": "table",
"name": "abc"
},
"result": {
"type": "statement",
"variant": "select",
"result": [
{
"type": "identifier",
"variant": "star",
"name": "*"
}
],
"from": {
"type": "identifier",
"variant": "table",
"name": "abc"
}
}
},
{
"type": "statement",
"variant": "insert",
"action": "insert",
"into": {
"type": "identifier",
"variant": "table",
"name": "abc"
},
"result": {
"type": "statement",
"variant": "select",
"result": [
{
"type": "identifier",
"variant": "star",
"name": "*"
}
],
"from": {
"type": "identifier",
"variant": "table",
"name": "abc"
}
}
}
]
}
|
{
"pile_set_name": "Github"
}
|
ALTER TABLE questions ADD COLUMN IF NOT EXISTS workspace_home text;
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2013 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
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mdtp_time_picker_dialog"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:background="@color/mdtp_background_color"
android:focusable="true" >
<com.wdullaer.materialdatetimepicker.time.RadialPickerLayout
android:id="@+id/mdtp_time_picker"
android:layout_width="@dimen/mdtp_picker_dimen"
android:layout_height="@dimen/mdtp_time_picker_height"
android:layout_gravity="center"
android:focusable="true"
android:focusableInTouchMode="true"
android:background="@color/mdtp_circle_background" />
<LinearLayout
android:layout_height="@dimen/mdtp_time_picker_height"
android:layout_width="wrap_content"
android:orientation="vertical"
android:background="@android:color/transparent">
<include layout="@layout/mdtp_time_title_view" />
<FrameLayout
android:id="@+id/mdtp_time_display_background"
android:layout_width="@dimen/mdtp_left_side_width"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/mdtp_accent_color" >
<include
layout="@layout/mdtp_time_header_label"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
</FrameLayout>
<include layout="@layout/mdtp_done_button" />
</LinearLayout>
</LinearLayout>
|
{
"pile_set_name": "Github"
}
|
@charset "UTF-8";
/// Checks if a list contains a value(s).
///
/// @access private
///
/// @param {List} $list
/// The list to check against.
///
/// @param {List} $values
/// A single value or list of values to check for.
///
/// @example scss - Usage
/// contains($list, $value)
///
/// @return {Bool}
@function contains($list, $values...) {
@each $value in $values {
@if type-of(index($list, $value)) != "number" {
@return false;
}
}
@return true;
}
|
{
"pile_set_name": "Github"
}
|
import crypto from 'crypto'
import { dbDriver, SessionCollection } from '@lib'
const singleton = Symbol()
export class SessionStore {
public static get instance(): SessionStore {
/* istanbul ignore next */
if (!this[singleton]) this[singleton] = new SessionStore()
return this[singleton]
}
private _sessionId: string = null
private constructor() {}
public get sessionId() {
return this._sessionId
}
public async newSession() {
this._sessionId = crypto.randomBytes(4).toString('hex')
const now = new Date().getTime()
const session: SessionCollection = {
sessionId: this.sessionId,
startTime: now,
lastTime: now,
}
await dbDriver.session.save(session)
}
public async loadSession() {
const sessions = await dbDriver.session
.find({})
.sort({ lastTime: -1 })
.limit(1)
.toArray()
if (!sessions || !sessions.length) return this.newSession()
const [session] = sessions
this._sessionId = session.sessionId
await dbDriver.session.updateOne({ sessionId: session.sessionId }, { $set: { lastTime: new Date().getTime() } })
}
}
|
{
"pile_set_name": "Github"
}
|
# -*- encoding : utf-8 -*-
require 'integration/shared'
describe GitStats::GitData::Repo do
include_context "shared"
it 'should gather all authors' do
repo.authors.should =~ expected_authors
end
it 'should calculate correct commits period' do
repo.commits_period.should == [DateTime.parse('2012-10-19 10:44:34 +0200'), DateTime.parse('2012-10-26 17:05:25 +0200')]
end
it 'should gather all commits sorted by date' do
repo.commits.map(&:sha).should =~ %w(
2c11f5e5224dd7d2fab27de0fca2a9a1d0ca4038
4e7d0e9e58e27e33d47f94faf4079a49a75931da
81e8bef75eaa93d772f2ce11d2a266ada1292741
872955c3a6a4be4d7ae9b2dd4bea659979f0b457
ab47ef832c59837afcb626bfe22f0b8f0dc3717e
b3b4f819041eb66922abe79ee2513d5ddfb64691
b621a5df78e2953a040128191e47a24be9514b5c
c87ecf9c0bbdca29d73def8ed442cebf48178d92
d60b5eccf4513621bdbd65f408a0d28ff6fa9f5b
fd66657521139b1af6fde2927c4a383ecd6508fa
)
end
it 'should return project name from dir' do
repo.project_name.should == 'test_repo'
end
it 'should return project version as last commit hash' do
repo.project_version.should == '872955c3a6a4be4d7ae9b2dd4bea659979f0b457'
end
it 'should count files in repo' do
repo.files_count.should == 6
end
it 'should count files by date' do
repo.files_count_by_date.keys == Hash[commit_dates_with_empty.zip [1, 2, 2, 3, 3, 4, 5, 5, 6, 6]]
end
it 'should count lines by date' do
repo.files_count_by_date.values == Hash[commit_dates_with_empty.zip [1, 2, 2, 3, 3, 4, 5, 5, 6, 6]]
end
it 'should count all lines in repo' do
repo.lines_count.should == 1114
end
it 'should count files by extension in repo' do
repo.files_by_extension_count.should == {'.haml' => 1, '.txt' => 3, '.rb' => 2}
end
it 'should count lines by extension in repo' do
repo.lines_by_extension.should == {'.haml' => 100, '.txt' => 1008, '.rb' => 6}
end
it 'should count commits_count_by_author' do
repo.commits_count_by_author.keys.should == expected_authors
repo.commits_count_by_author.values.should == [8, 2]
end
it 'should count lines_added_by_author' do
repo.insertions_by_author.keys.should == expected_authors
repo.insertions_by_author.values.should == [1021, 103]
end
it 'should count lines_deleted_by_author' do
repo.deletions_by_author.keys.should == expected_authors
repo.deletions_by_author.values.should == [10, 0]
end
end
|
{
"pile_set_name": "Github"
}
|
namespace ClassLib007
{
public class Class022
{
public static string Property => "ClassLib007";
}
}
|
{
"pile_set_name": "Github"
}
|
import schnetpack.atomistic.output_modules
import torch
import torch.nn.functional as F
from torch.optim import Adam
import schnetpack as spk
import schnetpack.representation as rep
from schnetpack.datasets import *
# load qm9 dataset and download if necessary
data = QM9("qm9.db", collect_triples=True)
# split in train and val
train, val, test = data.create_splits(100000, 10000)
loader = spk.data.AtomsLoader(train, batch_size=100, num_workers=4)
val_loader = spk.data.AtomsLoader(val)
# create model
reps = rep.BehlerSFBlock()
output = schnetpack.atomistic.ElementalAtomwise(reps.n_symfuncs)
model = schnetpack.atomistic.AtomisticModel(reps, output)
# filter for trainable parameters (https://github.com/pytorch/pytorch/issues/679)
trainable_params = filter(lambda p: p.requires_grad, model.parameters())
# create trainer
opt = Adam(trainable_params, lr=1e-4)
loss = lambda b, p: F.mse_loss(p["y"], b[QM9.U0])
trainer = spk.train.Trainer("wacsf/", model, loss, opt, loader, val_loader)
# start training
trainer.train(torch.device("cpu"))
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div { position: absolute; height: 10px; width: 10px; }
</style>
</head>
<body onload="document.getElementById('c').style.counterIncrement = 'z';">
<div style="column-count: 2;"><div id="c" style="white-space: pre;">
<div>
<div></div></div></div></div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
:github_url: hide
.. Generated automatically by doc/tools/makerst.py in Godot's source tree.
.. DO NOT EDIT THIS FILE, but the RootMotionView.xml source instead.
.. The source is found in doc/classes or modules/<name>/doc_classes.
.. _class_RootMotionView:
RootMotionView
==============
**Inherits:** :ref:`VisualInstance<class_VisualInstance>` **<** :ref:`Spatial<class_Spatial>` **<** :ref:`Node<class_Node>` **<** :ref:`Object<class_Object>`
Properties
----------
+---------------------------------+---------------------------------------------------------------------+
| :ref:`NodePath<class_NodePath>` | :ref:`animation_path<class_RootMotionView_property_animation_path>` |
+---------------------------------+---------------------------------------------------------------------+
| :ref:`float<class_float>` | :ref:`cell_size<class_RootMotionView_property_cell_size>` |
+---------------------------------+---------------------------------------------------------------------+
| :ref:`Color<class_Color>` | :ref:`color<class_RootMotionView_property_color>` |
+---------------------------------+---------------------------------------------------------------------+
| :ref:`float<class_float>` | :ref:`radius<class_RootMotionView_property_radius>` |
+---------------------------------+---------------------------------------------------------------------+
| :ref:`bool<class_bool>` | :ref:`zero_y<class_RootMotionView_property_zero_y>` |
+---------------------------------+---------------------------------------------------------------------+
Property Descriptions
---------------------
.. _class_RootMotionView_property_animation_path:
- :ref:`NodePath<class_NodePath>` **animation_path**
+----------+---------------------------+
| *Setter* | set_animation_path(value) |
+----------+---------------------------+
| *Getter* | get_animation_path() |
+----------+---------------------------+
----
.. _class_RootMotionView_property_cell_size:
- :ref:`float<class_float>` **cell_size**
+----------+----------------------+
| *Setter* | set_cell_size(value) |
+----------+----------------------+
| *Getter* | get_cell_size() |
+----------+----------------------+
----
.. _class_RootMotionView_property_color:
- :ref:`Color<class_Color>` **color**
+----------+------------------+
| *Setter* | set_color(value) |
+----------+------------------+
| *Getter* | get_color() |
+----------+------------------+
----
.. _class_RootMotionView_property_radius:
- :ref:`float<class_float>` **radius**
+----------+-------------------+
| *Setter* | set_radius(value) |
+----------+-------------------+
| *Getter* | get_radius() |
+----------+-------------------+
----
.. _class_RootMotionView_property_zero_y:
- :ref:`bool<class_bool>` **zero_y**
+----------+-------------------+
| *Setter* | set_zero_y(value) |
+----------+-------------------+
| *Getter* | get_zero_y() |
+----------+-------------------+
|
{
"pile_set_name": "Github"
}
|
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use crate::err::{AnkiError, Result, SyncErrorKind};
use crate::media::changetracker::ChangeTracker;
use crate::media::database::{MediaDatabaseContext, MediaDatabaseMetadata, MediaEntry};
use crate::media::files::{
add_file_from_ankiweb, data_for_file, mtime_as_i64, normalize_filename, AddedFile,
};
use crate::media::MediaManager;
use crate::{sync::Timeouts, version};
use bytes::Bytes;
use reqwest::{multipart, Client, Response};
use serde_derive::{Deserialize, Serialize};
use serde_tuple::Serialize_tuple;
use slog::{debug, Logger};
use std::borrow::Cow;
use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::Path;
use std::{io, time};
use time::Duration;
use version::sync_client_version;
static SYNC_MAX_FILES: usize = 25;
static SYNC_MAX_BYTES: usize = (2.5 * 1024.0 * 1024.0) as usize;
static SYNC_SINGLE_FILE_MAX_BYTES: usize = 100 * 1024 * 1024;
#[derive(Debug, Default, Clone, Copy)]
pub struct MediaSyncProgress {
pub checked: usize,
pub downloaded_files: usize,
pub downloaded_deletions: usize,
pub uploaded_files: usize,
pub uploaded_deletions: usize,
}
pub struct MediaSyncer<'a, P>
where
P: FnMut(MediaSyncProgress) -> bool,
{
mgr: &'a MediaManager,
ctx: MediaDatabaseContext<'a>,
skey: Option<String>,
client: Client,
progress_cb: P,
progress: MediaSyncProgress,
endpoint: String,
log: Logger,
}
#[derive(Debug, Deserialize)]
struct SyncBeginResult {
data: Option<SyncBeginResponse>,
err: String,
}
#[derive(Debug, Deserialize)]
struct SyncBeginResponse {
#[serde(rename = "sk")]
sync_key: String,
usn: i32,
}
#[derive(Debug, Clone, Copy)]
enum LocalState {
NotInDB,
InDBNotPending,
InDBAndPending,
}
#[derive(PartialEq, Debug)]
enum RequiredChange {
// none also covers the case where we'll later upload
None,
Download,
Delete,
RemovePending,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct RecordBatchRequest {
last_usn: i32,
}
#[derive(Debug, Deserialize)]
struct RecordBatchResult {
data: Option<Vec<ServerMediaRecord>>,
err: String,
}
#[derive(Debug, Deserialize)]
struct ServerMediaRecord {
fname: String,
usn: i32,
sha1: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct ZipRequest<'a> {
files: &'a [&'a String],
}
#[derive(Serialize_tuple)]
struct UploadEntry<'a> {
fname: &'a str,
in_zip_name: Option<String>,
}
#[derive(Deserialize, Debug)]
struct UploadResult {
data: Option<UploadReply>,
err: String,
}
#[derive(Deserialize, Debug)]
struct UploadReply {
processed: usize,
current_usn: i32,
}
#[derive(Serialize)]
struct FinalizeRequest {
local: u32,
}
#[derive(Debug, Deserialize)]
struct FinalizeResponse {
data: Option<String>,
err: String,
}
fn media_sync_endpoint(host_number: u32) -> String {
if let Ok(endpoint) = std::env::var("SYNC_ENDPOINT_MEDIA") {
endpoint
} else {
let suffix = if host_number > 0 {
format!("{}", host_number)
} else {
"".to_string()
};
format!("https://sync{}.ankiweb.net/msync/", suffix)
}
}
impl<P> MediaSyncer<'_, P>
where
P: FnMut(MediaSyncProgress) -> bool,
{
pub fn new(
mgr: &MediaManager,
progress_cb: P,
host_number: u32,
log: Logger,
) -> MediaSyncer<'_, P> {
let timeouts = Timeouts::new();
let client = Client::builder()
.connect_timeout(Duration::from_secs(timeouts.connect_secs))
.timeout(Duration::from_secs(timeouts.request_secs))
.io_timeout(Duration::from_secs(timeouts.io_secs))
.build()
.unwrap();
let endpoint = media_sync_endpoint(host_number);
let ctx = mgr.dbctx();
MediaSyncer {
mgr,
ctx,
skey: None,
client,
progress_cb,
progress: Default::default(),
endpoint,
log,
}
}
fn skey(&self) -> &str {
self.skey.as_ref().unwrap()
}
pub async fn sync(&mut self, hkey: &str) -> Result<()> {
self.sync_inner(hkey).await.map_err(|e| {
debug!(self.log, "sync error: {:?}", e);
e
})
}
#[allow(clippy::useless_let_if_seq)]
async fn sync_inner(&mut self, hkey: &str) -> Result<()> {
self.register_changes()?;
let meta = self.ctx.get_meta()?;
let client_usn = meta.last_sync_usn;
debug!(self.log, "begin media sync");
let (sync_key, server_usn) = self.sync_begin(hkey).await?;
self.skey = Some(sync_key);
debug!(self.log, "server usn was {}", server_usn);
let mut actions_performed = false;
// need to fetch changes from server?
if client_usn != server_usn {
debug!(
self.log,
"differs from local usn {}, fetching changes", client_usn
);
self.fetch_changes(meta).await?;
actions_performed = true;
}
// need to send changes to server?
let changes_pending = !self.ctx.get_pending_uploads(1)?.is_empty();
if changes_pending {
self.send_changes().await?;
actions_performed = true;
}
if actions_performed {
self.finalize_sync().await?;
}
self.fire_progress_cb()?;
debug!(self.log, "media sync complete");
Ok(())
}
/// Make sure media DB is up to date.
fn register_changes(&mut self) -> Result<()> {
// make borrow checker happy
let progress = &mut self.progress;
let progress_cb = &mut self.progress_cb;
let progress = |checked| {
progress.checked = checked;
(progress_cb)(*progress)
};
ChangeTracker::new(self.mgr.media_folder.as_path(), progress, &self.log)
.register_changes(&mut self.ctx)
}
async fn sync_begin(&self, hkey: &str) -> Result<(String, i32)> {
let url = format!("{}begin", self.endpoint);
let resp = self
.client
.get(&url)
.query(&[("k", hkey), ("v", &sync_client_version())])
.send()
.await?
.error_for_status()?;
let reply: SyncBeginResult = resp.json().await?;
if let Some(data) = reply.data {
Ok((data.sync_key, data.usn))
} else {
Err(AnkiError::server_message(reply.err))
}
}
async fn fetch_changes(&mut self, mut meta: MediaDatabaseMetadata) -> Result<()> {
let mut last_usn = meta.last_sync_usn;
loop {
debug!(
self.log,
"fetching record batch";
"start_usn"=>last_usn
);
let batch = self.fetch_record_batch(last_usn).await?;
if batch.is_empty() {
debug!(self.log, "empty batch, done");
break;
}
last_usn = batch.last().unwrap().usn;
self.progress.checked += batch.len();
self.fire_progress_cb()?;
let (to_download, to_delete, to_remove_pending) =
determine_required_changes(&mut self.ctx, &batch, &self.log)?;
// file removal
self.mgr.remove_files(&mut self.ctx, to_delete.as_slice())?;
self.progress.downloaded_deletions += to_delete.len();
self.fire_progress_cb()?;
// file download
let mut downloaded = vec![];
let mut dl_fnames = to_download.as_slice();
while !dl_fnames.is_empty() {
let batch: Vec<_> = dl_fnames
.iter()
.take(SYNC_MAX_FILES)
.map(ToOwned::to_owned)
.collect();
let zip_data = self.fetch_zip(batch.as_slice()).await?;
let download_batch = extract_into_media_folder(
self.mgr.media_folder.as_path(),
zip_data,
&self.log,
)?
.into_iter();
let len = download_batch.len();
dl_fnames = &dl_fnames[len..];
downloaded.extend(download_batch);
self.progress.downloaded_files += len;
self.fire_progress_cb()?;
}
// then update the DB
let dirmod = mtime_as_i64(&self.mgr.media_folder)?;
let log = &self.log;
self.ctx.transact(|ctx| {
record_clean(ctx, &to_remove_pending, log)?;
record_removals(ctx, &to_delete, log)?;
record_additions(ctx, downloaded, log)?;
// update usn
meta.last_sync_usn = last_usn;
meta.folder_mtime = dirmod;
ctx.set_meta(&meta)?;
Ok(())
})?;
}
Ok(())
}
async fn send_changes(&mut self) -> Result<()> {
loop {
let pending: Vec<MediaEntry> = self.ctx.get_pending_uploads(SYNC_MAX_FILES as u32)?;
if pending.is_empty() {
break;
}
let zip_data = zip_files(&mut self.ctx, &self.mgr.media_folder, &pending, &self.log)?;
if zip_data.is_none() {
self.progress.checked += pending.len();
self.fire_progress_cb()?;
// discard zip info and retry batch - not particularly efficient,
// but this is a corner case
continue;
}
let reply = self.send_zip_data(zip_data.unwrap()).await?;
let (processed_files, processed_deletions): (Vec<_>, Vec<_>) = pending
.iter()
.take(reply.processed)
.partition(|e| e.sha1.is_some());
self.progress.uploaded_files += processed_files.len();
self.progress.uploaded_deletions += processed_deletions.len();
self.fire_progress_cb()?;
let fnames: Vec<_> = processed_files
.iter()
.chain(processed_deletions.iter())
.map(|e| &e.fname)
.collect();
let fname_cnt = fnames.len() as i32;
let log = &self.log;
self.ctx.transact(|ctx| {
record_clean(ctx, fnames.as_slice(), log)?;
let mut meta = ctx.get_meta()?;
if meta.last_sync_usn + fname_cnt == reply.current_usn {
meta.last_sync_usn = reply.current_usn;
ctx.set_meta(&meta)?;
} else {
debug!(
log,
"server usn {} is not {}, skipping usn update",
reply.current_usn,
meta.last_sync_usn + fname_cnt
);
}
Ok(())
})?;
}
Ok(())
}
async fn finalize_sync(&mut self) -> Result<()> {
let url = format!("{}mediaSanity", self.endpoint);
let local = self.ctx.count()?;
let obj = FinalizeRequest { local };
let resp = ankiweb_json_request(&self.client, &url, &obj, self.skey(), false).await?;
let resp: FinalizeResponse = resp.json().await?;
if let Some(data) = resp.data {
if data == "OK" {
Ok(())
} else {
self.ctx.transact(|ctx| ctx.force_resync())?;
Err(AnkiError::SyncError {
info: "".into(),
kind: SyncErrorKind::ResyncRequired,
})
}
} else {
Err(AnkiError::server_message(resp.err))
}
}
fn fire_progress_cb(&mut self) -> Result<()> {
if (self.progress_cb)(self.progress) {
Ok(())
} else {
Err(AnkiError::Interrupted)
}
}
async fn fetch_record_batch(&self, last_usn: i32) -> Result<Vec<ServerMediaRecord>> {
let url = format!("{}mediaChanges", self.endpoint);
let req = RecordBatchRequest { last_usn };
let resp = ankiweb_json_request(&self.client, &url, &req, self.skey(), false).await?;
let res: RecordBatchResult = resp.json().await?;
if let Some(batch) = res.data {
Ok(batch)
} else {
Err(AnkiError::server_message(res.err))
}
}
async fn fetch_zip(&self, files: &[&String]) -> Result<Bytes> {
let url = format!("{}downloadFiles", self.endpoint);
debug!(self.log, "requesting files: {:?}", files);
let req = ZipRequest { files };
let resp = ankiweb_json_request(&self.client, &url, &req, self.skey(), true).await?;
resp.bytes().await.map_err(Into::into)
}
async fn send_zip_data(&self, data: Vec<u8>) -> Result<UploadReply> {
let url = format!("{}uploadChanges", self.endpoint);
let resp = ankiweb_bytes_request(&self.client, &url, data, self.skey(), true).await?;
let res: UploadResult = resp.json().await?;
if let Some(reply) = res.data {
Ok(reply)
} else {
Err(AnkiError::server_message(res.err))
}
}
}
fn determine_required_change(
local_sha1: &str,
remote_sha1: &str,
local_state: LocalState,
) -> RequiredChange {
use LocalState as L;
use RequiredChange as R;
match (local_sha1, remote_sha1, local_state) {
// both deleted, not in local DB
("", "", L::NotInDB) => R::None,
// both deleted, in local DB
("", "", _) => R::Delete,
// added on server, add even if local deletion pending
("", _, _) => R::Download,
// deleted on server but added locally; upload later
(_, "", L::InDBAndPending) => R::None,
// deleted on server and not pending sync
(_, "", _) => R::Delete,
// if pending but the same as server, don't need to upload
(lsum, rsum, L::InDBAndPending) if lsum == rsum => R::RemovePending,
(lsum, rsum, _) => {
if lsum == rsum {
// not pending and same as server, nothing to do
R::None
} else {
// differs from server, favour server
R::Download
}
}
}
}
/// Get a list of server filenames and the actions required on them.
/// Returns filenames in (to_download, to_delete).
fn determine_required_changes<'a>(
ctx: &mut MediaDatabaseContext,
records: &'a [ServerMediaRecord],
log: &Logger,
) -> Result<(Vec<&'a String>, Vec<&'a String>, Vec<&'a String>)> {
let mut to_download = vec![];
let mut to_delete = vec![];
let mut to_remove_pending = vec![];
for remote in records {
let (local_sha1, local_state) = match ctx.get_entry(&remote.fname)? {
Some(entry) => (
match entry.sha1 {
Some(arr) => hex::encode(arr),
None => "".to_string(),
},
if entry.sync_required {
LocalState::InDBAndPending
} else {
LocalState::InDBNotPending
},
),
None => ("".to_string(), LocalState::NotInDB),
};
let req_change = determine_required_change(&local_sha1, &remote.sha1, local_state);
debug!(
log,
"determine action";
"fname" => &remote.fname,
"lsha" => local_sha1.chars().take(8).collect::<String>(),
"rsha" => remote.sha1.chars().take(8).collect::<String>(),
"state" => ?local_state,
"action" => ?req_change
);
match req_change {
RequiredChange::Download => to_download.push(&remote.fname),
RequiredChange::Delete => to_delete.push(&remote.fname),
RequiredChange::RemovePending => to_remove_pending.push(&remote.fname),
RequiredChange::None => (),
};
}
Ok((to_download, to_delete, to_remove_pending))
}
async fn ankiweb_json_request<T>(
client: &Client,
url: &str,
json: &T,
skey: &str,
timeout_long: bool,
) -> Result<Response>
where
T: serde::Serialize,
{
let req_json = serde_json::to_string(json)?;
let part = multipart::Part::text(req_json);
ankiweb_request(client, url, part, skey, timeout_long).await
}
async fn ankiweb_bytes_request(
client: &Client,
url: &str,
bytes: Vec<u8>,
skey: &str,
timeout_long: bool,
) -> Result<Response> {
let part = multipart::Part::bytes(bytes);
ankiweb_request(client, url, part, skey, timeout_long).await
}
async fn ankiweb_request(
client: &Client,
url: &str,
data_part: multipart::Part,
skey: &str,
timeout_long: bool,
) -> Result<Response> {
let data_part = data_part.file_name("data");
let form = multipart::Form::new()
.part("data", data_part)
.text("sk", skey.to_string());
let mut req = client.post(url).multipart(form);
if timeout_long {
req = req.timeout(Duration::from_secs(60 * 60));
}
req.send().await?.error_for_status().map_err(Into::into)
}
fn extract_into_media_folder(
media_folder: &Path,
zip: Bytes,
log: &Logger,
) -> Result<Vec<AddedFile>> {
let reader = io::Cursor::new(zip);
let mut zip = zip::ZipArchive::new(reader)?;
let meta_file = zip.by_name("_meta")?;
let fmap: HashMap<String, String> = serde_json::from_reader(meta_file)?;
let mut output = Vec::with_capacity(fmap.len());
for i in 0..zip.len() {
let mut file = zip.by_index(i)?;
let name = file.name();
if name == "_meta" {
continue;
}
let real_name = fmap
.get(name)
.ok_or_else(|| AnkiError::sync_misc("malformed zip"))?;
let mut data = Vec::with_capacity(file.size() as usize);
file.read_to_end(&mut data)?;
let added = add_file_from_ankiweb(media_folder, real_name, &data, log)?;
output.push(added);
}
Ok(output)
}
fn record_removals(
ctx: &mut MediaDatabaseContext,
removals: &[&String],
log: &Logger,
) -> Result<()> {
for &fname in removals {
debug!(log, "mark removed"; "fname" => fname);
ctx.remove_entry(fname)?;
}
Ok(())
}
fn record_additions(
ctx: &mut MediaDatabaseContext,
additions: Vec<AddedFile>,
log: &Logger,
) -> Result<()> {
for file in additions {
if let Some(renamed) = file.renamed_from {
// the file AnkiWeb sent us wasn't normalized, so we need to record
// the old file name as a deletion
debug!(log, "marking non-normalized file as deleted: {}", renamed);
let mut entry = MediaEntry {
fname: renamed,
sha1: None,
mtime: 0,
sync_required: true,
};
ctx.set_entry(&entry)?;
// and upload the new filename to ankiweb
debug!(
log,
"marking renamed file as needing upload: {}", file.fname
);
entry = MediaEntry {
fname: file.fname.to_string(),
sha1: Some(file.sha1),
mtime: file.mtime,
sync_required: true,
};
ctx.set_entry(&entry)?;
} else {
// a normal addition
let entry = MediaEntry {
fname: file.fname.to_string(),
sha1: Some(file.sha1),
mtime: file.mtime,
sync_required: false,
};
debug!(log, "mark added";
"fname" => &entry.fname,
"sha1" => hex::encode(&entry.sha1.as_ref().unwrap()[0..4])
);
ctx.set_entry(&entry)?;
}
}
Ok(())
}
fn record_clean(ctx: &mut MediaDatabaseContext, clean: &[&String], log: &Logger) -> Result<()> {
for &fname in clean {
if let Some(mut entry) = ctx.get_entry(fname)? {
if entry.sync_required {
entry.sync_required = false;
debug!(log, "mark clean"; "fname"=>&entry.fname);
ctx.set_entry(&entry)?;
}
}
}
Ok(())
}
fn zip_files<'a>(
ctx: &mut MediaDatabaseContext,
media_folder: &Path,
files: &'a [MediaEntry],
log: &Logger,
) -> Result<Option<Vec<u8>>> {
let buf = vec![];
let mut invalid_entries = vec![];
let w = std::io::Cursor::new(buf);
let mut zip = zip::ZipWriter::new(w);
let options =
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
let mut accumulated_size = 0;
let mut entries = vec![];
for (idx, file) in files.iter().enumerate() {
if accumulated_size > SYNC_MAX_BYTES {
break;
}
#[cfg(target_vendor = "apple")]
{
use unicode_normalization::is_nfc;
if !is_nfc(&file.fname) {
// older Anki versions stored non-normalized filenames in the DB; clean them up
debug!(log, "clean up non-nfc entry"; "fname"=>&file.fname);
invalid_entries.push(&file.fname);
continue;
}
}
let file_data = if file.sha1.is_some() {
match data_for_file(media_folder, &file.fname) {
Ok(data) => data,
Err(e) => {
debug!(log, "error accessing {}: {}", &file.fname, e);
invalid_entries.push(&file.fname);
continue;
}
}
} else {
// uploading deletion
None
};
if let Some(data) = &file_data {
let normalized = normalize_filename(&file.fname);
if let Cow::Owned(o) = normalized {
debug!(log, "media check required: {} should be {}", &file.fname, o);
invalid_entries.push(&file.fname);
continue;
}
if data.is_empty() {
invalid_entries.push(&file.fname);
continue;
}
if data.len() > SYNC_SINGLE_FILE_MAX_BYTES {
invalid_entries.push(&file.fname);
continue;
}
accumulated_size += data.len();
zip.start_file(format!("{}", idx), options)?;
zip.write_all(data)?;
}
debug!(
log,
"will upload";
"fname"=>&file.fname,
"kind"=>if file_data.is_some() {
"addition "
} else {
"removal"
}
);
entries.push(UploadEntry {
fname: &file.fname,
in_zip_name: if file_data.is_some() {
Some(format!("{}", idx))
} else {
None
},
});
}
if !invalid_entries.is_empty() {
// clean up invalid entries; we'll build a new zip
ctx.transact(|ctx| {
for fname in invalid_entries {
ctx.remove_entry(fname)?;
}
Ok(())
})?;
return Ok(None);
}
let meta = serde_json::to_string(&entries)?;
zip.start_file("_meta", options)?;
zip.write_all(meta.as_bytes())?;
let w = zip.finish()?;
Ok(Some(w.into_inner()))
}
#[cfg(test)]
mod test {
use crate::err::Result;
use crate::media::sync::{
determine_required_change, LocalState, MediaSyncProgress, RequiredChange,
};
use crate::media::MediaManager;
use tempfile::tempdir;
use tokio::runtime::Runtime;
async fn test_sync(hkey: &str) -> Result<()> {
let dir = tempdir()?;
let media_dir = dir.path().join("media");
std::fs::create_dir(&media_dir)?;
let media_db = dir.path().join("media.db");
std::fs::write(media_dir.join("test.file").as_path(), "hello")?;
let progress = |progress: MediaSyncProgress| {
println!("got progress: {:?}", progress);
true
};
let log = crate::log::terminal();
let mgr = MediaManager::new(&media_dir, &media_db)?;
mgr.sync_media(progress, 0, hkey, log).await?;
Ok(())
}
#[test]
fn sync() {
let hkey = match std::env::var("TEST_HKEY") {
Ok(s) => s,
Err(_) => {
return;
}
};
let mut rt = Runtime::new().unwrap();
rt.block_on(test_sync(&hkey)).unwrap()
}
#[test]
fn required_change() {
use determine_required_change as d;
use LocalState as L;
use RequiredChange as R;
assert_eq!(d("", "", L::NotInDB), R::None);
assert_eq!(d("", "", L::InDBNotPending), R::Delete);
assert_eq!(d("", "1", L::InDBAndPending), R::Download);
assert_eq!(d("1", "", L::InDBAndPending), R::None);
assert_eq!(d("1", "", L::InDBNotPending), R::Delete);
assert_eq!(d("1", "1", L::InDBNotPending), R::None);
assert_eq!(d("1", "1", L::InDBAndPending), R::RemovePending);
assert_eq!(d("a", "b", L::InDBAndPending), R::Download);
assert_eq!(d("a", "b", L::InDBNotPending), R::Download);
}
}
|
{
"pile_set_name": "Github"
}
|
---
translateHelp: true
---
# @umijs/plugin-sass
启用 sass 编译支持。
## 启用方式
默认开启。
## 配置
### implementation
默认是 [Dart Sass](https://sass-lang.com/dart-sass)。
如果要切换到 [Node Sass](https://github.com/sass/node-sass),可安装 `node-sass` 依赖,然后配置,
```js
export default {
sass: {
implementation: require('node-sass'),
},
}
```
### sassOptions
* Type: `Object|Function`
传递给 [Dart Sass](https://github.com/sass/dart-sass#javascript-api) 或 [Node Sass](https://github.com/sass/node-sass/#options) 的配置项。
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env bash
set -e
__CrossDir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
__TIZEN_CROSSDIR="$__CrossDir/tizen"
if [[ -z "$ROOTFS_DIR" ]]; then
echo "ROOTFS_DIR is not defined."
exit 1;
fi
TIZEN_TMP_DIR=$ROOTFS_DIR/tizen_tmp
mkdir -p $TIZEN_TMP_DIR
# Download files
echo ">>Start downloading files"
VERBOSE=1 $__CrossDir/tizen-fetch.sh $TIZEN_TMP_DIR
echo "<<Finish downloading files"
echo ">>Start constructing Tizen rootfs"
TIZEN_RPM_FILES=`ls $TIZEN_TMP_DIR/*.rpm`
cd $ROOTFS_DIR
for f in $TIZEN_RPM_FILES; do
rpm2cpio $f | cpio -idm --quiet
done
echo "<<Finish constructing Tizen rootfs"
# Cleanup tmp
rm -rf $TIZEN_TMP_DIR
# Configure Tizen rootfs
echo ">>Start configuring Tizen rootfs"
ln -sfn asm-arm64 ./usr/include/asm
patch -p1 < $__TIZEN_CROSSDIR/tizen.patch
echo "<<Finish configuring Tizen rootfs"
|
{
"pile_set_name": "Github"
}
|
(***********************************************************************)
(* *)
(* OCaml *)
(* *)
(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 2002 Institut National de Recherche en Informatique et *)
(* en Automatique. All rights reserved. This file is distributed *)
(* under the terms of the GNU Library General Public License, with *)
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
open CamlinternalFormatBasics
open CamlinternalFormat
(* alias to avoid warning for ambiguity between
Pervasives.format6
and CamlinternalFormatBasics.format6
(the former is in fact an alias for the latter,
but the ambiguity warning doesn't care)
*)
type ('a, 'b, 'c, 'd, 'e, 'f) format6 =
('a, 'b, 'c, 'd, 'e, 'f) Pervasives.format6
(* The run-time library for scanners. *)
(* Scanning buffers. *)
module type SCANNING = sig
type in_channel;;
type scanbuf = in_channel;;
type file_name = string;;
val stdin : in_channel;;
(* The scanning buffer reading from [Pervasives.stdin].
[stdib] is equivalent to [Scanning.from_channel Pervasives.stdin]. *)
val stdib : in_channel;;
(* An alias for [Scanf.stdin], the scanning buffer reading from
[Pervasives.stdin]. *)
val next_char : scanbuf -> char;;
(* [Scanning.next_char ib] advance the scanning buffer for
one character.
If no more character can be read, sets a end of file condition and
returns '\000'. *)
val invalidate_current_char : scanbuf -> unit;;
(* [Scanning.invalidate_current_char ib] mark the current_char as already
scanned. *)
val peek_char : scanbuf -> char;;
(* [Scanning.peek_char ib] returns the current char available in
the buffer or reads one if necessary (when the current character is
already scanned).
If no character can be read, sets an end of file condition and
returns '\000'. *)
val checked_peek_char : scanbuf -> char;;
(* Same as above but always returns a valid char or fails:
instead of returning a null char when the reading method of the
input buffer has reached an end of file, the function raises exception
[End_of_file]. *)
val store_char : int -> scanbuf -> char -> int;;
(* [Scanning.store_char lim ib c] adds [c] to the token buffer
of the scanning buffer. It also advances the scanning buffer for one
character and returns [lim - 1], indicating the new limit
for the length of the current token. *)
val skip_char : int -> scanbuf -> int;;
(* [Scanning.skip_char lim ib] ignores the current character. *)
val ignore_char : int -> scanbuf -> int;;
(* [Scanning.ignore_char ib lim] ignores the current character and
decrements the limit. *)
val token : scanbuf -> string;;
(* [Scanning.token ib] returns the string stored into the token
buffer of the scanning buffer: it returns the token matched by the
format. *)
val reset_token : scanbuf -> unit;;
(* [Scanning.reset_token ib] resets the token buffer of
the given scanning buffer. *)
val char_count : scanbuf -> int;;
(* [Scanning.char_count ib] returns the number of characters
read so far from the given buffer. *)
val line_count : scanbuf -> int;;
(* [Scanning.line_count ib] returns the number of new line
characters read so far from the given buffer. *)
val token_count : scanbuf -> int;;
(* [Scanning.token_count ib] returns the number of tokens read
so far from [ib]. *)
val eof : scanbuf -> bool;;
(* [Scanning.eof ib] returns the end of input condition
of the given buffer. *)
val end_of_input : scanbuf -> bool;;
(* [Scanning.end_of_input ib] tests the end of input condition
of the given buffer (if no char has ever been read, an attempt to
read one is performed). *)
val beginning_of_input : scanbuf -> bool;;
(* [Scanning.beginning_of_input ib] tests the beginning of input
condition of the given buffer. *)
val name_of_input : scanbuf -> string;;
(* [Scanning.name_of_input ib] returns the name of the character
source for input buffer [ib]. *)
val open_in : file_name -> in_channel;;
val open_in_bin : file_name -> in_channel;;
val from_file : file_name -> in_channel;;
val from_file_bin : file_name -> in_channel;;
val from_string : string -> in_channel;;
val from_function : (unit -> char) -> in_channel;;
val from_channel : Pervasives.in_channel -> in_channel;;
val close_in : in_channel -> unit;;
end
;;
module Scanning : SCANNING = struct
(* The run-time library for scanf. *)
type in_channel_name =
| From_file of string * Pervasives.in_channel
| From_string
| From_function
| From_channel of Pervasives.in_channel
;;
type in_channel = {
mutable eof : bool;
mutable current_char : char;
mutable current_char_is_valid : bool;
mutable char_count : int;
mutable line_count : int;
mutable token_count : int;
mutable get_next_char : unit -> char;
tokbuf : Buffer.t;
input_name : in_channel_name;
}
;;
type scanbuf = in_channel;;
type file_name = string;;
let null_char = '\000';;
(* Reads a new character from input buffer. Next_char never fails,
even in case of end of input: it then simply sets the end of file
condition. *)
let next_char ib =
try
let c = ib.get_next_char () in
ib.current_char <- c;
ib.current_char_is_valid <- true;
ib.char_count <- succ ib.char_count;
if c = '\n' then ib.line_count <- succ ib.line_count;
c with
| End_of_file ->
let c = null_char in
ib.current_char <- c;
ib.current_char_is_valid <- false;
ib.eof <- true;
c
;;
let peek_char ib =
if ib.current_char_is_valid then ib.current_char else next_char ib;;
(* Returns a valid current char for the input buffer. In particular
no irrelevant null character (as set by [next_char] in case of end
of input) is returned, since [End_of_file] is raised when
[next_char] sets the end of file condition while trying to read a
new character. *)
let checked_peek_char ib =
let c = peek_char ib in
if ib.eof then raise End_of_file;
c
;;
let end_of_input ib =
ignore (peek_char ib);
ib.eof
;;
let eof ib = ib.eof;;
let beginning_of_input ib = ib.char_count = 0;;
let name_of_input ib =
match ib.input_name with
| From_file (fname, _ic) -> fname
| From_string -> "unnamed character string"
| From_function -> "unnamed function"
| From_channel _ic -> "unnamed pervasives input channel"
;;
let char_count ib =
if ib.current_char_is_valid then ib.char_count - 1 else ib.char_count
;;
let line_count ib = ib.line_count;;
let reset_token ib = Buffer.reset ib.tokbuf;;
let invalidate_current_char ib = ib.current_char_is_valid <- false;;
let token ib =
let tokbuf = ib.tokbuf in
let tok = Buffer.contents tokbuf in
Buffer.clear tokbuf;
ib.token_count <- succ ib.token_count;
tok
;;
let token_count ib = ib.token_count;;
let skip_char width ib =
invalidate_current_char ib;
width
;;
let ignore_char width ib = skip_char (width - 1) ib;;
let store_char width ib c =
Buffer.add_char ib.tokbuf c;
ignore_char width ib
;;
let default_token_buffer_size = 1024;;
let create iname next = {
eof = false;
current_char = null_char;
current_char_is_valid = false;
char_count = 0;
line_count = 0;
token_count = 0;
get_next_char = next;
tokbuf = Buffer.create default_token_buffer_size;
input_name = iname;
}
;;
let from_string s =
let i = ref 0 in
let len = String.length s in
let next () =
if !i >= len then raise End_of_file else
let c = s.[!i] in
incr i;
c in
create From_string next
;;
let from_function = create From_function;;
(* Scanning from an input channel. *)
(* Position of the problem:
We cannot prevent the scanning mechanism to use one lookahead character,
if needed by the semantics of the format string specifications (e.g. a
trailing 'skip space' specification in the format string); in this case,
the mandatory lookahead character is indeed read from the input and not
used to return the token read. It is thus mandatory to be able to store
an unused lookahead character somewhere to get it as the first character
of the next scan.
To circumvent this problem, all the scanning functions get a low level
input buffer argument where they store the lookahead character when
needed; additionally, the input buffer is the only source of character of
a scanner. The [scanbuf] input buffers are defined in module {!Scanning}.
Now we understand that it is extremely important that related successive
calls to scanners indeed read from the same input buffer. In effect, if a
scanner [scan1] is reading from [ib1] and stores an unused lookahead
character [c1] into its input buffer [ib1], then another scanner [scan2]
not reading from the same buffer [ib1] will miss the character [c],
seemingly vanished in the air from the point of view of [scan2].
This mechanism works perfectly to read from strings, from files, and from
functions, since in those cases, allocating two buffers reading from the
same source is unnatural.
Still, there is a difficulty in the case of scanning from an input
channel. In effect, when scanning from an input channel [ic], this channel
may not have been allocated from within this library. Hence, it may be
shared (two functions of the user's program may successively read from
[ic]). This is highly error prone since, one of the function may seek the
input channel, while the other function has still an unused lookahead
character in its input buffer. In conclusion, you should never mix direct
low level reading and high level scanning from the same input channel.
This phenomenon of reading mess is even worse when one defines more than
one scanning buffer reading from the same input channel
[ic]. Unfortunately, we have no simple way to get rid of this problem
(unless the basic input channel API is modified to offer a 'consider this
char as unread' procedure to keep back the unused lookahead character as
available in the input channel for further reading).
To prevent some of the confusion the scanning buffer allocation function
is a memo function that never allocates two different scanning buffers for
the same input channel. This way, the user can naively perform successive
call to [fscanf] below, without allocating a new scanning buffer at each
invocation and hence preserving the expected semantics.
As mentioned above, a more ambitious fix could be to change the input
channel API to allow arbitrary mixing of direct and formatted reading from
input channels. *)
(* Perform bufferized input to improve efficiency. *)
let file_buffer_size = ref 1024;;
(* The scanner closes the input channel at end of input. *)
let scan_close_at_end ic = close_in ic; raise End_of_file;;
(* The scanner does not close the input channel at end of input:
it just raises [End_of_file]. *)
let scan_raise_at_end _ic = raise End_of_file;;
let from_ic scan_close_ic iname ic =
let len = !file_buffer_size in
let buf = Bytes.create len in
let i = ref 0 in
let lim = ref 0 in
let eof = ref false in
let next () =
if !i < !lim then begin let c = Bytes.get buf !i in incr i; c end else
if !eof then raise End_of_file else begin
lim := input ic buf 0 len;
if !lim = 0 then begin eof := true; scan_close_ic ic end else begin
i := 1;
Bytes.get buf 0
end
end in
create iname next
;;
let from_ic_close_at_end = from_ic scan_close_at_end;;
(* The scanning buffer reading from [Pervasives.stdin].
One could try to define [stdib] as a scanning buffer reading a character
at a time (no bufferization at all), but unfortunately the top-level
interaction would be wrong. This is due to some kind of
'race condition' when reading from [Pervasives.stdin],
since the interactive compiler and [scanf] will simultaneously read the
material they need from [Pervasives.stdin]; then, confusion will result
from what should be read by the top-level and what should be read
by [scanf].
This is even more complicated by the one character lookahead that [scanf]
is sometimes obliged to maintain: the lookahead character will be
available for the next ([scanf]) entry, seemingly coming from nowhere.
Also no [End_of_file] is raised when reading from stdin: if not enough
characters have been read, we simply ask to read more. *)
let stdin =
from_ic scan_raise_at_end
(From_file ("-", Pervasives.stdin)) Pervasives.stdin
;;
let stdib = stdin;;
let open_in fname =
match fname with
| "-" -> stdin
| fname ->
let ic = open_in fname in
from_ic_close_at_end (From_file (fname, ic)) ic
;;
let open_in_bin fname =
match fname with
| "-" -> stdin
| fname ->
let ic = open_in_bin fname in
from_ic_close_at_end (From_file (fname, ic)) ic
;;
let from_file = open_in;;
let from_file_bin = open_in_bin;;
let memo_from_ic =
let memo = ref [] in
(fun scan_close_ic ic ->
try List.assq ic !memo with
| Not_found ->
let ib = from_ic scan_close_ic (From_channel ic) ic in
memo := (ic, ib) :: !memo;
ib)
;;
let from_channel = memo_from_ic scan_raise_at_end;;
let close_in ib =
match ib.input_name with
| From_file (_fname, ic) -> Pervasives.close_in ic
| From_string | From_function -> ()
| From_channel ic -> Pervasives.close_in ic
;;
end
;;
(* Formatted input functions. *)
type ('a, 'b, 'c, 'd) scanner =
('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> 'c
(* Reporting errors. *)
exception Scan_failure of string;;
let bad_input s = raise (Scan_failure s);;
let bad_input_escape c =
bad_input (Printf.sprintf "illegal escape character %C" c)
;;
let bad_token_length message =
bad_input
(Printf.sprintf
"scanning of %s failed: \
the specified length was too short for token" message)
;;
let bad_end_of_input message =
bad_input
(Printf.sprintf
"scanning of %s failed: \
premature end of file occurred before end of token" message)
let bad_float () =
bad_input "no dot or exponent part found in float token"
;;
let character_mismatch_err c ci =
Printf.sprintf "looking for %C, found %C" c ci
;;
let character_mismatch c ci =
bad_input (character_mismatch_err c ci)
let rec skip_whites ib =
let c = Scanning.peek_char ib in
if not (Scanning.eof ib) then begin
match c with
| ' ' | '\t' | '\n' | '\r' ->
Scanning.invalidate_current_char ib; skip_whites ib
| _ -> ()
end
(* Checking that [c] is indeed in the input, then skips it.
In this case, the character [c] has been explicitly specified in the
format as being mandatory in the input; hence we should fail with
End_of_file in case of end_of_input. (Remember that Scan_failure is raised
only when (we can prove by evidence) that the input does not match the
format string given. We must thus differentiate End_of_file as an error
due to lack of input, and Scan_failure which is due to provably wrong
input. I am not sure this is worth the burden: it is complex and somehow
subliminal; should be clearer to fail with Scan_failure "Not enough input
to complete scanning"!)
That's why, waiting for a better solution, we use checked_peek_char here.
We are also careful to treat "\r\n" in the input as an end of line marker:
it always matches a '\n' specification in the input format string. *)
let rec check_char ib c =
if c = ' ' then skip_whites ib else
let ci = Scanning.checked_peek_char ib in
if ci = c then Scanning.invalidate_current_char ib else
match ci with
| '\r' when c = '\n' ->
Scanning.invalidate_current_char ib; check_char ib '\n'
| _ -> character_mismatch c ci
(* Extracting tokens from the output token buffer. *)
let token_char ib = (Scanning.token ib).[0];;
let token_string = Scanning.token;;
let token_bool ib =
match Scanning.token ib with
| "true" -> true
| "false" -> false
| s -> bad_input (Printf.sprintf "invalid boolean %S" s)
;;
(* Extract an integer literal token.
Since the functions Pervasives.*int*_of_string do not accept a leading +,
we skip it if necessary. *)
let token_int_literal conv ib =
let tok =
match conv with
| 'd' | 'i' | 'u' -> Scanning.token ib
| 'o' -> "0o" ^ Scanning.token ib
| 'x' | 'X' -> "0x" ^ Scanning.token ib
| 'b' -> "0b" ^ Scanning.token ib
| _ -> assert false in
let l = String.length tok in
if l = 0 || tok.[0] <> '+' then tok else String.sub tok 1 (l - 1)
;;
(* All the functions that convert a string to a number raise the exception
Failure when the conversion is not possible.
This exception is then trapped in [kscanf]. *)
let token_int conv ib = int_of_string (token_int_literal conv ib);;
let token_float ib = float_of_string (Scanning.token ib);;
(* To scan native ints, int32 and int64 integers.
We cannot access to conversions to/from strings for those types,
Nativeint.of_string, Int32.of_string, and Int64.of_string,
since those modules are not available to [Scanf].
However, we can bind and use the corresponding primitives that are
available in the runtime. *)
external nativeint_of_string : string -> nativeint
= "caml_nativeint_of_string"
;;
external int32_of_string : string -> int32
= "caml_int32_of_string"
;;
external int64_of_string : string -> int64
= "caml_int64_of_string"
;;
let token_nativeint conv ib = nativeint_of_string (token_int_literal conv ib);;
let token_int32 conv ib = int32_of_string (token_int_literal conv ib);;
let token_int64 conv ib = int64_of_string (token_int_literal conv ib);;
(* Scanning numbers. *)
(* Digits scanning functions suppose that one character has been checked and
is available, since they return at end of file with the currently found
token selected.
Put it in another way, the digits scanning functions scan for a possibly
empty sequence of digits, (hence, a successful scanning from one of those
functions does not imply that the token is a well-formed number: to get a
true number, it is mandatory to check that at least one valid digit is
available before calling one of the digit scanning functions). *)
(* The decimal case is treated especially for optimization purposes. *)
let rec scan_decimal_digits width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| '0' .. '9' as c ->
let width = Scanning.store_char width ib c in
scan_decimal_digits width ib
| '_' ->
let width = Scanning.ignore_char width ib in
scan_decimal_digits width ib
| _ -> width
;;
let scan_decimal_digits_plus width ib =
if width = 0 then bad_token_length "decimal digits" else
let c = Scanning.checked_peek_char ib in
match c with
| '0' .. '9' ->
let width = Scanning.store_char width ib c in
scan_decimal_digits width ib
| c ->
bad_input (Printf.sprintf "character %C is not a decimal digit" c)
;;
let scan_digits_plus basis digitp width ib =
(* To scan numbers from other bases, we use a predicate argument to
scan_digits. *)
let rec scan_digits width =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| c when digitp c ->
let width = Scanning.store_char width ib c in
scan_digits width
| '_' ->
let width = Scanning.ignore_char width ib in
scan_digits width
| _ -> width in
(* Ensure we have got enough width left,
and read at list one digit. *)
if width = 0 then bad_token_length "digits" else
let c = Scanning.checked_peek_char ib in
if digitp c then
let width = Scanning.store_char width ib c in
scan_digits width
else
bad_input (Printf.sprintf "character %C is not a valid %s digit" c basis)
;;
let is_binary_digit = function
| '0' .. '1' -> true
| _ -> false
;;
let scan_binary_int = scan_digits_plus "binary" is_binary_digit;;
let is_octal_digit = function
| '0' .. '7' -> true
| _ -> false
;;
let scan_octal_int = scan_digits_plus "octal" is_octal_digit;;
let is_hexa_digit = function
| '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> true
| _ -> false
;;
let scan_hexadecimal_int = scan_digits_plus "hexadecimal" is_hexa_digit;;
(* Scan a decimal integer. *)
let scan_unsigned_decimal_int = scan_decimal_digits_plus;;
let scan_sign width ib =
let c = Scanning.checked_peek_char ib in
match c with
| '+' -> Scanning.store_char width ib c
| '-' -> Scanning.store_char width ib c
| _ -> width
;;
let scan_optionally_signed_decimal_int width ib =
let width = scan_sign width ib in
scan_unsigned_decimal_int width ib
;;
(* Scan an unsigned integer that could be given in any (common) basis.
If digits are prefixed by one of 0x, 0X, 0o, or 0b, the number is
assumed to be written respectively in hexadecimal, hexadecimal,
octal, or binary. *)
let scan_unsigned_int width ib =
match Scanning.checked_peek_char ib with
| '0' as c ->
let width = Scanning.store_char width ib c in
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
begin match c with
| 'x' | 'X' -> scan_hexadecimal_int (Scanning.store_char width ib c) ib
| 'o' -> scan_octal_int (Scanning.store_char width ib c) ib
| 'b' -> scan_binary_int (Scanning.store_char width ib c) ib
| _ -> scan_decimal_digits width ib end
| _ -> scan_unsigned_decimal_int width ib
;;
let scan_optionally_signed_int width ib =
let width = scan_sign width ib in
scan_unsigned_int width ib
;;
let scan_int_conv conv width ib =
match conv with
| 'b' -> scan_binary_int width ib
| 'd' -> scan_optionally_signed_decimal_int width ib
| 'i' -> scan_optionally_signed_int width ib
| 'o' -> scan_octal_int width ib
| 'u' -> scan_unsigned_decimal_int width ib
| 'x' | 'X' -> scan_hexadecimal_int width ib
| _ -> assert false
;;
(* Scanning floating point numbers. *)
(* Fractional part is optional and can be reduced to 0 digits. *)
let scan_frac_part width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| '0' .. '9' as c ->
scan_decimal_digits (Scanning.store_char width ib c) ib
| _ -> width
;;
(* Exp part is optional and can be reduced to 0 digits. *)
let scan_exp_part width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| 'e' | 'E' as c ->
scan_optionally_signed_decimal_int (Scanning.store_char width ib c) ib
| _ -> width
;;
(* Scan the integer part of a floating point number, (not using the
OCaml lexical convention since the integer part can be empty):
an optional sign, followed by a possibly empty sequence of decimal
digits (e.g. -.1). *)
let scan_int_part width ib =
let width = scan_sign width ib in
scan_decimal_digits width ib
;;
(*
For the time being we have (as found in scanf.mli):
The field width is composed of an optional integer literal
indicating the maximal width of the token to read.
Unfortunately, the type-checker let the user write an optional precision,
since this is valid for printf format strings.
Thus, the next step for Scanf is to support a full width and precision
indication, more or less similar to the one for printf, possibly extended
to the specification of a [max, min] range for the width of the token read
for strings. Something like the following spec for scanf.mli:
The optional [width] is an integer indicating the maximal
width of the token read. For instance, [%6d] reads an integer,
having at most 6 characters.
The optional [precision] is a dot [.] followed by an integer:
- in the floating point number conversions ([%f], [%e], [%g], [%F], [%E],
and [%F] conversions, the [precision] indicates the maximum number of
digits that may follow the decimal point. For instance, [%.4f] reads a
[float] with at most 4 fractional digits,
- in the string conversions ([%s], [%S], [%\[ range \]]), and in the
integer number conversions ([%i], [%d], [%u], [%x], [%o], and their
[int32], [int64], and [native_int] correspondent), the [precision]
indicates the required minimum width of the token read,
- on all other conversions, the width and precision are meaningless and
ignored (FIXME: lead to a runtime error ? type checking error ?).
*)
let scan_float width precision ib =
let width = scan_int_part width ib in
if width = 0 then width, precision else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width, precision else
match c with
| '.' ->
let width = Scanning.store_char width ib c in
let precision = min width precision in
let width = width - (precision - scan_frac_part precision ib) in
scan_exp_part width ib, precision
| _ ->
scan_exp_part width ib, precision
;;
let scan_caml_float width precision ib =
let width = scan_optionally_signed_decimal_int width ib in
if width = 0 then bad_float () else
let c = Scanning.peek_char ib in
if Scanning.eof ib then bad_float () else
match c with
| '.' ->
let width = Scanning.store_char width ib c in
let precision = min width precision in
let width = width - (precision - scan_frac_part precision ib) in
scan_exp_part width ib
| 'e' | 'E' ->
scan_exp_part width ib
| _ -> bad_float ()
(* Scan a regular string:
stops when encountering a space, if no scanning indication has been given;
otherwise, stops when encountering the characters in the scanning
indication [stp].
It also stops at end of file or when the maximum number of characters has
been read.*)
let scan_string stp width ib =
let rec loop width =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match stp with
| Some c' when c = c' -> Scanning.skip_char width ib
| Some _ -> loop (Scanning.store_char width ib c)
| None ->
match c with
| ' ' | '\t' | '\n' | '\r' -> width
| _ -> loop (Scanning.store_char width ib c)
in
loop width
;;
(* Scan a char: peek strictly one character in the input, whatsoever. *)
let scan_char width ib =
(* The case width = 0 could not happen here, since it is tested before
calling scan_char, in the main scanning function.
if width = 0 then bad_token_length "a character" else *)
Scanning.store_char width ib (Scanning.checked_peek_char ib)
;;
let char_for_backslash = function
| 'n' -> '\010'
| 'r' -> '\013'
| 'b' -> '\008'
| 't' -> '\009'
| c -> c
;;
(* The integer value corresponding to the facial value of a valid
decimal digit character. *)
let decimal_value_of_char c = int_of_char c - int_of_char '0';;
let char_for_decimal_code c0 c1 c2 =
let c =
100 * decimal_value_of_char c0 +
10 * decimal_value_of_char c1 +
decimal_value_of_char c2 in
if c < 0 || c > 255 then
bad_input
(Printf.sprintf
"bad character decimal encoding \\%c%c%c" c0 c1 c2) else
char_of_int c
;;
(* The integer value corresponding to the facial value of a valid
hexadecimal digit character. *)
let hexadecimal_value_of_char c =
let d = int_of_char c in
(* Could also be:
if d <= int_of_char '9' then d - int_of_char '0' else
if d <= int_of_char 'F' then 10 + d - int_of_char 'A' else
if d <= int_of_char 'f' then 10 + d - int_of_char 'a' else assert false
*)
if d >= int_of_char 'a' then
d - 87 (* 10 + int_of_char c - int_of_char 'a' *) else
if d >= int_of_char 'A' then
d - 55 (* 10 + int_of_char c - int_of_char 'A' *) else
d - int_of_char '0'
;;
let char_for_hexadecimal_code c1 c2 =
let c =
16 * hexadecimal_value_of_char c1 +
hexadecimal_value_of_char c2 in
if c < 0 || c > 255 then
bad_input
(Printf.sprintf "bad character hexadecimal encoding \\%c%c" c1 c2) else
char_of_int c
;;
(* Called in particular when encountering '\\' as starter of a char.
Stops before the corresponding '\''. *)
let check_next_char message width ib =
if width = 0 then bad_token_length message else
let c = Scanning.peek_char ib in
if Scanning.eof ib then bad_end_of_input message else
c
;;
let check_next_char_for_char = check_next_char "a Char";;
let check_next_char_for_string = check_next_char "a String";;
let scan_backslash_char width ib =
match check_next_char_for_char width ib with
| '\\' | '\'' | '\"' | 'n' | 't' | 'b' | 'r' as c ->
Scanning.store_char width ib (char_for_backslash c)
| '0' .. '9' as c ->
let get_digit () =
let c = Scanning.next_char ib in
match c with
| '0' .. '9' as c -> c
| c -> bad_input_escape c in
let c0 = c in
let c1 = get_digit () in
let c2 = get_digit () in
Scanning.store_char (width - 2) ib (char_for_decimal_code c0 c1 c2)
| 'x' ->
let get_digit () =
let c = Scanning.next_char ib in
match c with
| '0' .. '9' | 'A' .. 'F' | 'a' .. 'f' as c -> c
| c -> bad_input_escape c in
let c1 = get_digit () in
let c2 = get_digit () in
Scanning.store_char (width - 2) ib (char_for_hexadecimal_code c1 c2)
| c ->
bad_input_escape c
;;
(* Scan a character (an OCaml token). *)
let scan_caml_char width ib =
let rec find_start width =
match Scanning.checked_peek_char ib with
| '\'' -> find_char (Scanning.ignore_char width ib)
| c -> character_mismatch '\'' c
and find_char width =
match check_next_char_for_char width ib with
| '\\' ->
find_stop (scan_backslash_char (Scanning.ignore_char width ib) ib)
| c ->
find_stop (Scanning.store_char width ib c)
and find_stop width =
match check_next_char_for_char width ib with
| '\'' -> Scanning.ignore_char width ib
| c -> character_mismatch '\'' c in
find_start width
;;
(* Scan a delimited string (an OCaml token). *)
let scan_caml_string width ib =
let rec find_start width =
match Scanning.checked_peek_char ib with
| '\"' -> find_stop (Scanning.ignore_char width ib)
| c -> character_mismatch '\"' c
and find_stop width =
match check_next_char_for_string width ib with
| '\"' -> Scanning.ignore_char width ib
| '\\' -> scan_backslash (Scanning.ignore_char width ib)
| c -> find_stop (Scanning.store_char width ib c)
and scan_backslash width =
match check_next_char_for_string width ib with
| '\r' -> skip_newline (Scanning.ignore_char width ib)
| '\n' -> skip_spaces (Scanning.ignore_char width ib)
| _ -> find_stop (scan_backslash_char width ib)
and skip_newline width =
match check_next_char_for_string width ib with
| '\n' -> skip_spaces (Scanning.ignore_char width ib)
| _ -> find_stop (Scanning.store_char width ib '\r')
and skip_spaces width =
match check_next_char_for_string width ib with
| ' ' -> skip_spaces (Scanning.ignore_char width ib)
| _ -> find_stop width in
find_start width
;;
(* Scan a boolean (an OCaml token). *)
let scan_bool ib =
let c = Scanning.checked_peek_char ib in
let m =
match c with
| 't' -> 4
| 'f' -> 5
| c ->
bad_input
(Printf.sprintf "the character %C cannot start a boolean" c) in
scan_string None m ib
(* Scan a string containing elements in char_set and terminated by scan_indic
if provided. *)
let scan_chars_in_char_set char_set scan_indic width ib =
let rec scan_chars i stp =
let c = Scanning.peek_char ib in
if i > 0 && not (Scanning.eof ib) && is_in_char_set char_set c &&
int_of_char c <> stp then
let _ = Scanning.store_char max_int ib c in
scan_chars (i - 1) stp;
in
match scan_indic with
| None -> scan_chars width (-1);
| Some c ->
scan_chars width (int_of_char c);
if not (Scanning.eof ib) then
let ci = Scanning.peek_char ib in
if c = ci then Scanning.invalidate_current_char ib
else character_mismatch c ci
(* The global error report function for [Scanf]. *)
let scanf_bad_input ib = function
| Scan_failure s | Failure s ->
let i = Scanning.char_count ib in
bad_input (Printf.sprintf "scanf: bad input at char number %i: %S" i s)
| x -> raise x
(* Get the content of a counter from an input buffer. *)
let get_counter ib counter = match counter with
| Line_counter -> Scanning.line_count ib
| Char_counter -> Scanning.char_count ib
| Token_counter -> Scanning.token_count ib
(* Compute the width of a padding option (see "%42{" and "%123("). *)
let width_of_pad_opt pad_opt = match pad_opt with
| None -> max_int
| Some width -> width
let stopper_of_formatting_lit fmting =
if fmting = Escaped_percent then '%', "" else
let str = string_of_formatting_lit fmting in
let stp = str.[1] in
let sub_str = String.sub str 2 (String.length str - 2) in
stp, sub_str
(******************************************************************************)
(* Readers managment *)
(* A call to take_format_readers on a format is evaluated into functions
taking readers as arguments and aggregate them into an heterogeneous list *)
(* When all readers are taken, finally pass the list of the readers to the
continuation k. *)
let rec take_format_readers : type a c d e f .
((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, e, f) fmt ->
d =
fun k fmt -> match fmt with
| Reader fmt_rest ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_format_readers new_k fmt_rest
| Char rest -> take_format_readers k rest
| Caml_char rest -> take_format_readers k rest
| String (_, rest) -> take_format_readers k rest
| Caml_string (_, rest) -> take_format_readers k rest
| Int (_, _, _, rest) -> take_format_readers k rest
| Int32 (_, _, _, rest) -> take_format_readers k rest
| Nativeint (_, _, _, rest) -> take_format_readers k rest
| Int64 (_, _, _, rest) -> take_format_readers k rest
| Float (_, _, _, rest) -> take_format_readers k rest
| Bool rest -> take_format_readers k rest
| Alpha rest -> take_format_readers k rest
| Theta rest -> take_format_readers k rest
| Flush rest -> take_format_readers k rest
| String_literal (_, rest) -> take_format_readers k rest
| Char_literal (_, rest) -> take_format_readers k rest
| Custom (_, _, rest) -> take_format_readers k rest
| Scan_char_set (_, _, rest) -> take_format_readers k rest
| Scan_get_counter (_, rest) -> take_format_readers k rest
| Scan_next_char rest -> take_format_readers k rest
| Formatting_lit (_, rest) -> take_format_readers k rest
| Formatting_gen (Open_tag (Format (fmt, _)), rest) -> take_format_readers k (concat_fmt fmt rest)
| Formatting_gen (Open_box (Format (fmt, _)), rest) -> take_format_readers k (concat_fmt fmt rest)
| Format_arg (_, _, rest) -> take_format_readers k rest
| Format_subst (_, fmtty, rest) ->
take_fmtty_format_readers k (erase_rel (symm fmtty)) rest
| Ignored_param (ign, rest) -> take_ignored_format_readers k ign rest
| End_of_format -> k Nil
(* Take readers associated to an fmtty coming from a Format_subst "%(...%)". *)
and take_fmtty_format_readers : type x y a c d e f .
((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, x, y) fmtty ->
(y, Scanning.in_channel, c, x, e, f) fmt -> d =
fun k fmtty fmt -> match fmtty with
| Reader_ty fmt_rest ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_fmtty_format_readers new_k fmt_rest fmt
| Ignored_reader_ty fmt_rest ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_fmtty_format_readers new_k fmt_rest fmt
| Char_ty rest -> take_fmtty_format_readers k rest fmt
| String_ty rest -> take_fmtty_format_readers k rest fmt
| Int_ty rest -> take_fmtty_format_readers k rest fmt
| Int32_ty rest -> take_fmtty_format_readers k rest fmt
| Nativeint_ty rest -> take_fmtty_format_readers k rest fmt
| Int64_ty rest -> take_fmtty_format_readers k rest fmt
| Float_ty rest -> take_fmtty_format_readers k rest fmt
| Bool_ty rest -> take_fmtty_format_readers k rest fmt
| Alpha_ty rest -> take_fmtty_format_readers k rest fmt
| Theta_ty rest -> take_fmtty_format_readers k rest fmt
| Any_ty rest -> take_fmtty_format_readers k rest fmt
| Format_arg_ty (_, rest) -> take_fmtty_format_readers k rest fmt
| End_of_fmtty -> take_format_readers k fmt
| Format_subst_ty (ty1, ty2, rest) ->
let ty = trans (symm ty1) ty2 in
take_fmtty_format_readers k (concat_fmtty ty rest) fmt
(* Take readers associated to an ignored parameter. *)
and take_ignored_format_readers : type x y a c d e f .
((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, x, y) ignored ->
(y, Scanning.in_channel, c, x, e, f) fmt -> d =
fun k ign fmt -> match ign with
| Ignored_reader ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_format_readers new_k fmt
| Ignored_char -> take_format_readers k fmt
| Ignored_caml_char -> take_format_readers k fmt
| Ignored_string _ -> take_format_readers k fmt
| Ignored_caml_string _ -> take_format_readers k fmt
| Ignored_int (_, _) -> take_format_readers k fmt
| Ignored_int32 (_, _) -> take_format_readers k fmt
| Ignored_nativeint (_, _) -> take_format_readers k fmt
| Ignored_int64 (_, _) -> take_format_readers k fmt
| Ignored_float (_, _) -> take_format_readers k fmt
| Ignored_bool -> take_format_readers k fmt
| Ignored_format_arg _ -> take_format_readers k fmt
| Ignored_format_subst (_, fmtty) -> take_fmtty_format_readers k fmtty fmt
| Ignored_scan_char_set _ -> take_format_readers k fmt
| Ignored_scan_get_counter _ -> take_format_readers k fmt
| Ignored_scan_next_char -> take_format_readers k fmt
(******************************************************************************)
(* Generic scanning *)
(* Make a generic scanning function. *)
(* Scan a stream according to a format and readers obtained by
take_format_readers, and aggegate scanned values into an
heterogeneous list. *)
(* Return the heterogeneous list of scanned values. *)
let rec make_scanf : type a c d e f .
Scanning.in_channel -> (a, Scanning.in_channel, c, d, e, f) fmt ->
(d, _) heter_list -> (a, f) heter_list =
fun ib fmt readers -> match fmt with
| Char rest ->
let _ = scan_char 0 ib in
let c = token_char ib in
Cons (c, make_scanf ib rest readers)
| Caml_char rest ->
let _ = scan_caml_char 0 ib in
let c = token_char ib in
Cons (c, make_scanf ib rest readers)
| String (pad, Formatting_lit (fmting_lit, rest)) ->
let stp, str = stopper_of_formatting_lit fmting_lit in
let scan width _ ib = scan_string (Some stp) width ib in
let str_rest = String_literal (str, rest) in
pad_prec_scanf ib str_rest readers pad No_precision scan token_string
| String (pad, Formatting_gen (Open_tag (Format (fmt', _)), rest)) ->
let scan width _ ib = scan_string (Some '{') width ib in
pad_prec_scanf ib (concat_fmt fmt' rest) readers pad No_precision scan token_string
| String (pad, Formatting_gen (Open_box (Format (fmt', _)), rest)) ->
let scan width _ ib = scan_string (Some '[') width ib in
pad_prec_scanf ib (concat_fmt fmt' rest) readers pad No_precision scan token_string
| String (pad, rest) ->
let scan width _ ib = scan_string None width ib in
pad_prec_scanf ib rest readers pad No_precision scan token_string
| Caml_string (pad, rest) ->
let scan width _ ib = scan_caml_string width ib in
pad_prec_scanf ib rest readers pad No_precision scan token_string
| Int (iconv, pad, prec, rest) ->
let c = char_of_iconv iconv in
let scan width _ ib = scan_int_conv c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_int c)
| Int32 (iconv, pad, prec, rest) ->
let c = char_of_iconv iconv in
let scan width _ ib = scan_int_conv c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_int32 c)
| Nativeint (iconv, pad, prec, rest) ->
let c = char_of_iconv iconv in
let scan width _ ib = scan_int_conv c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_nativeint c)
| Int64 (iconv, pad, prec, rest) ->
let c = char_of_iconv iconv in
let scan width _ ib = scan_int_conv c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_int64 c)
| Float (Float_F, pad, prec, rest) ->
pad_prec_scanf ib rest readers pad prec scan_caml_float token_float
| Float ((Float_f | Float_pf | Float_sf | Float_e | Float_pe | Float_se
| Float_E | Float_pE | Float_sE | Float_g | Float_pg | Float_sg
| Float_G | Float_pG | Float_sG), pad, prec, rest) ->
pad_prec_scanf ib rest readers pad prec scan_float token_float
| Bool rest ->
let _ = scan_bool ib in
let b = token_bool ib in
Cons (b, make_scanf ib rest readers)
| Alpha _ ->
invalid_arg "scanf: bad conversion \"%a\""
| Theta _ ->
invalid_arg "scanf: bad conversion \"%t\""
| Custom _ ->
invalid_arg "scanf: bad conversion \"%?\" (custom converter)"
| Reader fmt_rest ->
let Cons (reader, readers_rest) = readers in
let x = reader ib in
Cons (x, make_scanf ib fmt_rest readers_rest)
| Flush rest ->
if Scanning.end_of_input ib then make_scanf ib rest readers
else bad_input "end of input not found"
| String_literal (str, rest) ->
String.iter (check_char ib) str;
make_scanf ib rest readers
| Char_literal (chr, rest) ->
check_char ib chr;
make_scanf ib rest readers
| Format_arg (pad_opt, fmtty, rest) ->
let _ = scan_caml_string (width_of_pad_opt pad_opt) ib in
let s = token_string ib in
let fmt =
try format_of_string_fmtty s fmtty
with Failure msg -> bad_input msg
in
Cons (fmt, make_scanf ib rest readers)
| Format_subst (pad_opt, fmtty, rest) ->
let _ = scan_caml_string (width_of_pad_opt pad_opt) ib in
let s = token_string ib in
let fmt, fmt' =
try
let Fmt_EBB fmt = fmt_ebb_of_string s in
let Fmt_EBB fmt' = fmt_ebb_of_string s in
(* TODO: find a way to avoid reparsing twice *)
(* TODO: these type-checks below *can* fail because of type
ambiguity in presence of ignored-readers: "%_r%d" and "%d%_r"
are typed in the same way.
# Scanf.sscanf "\"%_r%d\"3" "%(%d%_r%)" ignore
(fun fmt n -> string_of_format fmt, n);;
Exception: CamlinternalFormat.Type_mismatch.
We should properly catch this exception.
*)
type_format fmt (erase_rel fmtty),
type_format fmt' (erase_rel (symm fmtty))
with Failure msg -> bad_input msg
in
Cons (Format (fmt, s),
make_scanf ib (concat_fmt fmt' rest) readers)
| Scan_char_set (width_opt, char_set, Formatting_lit (fmting_lit, rest)) ->
let stp, str = stopper_of_formatting_lit fmting_lit in
let width = width_of_pad_opt width_opt in
let _ = scan_chars_in_char_set char_set (Some stp) width ib in
let s = token_string ib in
let str_rest = String_literal (str, rest) in
Cons (s, make_scanf ib str_rest readers)
| Scan_char_set (width_opt, char_set, rest) ->
let width = width_of_pad_opt width_opt in
let _ = scan_chars_in_char_set char_set None width ib in
let s = token_string ib in
Cons (s, make_scanf ib rest readers)
| Scan_get_counter (counter, rest) ->
let count = get_counter ib counter in
Cons (count, make_scanf ib rest readers)
| Scan_next_char rest ->
let c = Scanning.checked_peek_char ib in
Cons (c, make_scanf ib rest readers)
| Formatting_lit (formatting_lit, rest) ->
String.iter (check_char ib) (string_of_formatting_lit formatting_lit);
make_scanf ib rest readers
| Formatting_gen (Open_tag (Format (fmt', _)), rest) ->
check_char ib '@'; check_char ib '{';
make_scanf ib (concat_fmt fmt' rest) readers
| Formatting_gen (Open_box (Format (fmt', _)), rest) ->
check_char ib '@'; check_char ib '[';
make_scanf ib (concat_fmt fmt' rest) readers
| Ignored_param (ign, rest) ->
let Param_format_EBB fmt' = param_format_of_ignored_format ign rest in
begin match make_scanf ib fmt' readers with
| Cons (_, arg_rest) -> arg_rest
| Nil -> assert false
end
| End_of_format ->
Nil
(* Case analysis on padding and precision. *)
(* Reject formats containing "%*" or "%.*". *)
(* Pass padding and precision to the generic scanner `scan'. *)
and pad_prec_scanf : type a c d e f x y z t .
Scanning.in_channel -> (a, Scanning.in_channel, c, d, e, f) fmt ->
(d, _) heter_list -> (x, y) padding -> (y, z -> a) precision ->
(int -> int -> Scanning.in_channel -> t) ->
(Scanning.in_channel -> z) ->
(x, f) heter_list =
fun ib fmt readers pad prec scan token -> match pad, prec with
| No_padding, No_precision ->
let _ = scan max_int max_int ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| No_padding, Lit_precision p ->
let _ = scan max_int p ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| Lit_padding ((Right | Zeros), w), No_precision ->
let _ = scan w max_int ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| Lit_padding ((Right | Zeros), w), Lit_precision p ->
let _ = scan w p ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| Lit_padding (Left, _), _ ->
invalid_arg "scanf: bad conversion \"%-\""
| Lit_padding ((Right | Zeros), _), Arg_precision ->
invalid_arg "scanf: bad conversion \"%*\""
| Arg_padding _, _ ->
invalid_arg "scanf: bad conversion \"%*\""
| No_padding, Arg_precision ->
invalid_arg "scanf: bad conversion \"%*\""
(******************************************************************************)
(* Defining [scanf] and various flavors of [scanf] *)
type 'a kscanf_result = Args of 'a | Exc of exn
let kscanf ib ef (Format (fmt, str)) =
let rec apply : type a b . a -> (a, b) heter_list -> b =
fun f args -> match args with
| Cons (x, r) -> apply (f x) r
| Nil -> f
in
let k readers f =
Scanning.reset_token ib;
match try Args (make_scanf ib fmt readers) with
| (Scan_failure _ | Failure _ | End_of_file) as exc -> Exc exc
| Invalid_argument msg ->
invalid_arg (msg ^ " in format \"" ^ String.escaped str ^ "\"")
with
| Args args -> apply f args
| Exc exc -> ef ib exc
in
take_format_readers k fmt
let kbscanf = kscanf
(***)
let ksscanf s ef fmt = kbscanf (Scanning.from_string s) ef fmt
let kfscanf ic ef fmt = kbscanf (Scanning.from_channel ic) ef fmt
let bscanf ib fmt = kscanf ib scanf_bad_input fmt
let fscanf ic fmt = kscanf (Scanning.from_channel ic) scanf_bad_input fmt
let sscanf s fmt = kscanf (Scanning.from_string s) scanf_bad_input fmt
let scanf fmt = kscanf Scanning.stdib scanf_bad_input fmt
(***)
let bscanf_format : Scanning.in_channel -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
(('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g =
fun ib format f ->
let _ = scan_caml_string max_int ib in
let str = token_string ib in
let fmt' =
try format_of_string_format str format
with Failure msg -> bad_input msg
in
f fmt'
let sscanf_format : string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
(('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g =
fun s format f -> bscanf_format (Scanning.from_string s) format f
let string_to_String s =
let l = String.length s in
let b = Buffer.create (l + 2) in
Buffer.add_char b '\"';
for i = 0 to l - 1 do
let c = s.[i] in
if c = '\"' then Buffer.add_char b '\\';
Buffer.add_char b c;
done;
Buffer.add_char b '\"';
Buffer.contents b
;;
let format_from_string s fmt =
sscanf_format (string_to_String s) fmt (fun x -> x)
;;
let unescaped s =
sscanf ("\"" ^ s ^ "\"") "%S%!" (fun x -> x)
;;
|
{
"pile_set_name": "Github"
}
|
.pizza-name {
padding: 30px;
input {
width: 100%;
border: 1px solid #b8c8d0;
padding: 10px 15px;
border-radius: 2px;
font-size: 14px;
color: #01699a;
outline: 0;
}
}
.error {
border-radius: 0 0 2px 2px;
background: #d73a49;
color: #fff;
padding: 5px 10px;
font-size: 13px;
margin: -1px 0 0;
position: relative;
font-weight: 500;
}
|
{
"pile_set_name": "Github"
}
|
<metadata>
<attr path="/api/package[@name='androidx.work']" name="managedName">AndroidX.Work</attr>
<remove-node path="/api/package[contains(@name,'androidx.work.impl')]" />
<attr path="/api/package[@name='androidx.work']/class[@name='WorkRequest.Builder']/method[@name='build']" name="return">androidx.work.WorkRequest</attr>
<attr path="/api/package[@name='androidx.work']/class[@name='WorkRequest.Builder']/method[@name='addTag']" name="return">androidx.work.WorkRequest.Builder</attr>
<attr path="/api/package[@name='androidx.work']/class[@name='WorkRequest.Builder']/method[@name='keepResultsForAtLeast']" name="return">androidx.work.WorkRequest.Builder</attr>
<attr path="/api/package[@name='androidx.work']/class[@name='WorkRequest.Builder']/method[@name='setBackoffCriteria']" name="return">androidx.work.WorkRequest.Builder</attr>
<attr path="/api/package[@name='androidx.work']/class[@name='WorkRequest.Builder']/method[@name='setConstraints']" name="return">androidx.work.WorkRequest.Builder</attr>
<attr path="/api/package[@name='androidx.work']/class[@name='WorkRequest.Builder']/method[@name='setInitialRunAttemptCount']" name="return">androidx.work.WorkRequest.Builder</attr>
<attr path="/api/package[@name='androidx.work']/class[@name='WorkRequest.Builder']/method[@name='setInitialState']" name="return">androidx.work.WorkRequest.Builder</attr>
<attr path="/api/package[@name='androidx.work']/class[@name='WorkRequest.Builder']/method[@name='setInputData']" name="return">androidx.work.WorkRequest.Builder</attr>
<attr path="/api/package[@name='androidx.work']/class[@name='WorkRequest.Builder']/method[@name='setPeriodStartTime']" name="return">androidx.work.WorkRequest.Builder</attr>
<attr path="/api/package[@name='androidx.work']/class[@name='WorkRequest.Builder']/method[@name='setScheduleRequestedAt']" name="return">androidx.work.WorkRequest.Builder</attr>
</metadata>
|
{
"pile_set_name": "Github"
}
|
:020000021000EC
:10FC000001C0F2C0112484B790E890936100109273
:10FC10006100882369F0982F9A70923049F081FF33
:10FC200002C097EF94BF282E80E001D10C94000011
:10FC300085E08093810082E08093300188E18093A9
:10FC4000310181E08093340186E0809332018EE0BF
:10FC5000EED0279A84E020E93FEF91E030938500D1
:10FC60002093840096BBB09BFECF1F9AA89540912D
:10FC7000300147FD02C0815089F7CDD0813479F43D
:10FC8000CAD0C82FDAD0C23811F480E004C088E0AE
:10FC9000C13809F083E0B8D080E1B6D0EECF82342D
:10FCA00019F484E1D2D0F8CF853411F485E0FACF8D
:10FCB000853581F4B0D0E82EAED0F82E87FF07C08E
:10FCC0008BB781608BBFEE0CFF1CB7D0E5CF8BB735
:10FCD0008E7FF8CF863579F49ED08D3451F49BD049
:10FCE000CBB799D0C170880F8C2B8BBF81E0ADD082
:10FCF000CCCF83E0FCCF843609F046C08CD0C82F2F
:10FD0000D0E0DC2FCC2787D0C82B85D0D82E5E0141
:10FD10008EEFB81A00E012E04801EFEF8E1A9E0A4B
:10FD20007AD0F801808384018A149B04A9F785D0D6
:10FD3000F5E410E000E0DF1609F150E040E063E098
:10FD4000C70152D08701C12C92E0D92EF601419112
:10FD500051916F0161E0C80147D00E5F1F4F22979C
:10FD6000A9F750E040E065E0C7013ED095CF608143
:10FD7000C8018E0D9F1D78D00F5F1F4FF801FE5FE9
:10FD8000C017D107A1F788CF843701F544D0C82F19
:10FD9000D0E0DC2FCC273FD0C82B3DD0D82E4DD083
:10FDA0008701F5E4DF120BC0CE0DDF1DC80154D072
:10FDB0002BD00F5F1F4FC017D107C1F76DCFF801D0
:10FDC00087918F0121D02197D1F766CF853731F404
:10FDD00034D08EE119D087E917D05CCF813509F096
:10FDE00074CF88E024D071CFFC010A0167BFE89589
:10FDF000112407B600FCFDCF667029F0452B19F4DD
:10FE000081E187BFE89508959091300195FFFCCF7F
:10FE10008093360108958091300187FFFCCF809157
:10FE2000300184FD01C0A895809136010895E0E677
:10FE3000F0E098E1908380830895EDDF803219F03F
:10FE400088E0F5DFFFCF84E1DFCFCF93C82FE3DF7A
:10FE5000C150E9F7CF91F1CFF999FECF92BD81BDA5
:10FE6000F89A992780B50895262FF999FECF1FBAE1
:10FE700092BD81BD20BD0FB6F894FA9AF99A0FBED3
:04FE8000019608954A
:02FFFE000008F9
:040000031000FC00ED
:00000001FF
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.