text
stringlengths 2
99k
| meta
dict |
---|---|
/*
Copyright (c) 2015 Cromulence LLC
Authors: Cromulence <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __CTYPE_H__
#define __CTYPE_H__
int cgc_isdigit( int c );
int cgc_islower( int c );
int cgc_isupper( int c );
int cgc_isalpha( int c );
int cgc_isalnum( int c );
int cgc_isprint( int c );
int cgc_isspace( int c );
int cgc_toupper( int c );
int cgc_tolower( int c );
#endif // __CTYPE_H__
| {
"pile_set_name": "Github"
} |
--
-- Table structure for table `useragent_class`
--
CREATE TABLE `useragent_class` (
`class_id` int(11) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`class_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `useragent_type`
--
CREATE TABLE `useragent_type` (
`useragent_id` int(11) NOT NULL,
`description` varchar(255) NOT NULL,
`match_expression` varchar(255) NOT NULL,
PRIMARY KEY (`useragent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `useragent_mapping`
--
CREATE TABLE `useragent_mapping` (
`useragent_type` int(11) NOT NULL,
`useragent_class` int(11) NOT NULL,
PRIMARY KEY (`useragent_type`,`useragent_class`),
KEY `useragent_type_key` (`useragent_type`),
KEY `useragent_class_key` (`useragent_class`),
CONSTRAINT `0_68` FOREIGN KEY (`useragent_type`) REFERENCES `useragent_type` (`useragent_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `0_69` FOREIGN KEY (`useragent_class`) REFERENCES `useragent_class` (`class_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Add vlan parameter to the class table
--
ALTER TABLE `class` ADD vlan varchar(255) after `disable`;
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2011 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "libyuv/scale.h"
#include <assert.h>
#include <string.h>
#include "libyuv/cpu_id.h"
#include "libyuv/planar_functions.h" // For CopyPlane
#include "libyuv/row.h"
#include "libyuv/scale_row.h"
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
static __inline int Abs(int v) {
return v >= 0 ? v : -v;
}
#define SUBSAMPLE(v, a, s) (v < 0) ? (-((-v + a) >> s)) : ((v + a) >> s)
// Scale plane, 1/2
// This is an optimized version for scaling down a plane to 1/2 of
// its original size.
static void ScalePlaneDown2(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
enum FilterMode filtering) {
int y;
void (*ScaleRowDown2)(const uint8* src_ptr, ptrdiff_t src_stride,
uint8* dst_ptr, int dst_width) =
filtering == kFilterNone ? ScaleRowDown2_C :
(filtering == kFilterLinear ? ScaleRowDown2Linear_C : ScaleRowDown2Box_C);
int row_stride = src_stride << 1;
if (!filtering) {
src_ptr += src_stride; // Point to odd rows.
src_stride = 0;
}
#if defined(HAS_SCALEROWDOWN2_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
ScaleRowDown2 = filtering == kFilterNone ? ScaleRowDown2_Any_NEON :
(filtering == kFilterLinear ? ScaleRowDown2Linear_Any_NEON :
ScaleRowDown2Box_Any_NEON);
if (IS_ALIGNED(dst_width, 16)) {
ScaleRowDown2 = filtering == kFilterNone ? ScaleRowDown2_NEON :
(filtering == kFilterLinear ? ScaleRowDown2Linear_NEON :
ScaleRowDown2Box_NEON);
}
}
#endif
#if defined(HAS_SCALEROWDOWN2_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
ScaleRowDown2 = filtering == kFilterNone ? ScaleRowDown2_Any_SSSE3 :
(filtering == kFilterLinear ? ScaleRowDown2Linear_Any_SSSE3 :
ScaleRowDown2Box_Any_SSSE3);
if (IS_ALIGNED(dst_width, 16)) {
ScaleRowDown2 = filtering == kFilterNone ? ScaleRowDown2_SSSE3 :
(filtering == kFilterLinear ? ScaleRowDown2Linear_SSSE3 :
ScaleRowDown2Box_SSSE3);
}
}
#endif
#if defined(HAS_SCALEROWDOWN2_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
ScaleRowDown2 = filtering == kFilterNone ? ScaleRowDown2_Any_AVX2 :
(filtering == kFilterLinear ? ScaleRowDown2Linear_Any_AVX2 :
ScaleRowDown2Box_Any_AVX2);
if (IS_ALIGNED(dst_width, 32)) {
ScaleRowDown2 = filtering == kFilterNone ? ScaleRowDown2_AVX2 :
(filtering == kFilterLinear ? ScaleRowDown2Linear_AVX2 :
ScaleRowDown2Box_AVX2);
}
}
#endif
#if defined(HAS_SCALEROWDOWN2_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && IS_ALIGNED(src_ptr, 4) &&
IS_ALIGNED(src_stride, 4) && IS_ALIGNED(row_stride, 4) &&
IS_ALIGNED(dst_ptr, 4) && IS_ALIGNED(dst_stride, 4)) {
ScaleRowDown2 = filtering ?
ScaleRowDown2Box_DSPR2 : ScaleRowDown2_DSPR2;
}
#endif
if (filtering == kFilterLinear) {
src_stride = 0;
}
// TODO(fbarchard): Loop through source height to allow odd height.
for (y = 0; y < dst_height; ++y) {
ScaleRowDown2(src_ptr, src_stride, dst_ptr, dst_width);
src_ptr += row_stride;
dst_ptr += dst_stride;
}
}
static void ScalePlaneDown2_16(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint16* src_ptr, uint16* dst_ptr,
enum FilterMode filtering) {
int y;
void (*ScaleRowDown2)(const uint16* src_ptr, ptrdiff_t src_stride,
uint16* dst_ptr, int dst_width) =
filtering == kFilterNone ? ScaleRowDown2_16_C :
(filtering == kFilterLinear ? ScaleRowDown2Linear_16_C :
ScaleRowDown2Box_16_C);
int row_stride = src_stride << 1;
if (!filtering) {
src_ptr += src_stride; // Point to odd rows.
src_stride = 0;
}
#if defined(HAS_SCALEROWDOWN2_16_NEON)
if (TestCpuFlag(kCpuHasNEON) && IS_ALIGNED(dst_width, 16)) {
ScaleRowDown2 = filtering ? ScaleRowDown2Box_16_NEON :
ScaleRowDown2_16_NEON;
}
#endif
#if defined(HAS_SCALEROWDOWN2_16_SSE2)
if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(dst_width, 16)) {
ScaleRowDown2 = filtering == kFilterNone ? ScaleRowDown2_16_SSE2 :
(filtering == kFilterLinear ? ScaleRowDown2Linear_16_SSE2 :
ScaleRowDown2Box_16_SSE2);
}
#endif
#if defined(HAS_SCALEROWDOWN2_16_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && IS_ALIGNED(src_ptr, 4) &&
IS_ALIGNED(src_stride, 4) && IS_ALIGNED(row_stride, 4) &&
IS_ALIGNED(dst_ptr, 4) && IS_ALIGNED(dst_stride, 4)) {
ScaleRowDown2 = filtering ?
ScaleRowDown2Box_16_DSPR2 : ScaleRowDown2_16_DSPR2;
}
#endif
if (filtering == kFilterLinear) {
src_stride = 0;
}
// TODO(fbarchard): Loop through source height to allow odd height.
for (y = 0; y < dst_height; ++y) {
ScaleRowDown2(src_ptr, src_stride, dst_ptr, dst_width);
src_ptr += row_stride;
dst_ptr += dst_stride;
}
}
// Scale plane, 1/4
// This is an optimized version for scaling down a plane to 1/4 of
// its original size.
static void ScalePlaneDown4(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
enum FilterMode filtering) {
int y;
void (*ScaleRowDown4)(const uint8* src_ptr, ptrdiff_t src_stride,
uint8* dst_ptr, int dst_width) =
filtering ? ScaleRowDown4Box_C : ScaleRowDown4_C;
int row_stride = src_stride << 2;
if (!filtering) {
src_ptr += src_stride * 2; // Point to row 2.
src_stride = 0;
}
#if defined(HAS_SCALEROWDOWN4_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
ScaleRowDown4 = filtering ?
ScaleRowDown4Box_Any_NEON : ScaleRowDown4_Any_NEON;
if (IS_ALIGNED(dst_width, 8)) {
ScaleRowDown4 = filtering ? ScaleRowDown4Box_NEON : ScaleRowDown4_NEON;
}
}
#endif
#if defined(HAS_SCALEROWDOWN4_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
ScaleRowDown4 = filtering ?
ScaleRowDown4Box_Any_SSSE3 : ScaleRowDown4_Any_SSSE3;
if (IS_ALIGNED(dst_width, 8)) {
ScaleRowDown4 = filtering ? ScaleRowDown4Box_SSSE3 : ScaleRowDown4_SSSE3;
}
}
#endif
#if defined(HAS_SCALEROWDOWN4_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
ScaleRowDown4 = filtering ?
ScaleRowDown4Box_Any_AVX2 : ScaleRowDown4_Any_AVX2;
if (IS_ALIGNED(dst_width, 16)) {
ScaleRowDown4 = filtering ? ScaleRowDown4Box_AVX2 : ScaleRowDown4_AVX2;
}
}
#endif
#if defined(HAS_SCALEROWDOWN4_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && IS_ALIGNED(row_stride, 4) &&
IS_ALIGNED(src_ptr, 4) && IS_ALIGNED(src_stride, 4) &&
IS_ALIGNED(dst_ptr, 4) && IS_ALIGNED(dst_stride, 4)) {
ScaleRowDown4 = filtering ?
ScaleRowDown4Box_DSPR2 : ScaleRowDown4_DSPR2;
}
#endif
if (filtering == kFilterLinear) {
src_stride = 0;
}
for (y = 0; y < dst_height; ++y) {
ScaleRowDown4(src_ptr, src_stride, dst_ptr, dst_width);
src_ptr += row_stride;
dst_ptr += dst_stride;
}
}
static void ScalePlaneDown4_16(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint16* src_ptr, uint16* dst_ptr,
enum FilterMode filtering) {
int y;
void (*ScaleRowDown4)(const uint16* src_ptr, ptrdiff_t src_stride,
uint16* dst_ptr, int dst_width) =
filtering ? ScaleRowDown4Box_16_C : ScaleRowDown4_16_C;
int row_stride = src_stride << 2;
if (!filtering) {
src_ptr += src_stride * 2; // Point to row 2.
src_stride = 0;
}
#if defined(HAS_SCALEROWDOWN4_16_NEON)
if (TestCpuFlag(kCpuHasNEON) && IS_ALIGNED(dst_width, 8)) {
ScaleRowDown4 = filtering ? ScaleRowDown4Box_16_NEON :
ScaleRowDown4_16_NEON;
}
#endif
#if defined(HAS_SCALEROWDOWN4_16_SSE2)
if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(dst_width, 8)) {
ScaleRowDown4 = filtering ? ScaleRowDown4Box_16_SSE2 :
ScaleRowDown4_16_SSE2;
}
#endif
#if defined(HAS_SCALEROWDOWN4_16_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && IS_ALIGNED(row_stride, 4) &&
IS_ALIGNED(src_ptr, 4) && IS_ALIGNED(src_stride, 4) &&
IS_ALIGNED(dst_ptr, 4) && IS_ALIGNED(dst_stride, 4)) {
ScaleRowDown4 = filtering ?
ScaleRowDown4Box_16_DSPR2 : ScaleRowDown4_16_DSPR2;
}
#endif
if (filtering == kFilterLinear) {
src_stride = 0;
}
for (y = 0; y < dst_height; ++y) {
ScaleRowDown4(src_ptr, src_stride, dst_ptr, dst_width);
src_ptr += row_stride;
dst_ptr += dst_stride;
}
}
// Scale plane down, 3/4
static void ScalePlaneDown34(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
enum FilterMode filtering) {
int y;
void (*ScaleRowDown34_0)(const uint8* src_ptr, ptrdiff_t src_stride,
uint8* dst_ptr, int dst_width);
void (*ScaleRowDown34_1)(const uint8* src_ptr, ptrdiff_t src_stride,
uint8* dst_ptr, int dst_width);
const int filter_stride = (filtering == kFilterLinear) ? 0 : src_stride;
assert(dst_width % 3 == 0);
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_C;
ScaleRowDown34_1 = ScaleRowDown34_C;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Box_C;
ScaleRowDown34_1 = ScaleRowDown34_1_Box_C;
}
#if defined(HAS_SCALEROWDOWN34_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_Any_NEON;
ScaleRowDown34_1 = ScaleRowDown34_Any_NEON;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Box_Any_NEON;
ScaleRowDown34_1 = ScaleRowDown34_1_Box_Any_NEON;
}
if (dst_width % 24 == 0) {
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_NEON;
ScaleRowDown34_1 = ScaleRowDown34_NEON;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Box_NEON;
ScaleRowDown34_1 = ScaleRowDown34_1_Box_NEON;
}
}
}
#endif
#if defined(HAS_SCALEROWDOWN34_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_Any_SSSE3;
ScaleRowDown34_1 = ScaleRowDown34_Any_SSSE3;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Box_Any_SSSE3;
ScaleRowDown34_1 = ScaleRowDown34_1_Box_Any_SSSE3;
}
if (dst_width % 24 == 0) {
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_SSSE3;
ScaleRowDown34_1 = ScaleRowDown34_SSSE3;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Box_SSSE3;
ScaleRowDown34_1 = ScaleRowDown34_1_Box_SSSE3;
}
}
}
#endif
#if defined(HAS_SCALEROWDOWN34_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && (dst_width % 24 == 0) &&
IS_ALIGNED(src_ptr, 4) && IS_ALIGNED(src_stride, 4) &&
IS_ALIGNED(dst_ptr, 4) && IS_ALIGNED(dst_stride, 4)) {
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_DSPR2;
ScaleRowDown34_1 = ScaleRowDown34_DSPR2;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Box_DSPR2;
ScaleRowDown34_1 = ScaleRowDown34_1_Box_DSPR2;
}
}
#endif
for (y = 0; y < dst_height - 2; y += 3) {
ScaleRowDown34_0(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride;
dst_ptr += dst_stride;
ScaleRowDown34_1(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride;
dst_ptr += dst_stride;
ScaleRowDown34_0(src_ptr + src_stride, -filter_stride,
dst_ptr, dst_width);
src_ptr += src_stride * 2;
dst_ptr += dst_stride;
}
// Remainder 1 or 2 rows with last row vertically unfiltered
if ((dst_height % 3) == 2) {
ScaleRowDown34_0(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride;
dst_ptr += dst_stride;
ScaleRowDown34_1(src_ptr, 0, dst_ptr, dst_width);
} else if ((dst_height % 3) == 1) {
ScaleRowDown34_0(src_ptr, 0, dst_ptr, dst_width);
}
}
static void ScalePlaneDown34_16(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint16* src_ptr, uint16* dst_ptr,
enum FilterMode filtering) {
int y;
void (*ScaleRowDown34_0)(const uint16* src_ptr, ptrdiff_t src_stride,
uint16* dst_ptr, int dst_width);
void (*ScaleRowDown34_1)(const uint16* src_ptr, ptrdiff_t src_stride,
uint16* dst_ptr, int dst_width);
const int filter_stride = (filtering == kFilterLinear) ? 0 : src_stride;
assert(dst_width % 3 == 0);
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_16_C;
ScaleRowDown34_1 = ScaleRowDown34_16_C;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Box_16_C;
ScaleRowDown34_1 = ScaleRowDown34_1_Box_16_C;
}
#if defined(HAS_SCALEROWDOWN34_16_NEON)
if (TestCpuFlag(kCpuHasNEON) && (dst_width % 24 == 0)) {
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_16_NEON;
ScaleRowDown34_1 = ScaleRowDown34_16_NEON;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Box_16_NEON;
ScaleRowDown34_1 = ScaleRowDown34_1_Box_16_NEON;
}
}
#endif
#if defined(HAS_SCALEROWDOWN34_16_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3) && (dst_width % 24 == 0)) {
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_16_SSSE3;
ScaleRowDown34_1 = ScaleRowDown34_16_SSSE3;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Box_16_SSSE3;
ScaleRowDown34_1 = ScaleRowDown34_1_Box_16_SSSE3;
}
}
#endif
#if defined(HAS_SCALEROWDOWN34_16_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && (dst_width % 24 == 0) &&
IS_ALIGNED(src_ptr, 4) && IS_ALIGNED(src_stride, 4) &&
IS_ALIGNED(dst_ptr, 4) && IS_ALIGNED(dst_stride, 4)) {
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_16_DSPR2;
ScaleRowDown34_1 = ScaleRowDown34_16_DSPR2;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Box_16_DSPR2;
ScaleRowDown34_1 = ScaleRowDown34_1_Box_16_DSPR2;
}
}
#endif
for (y = 0; y < dst_height - 2; y += 3) {
ScaleRowDown34_0(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride;
dst_ptr += dst_stride;
ScaleRowDown34_1(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride;
dst_ptr += dst_stride;
ScaleRowDown34_0(src_ptr + src_stride, -filter_stride,
dst_ptr, dst_width);
src_ptr += src_stride * 2;
dst_ptr += dst_stride;
}
// Remainder 1 or 2 rows with last row vertically unfiltered
if ((dst_height % 3) == 2) {
ScaleRowDown34_0(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride;
dst_ptr += dst_stride;
ScaleRowDown34_1(src_ptr, 0, dst_ptr, dst_width);
} else if ((dst_height % 3) == 1) {
ScaleRowDown34_0(src_ptr, 0, dst_ptr, dst_width);
}
}
// Scale plane, 3/8
// This is an optimized version for scaling down a plane to 3/8
// of its original size.
//
// Uses box filter arranges like this
// aaabbbcc -> abc
// aaabbbcc def
// aaabbbcc ghi
// dddeeeff
// dddeeeff
// dddeeeff
// ggghhhii
// ggghhhii
// Boxes are 3x3, 2x3, 3x2 and 2x2
static void ScalePlaneDown38(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
enum FilterMode filtering) {
int y;
void (*ScaleRowDown38_3)(const uint8* src_ptr, ptrdiff_t src_stride,
uint8* dst_ptr, int dst_width);
void (*ScaleRowDown38_2)(const uint8* src_ptr, ptrdiff_t src_stride,
uint8* dst_ptr, int dst_width);
const int filter_stride = (filtering == kFilterLinear) ? 0 : src_stride;
assert(dst_width % 3 == 0);
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_C;
ScaleRowDown38_2 = ScaleRowDown38_C;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Box_C;
ScaleRowDown38_2 = ScaleRowDown38_2_Box_C;
}
#if defined(HAS_SCALEROWDOWN38_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_Any_NEON;
ScaleRowDown38_2 = ScaleRowDown38_Any_NEON;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Box_Any_NEON;
ScaleRowDown38_2 = ScaleRowDown38_2_Box_Any_NEON;
}
if (dst_width % 12 == 0) {
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_NEON;
ScaleRowDown38_2 = ScaleRowDown38_NEON;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Box_NEON;
ScaleRowDown38_2 = ScaleRowDown38_2_Box_NEON;
}
}
}
#endif
#if defined(HAS_SCALEROWDOWN38_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_Any_SSSE3;
ScaleRowDown38_2 = ScaleRowDown38_Any_SSSE3;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Box_Any_SSSE3;
ScaleRowDown38_2 = ScaleRowDown38_2_Box_Any_SSSE3;
}
if (dst_width % 12 == 0 && !filtering) {
ScaleRowDown38_3 = ScaleRowDown38_SSSE3;
ScaleRowDown38_2 = ScaleRowDown38_SSSE3;
}
if (dst_width % 6 == 0 && filtering) {
ScaleRowDown38_3 = ScaleRowDown38_3_Box_SSSE3;
ScaleRowDown38_2 = ScaleRowDown38_2_Box_SSSE3;
}
}
#endif
#if defined(HAS_SCALEROWDOWN38_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && (dst_width % 12 == 0) &&
IS_ALIGNED(src_ptr, 4) && IS_ALIGNED(src_stride, 4) &&
IS_ALIGNED(dst_ptr, 4) && IS_ALIGNED(dst_stride, 4)) {
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_DSPR2;
ScaleRowDown38_2 = ScaleRowDown38_DSPR2;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Box_DSPR2;
ScaleRowDown38_2 = ScaleRowDown38_2_Box_DSPR2;
}
}
#endif
for (y = 0; y < dst_height - 2; y += 3) {
ScaleRowDown38_3(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride * 3;
dst_ptr += dst_stride;
ScaleRowDown38_3(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride * 3;
dst_ptr += dst_stride;
ScaleRowDown38_2(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride * 2;
dst_ptr += dst_stride;
}
// Remainder 1 or 2 rows with last row vertically unfiltered
if ((dst_height % 3) == 2) {
ScaleRowDown38_3(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride * 3;
dst_ptr += dst_stride;
ScaleRowDown38_3(src_ptr, 0, dst_ptr, dst_width);
} else if ((dst_height % 3) == 1) {
ScaleRowDown38_3(src_ptr, 0, dst_ptr, dst_width);
}
}
static void ScalePlaneDown38_16(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint16* src_ptr, uint16* dst_ptr,
enum FilterMode filtering) {
int y;
void (*ScaleRowDown38_3)(const uint16* src_ptr, ptrdiff_t src_stride,
uint16* dst_ptr, int dst_width);
void (*ScaleRowDown38_2)(const uint16* src_ptr, ptrdiff_t src_stride,
uint16* dst_ptr, int dst_width);
const int filter_stride = (filtering == kFilterLinear) ? 0 : src_stride;
assert(dst_width % 3 == 0);
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_16_C;
ScaleRowDown38_2 = ScaleRowDown38_16_C;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Box_16_C;
ScaleRowDown38_2 = ScaleRowDown38_2_Box_16_C;
}
#if defined(HAS_SCALEROWDOWN38_16_NEON)
if (TestCpuFlag(kCpuHasNEON) && (dst_width % 12 == 0)) {
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_16_NEON;
ScaleRowDown38_2 = ScaleRowDown38_16_NEON;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Box_16_NEON;
ScaleRowDown38_2 = ScaleRowDown38_2_Box_16_NEON;
}
}
#endif
#if defined(HAS_SCALEROWDOWN38_16_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3) && (dst_width % 24 == 0)) {
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_16_SSSE3;
ScaleRowDown38_2 = ScaleRowDown38_16_SSSE3;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Box_16_SSSE3;
ScaleRowDown38_2 = ScaleRowDown38_2_Box_16_SSSE3;
}
}
#endif
#if defined(HAS_SCALEROWDOWN38_16_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2) && (dst_width % 12 == 0) &&
IS_ALIGNED(src_ptr, 4) && IS_ALIGNED(src_stride, 4) &&
IS_ALIGNED(dst_ptr, 4) && IS_ALIGNED(dst_stride, 4)) {
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_16_DSPR2;
ScaleRowDown38_2 = ScaleRowDown38_16_DSPR2;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Box_16_DSPR2;
ScaleRowDown38_2 = ScaleRowDown38_2_Box_16_DSPR2;
}
}
#endif
for (y = 0; y < dst_height - 2; y += 3) {
ScaleRowDown38_3(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride * 3;
dst_ptr += dst_stride;
ScaleRowDown38_3(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride * 3;
dst_ptr += dst_stride;
ScaleRowDown38_2(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride * 2;
dst_ptr += dst_stride;
}
// Remainder 1 or 2 rows with last row vertically unfiltered
if ((dst_height % 3) == 2) {
ScaleRowDown38_3(src_ptr, filter_stride, dst_ptr, dst_width);
src_ptr += src_stride * 3;
dst_ptr += dst_stride;
ScaleRowDown38_3(src_ptr, 0, dst_ptr, dst_width);
} else if ((dst_height % 3) == 1) {
ScaleRowDown38_3(src_ptr, 0, dst_ptr, dst_width);
}
}
#define MIN1(x) ((x) < 1 ? 1 : (x))
static __inline uint32 SumPixels(int iboxwidth, const uint16* src_ptr) {
uint32 sum = 0u;
int x;
assert(iboxwidth > 0);
for (x = 0; x < iboxwidth; ++x) {
sum += src_ptr[x];
}
return sum;
}
static __inline uint32 SumPixels_16(int iboxwidth, const uint32* src_ptr) {
uint32 sum = 0u;
int x;
assert(iboxwidth > 0);
for (x = 0; x < iboxwidth; ++x) {
sum += src_ptr[x];
}
return sum;
}
static void ScaleAddCols2_C(int dst_width, int boxheight, int x, int dx,
const uint16* src_ptr, uint8* dst_ptr) {
int i;
int scaletbl[2];
int minboxwidth = dx >> 16;
int boxwidth;
scaletbl[0] = 65536 / (MIN1(minboxwidth) * boxheight);
scaletbl[1] = 65536 / (MIN1(minboxwidth + 1) * boxheight);
for (i = 0; i < dst_width; ++i) {
int ix = x >> 16;
x += dx;
boxwidth = MIN1((x >> 16) - ix);
*dst_ptr++ = SumPixels(boxwidth, src_ptr + ix) *
scaletbl[boxwidth - minboxwidth] >> 16;
}
}
static void ScaleAddCols2_16_C(int dst_width, int boxheight, int x, int dx,
const uint32* src_ptr, uint16* dst_ptr) {
int i;
int scaletbl[2];
int minboxwidth = dx >> 16;
int boxwidth;
scaletbl[0] = 65536 / (MIN1(minboxwidth) * boxheight);
scaletbl[1] = 65536 / (MIN1(minboxwidth + 1) * boxheight);
for (i = 0; i < dst_width; ++i) {
int ix = x >> 16;
x += dx;
boxwidth = MIN1((x >> 16) - ix);
*dst_ptr++ = SumPixels_16(boxwidth, src_ptr + ix) *
scaletbl[boxwidth - minboxwidth] >> 16;
}
}
static void ScaleAddCols0_C(int dst_width, int boxheight, int x, int,
const uint16* src_ptr, uint8* dst_ptr) {
int scaleval = 65536 / boxheight;
int i;
src_ptr += (x >> 16);
for (i = 0; i < dst_width; ++i) {
*dst_ptr++ = src_ptr[i] * scaleval >> 16;
}
}
static void ScaleAddCols1_C(int dst_width, int boxheight, int x, int dx,
const uint16* src_ptr, uint8* dst_ptr) {
int boxwidth = MIN1(dx >> 16);
int scaleval = 65536 / (boxwidth * boxheight);
int i;
x >>= 16;
for (i = 0; i < dst_width; ++i) {
*dst_ptr++ = SumPixels(boxwidth, src_ptr + x) * scaleval >> 16;
x += boxwidth;
}
}
static void ScaleAddCols1_16_C(int dst_width, int boxheight, int x, int dx,
const uint32* src_ptr, uint16* dst_ptr) {
int boxwidth = MIN1(dx >> 16);
int scaleval = 65536 / (boxwidth * boxheight);
int i;
for (i = 0; i < dst_width; ++i) {
*dst_ptr++ = SumPixels_16(boxwidth, src_ptr + x) * scaleval >> 16;
x += boxwidth;
}
}
// Scale plane down to any dimensions, with interpolation.
// (boxfilter).
//
// Same method as SimpleScale, which is fixed point, outputting
// one pixel of destination using fixed point (16.16) to step
// through source, sampling a box of pixel with simple
// averaging.
static void ScalePlaneBox(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr) {
int j, k;
// Initial source x/y coordinate and step values as 16.16 fixed point.
int x = 0;
int y = 0;
int dx = 0;
int dy = 0;
const int max_y = (src_height << 16);
ScaleSlope(src_width, src_height, dst_width, dst_height, kFilterBox,
&x, &y, &dx, &dy);
src_width = Abs(src_width);
{
// Allocate a row buffer of uint16.
align_buffer_64(row16, src_width * 2);
void (*ScaleAddCols)(int dst_width, int boxheight, int x, int dx,
const uint16* src_ptr, uint8* dst_ptr) =
(dx & 0xffff) ? ScaleAddCols2_C:
((dx != 0x10000) ? ScaleAddCols1_C : ScaleAddCols0_C);
void (*ScaleAddRow)(const uint8* src_ptr, uint16* dst_ptr, int src_width) =
ScaleAddRow_C;
#if defined(HAS_SCALEADDROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
ScaleAddRow = ScaleAddRow_Any_SSE2;
if (IS_ALIGNED(src_width, 16)) {
ScaleAddRow = ScaleAddRow_SSE2;
}
}
#endif
#if defined(HAS_SCALEADDROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
ScaleAddRow = ScaleAddRow_Any_AVX2;
if (IS_ALIGNED(src_width, 32)) {
ScaleAddRow = ScaleAddRow_AVX2;
}
}
#endif
#if defined(HAS_SCALEADDROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
ScaleAddRow = ScaleAddRow_Any_NEON;
if (IS_ALIGNED(src_width, 16)) {
ScaleAddRow = ScaleAddRow_NEON;
}
}
#endif
for (j = 0; j < dst_height; ++j) {
int boxheight;
int iy = y >> 16;
const uint8* src = src_ptr + iy * src_stride;
y += dy;
if (y > max_y) {
y = max_y;
}
boxheight = MIN1((y >> 16) - iy);
memset(row16, 0, src_width * 2);
for (k = 0; k < boxheight; ++k) {
ScaleAddRow(src, (uint16 *)(row16), src_width);
src += src_stride;
}
ScaleAddCols(dst_width, boxheight, x, dx, (uint16*)(row16), dst_ptr);
dst_ptr += dst_stride;
}
free_aligned_buffer_64(row16);
}
}
static void ScalePlaneBox_16(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint16* src_ptr, uint16* dst_ptr) {
int j, k;
// Initial source x/y coordinate and step values as 16.16 fixed point.
int x = 0;
int y = 0;
int dx = 0;
int dy = 0;
const int max_y = (src_height << 16);
ScaleSlope(src_width, src_height, dst_width, dst_height, kFilterBox,
&x, &y, &dx, &dy);
src_width = Abs(src_width);
{
// Allocate a row buffer of uint32.
align_buffer_64(row32, src_width * 4);
void (*ScaleAddCols)(int dst_width, int boxheight, int x, int dx,
const uint32* src_ptr, uint16* dst_ptr) =
(dx & 0xffff) ? ScaleAddCols2_16_C: ScaleAddCols1_16_C;
void (*ScaleAddRow)(const uint16* src_ptr, uint32* dst_ptr, int src_width) =
ScaleAddRow_16_C;
#if defined(HAS_SCALEADDROW_16_SSE2)
if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(src_width, 16)) {
ScaleAddRow = ScaleAddRow_16_SSE2;
}
#endif
for (j = 0; j < dst_height; ++j) {
int boxheight;
int iy = y >> 16;
const uint16* src = src_ptr + iy * src_stride;
y += dy;
if (y > max_y) {
y = max_y;
}
boxheight = MIN1((y >> 16) - iy);
memset(row32, 0, src_width * 4);
for (k = 0; k < boxheight; ++k) {
ScaleAddRow(src, (uint32 *)(row32), src_width);
src += src_stride;
}
ScaleAddCols(dst_width, boxheight, x, dx, (uint32*)(row32), dst_ptr);
dst_ptr += dst_stride;
}
free_aligned_buffer_64(row32);
}
}
// Scale plane down with bilinear interpolation.
void ScalePlaneBilinearDown(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
enum FilterMode filtering) {
// Initial source x/y coordinate and step values as 16.16 fixed point.
int x = 0;
int y = 0;
int dx = 0;
int dy = 0;
// TODO(fbarchard): Consider not allocating row buffer for kFilterLinear.
// Allocate a row buffer.
align_buffer_64(row, src_width);
const int max_y = (src_height - 1) << 16;
int j;
void (*ScaleFilterCols)(uint8* dst_ptr, const uint8* src_ptr,
int dst_width, int x, int dx) =
(src_width >= 32768) ? ScaleFilterCols64_C : ScaleFilterCols_C;
void (*InterpolateRow)(uint8* dst_ptr, const uint8* src_ptr,
ptrdiff_t src_stride, int dst_width, int source_y_fraction) =
InterpolateRow_C;
ScaleSlope(src_width, src_height, dst_width, dst_height, filtering,
&x, &y, &dx, &dy);
src_width = Abs(src_width);
#if defined(HAS_INTERPOLATEROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
InterpolateRow = InterpolateRow_Any_SSSE3;
if (IS_ALIGNED(src_width, 16)) {
InterpolateRow = InterpolateRow_SSSE3;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
InterpolateRow = InterpolateRow_Any_AVX2;
if (IS_ALIGNED(src_width, 32)) {
InterpolateRow = InterpolateRow_AVX2;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
InterpolateRow = InterpolateRow_Any_NEON;
if (IS_ALIGNED(src_width, 16)) {
InterpolateRow = InterpolateRow_NEON;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
InterpolateRow = InterpolateRow_Any_DSPR2;
if (IS_ALIGNED(src_width, 4)) {
InterpolateRow = InterpolateRow_DSPR2;
}
}
#endif
#if defined(HAS_SCALEFILTERCOLS_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3) && src_width < 32768) {
ScaleFilterCols = ScaleFilterCols_SSSE3;
}
#endif
#if defined(HAS_SCALEFILTERCOLS_NEON)
if (TestCpuFlag(kCpuHasNEON) && src_width < 32768) {
ScaleFilterCols = ScaleFilterCols_Any_NEON;
if (IS_ALIGNED(dst_width, 8)) {
ScaleFilterCols = ScaleFilterCols_NEON;
}
}
#endif
if (y > max_y) {
y = max_y;
}
for (j = 0; j < dst_height; ++j) {
int yi = y >> 16;
const uint8* src = src_ptr + yi * src_stride;
if (filtering == kFilterLinear) {
ScaleFilterCols(dst_ptr, src, dst_width, x, dx);
} else {
int yf = (y >> 8) & 255;
InterpolateRow(row, src, src_stride, src_width, yf);
ScaleFilterCols(dst_ptr, row, dst_width, x, dx);
}
dst_ptr += dst_stride;
y += dy;
if (y > max_y) {
y = max_y;
}
}
free_aligned_buffer_64(row);
}
void ScalePlaneBilinearDown_16(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint16* src_ptr, uint16* dst_ptr,
enum FilterMode filtering) {
// Initial source x/y coordinate and step values as 16.16 fixed point.
int x = 0;
int y = 0;
int dx = 0;
int dy = 0;
// TODO(fbarchard): Consider not allocating row buffer for kFilterLinear.
// Allocate a row buffer.
align_buffer_64(row, src_width * 2);
const int max_y = (src_height - 1) << 16;
int j;
void (*ScaleFilterCols)(uint16* dst_ptr, const uint16* src_ptr,
int dst_width, int x, int dx) =
(src_width >= 32768) ? ScaleFilterCols64_16_C : ScaleFilterCols_16_C;
void (*InterpolateRow)(uint16* dst_ptr, const uint16* src_ptr,
ptrdiff_t src_stride, int dst_width, int source_y_fraction) =
InterpolateRow_16_C;
ScaleSlope(src_width, src_height, dst_width, dst_height, filtering,
&x, &y, &dx, &dy);
src_width = Abs(src_width);
#if defined(HAS_INTERPOLATEROW_16_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
InterpolateRow = InterpolateRow_Any_16_SSE2;
if (IS_ALIGNED(src_width, 16)) {
InterpolateRow = InterpolateRow_16_SSE2;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_16_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
InterpolateRow = InterpolateRow_Any_16_SSSE3;
if (IS_ALIGNED(src_width, 16)) {
InterpolateRow = InterpolateRow_16_SSSE3;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_16_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
InterpolateRow = InterpolateRow_Any_16_AVX2;
if (IS_ALIGNED(src_width, 32)) {
InterpolateRow = InterpolateRow_16_AVX2;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_16_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
InterpolateRow = InterpolateRow_Any_16_NEON;
if (IS_ALIGNED(src_width, 16)) {
InterpolateRow = InterpolateRow_16_NEON;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_16_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
InterpolateRow = InterpolateRow_Any_16_DSPR2;
if (IS_ALIGNED(src_width, 4)) {
InterpolateRow = InterpolateRow_16_DSPR2;
}
}
#endif
#if defined(HAS_SCALEFILTERCOLS_16_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3) && src_width < 32768) {
ScaleFilterCols = ScaleFilterCols_16_SSSE3;
}
#endif
if (y > max_y) {
y = max_y;
}
for (j = 0; j < dst_height; ++j) {
int yi = y >> 16;
const uint16* src = src_ptr + yi * src_stride;
if (filtering == kFilterLinear) {
ScaleFilterCols(dst_ptr, src, dst_width, x, dx);
} else {
int yf = (y >> 8) & 255;
InterpolateRow((uint16*)row, src, src_stride, src_width, yf);
ScaleFilterCols(dst_ptr, (uint16*)row, dst_width, x, dx);
}
dst_ptr += dst_stride;
y += dy;
if (y > max_y) {
y = max_y;
}
}
free_aligned_buffer_64(row);
}
// Scale up down with bilinear interpolation.
void ScalePlaneBilinearUp(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
enum FilterMode filtering) {
int j;
// Initial source x/y coordinate and step values as 16.16 fixed point.
int x = 0;
int y = 0;
int dx = 0;
int dy = 0;
const int max_y = (src_height - 1) << 16;
void (*InterpolateRow)(uint8* dst_ptr, const uint8* src_ptr,
ptrdiff_t src_stride, int dst_width, int source_y_fraction) =
InterpolateRow_C;
void (*ScaleFilterCols)(uint8* dst_ptr, const uint8* src_ptr,
int dst_width, int x, int dx) =
filtering ? ScaleFilterCols_C : ScaleCols_C;
ScaleSlope(src_width, src_height, dst_width, dst_height, filtering,
&x, &y, &dx, &dy);
src_width = Abs(src_width);
#if defined(HAS_INTERPOLATEROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
InterpolateRow = InterpolateRow_Any_SSSE3;
if (IS_ALIGNED(dst_width, 16)) {
InterpolateRow = InterpolateRow_SSSE3;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
InterpolateRow = InterpolateRow_Any_AVX2;
if (IS_ALIGNED(dst_width, 32)) {
InterpolateRow = InterpolateRow_AVX2;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
InterpolateRow = InterpolateRow_Any_NEON;
if (IS_ALIGNED(dst_width, 16)) {
InterpolateRow = InterpolateRow_NEON;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
InterpolateRow = InterpolateRow_Any_DSPR2;
if (IS_ALIGNED(dst_width, 4)) {
InterpolateRow = InterpolateRow_DSPR2;
}
}
#endif
if (filtering && src_width >= 32768) {
ScaleFilterCols = ScaleFilterCols64_C;
}
#if defined(HAS_SCALEFILTERCOLS_SSSE3)
if (filtering && TestCpuFlag(kCpuHasSSSE3) && src_width < 32768) {
ScaleFilterCols = ScaleFilterCols_SSSE3;
}
#endif
#if defined(HAS_SCALEFILTERCOLS_NEON)
if (filtering && TestCpuFlag(kCpuHasNEON) && src_width < 32768) {
ScaleFilterCols = ScaleFilterCols_Any_NEON;
if (IS_ALIGNED(dst_width, 8)) {
ScaleFilterCols = ScaleFilterCols_NEON;
}
}
#endif
if (!filtering && src_width * 2 == dst_width && x < 0x8000) {
ScaleFilterCols = ScaleColsUp2_C;
#if defined(HAS_SCALECOLS_SSE2)
if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(dst_width, 8)) {
ScaleFilterCols = ScaleColsUp2_SSE2;
}
#endif
}
if (y > max_y) {
y = max_y;
}
{
int yi = y >> 16;
const uint8* src = src_ptr + yi * src_stride;
// Allocate 2 row buffers.
const int kRowSize = (dst_width + 31) & ~31;
align_buffer_64(row, kRowSize * 2);
uint8* rowptr = row;
int rowstride = kRowSize;
int lasty = yi;
ScaleFilterCols(rowptr, src, dst_width, x, dx);
if (src_height > 1) {
src += src_stride;
}
ScaleFilterCols(rowptr + rowstride, src, dst_width, x, dx);
src += src_stride;
for (j = 0; j < dst_height; ++j) {
yi = y >> 16;
if (yi != lasty) {
if (y > max_y) {
y = max_y;
yi = y >> 16;
src = src_ptr + yi * src_stride;
}
if (yi != lasty) {
ScaleFilterCols(rowptr, src, dst_width, x, dx);
rowptr += rowstride;
rowstride = -rowstride;
lasty = yi;
src += src_stride;
}
}
if (filtering == kFilterLinear) {
InterpolateRow(dst_ptr, rowptr, 0, dst_width, 0);
} else {
int yf = (y >> 8) & 255;
InterpolateRow(dst_ptr, rowptr, rowstride, dst_width, yf);
}
dst_ptr += dst_stride;
y += dy;
}
free_aligned_buffer_64(row);
}
}
void ScalePlaneBilinearUp_16(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint16* src_ptr, uint16* dst_ptr,
enum FilterMode filtering) {
int j;
// Initial source x/y coordinate and step values as 16.16 fixed point.
int x = 0;
int y = 0;
int dx = 0;
int dy = 0;
const int max_y = (src_height - 1) << 16;
void (*InterpolateRow)(uint16* dst_ptr, const uint16* src_ptr,
ptrdiff_t src_stride, int dst_width, int source_y_fraction) =
InterpolateRow_16_C;
void (*ScaleFilterCols)(uint16* dst_ptr, const uint16* src_ptr,
int dst_width, int x, int dx) =
filtering ? ScaleFilterCols_16_C : ScaleCols_16_C;
ScaleSlope(src_width, src_height, dst_width, dst_height, filtering,
&x, &y, &dx, &dy);
src_width = Abs(src_width);
#if defined(HAS_INTERPOLATEROW_16_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
InterpolateRow = InterpolateRow_Any_16_SSE2;
if (IS_ALIGNED(dst_width, 16)) {
InterpolateRow = InterpolateRow_16_SSE2;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_16_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
InterpolateRow = InterpolateRow_Any_16_SSSE3;
if (IS_ALIGNED(dst_width, 16)) {
InterpolateRow = InterpolateRow_16_SSSE3;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_16_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
InterpolateRow = InterpolateRow_Any_16_AVX2;
if (IS_ALIGNED(dst_width, 32)) {
InterpolateRow = InterpolateRow_16_AVX2;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_16_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
InterpolateRow = InterpolateRow_Any_16_NEON;
if (IS_ALIGNED(dst_width, 16)) {
InterpolateRow = InterpolateRow_16_NEON;
}
}
#endif
#if defined(HAS_INTERPOLATEROW_16_DSPR2)
if (TestCpuFlag(kCpuHasDSPR2)) {
InterpolateRow = InterpolateRow_Any_16_DSPR2;
if (IS_ALIGNED(dst_width, 4)) {
InterpolateRow = InterpolateRow_16_DSPR2;
}
}
#endif
if (filtering && src_width >= 32768) {
ScaleFilterCols = ScaleFilterCols64_16_C;
}
#if defined(HAS_SCALEFILTERCOLS_16_SSSE3)
if (filtering && TestCpuFlag(kCpuHasSSSE3) && src_width < 32768) {
ScaleFilterCols = ScaleFilterCols_16_SSSE3;
}
#endif
if (!filtering && src_width * 2 == dst_width && x < 0x8000) {
ScaleFilterCols = ScaleColsUp2_16_C;
#if defined(HAS_SCALECOLS_16_SSE2)
if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(dst_width, 8)) {
ScaleFilterCols = ScaleColsUp2_16_SSE2;
}
#endif
}
if (y > max_y) {
y = max_y;
}
{
int yi = y >> 16;
const uint16* src = src_ptr + yi * src_stride;
// Allocate 2 row buffers.
const int kRowSize = (dst_width + 31) & ~31;
align_buffer_64(row, kRowSize * 4);
uint16* rowptr = (uint16*)row;
int rowstride = kRowSize;
int lasty = yi;
ScaleFilterCols(rowptr, src, dst_width, x, dx);
if (src_height > 1) {
src += src_stride;
}
ScaleFilterCols(rowptr + rowstride, src, dst_width, x, dx);
src += src_stride;
for (j = 0; j < dst_height; ++j) {
yi = y >> 16;
if (yi != lasty) {
if (y > max_y) {
y = max_y;
yi = y >> 16;
src = src_ptr + yi * src_stride;
}
if (yi != lasty) {
ScaleFilterCols(rowptr, src, dst_width, x, dx);
rowptr += rowstride;
rowstride = -rowstride;
lasty = yi;
src += src_stride;
}
}
if (filtering == kFilterLinear) {
InterpolateRow(dst_ptr, rowptr, 0, dst_width, 0);
} else {
int yf = (y >> 8) & 255;
InterpolateRow(dst_ptr, rowptr, rowstride, dst_width, yf);
}
dst_ptr += dst_stride;
y += dy;
}
free_aligned_buffer_64(row);
}
}
// Scale Plane to/from any dimensions, without interpolation.
// Fixed point math is used for performance: The upper 16 bits
// of x and dx is the integer part of the source position and
// the lower 16 bits are the fixed decimal part.
static void ScalePlaneSimple(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr) {
int i;
void (*ScaleCols)(uint8* dst_ptr, const uint8* src_ptr,
int dst_width, int x, int dx) = ScaleCols_C;
// Initial source x/y coordinate and step values as 16.16 fixed point.
int x = 0;
int y = 0;
int dx = 0;
int dy = 0;
ScaleSlope(src_width, src_height, dst_width, dst_height, kFilterNone,
&x, &y, &dx, &dy);
src_width = Abs(src_width);
if (src_width * 2 == dst_width && x < 0x8000) {
ScaleCols = ScaleColsUp2_C;
#if defined(HAS_SCALECOLS_SSE2)
if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(dst_width, 8)) {
ScaleCols = ScaleColsUp2_SSE2;
}
#endif
}
for (i = 0; i < dst_height; ++i) {
ScaleCols(dst_ptr, src_ptr + (y >> 16) * src_stride, dst_width, x, dx);
dst_ptr += dst_stride;
y += dy;
}
}
static void ScalePlaneSimple_16(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint16* src_ptr, uint16* dst_ptr) {
int i;
void (*ScaleCols)(uint16* dst_ptr, const uint16* src_ptr,
int dst_width, int x, int dx) = ScaleCols_16_C;
// Initial source x/y coordinate and step values as 16.16 fixed point.
int x = 0;
int y = 0;
int dx = 0;
int dy = 0;
ScaleSlope(src_width, src_height, dst_width, dst_height, kFilterNone,
&x, &y, &dx, &dy);
src_width = Abs(src_width);
if (src_width * 2 == dst_width && x < 0x8000) {
ScaleCols = ScaleColsUp2_16_C;
#if defined(HAS_SCALECOLS_16_SSE2)
if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(dst_width, 8)) {
ScaleCols = ScaleColsUp2_16_SSE2;
}
#endif
}
for (i = 0; i < dst_height; ++i) {
ScaleCols(dst_ptr, src_ptr + (y >> 16) * src_stride,
dst_width, x, dx);
dst_ptr += dst_stride;
y += dy;
}
}
// Scale a plane.
// This function dispatches to a specialized scaler based on scale factor.
LIBYUV_API
void ScalePlane(const uint8* src, int src_stride,
int src_width, int src_height,
uint8* dst, int dst_stride,
int dst_width, int dst_height,
enum FilterMode filtering) {
// Simplify filtering when possible.
filtering = ScaleFilterReduce(src_width, src_height,
dst_width, dst_height, filtering);
// Negative height means invert the image.
if (src_height < 0) {
src_height = -src_height;
src = src + (src_height - 1) * src_stride;
src_stride = -src_stride;
}
// Use specialized scales to improve performance for common resolutions.
// For example, all the 1/2 scalings will use ScalePlaneDown2()
if (dst_width == src_width && dst_height == src_height) {
// Straight copy.
CopyPlane(src, src_stride, dst, dst_stride, dst_width, dst_height);
return;
}
if (dst_width == src_width && filtering != kFilterBox) {
int dy = FixedDiv(src_height, dst_height);
// Arbitrary scale vertically, but unscaled horizontally.
ScalePlaneVertical(src_height,
dst_width, dst_height,
src_stride, dst_stride, src, dst,
0, 0, dy, 1, filtering);
return;
}
if (dst_width <= Abs(src_width) && dst_height <= src_height) {
// Scale down.
if (4 * dst_width == 3 * src_width &&
4 * dst_height == 3 * src_height) {
// optimized, 3/4
ScalePlaneDown34(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
if (2 * dst_width == src_width && 2 * dst_height == src_height) {
// optimized, 1/2
ScalePlaneDown2(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
// 3/8 rounded up for odd sized chroma height.
if (8 * dst_width == 3 * src_width &&
dst_height == ((src_height * 3 + 7) / 8)) {
// optimized, 3/8
ScalePlaneDown38(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
if (4 * dst_width == src_width && 4 * dst_height == src_height &&
(filtering == kFilterBox || filtering == kFilterNone)) {
// optimized, 1/4
ScalePlaneDown4(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
}
if (filtering == kFilterBox && dst_height * 2 < src_height) {
ScalePlaneBox(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst);
return;
}
if (filtering && dst_height > src_height) {
ScalePlaneBilinearUp(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
if (filtering) {
ScalePlaneBilinearDown(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
ScalePlaneSimple(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst);
}
LIBYUV_API
void ScalePlane_16(const uint16* src, int src_stride,
int src_width, int src_height,
uint16* dst, int dst_stride,
int dst_width, int dst_height,
enum FilterMode filtering) {
// Simplify filtering when possible.
filtering = ScaleFilterReduce(src_width, src_height,
dst_width, dst_height, filtering);
// Negative height means invert the image.
if (src_height < 0) {
src_height = -src_height;
src = src + (src_height - 1) * src_stride;
src_stride = -src_stride;
}
// Use specialized scales to improve performance for common resolutions.
// For example, all the 1/2 scalings will use ScalePlaneDown2()
if (dst_width == src_width && dst_height == src_height) {
// Straight copy.
CopyPlane_16(src, src_stride, dst, dst_stride, dst_width, dst_height);
return;
}
if (dst_width == src_width) {
int dy = FixedDiv(src_height, dst_height);
// Arbitrary scale vertically, but unscaled vertically.
ScalePlaneVertical_16(src_height,
dst_width, dst_height,
src_stride, dst_stride, src, dst,
0, 0, dy, 1, filtering);
return;
}
if (dst_width <= Abs(src_width) && dst_height <= src_height) {
// Scale down.
if (4 * dst_width == 3 * src_width &&
4 * dst_height == 3 * src_height) {
// optimized, 3/4
ScalePlaneDown34_16(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
if (2 * dst_width == src_width && 2 * dst_height == src_height) {
// optimized, 1/2
ScalePlaneDown2_16(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
// 3/8 rounded up for odd sized chroma height.
if (8 * dst_width == 3 * src_width &&
dst_height == ((src_height * 3 + 7) / 8)) {
// optimized, 3/8
ScalePlaneDown38_16(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
if (4 * dst_width == src_width && 4 * dst_height == src_height &&
filtering != kFilterBilinear) {
// optimized, 1/4
ScalePlaneDown4_16(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
}
if (filtering == kFilterBox && dst_height * 2 < src_height) {
ScalePlaneBox_16(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst);
return;
}
if (filtering && dst_height > src_height) {
ScalePlaneBilinearUp_16(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
if (filtering) {
ScalePlaneBilinearDown_16(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
return;
}
ScalePlaneSimple_16(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst);
}
// Scale an I420 image.
// This function in turn calls a scaling function for each plane.
LIBYUV_API
int I420Scale(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
int src_width, int src_height,
uint8* dst_y, int dst_stride_y,
uint8* dst_u, int dst_stride_u,
uint8* dst_v, int dst_stride_v,
int dst_width, int dst_height,
enum FilterMode filtering) {
int src_halfwidth = SUBSAMPLE(src_width, 1, 1);
int src_halfheight = SUBSAMPLE(src_height, 1, 1);
int dst_halfwidth = SUBSAMPLE(dst_width, 1, 1);
int dst_halfheight = SUBSAMPLE(dst_height, 1, 1);
if (!src_y || !src_u || !src_v || src_width == 0 || src_height == 0 ||
src_width > 32768 || src_height > 32768 ||
!dst_y || !dst_u || !dst_v || dst_width <= 0 || dst_height <= 0) {
return -1;
}
ScalePlane(src_y, src_stride_y, src_width, src_height,
dst_y, dst_stride_y, dst_width, dst_height,
filtering);
ScalePlane(src_u, src_stride_u, src_halfwidth, src_halfheight,
dst_u, dst_stride_u, dst_halfwidth, dst_halfheight,
filtering);
ScalePlane(src_v, src_stride_v, src_halfwidth, src_halfheight,
dst_v, dst_stride_v, dst_halfwidth, dst_halfheight,
filtering);
return 0;
}
LIBYUV_API
int I420Scale_16(const uint16* src_y, int src_stride_y,
const uint16* src_u, int src_stride_u,
const uint16* src_v, int src_stride_v,
int src_width, int src_height,
uint16* dst_y, int dst_stride_y,
uint16* dst_u, int dst_stride_u,
uint16* dst_v, int dst_stride_v,
int dst_width, int dst_height,
enum FilterMode filtering) {
int src_halfwidth = SUBSAMPLE(src_width, 1, 1);
int src_halfheight = SUBSAMPLE(src_height, 1, 1);
int dst_halfwidth = SUBSAMPLE(dst_width, 1, 1);
int dst_halfheight = SUBSAMPLE(dst_height, 1, 1);
if (!src_y || !src_u || !src_v || src_width == 0 || src_height == 0 ||
src_width > 32768 || src_height > 32768 ||
!dst_y || !dst_u || !dst_v || dst_width <= 0 || dst_height <= 0) {
return -1;
}
ScalePlane_16(src_y, src_stride_y, src_width, src_height,
dst_y, dst_stride_y, dst_width, dst_height,
filtering);
ScalePlane_16(src_u, src_stride_u, src_halfwidth, src_halfheight,
dst_u, dst_stride_u, dst_halfwidth, dst_halfheight,
filtering);
ScalePlane_16(src_v, src_stride_v, src_halfwidth, src_halfheight,
dst_v, dst_stride_v, dst_halfwidth, dst_halfheight,
filtering);
return 0;
}
// Deprecated api
LIBYUV_API
int Scale(const uint8* src_y, const uint8* src_u, const uint8* src_v,
int src_stride_y, int src_stride_u, int src_stride_v,
int src_width, int src_height,
uint8* dst_y, uint8* dst_u, uint8* dst_v,
int dst_stride_y, int dst_stride_u, int dst_stride_v,
int dst_width, int dst_height,
LIBYUV_BOOL interpolate) {
return I420Scale(src_y, src_stride_y,
src_u, src_stride_u,
src_v, src_stride_v,
src_width, src_height,
dst_y, dst_stride_y,
dst_u, dst_stride_u,
dst_v, dst_stride_v,
dst_width, dst_height,
interpolate ? kFilterBox : kFilterNone);
}
// Deprecated api
LIBYUV_API
int ScaleOffset(const uint8* src, int src_width, int src_height,
uint8* dst, int dst_width, int dst_height, int dst_yoffset,
LIBYUV_BOOL interpolate) {
// Chroma requires offset to multiple of 2.
int dst_yoffset_even = dst_yoffset & ~1;
int src_halfwidth = SUBSAMPLE(src_width, 1, 1);
int src_halfheight = SUBSAMPLE(src_height, 1, 1);
int dst_halfwidth = SUBSAMPLE(dst_width, 1, 1);
int dst_halfheight = SUBSAMPLE(dst_height, 1, 1);
int aheight = dst_height - dst_yoffset_even * 2; // actual output height
const uint8* src_y = src;
const uint8* src_u = src + src_width * src_height;
const uint8* src_v = src + src_width * src_height +
src_halfwidth * src_halfheight;
uint8* dst_y = dst + dst_yoffset_even * dst_width;
uint8* dst_u = dst + dst_width * dst_height +
(dst_yoffset_even >> 1) * dst_halfwidth;
uint8* dst_v = dst + dst_width * dst_height + dst_halfwidth * dst_halfheight +
(dst_yoffset_even >> 1) * dst_halfwidth;
if (!src || src_width <= 0 || src_height <= 0 ||
!dst || dst_width <= 0 || dst_height <= 0 || dst_yoffset_even < 0 ||
dst_yoffset_even >= dst_height) {
return -1;
}
return I420Scale(src_y, src_width,
src_u, src_halfwidth,
src_v, src_halfwidth,
src_width, src_height,
dst_y, dst_width,
dst_u, dst_halfwidth,
dst_v, dst_halfwidth,
dst_width, aheight,
interpolate ? kFilterBox : kFilterNone);
}
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
| {
"pile_set_name": "Github"
} |
"""Module progress tests"""
import unittest
from mock import Mock
from xblock.field_data import DictFieldData
from xmodule import x_module
from xmodule.progress import Progress
from . import get_test_system
class ProgressTest(unittest.TestCase):
''' Test that basic Progress objects work. A Progress represents a
fraction between 0 and 1.
'''
not_started = Progress(0, 17)
part_done = Progress(2, 6)
half_done = Progress(3, 6)
also_half_done = Progress(1, 2)
done = Progress(7, 7)
def test_create_object(self):
# These should work:
prg1 = Progress(0, 2) # pylint: disable=unused-variable
prg2 = Progress(1, 2) # pylint: disable=unused-variable
prg3 = Progress(2, 2) # pylint: disable=unused-variable
prg4 = Progress(2.5, 5.0) # pylint: disable=unused-variable
prg5 = Progress(3.7, 12.3333) # pylint: disable=unused-variable
# These shouldn't
self.assertRaises(ValueError, Progress, 0, 0)
self.assertRaises(ValueError, Progress, 2, 0)
self.assertRaises(ValueError, Progress, 1, -2)
self.assertRaises(TypeError, Progress, 0, "all")
# check complex numbers just for the heck of it :)
self.assertRaises(TypeError, Progress, 2j, 3)
def test_clamp(self):
self.assertEqual((2, 2), Progress(3, 2).frac())
self.assertEqual((0, 2), Progress(-2, 2).frac())
def test_frac(self):
prg = Progress(1, 2)
(a_mem, b_mem) = prg.frac()
self.assertEqual(a_mem, 1)
self.assertEqual(b_mem, 2)
def test_percent(self):
self.assertEqual(self.not_started.percent(), 0)
self.assertAlmostEqual(self.part_done.percent(), 33.33333333333333)
self.assertEqual(self.half_done.percent(), 50)
self.assertEqual(self.done.percent(), 100)
self.assertEqual(self.half_done.percent(), self.also_half_done.percent())
def test_started(self):
self.assertFalse(self.not_started.started())
self.assertTrue(self.part_done.started())
self.assertTrue(self.half_done.started())
self.assertTrue(self.done.started())
def test_inprogress(self):
# only true if working on it
self.assertFalse(self.done.inprogress())
self.assertFalse(self.not_started.inprogress())
self.assertTrue(self.part_done.inprogress())
self.assertTrue(self.half_done.inprogress())
def test_done(self):
self.assertTrue(self.done.done())
self.assertFalse(self.half_done.done())
self.assertFalse(self.not_started.done())
def test_str(self):
self.assertEqual(str(self.not_started), "0/17")
self.assertEqual(str(self.part_done), "2/6")
self.assertEqual(str(self.done), "7/7")
self.assertEqual(str(Progress(2.1234, 7)), '2.12/7')
self.assertEqual(str(Progress(2.0034, 7)), '2/7')
self.assertEqual(str(Progress(0.999, 7)), '1/7')
def test_add(self):
'''Test the Progress.add_counts() method'''
prg1 = Progress(0, 2)
prg2 = Progress(1, 3)
prg3 = Progress(2, 5)
prg_none = None
add = lambda a, b: Progress.add_counts(a, b).frac()
self.assertEqual(add(prg1, prg1), (0, 4))
self.assertEqual(add(prg1, prg2), (1, 5))
self.assertEqual(add(prg2, prg3), (3, 8))
self.assertEqual(add(prg2, prg_none), prg2.frac())
self.assertEqual(add(prg_none, prg2), prg2.frac())
def test_equality(self):
'''Test that comparing Progress objects for equality
works correctly.'''
prg1 = Progress(1, 2)
prg2 = Progress(2, 4)
prg3 = Progress(1, 2)
self.assertEqual(prg1, prg3)
self.assertNotEqual(prg1, prg2)
# Check != while we're at it
self.assertNotEqual(prg1, prg2)
self.assertEqual(prg1, prg3)
class ModuleProgressTest(unittest.TestCase):
''' Test that get_progress() does the right thing for the different modules
'''
def test_xmodule_default(self):
'''Make sure default get_progress exists, returns None'''
xmod = x_module.XModule(Mock(), get_test_system(), DictFieldData({'location': 'a://b/c/d/e'}), Mock())
prg = xmod.get_progress()
self.assertEqual(prg, None)
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/color_ec4a48" android:state_checked="true" />
<item android:color="@color/color_ec4a48" android:state_pressed="true" />
<item android:color="@color/color_ec4a48" android:state_selected="true" />
<!--必须放在最后一行,否则上面的效果全都不能用-->
<item android:color="@color/white"/>
</selector> | {
"pile_set_name": "Github"
} |
[![Sourcegraph](https://sourcegraph.com/github.com/json-iterator/go/-/badge.svg)](https://sourcegraph.com/github.com/json-iterator/go?badge)
[![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://pkg.go.dev/github.com/json-iterator/go)
[![Build Status](https://travis-ci.org/json-iterator/go.svg?branch=master)](https://travis-ci.org/json-iterator/go)
[![codecov](https://codecov.io/gh/json-iterator/go/branch/master/graph/badge.svg)](https://codecov.io/gh/json-iterator/go)
[![rcard](https://goreportcard.com/badge/github.com/json-iterator/go)](https://goreportcard.com/report/github.com/json-iterator/go)
[![License](http://img.shields.io/badge/license-mit-blue.svg?style=flat-square)](https://raw.githubusercontent.com/json-iterator/go/master/LICENSE)
[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/json-iterator/Lobby)
A high-performance 100% compatible drop-in replacement of "encoding/json"
You can also use thrift like JSON using [thrift-iterator](https://github.com/thrift-iterator/go)
# Benchmark
![benchmark](http://jsoniter.com/benchmarks/go-benchmark.png)
Source code: https://github.com/json-iterator/go-benchmark/blob/master/src/github.com/json-iterator/go-benchmark/benchmark_medium_payload_test.go
Raw Result (easyjson requires static code generation)
| | ns/op | allocation bytes | allocation times |
| --------------- | ----------- | ---------------- | ---------------- |
| std decode | 35510 ns/op | 1960 B/op | 99 allocs/op |
| easyjson decode | 8499 ns/op | 160 B/op | 4 allocs/op |
| jsoniter decode | 5623 ns/op | 160 B/op | 3 allocs/op |
| std encode | 2213 ns/op | 712 B/op | 5 allocs/op |
| easyjson encode | 883 ns/op | 576 B/op | 3 allocs/op |
| jsoniter encode | 837 ns/op | 384 B/op | 4 allocs/op |
Always benchmark with your own workload.
The result depends heavily on the data input.
# Usage
100% compatibility with standard lib
Replace
```go
import "encoding/json"
json.Marshal(&data)
```
with
```go
import jsoniter "github.com/json-iterator/go"
var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Marshal(&data)
```
Replace
```go
import "encoding/json"
json.Unmarshal(input, &data)
```
with
```go
import jsoniter "github.com/json-iterator/go"
var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Unmarshal(input, &data)
```
[More documentation](http://jsoniter.com/migrate-from-go-std.html)
# How to get
```
go get github.com/json-iterator/go
```
# Contribution Welcomed !
Contributors
- [thockin](https://github.com/thockin)
- [mattn](https://github.com/mattn)
- [cch123](https://github.com/cch123)
- [Oleg Shaldybin](https://github.com/olegshaldybin)
- [Jason Toffaletti](https://github.com/toffaletti)
Report issue or pull request, or email [email protected], or [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/json-iterator/Lobby)
| {
"pile_set_name": "Github"
} |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.572
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GoogleBillingClient", "GoogleBillingClient\GoogleBillingClient.csproj", "{9C98362A-86E1-4C80-8147-B37B25CF78E1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9C98362A-86E1-4C80-8147-B37B25CF78E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9C98362A-86E1-4C80-8147-B37B25CF78E1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9C98362A-86E1-4C80-8147-B37B25CF78E1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9C98362A-86E1-4C80-8147-B37B25CF78E1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {882D1958-3300-4EBA-B883-A5C263DAB1C8}
EndGlobalSection
EndGlobal
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
xmind.core.sheet command XMind sheets manipulation
"""
from xmind import utils
from . import const
from .mixin import WorkbookMixinElement
from .topic import TopicElement
from .title import TitleElement
from .relationship import RelationshipElement, RelationshipsElement
class SheetElement(WorkbookMixinElement):
TAG_NAME = const.TAG_SHEET
def __init__(self, node=None, ownerWorkbook=None):
super(SheetElement, self).__init__(node, ownerWorkbook)
self.addIdAttribute(const.ATTR_ID)
self.setAttribute(const.ATTR_TIMESTAMP, int(utils.get_current_time()))
self._root_topic = self._get_root_topic()
def _get_root_topic(self):
# This method initialize root topic, if not root topic DOM implementation, then create one
topics = self.getChildNodesByTagName(const.TAG_TOPIC)
owner_workbook = self.getOwnerWorkbook()
if len(topics) >= 1:
root_topic = topics[0]
root_topic = TopicElement(root_topic, owner_workbook)
else:
root_topic = TopicElement(ownerWorkbook=owner_workbook)
self.appendChild(root_topic)
return root_topic
def _getRelationships(self):
return self.getFirstChildNodeByTagName(const.TAG_RELATIONSHIPS)
def _addRelationship(self, rel):
"""
Add relationship to sheet
"""
_rels = self._getRelationships()
owner_workbook = self.getOwnerWorkbook()
rels = RelationshipsElement(_rels, owner_workbook)
if not _rels:
self.appendChild(rels)
rels.appendChild(rel)
def createRelationship(self, end1, end2, title=None):
"""
Create a relationship between two different topics and return the
created rel. Please notice that the created rel will be added to
sheet.
:param end1: topic or topic ID
:param end2: topic or topic ID
:param title: relationship title, default by None
:return: a `RelationshipElement` instance
"""
rel = RelationshipElement(ownerWorkbook=self.getOwnerWorkbook())
rel.setEnd1ID(end1 if isinstance(end1, str) else end1.getID())
rel.setEnd2ID(end2 if isinstance(end2, str) else end2.getID())
if title is not None:
rel.setTitle(title)
self._addRelationship(rel)
return rel
def getRelationships(self):
"""
Get list of relationship from current sheet
"""
_rels = self._getRelationships()
if not _rels:
return []
owner_workbook = self.getOwnerWorkbook()
return RelationshipsElement(_rels, owner_workbook).getRelationships()
def removeRelationship(self, rel):
"""
Remove a relationship between two different topics
"""
rels = self._getRelationships()
if not rels:
return
rel = rel.getImplementation()
rels.removeChild(rel)
if not rels.hasChildNodes():
self.getImplementation().removeChild(rels)
self.updateModifiedTime()
def getRootTopic(self):
return self._root_topic
def _get_title(self):
return self.getFirstChildNodeByTagName(const.TAG_TITLE)
# FIXME: convert to getter/setter
def getTitle(self):
title = self._get_title()
if title:
title = TitleElement(title, self.getOwnerWorkbook())
return title.getTextContent()
def setTitle(self, text):
_title = self._get_title()
title = TitleElement(_title, self.getOwnerWorkbook())
title.setTextContent(text)
if _title is None:
self.appendChild(title)
self.updateModifiedTime()
def getParent(self):
workbook = self.getOwnerWorkbook()
if workbook:
parent = self.getParentNode()
if parent == workbook.getWorkbookElement().getImplementation():
return workbook
def updateModifiedTime(self):
super(SheetElement, self).updateModifiedTime()
workbook = self.getParent()
if workbook:
workbook.updateModifiedTime()
def getData(self):
"""
Get sheet's main content in the form of a dictionary.
"""
root_topic = self.getRootTopic()
data = {
'id': self.getAttribute(const.ATTR_ID),
'title': self.getTitle(),
'topic': root_topic.getData()
}
return data
| {
"pile_set_name": "Github"
} |
/*
Copyright Rene Rivera 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_PREDEF_ARCHITECTURE_MIPS_H
#define BOOST_PREDEF_ARCHITECTURE_MIPS_H
#include <boost/predef/version_number.h>
#include <boost/predef/make.h>
/*`
[heading `BOOST_ARCH_MIPS`]
[@http://en.wikipedia.org/wiki/MIPS_architecture MIPS] architecture.
[table
[[__predef_symbol__] [__predef_version__]]
[[`__mips__`] [__predef_detection__]]
[[`__mips`] [__predef_detection__]]
[[`__MIPS__`] [__predef_detection__]]
[[`__mips`] [V.0.0]]
[[`_MIPS_ISA_MIPS1`] [1.0.0]]
[[`_R3000`] [1.0.0]]
[[`_MIPS_ISA_MIPS2`] [2.0.0]]
[[`__MIPS_ISA2__`] [2.0.0]]
[[`_R4000`] [2.0.0]]
[[`_MIPS_ISA_MIPS3`] [3.0.0]]
[[`__MIPS_ISA3__`] [3.0.0]]
[[`_MIPS_ISA_MIPS4`] [4.0.0]]
[[`__MIPS_ISA4__`] [4.0.0]]
]
*/
#define BOOST_ARCH_MIPS BOOST_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__mips__) || defined(__mips) || \
defined(__MIPS__)
# undef BOOST_ARCH_MIPS
# if !defined(BOOST_ARCH_MIPS) && (defined(__mips))
# define BOOST_ARCH_MIPS BOOST_VERSION_NUMBER(__mips,0,0)
# endif
# if !defined(BOOST_ARCH_MIPS) && (defined(_MIPS_ISA_MIPS1) || defined(_R3000))
# define BOOST_ARCH_MIPS BOOST_VERSION_NUMBER(1,0,0)
# endif
# if !defined(BOOST_ARCH_MIPS) && (defined(_MIPS_ISA_MIPS2) || defined(__MIPS_ISA2__) || defined(_R4000))
# define BOOST_ARCH_MIPS BOOST_VERSION_NUMBER(2,0,0)
# endif
# if !defined(BOOST_ARCH_MIPS) && (defined(_MIPS_ISA_MIPS3) || defined(__MIPS_ISA3__))
# define BOOST_ARCH_MIPS BOOST_VERSION_NUMBER(3,0,0)
# endif
# if !defined(BOOST_ARCH_MIPS) && (defined(_MIPS_ISA_MIPS4) || defined(__MIPS_ISA4__))
# define BOOST_ARCH_MIPS BOOST_VERSION_NUMBER(4,0,0)
# endif
# if !defined(BOOST_ARCH_MIPS)
# define BOOST_ARCH_MIPS BOOST_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BOOST_ARCH_MIPS
# define BOOST_ARCH_MIPS_AVAILABLE
#endif
#define BOOST_ARCH_MIPS_NAME "MIPS"
#endif
#include <boost/predef/detail/test.h>
BOOST_PREDEF_DECLARE_TEST(BOOST_ARCH_MIPS,BOOST_ARCH_MIPS_NAME)
| {
"pile_set_name": "Github"
} |
/* Generated by RuntimeBrowser.
*/
@protocol PSViewControllerOffsetProtocol
@required
- (void)setDesiredVerticalContentOffset:(float)arg1;
- (void)setDesiredVerticalContentOffsetItemNamed:(NSString *)arg1;
- (float)verticalContentOffset;
@end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project> | {
"pile_set_name": "Github"
} |
package com.vaadin.tests.components.grid;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.util.Person;
import com.vaadin.ui.Grid;
import com.vaadin.ui.components.grid.GridRowDragger;
@Theme("valo")
@Widgetset("com.vaadin.DefaultWidgetSet")
public class GridRowDraggerOneGrid extends AbstractGridDnD {
@Override
protected void setup(VaadinRequest request) {
getUI().setMobileHtml5DndEnabled(true);
Grid<Person> grid = createGridAndFillWithData(50);
GridRowDragger<Person> gridDragger = new GridRowDragger<>(grid);
initializeTestFor(gridDragger);
}
}
| {
"pile_set_name": "Github"
} |
/*
*
* Copyright 2020 gRPC 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 grpclog
// PrefixLogger does logging with a prefix.
//
// Logging method on a nil logs without any prefix.
type PrefixLogger struct {
prefix string
}
// Infof does info logging.
func (pl *PrefixLogger) Infof(format string, args ...interface{}) {
if pl != nil {
// Handle nil, so the tests can pass in a nil logger.
format = pl.prefix + format
}
Logger.Infof(format, args...)
}
// Warningf does warning logging.
func (pl *PrefixLogger) Warningf(format string, args ...interface{}) {
if pl != nil {
format = pl.prefix + format
}
Logger.Warningf(format, args...)
}
// Errorf does error logging.
func (pl *PrefixLogger) Errorf(format string, args ...interface{}) {
if pl != nil {
format = pl.prefix + format
}
Logger.Errorf(format, args...)
}
// Debugf does info logging at verbose level 2.
func (pl *PrefixLogger) Debugf(format string, args ...interface{}) {
if Logger.V(2) {
pl.Infof(format, args...)
}
}
// NewPrefixLogger creates a prefix logger with the given prefix.
func NewPrefixLogger(prefix string) *PrefixLogger {
return &PrefixLogger{prefix: prefix}
}
| {
"pile_set_name": "Github"
} |
<launch>
<node pkg="gridmapping2" type="gridmapping2_shared_gridmap_node" name="shared_gridmap" output="screen"/>
<node pkg="gridmapping2" type="gridmapping2_proxy_example1" name="proxy1" output="screen"/>
<node pkg="gridmapping2" type="gridmapping2_proxy_example2" name="proxy2" output="screen"/>
</launch>
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_AUTOFILL_CREDIT_CARD_FIELD_H_
#define CHROME_BROWSER_AUTOFILL_CREDIT_CARD_FIELD_H_
#pragma once
#include <vector>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/gtest_prod_util.h"
#include "chrome/browser/autofill/autofill_type.h"
#include "chrome/browser/autofill/form_field.h"
class AutofillField;
class AutofillScanner;
class CreditCardField : public FormField {
public:
static FormField* Parse(AutofillScanner* scanner);
protected:
// FormField:
virtual bool ClassifyField(FieldTypeMap* map) const OVERRIDE;
private:
FRIEND_TEST_ALL_PREFIXES(CreditCardFieldTest, ParseMiniumCreditCard);
FRIEND_TEST_ALL_PREFIXES(CreditCardFieldTest, ParseFullCreditCard);
FRIEND_TEST_ALL_PREFIXES(CreditCardFieldTest, ParseExpMonthYear);
FRIEND_TEST_ALL_PREFIXES(CreditCardFieldTest, ParseExpMonthYear2);
FRIEND_TEST_ALL_PREFIXES(CreditCardFieldTest, ParseExpField);
FRIEND_TEST_ALL_PREFIXES(CreditCardFieldTest, ParseExpField2DigitYear);
FRIEND_TEST_ALL_PREFIXES(CreditCardFieldTest,
ParseCreditCardHolderNameWithCCFullName);
CreditCardField();
const AutofillField* cardholder_; // Optional.
// Occasionally pages have separate fields for the cardholder's first and
// last names; for such pages cardholder_ holds the first name field and
// we store the last name field here.
// (We could store an embedded NameField object here, but we don't do so
// because the text patterns for matching a cardholder name are different
// than for ordinary names, and because cardholder names never have titles,
// middle names or suffixes.)
const AutofillField* cardholder_last_;
// TODO(jhawkins): Parse the select control.
const AutofillField* type_; // Optional.
const AutofillField* number_; // Required.
// The 3-digit card verification number; we don't currently fill this.
const AutofillField* verification_;
// Either |expiration_date_| or both |expiration_month_| and
// |expiration_year_| are required.
const AutofillField* expiration_month_;
const AutofillField* expiration_year_;
const AutofillField* expiration_date_;
// True if the year is detected to be a 2-digit year; otherwise, we assume
// a 4-digit year.
bool is_two_digit_year_;
DISALLOW_COPY_AND_ASSIGN(CreditCardField);
};
#endif // CHROME_BROWSER_AUTOFILL_CREDIT_CARD_FIELD_H_
| {
"pile_set_name": "Github"
} |
config BR2_PACKAGE_LIBDVDREAD
bool "libdvdread"
select BR2_PACKAGE_LIBDVDCSS
help
libdvdread provides a simple foundation for reading
DVD-Video images.
https://www.videolan.org/developers/libdvdnav.html
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<T3DataStructure>
<meta>
<langDisable>1</langDisable>
</meta>
<sheets>
<sDEF>
<ROOT>
<TCEforms>
<sheetTitle>LLL:EXT:bootstrap_package/Resources/Private/Language/Backend.xlf:settings</sheetTitle>
</TCEforms>
<type>array</type>
<el>
<default_element>
<TCEforms>
<label>LLL:EXT:bootstrap_package/Resources/Private/Language/Backend.xlf:accordion.default_element
</label>
<config>
<type>select</type>
<renderType>selectSingle</renderType>
<foreign_table>tx_bootstrappackage_accordion_item</foreign_table>
<foreign_table_where>AND tx_bootstrappackage_accordion_item.tt_content = ###THIS_UID###</foreign_table_where>
<items type="array">
<numIndex index="0" type="array">
<numIndex index="0">None</numIndex>
<numIndex index="1">0</numIndex>
</numIndex>
</items>
</config>
</TCEforms>
</default_element>
</el>
</ROOT>
</sDEF>
</sheets>
</T3DataStructure>
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0-only
//
// rt5682.c -- RT5682 ALSA SoC audio component driver
//
// Copyright 2018 Realtek Semiconductor Corp.
// Author: Bard Liao <[email protected]>
//
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/pm_runtime.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/acpi.h>
#include <linux/gpio.h>
#include <linux/of_gpio.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/jack.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include <sound/rt5682.h>
#include "rl6231.h"
#include "rt5682.h"
const char *rt5682_supply_names[RT5682_NUM_SUPPLIES] = {
"AVDD",
"MICVDD",
"VBAT",
};
EXPORT_SYMBOL_GPL(rt5682_supply_names);
static const struct reg_sequence patch_list[] = {
{RT5682_HP_IMP_SENS_CTRL_19, 0x1000},
{RT5682_DAC_ADC_DIG_VOL1, 0xa020},
{RT5682_I2C_CTRL, 0x000f},
{RT5682_PLL2_INTERNAL, 0x8266},
};
void rt5682_apply_patch_list(struct rt5682_priv *rt5682, struct device *dev)
{
int ret;
ret = regmap_multi_reg_write(rt5682->regmap, patch_list,
ARRAY_SIZE(patch_list));
if (ret)
dev_warn(dev, "Failed to apply regmap patch: %d\n", ret);
}
EXPORT_SYMBOL_GPL(rt5682_apply_patch_list);
const struct reg_default rt5682_reg[RT5682_REG_NUM] = {
{0x0002, 0x8080},
{0x0003, 0x8000},
{0x0005, 0x0000},
{0x0006, 0x0000},
{0x0008, 0x800f},
{0x000b, 0x0000},
{0x0010, 0x4040},
{0x0011, 0x0000},
{0x0012, 0x1404},
{0x0013, 0x1000},
{0x0014, 0xa00a},
{0x0015, 0x0404},
{0x0016, 0x0404},
{0x0019, 0xafaf},
{0x001c, 0x2f2f},
{0x001f, 0x0000},
{0x0022, 0x5757},
{0x0023, 0x0039},
{0x0024, 0x000b},
{0x0026, 0xc0c4},
{0x0029, 0x8080},
{0x002a, 0xa0a0},
{0x002b, 0x0300},
{0x0030, 0x0000},
{0x003c, 0x0080},
{0x0044, 0x0c0c},
{0x0049, 0x0000},
{0x0061, 0x0000},
{0x0062, 0x0000},
{0x0063, 0x003f},
{0x0064, 0x0000},
{0x0065, 0x0000},
{0x0066, 0x0030},
{0x0067, 0x0000},
{0x006b, 0x0000},
{0x006c, 0x0000},
{0x006d, 0x2200},
{0x006e, 0x0a10},
{0x0070, 0x8000},
{0x0071, 0x8000},
{0x0073, 0x0000},
{0x0074, 0x0000},
{0x0075, 0x0002},
{0x0076, 0x0001},
{0x0079, 0x0000},
{0x007a, 0x0000},
{0x007b, 0x0000},
{0x007c, 0x0100},
{0x007e, 0x0000},
{0x0080, 0x0000},
{0x0081, 0x0000},
{0x0082, 0x0000},
{0x0083, 0x0000},
{0x0084, 0x0000},
{0x0085, 0x0000},
{0x0086, 0x0005},
{0x0087, 0x0000},
{0x0088, 0x0000},
{0x008c, 0x0003},
{0x008d, 0x0000},
{0x008e, 0x0060},
{0x008f, 0x1000},
{0x0091, 0x0c26},
{0x0092, 0x0073},
{0x0093, 0x0000},
{0x0094, 0x0080},
{0x0098, 0x0000},
{0x009a, 0x0000},
{0x009b, 0x0000},
{0x009c, 0x0000},
{0x009d, 0x0000},
{0x009e, 0x100c},
{0x009f, 0x0000},
{0x00a0, 0x0000},
{0x00a3, 0x0002},
{0x00a4, 0x0001},
{0x00ae, 0x2040},
{0x00af, 0x0000},
{0x00b6, 0x0000},
{0x00b7, 0x0000},
{0x00b8, 0x0000},
{0x00b9, 0x0002},
{0x00be, 0x0000},
{0x00c0, 0x0160},
{0x00c1, 0x82a0},
{0x00c2, 0x0000},
{0x00d0, 0x0000},
{0x00d1, 0x2244},
{0x00d2, 0x3300},
{0x00d3, 0x2200},
{0x00d4, 0x0000},
{0x00d9, 0x0009},
{0x00da, 0x0000},
{0x00db, 0x0000},
{0x00dc, 0x00c0},
{0x00dd, 0x2220},
{0x00de, 0x3131},
{0x00df, 0x3131},
{0x00e0, 0x3131},
{0x00e2, 0x0000},
{0x00e3, 0x4000},
{0x00e4, 0x0aa0},
{0x00e5, 0x3131},
{0x00e6, 0x3131},
{0x00e7, 0x3131},
{0x00e8, 0x3131},
{0x00ea, 0xb320},
{0x00eb, 0x0000},
{0x00f0, 0x0000},
{0x00f1, 0x00d0},
{0x00f2, 0x00d0},
{0x00f6, 0x0000},
{0x00fa, 0x0000},
{0x00fb, 0x0000},
{0x00fc, 0x0000},
{0x00fd, 0x0000},
{0x00fe, 0x10ec},
{0x00ff, 0x6530},
{0x0100, 0xa0a0},
{0x010b, 0x0000},
{0x010c, 0xae00},
{0x010d, 0xaaa0},
{0x010e, 0x8aa2},
{0x010f, 0x02a2},
{0x0110, 0xc000},
{0x0111, 0x04a2},
{0x0112, 0x2800},
{0x0113, 0x0000},
{0x0117, 0x0100},
{0x0125, 0x0410},
{0x0132, 0x6026},
{0x0136, 0x5555},
{0x0138, 0x3700},
{0x013a, 0x2000},
{0x013b, 0x2000},
{0x013c, 0x2005},
{0x013f, 0x0000},
{0x0142, 0x0000},
{0x0145, 0x0002},
{0x0146, 0x0000},
{0x0147, 0x0000},
{0x0148, 0x0000},
{0x0149, 0x0000},
{0x0150, 0x79a1},
{0x0156, 0xaaaa},
{0x0160, 0x4ec0},
{0x0161, 0x0080},
{0x0162, 0x0200},
{0x0163, 0x0800},
{0x0164, 0x0000},
{0x0165, 0x0000},
{0x0166, 0x0000},
{0x0167, 0x000f},
{0x0168, 0x000f},
{0x0169, 0x0021},
{0x0190, 0x413d},
{0x0194, 0x0000},
{0x0195, 0x0000},
{0x0197, 0x0022},
{0x0198, 0x0000},
{0x0199, 0x0000},
{0x01af, 0x0000},
{0x01b0, 0x0400},
{0x01b1, 0x0000},
{0x01b2, 0x0000},
{0x01b3, 0x0000},
{0x01b4, 0x0000},
{0x01b5, 0x0000},
{0x01b6, 0x01c3},
{0x01b7, 0x02a0},
{0x01b8, 0x03e9},
{0x01b9, 0x1389},
{0x01ba, 0xc351},
{0x01bb, 0x0009},
{0x01bc, 0x0018},
{0x01bd, 0x002a},
{0x01be, 0x004c},
{0x01bf, 0x0097},
{0x01c0, 0x433d},
{0x01c2, 0x0000},
{0x01c3, 0x0000},
{0x01c4, 0x0000},
{0x01c5, 0x0000},
{0x01c6, 0x0000},
{0x01c7, 0x0000},
{0x01c8, 0x40af},
{0x01c9, 0x0702},
{0x01ca, 0x0000},
{0x01cb, 0x0000},
{0x01cc, 0x5757},
{0x01cd, 0x5757},
{0x01ce, 0x5757},
{0x01cf, 0x5757},
{0x01d0, 0x5757},
{0x01d1, 0x5757},
{0x01d2, 0x5757},
{0x01d3, 0x5757},
{0x01d4, 0x5757},
{0x01d5, 0x5757},
{0x01d6, 0x0000},
{0x01d7, 0x0008},
{0x01d8, 0x0029},
{0x01d9, 0x3333},
{0x01da, 0x0000},
{0x01db, 0x0004},
{0x01dc, 0x0000},
{0x01de, 0x7c00},
{0x01df, 0x0320},
{0x01e0, 0x06a1},
{0x01e1, 0x0000},
{0x01e2, 0x0000},
{0x01e3, 0x0000},
{0x01e4, 0x0000},
{0x01e6, 0x0001},
{0x01e7, 0x0000},
{0x01e8, 0x0000},
{0x01ea, 0x0000},
{0x01eb, 0x0000},
{0x01ec, 0x0000},
{0x01ed, 0x0000},
{0x01ee, 0x0000},
{0x01ef, 0x0000},
{0x01f0, 0x0000},
{0x01f1, 0x0000},
{0x01f2, 0x0000},
{0x01f3, 0x0000},
{0x01f4, 0x0000},
{0x0210, 0x6297},
{0x0211, 0xa005},
{0x0212, 0x824c},
{0x0213, 0xf7ff},
{0x0214, 0xf24c},
{0x0215, 0x0102},
{0x0216, 0x00a3},
{0x0217, 0x0048},
{0x0218, 0xa2c0},
{0x0219, 0x0400},
{0x021a, 0x00c8},
{0x021b, 0x00c0},
{0x021c, 0x0000},
{0x0250, 0x4500},
{0x0251, 0x40b3},
{0x0252, 0x0000},
{0x0253, 0x0000},
{0x0254, 0x0000},
{0x0255, 0x0000},
{0x0256, 0x0000},
{0x0257, 0x0000},
{0x0258, 0x0000},
{0x0259, 0x0000},
{0x025a, 0x0005},
{0x0270, 0x0000},
{0x02ff, 0x0110},
{0x0300, 0x001f},
{0x0301, 0x032c},
{0x0302, 0x5f21},
{0x0303, 0x4000},
{0x0304, 0x4000},
{0x0305, 0x06d5},
{0x0306, 0x8000},
{0x0307, 0x0700},
{0x0310, 0x4560},
{0x0311, 0xa4a8},
{0x0312, 0x7418},
{0x0313, 0x0000},
{0x0314, 0x0006},
{0x0315, 0xffff},
{0x0316, 0xc400},
{0x0317, 0x0000},
{0x03c0, 0x7e00},
{0x03c1, 0x8000},
{0x03c2, 0x8000},
{0x03c3, 0x8000},
{0x03c4, 0x8000},
{0x03c5, 0x8000},
{0x03c6, 0x8000},
{0x03c7, 0x8000},
{0x03c8, 0x8000},
{0x03c9, 0x8000},
{0x03ca, 0x8000},
{0x03cb, 0x8000},
{0x03cc, 0x8000},
{0x03d0, 0x0000},
{0x03d1, 0x0000},
{0x03d2, 0x0000},
{0x03d3, 0x0000},
{0x03d4, 0x2000},
{0x03d5, 0x2000},
{0x03d6, 0x0000},
{0x03d7, 0x0000},
{0x03d8, 0x2000},
{0x03d9, 0x2000},
{0x03da, 0x2000},
{0x03db, 0x2000},
{0x03dc, 0x0000},
{0x03dd, 0x0000},
{0x03de, 0x0000},
{0x03df, 0x2000},
{0x03e0, 0x0000},
{0x03e1, 0x0000},
{0x03e2, 0x0000},
{0x03e3, 0x0000},
{0x03e4, 0x0000},
{0x03e5, 0x0000},
{0x03e6, 0x0000},
{0x03e7, 0x0000},
{0x03e8, 0x0000},
{0x03e9, 0x0000},
{0x03ea, 0x0000},
{0x03eb, 0x0000},
{0x03ec, 0x0000},
{0x03ed, 0x0000},
{0x03ee, 0x0000},
{0x03ef, 0x0000},
{0x03f0, 0x0800},
{0x03f1, 0x0800},
{0x03f2, 0x0800},
{0x03f3, 0x0800},
};
EXPORT_SYMBOL_GPL(rt5682_reg);
bool rt5682_volatile_register(struct device *dev, unsigned int reg)
{
switch (reg) {
case RT5682_RESET:
case RT5682_CBJ_CTRL_2:
case RT5682_INT_ST_1:
case RT5682_4BTN_IL_CMD_1:
case RT5682_AJD1_CTRL:
case RT5682_HP_CALIB_CTRL_1:
case RT5682_DEVICE_ID:
case RT5682_I2C_MODE:
case RT5682_HP_CALIB_CTRL_10:
case RT5682_EFUSE_CTRL_2:
case RT5682_JD_TOP_VC_VTRL:
case RT5682_HP_IMP_SENS_CTRL_19:
case RT5682_IL_CMD_1:
case RT5682_SAR_IL_CMD_2:
case RT5682_SAR_IL_CMD_4:
case RT5682_SAR_IL_CMD_10:
case RT5682_SAR_IL_CMD_11:
case RT5682_EFUSE_CTRL_6...RT5682_EFUSE_CTRL_11:
case RT5682_HP_CALIB_STA_1...RT5682_HP_CALIB_STA_11:
return true;
default:
return false;
}
}
EXPORT_SYMBOL_GPL(rt5682_volatile_register);
bool rt5682_readable_register(struct device *dev, unsigned int reg)
{
switch (reg) {
case RT5682_RESET:
case RT5682_VERSION_ID:
case RT5682_VENDOR_ID:
case RT5682_DEVICE_ID:
case RT5682_HP_CTRL_1:
case RT5682_HP_CTRL_2:
case RT5682_HPL_GAIN:
case RT5682_HPR_GAIN:
case RT5682_I2C_CTRL:
case RT5682_CBJ_BST_CTRL:
case RT5682_CBJ_CTRL_1:
case RT5682_CBJ_CTRL_2:
case RT5682_CBJ_CTRL_3:
case RT5682_CBJ_CTRL_4:
case RT5682_CBJ_CTRL_5:
case RT5682_CBJ_CTRL_6:
case RT5682_CBJ_CTRL_7:
case RT5682_DAC1_DIG_VOL:
case RT5682_STO1_ADC_DIG_VOL:
case RT5682_STO1_ADC_BOOST:
case RT5682_HP_IMP_GAIN_1:
case RT5682_HP_IMP_GAIN_2:
case RT5682_SIDETONE_CTRL:
case RT5682_STO1_ADC_MIXER:
case RT5682_AD_DA_MIXER:
case RT5682_STO1_DAC_MIXER:
case RT5682_A_DAC1_MUX:
case RT5682_DIG_INF2_DATA:
case RT5682_REC_MIXER:
case RT5682_CAL_REC:
case RT5682_ALC_BACK_GAIN:
case RT5682_PWR_DIG_1:
case RT5682_PWR_DIG_2:
case RT5682_PWR_ANLG_1:
case RT5682_PWR_ANLG_2:
case RT5682_PWR_ANLG_3:
case RT5682_PWR_MIXER:
case RT5682_PWR_VOL:
case RT5682_CLK_DET:
case RT5682_RESET_LPF_CTRL:
case RT5682_RESET_HPF_CTRL:
case RT5682_DMIC_CTRL_1:
case RT5682_I2S1_SDP:
case RT5682_I2S2_SDP:
case RT5682_ADDA_CLK_1:
case RT5682_ADDA_CLK_2:
case RT5682_I2S1_F_DIV_CTRL_1:
case RT5682_I2S1_F_DIV_CTRL_2:
case RT5682_TDM_CTRL:
case RT5682_TDM_ADDA_CTRL_1:
case RT5682_TDM_ADDA_CTRL_2:
case RT5682_DATA_SEL_CTRL_1:
case RT5682_TDM_TCON_CTRL:
case RT5682_GLB_CLK:
case RT5682_PLL_CTRL_1:
case RT5682_PLL_CTRL_2:
case RT5682_PLL_TRACK_1:
case RT5682_PLL_TRACK_2:
case RT5682_PLL_TRACK_3:
case RT5682_PLL_TRACK_4:
case RT5682_PLL_TRACK_5:
case RT5682_PLL_TRACK_6:
case RT5682_PLL_TRACK_11:
case RT5682_SDW_REF_CLK:
case RT5682_DEPOP_1:
case RT5682_DEPOP_2:
case RT5682_HP_CHARGE_PUMP_1:
case RT5682_HP_CHARGE_PUMP_2:
case RT5682_MICBIAS_1:
case RT5682_MICBIAS_2:
case RT5682_PLL_TRACK_12:
case RT5682_PLL_TRACK_14:
case RT5682_PLL2_CTRL_1:
case RT5682_PLL2_CTRL_2:
case RT5682_PLL2_CTRL_3:
case RT5682_PLL2_CTRL_4:
case RT5682_RC_CLK_CTRL:
case RT5682_I2S_M_CLK_CTRL_1:
case RT5682_I2S2_F_DIV_CTRL_1:
case RT5682_I2S2_F_DIV_CTRL_2:
case RT5682_EQ_CTRL_1:
case RT5682_EQ_CTRL_2:
case RT5682_IRQ_CTRL_1:
case RT5682_IRQ_CTRL_2:
case RT5682_IRQ_CTRL_3:
case RT5682_IRQ_CTRL_4:
case RT5682_INT_ST_1:
case RT5682_GPIO_CTRL_1:
case RT5682_GPIO_CTRL_2:
case RT5682_GPIO_CTRL_3:
case RT5682_HP_AMP_DET_CTRL_1:
case RT5682_HP_AMP_DET_CTRL_2:
case RT5682_MID_HP_AMP_DET:
case RT5682_LOW_HP_AMP_DET:
case RT5682_DELAY_BUF_CTRL:
case RT5682_SV_ZCD_1:
case RT5682_SV_ZCD_2:
case RT5682_IL_CMD_1:
case RT5682_IL_CMD_2:
case RT5682_IL_CMD_3:
case RT5682_IL_CMD_4:
case RT5682_IL_CMD_5:
case RT5682_IL_CMD_6:
case RT5682_4BTN_IL_CMD_1:
case RT5682_4BTN_IL_CMD_2:
case RT5682_4BTN_IL_CMD_3:
case RT5682_4BTN_IL_CMD_4:
case RT5682_4BTN_IL_CMD_5:
case RT5682_4BTN_IL_CMD_6:
case RT5682_4BTN_IL_CMD_7:
case RT5682_ADC_STO1_HP_CTRL_1:
case RT5682_ADC_STO1_HP_CTRL_2:
case RT5682_AJD1_CTRL:
case RT5682_JD1_THD:
case RT5682_JD2_THD:
case RT5682_JD_CTRL_1:
case RT5682_DUMMY_1:
case RT5682_DUMMY_2:
case RT5682_DUMMY_3:
case RT5682_DAC_ADC_DIG_VOL1:
case RT5682_BIAS_CUR_CTRL_2:
case RT5682_BIAS_CUR_CTRL_3:
case RT5682_BIAS_CUR_CTRL_4:
case RT5682_BIAS_CUR_CTRL_5:
case RT5682_BIAS_CUR_CTRL_6:
case RT5682_BIAS_CUR_CTRL_7:
case RT5682_BIAS_CUR_CTRL_8:
case RT5682_BIAS_CUR_CTRL_9:
case RT5682_BIAS_CUR_CTRL_10:
case RT5682_VREF_REC_OP_FB_CAP_CTRL:
case RT5682_CHARGE_PUMP_1:
case RT5682_DIG_IN_CTRL_1:
case RT5682_PAD_DRIVING_CTRL:
case RT5682_SOFT_RAMP_DEPOP:
case RT5682_CHOP_DAC:
case RT5682_CHOP_ADC:
case RT5682_CALIB_ADC_CTRL:
case RT5682_VOL_TEST:
case RT5682_SPKVDD_DET_STA:
case RT5682_TEST_MODE_CTRL_1:
case RT5682_TEST_MODE_CTRL_2:
case RT5682_TEST_MODE_CTRL_3:
case RT5682_TEST_MODE_CTRL_4:
case RT5682_TEST_MODE_CTRL_5:
case RT5682_PLL1_INTERNAL:
case RT5682_PLL2_INTERNAL:
case RT5682_STO_NG2_CTRL_1:
case RT5682_STO_NG2_CTRL_2:
case RT5682_STO_NG2_CTRL_3:
case RT5682_STO_NG2_CTRL_4:
case RT5682_STO_NG2_CTRL_5:
case RT5682_STO_NG2_CTRL_6:
case RT5682_STO_NG2_CTRL_7:
case RT5682_STO_NG2_CTRL_8:
case RT5682_STO_NG2_CTRL_9:
case RT5682_STO_NG2_CTRL_10:
case RT5682_STO1_DAC_SIL_DET:
case RT5682_SIL_PSV_CTRL1:
case RT5682_SIL_PSV_CTRL2:
case RT5682_SIL_PSV_CTRL3:
case RT5682_SIL_PSV_CTRL4:
case RT5682_SIL_PSV_CTRL5:
case RT5682_HP_IMP_SENS_CTRL_01:
case RT5682_HP_IMP_SENS_CTRL_02:
case RT5682_HP_IMP_SENS_CTRL_03:
case RT5682_HP_IMP_SENS_CTRL_04:
case RT5682_HP_IMP_SENS_CTRL_05:
case RT5682_HP_IMP_SENS_CTRL_06:
case RT5682_HP_IMP_SENS_CTRL_07:
case RT5682_HP_IMP_SENS_CTRL_08:
case RT5682_HP_IMP_SENS_CTRL_09:
case RT5682_HP_IMP_SENS_CTRL_10:
case RT5682_HP_IMP_SENS_CTRL_11:
case RT5682_HP_IMP_SENS_CTRL_12:
case RT5682_HP_IMP_SENS_CTRL_13:
case RT5682_HP_IMP_SENS_CTRL_14:
case RT5682_HP_IMP_SENS_CTRL_15:
case RT5682_HP_IMP_SENS_CTRL_16:
case RT5682_HP_IMP_SENS_CTRL_17:
case RT5682_HP_IMP_SENS_CTRL_18:
case RT5682_HP_IMP_SENS_CTRL_19:
case RT5682_HP_IMP_SENS_CTRL_20:
case RT5682_HP_IMP_SENS_CTRL_21:
case RT5682_HP_IMP_SENS_CTRL_22:
case RT5682_HP_IMP_SENS_CTRL_23:
case RT5682_HP_IMP_SENS_CTRL_24:
case RT5682_HP_IMP_SENS_CTRL_25:
case RT5682_HP_IMP_SENS_CTRL_26:
case RT5682_HP_IMP_SENS_CTRL_27:
case RT5682_HP_IMP_SENS_CTRL_28:
case RT5682_HP_IMP_SENS_CTRL_29:
case RT5682_HP_IMP_SENS_CTRL_30:
case RT5682_HP_IMP_SENS_CTRL_31:
case RT5682_HP_IMP_SENS_CTRL_32:
case RT5682_HP_IMP_SENS_CTRL_33:
case RT5682_HP_IMP_SENS_CTRL_34:
case RT5682_HP_IMP_SENS_CTRL_35:
case RT5682_HP_IMP_SENS_CTRL_36:
case RT5682_HP_IMP_SENS_CTRL_37:
case RT5682_HP_IMP_SENS_CTRL_38:
case RT5682_HP_IMP_SENS_CTRL_39:
case RT5682_HP_IMP_SENS_CTRL_40:
case RT5682_HP_IMP_SENS_CTRL_41:
case RT5682_HP_IMP_SENS_CTRL_42:
case RT5682_HP_IMP_SENS_CTRL_43:
case RT5682_HP_LOGIC_CTRL_1:
case RT5682_HP_LOGIC_CTRL_2:
case RT5682_HP_LOGIC_CTRL_3:
case RT5682_HP_CALIB_CTRL_1:
case RT5682_HP_CALIB_CTRL_2:
case RT5682_HP_CALIB_CTRL_3:
case RT5682_HP_CALIB_CTRL_4:
case RT5682_HP_CALIB_CTRL_5:
case RT5682_HP_CALIB_CTRL_6:
case RT5682_HP_CALIB_CTRL_7:
case RT5682_HP_CALIB_CTRL_9:
case RT5682_HP_CALIB_CTRL_10:
case RT5682_HP_CALIB_CTRL_11:
case RT5682_HP_CALIB_STA_1:
case RT5682_HP_CALIB_STA_2:
case RT5682_HP_CALIB_STA_3:
case RT5682_HP_CALIB_STA_4:
case RT5682_HP_CALIB_STA_5:
case RT5682_HP_CALIB_STA_6:
case RT5682_HP_CALIB_STA_7:
case RT5682_HP_CALIB_STA_8:
case RT5682_HP_CALIB_STA_9:
case RT5682_HP_CALIB_STA_10:
case RT5682_HP_CALIB_STA_11:
case RT5682_SAR_IL_CMD_1:
case RT5682_SAR_IL_CMD_2:
case RT5682_SAR_IL_CMD_3:
case RT5682_SAR_IL_CMD_4:
case RT5682_SAR_IL_CMD_5:
case RT5682_SAR_IL_CMD_6:
case RT5682_SAR_IL_CMD_7:
case RT5682_SAR_IL_CMD_8:
case RT5682_SAR_IL_CMD_9:
case RT5682_SAR_IL_CMD_10:
case RT5682_SAR_IL_CMD_11:
case RT5682_SAR_IL_CMD_12:
case RT5682_SAR_IL_CMD_13:
case RT5682_EFUSE_CTRL_1:
case RT5682_EFUSE_CTRL_2:
case RT5682_EFUSE_CTRL_3:
case RT5682_EFUSE_CTRL_4:
case RT5682_EFUSE_CTRL_5:
case RT5682_EFUSE_CTRL_6:
case RT5682_EFUSE_CTRL_7:
case RT5682_EFUSE_CTRL_8:
case RT5682_EFUSE_CTRL_9:
case RT5682_EFUSE_CTRL_10:
case RT5682_EFUSE_CTRL_11:
case RT5682_JD_TOP_VC_VTRL:
case RT5682_DRC1_CTRL_0:
case RT5682_DRC1_CTRL_1:
case RT5682_DRC1_CTRL_2:
case RT5682_DRC1_CTRL_3:
case RT5682_DRC1_CTRL_4:
case RT5682_DRC1_CTRL_5:
case RT5682_DRC1_CTRL_6:
case RT5682_DRC1_HARD_LMT_CTRL_1:
case RT5682_DRC1_HARD_LMT_CTRL_2:
case RT5682_DRC1_PRIV_1:
case RT5682_DRC1_PRIV_2:
case RT5682_DRC1_PRIV_3:
case RT5682_DRC1_PRIV_4:
case RT5682_DRC1_PRIV_5:
case RT5682_DRC1_PRIV_6:
case RT5682_DRC1_PRIV_7:
case RT5682_DRC1_PRIV_8:
case RT5682_EQ_AUTO_RCV_CTRL1:
case RT5682_EQ_AUTO_RCV_CTRL2:
case RT5682_EQ_AUTO_RCV_CTRL3:
case RT5682_EQ_AUTO_RCV_CTRL4:
case RT5682_EQ_AUTO_RCV_CTRL5:
case RT5682_EQ_AUTO_RCV_CTRL6:
case RT5682_EQ_AUTO_RCV_CTRL7:
case RT5682_EQ_AUTO_RCV_CTRL8:
case RT5682_EQ_AUTO_RCV_CTRL9:
case RT5682_EQ_AUTO_RCV_CTRL10:
case RT5682_EQ_AUTO_RCV_CTRL11:
case RT5682_EQ_AUTO_RCV_CTRL12:
case RT5682_EQ_AUTO_RCV_CTRL13:
case RT5682_ADC_L_EQ_LPF1_A1:
case RT5682_R_EQ_LPF1_A1:
case RT5682_L_EQ_LPF1_H0:
case RT5682_R_EQ_LPF1_H0:
case RT5682_L_EQ_BPF1_A1:
case RT5682_R_EQ_BPF1_A1:
case RT5682_L_EQ_BPF1_A2:
case RT5682_R_EQ_BPF1_A2:
case RT5682_L_EQ_BPF1_H0:
case RT5682_R_EQ_BPF1_H0:
case RT5682_L_EQ_BPF2_A1:
case RT5682_R_EQ_BPF2_A1:
case RT5682_L_EQ_BPF2_A2:
case RT5682_R_EQ_BPF2_A2:
case RT5682_L_EQ_BPF2_H0:
case RT5682_R_EQ_BPF2_H0:
case RT5682_L_EQ_BPF3_A1:
case RT5682_R_EQ_BPF3_A1:
case RT5682_L_EQ_BPF3_A2:
case RT5682_R_EQ_BPF3_A2:
case RT5682_L_EQ_BPF3_H0:
case RT5682_R_EQ_BPF3_H0:
case RT5682_L_EQ_BPF4_A1:
case RT5682_R_EQ_BPF4_A1:
case RT5682_L_EQ_BPF4_A2:
case RT5682_R_EQ_BPF4_A2:
case RT5682_L_EQ_BPF4_H0:
case RT5682_R_EQ_BPF4_H0:
case RT5682_L_EQ_HPF1_A1:
case RT5682_R_EQ_HPF1_A1:
case RT5682_L_EQ_HPF1_H0:
case RT5682_R_EQ_HPF1_H0:
case RT5682_L_EQ_PRE_VOL:
case RT5682_R_EQ_PRE_VOL:
case RT5682_L_EQ_POST_VOL:
case RT5682_R_EQ_POST_VOL:
case RT5682_I2C_MODE:
return true;
default:
return false;
}
}
EXPORT_SYMBOL_GPL(rt5682_readable_register);
static const DECLARE_TLV_DB_SCALE(dac_vol_tlv, -6525, 75, 0);
static const DECLARE_TLV_DB_SCALE(adc_vol_tlv, -1725, 75, 0);
static const DECLARE_TLV_DB_SCALE(adc_bst_tlv, 0, 1200, 0);
/* {0, +20, +24, +30, +35, +40, +44, +50, +52} dB */
static const DECLARE_TLV_DB_RANGE(bst_tlv,
0, 0, TLV_DB_SCALE_ITEM(0, 0, 0),
1, 1, TLV_DB_SCALE_ITEM(2000, 0, 0),
2, 2, TLV_DB_SCALE_ITEM(2400, 0, 0),
3, 5, TLV_DB_SCALE_ITEM(3000, 500, 0),
6, 6, TLV_DB_SCALE_ITEM(4400, 0, 0),
7, 7, TLV_DB_SCALE_ITEM(5000, 0, 0),
8, 8, TLV_DB_SCALE_ITEM(5200, 0, 0)
);
/* Interface data select */
static const char * const rt5682_data_select[] = {
"L/R", "R/L", "L/L", "R/R"
};
static SOC_ENUM_SINGLE_DECL(rt5682_if2_adc_enum,
RT5682_DIG_INF2_DATA, RT5682_IF2_ADC_SEL_SFT, rt5682_data_select);
static SOC_ENUM_SINGLE_DECL(rt5682_if1_01_adc_enum,
RT5682_TDM_ADDA_CTRL_1, RT5682_IF1_ADC1_SEL_SFT, rt5682_data_select);
static SOC_ENUM_SINGLE_DECL(rt5682_if1_23_adc_enum,
RT5682_TDM_ADDA_CTRL_1, RT5682_IF1_ADC2_SEL_SFT, rt5682_data_select);
static SOC_ENUM_SINGLE_DECL(rt5682_if1_45_adc_enum,
RT5682_TDM_ADDA_CTRL_1, RT5682_IF1_ADC3_SEL_SFT, rt5682_data_select);
static SOC_ENUM_SINGLE_DECL(rt5682_if1_67_adc_enum,
RT5682_TDM_ADDA_CTRL_1, RT5682_IF1_ADC4_SEL_SFT, rt5682_data_select);
static const struct snd_kcontrol_new rt5682_if2_adc_swap_mux =
SOC_DAPM_ENUM("IF2 ADC Swap Mux", rt5682_if2_adc_enum);
static const struct snd_kcontrol_new rt5682_if1_01_adc_swap_mux =
SOC_DAPM_ENUM("IF1 01 ADC Swap Mux", rt5682_if1_01_adc_enum);
static const struct snd_kcontrol_new rt5682_if1_23_adc_swap_mux =
SOC_DAPM_ENUM("IF1 23 ADC Swap Mux", rt5682_if1_23_adc_enum);
static const struct snd_kcontrol_new rt5682_if1_45_adc_swap_mux =
SOC_DAPM_ENUM("IF1 45 ADC Swap Mux", rt5682_if1_45_adc_enum);
static const struct snd_kcontrol_new rt5682_if1_67_adc_swap_mux =
SOC_DAPM_ENUM("IF1 67 ADC Swap Mux", rt5682_if1_67_adc_enum);
static const char * const rt5682_dac_select[] = {
"IF1", "SOUND"
};
static SOC_ENUM_SINGLE_DECL(rt5682_dacl_enum,
RT5682_AD_DA_MIXER, RT5682_DAC1_L_SEL_SFT, rt5682_dac_select);
static const struct snd_kcontrol_new rt5682_dac_l_mux =
SOC_DAPM_ENUM("DAC L Mux", rt5682_dacl_enum);
static SOC_ENUM_SINGLE_DECL(rt5682_dacr_enum,
RT5682_AD_DA_MIXER, RT5682_DAC1_R_SEL_SFT, rt5682_dac_select);
static const struct snd_kcontrol_new rt5682_dac_r_mux =
SOC_DAPM_ENUM("DAC R Mux", rt5682_dacr_enum);
void rt5682_reset(struct rt5682_priv *rt5682)
{
regmap_write(rt5682->regmap, RT5682_RESET, 0);
if (!rt5682->is_sdw)
regmap_write(rt5682->regmap, RT5682_I2C_MODE, 1);
}
EXPORT_SYMBOL_GPL(rt5682_reset);
/**
* rt5682_sel_asrc_clk_src - select ASRC clock source for a set of filters
* @component: SoC audio component device.
* @filter_mask: mask of filters.
* @clk_src: clock source
*
* The ASRC function is for asynchronous MCLK and LRCK. Also, since RT5682 can
* only support standard 32fs or 64fs i2s format, ASRC should be enabled to
* support special i2s clock format such as Intel's 100fs(100 * sampling rate).
* ASRC function will track i2s clock and generate a corresponding system clock
* for codec. This function provides an API to select the clock source for a
* set of filters specified by the mask. And the component driver will turn on
* ASRC for these filters if ASRC is selected as their clock source.
*/
int rt5682_sel_asrc_clk_src(struct snd_soc_component *component,
unsigned int filter_mask, unsigned int clk_src)
{
switch (clk_src) {
case RT5682_CLK_SEL_SYS:
case RT5682_CLK_SEL_I2S1_ASRC:
case RT5682_CLK_SEL_I2S2_ASRC:
break;
default:
return -EINVAL;
}
if (filter_mask & RT5682_DA_STEREO1_FILTER) {
snd_soc_component_update_bits(component, RT5682_PLL_TRACK_2,
RT5682_FILTER_CLK_SEL_MASK,
clk_src << RT5682_FILTER_CLK_SEL_SFT);
}
if (filter_mask & RT5682_AD_STEREO1_FILTER) {
snd_soc_component_update_bits(component, RT5682_PLL_TRACK_3,
RT5682_FILTER_CLK_SEL_MASK,
clk_src << RT5682_FILTER_CLK_SEL_SFT);
}
return 0;
}
EXPORT_SYMBOL_GPL(rt5682_sel_asrc_clk_src);
static int rt5682_button_detect(struct snd_soc_component *component)
{
int btn_type, val;
val = snd_soc_component_read(component, RT5682_4BTN_IL_CMD_1);
btn_type = val & 0xfff0;
snd_soc_component_write(component, RT5682_4BTN_IL_CMD_1, val);
dev_dbg(component->dev, "%s btn_type=%x\n", __func__, btn_type);
snd_soc_component_update_bits(component,
RT5682_SAR_IL_CMD_2, 0x10, 0x10);
return btn_type;
}
static void rt5682_enable_push_button_irq(struct snd_soc_component *component,
bool enable)
{
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
if (enable) {
snd_soc_component_update_bits(component, RT5682_SAR_IL_CMD_1,
RT5682_SAR_BUTT_DET_MASK, RT5682_SAR_BUTT_DET_EN);
snd_soc_component_update_bits(component, RT5682_SAR_IL_CMD_13,
RT5682_SAR_SOUR_MASK, RT5682_SAR_SOUR_BTN);
snd_soc_component_write(component, RT5682_IL_CMD_1, 0x0040);
snd_soc_component_update_bits(component, RT5682_4BTN_IL_CMD_2,
RT5682_4BTN_IL_MASK | RT5682_4BTN_IL_RST_MASK,
RT5682_4BTN_IL_EN | RT5682_4BTN_IL_NOR);
if (rt5682->is_sdw)
snd_soc_component_update_bits(component,
RT5682_IRQ_CTRL_3,
RT5682_IL_IRQ_MASK | RT5682_IL_IRQ_TYPE_MASK,
RT5682_IL_IRQ_EN | RT5682_IL_IRQ_PUL);
else
snd_soc_component_update_bits(component,
RT5682_IRQ_CTRL_3, RT5682_IL_IRQ_MASK,
RT5682_IL_IRQ_EN);
} else {
snd_soc_component_update_bits(component, RT5682_IRQ_CTRL_3,
RT5682_IL_IRQ_MASK, RT5682_IL_IRQ_DIS);
snd_soc_component_update_bits(component, RT5682_SAR_IL_CMD_1,
RT5682_SAR_BUTT_DET_MASK, RT5682_SAR_BUTT_DET_DIS);
snd_soc_component_update_bits(component, RT5682_4BTN_IL_CMD_2,
RT5682_4BTN_IL_MASK, RT5682_4BTN_IL_DIS);
snd_soc_component_update_bits(component, RT5682_4BTN_IL_CMD_2,
RT5682_4BTN_IL_RST_MASK, RT5682_4BTN_IL_RST);
snd_soc_component_update_bits(component, RT5682_SAR_IL_CMD_13,
RT5682_SAR_SOUR_MASK, RT5682_SAR_SOUR_TYPE);
}
}
/**
* rt5682_headset_detect - Detect headset.
* @component: SoC audio component device.
* @jack_insert: Jack insert or not.
*
* Detect whether is headset or not when jack inserted.
*
* Returns detect status.
*/
int rt5682_headset_detect(struct snd_soc_component *component, int jack_insert)
{
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
struct snd_soc_dapm_context *dapm = &component->dapm;
unsigned int val, count;
if (jack_insert) {
snd_soc_component_update_bits(component, RT5682_PWR_ANLG_1,
RT5682_PWR_VREF2 | RT5682_PWR_MB,
RT5682_PWR_VREF2 | RT5682_PWR_MB);
snd_soc_component_update_bits(component,
RT5682_PWR_ANLG_1, RT5682_PWR_FV2, 0);
usleep_range(15000, 20000);
snd_soc_component_update_bits(component,
RT5682_PWR_ANLG_1, RT5682_PWR_FV2, RT5682_PWR_FV2);
snd_soc_component_update_bits(component, RT5682_PWR_ANLG_3,
RT5682_PWR_CBJ, RT5682_PWR_CBJ);
snd_soc_component_update_bits(component,
RT5682_HP_CHARGE_PUMP_1,
RT5682_OSW_L_MASK | RT5682_OSW_R_MASK, 0);
snd_soc_component_update_bits(component, RT5682_CBJ_CTRL_1,
RT5682_TRIG_JD_MASK, RT5682_TRIG_JD_HIGH);
count = 0;
val = snd_soc_component_read(component, RT5682_CBJ_CTRL_2)
& RT5682_JACK_TYPE_MASK;
while (val == 0 && count < 50) {
usleep_range(10000, 15000);
val = snd_soc_component_read(component,
RT5682_CBJ_CTRL_2) & RT5682_JACK_TYPE_MASK;
count++;
}
switch (val) {
case 0x1:
case 0x2:
rt5682->jack_type = SND_JACK_HEADSET;
rt5682_enable_push_button_irq(component, true);
break;
default:
rt5682->jack_type = SND_JACK_HEADPHONE;
break;
}
snd_soc_component_update_bits(component,
RT5682_HP_CHARGE_PUMP_1,
RT5682_OSW_L_MASK | RT5682_OSW_R_MASK,
RT5682_OSW_L_EN | RT5682_OSW_R_EN);
snd_soc_component_update_bits(component, RT5682_MICBIAS_2,
RT5682_PWR_CLK25M_MASK | RT5682_PWR_CLK1M_MASK,
RT5682_PWR_CLK25M_PU | RT5682_PWR_CLK1M_PU);
} else {
rt5682_enable_push_button_irq(component, false);
snd_soc_component_update_bits(component, RT5682_CBJ_CTRL_1,
RT5682_TRIG_JD_MASK, RT5682_TRIG_JD_LOW);
if (!snd_soc_dapm_get_pin_status(dapm, "MICBIAS"))
snd_soc_component_update_bits(component,
RT5682_PWR_ANLG_1, RT5682_PWR_MB, 0);
if (!snd_soc_dapm_get_pin_status(dapm, "Vref2"))
snd_soc_component_update_bits(component,
RT5682_PWR_ANLG_1, RT5682_PWR_VREF2, 0);
snd_soc_component_update_bits(component, RT5682_PWR_ANLG_3,
RT5682_PWR_CBJ, 0);
snd_soc_component_update_bits(component, RT5682_MICBIAS_2,
RT5682_PWR_CLK25M_MASK | RT5682_PWR_CLK1M_MASK,
RT5682_PWR_CLK25M_PD | RT5682_PWR_CLK1M_PD);
rt5682->jack_type = 0;
}
dev_dbg(component->dev, "jack_type = %d\n", rt5682->jack_type);
return rt5682->jack_type;
}
EXPORT_SYMBOL_GPL(rt5682_headset_detect);
static int rt5682_set_jack_detect(struct snd_soc_component *component,
struct snd_soc_jack *hs_jack, void *data)
{
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
rt5682->hs_jack = hs_jack;
if (!hs_jack) {
regmap_update_bits(rt5682->regmap, RT5682_IRQ_CTRL_2,
RT5682_JD1_EN_MASK, RT5682_JD1_DIS);
regmap_update_bits(rt5682->regmap, RT5682_RC_CLK_CTRL,
RT5682_POW_JDH | RT5682_POW_JDL, 0);
cancel_delayed_work_sync(&rt5682->jack_detect_work);
return 0;
}
if (!rt5682->is_sdw) {
switch (rt5682->pdata.jd_src) {
case RT5682_JD1:
snd_soc_component_update_bits(component,
RT5682_CBJ_CTRL_2, RT5682_EXT_JD_SRC,
RT5682_EXT_JD_SRC_MANUAL);
snd_soc_component_write(component, RT5682_CBJ_CTRL_1,
0xd042);
snd_soc_component_update_bits(component,
RT5682_CBJ_CTRL_3, RT5682_CBJ_IN_BUF_EN,
RT5682_CBJ_IN_BUF_EN);
snd_soc_component_update_bits(component,
RT5682_SAR_IL_CMD_1, RT5682_SAR_POW_MASK,
RT5682_SAR_POW_EN);
regmap_update_bits(rt5682->regmap, RT5682_GPIO_CTRL_1,
RT5682_GP1_PIN_MASK, RT5682_GP1_PIN_IRQ);
regmap_update_bits(rt5682->regmap, RT5682_RC_CLK_CTRL,
RT5682_POW_IRQ | RT5682_POW_JDH |
RT5682_POW_ANA, RT5682_POW_IRQ |
RT5682_POW_JDH | RT5682_POW_ANA);
regmap_update_bits(rt5682->regmap, RT5682_PWR_ANLG_2,
RT5682_PWR_JDH, RT5682_PWR_JDH);
regmap_update_bits(rt5682->regmap, RT5682_IRQ_CTRL_2,
RT5682_JD1_EN_MASK | RT5682_JD1_POL_MASK,
RT5682_JD1_EN | RT5682_JD1_POL_NOR);
regmap_update_bits(rt5682->regmap, RT5682_4BTN_IL_CMD_4,
0x7f7f, (rt5682->pdata.btndet_delay << 8 |
rt5682->pdata.btndet_delay));
regmap_update_bits(rt5682->regmap, RT5682_4BTN_IL_CMD_5,
0x7f7f, (rt5682->pdata.btndet_delay << 8 |
rt5682->pdata.btndet_delay));
regmap_update_bits(rt5682->regmap, RT5682_4BTN_IL_CMD_6,
0x7f7f, (rt5682->pdata.btndet_delay << 8 |
rt5682->pdata.btndet_delay));
regmap_update_bits(rt5682->regmap, RT5682_4BTN_IL_CMD_7,
0x7f7f, (rt5682->pdata.btndet_delay << 8 |
rt5682->pdata.btndet_delay));
mod_delayed_work(system_power_efficient_wq,
&rt5682->jack_detect_work,
msecs_to_jiffies(250));
break;
case RT5682_JD_NULL:
regmap_update_bits(rt5682->regmap, RT5682_IRQ_CTRL_2,
RT5682_JD1_EN_MASK, RT5682_JD1_DIS);
regmap_update_bits(rt5682->regmap, RT5682_RC_CLK_CTRL,
RT5682_POW_JDH | RT5682_POW_JDL, 0);
break;
default:
dev_warn(component->dev, "Wrong JD source\n");
break;
}
}
return 0;
}
void rt5682_jack_detect_handler(struct work_struct *work)
{
struct rt5682_priv *rt5682 =
container_of(work, struct rt5682_priv, jack_detect_work.work);
int val, btn_type;
while (!rt5682->component)
usleep_range(10000, 15000);
while (!rt5682->component->card->instantiated)
usleep_range(10000, 15000);
mutex_lock(&rt5682->calibrate_mutex);
val = snd_soc_component_read(rt5682->component, RT5682_AJD1_CTRL)
& RT5682_JDH_RS_MASK;
if (!val) {
/* jack in */
if (rt5682->jack_type == 0) {
/* jack was out, report jack type */
rt5682->jack_type =
rt5682_headset_detect(rt5682->component, 1);
} else if ((rt5682->jack_type & SND_JACK_HEADSET) ==
SND_JACK_HEADSET) {
/* jack is already in, report button event */
rt5682->jack_type = SND_JACK_HEADSET;
btn_type = rt5682_button_detect(rt5682->component);
/**
* rt5682 can report three kinds of button behavior,
* one click, double click and hold. However,
* currently we will report button pressed/released
* event. So all the three button behaviors are
* treated as button pressed.
*/
switch (btn_type) {
case 0x8000:
case 0x4000:
case 0x2000:
rt5682->jack_type |= SND_JACK_BTN_0;
break;
case 0x1000:
case 0x0800:
case 0x0400:
rt5682->jack_type |= SND_JACK_BTN_1;
break;
case 0x0200:
case 0x0100:
case 0x0080:
rt5682->jack_type |= SND_JACK_BTN_2;
break;
case 0x0040:
case 0x0020:
case 0x0010:
rt5682->jack_type |= SND_JACK_BTN_3;
break;
case 0x0000: /* unpressed */
break;
default:
dev_err(rt5682->component->dev,
"Unexpected button code 0x%04x\n",
btn_type);
break;
}
}
} else {
/* jack out */
rt5682->jack_type = rt5682_headset_detect(rt5682->component, 0);
}
snd_soc_jack_report(rt5682->hs_jack, rt5682->jack_type,
SND_JACK_HEADSET |
SND_JACK_BTN_0 | SND_JACK_BTN_1 |
SND_JACK_BTN_2 | SND_JACK_BTN_3);
if (!rt5682->is_sdw) {
if (rt5682->jack_type & (SND_JACK_BTN_0 | SND_JACK_BTN_1 |
SND_JACK_BTN_2 | SND_JACK_BTN_3))
schedule_delayed_work(&rt5682->jd_check_work, 0);
else
cancel_delayed_work_sync(&rt5682->jd_check_work);
}
mutex_unlock(&rt5682->calibrate_mutex);
}
EXPORT_SYMBOL_GPL(rt5682_jack_detect_handler);
static const struct snd_kcontrol_new rt5682_snd_controls[] = {
/* DAC Digital Volume */
SOC_DOUBLE_TLV("DAC1 Playback Volume", RT5682_DAC1_DIG_VOL,
RT5682_L_VOL_SFT + 1, RT5682_R_VOL_SFT + 1, 87, 0, dac_vol_tlv),
/* IN Boost Volume */
SOC_SINGLE_TLV("CBJ Boost Volume", RT5682_CBJ_BST_CTRL,
RT5682_BST_CBJ_SFT, 8, 0, bst_tlv),
/* ADC Digital Volume Control */
SOC_DOUBLE("STO1 ADC Capture Switch", RT5682_STO1_ADC_DIG_VOL,
RT5682_L_MUTE_SFT, RT5682_R_MUTE_SFT, 1, 1),
SOC_DOUBLE_TLV("STO1 ADC Capture Volume", RT5682_STO1_ADC_DIG_VOL,
RT5682_L_VOL_SFT + 1, RT5682_R_VOL_SFT + 1, 63, 0, adc_vol_tlv),
/* ADC Boost Volume Control */
SOC_DOUBLE_TLV("STO1 ADC Boost Gain Volume", RT5682_STO1_ADC_BOOST,
RT5682_STO1_ADC_L_BST_SFT, RT5682_STO1_ADC_R_BST_SFT,
3, 0, adc_bst_tlv),
};
static int rt5682_div_sel(struct rt5682_priv *rt5682,
int target, const int div[], int size)
{
int i;
if (rt5682->sysclk < target) {
dev_err(rt5682->component->dev,
"sysclk rate %d is too low\n", rt5682->sysclk);
return 0;
}
for (i = 0; i < size - 1; i++) {
dev_dbg(rt5682->component->dev, "div[%d]=%d\n", i, div[i]);
if (target * div[i] == rt5682->sysclk)
return i;
if (target * div[i + 1] > rt5682->sysclk) {
dev_dbg(rt5682->component->dev,
"can't find div for sysclk %d\n",
rt5682->sysclk);
return i;
}
}
if (target * div[i] < rt5682->sysclk)
dev_err(rt5682->component->dev,
"sysclk rate %d is too high\n", rt5682->sysclk);
return size - 1;
}
/**
* set_dmic_clk - Set parameter of dmic.
*
* @w: DAPM widget.
* @kcontrol: The kcontrol of this widget.
* @event: Event id.
*
* Choose dmic clock between 1MHz and 3MHz.
* It is better for clock to approximate 3MHz.
*/
static int set_dmic_clk(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_component *component =
snd_soc_dapm_to_component(w->dapm);
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
int idx = -EINVAL, dmic_clk_rate = 3072000;
static const int div[] = {2, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128};
if (rt5682->pdata.dmic_clk_rate)
dmic_clk_rate = rt5682->pdata.dmic_clk_rate;
idx = rt5682_div_sel(rt5682, dmic_clk_rate, div, ARRAY_SIZE(div));
snd_soc_component_update_bits(component, RT5682_DMIC_CTRL_1,
RT5682_DMIC_CLK_MASK, idx << RT5682_DMIC_CLK_SFT);
return 0;
}
static int set_filter_clk(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_component *component =
snd_soc_dapm_to_component(w->dapm);
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
int ref, val, reg, idx = -EINVAL;
static const int div_f[] = {1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48};
static const int div_o[] = {1, 2, 4, 6, 8, 12, 16, 24, 32, 48};
if (rt5682->is_sdw)
return 0;
val = snd_soc_component_read(component, RT5682_GPIO_CTRL_1) &
RT5682_GP4_PIN_MASK;
if (w->shift == RT5682_PWR_ADC_S1F_BIT &&
val == RT5682_GP4_PIN_ADCDAT2)
ref = 256 * rt5682->lrck[RT5682_AIF2];
else
ref = 256 * rt5682->lrck[RT5682_AIF1];
idx = rt5682_div_sel(rt5682, ref, div_f, ARRAY_SIZE(div_f));
if (w->shift == RT5682_PWR_ADC_S1F_BIT)
reg = RT5682_PLL_TRACK_3;
else
reg = RT5682_PLL_TRACK_2;
snd_soc_component_update_bits(component, reg,
RT5682_FILTER_CLK_DIV_MASK, idx << RT5682_FILTER_CLK_DIV_SFT);
/* select over sample rate */
for (idx = 0; idx < ARRAY_SIZE(div_o); idx++) {
if (rt5682->sysclk <= 12288000 * div_o[idx])
break;
}
snd_soc_component_update_bits(component, RT5682_ADDA_CLK_1,
RT5682_ADC_OSR_MASK | RT5682_DAC_OSR_MASK,
(idx << RT5682_ADC_OSR_SFT) | (idx << RT5682_DAC_OSR_SFT));
return 0;
}
static int is_sys_clk_from_pll1(struct snd_soc_dapm_widget *w,
struct snd_soc_dapm_widget *sink)
{
unsigned int val;
struct snd_soc_component *component =
snd_soc_dapm_to_component(w->dapm);
val = snd_soc_component_read(component, RT5682_GLB_CLK);
val &= RT5682_SCLK_SRC_MASK;
if (val == RT5682_SCLK_SRC_PLL1)
return 1;
else
return 0;
}
static int is_sys_clk_from_pll2(struct snd_soc_dapm_widget *w,
struct snd_soc_dapm_widget *sink)
{
unsigned int val;
struct snd_soc_component *component =
snd_soc_dapm_to_component(w->dapm);
val = snd_soc_component_read(component, RT5682_GLB_CLK);
val &= RT5682_SCLK_SRC_MASK;
if (val == RT5682_SCLK_SRC_PLL2)
return 1;
else
return 0;
}
static int is_using_asrc(struct snd_soc_dapm_widget *w,
struct snd_soc_dapm_widget *sink)
{
unsigned int reg, shift, val;
struct snd_soc_component *component =
snd_soc_dapm_to_component(w->dapm);
switch (w->shift) {
case RT5682_ADC_STO1_ASRC_SFT:
reg = RT5682_PLL_TRACK_3;
shift = RT5682_FILTER_CLK_SEL_SFT;
break;
case RT5682_DAC_STO1_ASRC_SFT:
reg = RT5682_PLL_TRACK_2;
shift = RT5682_FILTER_CLK_SEL_SFT;
break;
default:
return 0;
}
val = (snd_soc_component_read(component, reg) >> shift) & 0xf;
switch (val) {
case RT5682_CLK_SEL_I2S1_ASRC:
case RT5682_CLK_SEL_I2S2_ASRC:
return 1;
default:
return 0;
}
}
/* Digital Mixer */
static const struct snd_kcontrol_new rt5682_sto1_adc_l_mix[] = {
SOC_DAPM_SINGLE("ADC1 Switch", RT5682_STO1_ADC_MIXER,
RT5682_M_STO1_ADC_L1_SFT, 1, 1),
SOC_DAPM_SINGLE("ADC2 Switch", RT5682_STO1_ADC_MIXER,
RT5682_M_STO1_ADC_L2_SFT, 1, 1),
};
static const struct snd_kcontrol_new rt5682_sto1_adc_r_mix[] = {
SOC_DAPM_SINGLE("ADC1 Switch", RT5682_STO1_ADC_MIXER,
RT5682_M_STO1_ADC_R1_SFT, 1, 1),
SOC_DAPM_SINGLE("ADC2 Switch", RT5682_STO1_ADC_MIXER,
RT5682_M_STO1_ADC_R2_SFT, 1, 1),
};
static const struct snd_kcontrol_new rt5682_dac_l_mix[] = {
SOC_DAPM_SINGLE("Stereo ADC Switch", RT5682_AD_DA_MIXER,
RT5682_M_ADCMIX_L_SFT, 1, 1),
SOC_DAPM_SINGLE("DAC1 Switch", RT5682_AD_DA_MIXER,
RT5682_M_DAC1_L_SFT, 1, 1),
};
static const struct snd_kcontrol_new rt5682_dac_r_mix[] = {
SOC_DAPM_SINGLE("Stereo ADC Switch", RT5682_AD_DA_MIXER,
RT5682_M_ADCMIX_R_SFT, 1, 1),
SOC_DAPM_SINGLE("DAC1 Switch", RT5682_AD_DA_MIXER,
RT5682_M_DAC1_R_SFT, 1, 1),
};
static const struct snd_kcontrol_new rt5682_sto1_dac_l_mix[] = {
SOC_DAPM_SINGLE("DAC L1 Switch", RT5682_STO1_DAC_MIXER,
RT5682_M_DAC_L1_STO_L_SFT, 1, 1),
SOC_DAPM_SINGLE("DAC R1 Switch", RT5682_STO1_DAC_MIXER,
RT5682_M_DAC_R1_STO_L_SFT, 1, 1),
};
static const struct snd_kcontrol_new rt5682_sto1_dac_r_mix[] = {
SOC_DAPM_SINGLE("DAC L1 Switch", RT5682_STO1_DAC_MIXER,
RT5682_M_DAC_L1_STO_R_SFT, 1, 1),
SOC_DAPM_SINGLE("DAC R1 Switch", RT5682_STO1_DAC_MIXER,
RT5682_M_DAC_R1_STO_R_SFT, 1, 1),
};
/* Analog Input Mixer */
static const struct snd_kcontrol_new rt5682_rec1_l_mix[] = {
SOC_DAPM_SINGLE("CBJ Switch", RT5682_REC_MIXER,
RT5682_M_CBJ_RM1_L_SFT, 1, 1),
};
/* STO1 ADC1 Source */
/* MX-26 [13] [5] */
static const char * const rt5682_sto1_adc1_src[] = {
"DAC MIX", "ADC"
};
static SOC_ENUM_SINGLE_DECL(
rt5682_sto1_adc1l_enum, RT5682_STO1_ADC_MIXER,
RT5682_STO1_ADC1L_SRC_SFT, rt5682_sto1_adc1_src);
static const struct snd_kcontrol_new rt5682_sto1_adc1l_mux =
SOC_DAPM_ENUM("Stereo1 ADC1L Source", rt5682_sto1_adc1l_enum);
static SOC_ENUM_SINGLE_DECL(
rt5682_sto1_adc1r_enum, RT5682_STO1_ADC_MIXER,
RT5682_STO1_ADC1R_SRC_SFT, rt5682_sto1_adc1_src);
static const struct snd_kcontrol_new rt5682_sto1_adc1r_mux =
SOC_DAPM_ENUM("Stereo1 ADC1L Source", rt5682_sto1_adc1r_enum);
/* STO1 ADC Source */
/* MX-26 [11:10] [3:2] */
static const char * const rt5682_sto1_adc_src[] = {
"ADC1 L", "ADC1 R"
};
static SOC_ENUM_SINGLE_DECL(
rt5682_sto1_adcl_enum, RT5682_STO1_ADC_MIXER,
RT5682_STO1_ADCL_SRC_SFT, rt5682_sto1_adc_src);
static const struct snd_kcontrol_new rt5682_sto1_adcl_mux =
SOC_DAPM_ENUM("Stereo1 ADCL Source", rt5682_sto1_adcl_enum);
static SOC_ENUM_SINGLE_DECL(
rt5682_sto1_adcr_enum, RT5682_STO1_ADC_MIXER,
RT5682_STO1_ADCR_SRC_SFT, rt5682_sto1_adc_src);
static const struct snd_kcontrol_new rt5682_sto1_adcr_mux =
SOC_DAPM_ENUM("Stereo1 ADCR Source", rt5682_sto1_adcr_enum);
/* STO1 ADC2 Source */
/* MX-26 [12] [4] */
static const char * const rt5682_sto1_adc2_src[] = {
"DAC MIX", "DMIC"
};
static SOC_ENUM_SINGLE_DECL(
rt5682_sto1_adc2l_enum, RT5682_STO1_ADC_MIXER,
RT5682_STO1_ADC2L_SRC_SFT, rt5682_sto1_adc2_src);
static const struct snd_kcontrol_new rt5682_sto1_adc2l_mux =
SOC_DAPM_ENUM("Stereo1 ADC2L Source", rt5682_sto1_adc2l_enum);
static SOC_ENUM_SINGLE_DECL(
rt5682_sto1_adc2r_enum, RT5682_STO1_ADC_MIXER,
RT5682_STO1_ADC2R_SRC_SFT, rt5682_sto1_adc2_src);
static const struct snd_kcontrol_new rt5682_sto1_adc2r_mux =
SOC_DAPM_ENUM("Stereo1 ADC2R Source", rt5682_sto1_adc2r_enum);
/* MX-79 [6:4] I2S1 ADC data location */
static const unsigned int rt5682_if1_adc_slot_values[] = {
0,
2,
4,
6,
};
static const char * const rt5682_if1_adc_slot_src[] = {
"Slot 0", "Slot 2", "Slot 4", "Slot 6"
};
static SOC_VALUE_ENUM_SINGLE_DECL(rt5682_if1_adc_slot_enum,
RT5682_TDM_CTRL, RT5682_TDM_ADC_LCA_SFT, RT5682_TDM_ADC_LCA_MASK,
rt5682_if1_adc_slot_src, rt5682_if1_adc_slot_values);
static const struct snd_kcontrol_new rt5682_if1_adc_slot_mux =
SOC_DAPM_ENUM("IF1 ADC Slot location", rt5682_if1_adc_slot_enum);
/* Analog DAC L1 Source, Analog DAC R1 Source*/
/* MX-2B [4], MX-2B [0]*/
static const char * const rt5682_alg_dac1_src[] = {
"Stereo1 DAC Mixer", "DAC1"
};
static SOC_ENUM_SINGLE_DECL(
rt5682_alg_dac_l1_enum, RT5682_A_DAC1_MUX,
RT5682_A_DACL1_SFT, rt5682_alg_dac1_src);
static const struct snd_kcontrol_new rt5682_alg_dac_l1_mux =
SOC_DAPM_ENUM("Analog DAC L1 Source", rt5682_alg_dac_l1_enum);
static SOC_ENUM_SINGLE_DECL(
rt5682_alg_dac_r1_enum, RT5682_A_DAC1_MUX,
RT5682_A_DACR1_SFT, rt5682_alg_dac1_src);
static const struct snd_kcontrol_new rt5682_alg_dac_r1_mux =
SOC_DAPM_ENUM("Analog DAC R1 Source", rt5682_alg_dac_r1_enum);
/* Out Switch */
static const struct snd_kcontrol_new hpol_switch =
SOC_DAPM_SINGLE_AUTODISABLE("Switch", RT5682_HP_CTRL_1,
RT5682_L_MUTE_SFT, 1, 1);
static const struct snd_kcontrol_new hpor_switch =
SOC_DAPM_SINGLE_AUTODISABLE("Switch", RT5682_HP_CTRL_1,
RT5682_R_MUTE_SFT, 1, 1);
static int rt5682_hp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_component *component =
snd_soc_dapm_to_component(w->dapm);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_component_write(component,
RT5682_HP_LOGIC_CTRL_2, 0x0012);
snd_soc_component_write(component,
RT5682_HP_CTRL_2, 0x6000);
snd_soc_component_update_bits(component,
RT5682_DEPOP_1, 0x60, 0x60);
snd_soc_component_update_bits(component,
RT5682_DAC_ADC_DIG_VOL1, 0x00c0, 0x0080);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_component_update_bits(component,
RT5682_DEPOP_1, 0x60, 0x0);
snd_soc_component_write(component,
RT5682_HP_CTRL_2, 0x0000);
snd_soc_component_update_bits(component,
RT5682_DAC_ADC_DIG_VOL1, 0x00c0, 0x0000);
break;
}
return 0;
}
static int set_dmic_power(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_component *component =
snd_soc_dapm_to_component(w->dapm);
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
unsigned int delay = 50;
if (rt5682->pdata.dmic_delay)
delay = rt5682->pdata.dmic_delay;
switch (event) {
case SND_SOC_DAPM_POST_PMU:
/*Add delay to avoid pop noise*/
msleep(delay);
break;
}
return 0;
}
static int rt5682_set_verf(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_component *component =
snd_soc_dapm_to_component(w->dapm);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
switch (w->shift) {
case RT5682_PWR_VREF1_BIT:
snd_soc_component_update_bits(component,
RT5682_PWR_ANLG_1, RT5682_PWR_FV1, 0);
break;
case RT5682_PWR_VREF2_BIT:
snd_soc_component_update_bits(component,
RT5682_PWR_ANLG_1, RT5682_PWR_FV2, 0);
break;
}
break;
case SND_SOC_DAPM_POST_PMU:
usleep_range(15000, 20000);
switch (w->shift) {
case RT5682_PWR_VREF1_BIT:
snd_soc_component_update_bits(component,
RT5682_PWR_ANLG_1, RT5682_PWR_FV1,
RT5682_PWR_FV1);
break;
case RT5682_PWR_VREF2_BIT:
snd_soc_component_update_bits(component,
RT5682_PWR_ANLG_1, RT5682_PWR_FV2,
RT5682_PWR_FV2);
break;
}
break;
}
return 0;
}
static const unsigned int rt5682_adcdat_pin_values[] = {
1,
3,
};
static const char * const rt5682_adcdat_pin_select[] = {
"ADCDAT1",
"ADCDAT2",
};
static SOC_VALUE_ENUM_SINGLE_DECL(rt5682_adcdat_pin_enum,
RT5682_GPIO_CTRL_1, RT5682_GP4_PIN_SFT, RT5682_GP4_PIN_MASK,
rt5682_adcdat_pin_select, rt5682_adcdat_pin_values);
static const struct snd_kcontrol_new rt5682_adcdat_pin_ctrl =
SOC_DAPM_ENUM("ADCDAT", rt5682_adcdat_pin_enum);
static const struct snd_soc_dapm_widget rt5682_dapm_widgets[] = {
SND_SOC_DAPM_SUPPLY("LDO2", RT5682_PWR_ANLG_3, RT5682_PWR_LDO2_BIT,
0, NULL, 0),
SND_SOC_DAPM_SUPPLY("PLL1", RT5682_PWR_ANLG_3, RT5682_PWR_PLL_BIT,
0, NULL, 0),
SND_SOC_DAPM_SUPPLY("PLL2B", RT5682_PWR_ANLG_3, RT5682_PWR_PLL2B_BIT,
0, NULL, 0),
SND_SOC_DAPM_SUPPLY("PLL2F", RT5682_PWR_ANLG_3, RT5682_PWR_PLL2F_BIT,
0, set_filter_clk, SND_SOC_DAPM_PRE_PMU),
SND_SOC_DAPM_SUPPLY("Vref1", RT5682_PWR_ANLG_1, RT5682_PWR_VREF1_BIT, 0,
rt5682_set_verf, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_SUPPLY("Vref2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("MICBIAS", SND_SOC_NOPM, 0, 0, NULL, 0),
/* ASRC */
SND_SOC_DAPM_SUPPLY_S("DAC STO1 ASRC", 1, RT5682_PLL_TRACK_1,
RT5682_DAC_STO1_ASRC_SFT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY_S("ADC STO1 ASRC", 1, RT5682_PLL_TRACK_1,
RT5682_ADC_STO1_ASRC_SFT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY_S("AD ASRC", 1, RT5682_PLL_TRACK_1,
RT5682_AD_ASRC_SFT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY_S("DA ASRC", 1, RT5682_PLL_TRACK_1,
RT5682_DA_ASRC_SFT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY_S("DMIC ASRC", 1, RT5682_PLL_TRACK_1,
RT5682_DMIC_ASRC_SFT, 0, NULL, 0),
/* Input Side */
SND_SOC_DAPM_SUPPLY("MICBIAS1", RT5682_PWR_ANLG_2, RT5682_PWR_MB1_BIT,
0, NULL, 0),
SND_SOC_DAPM_SUPPLY("MICBIAS2", RT5682_PWR_ANLG_2, RT5682_PWR_MB2_BIT,
0, NULL, 0),
/* Input Lines */
SND_SOC_DAPM_INPUT("DMIC L1"),
SND_SOC_DAPM_INPUT("DMIC R1"),
SND_SOC_DAPM_INPUT("IN1P"),
SND_SOC_DAPM_SUPPLY("DMIC CLK", SND_SOC_NOPM, 0, 0,
set_dmic_clk, SND_SOC_DAPM_PRE_PMU),
SND_SOC_DAPM_SUPPLY("DMIC1 Power", RT5682_DMIC_CTRL_1,
RT5682_DMIC_1_EN_SFT, 0, set_dmic_power, SND_SOC_DAPM_POST_PMU),
/* Boost */
SND_SOC_DAPM_PGA("BST1 CBJ", SND_SOC_NOPM,
0, 0, NULL, 0),
/* REC Mixer */
SND_SOC_DAPM_MIXER("RECMIX1L", SND_SOC_NOPM, 0, 0, rt5682_rec1_l_mix,
ARRAY_SIZE(rt5682_rec1_l_mix)),
SND_SOC_DAPM_SUPPLY("RECMIX1L Power", RT5682_PWR_ANLG_2,
RT5682_PWR_RM1_L_BIT, 0, NULL, 0),
/* ADCs */
SND_SOC_DAPM_ADC("ADC1 L", NULL, SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_ADC("ADC1 R", NULL, SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_SUPPLY("ADC1 L Power", RT5682_PWR_DIG_1,
RT5682_PWR_ADC_L1_BIT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("ADC1 R Power", RT5682_PWR_DIG_1,
RT5682_PWR_ADC_R1_BIT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("ADC1 clock", RT5682_CHOP_ADC,
RT5682_CKGEN_ADC1_SFT, 0, NULL, 0),
/* ADC Mux */
SND_SOC_DAPM_MUX("Stereo1 ADC L1 Mux", SND_SOC_NOPM, 0, 0,
&rt5682_sto1_adc1l_mux),
SND_SOC_DAPM_MUX("Stereo1 ADC R1 Mux", SND_SOC_NOPM, 0, 0,
&rt5682_sto1_adc1r_mux),
SND_SOC_DAPM_MUX("Stereo1 ADC L2 Mux", SND_SOC_NOPM, 0, 0,
&rt5682_sto1_adc2l_mux),
SND_SOC_DAPM_MUX("Stereo1 ADC R2 Mux", SND_SOC_NOPM, 0, 0,
&rt5682_sto1_adc2r_mux),
SND_SOC_DAPM_MUX("Stereo1 ADC L Mux", SND_SOC_NOPM, 0, 0,
&rt5682_sto1_adcl_mux),
SND_SOC_DAPM_MUX("Stereo1 ADC R Mux", SND_SOC_NOPM, 0, 0,
&rt5682_sto1_adcr_mux),
SND_SOC_DAPM_MUX("IF1_ADC Mux", SND_SOC_NOPM, 0, 0,
&rt5682_if1_adc_slot_mux),
/* ADC Mixer */
SND_SOC_DAPM_SUPPLY("ADC Stereo1 Filter", RT5682_PWR_DIG_2,
RT5682_PWR_ADC_S1F_BIT, 0, set_filter_clk,
SND_SOC_DAPM_PRE_PMU),
SND_SOC_DAPM_MIXER("Stereo1 ADC MIXL", RT5682_STO1_ADC_DIG_VOL,
RT5682_L_MUTE_SFT, 1, rt5682_sto1_adc_l_mix,
ARRAY_SIZE(rt5682_sto1_adc_l_mix)),
SND_SOC_DAPM_MIXER("Stereo1 ADC MIXR", RT5682_STO1_ADC_DIG_VOL,
RT5682_R_MUTE_SFT, 1, rt5682_sto1_adc_r_mix,
ARRAY_SIZE(rt5682_sto1_adc_r_mix)),
SND_SOC_DAPM_SUPPLY("BTN Detection Mode", RT5682_SAR_IL_CMD_1,
14, 1, NULL, 0),
/* ADC PGA */
SND_SOC_DAPM_PGA("Stereo1 ADC MIX", SND_SOC_NOPM, 0, 0, NULL, 0),
/* Digital Interface */
SND_SOC_DAPM_SUPPLY("I2S1", RT5682_PWR_DIG_1, RT5682_PWR_I2S1_BIT,
0, NULL, 0),
SND_SOC_DAPM_SUPPLY("I2S2", RT5682_PWR_DIG_1, RT5682_PWR_I2S2_BIT,
0, NULL, 0),
SND_SOC_DAPM_PGA("IF1 DAC1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_PGA("IF1 DAC1 L", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_PGA("IF1 DAC1 R", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_PGA("SOUND DAC L", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_PGA("SOUND DAC R", SND_SOC_NOPM, 0, 0, NULL, 0),
/* Digital Interface Select */
SND_SOC_DAPM_MUX("IF1 01 ADC Swap Mux", SND_SOC_NOPM, 0, 0,
&rt5682_if1_01_adc_swap_mux),
SND_SOC_DAPM_MUX("IF1 23 ADC Swap Mux", SND_SOC_NOPM, 0, 0,
&rt5682_if1_23_adc_swap_mux),
SND_SOC_DAPM_MUX("IF1 45 ADC Swap Mux", SND_SOC_NOPM, 0, 0,
&rt5682_if1_45_adc_swap_mux),
SND_SOC_DAPM_MUX("IF1 67 ADC Swap Mux", SND_SOC_NOPM, 0, 0,
&rt5682_if1_67_adc_swap_mux),
SND_SOC_DAPM_MUX("IF2 ADC Swap Mux", SND_SOC_NOPM, 0, 0,
&rt5682_if2_adc_swap_mux),
SND_SOC_DAPM_MUX("ADCDAT Mux", SND_SOC_NOPM, 0, 0,
&rt5682_adcdat_pin_ctrl),
SND_SOC_DAPM_MUX("DAC L Mux", SND_SOC_NOPM, 0, 0,
&rt5682_dac_l_mux),
SND_SOC_DAPM_MUX("DAC R Mux", SND_SOC_NOPM, 0, 0,
&rt5682_dac_r_mux),
/* Audio Interface */
SND_SOC_DAPM_AIF_OUT("AIF1TX", "AIF1 Capture", 0,
RT5682_I2S1_SDP, RT5682_SEL_ADCDAT_SFT, 1),
SND_SOC_DAPM_AIF_OUT("AIF2TX", "AIF2 Capture", 0,
RT5682_I2S2_SDP, RT5682_I2S2_PIN_CFG_SFT, 1),
SND_SOC_DAPM_AIF_IN("AIF1RX", "AIF1 Playback", 0, SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_AIF_IN("SDWRX", "SDW Playback", 0, SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_AIF_OUT("SDWTX", "SDW Capture", 0, SND_SOC_NOPM, 0, 0),
/* Output Side */
/* DAC mixer before sound effect */
SND_SOC_DAPM_MIXER("DAC1 MIXL", SND_SOC_NOPM, 0, 0,
rt5682_dac_l_mix, ARRAY_SIZE(rt5682_dac_l_mix)),
SND_SOC_DAPM_MIXER("DAC1 MIXR", SND_SOC_NOPM, 0, 0,
rt5682_dac_r_mix, ARRAY_SIZE(rt5682_dac_r_mix)),
/* DAC channel Mux */
SND_SOC_DAPM_MUX("DAC L1 Source", SND_SOC_NOPM, 0, 0,
&rt5682_alg_dac_l1_mux),
SND_SOC_DAPM_MUX("DAC R1 Source", SND_SOC_NOPM, 0, 0,
&rt5682_alg_dac_r1_mux),
/* DAC Mixer */
SND_SOC_DAPM_SUPPLY("DAC Stereo1 Filter", RT5682_PWR_DIG_2,
RT5682_PWR_DAC_S1F_BIT, 0, set_filter_clk,
SND_SOC_DAPM_PRE_PMU),
SND_SOC_DAPM_MIXER("Stereo1 DAC MIXL", SND_SOC_NOPM, 0, 0,
rt5682_sto1_dac_l_mix, ARRAY_SIZE(rt5682_sto1_dac_l_mix)),
SND_SOC_DAPM_MIXER("Stereo1 DAC MIXR", SND_SOC_NOPM, 0, 0,
rt5682_sto1_dac_r_mix, ARRAY_SIZE(rt5682_sto1_dac_r_mix)),
/* DACs */
SND_SOC_DAPM_DAC("DAC L1", NULL, RT5682_PWR_DIG_1,
RT5682_PWR_DAC_L1_BIT, 0),
SND_SOC_DAPM_DAC("DAC R1", NULL, RT5682_PWR_DIG_1,
RT5682_PWR_DAC_R1_BIT, 0),
SND_SOC_DAPM_SUPPLY_S("DAC 1 Clock", 3, RT5682_CHOP_DAC,
RT5682_CKGEN_DAC1_SFT, 0, NULL, 0),
/* HPO */
SND_SOC_DAPM_PGA_S("HP Amp", 1, SND_SOC_NOPM, 0, 0, rt5682_hp_event,
SND_SOC_DAPM_POST_PMD | SND_SOC_DAPM_PRE_PMU),
SND_SOC_DAPM_SUPPLY("HP Amp L", RT5682_PWR_ANLG_1,
RT5682_PWR_HA_L_BIT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("HP Amp R", RT5682_PWR_ANLG_1,
RT5682_PWR_HA_R_BIT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY_S("Charge Pump", 1, RT5682_DEPOP_1,
RT5682_PUMP_EN_SFT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY_S("Capless", 2, RT5682_DEPOP_1,
RT5682_CAPLESS_EN_SFT, 0, NULL, 0),
SND_SOC_DAPM_SWITCH("HPOL Playback", SND_SOC_NOPM, 0, 0,
&hpol_switch),
SND_SOC_DAPM_SWITCH("HPOR Playback", SND_SOC_NOPM, 0, 0,
&hpor_switch),
/* CLK DET */
SND_SOC_DAPM_SUPPLY("CLKDET SYS", RT5682_CLK_DET,
RT5682_SYS_CLK_DET_SFT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("CLKDET PLL1", RT5682_CLK_DET,
RT5682_PLL1_CLK_DET_SFT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("CLKDET PLL2", RT5682_CLK_DET,
RT5682_PLL2_CLK_DET_SFT, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("CLKDET", RT5682_CLK_DET,
RT5682_POW_CLK_DET_SFT, 0, NULL, 0),
/* Output Lines */
SND_SOC_DAPM_OUTPUT("HPOL"),
SND_SOC_DAPM_OUTPUT("HPOR"),
};
static const struct snd_soc_dapm_route rt5682_dapm_routes[] = {
/*PLL*/
{"ADC Stereo1 Filter", NULL, "PLL1", is_sys_clk_from_pll1},
{"ADC Stereo1 Filter", NULL, "PLL2B", is_sys_clk_from_pll2},
{"ADC Stereo1 Filter", NULL, "PLL2F", is_sys_clk_from_pll2},
{"DAC Stereo1 Filter", NULL, "PLL1", is_sys_clk_from_pll1},
{"DAC Stereo1 Filter", NULL, "PLL2B", is_sys_clk_from_pll2},
{"DAC Stereo1 Filter", NULL, "PLL2F", is_sys_clk_from_pll2},
/*ASRC*/
{"ADC Stereo1 Filter", NULL, "ADC STO1 ASRC", is_using_asrc},
{"DAC Stereo1 Filter", NULL, "DAC STO1 ASRC", is_using_asrc},
{"ADC STO1 ASRC", NULL, "AD ASRC"},
{"ADC STO1 ASRC", NULL, "DA ASRC"},
{"ADC STO1 ASRC", NULL, "CLKDET"},
{"DAC STO1 ASRC", NULL, "AD ASRC"},
{"DAC STO1 ASRC", NULL, "DA ASRC"},
{"DAC STO1 ASRC", NULL, "CLKDET"},
/*Vref*/
{"MICBIAS1", NULL, "Vref1"},
{"MICBIAS2", NULL, "Vref1"},
{"CLKDET SYS", NULL, "CLKDET"},
{"IN1P", NULL, "LDO2"},
{"BST1 CBJ", NULL, "IN1P"},
{"RECMIX1L", "CBJ Switch", "BST1 CBJ"},
{"RECMIX1L", NULL, "RECMIX1L Power"},
{"ADC1 L", NULL, "RECMIX1L"},
{"ADC1 L", NULL, "ADC1 L Power"},
{"ADC1 L", NULL, "ADC1 clock"},
{"DMIC L1", NULL, "DMIC CLK"},
{"DMIC L1", NULL, "DMIC1 Power"},
{"DMIC R1", NULL, "DMIC CLK"},
{"DMIC R1", NULL, "DMIC1 Power"},
{"DMIC CLK", NULL, "DMIC ASRC"},
{"Stereo1 ADC L Mux", "ADC1 L", "ADC1 L"},
{"Stereo1 ADC L Mux", "ADC1 R", "ADC1 R"},
{"Stereo1 ADC R Mux", "ADC1 L", "ADC1 L"},
{"Stereo1 ADC R Mux", "ADC1 R", "ADC1 R"},
{"Stereo1 ADC L1 Mux", "ADC", "Stereo1 ADC L Mux"},
{"Stereo1 ADC L1 Mux", "DAC MIX", "Stereo1 DAC MIXL"},
{"Stereo1 ADC L2 Mux", "DMIC", "DMIC L1"},
{"Stereo1 ADC L2 Mux", "DAC MIX", "Stereo1 DAC MIXL"},
{"Stereo1 ADC R1 Mux", "ADC", "Stereo1 ADC R Mux"},
{"Stereo1 ADC R1 Mux", "DAC MIX", "Stereo1 DAC MIXR"},
{"Stereo1 ADC R2 Mux", "DMIC", "DMIC R1"},
{"Stereo1 ADC R2 Mux", "DAC MIX", "Stereo1 DAC MIXR"},
{"Stereo1 ADC MIXL", "ADC1 Switch", "Stereo1 ADC L1 Mux"},
{"Stereo1 ADC MIXL", "ADC2 Switch", "Stereo1 ADC L2 Mux"},
{"Stereo1 ADC MIXL", NULL, "ADC Stereo1 Filter"},
{"Stereo1 ADC MIXR", "ADC1 Switch", "Stereo1 ADC R1 Mux"},
{"Stereo1 ADC MIXR", "ADC2 Switch", "Stereo1 ADC R2 Mux"},
{"Stereo1 ADC MIXR", NULL, "ADC Stereo1 Filter"},
{"ADC Stereo1 Filter", NULL, "BTN Detection Mode"},
{"Stereo1 ADC MIX", NULL, "Stereo1 ADC MIXL"},
{"Stereo1 ADC MIX", NULL, "Stereo1 ADC MIXR"},
{"IF1 01 ADC Swap Mux", "L/R", "Stereo1 ADC MIX"},
{"IF1 01 ADC Swap Mux", "L/L", "Stereo1 ADC MIX"},
{"IF1 01 ADC Swap Mux", "R/L", "Stereo1 ADC MIX"},
{"IF1 01 ADC Swap Mux", "R/R", "Stereo1 ADC MIX"},
{"IF1 23 ADC Swap Mux", "L/R", "Stereo1 ADC MIX"},
{"IF1 23 ADC Swap Mux", "R/L", "Stereo1 ADC MIX"},
{"IF1 23 ADC Swap Mux", "L/L", "Stereo1 ADC MIX"},
{"IF1 23 ADC Swap Mux", "R/R", "Stereo1 ADC MIX"},
{"IF1 45 ADC Swap Mux", "L/R", "Stereo1 ADC MIX"},
{"IF1 45 ADC Swap Mux", "R/L", "Stereo1 ADC MIX"},
{"IF1 45 ADC Swap Mux", "L/L", "Stereo1 ADC MIX"},
{"IF1 45 ADC Swap Mux", "R/R", "Stereo1 ADC MIX"},
{"IF1 67 ADC Swap Mux", "L/R", "Stereo1 ADC MIX"},
{"IF1 67 ADC Swap Mux", "R/L", "Stereo1 ADC MIX"},
{"IF1 67 ADC Swap Mux", "L/L", "Stereo1 ADC MIX"},
{"IF1 67 ADC Swap Mux", "R/R", "Stereo1 ADC MIX"},
{"IF1_ADC Mux", "Slot 0", "IF1 01 ADC Swap Mux"},
{"IF1_ADC Mux", "Slot 2", "IF1 23 ADC Swap Mux"},
{"IF1_ADC Mux", "Slot 4", "IF1 45 ADC Swap Mux"},
{"IF1_ADC Mux", "Slot 6", "IF1 67 ADC Swap Mux"},
{"ADCDAT Mux", "ADCDAT1", "IF1_ADC Mux"},
{"AIF1TX", NULL, "I2S1"},
{"AIF1TX", NULL, "ADCDAT Mux"},
{"IF2 ADC Swap Mux", "L/R", "Stereo1 ADC MIX"},
{"IF2 ADC Swap Mux", "R/L", "Stereo1 ADC MIX"},
{"IF2 ADC Swap Mux", "L/L", "Stereo1 ADC MIX"},
{"IF2 ADC Swap Mux", "R/R", "Stereo1 ADC MIX"},
{"ADCDAT Mux", "ADCDAT2", "IF2 ADC Swap Mux"},
{"AIF2TX", NULL, "ADCDAT Mux"},
{"SDWTX", NULL, "PLL2B"},
{"SDWTX", NULL, "PLL2F"},
{"SDWTX", NULL, "ADCDAT Mux"},
{"IF1 DAC1 L", NULL, "AIF1RX"},
{"IF1 DAC1 L", NULL, "I2S1"},
{"IF1 DAC1 L", NULL, "DAC Stereo1 Filter"},
{"IF1 DAC1 R", NULL, "AIF1RX"},
{"IF1 DAC1 R", NULL, "I2S1"},
{"IF1 DAC1 R", NULL, "DAC Stereo1 Filter"},
{"SOUND DAC L", NULL, "SDWRX"},
{"SOUND DAC L", NULL, "DAC Stereo1 Filter"},
{"SOUND DAC L", NULL, "PLL2B"},
{"SOUND DAC L", NULL, "PLL2F"},
{"SOUND DAC R", NULL, "SDWRX"},
{"SOUND DAC R", NULL, "DAC Stereo1 Filter"},
{"SOUND DAC R", NULL, "PLL2B"},
{"SOUND DAC R", NULL, "PLL2F"},
{"DAC L Mux", "IF1", "IF1 DAC1 L"},
{"DAC L Mux", "SOUND", "SOUND DAC L"},
{"DAC R Mux", "IF1", "IF1 DAC1 R"},
{"DAC R Mux", "SOUND", "SOUND DAC R"},
{"DAC1 MIXL", "Stereo ADC Switch", "Stereo1 ADC MIXL"},
{"DAC1 MIXL", "DAC1 Switch", "DAC L Mux"},
{"DAC1 MIXR", "Stereo ADC Switch", "Stereo1 ADC MIXR"},
{"DAC1 MIXR", "DAC1 Switch", "DAC R Mux"},
{"Stereo1 DAC MIXL", "DAC L1 Switch", "DAC1 MIXL"},
{"Stereo1 DAC MIXL", "DAC R1 Switch", "DAC1 MIXR"},
{"Stereo1 DAC MIXR", "DAC R1 Switch", "DAC1 MIXR"},
{"Stereo1 DAC MIXR", "DAC L1 Switch", "DAC1 MIXL"},
{"DAC L1 Source", "DAC1", "DAC1 MIXL"},
{"DAC L1 Source", "Stereo1 DAC Mixer", "Stereo1 DAC MIXL"},
{"DAC R1 Source", "DAC1", "DAC1 MIXR"},
{"DAC R1 Source", "Stereo1 DAC Mixer", "Stereo1 DAC MIXR"},
{"DAC L1", NULL, "DAC L1 Source"},
{"DAC R1", NULL, "DAC R1 Source"},
{"DAC L1", NULL, "DAC 1 Clock"},
{"DAC R1", NULL, "DAC 1 Clock"},
{"HP Amp", NULL, "DAC L1"},
{"HP Amp", NULL, "DAC R1"},
{"HP Amp", NULL, "HP Amp L"},
{"HP Amp", NULL, "HP Amp R"},
{"HP Amp", NULL, "Capless"},
{"HP Amp", NULL, "Charge Pump"},
{"HP Amp", NULL, "CLKDET SYS"},
{"HP Amp", NULL, "Vref1"},
{"HPOL Playback", "Switch", "HP Amp"},
{"HPOR Playback", "Switch", "HP Amp"},
{"HPOL", NULL, "HPOL Playback"},
{"HPOR", NULL, "HPOR Playback"},
};
static int rt5682_set_tdm_slot(struct snd_soc_dai *dai, unsigned int tx_mask,
unsigned int rx_mask, int slots, int slot_width)
{
struct snd_soc_component *component = dai->component;
unsigned int cl, val = 0;
if (tx_mask || rx_mask)
snd_soc_component_update_bits(component, RT5682_TDM_ADDA_CTRL_2,
RT5682_TDM_EN, RT5682_TDM_EN);
else
snd_soc_component_update_bits(component, RT5682_TDM_ADDA_CTRL_2,
RT5682_TDM_EN, 0);
switch (slots) {
case 4:
val |= RT5682_TDM_TX_CH_4;
val |= RT5682_TDM_RX_CH_4;
break;
case 6:
val |= RT5682_TDM_TX_CH_6;
val |= RT5682_TDM_RX_CH_6;
break;
case 8:
val |= RT5682_TDM_TX_CH_8;
val |= RT5682_TDM_RX_CH_8;
break;
case 2:
break;
default:
return -EINVAL;
}
snd_soc_component_update_bits(component, RT5682_TDM_CTRL,
RT5682_TDM_TX_CH_MASK | RT5682_TDM_RX_CH_MASK, val);
switch (slot_width) {
case 8:
if (tx_mask || rx_mask)
return -EINVAL;
cl = RT5682_I2S1_TX_CHL_8 | RT5682_I2S1_RX_CHL_8;
break;
case 16:
val = RT5682_TDM_CL_16;
cl = RT5682_I2S1_TX_CHL_16 | RT5682_I2S1_RX_CHL_16;
break;
case 20:
val = RT5682_TDM_CL_20;
cl = RT5682_I2S1_TX_CHL_20 | RT5682_I2S1_RX_CHL_20;
break;
case 24:
val = RT5682_TDM_CL_24;
cl = RT5682_I2S1_TX_CHL_24 | RT5682_I2S1_RX_CHL_24;
break;
case 32:
val = RT5682_TDM_CL_32;
cl = RT5682_I2S1_TX_CHL_32 | RT5682_I2S1_RX_CHL_32;
break;
default:
return -EINVAL;
}
snd_soc_component_update_bits(component, RT5682_TDM_TCON_CTRL,
RT5682_TDM_CL_MASK, val);
snd_soc_component_update_bits(component, RT5682_I2S1_SDP,
RT5682_I2S1_TX_CHL_MASK | RT5682_I2S1_RX_CHL_MASK, cl);
return 0;
}
static int rt5682_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params, struct snd_soc_dai *dai)
{
struct snd_soc_component *component = dai->component;
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
unsigned int len_1 = 0, len_2 = 0;
int pre_div, frame_size;
rt5682->lrck[dai->id] = params_rate(params);
pre_div = rl6231_get_clk_info(rt5682->sysclk, rt5682->lrck[dai->id]);
frame_size = snd_soc_params_to_frame_size(params);
if (frame_size < 0) {
dev_err(component->dev, "Unsupported frame size: %d\n",
frame_size);
return -EINVAL;
}
dev_dbg(dai->dev, "lrck is %dHz and pre_div is %d for iis %d\n",
rt5682->lrck[dai->id], pre_div, dai->id);
switch (params_width(params)) {
case 16:
break;
case 20:
len_1 |= RT5682_I2S1_DL_20;
len_2 |= RT5682_I2S2_DL_20;
break;
case 24:
len_1 |= RT5682_I2S1_DL_24;
len_2 |= RT5682_I2S2_DL_24;
break;
case 32:
len_1 |= RT5682_I2S1_DL_32;
len_2 |= RT5682_I2S2_DL_24;
break;
case 8:
len_1 |= RT5682_I2S2_DL_8;
len_2 |= RT5682_I2S2_DL_8;
break;
default:
return -EINVAL;
}
switch (dai->id) {
case RT5682_AIF1:
snd_soc_component_update_bits(component, RT5682_I2S1_SDP,
RT5682_I2S1_DL_MASK, len_1);
if (rt5682->master[RT5682_AIF1]) {
snd_soc_component_update_bits(component,
RT5682_ADDA_CLK_1, RT5682_I2S_M_DIV_MASK |
RT5682_I2S_CLK_SRC_MASK,
pre_div << RT5682_I2S_M_DIV_SFT |
(rt5682->sysclk_src) << RT5682_I2S_CLK_SRC_SFT);
}
if (params_channels(params) == 1) /* mono mode */
snd_soc_component_update_bits(component,
RT5682_I2S1_SDP, RT5682_I2S1_MONO_MASK,
RT5682_I2S1_MONO_EN);
else
snd_soc_component_update_bits(component,
RT5682_I2S1_SDP, RT5682_I2S1_MONO_MASK,
RT5682_I2S1_MONO_DIS);
break;
case RT5682_AIF2:
snd_soc_component_update_bits(component, RT5682_I2S2_SDP,
RT5682_I2S2_DL_MASK, len_2);
if (rt5682->master[RT5682_AIF2]) {
snd_soc_component_update_bits(component,
RT5682_I2S_M_CLK_CTRL_1, RT5682_I2S2_M_PD_MASK,
pre_div << RT5682_I2S2_M_PD_SFT);
}
if (params_channels(params) == 1) /* mono mode */
snd_soc_component_update_bits(component,
RT5682_I2S2_SDP, RT5682_I2S2_MONO_MASK,
RT5682_I2S2_MONO_EN);
else
snd_soc_component_update_bits(component,
RT5682_I2S2_SDP, RT5682_I2S2_MONO_MASK,
RT5682_I2S2_MONO_DIS);
break;
default:
dev_err(component->dev, "Invalid dai->id: %d\n", dai->id);
return -EINVAL;
}
return 0;
}
static int rt5682_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct snd_soc_component *component = dai->component;
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
unsigned int reg_val = 0, tdm_ctrl = 0;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
rt5682->master[dai->id] = 1;
break;
case SND_SOC_DAIFMT_CBS_CFS:
rt5682->master[dai->id] = 0;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_NF:
reg_val |= RT5682_I2S_BP_INV;
tdm_ctrl |= RT5682_TDM_S_BP_INV;
break;
case SND_SOC_DAIFMT_NB_IF:
if (dai->id == RT5682_AIF1)
tdm_ctrl |= RT5682_TDM_S_LP_INV | RT5682_TDM_M_BP_INV;
else
return -EINVAL;
break;
case SND_SOC_DAIFMT_IB_IF:
if (dai->id == RT5682_AIF1)
tdm_ctrl |= RT5682_TDM_S_BP_INV | RT5682_TDM_S_LP_INV |
RT5682_TDM_M_BP_INV | RT5682_TDM_M_LP_INV;
else
return -EINVAL;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
break;
case SND_SOC_DAIFMT_LEFT_J:
reg_val |= RT5682_I2S_DF_LEFT;
tdm_ctrl |= RT5682_TDM_DF_LEFT;
break;
case SND_SOC_DAIFMT_DSP_A:
reg_val |= RT5682_I2S_DF_PCM_A;
tdm_ctrl |= RT5682_TDM_DF_PCM_A;
break;
case SND_SOC_DAIFMT_DSP_B:
reg_val |= RT5682_I2S_DF_PCM_B;
tdm_ctrl |= RT5682_TDM_DF_PCM_B;
break;
default:
return -EINVAL;
}
switch (dai->id) {
case RT5682_AIF1:
snd_soc_component_update_bits(component, RT5682_I2S1_SDP,
RT5682_I2S_DF_MASK, reg_val);
snd_soc_component_update_bits(component, RT5682_TDM_TCON_CTRL,
RT5682_TDM_MS_MASK | RT5682_TDM_S_BP_MASK |
RT5682_TDM_DF_MASK | RT5682_TDM_M_BP_MASK |
RT5682_TDM_M_LP_MASK | RT5682_TDM_S_LP_MASK,
tdm_ctrl | rt5682->master[dai->id]);
break;
case RT5682_AIF2:
if (rt5682->master[dai->id] == 0)
reg_val |= RT5682_I2S2_MS_S;
snd_soc_component_update_bits(component, RT5682_I2S2_SDP,
RT5682_I2S2_MS_MASK | RT5682_I2S_BP_MASK |
RT5682_I2S_DF_MASK, reg_val);
break;
default:
dev_err(component->dev, "Invalid dai->id: %d\n", dai->id);
return -EINVAL;
}
return 0;
}
static int rt5682_set_component_sysclk(struct snd_soc_component *component,
int clk_id, int source, unsigned int freq, int dir)
{
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
unsigned int reg_val = 0, src = 0;
if (freq == rt5682->sysclk && clk_id == rt5682->sysclk_src)
return 0;
switch (clk_id) {
case RT5682_SCLK_S_MCLK:
reg_val |= RT5682_SCLK_SRC_MCLK;
src = RT5682_CLK_SRC_MCLK;
break;
case RT5682_SCLK_S_PLL1:
reg_val |= RT5682_SCLK_SRC_PLL1;
src = RT5682_CLK_SRC_PLL1;
break;
case RT5682_SCLK_S_PLL2:
reg_val |= RT5682_SCLK_SRC_PLL2;
src = RT5682_CLK_SRC_PLL2;
break;
case RT5682_SCLK_S_RCCLK:
reg_val |= RT5682_SCLK_SRC_RCCLK;
src = RT5682_CLK_SRC_RCCLK;
break;
default:
dev_err(component->dev, "Invalid clock id (%d)\n", clk_id);
return -EINVAL;
}
snd_soc_component_update_bits(component, RT5682_GLB_CLK,
RT5682_SCLK_SRC_MASK, reg_val);
if (rt5682->master[RT5682_AIF2]) {
snd_soc_component_update_bits(component,
RT5682_I2S_M_CLK_CTRL_1, RT5682_I2S2_SRC_MASK,
src << RT5682_I2S2_SRC_SFT);
}
rt5682->sysclk = freq;
rt5682->sysclk_src = clk_id;
dev_dbg(component->dev, "Sysclk is %dHz and clock id is %d\n",
freq, clk_id);
return 0;
}
static int rt5682_set_component_pll(struct snd_soc_component *component,
int pll_id, int source, unsigned int freq_in,
unsigned int freq_out)
{
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
struct rl6231_pll_code pll_code, pll2f_code, pll2b_code;
unsigned int pll2_fout1, pll2_ps_val;
int ret;
if (source == rt5682->pll_src[pll_id] &&
freq_in == rt5682->pll_in[pll_id] &&
freq_out == rt5682->pll_out[pll_id])
return 0;
if (!freq_in || !freq_out) {
dev_dbg(component->dev, "PLL disabled\n");
rt5682->pll_in[pll_id] = 0;
rt5682->pll_out[pll_id] = 0;
snd_soc_component_update_bits(component, RT5682_GLB_CLK,
RT5682_SCLK_SRC_MASK, RT5682_SCLK_SRC_MCLK);
return 0;
}
if (pll_id == RT5682_PLL2) {
switch (source) {
case RT5682_PLL2_S_MCLK:
snd_soc_component_update_bits(component,
RT5682_GLB_CLK, RT5682_PLL2_SRC_MASK,
RT5682_PLL2_SRC_MCLK);
break;
default:
dev_err(component->dev, "Unknown PLL2 Source %d\n",
source);
return -EINVAL;
}
/**
* PLL2 concatenates 2 PLL units.
* We suggest the Fout of the front PLL is 3.84MHz.
*/
pll2_fout1 = 3840000;
ret = rl6231_pll_calc(freq_in, pll2_fout1, &pll2f_code);
if (ret < 0) {
dev_err(component->dev, "Unsupport input clock %d\n",
freq_in);
return ret;
}
dev_dbg(component->dev, "PLL2F: fin=%d fout=%d bypass=%d m=%d n=%d k=%d\n",
freq_in, pll2_fout1,
pll2f_code.m_bp,
(pll2f_code.m_bp ? 0 : pll2f_code.m_code),
pll2f_code.n_code, pll2f_code.k_code);
ret = rl6231_pll_calc(pll2_fout1, freq_out, &pll2b_code);
if (ret < 0) {
dev_err(component->dev, "Unsupport input clock %d\n",
pll2_fout1);
return ret;
}
dev_dbg(component->dev, "PLL2B: fin=%d fout=%d bypass=%d m=%d n=%d k=%d\n",
pll2_fout1, freq_out,
pll2b_code.m_bp,
(pll2b_code.m_bp ? 0 : pll2b_code.m_code),
pll2b_code.n_code, pll2b_code.k_code);
snd_soc_component_write(component, RT5682_PLL2_CTRL_1,
pll2f_code.k_code << RT5682_PLL2F_K_SFT |
pll2b_code.k_code << RT5682_PLL2B_K_SFT |
pll2b_code.m_code);
snd_soc_component_write(component, RT5682_PLL2_CTRL_2,
pll2f_code.m_code << RT5682_PLL2F_M_SFT |
pll2b_code.n_code);
snd_soc_component_write(component, RT5682_PLL2_CTRL_3,
pll2f_code.n_code << RT5682_PLL2F_N_SFT);
if (freq_out == 22579200)
pll2_ps_val = 1 << RT5682_PLL2B_SEL_PS_SFT;
else
pll2_ps_val = 1 << RT5682_PLL2B_PS_BYP_SFT;
snd_soc_component_update_bits(component, RT5682_PLL2_CTRL_4,
RT5682_PLL2B_SEL_PS_MASK | RT5682_PLL2B_PS_BYP_MASK |
RT5682_PLL2B_M_BP_MASK | RT5682_PLL2F_M_BP_MASK | 0xf,
pll2_ps_val |
(pll2b_code.m_bp ? 1 : 0) << RT5682_PLL2B_M_BP_SFT |
(pll2f_code.m_bp ? 1 : 0) << RT5682_PLL2F_M_BP_SFT |
0xf);
} else {
switch (source) {
case RT5682_PLL1_S_MCLK:
snd_soc_component_update_bits(component,
RT5682_GLB_CLK, RT5682_PLL1_SRC_MASK,
RT5682_PLL1_SRC_MCLK);
break;
case RT5682_PLL1_S_BCLK1:
snd_soc_component_update_bits(component,
RT5682_GLB_CLK, RT5682_PLL1_SRC_MASK,
RT5682_PLL1_SRC_BCLK1);
break;
default:
dev_err(component->dev, "Unknown PLL1 Source %d\n",
source);
return -EINVAL;
}
ret = rl6231_pll_calc(freq_in, freq_out, &pll_code);
if (ret < 0) {
dev_err(component->dev, "Unsupport input clock %d\n",
freq_in);
return ret;
}
dev_dbg(component->dev, "bypass=%d m=%d n=%d k=%d\n",
pll_code.m_bp, (pll_code.m_bp ? 0 : pll_code.m_code),
pll_code.n_code, pll_code.k_code);
snd_soc_component_write(component, RT5682_PLL_CTRL_1,
pll_code.n_code << RT5682_PLL_N_SFT | pll_code.k_code);
snd_soc_component_write(component, RT5682_PLL_CTRL_2,
(pll_code.m_bp ? 0 : pll_code.m_code) << RT5682_PLL_M_SFT |
pll_code.m_bp << RT5682_PLL_M_BP_SFT | RT5682_PLL_RST);
}
rt5682->pll_in[pll_id] = freq_in;
rt5682->pll_out[pll_id] = freq_out;
rt5682->pll_src[pll_id] = source;
return 0;
}
static int rt5682_set_bclk1_ratio(struct snd_soc_dai *dai, unsigned int ratio)
{
struct snd_soc_component *component = dai->component;
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
rt5682->bclk[dai->id] = ratio;
switch (ratio) {
case 256:
snd_soc_component_update_bits(component, RT5682_TDM_TCON_CTRL,
RT5682_TDM_BCLK_MS1_MASK, RT5682_TDM_BCLK_MS1_256);
break;
case 128:
snd_soc_component_update_bits(component, RT5682_TDM_TCON_CTRL,
RT5682_TDM_BCLK_MS1_MASK, RT5682_TDM_BCLK_MS1_128);
break;
case 64:
snd_soc_component_update_bits(component, RT5682_TDM_TCON_CTRL,
RT5682_TDM_BCLK_MS1_MASK, RT5682_TDM_BCLK_MS1_64);
break;
case 32:
snd_soc_component_update_bits(component, RT5682_TDM_TCON_CTRL,
RT5682_TDM_BCLK_MS1_MASK, RT5682_TDM_BCLK_MS1_32);
break;
default:
dev_err(dai->dev, "Invalid bclk1 ratio %d\n", ratio);
return -EINVAL;
}
return 0;
}
static int rt5682_set_bclk2_ratio(struct snd_soc_dai *dai, unsigned int ratio)
{
struct snd_soc_component *component = dai->component;
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
rt5682->bclk[dai->id] = ratio;
switch (ratio) {
case 64:
snd_soc_component_update_bits(component, RT5682_ADDA_CLK_2,
RT5682_I2S2_BCLK_MS2_MASK,
RT5682_I2S2_BCLK_MS2_64);
break;
case 32:
snd_soc_component_update_bits(component, RT5682_ADDA_CLK_2,
RT5682_I2S2_BCLK_MS2_MASK,
RT5682_I2S2_BCLK_MS2_32);
break;
default:
dev_err(dai->dev, "Invalid bclk2 ratio %d\n", ratio);
return -EINVAL;
}
return 0;
}
static int rt5682_set_bias_level(struct snd_soc_component *component,
enum snd_soc_bias_level level)
{
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
switch (level) {
case SND_SOC_BIAS_PREPARE:
regmap_update_bits(rt5682->regmap, RT5682_PWR_ANLG_1,
RT5682_PWR_BG, RT5682_PWR_BG);
regmap_update_bits(rt5682->regmap, RT5682_PWR_DIG_1,
RT5682_DIG_GATE_CTRL | RT5682_PWR_LDO,
RT5682_DIG_GATE_CTRL | RT5682_PWR_LDO);
break;
case SND_SOC_BIAS_STANDBY:
regmap_update_bits(rt5682->regmap, RT5682_PWR_DIG_1,
RT5682_DIG_GATE_CTRL, RT5682_DIG_GATE_CTRL);
break;
case SND_SOC_BIAS_OFF:
regmap_update_bits(rt5682->regmap, RT5682_PWR_DIG_1,
RT5682_DIG_GATE_CTRL | RT5682_PWR_LDO, 0);
regmap_update_bits(rt5682->regmap, RT5682_PWR_ANLG_1,
RT5682_PWR_BG, 0);
break;
case SND_SOC_BIAS_ON:
break;
}
return 0;
}
#ifdef CONFIG_COMMON_CLK
#define CLK_PLL2_FIN 48000000
#define CLK_48 48000
#define CLK_44 44100
static bool rt5682_clk_check(struct rt5682_priv *rt5682)
{
if (!rt5682->master[RT5682_AIF1]) {
dev_err(rt5682->component->dev, "sysclk/dai not set correctly\n");
return false;
}
return true;
}
static int rt5682_wclk_prepare(struct clk_hw *hw)
{
struct rt5682_priv *rt5682 =
container_of(hw, struct rt5682_priv,
dai_clks_hw[RT5682_DAI_WCLK_IDX]);
struct snd_soc_component *component = rt5682->component;
struct snd_soc_dapm_context *dapm =
snd_soc_component_get_dapm(component);
if (!rt5682_clk_check(rt5682))
return -EINVAL;
snd_soc_dapm_mutex_lock(dapm);
snd_soc_dapm_force_enable_pin_unlocked(dapm, "MICBIAS");
snd_soc_component_update_bits(component, RT5682_PWR_ANLG_1,
RT5682_PWR_MB, RT5682_PWR_MB);
snd_soc_dapm_force_enable_pin_unlocked(dapm, "Vref2");
snd_soc_component_update_bits(component, RT5682_PWR_ANLG_1,
RT5682_PWR_VREF2 | RT5682_PWR_FV2,
RT5682_PWR_VREF2);
usleep_range(55000, 60000);
snd_soc_component_update_bits(component, RT5682_PWR_ANLG_1,
RT5682_PWR_FV2, RT5682_PWR_FV2);
snd_soc_dapm_force_enable_pin_unlocked(dapm, "I2S1");
snd_soc_dapm_force_enable_pin_unlocked(dapm, "PLL2F");
snd_soc_dapm_force_enable_pin_unlocked(dapm, "PLL2B");
snd_soc_dapm_sync_unlocked(dapm);
snd_soc_dapm_mutex_unlock(dapm);
return 0;
}
static void rt5682_wclk_unprepare(struct clk_hw *hw)
{
struct rt5682_priv *rt5682 =
container_of(hw, struct rt5682_priv,
dai_clks_hw[RT5682_DAI_WCLK_IDX]);
struct snd_soc_component *component = rt5682->component;
struct snd_soc_dapm_context *dapm =
snd_soc_component_get_dapm(component);
if (!rt5682_clk_check(rt5682))
return;
snd_soc_dapm_mutex_lock(dapm);
snd_soc_dapm_disable_pin_unlocked(dapm, "MICBIAS");
snd_soc_dapm_disable_pin_unlocked(dapm, "Vref2");
if (!rt5682->jack_type)
snd_soc_component_update_bits(component, RT5682_PWR_ANLG_1,
RT5682_PWR_VREF2 | RT5682_PWR_FV2 |
RT5682_PWR_MB, 0);
snd_soc_dapm_disable_pin_unlocked(dapm, "I2S1");
snd_soc_dapm_disable_pin_unlocked(dapm, "PLL2F");
snd_soc_dapm_disable_pin_unlocked(dapm, "PLL2B");
snd_soc_dapm_sync_unlocked(dapm);
snd_soc_dapm_mutex_unlock(dapm);
}
static unsigned long rt5682_wclk_recalc_rate(struct clk_hw *hw,
unsigned long parent_rate)
{
struct rt5682_priv *rt5682 =
container_of(hw, struct rt5682_priv,
dai_clks_hw[RT5682_DAI_WCLK_IDX]);
struct snd_soc_component *component = rt5682->component;
const char * const clk_name = __clk_get_name(hw->clk);
if (!rt5682_clk_check(rt5682))
return 0;
/*
* Only accept to set wclk rate to 44.1k or 48kHz.
*/
if (rt5682->lrck[RT5682_AIF1] != CLK_48 &&
rt5682->lrck[RT5682_AIF1] != CLK_44) {
dev_warn(component->dev, "%s: clk %s only support %d or %d Hz output\n",
__func__, clk_name, CLK_44, CLK_48);
return 0;
}
return rt5682->lrck[RT5682_AIF1];
}
static long rt5682_wclk_round_rate(struct clk_hw *hw, unsigned long rate,
unsigned long *parent_rate)
{
struct rt5682_priv *rt5682 =
container_of(hw, struct rt5682_priv,
dai_clks_hw[RT5682_DAI_WCLK_IDX]);
struct snd_soc_component *component = rt5682->component;
const char * const clk_name = __clk_get_name(hw->clk);
if (!rt5682_clk_check(rt5682))
return -EINVAL;
/*
* Only accept to set wclk rate to 44.1k or 48kHz.
* It will force to 48kHz if not both.
*/
if (rate != CLK_48 && rate != CLK_44) {
dev_warn(component->dev, "%s: clk %s only support %d or %d Hz output\n",
__func__, clk_name, CLK_44, CLK_48);
rate = CLK_48;
}
return rate;
}
static int rt5682_wclk_set_rate(struct clk_hw *hw, unsigned long rate,
unsigned long parent_rate)
{
struct rt5682_priv *rt5682 =
container_of(hw, struct rt5682_priv,
dai_clks_hw[RT5682_DAI_WCLK_IDX]);
struct snd_soc_component *component = rt5682->component;
struct clk *parent_clk;
const char * const clk_name = __clk_get_name(hw->clk);
int pre_div;
unsigned int clk_pll2_out;
if (!rt5682_clk_check(rt5682))
return -EINVAL;
/*
* Whether the wclk's parent clk (mclk) exists or not, please ensure
* it is fixed or set to 48MHz before setting wclk rate. It's a
* temporary limitation. Only accept 48MHz clk as the clk provider.
*
* It will set the codec anyway by assuming mclk is 48MHz.
*/
parent_clk = clk_get_parent(hw->clk);
if (!parent_clk)
dev_warn(component->dev,
"Parent mclk of wclk not acquired in driver. Please ensure mclk was provided as %d Hz.\n",
CLK_PLL2_FIN);
if (parent_rate != CLK_PLL2_FIN)
dev_warn(component->dev, "clk %s only support %d Hz input\n",
clk_name, CLK_PLL2_FIN);
/*
* To achieve the rate conversion from 48MHz to 44.1k or 48kHz,
* PLL2 is needed.
*/
clk_pll2_out = rate * 512;
rt5682_set_component_pll(component, RT5682_PLL2, RT5682_PLL2_S_MCLK,
CLK_PLL2_FIN, clk_pll2_out);
rt5682_set_component_sysclk(component, RT5682_SCLK_S_PLL2, 0,
clk_pll2_out, SND_SOC_CLOCK_IN);
rt5682->lrck[RT5682_AIF1] = rate;
pre_div = rl6231_get_clk_info(rt5682->sysclk, rate);
snd_soc_component_update_bits(component, RT5682_ADDA_CLK_1,
RT5682_I2S_M_DIV_MASK | RT5682_I2S_CLK_SRC_MASK,
pre_div << RT5682_I2S_M_DIV_SFT |
(rt5682->sysclk_src) << RT5682_I2S_CLK_SRC_SFT);
return 0;
}
static unsigned long rt5682_bclk_recalc_rate(struct clk_hw *hw,
unsigned long parent_rate)
{
struct rt5682_priv *rt5682 =
container_of(hw, struct rt5682_priv,
dai_clks_hw[RT5682_DAI_BCLK_IDX]);
struct snd_soc_component *component = rt5682->component;
unsigned int bclks_per_wclk;
bclks_per_wclk = snd_soc_component_read(component, RT5682_TDM_TCON_CTRL);
switch (bclks_per_wclk & RT5682_TDM_BCLK_MS1_MASK) {
case RT5682_TDM_BCLK_MS1_256:
return parent_rate * 256;
case RT5682_TDM_BCLK_MS1_128:
return parent_rate * 128;
case RT5682_TDM_BCLK_MS1_64:
return parent_rate * 64;
case RT5682_TDM_BCLK_MS1_32:
return parent_rate * 32;
default:
return 0;
}
}
static unsigned long rt5682_bclk_get_factor(unsigned long rate,
unsigned long parent_rate)
{
unsigned long factor;
factor = rate / parent_rate;
if (factor < 64)
return 32;
else if (factor < 128)
return 64;
else if (factor < 256)
return 128;
else
return 256;
}
static long rt5682_bclk_round_rate(struct clk_hw *hw, unsigned long rate,
unsigned long *parent_rate)
{
struct rt5682_priv *rt5682 =
container_of(hw, struct rt5682_priv,
dai_clks_hw[RT5682_DAI_BCLK_IDX]);
unsigned long factor;
if (!*parent_rate || !rt5682_clk_check(rt5682))
return -EINVAL;
/*
* BCLK rates are set as a multiplier of WCLK in HW.
* We don't allow changing the parent WCLK. We just do
* some rounding down based on the parent WCLK rate
* and find the appropriate multiplier of BCLK to
* get the rounded down BCLK value.
*/
factor = rt5682_bclk_get_factor(rate, *parent_rate);
return *parent_rate * factor;
}
static int rt5682_bclk_set_rate(struct clk_hw *hw, unsigned long rate,
unsigned long parent_rate)
{
struct rt5682_priv *rt5682 =
container_of(hw, struct rt5682_priv,
dai_clks_hw[RT5682_DAI_BCLK_IDX]);
struct snd_soc_component *component = rt5682->component;
struct snd_soc_dai *dai = NULL;
unsigned long factor;
if (!rt5682_clk_check(rt5682))
return -EINVAL;
factor = rt5682_bclk_get_factor(rate, parent_rate);
for_each_component_dais(component, dai)
if (dai->id == RT5682_AIF1)
break;
if (!dai) {
dev_err(component->dev, "dai %d not found in component\n",
RT5682_AIF1);
return -ENODEV;
}
return rt5682_set_bclk1_ratio(dai, factor);
}
static const struct clk_ops rt5682_dai_clk_ops[RT5682_DAI_NUM_CLKS] = {
[RT5682_DAI_WCLK_IDX] = {
.prepare = rt5682_wclk_prepare,
.unprepare = rt5682_wclk_unprepare,
.recalc_rate = rt5682_wclk_recalc_rate,
.round_rate = rt5682_wclk_round_rate,
.set_rate = rt5682_wclk_set_rate,
},
[RT5682_DAI_BCLK_IDX] = {
.recalc_rate = rt5682_bclk_recalc_rate,
.round_rate = rt5682_bclk_round_rate,
.set_rate = rt5682_bclk_set_rate,
},
};
static int rt5682_register_dai_clks(struct snd_soc_component *component)
{
struct device *dev = component->dev;
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
struct rt5682_platform_data *pdata = &rt5682->pdata;
struct clk_init_data init;
struct clk *dai_clk;
struct clk_lookup *dai_clk_lookup;
struct clk_hw *dai_clk_hw;
const char *parent_name;
int i, ret;
for (i = 0; i < RT5682_DAI_NUM_CLKS; ++i) {
dai_clk_hw = &rt5682->dai_clks_hw[i];
switch (i) {
case RT5682_DAI_WCLK_IDX:
/* Make MCLK the parent of WCLK */
if (rt5682->mclk) {
parent_name = __clk_get_name(rt5682->mclk);
init.parent_names = &parent_name;
init.num_parents = 1;
} else {
init.parent_names = NULL;
init.num_parents = 0;
}
break;
case RT5682_DAI_BCLK_IDX:
/* Make WCLK the parent of BCLK */
parent_name = __clk_get_name(
rt5682->dai_clks[RT5682_DAI_WCLK_IDX]);
init.parent_names = &parent_name;
init.num_parents = 1;
break;
default:
dev_err(dev, "Invalid clock index\n");
ret = -EINVAL;
goto err;
}
init.name = pdata->dai_clk_names[i];
init.ops = &rt5682_dai_clk_ops[i];
init.flags = CLK_GET_RATE_NOCACHE | CLK_SET_RATE_GATE;
dai_clk_hw->init = &init;
dai_clk = devm_clk_register(dev, dai_clk_hw);
if (IS_ERR(dai_clk)) {
dev_warn(dev, "Failed to register %s: %ld\n",
init.name, PTR_ERR(dai_clk));
ret = PTR_ERR(dai_clk);
goto err;
}
rt5682->dai_clks[i] = dai_clk;
if (dev->of_node) {
devm_of_clk_add_hw_provider(dev, of_clk_hw_simple_get,
dai_clk_hw);
} else {
dai_clk_lookup = clkdev_create(dai_clk, init.name,
"%s", dev_name(dev));
if (!dai_clk_lookup) {
ret = -ENOMEM;
goto err;
} else {
rt5682->dai_clks_lookup[i] = dai_clk_lookup;
}
}
}
return 0;
err:
do {
if (rt5682->dai_clks_lookup[i])
clkdev_drop(rt5682->dai_clks_lookup[i]);
} while (i-- > 0);
return ret;
}
#endif /* CONFIG_COMMON_CLK */
static int rt5682_probe(struct snd_soc_component *component)
{
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
struct sdw_slave *slave;
unsigned long time;
struct snd_soc_dapm_context *dapm = &component->dapm;
#ifdef CONFIG_COMMON_CLK
int ret;
#endif
rt5682->component = component;
if (rt5682->is_sdw) {
slave = rt5682->slave;
time = wait_for_completion_timeout(
&slave->initialization_complete,
msecs_to_jiffies(RT5682_PROBE_TIMEOUT));
if (!time) {
dev_err(&slave->dev, "Initialization not complete, timed out\n");
return -ETIMEDOUT;
}
} else {
#ifdef CONFIG_COMMON_CLK
/* Check if MCLK provided */
rt5682->mclk = devm_clk_get(component->dev, "mclk");
if (IS_ERR(rt5682->mclk)) {
if (PTR_ERR(rt5682->mclk) != -ENOENT) {
ret = PTR_ERR(rt5682->mclk);
return ret;
}
rt5682->mclk = NULL;
}
/* Register CCF DAI clock control */
ret = rt5682_register_dai_clks(component);
if (ret)
return ret;
/* Initial setup for CCF */
rt5682->lrck[RT5682_AIF1] = CLK_48;
#endif
}
snd_soc_dapm_disable_pin(dapm, "MICBIAS");
snd_soc_dapm_disable_pin(dapm, "Vref2");
snd_soc_dapm_sync(dapm);
return 0;
}
static void rt5682_remove(struct snd_soc_component *component)
{
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
#ifdef CONFIG_COMMON_CLK
int i;
for (i = RT5682_DAI_NUM_CLKS - 1; i >= 0; --i) {
if (rt5682->dai_clks_lookup[i])
clkdev_drop(rt5682->dai_clks_lookup[i]);
}
#endif
rt5682_reset(rt5682);
}
#ifdef CONFIG_PM
static int rt5682_suspend(struct snd_soc_component *component)
{
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
regcache_cache_only(rt5682->regmap, true);
regcache_mark_dirty(rt5682->regmap);
return 0;
}
static int rt5682_resume(struct snd_soc_component *component)
{
struct rt5682_priv *rt5682 = snd_soc_component_get_drvdata(component);
regcache_cache_only(rt5682->regmap, false);
regcache_sync(rt5682->regmap);
mod_delayed_work(system_power_efficient_wq,
&rt5682->jack_detect_work, msecs_to_jiffies(250));
return 0;
}
#else
#define rt5682_suspend NULL
#define rt5682_resume NULL
#endif
const struct snd_soc_dai_ops rt5682_aif1_dai_ops = {
.hw_params = rt5682_hw_params,
.set_fmt = rt5682_set_dai_fmt,
.set_tdm_slot = rt5682_set_tdm_slot,
.set_bclk_ratio = rt5682_set_bclk1_ratio,
};
EXPORT_SYMBOL_GPL(rt5682_aif1_dai_ops);
const struct snd_soc_dai_ops rt5682_aif2_dai_ops = {
.hw_params = rt5682_hw_params,
.set_fmt = rt5682_set_dai_fmt,
.set_bclk_ratio = rt5682_set_bclk2_ratio,
};
EXPORT_SYMBOL_GPL(rt5682_aif2_dai_ops);
const struct snd_soc_component_driver rt5682_soc_component_dev = {
.probe = rt5682_probe,
.remove = rt5682_remove,
.suspend = rt5682_suspend,
.resume = rt5682_resume,
.set_bias_level = rt5682_set_bias_level,
.controls = rt5682_snd_controls,
.num_controls = ARRAY_SIZE(rt5682_snd_controls),
.dapm_widgets = rt5682_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(rt5682_dapm_widgets),
.dapm_routes = rt5682_dapm_routes,
.num_dapm_routes = ARRAY_SIZE(rt5682_dapm_routes),
.set_sysclk = rt5682_set_component_sysclk,
.set_pll = rt5682_set_component_pll,
.set_jack = rt5682_set_jack_detect,
.use_pmdown_time = 1,
.endianness = 1,
.non_legacy_dai_naming = 1,
};
EXPORT_SYMBOL_GPL(rt5682_soc_component_dev);
int rt5682_parse_dt(struct rt5682_priv *rt5682, struct device *dev)
{
device_property_read_u32(dev, "realtek,dmic1-data-pin",
&rt5682->pdata.dmic1_data_pin);
device_property_read_u32(dev, "realtek,dmic1-clk-pin",
&rt5682->pdata.dmic1_clk_pin);
device_property_read_u32(dev, "realtek,jd-src",
&rt5682->pdata.jd_src);
device_property_read_u32(dev, "realtek,btndet-delay",
&rt5682->pdata.btndet_delay);
device_property_read_u32(dev, "realtek,dmic-clk-rate-hz",
&rt5682->pdata.dmic_clk_rate);
device_property_read_u32(dev, "realtek,dmic-delay-ms",
&rt5682->pdata.dmic_delay);
rt5682->pdata.ldo1_en = of_get_named_gpio(dev->of_node,
"realtek,ldo1-en-gpios", 0);
if (device_property_read_string_array(dev, "clock-output-names",
rt5682->pdata.dai_clk_names,
RT5682_DAI_NUM_CLKS) < 0)
dev_warn(dev, "Using default DAI clk names: %s, %s\n",
rt5682->pdata.dai_clk_names[RT5682_DAI_WCLK_IDX],
rt5682->pdata.dai_clk_names[RT5682_DAI_BCLK_IDX]);
return 0;
}
EXPORT_SYMBOL_GPL(rt5682_parse_dt);
void rt5682_calibrate(struct rt5682_priv *rt5682)
{
int value, count;
mutex_lock(&rt5682->calibrate_mutex);
rt5682_reset(rt5682);
regmap_write(rt5682->regmap, RT5682_I2C_CTRL, 0x000f);
regmap_write(rt5682->regmap, RT5682_PWR_ANLG_1, 0xa2af);
usleep_range(15000, 20000);
regmap_write(rt5682->regmap, RT5682_PWR_ANLG_1, 0xf2af);
regmap_write(rt5682->regmap, RT5682_MICBIAS_2, 0x0300);
regmap_write(rt5682->regmap, RT5682_GLB_CLK, 0x8000);
regmap_write(rt5682->regmap, RT5682_PWR_DIG_1, 0x0100);
regmap_write(rt5682->regmap, RT5682_HP_IMP_SENS_CTRL_19, 0x3800);
regmap_write(rt5682->regmap, RT5682_CHOP_DAC, 0x3000);
regmap_write(rt5682->regmap, RT5682_CALIB_ADC_CTRL, 0x7005);
regmap_write(rt5682->regmap, RT5682_STO1_ADC_MIXER, 0x686c);
regmap_write(rt5682->regmap, RT5682_CAL_REC, 0x0d0d);
regmap_write(rt5682->regmap, RT5682_HP_CALIB_CTRL_2, 0x0321);
regmap_write(rt5682->regmap, RT5682_HP_LOGIC_CTRL_2, 0x0004);
regmap_write(rt5682->regmap, RT5682_HP_CALIB_CTRL_1, 0x7c00);
regmap_write(rt5682->regmap, RT5682_HP_CALIB_CTRL_3, 0x06a1);
regmap_write(rt5682->regmap, RT5682_A_DAC1_MUX, 0x0311);
regmap_write(rt5682->regmap, RT5682_HP_CALIB_CTRL_1, 0x7c00);
regmap_write(rt5682->regmap, RT5682_HP_CALIB_CTRL_1, 0xfc00);
for (count = 0; count < 60; count++) {
regmap_read(rt5682->regmap, RT5682_HP_CALIB_STA_1, &value);
if (!(value & 0x8000))
break;
usleep_range(10000, 10005);
}
if (count >= 60)
dev_err(rt5682->component->dev, "HP Calibration Failure\n");
/* restore settings */
regmap_write(rt5682->regmap, RT5682_PWR_ANLG_1, 0x002f);
regmap_write(rt5682->regmap, RT5682_MICBIAS_2, 0x0080);
regmap_write(rt5682->regmap, RT5682_GLB_CLK, 0x0000);
regmap_write(rt5682->regmap, RT5682_PWR_DIG_1, 0x0000);
regmap_write(rt5682->regmap, RT5682_CHOP_DAC, 0x2000);
regmap_write(rt5682->regmap, RT5682_CALIB_ADC_CTRL, 0x2005);
regmap_write(rt5682->regmap, RT5682_STO1_ADC_MIXER, 0xc0c4);
regmap_write(rt5682->regmap, RT5682_CAL_REC, 0x0c0c);
mutex_unlock(&rt5682->calibrate_mutex);
}
EXPORT_SYMBOL_GPL(rt5682_calibrate);
MODULE_DESCRIPTION("ASoC RT5682 driver");
MODULE_AUTHOR("Bard Liao <[email protected]>");
MODULE_LICENSE("GPL v2");
| {
"pile_set_name": "Github"
} |
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by winquake.rc
//
#define IDS_STRING1 1
#define IDI_ICON1 1
#define IDB_BITMAP1 1
#define IDB_BITMAP2 128
#define IDC_CURSOR1 129
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 130
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1005
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| {
"pile_set_name": "Github"
} |
################################################################################
# Wrapper for 32 bit machines #
################################################################################
--source include/have_32bit.inc
--source suite/sys_vars/inc/binlog_stmt_cache_size_basic.inc
| {
"pile_set_name": "Github"
} |
require('../../modules/es6.string.from-code-point');
require('../../modules/es6.string.raw');
require('../../modules/es6.string.trim');
require('../../modules/es6.string.iterator');
require('../../modules/es6.string.code-point-at');
require('../../modules/es6.string.ends-with');
require('../../modules/es6.string.includes');
require('../../modules/es6.string.repeat');
require('../../modules/es6.string.starts-with');
require('../../modules/es6.regexp.match');
require('../../modules/es6.regexp.replace');
require('../../modules/es6.regexp.search');
require('../../modules/es6.regexp.split');
require('../../modules/es6.string.anchor');
require('../../modules/es6.string.big');
require('../../modules/es6.string.blink');
require('../../modules/es6.string.bold');
require('../../modules/es6.string.fixed');
require('../../modules/es6.string.fontcolor');
require('../../modules/es6.string.fontsize');
require('../../modules/es6.string.italics');
require('../../modules/es6.string.link');
require('../../modules/es6.string.small');
require('../../modules/es6.string.strike');
require('../../modules/es6.string.sub');
require('../../modules/es6.string.sup');
require('../../modules/es7.string.at');
require('../../modules/es7.string.pad-start');
require('../../modules/es7.string.pad-end');
require('../../modules/es7.string.trim-left');
require('../../modules/es7.string.trim-right');
require('../../modules/es7.string.match-all');
require('../../modules/core.string.escape-html');
require('../../modules/core.string.unescape-html');
module.exports = require('../../modules/_core').String;
| {
"pile_set_name": "Github"
} |
package com.liato.bankdroid.banking.banks;
import com.liato.bankdroid.Helpers;
import com.liato.bankdroid.banking.Account;
import com.liato.bankdroid.banking.Bank;
import com.liato.bankdroid.banking.exceptions.BankChoiceException;
import com.liato.bankdroid.banking.exceptions.BankException;
import com.liato.bankdroid.banking.exceptions.LoginException;
import com.liato.bankdroid.legacy.R;
import com.liato.bankdroid.provider.IBankTypes;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.text.Html;
import android.text.InputType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import eu.nullbyte.android.urllib.Urllib;
public class Chalmrest extends Bank {
private static final String NAME = "Chalmrest";
private static final int BANKTYPE_ID = IBankTypes.CHALMREST;
private Pattern reViewState = Pattern.compile("__VIEWSTATE\"\\s+value=\"([^\"]+)\"");
private Pattern reEventValidation = Pattern.compile("__EVENTVALIDATION\"\\s+value=\"([^\"]+)\"");
private Pattern reAccount = Pattern
.compile("<span id=\"txtPTMCardName\">(.*?)</span>",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
private Pattern reBalance = Pattern.compile(
"<span id=\"txtPTMCardValue\">(.*?)</span>",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
private String response = null;
public Chalmrest(Context context) {
super(context, R.drawable.logo_chalmrest);
super.inputTitletextUsername = R.string.card_number;
super.inputHintUsername = "XXXXXXXXXXXXXXXX";
super.inputTypeUsername = InputType.TYPE_CLASS_NUMBER;
super.inputHiddenPassword = true;
}
@Override
public int getBanktypeId() {
return BANKTYPE_ID;
}
@Override
public String getName() {
return NAME;
}
public Chalmrest(String username, String password, Context context) throws BankException,
LoginException, BankChoiceException, IOException {
this(context);
this.update(username, password);
}
@Override
protected LoginPackage preLogin() throws BankException, IOException {
urlopen = new Urllib(context);
response = urlopen.open("http://kortladdning3.chalmerskonferens.se/Default.aspx");
Matcher matcherView = reViewState.matcher(response);
if (!matcherView.find()) {
throw new BankException(
res.getText(R.string.unable_to_find).toString() + " ViewState.");
}
String strViewState = matcherView.group(1);
Matcher matcherEvent = reEventValidation.matcher(response);
if (!matcherEvent.find()) {
throw new BankException(
res.getText(R.string.unable_to_find).toString() + " EventValidation.");
}
String strEvent = matcherEvent.group(1);
List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("__VIEWSTATE", strViewState));
postData.add(new BasicNameValuePair("__EVENTVALIDATION", strEvent));
postData.add(new BasicNameValuePair("txtCardNumber", getUsername()));
postData.add(new BasicNameValuePair("btnNext", "Nästa"));
postData.add(new BasicNameValuePair("hiddenIsMobile", "desktop"));
return new LoginPackage(urlopen, postData, response,
"http://kortladdning3.chalmerskonferens.se/Default.aspx");
}
@Override
public Urllib login() throws LoginException, BankException, IOException {
LoginPackage lp = preLogin();
response = urlopen.open(lp.getLoginTarget(), lp.getPostData());
if (!response.contains("Logga ut")) {
throw new LoginException(res.getText(R.string.invalid_username_password).toString());
}
return urlopen;
}
@Override
public void update() throws BankException, LoginException, BankChoiceException, IOException {
super.update();
if (getUsername().isEmpty()) {
throw new LoginException(res.getText(R.string.invalid_username_password).toString());
}
urlopen = login();
response = urlopen.open("http://kortladdning3.chalmerskonferens.se/CardLoad_Order.aspx");
Matcher accountMatcher;
Matcher balanceMatcher;
accountMatcher = reAccount.matcher(response);
if (accountMatcher.find()) {
/*
* Capture groups:
* GROUP EXAMPLE DATA
* 1: Name Kalle Karlsson
*/
balanceMatcher = reBalance.matcher(response);
if (balanceMatcher.find()) {
/*
* Capture groups:
* GROUP EXAMPLE DATA
* 1: Balance 118 kr
*/
String balanceString = balanceMatcher.group(1).replaceAll("\\<a[^>]*>", "")
.replaceAll("\\<[^>]*>", "").trim();
accounts.add(new Account(Html.fromHtml(accountMatcher.group(1)).toString().trim(),
Helpers.parseBalance(balanceString), accountMatcher.group(1)));
balance = balance.add(Helpers.parseBalance(balanceString));
}
}
if (accounts.isEmpty()) {
throw new BankException(res.getText(R.string.no_accounts_found).toString());
}
super.updateComplete();
}
}
| {
"pile_set_name": "Github"
} |
lexer grammar t001lexer;
options {
language = Python3;
}
ZERO: '0';
| {
"pile_set_name": "Github"
} |
# Flickr
This folder contains the extension implementation for the
[Flickr](https://www.flickr.com) service.
The implementation is based off of [Flickr4Java](https://github.com/boncey/Flickr4Java).
## Data Supported
- [Photos](src/main/java/org/datatransferproject/datatransfer/flickr/photos) Import & Export
## Current State
No known issues, however like much of DTP still needs some in depth testing to ensure corner
cases are working.
## Keys & Auth
Apply for a key at [www.flickr.com/services/apps/create/apply](https://www.flickr.com/services/apps/create/apply)
Flickr uses OAuth 1.0 for authorization.
## Maintained By
The Flickr extension was created by the
[DTP maintainers](mailto:[email protected])
and is not an official product of Flickr.
| {
"pile_set_name": "Github"
} |
gcr.io/google_containers/kube-scheduler-ppc64le:v1.10.0-beta.0
| {
"pile_set_name": "Github"
} |
<action-sequence>
<name>template1.xaction</name>
<version>1</version>
<title>Test of template component</title>
<logging-level>debug</logging-level>
<documentation>
<author>James Dixon</author>
<description></description>
<help></help>
</documentation>
<inputs>
<customer type="string">
<default-value>None</default-value>
<sources>
<request>customer</request>
</sources>
</customer>
<region type="string">
<default-value>West</default-value>
</region>
<template type="string">
<default-value>Customer '{customer}' is in region {region}</default-value>
</template>
</inputs>
<outputs>
<output type="string"/>
</outputs>
<resources/>
<actions>
<action-definition>
<action-inputs>
<customer type="string"/>
<region type="string"/>
<template type="string"/>
</action-inputs>
<action-outputs>
<output type="string"/>
</action-outputs>
<component-name>TemplateComponent</component-name>
<action-type>rule</action-type>
<component-definition>
</component-definition>
</action-definition>
</actions>
</action-sequence>
| {
"pile_set_name": "Github"
} |
/* Reflection and Meta-Programming */
/* ERROR MESSAGES */
from simple.debugging.ErrorMessages
from simple.util.Console
errMsg = new ErrorMessages
errMsgAttrs = __object_attributes(errMsg)
for error in errMsgAttrs {
errorValue = __get_attribute_value(errMsg,error)
stderr.Printfc(ConsoleColor.DARKRED,error + " = " + errorValue + "\n")
} | {
"pile_set_name": "Github"
} |
use wasm_bindgen::prelude::*;
#[wasm_bindgen(typescript_custom_section)]
const TS_INTERFACE_EXPORT: &'static str = r"
interface Height { height: number; }
";
#[wasm_bindgen]
pub struct Person {
pub height: u32,
}
| {
"pile_set_name": "Github"
} |
import React from 'react';
import styles from 'components/Sidebar/Sidebar.scss';
export default ({ name, onClick }) => (
<div className={styles.currentApp} onClick={onClick}>
{name}
</div>
);
| {
"pile_set_name": "Github"
} |
#define NAMESPACE namespace A
NAMESPACE {
int Foo; /* Test 1 */ // CHECK: int Bar;
}
int Foo; // CHECK: int Foo;
int Qux = Foo; // CHECK: int Qux = Foo;
int Baz = A::Foo; /* Test 2 */ // CHECK: Baz = A::Bar;
void fun() {
struct {
int Foo; // CHECK: int Foo;
} b = {100};
int Foo = 100; // CHECK: int Foo = 100;
Baz = Foo; // CHECK: Baz = Foo;
{
extern int Foo; // CHECK: extern int Foo;
Baz = Foo; // CHECK: Baz = Foo;
Foo = A::Foo /* Test 3 */ + Baz; // CHECK: Foo = A::Bar /* Test 3 */ + Baz;
A::Foo /* Test 4 */ = b.Foo; // CHECK: A::Bar /* Test 4 */ = b.Foo;
}
Foo = b.Foo; // Foo = b.Foo;
}
// Test 1.
// RUN: clang-rename -offset=46 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s
// Test 2.
// RUN: clang-rename -offset=234 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s
// Test 3.
// RUN: clang-rename -offset=641 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s
// Test 4.
// RUN: clang-rename -offset=716 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s
// To find offsets after modifying the file, use:
// grep -Ubo 'Foo.*' <file>
| {
"pile_set_name": "Github"
} |
\name{golden-class}
\docType{class}
\title{Class \code{"golden"} and Generator for Golden Search Optimizer Class}
\alias{golden-class}
\alias{golden}
\description{
\code{"golden"} is a reference class for a golden search scalar optimizer,
for a parameter within an interval.
\code{golden()} is the generator for the \code{"golden"}
class. The optimizer uses reverse communications.
}
\usage{
golden(...)
}
\arguments{
\item{\dots}{(partly optional) arguments passed to
\code{\link{new}()} must be named arguments. \code{lower} and
\code{upper} are the bounds for the scalar parameter; they must be
finite.}
}
\section{Extends}{
All reference classes extend and inherit methods from
\code{"\linkS4class{envRefClass}"}.
}
\examples{
showClass("golden")
golden(lower= -100, upper= 1e100)
}
\keyword{classes}
| {
"pile_set_name": "Github"
} |
/*
* Linux driver for digital TV devices equipped with B2C2 FlexcopII(b)/III
* flexcop-reg.h - register abstraction for FlexCopII, FlexCopIIb and FlexCopIII
* see flexcop.c for copyright information
*/
#ifndef __FLEXCOP_REG_H__
#define __FLEXCOP_REG_H__
typedef enum {
FLEXCOP_UNK = 0,
FLEXCOP_II,
FLEXCOP_IIB,
FLEXCOP_III,
} flexcop_revision_t;
typedef enum {
FC_UNK = 0,
FC_CABLE,
FC_AIR_DVBT,
FC_AIR_ATSC1,
FC_AIR_ATSC2,
FC_AIR_ATSC3,
FC_SKY_REV23,
FC_SKY_REV26,
FC_SKY_REV27,
FC_SKY_REV28,
} flexcop_device_type_t;
typedef enum {
FC_USB = 0,
FC_PCI,
} flexcop_bus_t;
/* FlexCop IBI Registers */
#if defined(__LITTLE_ENDIAN)
#include "flexcop_ibi_value_le.h"
#else
#if defined(__BIG_ENDIAN)
#include "flexcop_ibi_value_be.h"
#else
#error no endian defined
#endif
#endif
#define fc_data_Tag_ID_DVB 0x3e
#define fc_data_Tag_ID_ATSC 0x3f
#define fc_data_Tag_ID_IDSB 0x8b
#define fc_key_code_default 0x1
#define fc_key_code_even 0x2
#define fc_key_code_odd 0x3
extern flexcop_ibi_value ibi_zero;
typedef enum {
FC_I2C_PORT_DEMOD = 1,
FC_I2C_PORT_EEPROM = 2,
FC_I2C_PORT_TUNER = 3,
} flexcop_i2c_port_t;
typedef enum {
FC_WRITE = 0,
FC_READ = 1,
} flexcop_access_op_t;
typedef enum {
FC_SRAM_DEST_NET = 1,
FC_SRAM_DEST_CAI = 2,
FC_SRAM_DEST_CAO = 4,
FC_SRAM_DEST_MEDIA = 8
} flexcop_sram_dest_t;
typedef enum {
FC_SRAM_DEST_TARGET_WAN_USB = 0,
FC_SRAM_DEST_TARGET_DMA1 = 1,
FC_SRAM_DEST_TARGET_DMA2 = 2,
FC_SRAM_DEST_TARGET_FC3_CA = 3
} flexcop_sram_dest_target_t;
typedef enum {
FC_SRAM_2_32KB = 0, /* 64KB */
FC_SRAM_1_32KB = 1, /* 32KB - default fow FCII */
FC_SRAM_1_128KB = 2, /* 128KB */
FC_SRAM_1_48KB = 3, /* 48KB - default for FCIII */
} flexcop_sram_type_t;
typedef enum {
FC_WAN_SPEED_4MBITS = 0,
FC_WAN_SPEED_8MBITS = 1,
FC_WAN_SPEED_12MBITS = 2,
FC_WAN_SPEED_16MBITS = 3,
} flexcop_wan_speed_t;
typedef enum {
FC_DMA_1 = 1,
FC_DMA_2 = 2,
} flexcop_dma_index_t;
typedef enum {
FC_DMA_SUBADDR_0 = 1,
FC_DMA_SUBADDR_1 = 2,
} flexcop_dma_addr_index_t;
/* names of the particular registers */
typedef enum {
dma1_000 = 0x000,
dma1_004 = 0x004,
dma1_008 = 0x008,
dma1_00c = 0x00c,
dma2_010 = 0x010,
dma2_014 = 0x014,
dma2_018 = 0x018,
dma2_01c = 0x01c,
tw_sm_c_100 = 0x100,
tw_sm_c_104 = 0x104,
tw_sm_c_108 = 0x108,
tw_sm_c_10c = 0x10c,
tw_sm_c_110 = 0x110,
lnb_switch_freq_200 = 0x200,
misc_204 = 0x204,
ctrl_208 = 0x208,
irq_20c = 0x20c,
sw_reset_210 = 0x210,
misc_214 = 0x214,
mbox_v8_to_host_218 = 0x218,
mbox_host_to_v8_21c = 0x21c,
pid_filter_300 = 0x300,
pid_filter_304 = 0x304,
pid_filter_308 = 0x308,
pid_filter_30c = 0x30c,
index_reg_310 = 0x310,
pid_n_reg_314 = 0x314,
mac_low_reg_318 = 0x318,
mac_high_reg_31c = 0x31c,
data_tag_400 = 0x400,
card_id_408 = 0x408,
card_id_40c = 0x40c,
mac_address_418 = 0x418,
mac_address_41c = 0x41c,
ci_600 = 0x600,
pi_604 = 0x604,
pi_608 = 0x608,
dvb_reg_60c = 0x60c,
sram_ctrl_reg_700 = 0x700,
net_buf_reg_704 = 0x704,
cai_buf_reg_708 = 0x708,
cao_buf_reg_70c = 0x70c,
media_buf_reg_710 = 0x710,
sram_dest_reg_714 = 0x714,
net_buf_reg_718 = 0x718,
wan_ctrl_reg_71c = 0x71c,
} flexcop_ibi_register;
#define flexcop_set_ibi_value(reg,attr,val) { \
flexcop_ibi_value v = fc->read_ibi_reg(fc,reg); \
v.reg.attr = val; \
fc->write_ibi_reg(fc,reg,v); \
}
#endif
| {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Benoit Jacob <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DETERMINANT_H
#define EIGEN_DETERMINANT_H
namespace Eigen {
namespace internal {
template<typename Derived>
inline const typename Derived::Scalar bruteforce_det3_helper
(const MatrixBase<Derived>& matrix, int a, int b, int c)
{
return matrix.coeff(0,a)
* (matrix.coeff(1,b) * matrix.coeff(2,c) - matrix.coeff(1,c) * matrix.coeff(2,b));
}
template<typename Derived>
const typename Derived::Scalar bruteforce_det4_helper
(const MatrixBase<Derived>& matrix, int j, int k, int m, int n)
{
return (matrix.coeff(j,0) * matrix.coeff(k,1) - matrix.coeff(k,0) * matrix.coeff(j,1))
* (matrix.coeff(m,2) * matrix.coeff(n,3) - matrix.coeff(n,2) * matrix.coeff(m,3));
}
template<typename Derived,
int DeterminantType = Derived::RowsAtCompileTime
> struct determinant_impl
{
static inline typename traits<Derived>::Scalar run(const Derived& m)
{
if(Derived::ColsAtCompileTime==Dynamic && m.rows()==0)
return typename traits<Derived>::Scalar(1);
return m.partialPivLu().determinant();
}
};
template<typename Derived> struct determinant_impl<Derived, 1>
{
static inline typename traits<Derived>::Scalar run(const Derived& m)
{
return m.coeff(0,0);
}
};
template<typename Derived> struct determinant_impl<Derived, 2>
{
static inline typename traits<Derived>::Scalar run(const Derived& m)
{
return m.coeff(0,0) * m.coeff(1,1) - m.coeff(1,0) * m.coeff(0,1);
}
};
template<typename Derived> struct determinant_impl<Derived, 3>
{
static inline typename traits<Derived>::Scalar run(const Derived& m)
{
return bruteforce_det3_helper(m,0,1,2)
- bruteforce_det3_helper(m,1,0,2)
+ bruteforce_det3_helper(m,2,0,1);
}
};
template<typename Derived> struct determinant_impl<Derived, 4>
{
static typename traits<Derived>::Scalar run(const Derived& m)
{
// trick by Martin Costabel to compute 4x4 det with only 30 muls
return bruteforce_det4_helper(m,0,1,2,3)
- bruteforce_det4_helper(m,0,2,1,3)
+ bruteforce_det4_helper(m,0,3,1,2)
+ bruteforce_det4_helper(m,1,2,0,3)
- bruteforce_det4_helper(m,1,3,0,2)
+ bruteforce_det4_helper(m,2,3,0,1);
}
};
} // end namespace internal
/** \lu_module
*
* \returns the determinant of this matrix
*/
template<typename Derived>
inline typename internal::traits<Derived>::Scalar MatrixBase<Derived>::determinant() const
{
eigen_assert(rows() == cols());
typedef typename internal::nested_eval<Derived,Base::RowsAtCompileTime>::type Nested;
return internal::determinant_impl<typename internal::remove_all<Nested>::type>::run(derived());
}
} // end namespace Eigen
#endif // EIGEN_DETERMINANT_H
| {
"pile_set_name": "Github"
} |
@function __reject-iteratee($value, $index, $collection) {
$predicate: __this('predicate');
$test: __exec($predicate, $value, $index, $collection);
$result: __is-falsey(__exec($predicate, $value, $index, $collection));
@return $result;
}
@function __reject($collection, $predicate: '__identity', $this-arg: null) {
$function: if(__is-list($collection), '__list-filter', '__base-filter');
$predicate: __get-callback($predicate, $this-arg, 3);
$_: __scope((
'predicate': $predicate
));
$reject-iteratee: __bind('__reject-iteratee');
$result: __exec($function, $collection, $reject-iteratee);
$_: __scope(false);
@return $result;
}
///
/// The opposite of `_filter`; this method returns the elements of `$collection`
/// that `$predicate` does **not** return truthy for.
///
/// If a property name is provided for `$predicate` the created `_property`
/// style callback returns the property value of the given element.
///
/// If a value is also provided for `$this-arg` the created `_matches-property`
/// style callback returns `true` for elements that have a matching property
/// value, else `false`.
///
/// If a map is provided for `$predicate` the created `_matches` style
/// callback returns `true` for elements that have the properties of the given
/// object, else `false`.
///
///
/// @access public
/// @group Collection
/// @param {List|Map|string} $collection The collection to iterate over.
/// @param {Function|Map|string} $predicate [_identity] - The function invoked
/// per iteration.
/// @param {*} $this-arg [null] - The `_this` binding of `$predicate`.
/// @returns {List} Returns the new filtered list.
/// @example scss
/// $foo: _reject((1, 2, 3, 4), is-even);
/// // => (1, 3)
///
/// $users: (
/// ( 'user': 'barney', 'age': 36, 'active': false ),
/// ( 'user': 'fred', 'age': 40, 'active': true )
/// );
/// // using the `_matches` callback shorthand
/// $foo: _pluck(_reject($users, ( 'age': 40, 'active': true )), 'user');
/// // => ('barney')
///
/// // using the `_matches-property` callback shorthand
/// $foo: _pluck(_reject($users, 'active', false), 'user');
/// // => ('fred')
///
/// // using the `_property` callback shorthand
/// $foo: _pluck(_reject($users, 'active'), 'user');
/// // => ('barney')
@function _reject($args...) {
@return call(get-function('__reject'), $args...);
}
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>判断UA</title>
</head>
<body>
<script>
var UA = window.navigator.userAgent;
var ua = UA.toLowerCase();
var browserRegExp = {
ie:/msie\s*(\d+(?:\.\d+)?)+/,
chrome:/chrome\/(\d+(?:\.\d+)?)+/,
firefox:/firefox\/(\d+(?:\.\d+)?)+/,
safari:/version\/(\d+(?:\.\d+)?)\s*safari/,
opera:/opera[ |\/](\d+(?:\.\d+)?)/
};
$ = {};
$.browser = 'unknow';
$.browserVersion = 0;
function checkUA(ua,browser,version){
ua = ua.toLowerCase();
for(var i in browserRegExp){
var match = browserRegExp[i].exec(ua);
if(match){
$.browser = i;
if(browser===i && version==match[1]){
}else{
console.log(browser+'|'+version+'|'+match[1]+':'+ua);
}
break;
}else{
// console.log(ua);
}
}
}
var arr = [
['chrome',19.0,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3'],
['chrome',24.0,'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/24.0.1292.0 Safari/537.14'],
['chrome',15.0,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.861.0 Safari/535.2'],
['chrome',4.0,'Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/4.0.211.2 Safari/532.0'],
['chrome',0.2,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13(KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13'],
['safari',6.0,'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25'],
['safari',5.0,'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; da-dk) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'],
['safari',5.1,'Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko ) Version/5.1 Mobile/9B176 Safari/7534.48.3'],
['safari',5.0,'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; th-th) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8'],
['safari',4.0,'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_4; en-gb) AppleWebKit/528.4+ (KHTML, like Gecko) Version/4.0dp1 Safari/526.11.2'],
['safari',4.0,'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7'],
['safari',4.0,'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10gin_lib.cc'],
['safari',4.0,'Mozilla/5.0 (Windows; U; Windows NT 5.1; fi-FI) AppleWebKit/528.16 (KHTML, like Gecko) Version/4.0 Safari/528.16'],
['safari',3.2,'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_7; de-de) AppleWebKit/525.28.3 (KHTML, like Gecko) Version/3.2.3 Safari/525.28.3'],
['safari',3.2,'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; fr-fr) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/3.2.1 Safari/525.27.1'],
['safari',3.0,'Mozilla/5.0 (Windows; U; Windows NT 6.0; en) AppleWebKit/525+ (KHTML, like Gecko) Version/3.0.4 Safari/523.11'],
['safari',2.0,'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/418 (KHTML, like Gecko) Safari/417.9.2'],
['safari',1.3,'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/312.8 (KHTML, like Gecko) Safari/312.5_Adobe'],
['safari',1.0,'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/85.7 (KHTML, like Gecko) Safari/85.5'],
['firefox',23.0,'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20130406 Firefox/23.0'],
['firefox',16.0,'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1'],
['firefox',6.0,'Mozilla/5.0 (Windows NT 5.0; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0'],
['firefox',6.0,'Mozilla/5.0 (Windows NT 5.1; rv:6.0) Gecko/20100101 Firefox/6.0 FirePHP/0.6'],
['firefox',5.0,'Mozilla/5.0 (X11; Linux i686 on x86_64; rv:5.0a2) Gecko/20110524 Firefox/5.0a2'],
['firefox',4.0,'Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)'],
['firefox',4.0,'Mozilla/5.0 (Windows NT 6.1; rv:1.9) Gecko/20100101 Firefox/4.0'],
['firefox',3.5,'Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9 GTB7.0 (.NET CLR 3.0.30618)'],
['firefox',2.1,'Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.9.0.15) Gecko/2009101601 Firefox 2.1 (.NET CLR 3.5.30729)'],
['firefox',2.0,'Mozilla/5.0 (X11; U; SunOS sun4v; en-US; rv:1.8.1.3) Gecko/20070321 Firefox/2.0.0.3'],
['firefox',1.6,'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9a1) Gecko/20060112 Firefox/1.6a1'],
['firefox',1.0,'Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.7.6) Gecko/20050317 Firefox/1.0.2 (ax)'],
['firefox',0.1,'Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; rv:1.7.3) Gecko/20040913 Firefox/0.10'],
['ie',10.6,'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0'],
['ie',10.0,'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)'],
['ie',9.0,'Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))'],
['ie',9.0,'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Zune 4.0; InfoPath.3; MS-RTC LM 8; .NET4.0C; .NET4.0E)'],
['ie',8.0,'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MS-RTC LM 8; InfoPath.3; .NET4.0C; .NET4.0E) chromeframe/8.0.552.224'],
['ie',7.0,'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)'],
['ie',7.0,'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)'],
['ie',6.0,'Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)'],
['ie',6.1,'Mozilla/4.0 (compatible; MSIE 6.1; Windows XP; .NET CLR 1.1.4322; .NET CLR 2.0.50727)'],
['opera',12.14,'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14'],
['opera',12.02,'Opera/12.80 (Windows NT 5.1; U; en) Presto/2.10.289 Version/12.02'],
['opera',12.0,'Mozilla/5.0 (Windows NT 5.1) Gecko/20100101 Firefox/14.0 Opera/12.0'],
['opera',12.00,'Opera/12.0(Windows NT 5.1;U;en)Presto/22.9.168 Version/12.00'],
['opera',11.62,'Opera/9.80 (Windows NT 6.0; U; pl) Presto/2.10.229 Version/11.62'],
['opera',11.50,'Opera/9.80 (X11; Linux x86_64; U; fr) Presto/2.9.168 Version/11.50'],
['opera',11.11,'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/5.0 Opera 11.11'],
['opera',11.11,'Opera/9.80 (X11; Linux i686; U; es-ES) Presto/2.8.131 Version/11.11'],
['opera',11.10,'Opera/9.80 (Windows NT 6.1; U; zh-tw) Presto/2.7.62 Version/11.01'],
['opera',11.00,'Opera/9.80 (X11; Linux x86_64; U; pl) Presto/2.7.62 Version/11.00'],
['opera',11.00,'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; en) Opera 11.00'],
['opera',10.70,'Opera/9.80 (Windows NT 6.1; U; pl) Presto/2.6.31 Version/10.70'],
['opera',10.70,'Mozilla/5.0 (Windows NT 5.1; U; zh-cn; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 Opera 10.70'],
['opera',10.63,'Opera/9.80 (Windows NT 5.2; U; zh-cn) Presto/2.6.30 Version/10.63'],
['opera',9.80,'Opera/9.80 (J2ME/MIDP; Opera Mini/5.0 (Windows; U; Windows NT 5.1; en) AppleWebKit/886; U; en) Presto/2.4.15'],
];
for(var i=0,len = arr.length;i<len;i++){
checkUA(arr[i][2],arr[i][0],arr[i][1]);
}
</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
package io.quarkus.deployment.builditem;
import io.quarkus.builder.item.MultiBuildItem;
import io.quarkus.deployment.recording.ObjectLoader;
/**
*/
public final class BytecodeRecorderObjectLoaderBuildItem extends MultiBuildItem {
private final ObjectLoader objectLoader;
public BytecodeRecorderObjectLoaderBuildItem(final ObjectLoader objectLoader) {
this.objectLoader = objectLoader;
}
public ObjectLoader getObjectLoader() {
return objectLoader;
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2008-present Contributors to the OpenImageIO project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/OpenImageIO/oiio/blob/master/LICENSE.md
/////////////////////////////////////////////////////////////////////////
/// \file
///
/// Helper routines for managing runtime-loadable "plugins", implemented
/// variously as DSO's (traditional Unix/Linux), dynamic libraries (Mac
/// OS X), DLL's (Windows).
/////////////////////////////////////////////////////////////////////////
#pragma once
#include <string>
#include <OpenImageIO/export.h>
#include <OpenImageIO/oiioversion.h>
OIIO_NAMESPACE_BEGIN
namespace Plugin {
typedef void* Handle;
/// Return the platform-dependent suffix for plug-ins ("dll" on
/// Windows, "so" on Linux and Mac OS X.
OIIO_API const char*
plugin_extension(void);
/// Open the named plugin, return its handle. If it could not be
/// opened, return 0 and the next call to geterror() will contain
/// an explanatory message. If the 'global' parameter is true, all
/// symbols from the plugin will be available to the app (on Unix-like
/// platforms; this has no effect on Windows).
OIIO_API Handle
open(const char* plugin_filename, bool global = true);
inline Handle
open(const std::string& plugin_filename, bool global = true)
{
return open(plugin_filename.c_str(), global);
}
/// Close the open plugin with the given handle and return true upon
/// success. If some error occurred, return false and the next call to
/// geterror() will contain an explanatory message.
OIIO_API bool
close(Handle plugin_handle);
/// Get the address of the named symbol from the open plugin handle. If
/// some error occurred, return nullptr and the next call to
/// geterror() will contain an explanatory message (unless report_error
/// is false, in which case the error message will be suppressed).
OIIO_API void*
getsym(Handle plugin_handle, const char* symbol_name, bool report_error = true);
inline void*
getsym(Handle plugin_handle, const std::string& symbol_name,
bool report_error = true)
{
return getsym(plugin_handle, symbol_name.c_str(), report_error);
}
/// Return any error messages associated with the last call to any of
/// open, close, or getsym. Note that in a multithreaded environment,
/// it's up to the caller to properly mutex to ensure that no other
/// thread has called open, close, or getsym (all of which clear or
/// overwrite the error message) between the error-generating call and
/// geterror.
OIIO_API std::string
geterror(void);
} // namespace Plugin
OIIO_NAMESPACE_END
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Request xsi:schemaLocation="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17 http://docs.oasis-open.org/xacml/3.0/xacml-core-v3-schema-wd-17.xsd" ReturnPolicyIdList="false" CombinedDecision="false" xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Attributes Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject">
<Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Julius Hibbert</AttributeValue>
</Attribute>
<Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:2.0:conformance-test:test-attr">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#hexBinary">0BF7A9876CDE</AttributeValue>
</Attribute>
<Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:2.0:conformance-test:test-attr">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#hexBinary">0BF7A9876CAB</AttributeValue>
</Attribute>
</Attributes>
<Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource">
<Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://medico.com/record/patient/BartSimpson</AttributeValue>
</Attribute>
</Attributes>
<Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action">
<Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">read</AttributeValue>
</Attribute>
</Attributes>
<Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment"/>
</Request>
| {
"pile_set_name": "Github"
} |
# This is a part of the Microsoft Foundation Classes C++ library.
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is only intended as a supplement to the
# Microsoft Foundation Classes Reference and related
# electronic documentation provided with the library.
# See these sources for detailed information regarding the
# Microsoft Foundation Classes product.
PROJ=CMNCTRL2
OBJS=cmnctrl2.obj notifwdw.obj progctrl.obj propsht.obj slidctrl.obj \
spinctrl.obj
!include <mfcsamps.mak>
| {
"pile_set_name": "Github"
} |
// I noticed this on the ConEmu web site:
//
// https://social.msdn.microsoft.com/Forums/en-US/40c8e395-cca9-45c8-b9b8-2fbe6782ac2b/readconsoleoutput-cause-access-violation-writing-location-exception
// https://conemu.github.io/en/MicrosoftBugs.html
//
// In Windows 7, 8, and 8.1, a ReadConsoleOutputW with an out-of-bounds read
// region crashes the application. I have reproduced the problem on Windows 8
// and 8.1, but not on Windows 7.
//
#include <windows.h>
#include "TestUtil.cc"
int main() {
setWindowPos(0, 0, 1, 1);
setBufferSize(80, 25);
setWindowPos(0, 0, 80, 25);
const HANDLE conout = openConout();
static CHAR_INFO lineBuf[80];
SMALL_RECT readRegion = { 0, 999, 79, 999 };
const BOOL ret = ReadConsoleOutputW(conout, lineBuf, {80, 1}, {0, 0}, &readRegion);
ASSERT(!ret && "ReadConsoleOutputW should have failed");
return 0;
}
| {
"pile_set_name": "Github"
} |
See LICENSE file in the project root for full license information.
| {
"pile_set_name": "Github"
} |
/**
@page TM_SinglePulseMode
@verbatim
* @file TM/SinglePulseMode/readme.txt
* @version V1.00
* @date 2014-06-30
* @brief Description of GPTM single pulse mode example.
@endverbatim
@par Example Description:
This example shows how to use the GPTM peripheral to generate a Single Pulse Mode
after a rising edge of an external signal has been received in Timer Input pin.
If the GPTM0_PCLK frequency is set to 72 MHz / 96 MHz and the Prescaler is 72 / 96, so the GPTM0 counter
clock is 1 MHz.
The CounterReload value is 50000 (GPTM0_CRR), so the maximum frequency value to trigger
the GPTM0 input is 1 MHz/50000= 20 Hz.
The GPTM0 is configured as follows:
- The Single Pulse mode is used.
- The external signal is connected to GT0_ETI pin.
- The rising edge is used as active edge.
- The Single Pulse signal is output on GT0_CH3.
The Compare value decides the delay value, the delay value is fixed to 5 ms:
- delay = CH3CCR/GPTM0 counter clock = 5 ms.
(CounterReload - Compare + 1) defines the Single Pulse value while the pulse value is fixed to 45 ms.
@par Directory Contents:
- GPTM/SinglePulseMode/main.c Main program
- GPTM/SinglePulseMode/ht32f1xxxx_01_it.c Interrupt handlers
@par Hardware and Software Environment:
- Connect the external signal to the GT0_ETI pin. Refer "ht32_board_config.h" for pin assignment.
- Generate a rising edge on GT0_ETI to trigger single pulse output.
- Connect the GT0_CH3 (PA7) pin to an oscilloscope to monitor the waveform.
- This example can be run on HT32 Series development board.
@par Firmware Disclaimer Information
1. The customer hereby acknowledges and agrees that the program technical documentation, including the
code, which is supplied by Holtek Semiconductor Inc., (hereinafter referred to as "HOLTEK") is the
proprietary and confidential intellectual property of HOLTEK, and is protected by copyright law and
other intellectual property laws.
2. The customer hereby acknowledges and agrees that the program technical documentation, including the
code, is confidential information belonging to HOLTEK, and must not be disclosed to any third parties
other than HOLTEK and the customer.
3. The program technical documentation, including the code, is provided "as is" and for customer reference
only. After delivery by HOLTEK, the customer shall use the program technical documentation, including
the code, at their own risk. HOLTEK disclaims any expressed, implied or statutory warranties, including
the warranties of merchantability, satisfactory quality and fitness for a particular purpose.
* <h2><center>Copyright (C) Holtek Semiconductor Inc. All rights reserved</center></h2>
*/
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="90dp"
android:background="#fff"
android:orientation="vertical">
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:background="#008bea" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="精品应用推荐下载"
android:textColor="#000"
android:textSize="16sp" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/promoter_frame"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:paddingTop="10dp"></LinearLayout>
<RelativeLayout
android:id="@+id/progress_frame"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#fff">
<TextView
android:id="@+id/status_msg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:textColor="#000"
android:textSize="18sp"/>
<ProgressBar
android:id="@+id/loading"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</FrameLayout>
</LinearLayout> | {
"pile_set_name": "Github"
} |
import Cocoa
class EditorTemplateCellView: NSTableCellView {
static let identifier = NSUserInterfaceItemIdentifier("EditorTemplateCellView")
@IBOutlet weak var titleTextField: NSTextField!
}
| {
"pile_set_name": "Github"
} |
53851357df0689a5b799dac03a8d80a8425906ebc5b5aab26337ee1b7bb8ffb331f2939fc38881dff33baa859502ebb3c4f59ad4db49d6392818835c53cd697e
| {
"pile_set_name": "Github"
} |
using System.Linq;
using Bogus.Extensions;
using FluentAssertions;
using Xunit;
namespace Bogus.Tests.GitHubIssues
{
public class Issue178 : SeededTest
{
[Fact]
public void weighted_null_check()
{
var f = new Faker();
var mostlyNull = Enumerable.Range(1, 100)
.Select(n => (int?)n.OrNull(f, 0.9f))
.Count( n => !n.HasValue);
mostlyNull.Should().BeGreaterThan(80);
var mostlyNotNull = Enumerable.Range(1, 100)
.Select(n => (int?)n.OrNull(f, 0.1f))
.Count(n => !n.HasValue);
mostlyNotNull.Should().BeLessThan(20);
}
[Fact]
public void weighted_default_check()
{
var f = new Faker();
var mostlyDefault = Enumerable.Range(1, 100)
.Select(n => n.OrDefault(f, 0.9f))
.Count(n => n == default);
mostlyDefault.Should().BeGreaterThan(80);
var mostlyNotDefault = Enumerable.Range(1, 100)
.Select(n => n.OrDefault(f, 0.1f))
.Count(n => n == default);
mostlyNotDefault.Should().BeLessThan(20);
var mostlyNotDefaultObject = Enumerable.Range(1, 100)
.Select( n => new object())
.Select(s => s.OrDefault(f, 0.1f))
.Count(s => s == null);
mostlyNotDefaultObject.Should().BeLessThan(20);
}
}
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
MIT License
Copyright (c) 2010-2020 The Waffle Project Contributors: https://github.com/Waffle/waffle/graphs/contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<!DOCTYPE Format>
<Format>
<!-- Dummy format file -->
</Format>
| {
"pile_set_name": "Github"
} |
---
deprecations:
- The V8 Federation driver interface is deprecated in favor of the V9
Federation driver interface. Support for the V8 Federation driver
interface is planned to be removed in the 'O' release of OpenStack.
| {
"pile_set_name": "Github"
} |
ActiveAdmin.register Country do
permit_params :name, :information
end
| {
"pile_set_name": "Github"
} |
var constants = require('constants')
var origCwd = process.cwd
var cwd = null
var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform
process.cwd = function() {
if (!cwd)
cwd = origCwd.call(process)
return cwd
}
try {
process.cwd()
} catch (er) {}
var chdir = process.chdir
process.chdir = function(d) {
cwd = null
chdir.call(process, d)
}
module.exports = patch
function patch (fs) {
// (re-)implement some things that are known busted or missing.
// lchmod, broken prior to 0.6.2
// back-port the fix here.
if (constants.hasOwnProperty('O_SYMLINK') &&
process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
patchLchmod(fs)
}
// lutimes implementation, or no-op
if (!fs.lutimes) {
patchLutimes(fs)
}
// https://github.com/isaacs/node-graceful-fs/issues/4
// Chown should not fail on einval or eperm if non-root.
// It should not fail on enosys ever, as this just indicates
// that a fs doesn't support the intended operation.
fs.chown = chownFix(fs.chown)
fs.fchown = chownFix(fs.fchown)
fs.lchown = chownFix(fs.lchown)
fs.chmod = chmodFix(fs.chmod)
fs.fchmod = chmodFix(fs.fchmod)
fs.lchmod = chmodFix(fs.lchmod)
fs.chownSync = chownFixSync(fs.chownSync)
fs.fchownSync = chownFixSync(fs.fchownSync)
fs.lchownSync = chownFixSync(fs.lchownSync)
fs.chmodSync = chmodFixSync(fs.chmodSync)
fs.fchmodSync = chmodFixSync(fs.fchmodSync)
fs.lchmodSync = chmodFixSync(fs.lchmodSync)
fs.stat = statFix(fs.stat)
fs.fstat = statFix(fs.fstat)
fs.lstat = statFix(fs.lstat)
fs.statSync = statFixSync(fs.statSync)
fs.fstatSync = statFixSync(fs.fstatSync)
fs.lstatSync = statFixSync(fs.lstatSync)
// if lchmod/lchown do not exist, then make them no-ops
if (!fs.lchmod) {
fs.lchmod = function (path, mode, cb) {
if (cb) process.nextTick(cb)
}
fs.lchmodSync = function () {}
}
if (!fs.lchown) {
fs.lchown = function (path, uid, gid, cb) {
if (cb) process.nextTick(cb)
}
fs.lchownSync = function () {}
}
// on Windows, A/V software can lock the directory, causing this
// to fail with an EACCES or EPERM if the directory contains newly
// created files. Try again on failure, for up to 60 seconds.
// Set the timeout this long because some Windows Anti-Virus, such as Parity
// bit9, may lock files for up to a minute, causing npm package install
// failures. Also, take care to yield the scheduler. Windows scheduling gives
// CPU to a busy looping process, which can cause the program causing the lock
// contention to be starved of CPU by node, so the contention doesn't resolve.
if (platform === "win32") {
fs.rename = (function (fs$rename) { return function (from, to, cb) {
var start = Date.now()
var backoff = 0;
fs$rename(from, to, function CB (er) {
if (er
&& (er.code === "EACCES" || er.code === "EPERM")
&& Date.now() - start < 60000) {
setTimeout(function() {
fs.stat(to, function (stater, st) {
if (stater && stater.code === "ENOENT")
fs$rename(from, to, CB);
else
cb(er)
})
}, backoff)
if (backoff < 100)
backoff += 10;
return;
}
if (cb) cb(er)
})
}})(fs.rename)
}
// if read() returns EAGAIN, then just try it again.
fs.read = (function (fs$read) {
function read (fd, buffer, offset, length, position, callback_) {
var callback
if (callback_ && typeof callback_ === 'function') {
var eagCounter = 0
callback = function (er, _, __) {
if (er && er.code === 'EAGAIN' && eagCounter < 10) {
eagCounter ++
return fs$read.call(fs, fd, buffer, offset, length, position, callback)
}
callback_.apply(this, arguments)
}
}
return fs$read.call(fs, fd, buffer, offset, length, position, callback)
}
// This ensures `util.promisify` works as it does for native `fs.read`.
read.__proto__ = fs$read
return read
})(fs.read)
fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
var eagCounter = 0
while (true) {
try {
return fs$readSync.call(fs, fd, buffer, offset, length, position)
} catch (er) {
if (er.code === 'EAGAIN' && eagCounter < 10) {
eagCounter ++
continue
}
throw er
}
}
}})(fs.readSync)
function patchLchmod (fs) {
fs.lchmod = function (path, mode, callback) {
fs.open( path
, constants.O_WRONLY | constants.O_SYMLINK
, mode
, function (err, fd) {
if (err) {
if (callback) callback(err)
return
}
// prefer to return the chmod error, if one occurs,
// but still try to close, and report closing errors if they occur.
fs.fchmod(fd, mode, function (err) {
fs.close(fd, function(err2) {
if (callback) callback(err || err2)
})
})
})
}
fs.lchmodSync = function (path, mode) {
var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
// prefer to return the chmod error, if one occurs,
// but still try to close, and report closing errors if they occur.
var threw = true
var ret
try {
ret = fs.fchmodSync(fd, mode)
threw = false
} finally {
if (threw) {
try {
fs.closeSync(fd)
} catch (er) {}
} else {
fs.closeSync(fd)
}
}
return ret
}
}
function patchLutimes (fs) {
if (constants.hasOwnProperty("O_SYMLINK")) {
fs.lutimes = function (path, at, mt, cb) {
fs.open(path, constants.O_SYMLINK, function (er, fd) {
if (er) {
if (cb) cb(er)
return
}
fs.futimes(fd, at, mt, function (er) {
fs.close(fd, function (er2) {
if (cb) cb(er || er2)
})
})
})
}
fs.lutimesSync = function (path, at, mt) {
var fd = fs.openSync(path, constants.O_SYMLINK)
var ret
var threw = true
try {
ret = fs.futimesSync(fd, at, mt)
threw = false
} finally {
if (threw) {
try {
fs.closeSync(fd)
} catch (er) {}
} else {
fs.closeSync(fd)
}
}
return ret
}
} else {
fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) }
fs.lutimesSync = function () {}
}
}
function chmodFix (orig) {
if (!orig) return orig
return function (target, mode, cb) {
return orig.call(fs, target, mode, function (er) {
if (chownErOk(er)) er = null
if (cb) cb.apply(this, arguments)
})
}
}
function chmodFixSync (orig) {
if (!orig) return orig
return function (target, mode) {
try {
return orig.call(fs, target, mode)
} catch (er) {
if (!chownErOk(er)) throw er
}
}
}
function chownFix (orig) {
if (!orig) return orig
return function (target, uid, gid, cb) {
return orig.call(fs, target, uid, gid, function (er) {
if (chownErOk(er)) er = null
if (cb) cb.apply(this, arguments)
})
}
}
function chownFixSync (orig) {
if (!orig) return orig
return function (target, uid, gid) {
try {
return orig.call(fs, target, uid, gid)
} catch (er) {
if (!chownErOk(er)) throw er
}
}
}
function statFix (orig) {
if (!orig) return orig
// Older versions of Node erroneously returned signed integers for
// uid + gid.
return function (target, options, cb) {
if (typeof options === 'function') {
cb = options
options = null
}
function callback (er, stats) {
if (stats) {
if (stats.uid < 0) stats.uid += 0x100000000
if (stats.gid < 0) stats.gid += 0x100000000
}
if (cb) cb.apply(this, arguments)
}
return options ? orig.call(fs, target, options, callback)
: orig.call(fs, target, callback)
}
}
function statFixSync (orig) {
if (!orig) return orig
// Older versions of Node erroneously returned signed integers for
// uid + gid.
return function (target, options) {
var stats = options ? orig.call(fs, target, options)
: orig.call(fs, target)
if (stats.uid < 0) stats.uid += 0x100000000
if (stats.gid < 0) stats.gid += 0x100000000
return stats;
}
}
// ENOSYS means that the fs doesn't support the op. Just ignore
// that, because it doesn't matter.
//
// if there's no getuid, or if getuid() is something other
// than 0, and the error is EINVAL or EPERM, then just ignore
// it.
//
// This specific case is a silent failure in cp, install, tar,
// and most other unix tools that manage permissions.
//
// When running as root, or if other types of errors are
// encountered, then it's strict.
function chownErOk (er) {
if (!er)
return true
if (er.code === "ENOSYS")
return true
var nonroot = !process.getuid || process.getuid() !== 0
if (nonroot) {
if (er.code === "EINVAL" || er.code === "EPERM")
return true
}
return false
}
}
| {
"pile_set_name": "Github"
} |
#ident "@(#) NEC mode542x.h 1.3 95/07/05 13:10:57"
/*++
Copyright (c) 1992 Microsoft Corporation
Module Name:
Mode542x.h
Abstract:
This module contains all the global data used by the Cirrus Logic
CL-542x driver.
Environment:
Kernel mode
Revision History:
--*/
//
// The next set of tables are for the CL542x
// Note: all resolutions supported
//
//
// 640x480 16-color mode (BIOS mode 12) set command string for CL 542x.
//
USHORT CL542x_640x480[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM,
GRAPH_ADDRESS_PORT,
3,
0x0009, 0x000a, 0x000b, // no banking in 640x480 mode
EOD
};
//
// 800x600 16-color (60Hz refresh) mode set command string for CL 542x.
//
USHORT CL542x_800x600[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM,
GRAPH_ADDRESS_PORT,
3,
0x0009, 0x000a, 0x000b, // no banking in 800x600 mode
EOD
};
//
// 1024x768 16-color (60Hz refresh) mode set command string for CL 542x.
//
USHORT CL542x_1024x768[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM,
GRAPH_ADDRESS_PORT,
3,
#if ONE_64K_BANK
0x0009, 0x000a, 0x000b,
#endif
#if TWO_32K_BANKS
0x0009, 0x000a, 0x010b,
#endif
OB,
DAC_PIXEL_MASK_PORT,
0xFF,
EOD
};
//-----------------------------
// standard VGA text modes here
// 80x25 at 640x350
//
//-----------------------------
//
// 80x25 text mode set command string for CL 542x.
// (720x400 pixel resolution; 9x16 character cell.)
//
USHORT CL542x_80x25Text[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM,
GRAPH_ADDRESS_PORT,
3,
0x0009, 0x000a, 0x000b, // no banking in text mode
EOD
};
//
// 80x25 text mode set command string for CL 542x.
// (640x350 pixel resolution; 8x14 character cell.)
//
USHORT CL542x_80x25_14_Text[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM,
GRAPH_ADDRESS_PORT,
3,
0x0009, 0x000a, 0x000b, // no banking in text mode
EOD
};
//
// 1280x1024 16-color mode (BIOS mode 0x6C) set command string for CL 542x.
//
USHORT CL542x_1280x1024[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM,
GRAPH_ADDRESS_PORT,
3,
#if ONE_64K_BANK
0x0009, 0x000a, 0x000b,
#endif
#if TWO_32K_BANKS
0x0009, 0x000a, 0x010b,
#endif
EOD
};
//
// 640x480 64k-color mode (BIOS mode 0x64) set command string for CL 542x.
//
USHORT CL542x_640x480_64k[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM,
GRAPH_ADDRESS_PORT,
4,
0x0506, // Some BIOS's set Chain Odd maps bit
#if ONE_64K_BANK
0x0009, 0x000a, 0x000b,
#endif
#if TWO_32K_BANKS
0x0009, 0x000a, 0x010b,
#endif
EOD
};
#ifdef _X86_
//
// 640x480 256-color mode (BIOS mode 0x5F) set command string for CL 542x.
//
USHORT CL542x_640x480_256[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM,
GRAPH_ADDRESS_PORT,
3,
#if ONE_64K_BANK
0x0009, 0x000a, 0x000b,
#endif
#if TWO_32K_BANKS
0x0009, 0x000a, 0x010b,
#endif
EOD
};
//
// 800x600 256-color mode (BIOS mode 0x5C) set command string for CL 542x.
//
USHORT CL542x_800x600_256[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM,
GRAPH_ADDRESS_PORT,
3,
#if ONE_64K_BANK
0x0009, 0x000a, 0x000b,
#endif
#if TWO_32K_BANKS
0x0009, 0x000a, 0x010b,
#endif
EOD
};
#else
//
// NOTE(DBCS) : Update 94/09/12 - NEC Corporation
//
// - Add mode set command string for NEC MIPS machine.
//
// - 640x480 256 color 72Hz
// - 800x600 256 color 56 / 60Hz
// - 1024x768 256 color 70 / 45Hz
//
#if defined(DBCS) && defined(_MIPS_)
//
// For MIPS NEC machine only
//
//
// 640x480 256-color 60Hz mode (BIOS mode 0x5F) set command string for
// CL 542x.
//
USHORT CL542x_640x480_256_60[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM, // begin setmode
SEQ_ADDRESS_PORT,
15, // count
0x100, // start sync reset
0x0101,0x0F02,0x0003,0x0E04, // program up sequencer
//
// the Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed Liner addressing.
//
(LA_MASK << 12 | 0x0107),
0x0008,
0x4A0B,0x5B0C,0x450D,0x7E0E,
0x2B1B,0x2F1C,0x301D,0x331E,
OB, // point sequencer index to ff
SEQ_ADDRESS_PORT,
0x0F,
METAOUT+MASKOUT, // masked out.
SEQ_DATA_PORT,
0xDF,0x20, // and mask, xor mask
OB, // misc. register
MISC_OUTPUT_REG_WRITE_PORT,
0xE3,
OW, // text/graphics bit
GRAPH_ADDRESS_PORT,
0x506,
OW, // end sync reset
SEQ_ADDRESS_PORT,
0x300,
OW, // unprotect crtc 0-7
CRTC_ADDRESS_PORT_COLOR,
0x2011,
METAOUT+INDXOUT, // program crtc registers
CRTC_ADDRESS_PORT_COLOR,
28,0, // count, startindex
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0x5D, 0x4F, 0x50, 0x82, 0x53, 0x9F,
0x00, 0x3E, 0x00, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xE1, 0x83,
0xDF, 0x50, 0x00, 0xE7, 0x04, 0xE3,
0xFF, 0x00, 0x00, 0x22,
#else
0x5f, 0x4f, 0x50, 0x82, 0x54, 0x80,
0x0b, 0x3e, 0x00, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xea, 0x8c,
0xdf, 0x50, 0x00, 0xe7, 0x04, 0xe3,
0xff, 0x00, 0x00, 0x22,
#endif // defined(DBCS) && defined(_MIPS_)
METAOUT+INDXOUT, // program gdc registers
GRAPH_ADDRESS_PORT,
9,0, // count, startindex
0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x05, 0x0F, 0xFF,
IB, // prepare atc for writing
INPUT_STATUS_1_COLOR,
METAOUT+ATCOUT, // program atc registers
ATT_ADDRESS_PORT,
21,0, // count, startindex
0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F, 0x41, 0x00,
0x0F, 0x00, 0x00,
OB, // turn video on.
ATT_ADDRESS_PORT,
0x20,
OB,
DAC_PIXEL_MASK_PORT,
0xFF,
OWM,
GRAPH_ADDRESS_PORT,
3,
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed it for Liner addressing.
//
0x0009, 0x000a, 0x000b,
EOD
};
//
// 640x480 256-color 72Hz mode (BIOS mode 0x5F) set command string for
// CL 542x.
//
USHORT CL542x_640x480_256_72[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM, // begin setmode
SEQ_ADDRESS_PORT,
15, // count
0x100, // start sync reset
0x0101,0x0F02,0x0003,0x0E04, // program up sequencer
//
// the Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed Liner addressing.
//
(LA_MASK << 12 | 0x0107),
0x0008,
0x4A0B,0x5B0C,0x450D,0x420E,
0x2B1B,0x2F1C,0x301D,0x1F1E,
OB, // point sequencer index to ff
SEQ_ADDRESS_PORT,
0x0F,
METAOUT+MASKOUT, // masked out.
SEQ_DATA_PORT,
0xDF,0x20, // and mask, xor mask
OB, // misc. register
MISC_OUTPUT_REG_WRITE_PORT,
0xEF,
OW, // text/graphics bit
GRAPH_ADDRESS_PORT,
0x506,
OW, // end sync reset
SEQ_ADDRESS_PORT,
0x300,
OW, // unprotect crtc 0-7
CRTC_ADDRESS_PORT_COLOR,
0x2011,
METAOUT+INDXOUT, // program crtc registers
CRTC_ADDRESS_PORT_COLOR,
28,0, // count, startindex
//
// NOTE(DBCS) : Update 95/06/30 - NEC Corporation (same as cirrus\mode542x.h)
//
// - Set Mode Type is VESA compatible. (Old Miss match)
//
#if defined(DBCS) && defined(_MIPS_)
0x61, 0x4F, 0x50, 0x82, 0x54, 0x99,
0xF6, 0x1F, 0x00, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xE0, 0x03,
0xDF, 0x50, 0x00, 0xE7, 0x04, 0xE3,
0xFF, 0x00, 0x00, 0x22,
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
// 0x63, 0x4F, 0x50, 0x82, 0x55, 0x9A, thase parameter not match
// 0x06, 0x3E, 0x00, 0x40, 0x00, 0x00, VESA Mode.
// 0x00, 0x00, 0x00, 0x00, 0xE8, 0x8B,
// 0xDF, 0x50, 0x00, 0xE7, 0x04, 0xE3,
// 0xFF, 0x00, 0x00, 0x22,
#else
0x5f, 0x4f, 0x50, 0x82, 0x54, 0x80,
0x0b, 0x3e, 0x00, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xea, 0x8c,
0xdf, 0x50, 0x00, 0xe7, 0x04, 0xe3,
0xff, 0x00, 0x00, 0x22,
#endif // defined(DBCS) && defined(_MIPS_)
METAOUT+INDXOUT, // program gdc registers
GRAPH_ADDRESS_PORT,
9,0, // count, startindex
0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x05, 0x0F, 0xFF,
IB, // prepare atc for writing
INPUT_STATUS_1_COLOR,
METAOUT+ATCOUT, // program atc registers
ATT_ADDRESS_PORT,
21,0, // count, startindex
0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F, 0x41, 0x00,
0x0F, 0x00, 0x00,
OB, // turn video on.
ATT_ADDRESS_PORT,
0x20,
OB,
DAC_PIXEL_MASK_PORT,
0xFF,
OWM,
GRAPH_ADDRESS_PORT,
3,
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed it for Liner addressing.
//
0x0009, 0x000a, 0x000b,
EOD
};
//
// 800x600 256-color 56Hz mode (BIOS mode 0x5C) set command string for
// CL 542x.
//
USHORT CL542x_800x600_256_56[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM, // begin setmode
SEQ_ADDRESS_PORT,
15, // count
0x100, // start sync reset
0x0101,0x0F02,0x0003,0x0E04, // program up sequencer
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed Liner addressing.
//
(LA_MASK << 12 | 0x0107),
0x0008,
0x4A0B,0x5B0C,0x450D,0x7E0E,
0x2B1B,0x2F1C,0x301D,0x331E,
OB, // point sequencer index to ff
SEQ_ADDRESS_PORT,
0x0F,
METAOUT+MASKOUT, // masked out.
SEQ_DATA_PORT,
0xDF,0x20, // and mask, xor mask
OB, // misc. register
MISC_OUTPUT_REG_WRITE_PORT,
0xEF,
OW, // text/graphics bit
GRAPH_ADDRESS_PORT,
0x506,
OW, // end sync reset
SEQ_ADDRESS_PORT,
0x300,
OW, // unprotect crtc 0-7
CRTC_ADDRESS_PORT_COLOR,
0x2011,
METAOUT+INDXOUT, // program crtc registers
CRTC_ADDRESS_PORT_COLOR,
28,0, // count, startindex
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0x7B, 0x63, 0x64, 0x80, 0x69, 0x12,
0x6F, 0xF0, 0x00, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x58, 0x8A,
0x57, 0x64, 0x00, 0x5F, 0x91, 0xE3,
0xFF, 0x00, 0x00, 0x22,
#else
0x7D, 0x63, 0x64, 0x80, 0x6D, 0x1C,
0x98, 0xF0, 0x00, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7B, 0x80,
0x57, 0x64, 0x00, 0x5F, 0x91, 0xe3,
0xff, 0x00, 0x00, 0x22,
#endif // defined(DBCS) && defined(_MIPS_)
METAOUT+INDXOUT, // program gdc registers
GRAPH_ADDRESS_PORT,
9,0, // count, startindex
0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x05, 0x0F, 0xFF,
IB, // prepare atc for writing
INPUT_STATUS_1_COLOR,
METAOUT+ATCOUT, // program atc registers
ATT_ADDRESS_PORT,
21,0, // count, startindex
0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F, 0x41, 0x00,
0x0F, 0x00, 0x00,
OB, // turn video on.
ATT_ADDRESS_PORT,
0x20,
OB,
DAC_PIXEL_MASK_PORT,
0xFF,
OWM,
GRAPH_ADDRESS_PORT,
3,
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed it for Liner addressing.
//
0x0009, 0x000a, 0x000b,
EOD
};
//
// 800x600 256-color 60Hz mode (BIOS mode 0x5C) set command string for
// CL 542x.
//
USHORT CL542x_800x600_256_60[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM, // begin setmode
SEQ_ADDRESS_PORT,
15, // count
0x100, // start sync reset
0x0101,0x0F02,0x0003,0x0E04, // program up sequencer
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed Liner addressing.
//
(LA_MASK << 12 | 0x0107),
0x0008,
0x4A0B,0x5B0C,0x450D,0x510E,
0x2B1B,0x2F1C,0x301D,0x3A1E,
OB, // point sequencer index to ff
SEQ_ADDRESS_PORT,
0x0F,
METAOUT+MASKOUT, // masked out.
SEQ_DATA_PORT,
0xDF,0x20, // and mask, xor mask
OB, // misc. register
MISC_OUTPUT_REG_WRITE_PORT,
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0xEF,
#else
0x2F,
#endif // defined(DBCS) && defined(_MIPS_)
OW, // text/graphics bit
GRAPH_ADDRESS_PORT,
0x506,
OW, // end sync reset
SEQ_ADDRESS_PORT,
0x300,
OW, // unprotect crtc 0-7
CRTC_ADDRESS_PORT_COLOR,
0x2011,
METAOUT+INDXOUT, // program crtc registers
CRTC_ADDRESS_PORT_COLOR,
28,0, // count, startindex
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0x7F, 0x63, 0x64, 0x80, 0x6B, 0x1B,
0x72, 0xF0, 0x00, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x58, 0x8C,
0x57, 0x64, 0x00, 0x5F, 0x91, 0xE3,
0xFF, 0x00, 0x00, 0x22,
#else
0x7D, 0x63, 0x64, 0x80, 0x6D, 0x1C,
0x98, 0xF0, 0x00, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7B, 0x80,
0x57, 0x64, 0x00, 0x5F, 0x91, 0xe3,
0xff, 0x00, 0x00, 0x22,
#endif // defined(DBCS) && defined(_MIPS_)
METAOUT+INDXOUT, // program gdc registers
GRAPH_ADDRESS_PORT,
9,0, // count, startindex
0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x05, 0x0F, 0xFF,
IB, // prepare atc for writing
INPUT_STATUS_1_COLOR,
METAOUT+ATCOUT, // program atc registers
ATT_ADDRESS_PORT,
21,0, // count, startindex
0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F, 0x41, 0x00,
0x0F, 0x00, 0x00,
OB, // turn video on.
ATT_ADDRESS_PORT,
0x20,
OB,
DAC_PIXEL_MASK_PORT,
0xFF,
OWM,
GRAPH_ADDRESS_PORT,
3,
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed it for Liner addressing.
//
0x0009, 0x000a, 0x000b,
EOD
};
//
// 800x600 256-color 72Hz mode (BIOS mode 0x5C) set command string for
// CL 542x.
//
USHORT CL542x_800x600_256_72[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM, // begin setmode
SEQ_ADDRESS_PORT,
15, // count
0x100, // start sync reset
0x0101,0x0F02,0x0003,0x0E04, // program up sequencer
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed Liner addressing.
//
(LA_MASK << 12 | 0x0107),
0x0008,
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0x4A0B,0x5B0C,0x450D,0x650E,
#else
0x4A0B,0x5B0C,0x450D,0x640E,
#endif // defined(DBCS) && defined(_MIPS_)
0x2B1B,0x2F1C,0x301D,0x3A1E,
OB, // point sequencer index to ff
SEQ_ADDRESS_PORT,
0x0F,
METAOUT+MASKOUT, // masked out.
SEQ_DATA_PORT,
0xDF,0x20, // and mask, xor mask
OB, // misc. register
MISC_OUTPUT_REG_WRITE_PORT,
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0xEF,
#else
0x2F,
#endif // defined(DBCS) && defined(_MIPS_)
OW, // text/graphics bit
GRAPH_ADDRESS_PORT,
0x506,
OW, // end sync reset
SEQ_ADDRESS_PORT,
0x300,
OW, // unprotect crtc 0-7
CRTC_ADDRESS_PORT_COLOR,
0x2011,
METAOUT+INDXOUT, // program crtc registers
CRTC_ADDRESS_PORT_COLOR,
28,0, // count, startindex
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0x7D, 0x63, 0x64, 0x80, 0x6D, 0x1C,
0x96, 0xF0, 0x00, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7B, 0x81,
0x57, 0x64, 0x00, 0x5F, 0x91, 0xE3,
0xFF, 0x00, 0x00, 0x22,
#else
0x7D, 0x63, 0x64, 0x80, 0x6D, 0x1C,
0x98, 0xF0, 0x00, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7B, 0x80,
0x57, 0x64, 0x00, 0x5F, 0x91, 0xe3,
0xff, 0x00, 0x00, 0x22,
#endif // defined(DBCS) && defined(_MIPS_)
METAOUT+INDXOUT, // program gdc registers
GRAPH_ADDRESS_PORT,
9,0, // count, startindex
0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x05, 0x0F, 0xFF,
IB, // prepare atc for writing
INPUT_STATUS_1_COLOR,
METAOUT+ATCOUT, // program atc registers
ATT_ADDRESS_PORT,
21,0, // count, startindex
0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F, 0x41, 0x00,
0x0F, 0x00, 0x00,
OB, // turn video on.
ATT_ADDRESS_PORT,
0x20,
OB,
DAC_PIXEL_MASK_PORT,
0xFF,
OWM,
GRAPH_ADDRESS_PORT,
3,
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed it for Liner addressing.
//
0x0009, 0x000a, 0x000b,
EOD
};
//
// 1024x768 256-color 60Hz mode (BIOS mode 0x60) set command string for
// CL 542x.
//
USHORT CL542x_1024x768_256_60[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM, // begin setmode
SEQ_ADDRESS_PORT,
15, // count
0x100, // start sync reset
0x0101,0x0F02,0x0003,0x0E04, // program up sequencer
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed Liner addressing.
//
(LA_MASK << 12 | 0x0107),
0x0008,
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0x4A0B, 0x5B0C, 0x450D, 0x760E,
0x2B1B, 0x2F1C, 0x301D, 0x341E,
#else
0x4A0B, 0x5B0C, 0x450D, 0x3B0E,
0x2B1B, 0x2F1C, 0x301D, 0x1A1E,
#endif // defined(DBCS) && defined(_MIPS_)
OB, // point sequencer index to ff
SEQ_ADDRESS_PORT,
0x0F,
METAOUT+MASKOUT, // masked out.
SEQ_DATA_PORT,
0xDF,0x20, // and mask, xor mask
OB, // misc. register
MISC_OUTPUT_REG_WRITE_PORT,
0xEF,
OW, // text/graphics bit
GRAPH_ADDRESS_PORT,
0x506,
OW, // end sync reset
SEQ_ADDRESS_PORT,
0x300,
OW, // unprotect crtc 0-7
CRTC_ADDRESS_PORT_COLOR,
0x2011,
METAOUT+INDXOUT, // program crtc registers
CRTC_ADDRESS_PORT_COLOR,
28,0, // count, startindex
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0xA3, 0x7F, 0x80, 0x86, 0x85, 0x96,
0x24, 0xFD, 0x00, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x88,
0xFF, 0x80, 0x00, 0x00, 0x24, 0xE3,
0xFF, 0x4A, 0x00, 0x22,
#else
0xA3, 0x7F, 0x80, 0x86, 0x85, 0x96,
0x24, 0xFD, 0x00, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x88,
0xFF, 0x80, 0x00, 0x00, 0x24, 0xe3,
0xff, 0x4A, 0x00, 0x22,
#endif // defined(DBCS) && defined(_MIPS_)
METAOUT+INDXOUT, // program gdc registers
GRAPH_ADDRESS_PORT,
9,0, // count, startindex
0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x05, 0x0F, 0xFF,
IB, // prepare atc for writing
INPUT_STATUS_1_COLOR,
METAOUT+ATCOUT, // program atc registers
ATT_ADDRESS_PORT,
21,0, // count, startindex
0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F, 0x41, 0x00,
0x0F, 0x00, 0x00,
OB, // turn video on.
ATT_ADDRESS_PORT,
0x20,
OB,
DAC_PIXEL_MASK_PORT,
0xFF,
OWM,
GRAPH_ADDRESS_PORT,
3,
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed it for Liner addressing.
//
0x0009, 0x000a, 0x000b,
EOD
};
//
// 1024x768 256-color 70Hz mode (BIOS mode 0x60) set command string for
// CL 542x.
//
USHORT CL542x_1024x768_256_70[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM, // begin setmode
SEQ_ADDRESS_PORT,
15, // count
0x100, // start sync reset
0x0101,0x0F02,0x0003,0x0E04, // program up sequencer
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed Liner addressing.
//
(LA_MASK << 12 | 0x0107),
0x0008,
0x4A0B, 0x5B0C, 0x450D, 0x6E0E,
0x2B1B, 0x2F1C, 0x301D, 0x2A1E,
OB, // point sequencer index to ff
SEQ_ADDRESS_PORT,
0x0F,
METAOUT+MASKOUT, // masked out.
SEQ_DATA_PORT,
0xDF,0x20, // and mask, xor mask
OB, // misc. register
MISC_OUTPUT_REG_WRITE_PORT,
0xEF,
OW, // text/graphics bit
GRAPH_ADDRESS_PORT,
0x506,
OW, // end sync reset
SEQ_ADDRESS_PORT,
0x300,
OW, // unprotect crtc 0-7
CRTC_ADDRESS_PORT_COLOR,
0x2011,
METAOUT+INDXOUT, // program crtc registers
CRTC_ADDRESS_PORT_COLOR,
28,0, // count, startindex
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0xA1, 0x7F, 0x80, 0x86, 0x85, 0x96,
0x24, 0xFD, 0x00, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x88,
0xFF, 0x80, 0x00, 0x00, 0x24, 0xE3,
0xFF, 0x4A, 0x00, 0x22,
#else
0xA3, 0x7F, 0x80, 0x86, 0x85, 0x96,
0x24, 0xFD, 0x00, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x88,
0xFF, 0x80, 0x00, 0x00, 0x24, 0xe3,
0xff, 0x4A, 0x00, 0x22,
#endif // defined(DBCS) && defined(_MIPS_)
METAOUT+INDXOUT, // program gdc registers
GRAPH_ADDRESS_PORT,
9,0, // count, startindex
0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x05, 0x0F, 0xFF,
IB, // prepare atc for writing
INPUT_STATUS_1_COLOR,
METAOUT+ATCOUT, // program atc registers
ATT_ADDRESS_PORT,
21,0, // count, startindex
0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F, 0x41, 0x00,
0x0F, 0x00, 0x00,
OB, // turn video on.
ATT_ADDRESS_PORT,
0x20,
OB,
DAC_PIXEL_MASK_PORT,
0xFF,
OWM,
GRAPH_ADDRESS_PORT,
3,
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed it for Liner addressing.
//
0x0009, 0x000a, 0x000b,
EOD
};
//
// 1024x768 256-color 87Hz mode (BIOS mode 0x60) set command string for
// CL 542x. (Interlaced)
//
USHORT CL542x_1024x768_256_87[] = {
OWM, // begin setmode
SEQ_ADDRESS_PORT,
2, // count
0x1206, // enable extensions
0x0012,
OWM, // begin setmode
SEQ_ADDRESS_PORT,
15, // count
0x100, // start sync reset
0x0101,0x0F02,0x0003,0x0E04, // program up sequencer
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed Liner addressing.
//
(LA_MASK << 12 | 0x0107),
0x0008,
0x4A0B, 0x5B0C, 0x450D, 0x550E,
0x2B1B, 0x2F1C, 0x301D, 0x361E,
OB, // point sequencer index to ff
SEQ_ADDRESS_PORT,
0x0F,
METAOUT+MASKOUT, // masked out.
SEQ_DATA_PORT,
0xDF,0x20, // and mask, xor mask
OB, // misc. register
MISC_OUTPUT_REG_WRITE_PORT,
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0xEF,
#else
0x2F,
#endif // defined(DBCS) && defined(_MIPS_)
OW, // text/graphics bit
GRAPH_ADDRESS_PORT,
0x506,
OW, // end sync reset
SEQ_ADDRESS_PORT,
0x300,
OW, // unprotect crtc 0-7
CRTC_ADDRESS_PORT_COLOR,
0x2011,
METAOUT+INDXOUT, // program crtc registers
CRTC_ADDRESS_PORT_COLOR,
28,0, // count, startindex
//
// NOTE(DBCS) : Update 94/10/26 - NEC Corporation
//
// - Set Mode Type is VESA compatible.
//
#if defined(DBCS) && defined(_MIPS_)
0x99, 0x7F, 0x80, 0x86, 0x83, 0x99,
0x96, 0x1F, 0x00, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7F, 0x83,
0x7F, 0x80, 0x00, 0x7F, 0x12, 0xE3,
0xff, 0x4A, 0x01, 0x22,
#else
0xA3, 0x7F, 0x80, 0x86, 0x85, 0x96,
0xBE, 0x1F, 0x00, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x81, 0x84,
0x7F, 0x80, 0x00, 0x80, 0x12, 0xE3,
0xff, 0x4A, 0x01, 0x22,
#endif // defined(DBCS) && defined(_MIPS_)
METAOUT+INDXOUT, // program gdc registers
GRAPH_ADDRESS_PORT,
9,0, // count, startindex
0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x05, 0x0F, 0xFF,
IB, // prepare atc for writing
INPUT_STATUS_1_COLOR,
METAOUT+ATCOUT, // program atc registers
ATT_ADDRESS_PORT,
21,0, // count, startindex
0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F, 0x41, 0x00,
0x0F, 0x00, 0x00,
OB, // turn video on.
ATT_ADDRESS_PORT,
0x20,
OB,
DAC_PIXEL_MASK_PORT,
0xFF,
OWM,
GRAPH_ADDRESS_PORT,
3,
//
// The Miniport Driver for R96 machine is Liner addressing mode.
// This set command was changed it for Liner addressing.
//
0x0009, 0x000a, 0x000b,
EOD
};
#endif // defined(DBCS) && defined(_MIPS_)
#endif
| {
"pile_set_name": "Github"
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GerberClipper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("This is not Rocket Science")]
[assembly: AssemblyProduct("CLIP")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4f1ec287-9873-4a1a-bb2e-6343b5237a91")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"pile_set_name": "Github"
} |
/**
******************************************************************************
* @file stm32f4xx_hash.h
* @author MCD Application Team
* @version V1.0.0
* @date 30-September-2011
* @brief This file contains all the functions prototypes for the HASH
* firmware library.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_HASH_H
#define __STM32F4xx_HASH_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx.h"
/** @addtogroup STM32F4xx_StdPeriph_Driver
* @{
*/
/** @addtogroup HASH
* @{
*/
/* Exported types ------------------------------------------------------------*/
/**
* @brief HASH Init structure definition
*/
typedef struct
{
uint32_t HASH_AlgoSelection; /*!< SHA-1 or MD5. This parameter can be a value
of @ref HASH_Algo_Selection */
uint32_t HASH_AlgoMode; /*!< HASH or HMAC. This parameter can be a value
of @ref HASH_processor_Algorithm_Mode */
uint32_t HASH_DataType; /*!< 32-bit data, 16-bit data, 8-bit data or
bit-string. This parameter can be a value of
@ref HASH_Data_Type */
uint32_t HASH_HMACKeyType; /*!< HMAC Short key or HMAC Long Key. This parameter
can be a value of @ref HASH_HMAC_Long_key_only_for_HMAC_mode */
}HASH_InitTypeDef;
/**
* @brief HASH message digest result structure definition
*/
typedef struct
{
uint32_t Data[5]; /*!< Message digest result : 5x 32bit words for SHA1 or
4x 32bit words for MD5 */
} HASH_MsgDigest;
/**
* @brief HASH context swapping structure definition
*/
typedef struct
{
uint32_t HASH_IMR;
uint32_t HASH_STR;
uint32_t HASH_CR;
uint32_t HASH_CSR[51];
}HASH_Context;
/* Exported constants --------------------------------------------------------*/
/** @defgroup HASH_Exported_Constants
* @{
*/
/** @defgroup HASH_Algo_Selection
* @{
*/
#define HASH_AlgoSelection_SHA1 ((uint16_t)0x0000) /*!< HASH function is SHA1 */
#define HASH_AlgoSelection_MD5 ((uint16_t)0x0080) /*!< HASH function is MD5 */
#define IS_HASH_ALGOSELECTION(ALGOSELECTION) (((ALGOSELECTION) == HASH_AlgoSelection_SHA1) || \
((ALGOSELECTION) == HASH_AlgoSelection_MD5))
/**
* @}
*/
/** @defgroup HASH_processor_Algorithm_Mode
* @{
*/
#define HASH_AlgoMode_HASH ((uint16_t)0x0000) /*!< Algorithm is HASH */
#define HASH_AlgoMode_HMAC ((uint16_t)0x0040) /*!< Algorithm is HMAC */
#define IS_HASH_ALGOMODE(ALGOMODE) (((ALGOMODE) == HASH_AlgoMode_HASH) || \
((ALGOMODE) == HASH_AlgoMode_HMAC))
/**
* @}
*/
/** @defgroup HASH_Data_Type
* @{
*/
#define HASH_DataType_32b ((uint16_t)0x0000)
#define HASH_DataType_16b ((uint16_t)0x0010)
#define HASH_DataType_8b ((uint16_t)0x0020)
#define HASH_DataType_1b ((uint16_t)0x0030)
#define IS_HASH_DATATYPE(DATATYPE) (((DATATYPE) == HASH_DataType_32b)|| \
((DATATYPE) == HASH_DataType_16b)|| \
((DATATYPE) == HASH_DataType_8b)|| \
((DATATYPE) == HASH_DataType_1b))
/**
* @}
*/
/** @defgroup HASH_HMAC_Long_key_only_for_HMAC_mode
* @{
*/
#define HASH_HMACKeyType_ShortKey ((uint32_t)0x00000000) /*!< HMAC Key is <= 64 bytes */
#define HASH_HMACKeyType_LongKey ((uint32_t)0x00010000) /*!< HMAC Key is > 64 bytes */
#define IS_HASH_HMAC_KEYTYPE(KEYTYPE) (((KEYTYPE) == HASH_HMACKeyType_ShortKey) || \
((KEYTYPE) == HASH_HMACKeyType_LongKey))
/**
* @}
*/
/** @defgroup Number_of_valid_bits_in_last_word_of_the_message
* @{
*/
#define IS_HASH_VALIDBITSNUMBER(VALIDBITS) ((VALIDBITS) <= 0x1F)
/**
* @}
*/
/** @defgroup HASH_interrupts_definition
* @{
*/
#define HASH_IT_DINI ((uint8_t)0x01) /*!< A new block can be entered into the input buffer (DIN)*/
#define HASH_IT_DCI ((uint8_t)0x02) /*!< Digest calculation complete */
#define IS_HASH_IT(IT) ((((IT) & (uint8_t)0xFC) == 0x00) && ((IT) != 0x00))
#define IS_HASH_GET_IT(IT) (((IT) == HASH_IT_DINI) || ((IT) == HASH_IT_DCI))
/**
* @}
*/
/** @defgroup HASH_flags_definition
* @{
*/
#define HASH_FLAG_DINIS ((uint16_t)0x0001) /*!< 16 locations are free in the DIN : A new block can be entered into the input buffer.*/
#define HASH_FLAG_DCIS ((uint16_t)0x0002) /*!< Digest calculation complete */
#define HASH_FLAG_DMAS ((uint16_t)0x0004) /*!< DMA interface is enabled (DMAE=1) or a transfer is ongoing */
#define HASH_FLAG_BUSY ((uint16_t)0x0008) /*!< The hash core is Busy : processing a block of data */
#define HASH_FLAG_DINNE ((uint16_t)0x1000) /*!< DIN not empty : The input buffer contains at least one word of data */
#define IS_HASH_GET_FLAG(FLAG) (((FLAG) == HASH_FLAG_DINIS) || \
((FLAG) == HASH_FLAG_DCIS) || \
((FLAG) == HASH_FLAG_DMAS) || \
((FLAG) == HASH_FLAG_BUSY) || \
((FLAG) == HASH_FLAG_DINNE))
#define IS_HASH_CLEAR_FLAG(FLAG)(((FLAG) == HASH_FLAG_DINIS) || \
((FLAG) == HASH_FLAG_DCIS))
/**
* @}
*/
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/* Function used to set the HASH configuration to the default reset state ****/
void HASH_DeInit(void);
/* HASH Configuration function ************************************************/
void HASH_Init(HASH_InitTypeDef* HASH_InitStruct);
void HASH_StructInit(HASH_InitTypeDef* HASH_InitStruct);
void HASH_Reset(void);
/* HASH Message Digest generation functions ***********************************/
void HASH_DataIn(uint32_t Data);
uint8_t HASH_GetInFIFOWordsNbr(void);
void HASH_SetLastWordValidBitsNbr(uint16_t ValidNumber);
void HASH_StartDigest(void);
void HASH_GetDigest(HASH_MsgDigest* HASH_MessageDigest);
/* HASH Context swapping functions ********************************************/
void HASH_SaveContext(HASH_Context* HASH_ContextSave);
void HASH_RestoreContext(HASH_Context* HASH_ContextRestore);
/* HASH's DMA interface function **********************************************/
void HASH_DMACmd(FunctionalState NewState);
/* HASH Interrupts and flags management functions *****************************/
void HASH_ITConfig(uint8_t HASH_IT, FunctionalState NewState);
FlagStatus HASH_GetFlagStatus(uint16_t HASH_FLAG);
void HASH_ClearFlag(uint16_t HASH_FLAG);
ITStatus HASH_GetITStatus(uint8_t HASH_IT);
void HASH_ClearITPendingBit(uint8_t HASH_IT);
/* High Level SHA1 functions **************************************************/
ErrorStatus HASH_SHA1(uint8_t *Input, uint32_t Ilen, uint8_t Output[20]);
ErrorStatus HMAC_SHA1(uint8_t *Key, uint32_t Keylen,
uint8_t *Input, uint32_t Ilen,
uint8_t Output[20]);
/* High Level MD5 functions ***************************************************/
ErrorStatus HASH_MD5(uint8_t *Input, uint32_t Ilen, uint8_t Output[16]);
ErrorStatus HMAC_MD5(uint8_t *Key, uint32_t Keylen,
uint8_t *Input, uint32_t Ilen,
uint8_t Output[16]);
#ifdef __cplusplus
}
#endif
#endif /*__STM32F4xx_HASH_H */
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
| {
"pile_set_name": "Github"
} |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opengles;
import org.lwjgl.system.*;
import static org.lwjgl.system.dyncall.DynCallback.*;
/**
* Instances of this interface may be passed to the {@link GLES32#glDebugMessageCallback DebugMessageCallback} method.
*
* <h3>Type</h3>
*
* <pre><code>
* void (*) (
* GLenum source,
* GLenum type,
* GLuint id,
* GLenum severity,
* GLsizei length,
* GLchar const *message,
* void const *userParam
* )</code></pre>
*/
@FunctionalInterface
@NativeType("GLDEBUGPROC")
public interface GLDebugMessageCallbackI extends CallbackI.V {
String SIGNATURE = Callback.__stdcall("(iiiiipp)v");
@Override
default String getSignature() { return SIGNATURE; }
@Override
default void callback(long args) {
invoke(
dcbArgInt(args),
dcbArgInt(args),
dcbArgInt(args),
dcbArgInt(args),
dcbArgInt(args),
dcbArgPointer(args),
dcbArgPointer(args)
);
}
/**
* Will be called when a debug message is generated.
*
* @param source the message source
* @param type the message type
* @param id the message ID
* @param severity the message severity
* @param length the message length, excluding the null-terminator
* @param message a pointer to the message string representation
* @param userParam the user-specified value that was passed when calling {@link GLES32#glDebugMessageCallback DebugMessageCallback}
*/
void invoke(@NativeType("GLenum") int source, @NativeType("GLenum") int type, @NativeType("GLuint") int id, @NativeType("GLenum") int severity, @NativeType("GLsizei") int length, @NativeType("GLchar const *") long message, @NativeType("void const *") long userParam);
} | {
"pile_set_name": "Github"
} |
/*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef WORLD_PVP_EP
#define WORLD_PVP_EP
#include "Common.h"
#include "OutdoorPvP.h"
#include "Tools/Language.h"
#include "World/WorldStateDefines.h"
enum
{
TOWER_ID_NORTHPASS = 0,
TOWER_ID_CROWNGUARD = 1,
TOWER_ID_EASTWALL = 2,
TOWER_ID_PLAGUEWOOD = 3,
MAX_EP_TOWERS = 4,
// spells
SPELL_ECHOES_OF_LORDAERON_ALLIANCE_1 = 11413,
SPELL_ECHOES_OF_LORDAERON_ALLIANCE_2 = 11414,
SPELL_ECHOES_OF_LORDAERON_ALLIANCE_3 = 11415,
SPELL_ECHOES_OF_LORDAERON_ALLIANCE_4 = 1386,
SPELL_ECHOES_OF_LORDAERON_HORDE_1 = 30880,
SPELL_ECHOES_OF_LORDAERON_HORDE_2 = 30683,
SPELL_ECHOES_OF_LORDAERON_HORDE_3 = 30682,
SPELL_ECHOES_OF_LORDAERON_HORDE_4 = 29520,
// graveyards
GRAVEYARD_ZONE_EASTERN_PLAGUE = 139,
GRAVEYARD_ID_EASTERN_PLAGUE = 927,
// misc
HONOR_REWARD_PLAGUELANDS = 18,
// npcs
NPC_SPECTRAL_FLIGHT_MASTER = 17209,
// flight master factions
FACTION_FLIGHT_MASTER_ALLIANCE = 774,
FACTION_FLIGHT_MASTER_HORDE = 775,
SPELL_SPIRIT_PARTICLES_BLUE = 17327,
SPELL_SPIRIT_PARTICLES_RED = 31309,
// quest
NPC_CROWNGUARD_TOWER_QUEST_DOODAD = 17689,
NPC_EASTWALL_TOWER_QUEST_DOODAD = 17690,
NPC_NORTHPASS_TOWER_QUEST_DOODAD = 17696,
NPC_PLAGUEWOOD_TOWER_QUEST_DOODAD = 17698,
// alliance
NPC_LORDAERON_COMMANDER = 17635,
NPC_LORDAERON_SOLDIER = 17647,
// horde
NPC_LORDAERON_VETERAN = 17995,
NPC_LORDAERON_FIGHTER = 17996,
// gameobjects
GO_LORDAERON_SHRINE_ALLIANCE = 181682,
GO_LORDAERON_SHRINE_HORDE = 181955,
GO_TOWER_FLAG = 182106,
// possible shrine auras - not used
//GO_ALLIANCE_BANNER_AURA = 180100,
//GO_HORDE_BANNER_AURA = 180101,
// capture points
GO_TOWER_BANNER_NORTHPASS = 181899,
GO_TOWER_BANNER_CROWNGUARD = 182096,
GO_TOWER_BANNER_EASTWALL = 182097,
GO_TOWER_BANNER_PLAGUEWOOD = 182098,
GO_TOWER_BANNER = 182106, // tower banners around
// events
//EVENT_NORTHPASS_WIN_ALLIANCE = 10568,
//EVENT_NORTHPASS_WIN_HORDE = 10556,
//EVENT_NORTHPASS_CONTEST_ALLIANCE = 10697,
//EVENT_NORTHPASS_CONTEST_HORDE = 10696,
EVENT_NORTHPASS_PROGRESS_ALLIANCE = 10699,
EVENT_NORTHPASS_PROGRESS_HORDE = 10698,
EVENT_NORTHPASS_NEUTRAL_ALLIANCE = 11151,
EVENT_NORTHPASS_NEUTRAL_HORDE = 11150,
//EVENT_CROWNGUARD_WIN_ALLIANCE = 10570,
//EVENT_CROWNGUARD_WIN_HORDE = 10566,
//EVENT_CROWNGUARD_CONTEST_ALLIANCE = 10703,
//EVENT_CROWNGUARD_CONTEST_HORDE = 10702,
EVENT_CROWNGUARD_PROGRESS_ALLIANCE = 10705,
EVENT_CROWNGUARD_PROGRESS_HORDE = 10704,
EVENT_CROWNGUARD_NEUTRAL_ALLIANCE = 11155,
EVENT_CROWNGUARD_NEUTRAL_HORDE = 11154,
//EVENT_EASTWALL_WIN_ALLIANCE = 10569,
//EVENT_EASTWALL_WIN_HORDE = 10565,
//EVENT_EASTWALL_CONTEST_ALLIANCE = 10689,
//EVENT_EASTWALL_CONTEST_HORDE = 10690,
EVENT_EASTWALL_PROGRESS_ALLIANCE = 10691,
EVENT_EASTWALL_PROGRESS_HORDE = 10692,
EVENT_EASTWALL_NEUTRAL_ALLIANCE = 11149,
EVENT_EASTWALL_NEUTRAL_HORDE = 11148,
//EVENT_PLAGUEWOOD_WIN_ALLIANCE = 10567,
//EVENT_PLAGUEWOOD_WIN_HORDE = 10564,
//EVENT_PLAGUEWOOD_CONTEST_ALLIANCE = 10687,
//EVENT_PLAGUEWOOD_CONTEST_HORDE = 10688,
EVENT_PLAGUEWOOD_PROGRESS_ALLIANCE = 10701,
EVENT_PLAGUEWOOD_PROGRESS_HORDE = 10700,
EVENT_PLAGUEWOOD_NEUTRAL_ALLIANCE = 11153,
EVENT_PLAGUEWOOD_NEUTRAL_HORDE = 11152,
BROADCAST_TEXT_OPVP_EP_CAPTURE_NPT_H = 13635,
BROADCAST_TEXT_OPVP_EP_CAPTURE_NPT_A = 13630,
BROADCAST_TEXT_OPVP_EP_CAPTURE_CGT_H = 13633,
BROADCAST_TEXT_OPVP_EP_CAPTURE_CGT_A = 13632,
BROADCAST_TEXT_OPVP_EP_CAPTURE_EWT_H = 13636,
BROADCAST_TEXT_OPVP_EP_CAPTURE_EWT_A = 13631,
BROADCAST_TEXT_OPVP_EP_CAPTURE_PWT_H = 13634,
BROADCAST_TEXT_OPVP_EP_CAPTURE_PWT_A = 13629,
BROADCAST_TEXT_OPVP_EP_ALL_TOWERS_H = 13637, // NYI
BROADCAST_TEXT_OPVP_EP_ALL_TOWERS_A = 13638, // NYI
};
struct PlaguelandsTowerBuff
{
uint32 spellIdAlliance, spellIdHorde;
};
static const PlaguelandsTowerBuff plaguelandsTowerBuffs[MAX_EP_TOWERS] =
{
{SPELL_ECHOES_OF_LORDAERON_ALLIANCE_1, SPELL_ECHOES_OF_LORDAERON_HORDE_1},
{SPELL_ECHOES_OF_LORDAERON_ALLIANCE_2, SPELL_ECHOES_OF_LORDAERON_HORDE_2},
{SPELL_ECHOES_OF_LORDAERON_ALLIANCE_3, SPELL_ECHOES_OF_LORDAERON_HORDE_3},
{SPELL_ECHOES_OF_LORDAERON_ALLIANCE_4, SPELL_ECHOES_OF_LORDAERON_HORDE_4}
};
// capture points coordinates to sort the banners
static const float plaguelandsTowerLocations[MAX_EP_TOWERS][2] =
{
{3181.08f, -4379.36f}, // Northpass
{1860.85f, -3731.23f}, // Crownguard
{2574.51f, -4794.89f}, // Eastwall
{2962.71f, -3042.31f} // Plaguewood
};
struct PlaguelandsTowerEvent
{
uint32 eventEntry;
Team team;
uint32 defenseMessage;
uint32 worldState;
};
static const PlaguelandsTowerEvent plaguelandsTowerEvents[MAX_EP_TOWERS][4] =
{
{
{EVENT_NORTHPASS_PROGRESS_ALLIANCE, ALLIANCE, BROADCAST_TEXT_OPVP_EP_CAPTURE_NPT_A, WORLD_STATE_EP_NORTHPASS_ALLIANCE},
{EVENT_NORTHPASS_PROGRESS_HORDE, HORDE, BROADCAST_TEXT_OPVP_EP_CAPTURE_NPT_H, WORLD_STATE_EP_NORTHPASS_HORDE},
{EVENT_NORTHPASS_NEUTRAL_HORDE, TEAM_NONE, 0, WORLD_STATE_EP_NORTHPASS_NEUTRAL},
{EVENT_NORTHPASS_NEUTRAL_ALLIANCE, TEAM_NONE, 0, WORLD_STATE_EP_NORTHPASS_NEUTRAL},
},
{
{EVENT_CROWNGUARD_PROGRESS_ALLIANCE, ALLIANCE, BROADCAST_TEXT_OPVP_EP_CAPTURE_CGT_A, WORLD_STATE_EP_CROWNGUARD_ALLIANCE},
{EVENT_CROWNGUARD_PROGRESS_HORDE, HORDE, BROADCAST_TEXT_OPVP_EP_CAPTURE_CGT_H, WORLD_STATE_EP_CROWNGUARD_HORDE},
{EVENT_CROWNGUARD_NEUTRAL_HORDE, TEAM_NONE, 0, WORLD_STATE_EP_CROWNGUARD_NEUTRAL},
{EVENT_CROWNGUARD_NEUTRAL_ALLIANCE, TEAM_NONE, 0, WORLD_STATE_EP_CROWNGUARD_NEUTRAL},
},
{
{EVENT_EASTWALL_PROGRESS_ALLIANCE, ALLIANCE, BROADCAST_TEXT_OPVP_EP_CAPTURE_EWT_A, WORLD_STATE_EP_EASTWALL_ALLIANCE},
{EVENT_EASTWALL_PROGRESS_HORDE, HORDE, BROADCAST_TEXT_OPVP_EP_CAPTURE_EWT_H, WORLD_STATE_EP_EASTWALL_HORDE},
{EVENT_EASTWALL_NEUTRAL_HORDE, TEAM_NONE, 0, WORLD_STATE_EP_EASTWALL_NEUTRAL},
{EVENT_EASTWALL_NEUTRAL_ALLIANCE, TEAM_NONE, 0, WORLD_STATE_EP_EASTWALL_NEUTRAL},
},
{
{EVENT_PLAGUEWOOD_PROGRESS_ALLIANCE, ALLIANCE, BROADCAST_TEXT_OPVP_EP_CAPTURE_PWT_A, WORLD_STATE_EP_PLAGUEWOOD_ALLIANCE},
{EVENT_PLAGUEWOOD_PROGRESS_HORDE, HORDE, BROADCAST_TEXT_OPVP_EP_CAPTURE_PWT_H, WORLD_STATE_EP_PLAGUEWOOD_HORDE},
{EVENT_PLAGUEWOOD_NEUTRAL_HORDE, TEAM_NONE, 0, WORLD_STATE_EP_PLAGUEWOOD_NEUTRAL},
{EVENT_PLAGUEWOOD_NEUTRAL_ALLIANCE, TEAM_NONE, 0, WORLD_STATE_EP_PLAGUEWOOD_NEUTRAL},
},
};
static const uint32 plaguelandsBanners[MAX_EP_TOWERS] = {GO_TOWER_BANNER_NORTHPASS, GO_TOWER_BANNER_CROWNGUARD, GO_TOWER_BANNER_EASTWALL, GO_TOWER_BANNER_PLAGUEWOOD};
class OutdoorPvPEP : public OutdoorPvP
{
public:
OutdoorPvPEP();
void HandlePlayerEnterZone(Player* player, bool isMainZone) override;
void HandlePlayerLeaveZone(Player* player, bool isMainZone) override;
void FillInitialWorldStates(WorldPacket& data, uint32& count) override;
void SendRemoveWorldStates(Player* player) override;
bool HandleEvent(uint32 eventId, GameObject* go, Unit* invoker) override;
void HandleObjectiveComplete(uint32 eventId, const PlayerList& players, Team team) override;
void HandleCreatureCreate(Creature* creature) override;
void HandleGameObjectCreate(GameObject* go) override;
bool HandleGameObjectUse(Player* player, GameObject* go) override;
private:
// process capture events
bool ProcessCaptureEvent(GameObject* go, uint32 towerId, Team team, uint32 newWorldState);
void InitBanner(GameObject* go, uint32 towerId);
// Plaguewood bonus - flight master
void UnsummonFlightMaster(const WorldObject* objRef);
// Eastwall bonus - soldiers
void UnsummonSoldiers(const WorldObject* objRef);
Team m_towerOwner[MAX_EP_TOWERS];
uint32 m_towerWorldState[MAX_EP_TOWERS];
uint8 m_towersAlliance;
uint8 m_towersHorde;
ObjectGuid m_flightMaster;
ObjectGuid m_lordaeronShrineAlliance;
ObjectGuid m_lordaeronShrineHorde;
GuidList m_soldiers;
GuidList m_towerBanners[MAX_EP_TOWERS];
};
#endif
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_31) on Mon May 14 18:45:49 PDT 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
ByteArrayBuilder (Jackson-core 2.0.2 API)
</TITLE>
<META NAME="date" CONTENT="2012-05-14">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ByteArrayBuilder (Jackson-core 2.0.2 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ByteArrayBuilder.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><script type="text/javascript"><!--
google_ad_client = "pub-1467773697956887";
/* Jackson-ad-small */
google_ad_slot = "6699487946";
google_ad_width = 234;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../com/fasterxml/jackson/core/util/BufferRecycler.CharBufferType.html" title="enum in com.fasterxml.jackson.core.util"><B>PREV CLASS</B></A>
<A HREF="../../../../../com/fasterxml/jackson/core/util/DefaultPrettyPrinter.html" title="class in com.fasterxml.jackson.core.util"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/fasterxml/jackson/core/util/ByteArrayBuilder.html" target="_top"><B>FRAMES</B></A>
<A HREF="ByteArrayBuilder.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
com.fasterxml.jackson.core.util</FONT>
<BR>
Class ByteArrayBuilder</H2>
<PRE>
<A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</A>
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">java.io.OutputStream</A>
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>com.fasterxml.jackson.core.util.ByteArrayBuilder</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/Closeable.html?is-external=true" title="class or interface in java.io">Closeable</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/Flushable.html?is-external=true" title="class or interface in java.io">Flushable</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public final class <B>ByteArrayBuilder</B><DT>extends <A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">OutputStream</A></DL>
</PRE>
<P>
Helper class that is similar to <A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html?is-external=true" title="class or interface in java.io"><CODE>ByteArrayOutputStream</CODE></A>
in usage, but more geared to Jackson use cases internally.
Specific changes include segment storage (no need to have linear
backing buffer, can avoid reallocs, copying), as well API
not based on <A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io"><CODE>OutputStream</CODE></A>. In short, a very much
specialized builder object.
<p>
Since version 1.5, also implements <A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io"><CODE>OutputStream</CODE></A> to allow
efficient aggregation of output content as a byte array, similar
to how <A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html?is-external=true" title="class or interface in java.io"><CODE>ByteArrayOutputStream</CODE></A> works, but somewhat more
efficiently for many use cases.
<P>
<P>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#ByteArrayBuilder()">ByteArrayBuilder</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#ByteArrayBuilder(com.fasterxml.jackson.core.util.BufferRecycler)">ByteArrayBuilder</A></B>(<A HREF="../../../../../com/fasterxml/jackson/core/util/BufferRecycler.html" title="class in com.fasterxml.jackson.core.util">BufferRecycler</A> br)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#ByteArrayBuilder(com.fasterxml.jackson.core.util.BufferRecycler, int)">ByteArrayBuilder</A></B>(<A HREF="../../../../../com/fasterxml/jackson/core/util/BufferRecycler.html" title="class in com.fasterxml.jackson.core.util">BufferRecycler</A> br,
int firstBlockSize)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#ByteArrayBuilder(int)">ByteArrayBuilder</A></B>(int firstBlockSize)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#append(int)">append</A></B>(int i)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#appendThreeBytes(int)">appendThreeBytes</A></B>(int b24)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#appendTwoBytes(int)">appendTwoBytes</A></B>(int b16)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#close()">close</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> byte[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#completeAndCoalesce(int)">completeAndCoalesce</A></B>(int lastBlockLength)</CODE>
<BR>
Method that will complete "manual" output process, coalesce
content (if necessary) and return results as a contiguous buffer.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> byte[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#finishCurrentSegment()">finishCurrentSegment</A></B>()</CODE>
<BR>
Method called when the current segment buffer is full; will
append to current contents, allocate a new segment buffer
and return it</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#flush()">flush</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> byte[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#getCurrentSegment()">getCurrentSegment</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#getCurrentSegmentLength()">getCurrentSegmentLength</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#release()">release</A></B>()</CODE>
<BR>
Clean up method to call to release all buffers this object may be
using.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#reset()">reset</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> byte[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#resetAndGetFirstSegment()">resetAndGetFirstSegment</A></B>()</CODE>
<BR>
Method called when starting "manual" output: will clear out
current state and return the first segment buffer to fill</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#setCurrentSegmentLength(int)">setCurrentSegmentLength</A></B>(int len)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> byte[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#toByteArray()">toByteArray</A></B>()</CODE>
<BR>
Method called when results are finalized and we can get the
full aggregated result buffer to return to the caller</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#write(byte[])">write</A></B>(byte[] b)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#write(byte[], int, int)">write</A></B>(byte[] b,
int off,
int len)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/fasterxml/jackson/core/util/ByteArrayBuilder.html#write(int)">write</A></B>(int b)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.<A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#clone()" title="class or interface in java.lang">clone</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#equals(java.lang.Object)" title="class or interface in java.lang">equals</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#finalize()" title="class or interface in java.lang">finalize</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#getClass()" title="class or interface in java.lang">getClass</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#hashCode()" title="class or interface in java.lang">hashCode</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#notify()" title="class or interface in java.lang">notify</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#notifyAll()" title="class or interface in java.lang">notifyAll</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#toString()" title="class or interface in java.lang">toString</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait()" title="class or interface in java.lang">wait</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait(long)" title="class or interface in java.lang">wait</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait(long, int)" title="class or interface in java.lang">wait</A></CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="ByteArrayBuilder()"><!-- --></A><H3>
ByteArrayBuilder</H3>
<PRE>
public <B>ByteArrayBuilder</B>()</PRE>
<DL>
</DL>
<HR>
<A NAME="ByteArrayBuilder(com.fasterxml.jackson.core.util.BufferRecycler)"><!-- --></A><H3>
ByteArrayBuilder</H3>
<PRE>
public <B>ByteArrayBuilder</B>(<A HREF="../../../../../com/fasterxml/jackson/core/util/BufferRecycler.html" title="class in com.fasterxml.jackson.core.util">BufferRecycler</A> br)</PRE>
<DL>
</DL>
<HR>
<A NAME="ByteArrayBuilder(int)"><!-- --></A><H3>
ByteArrayBuilder</H3>
<PRE>
public <B>ByteArrayBuilder</B>(int firstBlockSize)</PRE>
<DL>
</DL>
<HR>
<A NAME="ByteArrayBuilder(com.fasterxml.jackson.core.util.BufferRecycler, int)"><!-- --></A><H3>
ByteArrayBuilder</H3>
<PRE>
public <B>ByteArrayBuilder</B>(<A HREF="../../../../../com/fasterxml/jackson/core/util/BufferRecycler.html" title="class in com.fasterxml.jackson.core.util">BufferRecycler</A> br,
int firstBlockSize)</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="reset()"><!-- --></A><H3>
reset</H3>
<PRE>
public void <B>reset</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="release()"><!-- --></A><H3>
release</H3>
<PRE>
public void <B>release</B>()</PRE>
<DL>
<DD>Clean up method to call to release all buffers this object may be
using. After calling the method, no other accessors can be used (and
attempt to do so may result in an exception)
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="append(int)"><!-- --></A><H3>
append</H3>
<PRE>
public void <B>append</B>(int i)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="appendTwoBytes(int)"><!-- --></A><H3>
appendTwoBytes</H3>
<PRE>
public void <B>appendTwoBytes</B>(int b16)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="appendThreeBytes(int)"><!-- --></A><H3>
appendThreeBytes</H3>
<PRE>
public void <B>appendThreeBytes</B>(int b24)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="toByteArray()"><!-- --></A><H3>
toByteArray</H3>
<PRE>
public byte[] <B>toByteArray</B>()</PRE>
<DL>
<DD>Method called when results are finalized and we can get the
full aggregated result buffer to return to the caller
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="resetAndGetFirstSegment()"><!-- --></A><H3>
resetAndGetFirstSegment</H3>
<PRE>
public byte[] <B>resetAndGetFirstSegment</B>()</PRE>
<DL>
<DD>Method called when starting "manual" output: will clear out
current state and return the first segment buffer to fill
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="finishCurrentSegment()"><!-- --></A><H3>
finishCurrentSegment</H3>
<PRE>
public byte[] <B>finishCurrentSegment</B>()</PRE>
<DL>
<DD>Method called when the current segment buffer is full; will
append to current contents, allocate a new segment buffer
and return it
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="completeAndCoalesce(int)"><!-- --></A><H3>
completeAndCoalesce</H3>
<PRE>
public byte[] <B>completeAndCoalesce</B>(int lastBlockLength)</PRE>
<DL>
<DD>Method that will complete "manual" output process, coalesce
content (if necessary) and return results as a contiguous buffer.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>lastBlockLength</CODE> - Amount of content in the current segment
buffer.
<DT><B>Returns:</B><DD>Coalesced contents</DL>
</DD>
</DL>
<HR>
<A NAME="getCurrentSegment()"><!-- --></A><H3>
getCurrentSegment</H3>
<PRE>
public byte[] <B>getCurrentSegment</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setCurrentSegmentLength(int)"><!-- --></A><H3>
setCurrentSegmentLength</H3>
<PRE>
public void <B>setCurrentSegmentLength</B>(int len)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getCurrentSegmentLength()"><!-- --></A><H3>
getCurrentSegmentLength</H3>
<PRE>
public int <B>getCurrentSegmentLength</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="write(byte[])"><!-- --></A><H3>
write</H3>
<PRE>
public void <B>write</B>(byte[] b)</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true#write(byte[])" title="class or interface in java.io">write</A></CODE> in class <CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">OutputStream</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="write(byte[], int, int)"><!-- --></A><H3>
write</H3>
<PRE>
public void <B>write</B>(byte[] b,
int off,
int len)</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true#write(byte[], int, int)" title="class or interface in java.io">write</A></CODE> in class <CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">OutputStream</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="write(int)"><!-- --></A><H3>
write</H3>
<PRE>
public void <B>write</B>(int b)</PRE>
<DL>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true#write(int)" title="class or interface in java.io">write</A></CODE> in class <CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">OutputStream</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="close()"><!-- --></A><H3>
close</H3>
<PRE>
public void <B>close</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/Closeable.html?is-external=true#close()" title="class or interface in java.io">close</A></CODE> in interface <CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/Closeable.html?is-external=true" title="class or interface in java.io">Closeable</A></CODE><DT><B>Overrides:</B><DD><CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true#close()" title="class or interface in java.io">close</A></CODE> in class <CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">OutputStream</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="flush()"><!-- --></A><H3>
flush</H3>
<PRE>
public void <B>flush</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/Flushable.html?is-external=true#flush()" title="class or interface in java.io">flush</A></CODE> in interface <CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/Flushable.html?is-external=true" title="class or interface in java.io">Flushable</A></CODE><DT><B>Overrides:</B><DD><CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true#flush()" title="class or interface in java.io">flush</A></CODE> in class <CODE><A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">OutputStream</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR><td rowspan='3'><script type="text/javascript"><!--
google_ad_client = "pub-1467773697956887";
/* Jackson-ad-small */
google_ad_slot = "6699487946";
google_ad_width = 234;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<!-- GA -->
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-140287-6");
pageTracker._trackPageview();
} catch(err) {}
</script>
</td>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ByteArrayBuilder.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../com/fasterxml/jackson/core/util/BufferRecycler.CharBufferType.html" title="enum in com.fasterxml.jackson.core.util"><B>PREV CLASS</B></A>
<A HREF="../../../../../com/fasterxml/jackson/core/util/DefaultPrettyPrinter.html" title="class in com.fasterxml.jackson.core.util"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/fasterxml/jackson/core/util/ByteArrayBuilder.html" target="_top"><B>FRAMES</B></A>
<A HREF="ByteArrayBuilder.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2012 <a href="http://fasterxml.com">fasterxml.com</a>. All Rights Reserved.
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
if TARGET_PATI
config SYS_BOARD
default "pati"
config SYS_VENDOR
default "mpl"
config SYS_CONFIG_NAME
default "PATI"
endif
| {
"pile_set_name": "Github"
} |
(define (make-frame variables values)
(if (null? variables)
'()
(cons
(cons (car variables) (car values))
(make-frame (cdr variables) (cdr values)))))
(define (first-binding frame)
(car frame))
(define (rest-bindings frame)
(cdr frame))
(define (add-binding-to-frame! var val frame)
(cons (cons var val) frame))
; extend-environment 不需要修改
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
(define (lookup-variable-value var env)
(define (env-loop env)
(define (scan frame)
(cond ((null? frame)
(env-loop (enclosing-environment env))
((eq? var (car (first-binding frame)))
(cdr (first-binding frame)))
(else (scan (rest-bindings frame))))))
(if (eq? env the-empty-environment)
(error "Unbound variable " var)
(let ((frame (first-frame env))
(scan frame)))))
(env-loop env))
(define (set-variable-value! var val env)
(define (env-loop env)
(define (scan frame)
(cond ((null? frame)
(env-loop (enclosing-environment env))
((eq? var (car (first-binding frame)))
(set-cdr! (first-binding frame) val))
(else (scan (rest-bindings frame))))))
(if (eq? env the-empty-environment)
(error "Unbound variable " var)
(let ((frame (first-frame env))
(scan frame)))))
(env-loop env))
(define (define-variable! var val env)
(let ((frame (first-frame env)))
(define (scan frame)
(cond ((null? frame)
(add-binding-to-frame! var val frame))
((eq? var (car (first-binding frame)))
(set-cdr! (first-binding frame) val))
(else (scan (rest-bindings frame)))))
(scan (first-frame env))))
| {
"pile_set_name": "Github"
} |
const { assert } = require('chai');
const parseCommandLine = require('../../src/main-process/parse-command-line');
describe('parseCommandLine', () => {
describe('when --uri-handler is not passed', () => {
it('parses arguments as normal', () => {
const args = parseCommandLine([
'-d',
'--safe',
'--test',
'/some/path',
'atom://test/url',
'atom://other/url'
]);
assert.isTrue(args.devMode);
assert.isTrue(args.safeMode);
assert.isTrue(args.test);
assert.deepEqual(args.urlsToOpen, [
'atom://test/url',
'atom://other/url'
]);
assert.deepEqual(args.pathsToOpen, ['/some/path']);
});
});
describe('when --uri-handler is passed', () => {
it('ignores other arguments and limits to one URL', () => {
const args = parseCommandLine([
'-d',
'--uri-handler',
'--safe',
'--test',
'/some/path',
'atom://test/url',
'atom://other/url'
]);
assert.isUndefined(args.devMode);
assert.isUndefined(args.safeMode);
assert.isUndefined(args.test);
assert.deepEqual(args.urlsToOpen, ['atom://test/url']);
assert.deepEqual(args.pathsToOpen, []);
});
});
});
| {
"pile_set_name": "Github"
} |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#! /usr/bin/env python2
import os
import numpy as np
from matplotlib import pyplot
import re
from argparse import Namespace
# the directory used in run_on_cluster.bash
basedir = '/mnt/vol/gfsai-east/ai-group/users/matthijs/bench_all_ivf/'
logdir = basedir + 'logs/'
# which plot to output
db = 'bigann1B'
code_size = 8
def unitsize(indexkey):
""" size of one vector in the index """
mo = re.match('.*,PQ(\\d+)', indexkey)
if mo:
return int(mo.group(1))
if indexkey.endswith('SQ8'):
bits_per_d = 8
elif indexkey.endswith('SQ4'):
bits_per_d = 4
elif indexkey.endswith('SQfp16'):
bits_per_d = 16
else:
assert False
mo = re.match('PCAR(\\d+),.*', indexkey)
if mo:
return bits_per_d * int(mo.group(1)) / 8
mo = re.match('OPQ\\d+_(\\d+),.*', indexkey)
if mo:
return bits_per_d * int(mo.group(1)) / 8
mo = re.match('RR(\\d+),.*', indexkey)
if mo:
return bits_per_d * int(mo.group(1)) / 8
assert False
def dbsize_from_name(dbname):
sufs = {
'1B': 10**9,
'100M': 10**8,
'10M': 10**7,
'1M': 10**6,
}
for s in sufs:
if dbname.endswith(s):
return sufs[s]
else:
assert False
def keep_latest_stdout(fnames):
fnames = [fname for fname in fnames if fname.endswith('.stdout')]
fnames.sort()
n = len(fnames)
fnames2 = []
for i, fname in enumerate(fnames):
if i + 1 < n and fnames[i + 1][:-8] == fname[:-8]:
continue
fnames2.append(fname)
return fnames2
def parse_result_file(fname):
# print fname
st = 0
res = []
keys = []
stats = {}
stats['run_version'] = fname[-8]
for l in open(fname):
if st == 0:
if l.startswith('CHRONOS_JOB_INSTANCE_ID'):
stats['CHRONOS_JOB_INSTANCE_ID'] = l.split()[-1]
if l.startswith('index size on disk:'):
stats['index_size'] = int(l.split()[-1])
if l.startswith('current RSS:'):
stats['RSS'] = int(l.split()[-1])
if l.startswith('precomputed tables size:'):
stats['tables_size'] = int(l.split()[-1])
if l.startswith('Setting nb of threads to'):
stats['n_threads'] = int(l.split()[-1])
if l.startswith(' add in'):
stats['add_time'] = float(l.split()[-2])
if l.startswith('args:'):
args = eval(l[l.find(' '):])
indexkey = args.indexkey
elif 'R@1 R@10 R@100' in l:
st = 1
elif 'index size on disk:' in l:
index_size = int(l.split()[-1])
elif st == 1:
st = 2
elif st == 2:
fi = l.split()
keys.append(fi[0])
res.append([float(x) for x in fi[1:]])
return indexkey, np.array(res), keys, stats
# run parsing
allres = {}
allstats = {}
nts = []
missing = []
versions = {}
fnames = keep_latest_stdout(os.listdir(logdir))
# print fnames
# filenames are in the form <key>.x.stdout
# where x is a version number (from a to z)
# keep only latest version of each name
for fname in fnames:
if not ('db' + db in fname and fname.endswith('.stdout')):
continue
indexkey, res, _, stats = parse_result_file(logdir + fname)
if res.size == 0:
missing.append(fname)
errorline = open(
logdir + fname.replace('.stdout', '.stderr')).readlines()
if len(errorline) > 0:
errorline = errorline[-1]
else:
errorline = 'NO STDERR'
print fname, stats['CHRONOS_JOB_INSTANCE_ID'], errorline
else:
if indexkey in allres:
if allstats[indexkey]['run_version'] > stats['run_version']:
# don't use this run
continue
n_threads = stats.get('n_threads', 1)
nts.append(n_threads)
allres[indexkey] = res
allstats[indexkey] = stats
assert len(set(nts)) == 1
n_threads = nts[0]
def plot_tradeoffs(allres, code_size, recall_rank):
dbsize = dbsize_from_name(db)
recall_idx = int(np.log10(recall_rank))
bigtab = []
names = []
for k,v in sorted(allres.items()):
if v.ndim != 2: continue
us = unitsize(k)
if us != code_size: continue
perf = v[:, recall_idx]
times = v[:, 3]
bigtab.append(
np.vstack((
np.ones(times.size, dtype=int) * len(names),
perf, times
))
)
names.append(k)
bigtab = np.hstack(bigtab)
perm = np.argsort(bigtab[1, :])
bigtab = bigtab[:, perm]
times = np.minimum.accumulate(bigtab[2, ::-1])[::-1]
selection = np.where(bigtab[2, :] == times)
selected_methods = [names[i] for i in
np.unique(bigtab[0, selection].astype(int))]
not_selected = list(set(names) - set(selected_methods))
print "methods without an optimal OP: ", not_selected
nq = 10000
pyplot.title('database ' + db + ' code_size=%d' % code_size)
# grayed out lines
for k in not_selected:
v = allres[k]
if v.ndim != 2: continue
us = unitsize(k)
if us != code_size: continue
linestyle = (':' if 'PQ' in k else
'-.' if 'SQ4' in k else
'--' if 'SQ8' in k else '-')
pyplot.semilogy(v[:, recall_idx], v[:, 3], label=None,
linestyle=linestyle,
marker='o' if 'HNSW' in k else '+',
color='#cccccc', linewidth=0.2)
# important methods
for k in selected_methods:
v = allres[k]
if v.ndim != 2: continue
us = unitsize(k)
if us != code_size: continue
stats = allstats[k]
tot_size = stats['index_size'] + stats['tables_size']
id_size = 8 # 64 bit
addt = ''
if 'add_time' in stats:
add_time = stats['add_time']
if add_time > 7200:
add_min = add_time / 60
addt = ', %dh%02d' % (add_min / 60, add_min % 60)
else:
add_sec = int(add_time)
addt = ', %dm%02d' % (add_sec / 60, add_sec % 60)
label = k + ' (size+%.1f%%%s)' % (
tot_size / float((code_size + id_size) * dbsize) * 100 - 100,
addt)
linestyle = (':' if 'PQ' in k else
'-.' if 'SQ4' in k else
'--' if 'SQ8' in k else '-')
pyplot.semilogy(v[:, recall_idx], v[:, 3], label=label,
linestyle=linestyle,
marker='o' if 'HNSW' in k else '+')
if len(not_selected) == 0:
om = ''
else:
om = '\nomitted:'
nc = len(om)
for m in not_selected:
if nc > 80:
om += '\n'
nc = 0
om += ' ' + m
nc += len(m) + 1
pyplot.xlabel('1-recall at %d %s' % (recall_rank, om) )
pyplot.ylabel('search time per query (ms, %d threads)' % n_threads)
pyplot.legend()
pyplot.grid()
pyplot.savefig('figs/tradeoffs_%s_cs%d_r%d.png' % (
db, code_size, recall_rank))
return selected_methods, not_selected
pyplot.gcf().set_size_inches(15, 10)
plot_tradeoffs(allres, code_size=code_size, recall_rank=1)
| {
"pile_set_name": "Github"
} |
{ stdenv
, buildPythonPackage
, fetchPypi
, fetchpatch
, isPy27
, ipaddress
, openssl
, cryptography_vectors
, darwin
, packaging
, six
, pythonOlder
, isPyPy
, cffi
, pytest
, pretend
, iso8601
, pytz
, hypothesis
, enum34
}:
buildPythonPackage rec {
pname = "cryptography";
version = "2.9.2"; # Also update the hash in vectors.nix
src = fetchPypi {
inherit pname version;
sha256 = "0af25w5mkd6vwns3r6ai1w5ip9xp0ms9s261zzssbpadzdr05hx0";
};
outputs = [ "out" "dev" ];
buildInputs = [ openssl ]
++ stdenv.lib.optional stdenv.isDarwin darwin.apple_sdk.frameworks.Security;
propagatedBuildInputs = [
packaging
six
] ++ stdenv.lib.optional (!isPyPy) cffi
++ stdenv.lib.optionals isPy27 [ ipaddress enum34 ];
checkInputs = [
cryptography_vectors
hypothesis
iso8601
pretend
pytest
pytz
];
checkPhase = ''
py.test --disable-pytest-warnings tests
'';
# IOKit's dependencies are inconsistent between OSX versions, so this is the best we
# can do until nix 1.11's release
__impureHostDeps = [ "/usr/lib" ];
meta = with stdenv.lib; {
description = "A package which provides cryptographic recipes and primitives";
longDescription = ''
Cryptography includes both high level recipes and low level interfaces to
common cryptographic algorithms such as symmetric ciphers, message
digests, and key derivation functions.
Our goal is for it to be your "cryptographic standard library". It
supports Python 2.7, Python 3.5+, and PyPy 5.4+.
'';
homepage = "https://github.com/pyca/cryptography";
changelog = "https://cryptography.io/en/latest/changelog/#v"
+ replaceStrings [ "." ] [ "-" ] version;
license = with licenses; [ asl20 bsd3 psfl ];
maintainers = with maintainers; [ primeos ];
};
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.tyorikan.voicerecordingvisualizer.VisualizerView
android:id="@+id/visualizer"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_marginTop="@dimen/spacing_large"
android:background="@android:color/black"
app:numColumns="4"
app:renderColor="@color/renderColor"
app:renderRange="top"
app:renderType="bar|fade" />
<com.tyorikan.voicerecordingvisualizer.VisualizerView
android:id="@+id/visualizer2"
android:layout_width="50dp"
android:layout_height="150dp"
android:layout_gravity="center_horizontal|top"
android:layout_marginTop="@dimen/spacing_large"
android:background="@android:color/background_light"
app:numColumns="10"
app:renderColor="@color/renderColor2"
app:renderRange="bottom"
app:renderType="pixel|fade" />
<com.tyorikan.voicerecordingvisualizer.VisualizerView
android:id="@+id/visualizer3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginTop="@dimen/spacing_large"
android:background="@android:color/darker_gray"
app:numColumns="100"
app:renderColor="@color/renderColor3"
app:renderRange="both"
app:renderType="pixel" />
</LinearLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="@dimen/spacing_large"
android:src="@drawable/ic_mic"
app:backgroundTint="@android:color/white"
app:borderWidth="0dp"
app:fabSize="normal" />
</FrameLayout> | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{6BB5C546-306D-4810-8482-4A9600F0A4F5}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BuildSupport</RootNamespace>
<AssemblyName>BuildSupport</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Deploy|x86'">
<OutputPath>..\lib\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisLogFile>bin\Release\BuildSupport.exe.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;C:\Program Files\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
<CodeAnalysisFailOnMissingRules>false</CodeAnalysisFailOnMissingRules>
</PropertyGroup>
<ItemGroup>
<Reference Include="Ionic.Zip.Reduced, Version=1.9.1.5, Culture=neutral, PublicKeyToken=edbe51ad942a3f5c, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\Ionic.Zip.Reduced.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Commands.ZipDirectory.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<numFmts count="2">
<numFmt numFmtId="164" formatCode="GENERAL" />
<numFmt numFmtId="165" formatCode="MM/DD/YYYY" />
</numFmts>
<fonts count="6">
<font>
<sz val="11" />
<color rgb="FF000000" />
<name val="Calibri" />
<family val="2" />
<charset val="1" />
</font>
<font>
<sz val="10" />
<name val="Arial" />
<family val="0" />
</font>
<font>
<sz val="10" />
<name val="Arial" />
<family val="0" />
</font>
<font>
<sz val="10" />
<name val="Arial" />
<family val="0" />
</font>
<font><b val="true" />
<sz val="12" />
<color rgb="FFFFFFFF" />
<name val="Calibri" />
<family val="2" />
<charset val="1" />
</font>
<font><b val="true" />
<sz val="11" />
<color rgb="FF000000" />
<name val="Calibri" />
<family val="2" />
<charset val="1" />
</font>
</fonts>
<fills count="4">
<fill>
<patternFill patternType="none" />
</fill>
<fill>
<patternFill patternType="gray125" />
</fill>
<fill>
<patternFill patternType="solid">
<fgColor rgb="FF090948" />
<bgColor rgb="FF000080" />
</patternFill>
</fill>
<fill>
<patternFill patternType="solid">
<fgColor rgb="FFDCE6F2" />
<bgColor rgb="FFCCFFFF" />
</patternFill>
</fill>
</fills>
<borders count="2">
<border diagonalUp="false" diagonalDown="false">
<left/>
<right/>
<top/>
<bottom/>
<diagonal/>
</border>
<border diagonalUp="false" diagonalDown="false">
<left style="thin" />
<right style="thin" />
<top style="thin" />
<bottom style="thin" />
<diagonal/>
</border>
</borders>
<cellStyleXfs count="20">
<xf numFmtId="164" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="true" applyAlignment="true" applyProtection="true">
<alignment horizontal="general" vertical="bottom" textRotation="0" wrapText="false" indent="0" shrinkToFit="false" />
<protection locked="true" hidden="false" />
</xf>
<xf numFmtId="0" fontId="1" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="1" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="2" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="2" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="43" fontId="1" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="41" fontId="1" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="44" fontId="1" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="42" fontId="1" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
<xf numFmtId="9" fontId="1" fillId="0" borderId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false"></xf>
</cellStyleXfs>
<cellXfs count="8">
<xf numFmtId="164" fontId="0" fillId="0" borderId="0" xfId="0" applyFont="false" applyBorder="false" applyAlignment="false" applyProtection="false">
<alignment horizontal="general" vertical="bottom" textRotation="0" wrapText="false" indent="0" shrinkToFit="false" />
<protection locked="true" hidden="false" />
</xf>
<xf numFmtId="164" fontId="4" fillId="2" borderId="1" xfId="0" applyFont="true" applyBorder="true" applyAlignment="true" applyProtection="false">
<alignment horizontal="center" vertical="bottom" textRotation="0" wrapText="false" indent="0" shrinkToFit="false" />
<protection locked="true" hidden="false" />
</xf>
<xf numFmtId="164" fontId="4" fillId="2" borderId="0" xfId="0" applyFont="true" applyBorder="true" applyAlignment="true" applyProtection="false">
<alignment horizontal="center" vertical="bottom" textRotation="0" wrapText="false" indent="0" shrinkToFit="false" />
<protection locked="true" hidden="false" />
</xf>
<xf numFmtId="165" fontId="4" fillId="2" borderId="0" xfId="0" applyFont="true" applyBorder="true" applyAlignment="true" applyProtection="false">
<alignment horizontal="center" vertical="bottom" textRotation="0" wrapText="false" indent="0" shrinkToFit="false" />
<protection locked="true" hidden="false" />
</xf>
<xf numFmtId="164" fontId="5" fillId="3" borderId="0" xfId="0" applyFont="true" applyBorder="true" applyAlignment="true" applyProtection="false">
<alignment horizontal="general" vertical="center" textRotation="0" wrapText="true" indent="0" shrinkToFit="false" />
<protection locked="true" hidden="false" />
</xf>
<xf numFmtId="164" fontId="0" fillId="0" borderId="0" xfId="0" applyFont="true" applyBorder="true" applyAlignment="true" applyProtection="false">
<alignment horizontal="left" vertical="center" textRotation="0" wrapText="true" indent="0" shrinkToFit="false" />
<protection locked="true" hidden="false" />
</xf>
<xf numFmtId="164" fontId="0" fillId="0" borderId="0" xfId="0" applyFont="true" applyBorder="false" applyAlignment="false" applyProtection="false">
<alignment horizontal="general" vertical="bottom" textRotation="0" wrapText="false" indent="0" shrinkToFit="false" />
<protection locked="true" hidden="false" />
</xf>
<xf numFmtId="164" fontId="0" fillId="0" borderId="0" xfId="0" applyFont="false" applyBorder="true" applyAlignment="false" applyProtection="false">
<alignment horizontal="general" vertical="bottom" textRotation="0" wrapText="false" indent="0" shrinkToFit="false" />
<protection locked="true" hidden="false" />
</xf>
</cellXfs>
<cellStyles count="6">
<cellStyle name="Normal" xfId="0" builtinId="0" customBuiltin="false" />
<cellStyle name="Comma" xfId="15" builtinId="3" customBuiltin="false" />
<cellStyle name="Comma [0]" xfId="16" builtinId="6" customBuiltin="false" />
<cellStyle name="Currency" xfId="17" builtinId="4" customBuiltin="false" />
<cellStyle name="Currency [0]" xfId="18" builtinId="7" customBuiltin="false" />
<cellStyle name="Percent" xfId="19" builtinId="5" customBuiltin="false" />
</cellStyles>
<colors>
<indexedColors>
<rgbColor rgb="FF000000" />
<rgbColor rgb="FFFFFFFF" />
<rgbColor rgb="FFFF0000" />
<rgbColor rgb="FF00FF00" />
<rgbColor rgb="FF0000FF" />
<rgbColor rgb="FFFFFF00" />
<rgbColor rgb="FFFF00FF" />
<rgbColor rgb="FF00FFFF" />
<rgbColor rgb="FF800000" />
<rgbColor rgb="FF008000" />
<rgbColor rgb="FF090948" />
<rgbColor rgb="FF808000" />
<rgbColor rgb="FF800080" />
<rgbColor rgb="FF008080" />
<rgbColor rgb="FFC0C0C0" />
<rgbColor rgb="FF808080" />
<rgbColor rgb="FF9999FF" />
<rgbColor rgb="FF993366" />
<rgbColor rgb="FFFFFFCC" />
<rgbColor rgb="FFDCE6F2" />
<rgbColor rgb="FF660066" />
<rgbColor rgb="FFFF8080" />
<rgbColor rgb="FF0066CC" />
<rgbColor rgb="FFCCCCFF" />
<rgbColor rgb="FF000080" />
<rgbColor rgb="FFFF00FF" />
<rgbColor rgb="FFFFFF00" />
<rgbColor rgb="FF00FFFF" />
<rgbColor rgb="FF800080" />
<rgbColor rgb="FF800000" />
<rgbColor rgb="FF008080" />
<rgbColor rgb="FF0000FF" />
<rgbColor rgb="FF00CCFF" />
<rgbColor rgb="FFCCFFFF" />
<rgbColor rgb="FFCCFFCC" />
<rgbColor rgb="FFFFFF99" />
<rgbColor rgb="FF99CCFF" />
<rgbColor rgb="FFFF99CC" />
<rgbColor rgb="FFCC99FF" />
<rgbColor rgb="FFFFCC99" />
<rgbColor rgb="FF3366FF" />
<rgbColor rgb="FF33CCCC" />
<rgbColor rgb="FF99CC00" />
<rgbColor rgb="FFFFCC00" />
<rgbColor rgb="FFFF9900" />
<rgbColor rgb="FFFF6600" />
<rgbColor rgb="FF666699" />
<rgbColor rgb="FF969696" />
<rgbColor rgb="FF003366" />
<rgbColor rgb="FF339966" />
<rgbColor rgb="FF003300" />
<rgbColor rgb="FF333300" />
<rgbColor rgb="FF993300" />
<rgbColor rgb="FF993366" />
<rgbColor rgb="FF333399" />
<rgbColor rgb="FF333333" />
</indexedColors>
</colors>
</styleSheet>
| {
"pile_set_name": "Github"
} |
DROP TABLE IF EXISTS t1;
CREATE TABLE t1(c1 BIT NULL COMMENT 'This is a BIT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` bit(1) DEFAULT NULL COMMENT 'This is a BIT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 TINYINT NULL COMMENT 'This is a TINYINT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` tinyint(4) DEFAULT NULL COMMENT 'This is a TINYINT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 SMALLINT NULL COMMENT 'This is a SMALLINT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` smallint(6) DEFAULT NULL COMMENT 'This is a SMALLINT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 MEDIUMINT NULL COMMENT 'This is a MEDIUMINT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` mediumint(9) DEFAULT NULL COMMENT 'This is a MEDIUMINT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 INT NULL COMMENT 'This is a INT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` int(11) DEFAULT NULL COMMENT 'This is a INT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 INTEGER NULL COMMENT 'This is a INTEGER column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` int(11) DEFAULT NULL COMMENT 'This is a INTEGER column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 BIGINT NULL COMMENT 'This is a BIGINT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` bigint(20) DEFAULT NULL COMMENT 'This is a BIGINT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 DECIMAL NULL COMMENT 'This is a DECIMAL column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` decimal(10,0) DEFAULT NULL COMMENT 'This is a DECIMAL column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 DEC NULL COMMENT 'This is a DEC column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` decimal(10,0) DEFAULT NULL COMMENT 'This is a DEC column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 FIXED NULL COMMENT 'This is a FIXED column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` decimal(10,0) DEFAULT NULL COMMENT 'This is a FIXED column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 NUMERIC NULL COMMENT 'This is a NUMERIC column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` decimal(10,0) DEFAULT NULL COMMENT 'This is a NUMERIC column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 DOUBLE NULL COMMENT 'This is a DOUBLE column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` double DEFAULT NULL COMMENT 'This is a DOUBLE column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 REAL NULL COMMENT 'This is a REAL column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` double DEFAULT NULL COMMENT 'This is a REAL column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 DOUBLE PRECISION NULL COMMENT 'This is a DOUBLE PRECISION column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` double DEFAULT NULL COMMENT 'This is a DOUBLE PRECISION column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 FLOAT NULL COMMENT 'This is a FLOAT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` float DEFAULT NULL COMMENT 'This is a FLOAT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 DATE NULL COMMENT 'This is a DATE column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` date DEFAULT NULL COMMENT 'This is a DATE column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 TIME NULL COMMENT 'This is a TIME column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` time DEFAULT NULL COMMENT 'This is a TIME column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 TIMESTAMP NULL COMMENT 'This is a TIMESTAMP column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` timestamp NULL DEFAULT NULL COMMENT 'This is a TIMESTAMP column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 DATETIME NULL COMMENT 'This is a DATETIME column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` datetime DEFAULT NULL COMMENT 'This is a DATETIME column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 YEAR NULL COMMENT 'This is a YEAR column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` year(4) DEFAULT NULL COMMENT 'This is a YEAR column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 TINYBLOB NULL COMMENT 'This is a TINYBLOB column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` tinyblob COMMENT 'This is a TINYBLOB column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 BLOB NULL COMMENT 'This is a BLOB column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` blob COMMENT 'This is a BLOB column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 MEDIUMBLOB NULL COMMENT 'This is a MEDIUMBLOB column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` mediumblob COMMENT 'This is a MEDIUMBLOB column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 LONGBLOB NULL COMMENT 'This is a LONGBLOB column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` longblob COMMENT 'This is a LONGBLOB column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 TINYTEXT NULL COMMENT 'This is a TINYTEXT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` tinytext COMMENT 'This is a TINYTEXT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 TEXT NULL COMMENT 'This is a TEXT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` text COMMENT 'This is a TEXT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 MEDIUMTEXT NULL COMMENT 'This is a MEDIUMTEXT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` mediumtext COMMENT 'This is a MEDIUMTEXT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
CREATE TABLE t1(c1 LONGTEXT NULL COMMENT 'This is a LONGTEXT column');
SHOW TABLES;
Tables_in_test
t1
SHOW CREATE TABLE t1;
Table Create Table
t1 CREATE TABLE `t1` (
`c1` longtext COMMENT 'This is a LONGTEXT column'
) ENGINE=ENGINE DEFAULT CHARSET=latin1
DROP TABLE t1;
SHOW TABLES;
Tables_in_test
| {
"pile_set_name": "Github"
} |
> From: [eLinux.org](http://eLinux.org/CR48-JavaVNC "http://eLinux.org/CR48-JavaVNC")
# CR48-JavaVNC
# Installing VNCViewer
### NOTE: Your device needs to be [rooted](http://eLinux.org/CR48-rooting "CR48-rooting") before you can continue.
- Open up a shell on the cr-48, and
` sudo su mkdir /mnt/stateful_partition/opt (if you haven't already) cd /mnt/stateful_partition/opt wget http://www.calliesfarm.com/chromeos/java.tar.gz wget http://www.calliesfarm.com/chromeos/vncviewer.tar.gz tar -zxvf java.tar.gz tar -zxvf vncviewer.tar.gz rm -rf java.tar.gz vncviewer.tar.gz ln -s /usr/bin/java jre1.6.0_23/bin/java mv vncviewer/vncviewer /usr/bin`
- After it's installed, you should be able to run
` vncviewer`
- However, since there are no close window widgets, there's two ways
to disconnect.. either navigate to the vnc server icon once
connected, and tell it to disconnect you. or, kill it from the
terminal.
[Back to CR48 Home](http://eLinux.org/CR48 "CR48")
[Category](http://eLinux.org/Special:Categories "Special:Categories"):
- [CR48](http://eLinux.org/Category:CR48 "Category:CR48")
| {
"pile_set_name": "Github"
} |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: SI (Slovenian)
*/
jQuery.extend(jQuery.validator.messages, {
required: "To polje je obvezno.",
remote: "Vpis v tem polju ni v pravi obliki.",
email: "Prosimo, vnesite pravi email naslov.",
url: "Prosimo, vnesite pravi URL.",
date: "Prosimo, vnesite pravi datum.",
dateISO: "Prosimo, vnesite pravi datum (ISO).",
number: "Prosimo, vnesite pravo številko.",
digits: "Prosimo, vnesite samo številke.",
creditcard: "Prosimo, vnesite pravo številko kreditne kartice.",
equalTo: "Prosimo, ponovno vnesite enako vsebino.",
accept: "Prosimo, vnesite vsebino z pravo končnico.",
maxlength: $.validator.format("Prosimo, da ne vnašate več kot {0} znakov."),
minlength: $.validator.format("Prosimo, vnesite vsaj {0} znakov."),
rangelength: $.validator.format("Prosimo, vnesite od {0} do {1} znakov."),
range: $.validator.format("Prosimo, vnesite vrednost med {0} in {1}."),
max: $.validator.format("Prosimo, vnesite vrednost manjšo ali enako {0}."),
min: $.validator.format("Prosimo, vnesite vrednost večjo ali enako {0}.")
});
| {
"pile_set_name": "Github"
} |
/****************************************************************************
****************************************************************************
***
*** This header was automatically generated from a Linux kernel header
*** of the same name, to make information necessary for userspace to
*** call into the kernel available to libc. It contains only constants,
*** structures, and macros generated from the original header, and thus,
*** contains no copyrightable information.
***
*** To edit the content of this header, modify the corresponding
*** source file (e.g. under external/kernel-headers/original/) then
*** run bionic/libc/kernel/tools/update_all.py
***
*** Any manual change here will be lost the next time this script will
*** be run. You've been warned!
***
****************************************************************************
****************************************************************************/
#include <asm-generic/socket.h>
| {
"pile_set_name": "Github"
} |
"""Sparse block 1-norm estimator.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from scipy.sparse.linalg import aslinearoperator
__all__ = ['onenormest']
def onenormest(A, t=2, itmax=5, compute_v=False, compute_w=False):
"""
Compute a lower bound of the 1-norm of a sparse matrix.
Parameters
----------
A : ndarray or other linear operator
A linear operator that can be transposed and that can
produce matrix products.
t : int, optional
A positive parameter controlling the tradeoff between
accuracy versus time and memory usage.
Larger values take longer and use more memory
but give more accurate output.
itmax : int, optional
Use at most this many iterations.
compute_v : bool, optional
Request a norm-maximizing linear operator input vector if True.
compute_w : bool, optional
Request a norm-maximizing linear operator output vector if True.
Returns
-------
est : float
An underestimate of the 1-norm of the sparse matrix.
v : ndarray, optional
The vector such that ||Av||_1 == est*||v||_1.
It can be thought of as an input to the linear operator
that gives an output with particularly large norm.
w : ndarray, optional
The vector Av which has relatively large 1-norm.
It can be thought of as an output of the linear operator
that is relatively large in norm compared to the input.
Notes
-----
This is algorithm 2.4 of [1].
In [2] it is described as follows.
"This algorithm typically requires the evaluation of
about 4t matrix-vector products and almost invariably
produces a norm estimate (which is, in fact, a lower
bound on the norm) correct to within a factor 3."
.. versionadded:: 0.13.0
References
----------
.. [1] Nicholas J. Higham and Francoise Tisseur (2000),
"A Block Algorithm for Matrix 1-Norm Estimation,
with an Application to 1-Norm Pseudospectra."
SIAM J. Matrix Anal. Appl. Vol. 21, No. 4, pp. 1185-1201.
.. [2] Awad H. Al-Mohy and Nicholas J. Higham (2009),
"A new scaling and squaring algorithm for the matrix exponential."
SIAM J. Matrix Anal. Appl. Vol. 31, No. 3, pp. 970-989.
Examples
--------
>>> from scipy.sparse import csc_matrix
>>> from scipy.sparse.linalg import onenormest
>>> A = csc_matrix([[1., 0., 0.], [5., 8., 2.], [0., -1., 0.]], dtype=float)
>>> A.todense()
matrix([[ 1., 0., 0.],
[ 5., 8., 2.],
[ 0., -1., 0.]])
>>> onenormest(A)
9.0
>>> np.linalg.norm(A.todense(), ord=1)
9.0
"""
# Check the input.
A = aslinearoperator(A)
if A.shape[0] != A.shape[1]:
raise ValueError('expected the operator to act like a square matrix')
# If the operator size is small compared to t,
# then it is easier to compute the exact norm.
# Otherwise estimate the norm.
n = A.shape[1]
if t >= n:
A_explicit = np.asarray(aslinearoperator(A).matmat(np.identity(n)))
if A_explicit.shape != (n, n):
raise Exception('internal error: ',
'unexpected shape ' + str(A_explicit.shape))
col_abs_sums = abs(A_explicit).sum(axis=0)
if col_abs_sums.shape != (n, ):
raise Exception('internal error: ',
'unexpected shape ' + str(col_abs_sums.shape))
argmax_j = np.argmax(col_abs_sums)
v = elementary_vector(n, argmax_j)
w = A_explicit[:, argmax_j]
est = col_abs_sums[argmax_j]
else:
est, v, w, nmults, nresamples = _onenormest_core(A, A.H, t, itmax)
# Report the norm estimate along with some certificates of the estimate.
if compute_v or compute_w:
result = (est,)
if compute_v:
result += (v,)
if compute_w:
result += (w,)
return result
else:
return est
def _blocked_elementwise(func):
"""
Decorator for an elementwise function, to apply it blockwise along
first dimension, to avoid excessive memory usage in temporaries.
"""
block_size = 2**20
def wrapper(x):
if x.shape[0] < block_size:
return func(x)
else:
y0 = func(x[:block_size])
y = np.zeros((x.shape[0],) + y0.shape[1:], dtype=y0.dtype)
y[:block_size] = y0
del y0
for j in range(block_size, x.shape[0], block_size):
y[j:j+block_size] = func(x[j:j+block_size])
return y
return wrapper
@_blocked_elementwise
def sign_round_up(X):
"""
This should do the right thing for both real and complex matrices.
From Higham and Tisseur:
"Everything in this section remains valid for complex matrices
provided that sign(A) is redefined as the matrix (aij / |aij|)
(and sign(0) = 1) transposes are replaced by conjugate transposes."
"""
Y = X.copy()
Y[Y == 0] = 1
Y /= np.abs(Y)
return Y
@_blocked_elementwise
def _max_abs_axis1(X):
return np.max(np.abs(X), axis=1)
def _sum_abs_axis0(X):
block_size = 2**20
r = None
for j in range(0, X.shape[0], block_size):
y = np.sum(np.abs(X[j:j+block_size]), axis=0)
if r is None:
r = y
else:
r += y
return r
def elementary_vector(n, i):
v = np.zeros(n, dtype=float)
v[i] = 1
return v
def vectors_are_parallel(v, w):
# Columns are considered parallel when they are equal or negative.
# Entries are required to be in {-1, 1},
# which guarantees that the magnitudes of the vectors are identical.
if v.ndim != 1 or v.shape != w.shape:
raise ValueError('expected conformant vectors with entries in {-1,1}')
n = v.shape[0]
return np.dot(v, w) == n
def every_col_of_X_is_parallel_to_a_col_of_Y(X, Y):
for v in X.T:
if not any(vectors_are_parallel(v, w) for w in Y.T):
return False
return True
def column_needs_resampling(i, X, Y=None):
# column i of X needs resampling if either
# it is parallel to a previous column of X or
# it is parallel to a column of Y
n, t = X.shape
v = X[:, i]
if any(vectors_are_parallel(v, X[:, j]) for j in range(i)):
return True
if Y is not None:
if any(vectors_are_parallel(v, w) for w in Y.T):
return True
return False
def resample_column(i, X):
X[:, i] = np.random.randint(0, 2, size=X.shape[0])*2 - 1
def less_than_or_close(a, b):
return np.allclose(a, b) or (a < b)
def _algorithm_2_2(A, AT, t):
"""
This is Algorithm 2.2.
Parameters
----------
A : ndarray or other linear operator
A linear operator that can produce matrix products.
AT : ndarray or other linear operator
The transpose of A.
t : int, optional
A positive parameter controlling the tradeoff between
accuracy versus time and memory usage.
Returns
-------
g : sequence
A non-negative decreasing vector
such that g[j] is a lower bound for the 1-norm
of the column of A of jth largest 1-norm.
The first entry of this vector is therefore a lower bound
on the 1-norm of the linear operator A.
This sequence has length t.
ind : sequence
The ith entry of ind is the index of the column A whose 1-norm
is given by g[i].
This sequence of indices has length t, and its entries are
chosen from range(n), possibly with repetition,
where n is the order of the operator A.
Notes
-----
This algorithm is mainly for testing.
It uses the 'ind' array in a way that is similar to
its usage in algorithm 2.4. This algorithm 2.2 may be easier to test,
so it gives a chance of uncovering bugs related to indexing
which could have propagated less noticeably to algorithm 2.4.
"""
A_linear_operator = aslinearoperator(A)
AT_linear_operator = aslinearoperator(AT)
n = A_linear_operator.shape[0]
# Initialize the X block with columns of unit 1-norm.
X = np.ones((n, t))
if t > 1:
X[:, 1:] = np.random.randint(0, 2, size=(n, t-1))*2 - 1
X /= float(n)
# Iteratively improve the lower bounds.
# Track extra things, to assert invariants for debugging.
g_prev = None
h_prev = None
k = 1
ind = range(t)
while True:
Y = np.asarray(A_linear_operator.matmat(X))
g = _sum_abs_axis0(Y)
best_j = np.argmax(g)
g.sort()
g = g[::-1]
S = sign_round_up(Y)
Z = np.asarray(AT_linear_operator.matmat(S))
h = _max_abs_axis1(Z)
# If this algorithm runs for fewer than two iterations,
# then its return values do not have the properties indicated
# in the description of the algorithm.
# In particular, the entries of g are not 1-norms of any
# column of A until the second iteration.
# Therefore we will require the algorithm to run for at least
# two iterations, even though this requirement is not stated
# in the description of the algorithm.
if k >= 2:
if less_than_or_close(max(h), np.dot(Z[:, best_j], X[:, best_j])):
break
ind = np.argsort(h)[::-1][:t]
h = h[ind]
for j in range(t):
X[:, j] = elementary_vector(n, ind[j])
# Check invariant (2.2).
if k >= 2:
if not less_than_or_close(g_prev[0], h_prev[0]):
raise Exception('invariant (2.2) is violated')
if not less_than_or_close(h_prev[0], g[0]):
raise Exception('invariant (2.2) is violated')
# Check invariant (2.3).
if k >= 3:
for j in range(t):
if not less_than_or_close(g[j], g_prev[j]):
raise Exception('invariant (2.3) is violated')
# Update for the next iteration.
g_prev = g
h_prev = h
k += 1
# Return the lower bounds and the corresponding column indices.
return g, ind
def _onenormest_core(A, AT, t, itmax):
"""
Compute a lower bound of the 1-norm of a sparse matrix.
Parameters
----------
A : ndarray or other linear operator
A linear operator that can produce matrix products.
AT : ndarray or other linear operator
The transpose of A.
t : int, optional
A positive parameter controlling the tradeoff between
accuracy versus time and memory usage.
itmax : int, optional
Use at most this many iterations.
Returns
-------
est : float
An underestimate of the 1-norm of the sparse matrix.
v : ndarray, optional
The vector such that ||Av||_1 == est*||v||_1.
It can be thought of as an input to the linear operator
that gives an output with particularly large norm.
w : ndarray, optional
The vector Av which has relatively large 1-norm.
It can be thought of as an output of the linear operator
that is relatively large in norm compared to the input.
nmults : int, optional
The number of matrix products that were computed.
nresamples : int, optional
The number of times a parallel column was observed,
necessitating a re-randomization of the column.
Notes
-----
This is algorithm 2.4.
"""
# This function is a more or less direct translation
# of Algorithm 2.4 from the Higham and Tisseur (2000) paper.
A_linear_operator = aslinearoperator(A)
AT_linear_operator = aslinearoperator(AT)
if itmax < 2:
raise ValueError('at least two iterations are required')
if t < 1:
raise ValueError('at least one column is required')
n = A.shape[0]
if t >= n:
raise ValueError('t should be smaller than the order of A')
# Track the number of big*small matrix multiplications
# and the number of resamplings.
nmults = 0
nresamples = 0
# "We now explain our choice of starting matrix. We take the first
# column of X to be the vector of 1s [...] This has the advantage that
# for a matrix with nonnegative elements the algorithm converges
# with an exact estimate on the second iteration, and such matrices
# arise in applications [...]"
X = np.ones((n, t), dtype=float)
# "The remaining columns are chosen as rand{-1,1},
# with a check for and correction of parallel columns,
# exactly as for S in the body of the algorithm."
if t > 1:
for i in range(1, t):
# These are technically initial samples, not resamples,
# so the resampling count is not incremented.
resample_column(i, X)
for i in range(t):
while column_needs_resampling(i, X):
resample_column(i, X)
nresamples += 1
# "Choose starting matrix X with columns of unit 1-norm."
X /= float(n)
# "indices of used unit vectors e_j"
ind_hist = np.zeros(0, dtype=np.intp)
est_old = 0
S = np.zeros((n, t), dtype=float)
k = 1
ind = None
while True:
Y = np.asarray(A_linear_operator.matmat(X))
nmults += 1
mags = _sum_abs_axis0(Y)
est = np.max(mags)
best_j = np.argmax(mags)
if est > est_old or k == 2:
if k >= 2:
ind_best = ind[best_j]
w = Y[:, best_j]
# (1)
if k >= 2 and est <= est_old:
est = est_old
break
est_old = est
S_old = S
if k > itmax:
break
S = sign_round_up(Y)
del Y
# (2)
if every_col_of_X_is_parallel_to_a_col_of_Y(S, S_old):
break
if t > 1:
# "Ensure that no column of S is parallel to another column of S
# or to a column of S_old by replacing columns of S by rand{-1,1}."
for i in range(t):
while column_needs_resampling(i, S, S_old):
resample_column(i, S)
nresamples += 1
del S_old
# (3)
Z = np.asarray(AT_linear_operator.matmat(S))
nmults += 1
h = _max_abs_axis1(Z)
del Z
# (4)
if k >= 2 and max(h) == h[ind_best]:
break
# "Sort h so that h_first >= ... >= h_last
# and re-order ind correspondingly."
#
# Later on, we will need at most t+len(ind_hist) largest
# entries, so drop the rest
ind = np.argsort(h)[::-1][:t+len(ind_hist)].copy()
del h
if t > 1:
# (5)
# Break if the most promising t vectors have been visited already.
if np.in1d(ind[:t], ind_hist).all():
break
# Put the most promising unvisited vectors at the front of the list
# and put the visited vectors at the end of the list.
# Preserve the order of the indices induced by the ordering of h.
seen = np.in1d(ind, ind_hist)
ind = np.concatenate((ind[~seen], ind[seen]))
for j in range(t):
X[:, j] = elementary_vector(n, ind[j])
new_ind = ind[:t][~np.in1d(ind[:t], ind_hist)]
ind_hist = np.concatenate((ind_hist, new_ind))
k += 1
v = elementary_vector(n, ind_best)
return est, v, w, nmults, nresamples
| {
"pile_set_name": "Github"
} |
package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_9r1_9r2_10_11_12r1_12r2_13_14r1_14r2_15_16r1_16r2;
import io.netty.buffer.ByteBuf;
import protocolsupport.protocol.packet.middle.serverbound.play.MiddleAnimation;
import protocolsupport.protocol.serializer.MiscSerializer;
import protocolsupport.protocol.types.UsedHand;
public class Animation extends MiddleAnimation {
public Animation(MiddlePacketInit init) {
super(init);
}
@Override
protected void readClientData(ByteBuf clientdata) {
hand = MiscSerializer.readVarIntEnum(clientdata, UsedHand.CONSTANT_LOOKUP);
}
}
| {
"pile_set_name": "Github"
} |
'use strict';
var Emitter = require('events').EventEmitter;
var GridFSBucketReadStream = require('./download');
var GridFSBucketWriteStream = require('./upload');
var shallowClone = require('../utils').shallowClone;
var toError = require('../utils').toError;
var util = require('util');
var executeLegacyOperation = require('../utils').executeLegacyOperation;
var DEFAULT_GRIDFS_BUCKET_OPTIONS = {
bucketName: 'fs',
chunkSizeBytes: 255 * 1024
};
module.exports = GridFSBucket;
/**
* Constructor for a streaming GridFS interface
* @class
* @extends external:EventEmitter
* @param {Db} db A db handle
* @param {object} [options] Optional settings.
* @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot.
* @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB
* @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }`
* @param {object} [options.readPreference] Optional read preference to be passed to read operations
* @fires GridFSBucketWriteStream#index
*/
function GridFSBucket(db, options) {
Emitter.apply(this);
this.setMaxListeners(0);
if (options && typeof options === 'object') {
options = shallowClone(options);
var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS);
for (var i = 0; i < keys.length; ++i) {
if (!options[keys[i]]) {
options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]];
}
}
} else {
options = DEFAULT_GRIDFS_BUCKET_OPTIONS;
}
this.s = {
db: db,
options: options,
_chunksCollection: db.collection(options.bucketName + '.chunks'),
_filesCollection: db.collection(options.bucketName + '.files'),
checkedIndexes: false,
calledOpenUploadStream: false,
promiseLibrary: db.s.promiseLibrary || Promise
};
}
util.inherits(GridFSBucket, Emitter);
/**
* When the first call to openUploadStream is made, the upload stream will
* check to see if it needs to create the proper indexes on the chunks and
* files collections. This event is fired either when 1) it determines that
* no index creation is necessary, 2) when it successfully creates the
* necessary indexes.
*
* @event GridFSBucket#index
* @type {Error}
*/
/**
* Returns a writable stream (GridFSBucketWriteStream) for writing
* buffers to GridFS. The stream's 'id' property contains the resulting
* file's id.
* @method
* @param {string} filename The value of the 'filename' key in the files doc
* @param {object} [options] Optional settings.
* @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file
* @param {object} [options.metadata] Optional object to store in the file document's `metadata` field
* @param {string} [options.contentType] Optional string to store in the file document's `contentType` field
* @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field
* @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data
* @return {GridFSBucketWriteStream}
*/
GridFSBucket.prototype.openUploadStream = function(filename, options) {
if (options) {
options = shallowClone(options);
} else {
options = {};
}
if (!options.chunkSizeBytes) {
options.chunkSizeBytes = this.s.options.chunkSizeBytes;
}
return new GridFSBucketWriteStream(this, filename, options);
};
/**
* Returns a writable stream (GridFSBucketWriteStream) for writing
* buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting
* file's id.
* @method
* @param {string|number|object} id A custom id used to identify the file
* @param {string} filename The value of the 'filename' key in the files doc
* @param {object} [options] Optional settings.
* @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file
* @param {object} [options.metadata] Optional object to store in the file document's `metadata` field
* @param {string} [options.contentType] Optional string to store in the file document's `contentType` field
* @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field
* @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data
* @return {GridFSBucketWriteStream}
*/
GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) {
if (options) {
options = shallowClone(options);
} else {
options = {};
}
if (!options.chunkSizeBytes) {
options.chunkSizeBytes = this.s.options.chunkSizeBytes;
}
options.id = id;
return new GridFSBucketWriteStream(this, filename, options);
};
/**
* Returns a readable stream (GridFSBucketReadStream) for streaming file
* data from GridFS.
* @method
* @param {ObjectId} id The id of the file doc
* @param {Object} [options] Optional settings.
* @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from
* @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before
* @return {GridFSBucketReadStream}
*/
GridFSBucket.prototype.openDownloadStream = function(id, options) {
var filter = { _id: id };
options = {
start: options && options.start,
end: options && options.end
};
return new GridFSBucketReadStream(
this.s._chunksCollection,
this.s._filesCollection,
this.s.options.readPreference,
filter,
options
);
};
/**
* Deletes a file with the given id
* @method
* @param {ObjectId} id The id of the file doc
* @param {GridFSBucket~errorCallback} [callback]
*/
GridFSBucket.prototype.delete = function(id, callback) {
return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], {
skipSessions: true
});
};
/**
* @ignore
*/
function _delete(_this, id, callback) {
_this.s._filesCollection.deleteOne({ _id: id }, function(error, res) {
if (error) {
return callback(error);
}
_this.s._chunksCollection.deleteMany({ files_id: id }, function(error) {
if (error) {
return callback(error);
}
// Delete orphaned chunks before returning FileNotFound
if (!res.result.n) {
var errmsg = 'FileNotFound: no file with id ' + id + ' found';
return callback(new Error(errmsg));
}
callback();
});
});
}
/**
* Convenience wrapper around find on the files collection
* @method
* @param {Object} filter
* @param {Object} [options] Optional settings for cursor
* @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}.
* @param {number} [options.limit] Optional limit for cursor
* @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor
* @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag
* @param {number} [options.skip] Optional skip for cursor
* @param {object} [options.sort] Optional sort for cursor
* @return {Cursor}
*/
GridFSBucket.prototype.find = function(filter, options) {
filter = filter || {};
options = options || {};
var cursor = this.s._filesCollection.find(filter);
if (options.batchSize != null) {
cursor.batchSize(options.batchSize);
}
if (options.limit != null) {
cursor.limit(options.limit);
}
if (options.maxTimeMS != null) {
cursor.maxTimeMS(options.maxTimeMS);
}
if (options.noCursorTimeout != null) {
cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout);
}
if (options.skip != null) {
cursor.skip(options.skip);
}
if (options.sort != null) {
cursor.sort(options.sort);
}
return cursor;
};
/**
* Returns a readable stream (GridFSBucketReadStream) for streaming the
* file with the given name from GridFS. If there are multiple files with
* the same name, this will stream the most recent file with the given name
* (as determined by the `uploadDate` field). You can set the `revision`
* option to change this behavior.
* @method
* @param {String} filename The name of the file to stream
* @param {Object} [options] Optional settings
* @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest.
* @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from
* @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before
* @return {GridFSBucketReadStream}
*/
GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) {
var sort = { uploadDate: -1 };
var skip = null;
if (options && options.revision != null) {
if (options.revision >= 0) {
sort = { uploadDate: 1 };
skip = options.revision;
} else {
skip = -options.revision - 1;
}
}
var filter = { filename: filename };
options = {
sort: sort,
skip: skip,
start: options && options.start,
end: options && options.end
};
return new GridFSBucketReadStream(
this.s._chunksCollection,
this.s._filesCollection,
this.s.options.readPreference,
filter,
options
);
};
/**
* Renames the file with the given _id to the given string
* @method
* @param {ObjectId} id the id of the file to rename
* @param {String} filename new name for the file
* @param {GridFSBucket~errorCallback} [callback]
*/
GridFSBucket.prototype.rename = function(id, filename, callback) {
return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], {
skipSessions: true
});
};
/**
* @ignore
*/
function _rename(_this, id, filename, callback) {
var filter = { _id: id };
var update = { $set: { filename: filename } };
_this.s._filesCollection.updateOne(filter, update, function(error, res) {
if (error) {
return callback(error);
}
if (!res.result.n) {
return callback(toError('File with id ' + id + ' not found'));
}
callback();
});
}
/**
* Removes this bucket's files collection, followed by its chunks collection.
* @method
* @param {GridFSBucket~errorCallback} [callback]
*/
GridFSBucket.prototype.drop = function(callback) {
return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], {
skipSessions: true
});
};
/**
* Return the db logger
* @method
* @return {Logger} return the db logger
* @ignore
*/
GridFSBucket.prototype.getLogger = function() {
return this.s.db.s.logger;
};
/**
* @ignore
*/
function _drop(_this, callback) {
_this.s._filesCollection.drop(function(error) {
if (error) {
return callback(error);
}
_this.s._chunksCollection.drop(function(error) {
if (error) {
return callback(error);
}
return callback();
});
});
}
/**
* Callback format for all GridFSBucket methods that can accept a callback.
* @callback GridFSBucket~errorCallback
* @param {MongoError|undefined} error If present, an error instance representing any errors that occurred
* @param {*} result If present, a returned result for the method
*/
| {
"pile_set_name": "Github"
} |
-----BEGIN CERTIFICATE-----
MIICzjCCAbagAwIBAgIUYW27TGzVOIbjpG1ADx7m7mZnrNQwDQYJKoZIhvcNAQEF
BQAwDTELMAkGA1UEAwwCY2EwIhgPMjAxMDAxMDEwMDAwMDBaGA8yMDIwMDEwMTAw
MDAwMFowEjEQMA4GA1UEAwwHaW50LXByZTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBALqIUahEjhbWQf1utogGNhA9PBPZ6uQ1SrTs9WhXbCR7wcclqODY
H72xnAabbhqG8mvir1p1a2pkcQh6pVqnRYf3HNUknAJ+zUP8HmnQOCApk6sgw0nk
27lMwmtsDu0Vgg/xfq1pGrHTAjqLKkHup3DgDw2N/WYLK7AkkqR9uYhheZCxV5A9
0jvF4LhIH6g304hD7ycW2FW3ZlqqfgKQLzp7EIAGJMwcbJetlmFbt+KWEsB1MaMM
kd20yvf8rR0l0wnvuRcOp2jhs3svIm9p47SKlWEd7ibWJZ2rkQhONsscJAQsvxaL
L+Xxj5kXMbiz/kkj+nJRxDHVA6zaGAo17Y0CAwEAAaMdMBswCwYDVR0PBAQDAgEG
MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAESNgcKkxBwkaBykKo2Q
GzgimnI3eNw8O8GrhefL+r3Ek/CH4/oBHGvfvrz6D19uemdOyHxo5QNW2iWEq0No
pE6Hhm504P1fdkfQvjqjIhu/h3y5QjO3zdMGeVE/39TWAGrGsNFKE+jSxm8IbycF
Ue6165agasf+PhQdorjFca48iLcowKYs5Df0SAhY7zbw1fM1HTr1YGAXc1K9aCA5
fTmu8Nd0fNKc1NcbNDpdCG2YEj1nox1iMN5A4nY1ve88zJsnlpfsoJkHJqo2Cy+M
mpQSnkTlf3Gfpl8NO3UW9FTcnK8L4Ix2DSNBDe8Yg2YL5w/VIxecFwlmwV0wWdg6
vl0=
-----END CERTIFICATE-----
| {
"pile_set_name": "Github"
} |
synopsis:
Display system custom info
description:
Display custom info for all systems in Spacewalk with any custom info associated
columns:
server_id Server id
org_id Organization id
server_name Server name
key Custom info key
value Custom info value
sql:
select * from (
select rhnServer.id as server_id,
rhnServer.org_id as org_id,
rhnServer.name as server_name,
rhnCustomDataKey.label as key,
rhnServerCustomDataValue.value as value
from rhnServer join rhnServerCustomDataValue on rhnServer.id=rhnServerCustomDataValue.server_id join rhnCustomDataKey on rhnServerCustomDataValue.key_id=rhnCustomDataKey.id
) X
-- where placeholder
order by org_id, server_id
| {
"pile_set_name": "Github"
} |
//////////////////////////////////////////////////////////////////////////
class MyQueue
{
public:
/** Initialize your data structure here. */
MyQueue() {}
/** Push element x to the back of queue. */
void push(int x)
{
m_in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
int i = peek();
m_out.pop();
return i;
}
/** Get the front element. */
int peek()
{
TransferData();
return m_out.top();
}
/** Returns whether the queue is empty. */
bool empty()
{
return m_out.empty() && m_in.empty();
}
void TransferData()
{
if (!m_out.empty()) return;
while (!m_in.empty())
{
m_out.push(m_in.top());
m_in.pop();
}
}
private:
stack<int> m_out;
stack<int> m_in;
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
//////////////////////////////////////////////////////////////////////////
//int _solution_run(int)
//{
//}
#define USE_SOLUTION_CUSTOM
string _solution_custom(TestCases &tc)
{
vector<string> sf = tc.get<vector<string>>();
vector<string> sp = tc.get<vector<string>>();
vector<string> ans;
MyQueue *obj = nullptr;
for (auto i = 0; i < sf.size(); i++)
{
if (sf[i] == "MyQueue")
{
obj = new MyQueue();
ans.push_back("null");
}
else if (sf[i] == "push")
{
TestCases stc(sp[i]);
int x = stc.get<int>();
obj->push(x);
ans.push_back("null");
}
else if (sf[i] == "pop")
{
TestCases stc(sp[i]);
int r = obj->pop();
ans.push_back(convert<string>(r));
}
else if (sf[i] == "peek")
{
TestCases stc(sp[i]);
int r = obj->peek();
ans.push_back(convert<string>(r));
}
else if (sf[i] == "empty")
{
TestCases stc(sp[i]);
bool r = obj->empty();
ans.push_back(convert<string>(r));
}
else if (sf[i] == "TransferData")
{
TestCases stc(sp[i]);
obj->TransferData();
ans.push_back("null");
}
}
delete obj;
return convert<string>(ans);
}
//////////////////////////////////////////////////////////////////////////
//#define USE_GET_TEST_CASES_IN_CPP
//vector<string> _get_test_cases_string()
//{
// return {};
//}
| {
"pile_set_name": "Github"
} |
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatchFinally_Basic()
Dim source = <![CDATA[
Imports System
Class C
Private Sub M(i As Integer)
Try'BIND:"Try"
i = 0
Catch ex As Exception When i > 0
Throw ex
Finally
i = 1
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 0')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Catch clauses(1):
ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch ex As ... Throw ex')
Locals: Local_1: ex As System.Exception
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: ex As System.Exception) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'ex')
Initializer:
null
Filter:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 0')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Handler:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch ex As ... Throw ex')
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'Throw ex')
ILocalReferenceOperation: ex (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'ex')
Finally:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: 'Finally ... i = 1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 1')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatchFinally_Parent()
Dim source = <![CDATA[
Imports System
Class C
Private Sub M(i As Integer)'BIND:"Private Sub M(i As Integer)"
Try
i = 0
Catch ex As Exception When i > 0
Throw ex
Finally
i = 1
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'Private Sub ... End Sub')
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try ... End Try')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try ... End Try')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 0')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Catch clauses(1):
ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch ex As ... Throw ex')
Locals: Local_1: ex As System.Exception
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: ex As System.Exception) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'ex')
Initializer:
null
Filter:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 0')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Handler:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch ex As ... Throw ex')
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'Throw ex')
ILocalReferenceOperation: ex (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'ex')
Finally:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: 'Finally ... i = 1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 1')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_SingleCatchClause()
Dim source = <![CDATA[
Class C
Private Shared Sub M()
Try'BIND:"Try"
Catch e As System.IO.IOException
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch e As ... IOException')
Locals: Local_1: e As System.IO.IOException
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: e As System.IO.IOException) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e')
Initializer:
null
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch e As ... IOException')
Finally:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_SingleCatchClauseAndFilter()
Dim source = <![CDATA[
Class C
Private Shared Sub M()
Try'BIND:"Try"
Catch e As System.IO.IOException When e.Message IsNot Nothing
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch e As ... Not Nothing')
Locals: Local_1: e As System.IO.IOException
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: e As System.IO.IOException) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e')
Initializer:
null
Filter:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message IsNot Nothing')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'e.Message')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Exception.Message As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message')
Instance Receiver:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch e As ... Not Nothing')
Finally:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_MultipleCatchClausesWithDifferentCaughtTypes()
Dim source = <![CDATA[
Class C
Private Shared Sub M()
Try'BIND:"Try"
Catch e As System.IO.IOException
Catch e As System.Exception When e.Message IsNot Nothing
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(2):
ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch e As ... IOException')
Locals: Local_1: e As System.IO.IOException
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: e As System.IO.IOException) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e')
Initializer:
null
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch e As ... IOException')
ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch e As ... Not Nothing')
Locals: Local_1: e As System.Exception
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: e As System.Exception) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e')
Initializer:
null
Filter:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message IsNot Nothing')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'e.Message')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Exception.Message As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message')
Instance Receiver:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch e As ... Not Nothing')
Finally:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_MultipleCatchClausesWithDuplicateCaughtTypes()
Dim source = <![CDATA[
Class C
Private Shared Sub M()
Try'BIND:"Try"
Catch e As System.IO.IOException
Catch e As System.IO.IOException When e.Message IsNot Nothing
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(2):
ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch e As ... IOException')
Locals: Local_1: e As System.IO.IOException
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: e As System.IO.IOException) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e')
Initializer:
null
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch e As ... IOException')
ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch e As ... Not Nothing')
Locals: Local_1: e As System.IO.IOException
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: e As System.IO.IOException) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e')
Initializer:
null
Filter:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message IsNot Nothing')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'e.Message')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Exception.Message As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message')
Instance Receiver:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch e As ... Not Nothing')
Finally:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42031: 'Catch' block never reached; 'IOException' handled above in the same Try statement.
Catch e As System.IO.IOException When e.Message IsNot Nothing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_CatchClauseWithTypeExpression()
Dim source = <![CDATA[
Class C
Private Shared Sub M()
Try'BIND:"Try"
Catch System.Exception
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null, IsInvalid) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: ?) (OperationKind.CatchClause, Type: null, IsInvalid) (Syntax: 'Catch System')
ExceptionDeclarationOrExpression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'System')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'System')
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Catch System')
Finally:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31082: 'System' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch System.Exception
~~~~~~
BC30205: End of statement expected.
Catch System.Exception
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_CatchClauseWithLocalReferenceExpression()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M()
Dim e As IO.IOException = Nothing
Try'BIND:"Try"
Catch e
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch e')
ExceptionDeclarationOrExpression:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e')
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch e')
Finally:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_CatchClauseWithParameterReferenceExpression()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M(e As IO.IOException)
Try'BIND:"Try"
Catch e
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch e')
ExceptionDeclarationOrExpression:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.IO.IOException) (Syntax: 'e')
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch e')
Finally:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_CatchClauseWithFieldReferenceExpression()
Dim source = <![CDATA[
Imports System
Class C
Private e As IO.IOException = Nothing
Private Sub M()
Try 'BIND:"Try"'BIND:"Try 'BIND:"Try""
Catch e
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null, IsInvalid) (Syntax: 'Try 'BIND:" ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Try 'BIND:" ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null, IsInvalid) (Syntax: 'Catch e')
ExceptionDeclarationOrExpression:
IFieldReferenceOperation: C.e As System.IO.IOException (OperationKind.FieldReference, Type: System.IO.IOException, IsInvalid) (Syntax: 'e')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'e')
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Catch e')
Finally:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31082: 'e' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch e
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_CatchClauseWithErrorExpression()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M()
Try'BIND:"Try"
Catch e
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null, IsInvalid) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: ?) (OperationKind.CatchClause, Type: null, IsInvalid) (Syntax: 'Catch e')
ExceptionDeclarationOrExpression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'e')
Children(0)
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Catch e')
Finally:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30451: 'e' is not declared. It may be inaccessible due to its protection level.
Catch e
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_CatchClauseWithInvalidExpression()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M()
Try'BIND:"Try"
Catch M2(e)
End Try
End Sub
Private Shared Function M2(e As Exception) As Exception
Return e
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null, IsInvalid) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: ?) (OperationKind.CatchClause, Type: null, IsInvalid) (Syntax: 'Catch M2')
ExceptionDeclarationOrExpression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Catch M2')
Finally:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31082: 'M2' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch M2(e)
~~
BC30205: End of statement expected.
Catch M2(e)
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_CatchClauseWithoutCaughtTypeOrExceptionLocal()
Dim source = <![CDATA[
Class C
Private Shared Sub M()
Try'BIND:"Try"
Catch
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch')
ExceptionDeclarationOrExpression:
null
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch')
Finally:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_FinallyWithoutCatchClause()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M(s As String)
Try'BIND:"Try"
Finally
Console.WriteLine(s)
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(0)
Finally:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: 'Finally ... riteLine(s)')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's')
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.String) (Syntax: 's')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_TryBlockWithLocalDeclaration()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M(s As String)
Try'BIND:"Try"
Dim i As Integer = 0
Finally
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Locals: Local_1: i As System.Int32
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i As Integer = 0')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i As Integer = 0')
Declarators:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Catch clauses(0)
Finally:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: 'Finally')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_CatchBlockWithLocalDeclaration()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M(s As String)
Try'BIND:"Try"
Catch ex As Exception
Dim i As Integer = 0
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch ex As ... Integer = 0')
Locals: Local_1: ex As System.Exception
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: ex As System.Exception) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'ex')
Initializer:
null
Filter:
null
Handler:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch ex As ... Integer = 0')
Locals: Local_1: i As System.Int32
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i As Integer = 0')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i As Integer = 0')
Declarators:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Finally:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_FinallyWithLocalDeclaration()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M(s As String)
Try'BIND:"Try"
Finally
Dim i As Integer = 0
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(0)
Finally:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: 'Finally ... Integer = 0')
Locals: Local_1: i As System.Int32
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i As Integer = 0')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i As Integer = 0')
Declarators:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_InvalidCaughtType()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M(s As String)
Try'BIND:"Try"
Catch i As Integer
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ITryOperation (Exit Label Id: 0) (OperationKind.Try, Type: null, IsInvalid) (Syntax: 'Try'BIND:"T ... End Try')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Try'BIND:"T ... End Try')
Catch clauses(1):
ICatchClauseOperation (Exception type: System.Int32) (OperationKind.CatchClause, Type: null, IsInvalid) (Syntax: 'Catch i As Integer')
Locals: Local_1: i As System.Int32
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i')
Initializer:
null
Filter:
null
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Catch i As Integer')
Finally:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30392: 'Catch' cannot catch type 'Integer' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch i As Integer
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForCatchBlock()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M()
Try
Catch e As IO.IOException When e.Message IsNot Nothing'BIND:"Catch e As IO.IOException When e.Message IsNot Nothing"
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'Catch e As ... Not Nothing')
Locals: Local_1: e As System.IO.IOException
ExceptionDeclarationOrExpression:
IVariableDeclaratorOperation (Symbol: e As System.IO.IOException) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e')
Initializer:
null
Filter:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message IsNot Nothing')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'e.Message')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Exception.Message As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message')
Instance Receiver:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
Handler:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Catch e As ... Not Nothing')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CatchBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForFinallyBlock()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M(s As String)
Try
Finally'BIND:"Finally"
Console.WriteLine(s)
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: 'Finally'BIN ... riteLine(s)')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's')
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.String) (Syntax: 's')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of FinallyBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForCatchExceptionIdentifier()
Dim source = <![CDATA[
Imports System
Class C
Private Sub M(e As Exception)
Try
Catch e'BIND:"e"
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'e')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(Skip:="https://github.com/dotnet/roslyn/issues/22299")>
Public Sub TryCatch_GetOperationForCatchExceptionDeclaration()
Dim source = <![CDATA[
Imports System
Class C
Private Sub M()
Try
Catch e As Exception'BIND:"e"
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'e')
Variables: Local_1: e As System.Exception
Initializer: null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForCatchFilterClause()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M()
Try
Catch e As IO.IOException When e.Message IsNot Nothing'BIND:"When e.Message IsNot Nothing"
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
]]>.Value
' GetOperation return Nothing for CatchFilterClauseSyntax
Assert.Null(GetOperationTreeForTest(Of CatchFilterClauseSyntax)(source).operation)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForCatchFilterClauseExpression()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M()
Try
Catch e As IO.IOException When e.Message IsNot Nothing'BIND:"e.Message IsNot Nothing"
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message IsNot Nothing')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'e.Message')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Exception.Message As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message')
Instance Receiver:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of BinaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForCatchStatement()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M()
Try
Catch e As IO.IOException When e.Message IsNot Nothing'BIND:"Catch e As IO.IOException When e.Message IsNot Nothing"
End Try
End Sub
End Class]]>.Value
' GetOperation returns Nothing for CatchStatementSyntax
Assert.Null(GetOperationTreeForTest(Of CatchStatementSyntax)(source).operation)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForTryStatement()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M()
Try'BIND:"Try"
Catch e As IO.IOException When e.Message IsNot Nothing
End Try
End Sub
End Class]]>.Value
' GetOperation returns Nothing for TryStatementSyntax
Assert.Null(GetOperationTreeForTest(Of TryStatementSyntax)(source).operation)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForEndTryStatement()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M()
Try
Catch e As IO.IOException When e.Message IsNot Nothing
End Try'BIND:"End Try"
End Sub
End Class]]>.Value
' GetOperation returns Nothing for End Try statement
Assert.Null(GetOperationTreeForTest(Of EndBlockStatementSyntax)(source).operation)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForFinallyStatement()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M(s As String)
Try
Finally'BIND:"Finally"
Console.WriteLine(s)
End Try
End Sub
End Class]]>.Value
' GetOperation returns Nothing for FinallyStatementSyntax
Assert.Null(GetOperationTreeForTest(Of FinallyStatementSyntax)(source).operation)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForStatementInTryBlock()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M(s As String)
Try
Console.WriteLine(s)'BIND:"Console.WriteLine(s)"
Catch e As IO.IOException
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's')
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.String) (Syntax: 's')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForStatementInCatchBlock()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M()
Try
Catch e As IO.IOException
Console.WriteLine(e)'BIND:"Console.WriteLine(e)"
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(e)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(e)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'e')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'e')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TryCatch_GetOperationForStatementInFinallyBlock()
Dim source = <![CDATA[
Imports System
Class C
Private Shared Sub M(s As String)
Try
Finally
Console.WriteLine(s)'BIND:"Console.WriteLine(s)"
End Try
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's')
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.String) (Syntax: 's')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ExceptionDispatch_45()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer) 'BIND:"Sub M"
Try
Throw New NullReferenceException()
label1:
x = 1
End
Catch
x = 3
GoTo label1
Finally
x = 4
end Try
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.try {R1, R2}
{
.try {R3, R4}
{
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Throw) Block[null]
IObjectCreationOperation (Constructor: Sub System.NullReferenceException..ctor()) (OperationKind.ObjectCreation, Type: System.NullReferenceException) (Syntax: 'New NullRef ... Exception()')
Arguments(0)
Initializer:
null
Block[B2] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (ProgramTermination) Block[null]
}
.catch {R5} (System.Exception)
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 3')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B2]
Leaving: {R5}
Entering: {R4}
}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 4')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 4')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (StructuredExceptionHandling) Block[null]
}
Block[B5] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub FinallyDispatch_04()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Integer) 'BIND:"Sub M"
GoTo label2
Try
Try
label1:
x = 1
label2:
x = 2
Finally
x = 3
end Try
Finally
x = 4
goto label1
end Try
End Sub
End Class]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30754: 'GoTo label2' is not valid because 'label2' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label2
~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
goto label1
~~~~~~
BC30754: 'GoTo label1' is not valid because 'label1' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
goto label1
~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Entering: {R1} {R2} {R3} {R4}
.try {R1, R2}
{
.try {R3, R4}
{
Block[B1] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B0] [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 2')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B5]
Finalizing: {R5} {R6}
Leaving: {R4} {R3} {R2} {R1}
}
.finally {R5}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 3')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 4')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 4')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B1]
Leaving: {R6}
Entering: {R2} {R3} {R4}
}
Block[B5] - Exit [UnReachable]
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub TryFlow_30()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Integer) 'BIND:"Sub M"
Try
x = 1
end Try
End Sub
End Class]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30030: Try must have at least one 'Catch' or a 'Finally'.
Try
~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub TryFlow_31()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Integer, y as boolean) 'BIND:"Sub M"
Try
If y
Exit Try
End If
x = 1
end Try
x = 2
End Sub
End Class]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30030: Try must have at least one 'Catch' or a 'Finally'.
Try
~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 2')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| {
"pile_set_name": "Github"
} |
#import <Foundation/Foundation.h>
NSArray *CDRReportersFromEnv(const char*defaultReporterClassName);
int runSpecs();
int runAllSpecs() __attribute__((deprecated));
int runSpecsWithCustomExampleReporters(NSArray *reporters);
NSArray *specClassesToRun();
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2008 Michael Brown <[email protected]>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
FILE_LICENCE ( GPL2_OR_LATER );
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <byteswap.h>
#include <ipxe/netdevice.h>
#include <ipxe/iobuf.h>
#include <ipxe/in.h>
#include <ipxe/pci.h>
#include <ipxe/efi/efi.h>
#include <ipxe/efi/efi_pci.h>
#include <ipxe/efi/efi_driver.h>
#include <ipxe/efi/efi_strings.h>
#include <ipxe/efi/efi_hii.h>
#include <ipxe/efi/Protocol/SimpleNetwork.h>
#include <ipxe/efi/Protocol/NetworkInterfaceIdentifier.h>
#include <ipxe/efi/Protocol/DevicePath.h>
#include <ipxe/efi/Protocol/HiiConfigAccess.h>
#include <ipxe/efi/Protocol/HiiDatabase.h>
#include <config/general.h>
/** @file
*
* iPXE EFI SNP interface
*
*/
/** An SNP device */
struct efi_snp_device {
/** List of SNP devices */
struct list_head list;
/** The underlying iPXE network device */
struct net_device *netdev;
/** The underlying EFI PCI device */
struct efi_pci_device *efipci;
/** EFI device handle */
EFI_HANDLE handle;
/** The SNP structure itself */
EFI_SIMPLE_NETWORK_PROTOCOL snp;
/** The SNP "mode" (parameters) */
EFI_SIMPLE_NETWORK_MODE mode;
/** Outstanding TX packet count (via "interrupt status")
*
* Used in order to generate TX completions.
*/
unsigned int tx_count_interrupts;
/** Outstanding TX packet count (via "recycled tx buffers")
*
* Used in order to generate TX completions.
*/
unsigned int tx_count_txbufs;
/** Outstanding RX packet count (via "interrupt status") */
unsigned int rx_count_interrupts;
/** Outstanding RX packet count (via WaitForPacket event) */
unsigned int rx_count_events;
/** The network interface identifier */
EFI_NETWORK_INTERFACE_IDENTIFIER_PROTOCOL nii;
/** HII configuration access protocol */
EFI_HII_CONFIG_ACCESS_PROTOCOL hii;
/** HII package list */
EFI_HII_PACKAGE_LIST_HEADER *package_list;
/** HII handle */
EFI_HII_HANDLE hii_handle;
/** Device name */
wchar_t name[ sizeof ( ( ( struct net_device * ) NULL )->name ) ];
/** The device path
*
* This field is variable in size and must appear at the end
* of the structure.
*/
EFI_DEVICE_PATH_PROTOCOL path;
};
/** EFI simple network protocol GUID */
static EFI_GUID efi_simple_network_protocol_guid
= EFI_SIMPLE_NETWORK_PROTOCOL_GUID;
/** EFI device path protocol GUID */
static EFI_GUID efi_device_path_protocol_guid
= EFI_DEVICE_PATH_PROTOCOL_GUID;
/** EFI network interface identifier GUID */
static EFI_GUID efi_nii_protocol_guid
= EFI_NETWORK_INTERFACE_IDENTIFIER_PROTOCOL_GUID;
/** EFI network interface identifier GUID (extra special version) */
static EFI_GUID efi_nii31_protocol_guid = {
/* At some point, it seems that someone decided to change the
* GUID. Current EFI builds ignore the older GUID, older EFI
* builds ignore the newer GUID, so we have to expose both.
*/
0x1ACED566, 0x76ED, 0x4218,
{ 0xBC, 0x81, 0x76, 0x7F, 0x1F, 0x97, 0x7A, 0x89 }
};
/** List of SNP devices */
static LIST_HEAD ( efi_snp_devices );
/**
* Set EFI SNP mode based on iPXE net device parameters
*
* @v snp SNP interface
*/
static void efi_snp_set_mode ( struct efi_snp_device *snpdev ) {
struct net_device *netdev = snpdev->netdev;
EFI_SIMPLE_NETWORK_MODE *mode = &snpdev->mode;
struct ll_protocol *ll_protocol = netdev->ll_protocol;
unsigned int ll_addr_len = ll_protocol->ll_addr_len;
mode->HwAddressSize = ll_addr_len;
mode->MediaHeaderSize = ll_protocol->ll_header_len;
mode->MaxPacketSize = netdev->max_pkt_len;
mode->ReceiveFilterMask = ( EFI_SIMPLE_NETWORK_RECEIVE_UNICAST |
EFI_SIMPLE_NETWORK_RECEIVE_MULTICAST |
EFI_SIMPLE_NETWORK_RECEIVE_BROADCAST );
assert ( ll_addr_len <= sizeof ( mode->CurrentAddress ) );
memcpy ( &mode->CurrentAddress, netdev->ll_addr, ll_addr_len );
memcpy ( &mode->BroadcastAddress, netdev->ll_broadcast, ll_addr_len );
ll_protocol->init_addr ( netdev->hw_addr, &mode->PermanentAddress );
mode->IfType = ntohs ( ll_protocol->ll_proto );
mode->MacAddressChangeable = TRUE;
mode->MediaPresentSupported = TRUE;
mode->MediaPresent = ( netdev_link_ok ( netdev ) ? TRUE : FALSE );
}
/**
* Poll net device and count received packets
*
* @v snpdev SNP device
*/
static void efi_snp_poll ( struct efi_snp_device *snpdev ) {
struct io_buffer *iobuf;
unsigned int before = 0;
unsigned int after = 0;
unsigned int arrived;
/* We have to report packet arrivals, and this is the easiest
* way to fake it.
*/
list_for_each_entry ( iobuf, &snpdev->netdev->rx_queue, list )
before++;
netdev_poll ( snpdev->netdev );
list_for_each_entry ( iobuf, &snpdev->netdev->rx_queue, list )
after++;
arrived = ( after - before );
snpdev->rx_count_interrupts += arrived;
snpdev->rx_count_events += arrived;
}
/**
* Change SNP state from "stopped" to "started"
*
* @v snp SNP interface
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_start ( EFI_SIMPLE_NETWORK_PROTOCOL *snp ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
DBGC2 ( snpdev, "SNPDEV %p START\n", snpdev );
snpdev->mode.State = EfiSimpleNetworkStarted;
return 0;
}
/**
* Change SNP state from "started" to "stopped"
*
* @v snp SNP interface
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_stop ( EFI_SIMPLE_NETWORK_PROTOCOL *snp ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
DBGC2 ( snpdev, "SNPDEV %p STOP\n", snpdev );
snpdev->mode.State = EfiSimpleNetworkStopped;
return 0;
}
/**
* Open the network device
*
* @v snp SNP interface
* @v extra_rx_bufsize Extra RX buffer size, in bytes
* @v extra_tx_bufsize Extra TX buffer size, in bytes
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_initialize ( EFI_SIMPLE_NETWORK_PROTOCOL *snp,
UINTN extra_rx_bufsize, UINTN extra_tx_bufsize ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
int rc;
DBGC2 ( snpdev, "SNPDEV %p INITIALIZE (%ld extra RX, %ld extra TX)\n",
snpdev, ( ( unsigned long ) extra_rx_bufsize ),
( ( unsigned long ) extra_tx_bufsize ) );
if ( ( rc = netdev_open ( snpdev->netdev ) ) != 0 ) {
DBGC ( snpdev, "SNPDEV %p could not open %s: %s\n",
snpdev, snpdev->netdev->name, strerror ( rc ) );
return RC_TO_EFIRC ( rc );
}
snpdev->mode.State = EfiSimpleNetworkInitialized;
return 0;
}
/**
* Reset the network device
*
* @v snp SNP interface
* @v ext_verify Extended verification required
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_reset ( EFI_SIMPLE_NETWORK_PROTOCOL *snp, BOOLEAN ext_verify ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
int rc;
DBGC2 ( snpdev, "SNPDEV %p RESET (%s extended verification)\n",
snpdev, ( ext_verify ? "with" : "without" ) );
netdev_close ( snpdev->netdev );
snpdev->mode.State = EfiSimpleNetworkStarted;
if ( ( rc = netdev_open ( snpdev->netdev ) ) != 0 ) {
DBGC ( snpdev, "SNPDEV %p could not reopen %s: %s\n",
snpdev, snpdev->netdev->name, strerror ( rc ) );
return RC_TO_EFIRC ( rc );
}
snpdev->mode.State = EfiSimpleNetworkInitialized;
return 0;
}
/**
* Shut down the network device
*
* @v snp SNP interface
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_shutdown ( EFI_SIMPLE_NETWORK_PROTOCOL *snp ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
DBGC2 ( snpdev, "SNPDEV %p SHUTDOWN\n", snpdev );
netdev_close ( snpdev->netdev );
snpdev->mode.State = EfiSimpleNetworkStarted;
return 0;
}
/**
* Manage receive filters
*
* @v snp SNP interface
* @v enable Receive filters to enable
* @v disable Receive filters to disable
* @v mcast_reset Reset multicast filters
* @v mcast_count Number of multicast filters
* @v mcast Multicast filters
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_receive_filters ( EFI_SIMPLE_NETWORK_PROTOCOL *snp, UINT32 enable,
UINT32 disable, BOOLEAN mcast_reset,
UINTN mcast_count, EFI_MAC_ADDRESS *mcast ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
unsigned int i;
DBGC2 ( snpdev, "SNPDEV %p RECEIVE_FILTERS %08x&~%08x%s %ld mcast\n",
snpdev, enable, disable, ( mcast_reset ? " reset" : "" ),
( ( unsigned long ) mcast_count ) );
for ( i = 0 ; i < mcast_count ; i++ ) {
DBGC2_HDA ( snpdev, i, &mcast[i],
snpdev->netdev->ll_protocol->ll_addr_len );
}
/* Lie through our teeth, otherwise MNP refuses to accept us */
return 0;
}
/**
* Set station address
*
* @v snp SNP interface
* @v reset Reset to permanent address
* @v new New station address
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_station_address ( EFI_SIMPLE_NETWORK_PROTOCOL *snp, BOOLEAN reset,
EFI_MAC_ADDRESS *new ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
struct ll_protocol *ll_protocol = snpdev->netdev->ll_protocol;
DBGC2 ( snpdev, "SNPDEV %p STATION_ADDRESS %s\n", snpdev,
( reset ? "reset" : ll_protocol->ntoa ( new ) ) );
/* Set the MAC address */
if ( reset )
new = &snpdev->mode.PermanentAddress;
memcpy ( snpdev->netdev->ll_addr, new, ll_protocol->ll_addr_len );
/* MAC address changes take effect only on netdev_open() */
if ( netdev_is_open ( snpdev->netdev ) ) {
DBGC ( snpdev, "SNPDEV %p MAC address changed while net "
"devive open\n", snpdev );
}
return 0;
}
/**
* Get (or reset) statistics
*
* @v snp SNP interface
* @v reset Reset statistics
* @v stats_len Size of statistics table
* @v stats Statistics table
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_statistics ( EFI_SIMPLE_NETWORK_PROTOCOL *snp, BOOLEAN reset,
UINTN *stats_len, EFI_NETWORK_STATISTICS *stats ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
EFI_NETWORK_STATISTICS stats_buf;
DBGC2 ( snpdev, "SNPDEV %p STATISTICS%s", snpdev,
( reset ? " reset" : "" ) );
/* Gather statistics */
memset ( &stats_buf, 0, sizeof ( stats_buf ) );
stats_buf.TxGoodFrames = snpdev->netdev->tx_stats.good;
stats_buf.TxDroppedFrames = snpdev->netdev->tx_stats.bad;
stats_buf.TxTotalFrames = ( snpdev->netdev->tx_stats.good +
snpdev->netdev->tx_stats.bad );
stats_buf.RxGoodFrames = snpdev->netdev->rx_stats.good;
stats_buf.RxDroppedFrames = snpdev->netdev->rx_stats.bad;
stats_buf.RxTotalFrames = ( snpdev->netdev->rx_stats.good +
snpdev->netdev->rx_stats.bad );
if ( *stats_len > sizeof ( stats_buf ) )
*stats_len = sizeof ( stats_buf );
if ( stats )
memcpy ( stats, &stats_buf, *stats_len );
/* Reset statistics if requested to do so */
if ( reset ) {
memset ( &snpdev->netdev->tx_stats, 0,
sizeof ( snpdev->netdev->tx_stats ) );
memset ( &snpdev->netdev->rx_stats, 0,
sizeof ( snpdev->netdev->rx_stats ) );
}
return 0;
}
/**
* Convert multicast IP address to MAC address
*
* @v snp SNP interface
* @v ipv6 Address is IPv6
* @v ip IP address
* @v mac MAC address
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_mcast_ip_to_mac ( EFI_SIMPLE_NETWORK_PROTOCOL *snp, BOOLEAN ipv6,
EFI_IP_ADDRESS *ip, EFI_MAC_ADDRESS *mac ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
struct ll_protocol *ll_protocol = snpdev->netdev->ll_protocol;
const char *ip_str;
int rc;
ip_str = ( ipv6 ? "(IPv6)" /* FIXME when we have inet6_ntoa() */ :
inet_ntoa ( *( ( struct in_addr * ) ip ) ) );
DBGC2 ( snpdev, "SNPDEV %p MCAST_IP_TO_MAC %s\n", snpdev, ip_str );
/* Try to hash the address */
if ( ( rc = ll_protocol->mc_hash ( ( ipv6 ? AF_INET6 : AF_INET ),
ip, mac ) ) != 0 ) {
DBGC ( snpdev, "SNPDEV %p could not hash %s: %s\n",
snpdev, ip_str, strerror ( rc ) );
return RC_TO_EFIRC ( rc );
}
return 0;
}
/**
* Read or write non-volatile storage
*
* @v snp SNP interface
* @v read Operation is a read
* @v offset Starting offset within NVRAM
* @v len Length of data buffer
* @v data Data buffer
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_nvdata ( EFI_SIMPLE_NETWORK_PROTOCOL *snp, BOOLEAN read,
UINTN offset, UINTN len, VOID *data ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
DBGC2 ( snpdev, "SNPDEV %p NVDATA %s %lx+%lx\n", snpdev,
( read ? "read" : "write" ), ( ( unsigned long ) offset ),
( ( unsigned long ) len ) );
if ( ! read )
DBGC2_HDA ( snpdev, offset, data, len );
return EFI_UNSUPPORTED;
}
/**
* Read interrupt status and TX recycled buffer status
*
* @v snp SNP interface
* @v interrupts Interrupt status, or NULL
* @v txbufs Recycled transmit buffer address, or NULL
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_get_status ( EFI_SIMPLE_NETWORK_PROTOCOL *snp,
UINT32 *interrupts, VOID **txbufs ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
DBGC2 ( snpdev, "SNPDEV %p GET_STATUS", snpdev );
/* Poll the network device */
efi_snp_poll ( snpdev );
/* Interrupt status. In practice, this seems to be used only
* to detect TX completions.
*/
if ( interrupts ) {
*interrupts = 0;
/* Report TX completions once queue is empty; this
* avoids having to add hooks in the net device layer.
*/
if ( snpdev->tx_count_interrupts &&
list_empty ( &snpdev->netdev->tx_queue ) ) {
*interrupts |= EFI_SIMPLE_NETWORK_TRANSMIT_INTERRUPT;
snpdev->tx_count_interrupts--;
}
/* Report RX */
if ( snpdev->rx_count_interrupts ) {
*interrupts |= EFI_SIMPLE_NETWORK_RECEIVE_INTERRUPT;
snpdev->rx_count_interrupts--;
}
DBGC2 ( snpdev, " INTS:%02x", *interrupts );
}
/* TX completions. It would be possible to design a more
* idiotic scheme for this, but it would be a challenge.
* According to the UEFI header file, txbufs will be filled in
* with a list of "recycled transmit buffers" (i.e. completed
* TX buffers). Observant readers may care to note that
* *txbufs is a void pointer. Precisely how a list of
* completed transmit buffers is meant to be represented as an
* array of voids is left as an exercise for the reader.
*
* The only users of this interface (MnpDxe/MnpIo.c and
* PxeBcDxe/Bc.c within the EFI dev kit) both just poll until
* seeing a non-NULL result return in txbufs. This is valid
* provided that they do not ever attempt to transmit more
* than one packet concurrently (and that TX never times out).
*/
if ( txbufs ) {
if ( snpdev->tx_count_txbufs &&
list_empty ( &snpdev->netdev->tx_queue ) ) {
*txbufs = "Which idiot designed this API?";
snpdev->tx_count_txbufs--;
} else {
*txbufs = NULL;
}
DBGC2 ( snpdev, " TX:%s", ( *txbufs ? "some" : "none" ) );
}
DBGC2 ( snpdev, "\n" );
return 0;
}
/**
* Start packet transmission
*
* @v snp SNP interface
* @v ll_header_len Link-layer header length, if to be filled in
* @v len Length of data buffer
* @v data Data buffer
* @v ll_src Link-layer source address, if specified
* @v ll_dest Link-layer destination address, if specified
* @v net_proto Network-layer protocol (in host order)
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_transmit ( EFI_SIMPLE_NETWORK_PROTOCOL *snp,
UINTN ll_header_len, UINTN len, VOID *data,
EFI_MAC_ADDRESS *ll_src, EFI_MAC_ADDRESS *ll_dest,
UINT16 *net_proto ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
struct ll_protocol *ll_protocol = snpdev->netdev->ll_protocol;
struct io_buffer *iobuf;
size_t ll_headroom;
int rc;
EFI_STATUS efirc;
DBGC2 ( snpdev, "SNPDEV %p TRANSMIT %p+%lx", snpdev, data,
( ( unsigned long ) len ) );
if ( ll_header_len ) {
if ( ll_src ) {
DBGC2 ( snpdev, " src %s",
ll_protocol->ntoa ( ll_src ) );
}
if ( ll_dest ) {
DBGC2 ( snpdev, " dest %s",
ll_protocol->ntoa ( ll_dest ) );
}
if ( net_proto ) {
DBGC2 ( snpdev, " proto %04x", *net_proto );
}
}
DBGC2 ( snpdev, "\n" );
/* Sanity checks */
if ( ll_header_len ) {
if ( ll_header_len != ll_protocol->ll_header_len ) {
DBGC ( snpdev, "SNPDEV %p TX invalid header length "
"%ld\n", snpdev,
( ( unsigned long ) ll_header_len ) );
efirc = EFI_INVALID_PARAMETER;
goto err_sanity;
}
if ( len < ll_header_len ) {
DBGC ( snpdev, "SNPDEV %p invalid packet length %ld\n",
snpdev, ( ( unsigned long ) len ) );
efirc = EFI_BUFFER_TOO_SMALL;
goto err_sanity;
}
if ( ! ll_dest ) {
DBGC ( snpdev, "SNPDEV %p TX missing destination "
"address\n", snpdev );
efirc = EFI_INVALID_PARAMETER;
goto err_sanity;
}
if ( ! net_proto ) {
DBGC ( snpdev, "SNPDEV %p TX missing network "
"protocol\n", snpdev );
efirc = EFI_INVALID_PARAMETER;
goto err_sanity;
}
if ( ! ll_src )
ll_src = &snpdev->mode.CurrentAddress;
}
/* Allocate buffer */
ll_headroom = ( MAX_LL_HEADER_LEN - ll_header_len );
iobuf = alloc_iob ( ll_headroom + len );
if ( ! iobuf ) {
DBGC ( snpdev, "SNPDEV %p TX could not allocate %ld-byte "
"buffer\n", snpdev, ( ( unsigned long ) len ) );
efirc = EFI_DEVICE_ERROR;
goto err_alloc_iob;
}
iob_reserve ( iobuf, ll_headroom );
memcpy ( iob_put ( iobuf, len ), data, len );
/* Create link-layer header, if specified */
if ( ll_header_len ) {
iob_pull ( iobuf, ll_header_len );
if ( ( rc = ll_protocol->push ( snpdev->netdev,
iobuf, ll_dest, ll_src,
htons ( *net_proto ) )) != 0 ){
DBGC ( snpdev, "SNPDEV %p TX could not construct "
"header: %s\n", snpdev, strerror ( rc ) );
efirc = RC_TO_EFIRC ( rc );
goto err_ll_push;
}
}
/* Transmit packet */
if ( ( rc = netdev_tx ( snpdev->netdev, iob_disown ( iobuf ) ) ) != 0){
DBGC ( snpdev, "SNPDEV %p TX could not transmit: %s\n",
snpdev, strerror ( rc ) );
efirc = RC_TO_EFIRC ( rc );
goto err_tx;
}
/* Record transmission as outstanding */
snpdev->tx_count_interrupts++;
snpdev->tx_count_txbufs++;
return 0;
err_tx:
err_ll_push:
free_iob ( iobuf );
err_alloc_iob:
err_sanity:
return efirc;
}
/**
* Receive packet
*
* @v snp SNP interface
* @v ll_header_len Link-layer header length, if to be filled in
* @v len Length of data buffer
* @v data Data buffer
* @v ll_src Link-layer source address, if specified
* @v ll_dest Link-layer destination address, if specified
* @v net_proto Network-layer protocol (in host order)
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_receive ( EFI_SIMPLE_NETWORK_PROTOCOL *snp,
UINTN *ll_header_len, UINTN *len, VOID *data,
EFI_MAC_ADDRESS *ll_src, EFI_MAC_ADDRESS *ll_dest,
UINT16 *net_proto ) {
struct efi_snp_device *snpdev =
container_of ( snp, struct efi_snp_device, snp );
struct ll_protocol *ll_protocol = snpdev->netdev->ll_protocol;
struct io_buffer *iobuf;
const void *iob_ll_dest;
const void *iob_ll_src;
uint16_t iob_net_proto;
int rc;
EFI_STATUS efirc;
DBGC2 ( snpdev, "SNPDEV %p RECEIVE %p(+%lx)", snpdev, data,
( ( unsigned long ) *len ) );
/* Poll the network device */
efi_snp_poll ( snpdev );
/* Dequeue a packet, if one is available */
iobuf = netdev_rx_dequeue ( snpdev->netdev );
if ( ! iobuf ) {
DBGC2 ( snpdev, "\n" );
efirc = EFI_NOT_READY;
goto out_no_packet;
}
DBGC2 ( snpdev, "+%zx\n", iob_len ( iobuf ) );
/* Return packet to caller */
memcpy ( data, iobuf->data, iob_len ( iobuf ) );
*len = iob_len ( iobuf );
/* Attempt to decode link-layer header */
if ( ( rc = ll_protocol->pull ( snpdev->netdev, iobuf, &iob_ll_dest,
&iob_ll_src, &iob_net_proto ) ) != 0 ){
DBGC ( snpdev, "SNPDEV %p could not parse header: %s\n",
snpdev, strerror ( rc ) );
efirc = RC_TO_EFIRC ( rc );
goto out_bad_ll_header;
}
/* Return link-layer header parameters to caller, if required */
if ( ll_header_len )
*ll_header_len = ll_protocol->ll_header_len;
if ( ll_src )
memcpy ( ll_src, iob_ll_src, ll_protocol->ll_addr_len );
if ( ll_dest )
memcpy ( ll_dest, iob_ll_dest, ll_protocol->ll_addr_len );
if ( net_proto )
*net_proto = ntohs ( iob_net_proto );
efirc = 0;
out_bad_ll_header:
free_iob ( iobuf );
out_no_packet:
return efirc;
}
/**
* Poll event
*
* @v event Event
* @v context Event context
*/
static VOID EFIAPI efi_snp_wait_for_packet ( EFI_EVENT event,
VOID *context ) {
EFI_BOOT_SERVICES *bs = efi_systab->BootServices;
struct efi_snp_device *snpdev = context;
DBGCP ( snpdev, "SNPDEV %p WAIT_FOR_PACKET\n", snpdev );
/* Do nothing unless the net device is open */
if ( ! netdev_is_open ( snpdev->netdev ) )
return;
/* Poll the network device */
efi_snp_poll ( snpdev );
/* Fire event if packets have been received */
if ( snpdev->rx_count_events != 0 ) {
DBGC2 ( snpdev, "SNPDEV %p firing WaitForPacket event\n",
snpdev );
bs->SignalEvent ( event );
snpdev->rx_count_events--;
}
}
/** SNP interface */
static EFI_SIMPLE_NETWORK_PROTOCOL efi_snp_device_snp = {
.Revision = EFI_SIMPLE_NETWORK_PROTOCOL_REVISION,
.Start = efi_snp_start,
.Stop = efi_snp_stop,
.Initialize = efi_snp_initialize,
.Reset = efi_snp_reset,
.Shutdown = efi_snp_shutdown,
.ReceiveFilters = efi_snp_receive_filters,
.StationAddress = efi_snp_station_address,
.Statistics = efi_snp_statistics,
.MCastIpToMac = efi_snp_mcast_ip_to_mac,
.NvData = efi_snp_nvdata,
.GetStatus = efi_snp_get_status,
.Transmit = efi_snp_transmit,
.Receive = efi_snp_receive,
};
/******************************************************************************
*
* Human Interface Infrastructure
*
******************************************************************************
*/
/** EFI configuration access protocol GUID */
static EFI_GUID efi_hii_config_access_protocol_guid
= EFI_HII_CONFIG_ACCESS_PROTOCOL_GUID;
/** EFI HII database protocol */
static EFI_HII_DATABASE_PROTOCOL *efihii;
EFI_REQUIRE_PROTOCOL ( EFI_HII_DATABASE_PROTOCOL, &efihii );
/** Local GUID used for our EFI SNP formset */
#define EFI_SNP_FORMSET_GUID \
{ 0xc4f84019, 0x6dfd, 0x4a27, \
{ 0x9b, 0x94, 0xb7, 0x2e, 0x1f, 0xbc, 0xad, 0xca } }
/** Form identifiers used for our EFI SNP HII */
enum efi_snp_hii_form_id {
EFI_SNP_FORM = 0x0001, /**< The only form */
};
/** String identifiers used for our EFI SNP HII */
enum efi_snp_hii_string_id {
/* Language name */
EFI_SNP_LANGUAGE_NAME = 0x0001,
/* Formset */
EFI_SNP_FORMSET_TITLE, EFI_SNP_FORMSET_HELP,
/* Product name */
EFI_SNP_PRODUCT_PROMPT, EFI_SNP_PRODUCT_HELP, EFI_SNP_PRODUCT_TEXT,
/* Version */
EFI_SNP_VERSION_PROMPT, EFI_SNP_VERSION_HELP, EFI_SNP_VERSION_TEXT,
/* Driver */
EFI_SNP_DRIVER_PROMPT, EFI_SNP_DRIVER_HELP, EFI_SNP_DRIVER_TEXT,
/* Device */
EFI_SNP_DEVICE_PROMPT, EFI_SNP_DEVICE_HELP, EFI_SNP_DEVICE_TEXT,
/* End of list */
EFI_SNP_MAX_STRING_ID
};
/** EFI SNP formset */
struct efi_snp_formset {
EFI_HII_PACKAGE_HEADER Header;
EFI_IFR_FORM_SET_TYPE(1) FormSet;
EFI_IFR_GUID_CLASS Class;
EFI_IFR_GUID_SUBCLASS SubClass;
EFI_IFR_FORM Form;
EFI_IFR_TEXT ProductText;
EFI_IFR_TEXT VersionText;
EFI_IFR_TEXT DriverText;
EFI_IFR_TEXT DeviceText;
EFI_IFR_END EndForm;
EFI_IFR_END EndFormSet;
} __attribute__ (( packed )) efi_snp_formset = {
.Header = {
.Length = sizeof ( efi_snp_formset ),
.Type = EFI_HII_PACKAGE_FORMS,
},
.FormSet = EFI_IFR_FORM_SET ( EFI_SNP_FORMSET_GUID,
EFI_SNP_FORMSET_TITLE,
EFI_SNP_FORMSET_HELP,
typeof ( efi_snp_formset.FormSet ),
EFI_HII_PLATFORM_SETUP_FORMSET_GUID ),
.Class = EFI_IFR_GUID_CLASS ( EFI_NETWORK_DEVICE_CLASS ),
.SubClass = EFI_IFR_GUID_SUBCLASS ( 0x03 ),
.Form = EFI_IFR_FORM ( EFI_SNP_FORM, EFI_SNP_FORMSET_TITLE ),
.ProductText = EFI_IFR_TEXT ( EFI_SNP_PRODUCT_PROMPT,
EFI_SNP_PRODUCT_HELP,
EFI_SNP_PRODUCT_TEXT ),
.VersionText = EFI_IFR_TEXT ( EFI_SNP_VERSION_PROMPT,
EFI_SNP_VERSION_HELP,
EFI_SNP_VERSION_TEXT ),
.DriverText = EFI_IFR_TEXT ( EFI_SNP_DRIVER_PROMPT,
EFI_SNP_DRIVER_HELP,
EFI_SNP_DRIVER_TEXT ),
.DeviceText = EFI_IFR_TEXT ( EFI_SNP_DEVICE_PROMPT,
EFI_SNP_DEVICE_HELP,
EFI_SNP_DEVICE_TEXT ),
.EndForm = EFI_IFR_END(),
.EndFormSet = EFI_IFR_END(),
};
/**
* Generate EFI SNP string
*
* @v wbuf Buffer
* @v swlen Size of buffer (in wide characters)
* @v snpdev SNP device
* @ret wlen Length of string (in wide characters)
*/
static int efi_snp_string ( wchar_t *wbuf, ssize_t swlen,
enum efi_snp_hii_string_id id,
struct efi_snp_device *snpdev ) {
struct net_device *netdev = snpdev->netdev;
struct device *dev = netdev->dev;
switch ( id ) {
case EFI_SNP_LANGUAGE_NAME:
return efi_ssnprintf ( wbuf, swlen, "English" );
case EFI_SNP_FORMSET_TITLE:
return efi_ssnprintf ( wbuf, swlen, "%s (%s)",
( PRODUCT_NAME[0] ?
PRODUCT_NAME : PRODUCT_SHORT_NAME ),
netdev_addr ( netdev ) );
case EFI_SNP_FORMSET_HELP:
return efi_ssnprintf ( wbuf, swlen,
"Configure " PRODUCT_SHORT_NAME );
case EFI_SNP_PRODUCT_PROMPT:
return efi_ssnprintf ( wbuf, swlen, "Name" );
case EFI_SNP_PRODUCT_HELP:
return efi_ssnprintf ( wbuf, swlen, "Firmware product name" );
case EFI_SNP_PRODUCT_TEXT:
return efi_ssnprintf ( wbuf, swlen, "%s",
( PRODUCT_NAME[0] ?
PRODUCT_NAME : PRODUCT_SHORT_NAME ) );
case EFI_SNP_VERSION_PROMPT:
return efi_ssnprintf ( wbuf, swlen, "Version" );
case EFI_SNP_VERSION_HELP:
return efi_ssnprintf ( wbuf, swlen, "Firmware version" );
case EFI_SNP_VERSION_TEXT:
return efi_ssnprintf ( wbuf, swlen, VERSION );
case EFI_SNP_DRIVER_PROMPT:
return efi_ssnprintf ( wbuf, swlen, "Driver" );
case EFI_SNP_DRIVER_HELP:
return efi_ssnprintf ( wbuf, swlen, "Firmware driver" );
case EFI_SNP_DRIVER_TEXT:
return efi_ssnprintf ( wbuf, swlen, "%s", dev->driver_name );
case EFI_SNP_DEVICE_PROMPT:
return efi_ssnprintf ( wbuf, swlen, "Device" );
case EFI_SNP_DEVICE_HELP:
return efi_ssnprintf ( wbuf, swlen, "Hardware device" );
case EFI_SNP_DEVICE_TEXT:
return efi_ssnprintf ( wbuf, swlen, "%s", dev->name );
default:
assert ( 0 );
return 0;
}
}
/**
* Generate EFI SNP string package
*
* @v strings String package header buffer
* @v max_len Buffer length
* @v snpdev SNP device
* @ret len Length of string package
*/
static int efi_snp_strings ( EFI_HII_STRING_PACKAGE_HDR *strings,
size_t max_len, struct efi_snp_device *snpdev ) {
static const char language[] = "en-us";
void *buf = strings;
ssize_t remaining = max_len;
size_t hdrsize;
EFI_HII_SIBT_STRING_UCS2_BLOCK *string;
ssize_t wremaining;
size_t string_wlen;
unsigned int id;
EFI_HII_STRING_BLOCK *end;
size_t len;
/* Calculate header size */
hdrsize = ( offsetof ( typeof ( *strings ), Language ) +
sizeof ( language ) );
buf += hdrsize;
remaining -= hdrsize;
/* Fill in strings */
for ( id = 1 ; id < EFI_SNP_MAX_STRING_ID ; id++ ) {
string = buf;
if ( remaining >= ( ( ssize_t ) sizeof ( string->Header ) ) )
string->Header.BlockType = EFI_HII_SIBT_STRING_UCS2;
buf += offsetof ( typeof ( *string ), StringText );
remaining -= offsetof ( typeof ( *string ), StringText );
wremaining = ( remaining /
( ( ssize_t ) sizeof ( string->StringText[0] )));
assert ( ! ( ( remaining <= 0 ) && ( wremaining > 0 ) ) );
string_wlen = efi_snp_string ( string->StringText, wremaining,
id, snpdev );
buf += ( ( string_wlen + 1 /* wNUL */ ) *
sizeof ( string->StringText[0] ) );
remaining -= ( ( string_wlen + 1 /* wNUL */ ) *
sizeof ( string->StringText[0] ) );
}
/* Fill in end marker */
end = buf;
if ( remaining >= ( ( ssize_t ) sizeof ( *end ) ) )
end->BlockType = EFI_HII_SIBT_END;
buf += sizeof ( *end );
remaining -= sizeof ( *end );
/* Calculate overall length */
len = ( max_len - remaining );
/* Fill in string package header */
if ( strings ) {
memset ( strings, 0, sizeof ( *strings ) );
strings->Header.Length = len;
strings->Header.Type = EFI_HII_PACKAGE_STRINGS;
strings->HdrSize = hdrsize;
strings->StringInfoOffset = hdrsize;
strings->LanguageName = EFI_SNP_LANGUAGE_NAME;
memcpy ( strings->Language, language, sizeof ( language ) );
}
return len;
}
/**
* Generate EFI SNP package list
*
* @v snpdev SNP device
* @ret package_list Package list, or NULL on error
*
* The package list is allocated using malloc(), and must eventually
* be freed by the caller.
*/
static EFI_HII_PACKAGE_LIST_HEADER *
efi_snp_package_list ( struct efi_snp_device *snpdev ) {
size_t strings_len = efi_snp_strings ( NULL, 0, snpdev );
struct {
EFI_HII_PACKAGE_LIST_HEADER header;
struct efi_snp_formset formset;
union {
EFI_HII_STRING_PACKAGE_HDR strings;
uint8_t pad[strings_len];
} __attribute__ (( packed )) strings;
EFI_HII_PACKAGE_HEADER end;
} __attribute__ (( packed )) *package_list;
/* Allocate package list */
package_list = zalloc ( sizeof ( *package_list ) );
if ( ! package_list )
return NULL;
/* Populate package list */
memcpy ( &package_list->header.PackageListGuid,
&efi_snp_formset.FormSet.FormSet.Guid,
sizeof ( package_list->header.PackageListGuid ) );
package_list->header.PackageLength = sizeof ( *package_list );
memcpy ( &package_list->formset, &efi_snp_formset,
sizeof ( package_list->formset ) );
efi_snp_strings ( &package_list->strings.strings,
sizeof ( package_list->strings ), snpdev );
package_list->end.Length = sizeof ( package_list->end );
package_list->end.Type = EFI_HII_PACKAGE_END;
return &package_list->header;
}
/**
* Fetch configuration
*
* @v hii HII configuration access protocol
* @v request Configuration to fetch
* @ret progress Progress made through configuration to fetch
* @ret results Query results
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_hii_extract_config ( const EFI_HII_CONFIG_ACCESS_PROTOCOL *hii,
EFI_STRING request, EFI_STRING *progress,
EFI_STRING *results __unused ) {
struct efi_snp_device *snpdev =
container_of ( hii, struct efi_snp_device, hii );
DBGC ( snpdev, "SNPDEV %p ExtractConfig\n", snpdev );
*progress = request;
return EFI_INVALID_PARAMETER;
}
/**
* Store configuration
*
* @v hii HII configuration access protocol
* @v config Configuration to store
* @ret progress Progress made through configuration to store
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_hii_route_config ( const EFI_HII_CONFIG_ACCESS_PROTOCOL *hii,
EFI_STRING config, EFI_STRING *progress ) {
struct efi_snp_device *snpdev =
container_of ( hii, struct efi_snp_device, hii );
DBGC ( snpdev, "SNPDEV %p RouteConfig\n", snpdev );
*progress = config;
return EFI_INVALID_PARAMETER;
}
/**
* Handle form actions
*
* @v hii HII configuration access protocol
* @v action Form browser action
* @v question_id Question ID
* @v type Type of value
* @v value Value
* @ret action_request Action requested by driver
* @ret efirc EFI status code
*/
static EFI_STATUS EFIAPI
efi_snp_hii_callback ( const EFI_HII_CONFIG_ACCESS_PROTOCOL *hii,
EFI_BROWSER_ACTION action __unused,
EFI_QUESTION_ID question_id __unused,
UINT8 type __unused, EFI_IFR_TYPE_VALUE *value __unused,
EFI_BROWSER_ACTION_REQUEST *action_request __unused ) {
struct efi_snp_device *snpdev =
container_of ( hii, struct efi_snp_device, hii );
DBGC ( snpdev, "SNPDEV %p Callback\n", snpdev );
return EFI_UNSUPPORTED;
}
/** HII configuration access protocol */
static EFI_HII_CONFIG_ACCESS_PROTOCOL efi_snp_device_hii = {
.ExtractConfig = efi_snp_hii_extract_config,
.RouteConfig = efi_snp_hii_route_config,
.Callback = efi_snp_hii_callback,
};
/******************************************************************************
*
* iPXE network driver
*
******************************************************************************
*/
/**
* Locate SNP device corresponding to network device
*
* @v netdev Network device
* @ret snp SNP device, or NULL if not found
*/
static struct efi_snp_device * efi_snp_demux ( struct net_device *netdev ) {
struct efi_snp_device *snpdev;
list_for_each_entry ( snpdev, &efi_snp_devices, list ) {
if ( snpdev->netdev == netdev )
return snpdev;
}
return NULL;
}
/**
* Create SNP device
*
* @v netdev Network device
* @ret rc Return status code
*/
static int efi_snp_probe ( struct net_device *netdev ) {
EFI_BOOT_SERVICES *bs = efi_systab->BootServices;
struct efi_pci_device *efipci;
struct efi_snp_device *snpdev;
EFI_DEVICE_PATH_PROTOCOL *path_end;
MAC_ADDR_DEVICE_PATH *macpath;
size_t path_prefix_len = 0;
EFI_STATUS efirc;
int rc;
/* Find EFI PCI device */
efipci = efipci_find ( netdev->dev );
if ( ! efipci ) {
DBG ( "SNP skipping non-PCI device %s\n", netdev->name );
rc = 0;
goto err_no_pci;
}
/* Calculate device path prefix length */
path_end = efi_devpath_end ( efipci->path );
path_prefix_len = ( ( ( void * ) path_end ) -
( ( void * ) efipci->path ) );
/* Allocate the SNP device */
snpdev = zalloc ( sizeof ( *snpdev ) + path_prefix_len +
sizeof ( *macpath ) );
if ( ! snpdev ) {
rc = -ENOMEM;
goto err_alloc_snp;
}
snpdev->netdev = netdev_get ( netdev );
snpdev->efipci = efipci;
/* Sanity check */
if ( netdev->ll_protocol->ll_addr_len > sizeof ( EFI_MAC_ADDRESS ) ) {
DBGC ( snpdev, "SNPDEV %p cannot support link-layer address "
"length %d for %s\n", snpdev,
netdev->ll_protocol->ll_addr_len, netdev->name );
rc = -ENOTSUP;
goto err_ll_addr_len;
}
/* Populate the SNP structure */
memcpy ( &snpdev->snp, &efi_snp_device_snp, sizeof ( snpdev->snp ) );
snpdev->snp.Mode = &snpdev->mode;
if ( ( efirc = bs->CreateEvent ( EVT_NOTIFY_WAIT, TPL_NOTIFY,
efi_snp_wait_for_packet, snpdev,
&snpdev->snp.WaitForPacket ) ) != 0 ){
DBGC ( snpdev, "SNPDEV %p could not create event: %s\n",
snpdev, efi_strerror ( efirc ) );
rc = EFIRC_TO_RC ( efirc );
goto err_create_event;
}
/* Populate the SNP mode structure */
snpdev->mode.State = EfiSimpleNetworkStopped;
efi_snp_set_mode ( snpdev );
/* Populate the NII structure */
snpdev->nii.Revision =
EFI_NETWORK_INTERFACE_IDENTIFIER_PROTOCOL_REVISION;
strncpy ( snpdev->nii.StringId, "iPXE",
sizeof ( snpdev->nii.StringId ) );
/* Populate the HII configuration access structure */
memcpy ( &snpdev->hii, &efi_snp_device_hii, sizeof ( snpdev->hii ) );
/* Populate the device name */
efi_snprintf ( snpdev->name, ( sizeof ( snpdev->name ) /
sizeof ( snpdev->name[0] ) ),
"%s", netdev->name );
/* Populate the device path */
memcpy ( &snpdev->path, efipci->path, path_prefix_len );
macpath = ( ( ( void * ) &snpdev->path ) + path_prefix_len );
path_end = ( ( void * ) ( macpath + 1 ) );
memset ( macpath, 0, sizeof ( *macpath ) );
macpath->Header.Type = MESSAGING_DEVICE_PATH;
macpath->Header.SubType = MSG_MAC_ADDR_DP;
macpath->Header.Length[0] = sizeof ( *macpath );
memcpy ( &macpath->MacAddress, netdev->ll_addr,
sizeof ( macpath->MacAddress ) );
macpath->IfType = ntohs ( netdev->ll_protocol->ll_proto );
memset ( path_end, 0, sizeof ( *path_end ) );
path_end->Type = END_DEVICE_PATH_TYPE;
path_end->SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;
path_end->Length[0] = sizeof ( *path_end );
/* Install the SNP */
if ( ( efirc = bs->InstallMultipleProtocolInterfaces (
&snpdev->handle,
&efi_simple_network_protocol_guid, &snpdev->snp,
&efi_device_path_protocol_guid, &snpdev->path,
&efi_nii_protocol_guid, &snpdev->nii,
&efi_nii31_protocol_guid, &snpdev->nii,
&efi_hii_config_access_protocol_guid, &snpdev->hii,
NULL ) ) != 0 ) {
DBGC ( snpdev, "SNPDEV %p could not install protocols: "
"%s\n", snpdev, efi_strerror ( efirc ) );
rc = EFIRC_TO_RC ( efirc );
goto err_install_protocol_interface;
}
/* Add as child of PCI device */
if ( ( efirc = efipci_child_add ( efipci, snpdev->handle ) ) != 0 ) {
DBGC ( snpdev, "SNPDEV %p could not become child of " PCI_FMT
": %s\n", snpdev, PCI_ARGS ( &efipci->pci ),
efi_strerror ( efirc ) );
rc = EFIRC_TO_RC ( efirc );
goto err_efipci_child_add;
}
/* Create HII package list */
snpdev->package_list = efi_snp_package_list ( snpdev );
if ( ! snpdev->package_list ) {
DBGC ( snpdev, "SNPDEV %p could not create HII package list\n",
snpdev );
rc = -ENOMEM;
goto err_create_hii;
}
/* Add HII packages */
if ( ( efirc = efihii->NewPackageList ( efihii, snpdev->package_list,
snpdev->handle,
&snpdev->hii_handle ) ) != 0 ) {
DBGC ( snpdev, "SNPDEV %p could not add HII packages: %s\n",
snpdev, efi_strerror ( efirc ) );
rc = EFIRC_TO_RC ( efirc );
goto err_register_hii;
}
/* Add to list of SNP devices */
list_add ( &snpdev->list, &efi_snp_devices );
DBGC ( snpdev, "SNPDEV %p installed for %s as device %p\n",
snpdev, netdev->name, snpdev->handle );
return 0;
efihii->RemovePackageList ( efihii, snpdev->hii_handle );
err_register_hii:
free ( snpdev->package_list );
err_create_hii:
efipci_child_del ( efipci, snpdev->handle );
err_efipci_child_add:
bs->UninstallMultipleProtocolInterfaces (
snpdev->handle,
&efi_simple_network_protocol_guid, &snpdev->snp,
&efi_device_path_protocol_guid, &snpdev->path,
&efi_nii_protocol_guid, &snpdev->nii,
&efi_nii31_protocol_guid, &snpdev->nii,
&efi_hii_config_access_protocol_guid, &snpdev->hii,
NULL );
err_install_protocol_interface:
bs->CloseEvent ( snpdev->snp.WaitForPacket );
err_create_event:
err_ll_addr_len:
netdev_put ( netdev );
free ( snpdev );
err_alloc_snp:
err_no_pci:
return rc;
}
/**
* Handle SNP device or link state change
*
* @v netdev Network device
*/
static void efi_snp_notify ( struct net_device *netdev __unused ) {
/* Nothing to do */
}
/**
* Destroy SNP device
*
* @v netdev Network device
*/
static void efi_snp_remove ( struct net_device *netdev ) {
EFI_BOOT_SERVICES *bs = efi_systab->BootServices;
struct efi_snp_device *snpdev;
/* Locate SNP device */
snpdev = efi_snp_demux ( netdev );
if ( ! snpdev ) {
DBG ( "SNP skipping non-SNP device %s\n", netdev->name );
return;
}
/* Uninstall the SNP */
efihii->RemovePackageList ( efihii, snpdev->hii_handle );
free ( snpdev->package_list );
efipci_child_del ( snpdev->efipci, snpdev->handle );
list_del ( &snpdev->list );
bs->UninstallMultipleProtocolInterfaces (
snpdev->handle,
&efi_simple_network_protocol_guid, &snpdev->snp,
&efi_device_path_protocol_guid, &snpdev->path,
&efi_nii_protocol_guid, &snpdev->nii,
&efi_nii31_protocol_guid, &snpdev->nii,
&efi_hii_config_access_protocol_guid, &snpdev->hii,
NULL );
bs->CloseEvent ( snpdev->snp.WaitForPacket );
netdev_put ( snpdev->netdev );
free ( snpdev );
}
/** SNP driver */
struct net_driver efi_snp_driver __net_driver = {
.name = "SNP",
.probe = efi_snp_probe,
.notify = efi_snp_notify,
.remove = efi_snp_remove,
};
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2015, Peter Thorson. 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 the WebSocket++ Project 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 PETER THORSON 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 <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
#include <websocketpp/extensions/permessage_deflate/enabled.hpp>
#include <iostream>
struct deflate_config : public websocketpp::config::asio_client {
typedef deflate_config type;
typedef asio_client base;
typedef base::concurrency_type concurrency_type;
typedef base::request_type request_type;
typedef base::response_type response_type;
typedef base::message_type message_type;
typedef base::con_msg_manager_type con_msg_manager_type;
typedef base::endpoint_msg_manager_type endpoint_msg_manager_type;
typedef base::alog_type alog_type;
typedef base::elog_type elog_type;
typedef base::rng_type rng_type;
struct transport_config : public base::transport_config {
typedef type::concurrency_type concurrency_type;
typedef type::alog_type alog_type;
typedef type::elog_type elog_type;
typedef type::request_type request_type;
typedef type::response_type response_type;
typedef websocketpp::transport::asio::basic_socket::endpoint
socket_type;
};
typedef websocketpp::transport::asio::endpoint<transport_config>
transport_type;
/// permessage_compress extension
struct permessage_deflate_config {};
typedef websocketpp::extensions::permessage_deflate::enabled
<permessage_deflate_config> permessage_deflate_type;
};
typedef websocketpp::client<deflate_config> client;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
// pull out the type of messages sent by our config
typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
int case_count = 0;
void on_message(client* c, websocketpp::connection_hdl hdl, message_ptr msg) {
client::connection_ptr con = c->get_con_from_hdl(hdl);
if (con->get_resource() == "/getCaseCount") {
std::cout << "Detected " << msg->get_payload() << " test cases."
<< std::endl;
case_count = atoi(msg->get_payload().c_str());
} else {
c->send(hdl, msg->get_payload(), msg->get_opcode());
}
}
int main(int argc, char* argv[]) {
// Create a server endpoint
client c;
std::string uri = "ws://localhost:9001";
if (argc == 2) {
uri = argv[1];
}
try {
// We expect there to be a lot of errors, so suppress them
c.clear_access_channels(websocketpp::log::alevel::all);
c.clear_error_channels(websocketpp::log::elevel::all);
// Initialize ASIO
c.init_asio();
// Register our handlers
c.set_message_handler(bind(&on_message,&c,::_1,::_2));
websocketpp::lib::error_code ec;
client::connection_ptr con = c.get_connection(uri+"/getCaseCount", ec);
c.connect(con);
// Start the ASIO io_service run loop
c.run();
std::cout << "case count: " << case_count << std::endl;
for (int i = 1; i <= case_count; i++) {
c.reset();
std::stringstream url;
url << uri << "/runCase?case=" << i << "&agent="
<< websocketpp::user_agent;
con = c.get_connection(url.str(), ec);
c.connect(con);
c.run();
}
std::cout << "done" << std::endl;
} catch (websocketpp::exception const & e) {
std::cout << e.what() << std::endl;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2010-2015 Samy Al Bahra.
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
#ifndef CK_HP_STACK_H
#define CK_HP_STACK_H
#include <ck_cc.h>
#include <ck_hp.h>
#include <ck_pr.h>
#include <ck_stack.h>
#include <ck_stddef.h>
#define CK_HP_STACK_SLOTS_COUNT 1
#define CK_HP_STACK_SLOTS_SIZE sizeof(void *)
CK_CC_INLINE static void
ck_hp_stack_push_mpmc(struct ck_stack *target, struct ck_stack_entry *entry)
{
ck_stack_push_upmc(target, entry);
return;
}
CK_CC_INLINE static bool
ck_hp_stack_trypush_mpmc(struct ck_stack *target, struct ck_stack_entry *entry)
{
return ck_stack_trypush_upmc(target, entry);
}
CK_CC_INLINE static struct ck_stack_entry *
ck_hp_stack_pop_mpmc(ck_hp_record_t *record, struct ck_stack *target)
{
struct ck_stack_entry *entry, *update;
do {
entry = ck_pr_load_ptr(&target->head);
if (entry == NULL)
return NULL;
ck_hp_set_fence(record, 0, entry);
} while (entry != ck_pr_load_ptr(&target->head));
while (ck_pr_cas_ptr_value(&target->head, entry, entry->next, &entry) == false) {
if (entry == NULL)
return NULL;
ck_hp_set_fence(record, 0, entry);
update = ck_pr_load_ptr(&target->head);
while (entry != update) {
ck_hp_set_fence(record, 0, update);
entry = update;
update = ck_pr_load_ptr(&target->head);
if (update == NULL)
return NULL;
}
}
return entry;
}
CK_CC_INLINE static bool
ck_hp_stack_trypop_mpmc(ck_hp_record_t *record, struct ck_stack *target, struct ck_stack_entry **r)
{
struct ck_stack_entry *entry;
entry = ck_pr_load_ptr(&target->head);
if (entry == NULL)
return false;
ck_hp_set_fence(record, 0, entry);
if (entry != ck_pr_load_ptr(&target->head))
goto leave;
if (ck_pr_cas_ptr_value(&target->head, entry, entry->next, &entry) == false)
goto leave;
*r = entry;
return true;
leave:
ck_hp_set(record, 0, NULL);
return false;
}
#endif /* CK_HP_STACK_H */
| {
"pile_set_name": "Github"
} |
const char* ExtensionToString(Extension extension) {
switch (extension) {
case Extension::kSPV_AMD_gcn_shader:
return "SPV_AMD_gcn_shader";
case Extension::kSPV_AMD_gpu_shader_half_float:
return "SPV_AMD_gpu_shader_half_float";
case Extension::kSPV_AMD_gpu_shader_half_float_fetch:
return "SPV_AMD_gpu_shader_half_float_fetch";
case Extension::kSPV_AMD_gpu_shader_int16:
return "SPV_AMD_gpu_shader_int16";
case Extension::kSPV_AMD_shader_ballot:
return "SPV_AMD_shader_ballot";
case Extension::kSPV_AMD_shader_explicit_vertex_parameter:
return "SPV_AMD_shader_explicit_vertex_parameter";
case Extension::kSPV_AMD_shader_fragment_mask:
return "SPV_AMD_shader_fragment_mask";
case Extension::kSPV_AMD_shader_image_load_store_lod:
return "SPV_AMD_shader_image_load_store_lod";
case Extension::kSPV_AMD_shader_trinary_minmax:
return "SPV_AMD_shader_trinary_minmax";
case Extension::kSPV_AMD_texture_gather_bias_lod:
return "SPV_AMD_texture_gather_bias_lod";
case Extension::kSPV_EXT_demote_to_helper_invocation:
return "SPV_EXT_demote_to_helper_invocation";
case Extension::kSPV_EXT_descriptor_indexing:
return "SPV_EXT_descriptor_indexing";
case Extension::kSPV_EXT_fragment_fully_covered:
return "SPV_EXT_fragment_fully_covered";
case Extension::kSPV_EXT_fragment_invocation_density:
return "SPV_EXT_fragment_invocation_density";
case Extension::kSPV_EXT_fragment_shader_interlock:
return "SPV_EXT_fragment_shader_interlock";
case Extension::kSPV_EXT_physical_storage_buffer:
return "SPV_EXT_physical_storage_buffer";
case Extension::kSPV_EXT_shader_stencil_export:
return "SPV_EXT_shader_stencil_export";
case Extension::kSPV_EXT_shader_viewport_index_layer:
return "SPV_EXT_shader_viewport_index_layer";
case Extension::kSPV_GOOGLE_decorate_string:
return "SPV_GOOGLE_decorate_string";
case Extension::kSPV_GOOGLE_hlsl_functionality1:
return "SPV_GOOGLE_hlsl_functionality1";
case Extension::kSPV_GOOGLE_user_type:
return "SPV_GOOGLE_user_type";
case Extension::kSPV_INTEL_device_side_avc_motion_estimation:
return "SPV_INTEL_device_side_avc_motion_estimation";
case Extension::kSPV_INTEL_media_block_io:
return "SPV_INTEL_media_block_io";
case Extension::kSPV_INTEL_shader_integer_functions2:
return "SPV_INTEL_shader_integer_functions2";
case Extension::kSPV_INTEL_subgroups:
return "SPV_INTEL_subgroups";
case Extension::kSPV_KHR_16bit_storage:
return "SPV_KHR_16bit_storage";
case Extension::kSPV_KHR_8bit_storage:
return "SPV_KHR_8bit_storage";
case Extension::kSPV_KHR_device_group:
return "SPV_KHR_device_group";
case Extension::kSPV_KHR_float_controls:
return "SPV_KHR_float_controls";
case Extension::kSPV_KHR_multiview:
return "SPV_KHR_multiview";
case Extension::kSPV_KHR_no_integer_wrap_decoration:
return "SPV_KHR_no_integer_wrap_decoration";
case Extension::kSPV_KHR_non_semantic_info:
return "SPV_KHR_non_semantic_info";
case Extension::kSPV_KHR_physical_storage_buffer:
return "SPV_KHR_physical_storage_buffer";
case Extension::kSPV_KHR_post_depth_coverage:
return "SPV_KHR_post_depth_coverage";
case Extension::kSPV_KHR_shader_atomic_counter_ops:
return "SPV_KHR_shader_atomic_counter_ops";
case Extension::kSPV_KHR_shader_ballot:
return "SPV_KHR_shader_ballot";
case Extension::kSPV_KHR_shader_clock:
return "SPV_KHR_shader_clock";
case Extension::kSPV_KHR_shader_draw_parameters:
return "SPV_KHR_shader_draw_parameters";
case Extension::kSPV_KHR_storage_buffer_storage_class:
return "SPV_KHR_storage_buffer_storage_class";
case Extension::kSPV_KHR_subgroup_vote:
return "SPV_KHR_subgroup_vote";
case Extension::kSPV_KHR_variable_pointers:
return "SPV_KHR_variable_pointers";
case Extension::kSPV_KHR_vulkan_memory_model:
return "SPV_KHR_vulkan_memory_model";
case Extension::kSPV_NVX_multiview_per_view_attributes:
return "SPV_NVX_multiview_per_view_attributes";
case Extension::kSPV_NV_compute_shader_derivatives:
return "SPV_NV_compute_shader_derivatives";
case Extension::kSPV_NV_cooperative_matrix:
return "SPV_NV_cooperative_matrix";
case Extension::kSPV_NV_fragment_shader_barycentric:
return "SPV_NV_fragment_shader_barycentric";
case Extension::kSPV_NV_geometry_shader_passthrough:
return "SPV_NV_geometry_shader_passthrough";
case Extension::kSPV_NV_mesh_shader:
return "SPV_NV_mesh_shader";
case Extension::kSPV_NV_ray_tracing:
return "SPV_NV_ray_tracing";
case Extension::kSPV_NV_sample_mask_override_coverage:
return "SPV_NV_sample_mask_override_coverage";
case Extension::kSPV_NV_shader_image_footprint:
return "SPV_NV_shader_image_footprint";
case Extension::kSPV_NV_shader_sm_builtins:
return "SPV_NV_shader_sm_builtins";
case Extension::kSPV_NV_shader_subgroup_partitioned:
return "SPV_NV_shader_subgroup_partitioned";
case Extension::kSPV_NV_shading_rate:
return "SPV_NV_shading_rate";
case Extension::kSPV_NV_stereo_view_rendering:
return "SPV_NV_stereo_view_rendering";
case Extension::kSPV_NV_viewport_array2:
return "SPV_NV_viewport_array2";
case Extension::kSPV_VALIDATOR_ignore_type_decl_unique:
return "SPV_VALIDATOR_ignore_type_decl_unique";
};
return "";
}
bool GetExtensionFromString(const char* str, Extension* extension) {
static const char* known_ext_strs[] = { "SPV_AMD_gcn_shader", "SPV_AMD_gpu_shader_half_float", "SPV_AMD_gpu_shader_half_float_fetch", "SPV_AMD_gpu_shader_int16", "SPV_AMD_shader_ballot", "SPV_AMD_shader_explicit_vertex_parameter", "SPV_AMD_shader_fragment_mask", "SPV_AMD_shader_image_load_store_lod", "SPV_AMD_shader_trinary_minmax", "SPV_AMD_texture_gather_bias_lod", "SPV_EXT_demote_to_helper_invocation", "SPV_EXT_descriptor_indexing", "SPV_EXT_fragment_fully_covered", "SPV_EXT_fragment_invocation_density", "SPV_EXT_fragment_shader_interlock", "SPV_EXT_physical_storage_buffer", "SPV_EXT_shader_stencil_export", "SPV_EXT_shader_viewport_index_layer", "SPV_GOOGLE_decorate_string", "SPV_GOOGLE_hlsl_functionality1", "SPV_GOOGLE_user_type", "SPV_INTEL_device_side_avc_motion_estimation", "SPV_INTEL_media_block_io", "SPV_INTEL_shader_integer_functions2", "SPV_INTEL_subgroups", "SPV_KHR_16bit_storage", "SPV_KHR_8bit_storage", "SPV_KHR_device_group", "SPV_KHR_float_controls", "SPV_KHR_multiview", "SPV_KHR_no_integer_wrap_decoration", "SPV_KHR_non_semantic_info", "SPV_KHR_physical_storage_buffer", "SPV_KHR_post_depth_coverage", "SPV_KHR_shader_atomic_counter_ops", "SPV_KHR_shader_ballot", "SPV_KHR_shader_clock", "SPV_KHR_shader_draw_parameters", "SPV_KHR_storage_buffer_storage_class", "SPV_KHR_subgroup_vote", "SPV_KHR_variable_pointers", "SPV_KHR_vulkan_memory_model", "SPV_NVX_multiview_per_view_attributes", "SPV_NV_compute_shader_derivatives", "SPV_NV_cooperative_matrix", "SPV_NV_fragment_shader_barycentric", "SPV_NV_geometry_shader_passthrough", "SPV_NV_mesh_shader", "SPV_NV_ray_tracing", "SPV_NV_sample_mask_override_coverage", "SPV_NV_shader_image_footprint", "SPV_NV_shader_sm_builtins", "SPV_NV_shader_subgroup_partitioned", "SPV_NV_shading_rate", "SPV_NV_stereo_view_rendering", "SPV_NV_viewport_array2", "SPV_VALIDATOR_ignore_type_decl_unique" };
static const Extension known_ext_ids[] = { Extension::kSPV_AMD_gcn_shader, Extension::kSPV_AMD_gpu_shader_half_float, Extension::kSPV_AMD_gpu_shader_half_float_fetch, Extension::kSPV_AMD_gpu_shader_int16, Extension::kSPV_AMD_shader_ballot, Extension::kSPV_AMD_shader_explicit_vertex_parameter, Extension::kSPV_AMD_shader_fragment_mask, Extension::kSPV_AMD_shader_image_load_store_lod, Extension::kSPV_AMD_shader_trinary_minmax, Extension::kSPV_AMD_texture_gather_bias_lod, Extension::kSPV_EXT_demote_to_helper_invocation, Extension::kSPV_EXT_descriptor_indexing, Extension::kSPV_EXT_fragment_fully_covered, Extension::kSPV_EXT_fragment_invocation_density, Extension::kSPV_EXT_fragment_shader_interlock, Extension::kSPV_EXT_physical_storage_buffer, Extension::kSPV_EXT_shader_stencil_export, Extension::kSPV_EXT_shader_viewport_index_layer, Extension::kSPV_GOOGLE_decorate_string, Extension::kSPV_GOOGLE_hlsl_functionality1, Extension::kSPV_GOOGLE_user_type, Extension::kSPV_INTEL_device_side_avc_motion_estimation, Extension::kSPV_INTEL_media_block_io, Extension::kSPV_INTEL_shader_integer_functions2, Extension::kSPV_INTEL_subgroups, Extension::kSPV_KHR_16bit_storage, Extension::kSPV_KHR_8bit_storage, Extension::kSPV_KHR_device_group, Extension::kSPV_KHR_float_controls, Extension::kSPV_KHR_multiview, Extension::kSPV_KHR_no_integer_wrap_decoration, Extension::kSPV_KHR_non_semantic_info, Extension::kSPV_KHR_physical_storage_buffer, Extension::kSPV_KHR_post_depth_coverage, Extension::kSPV_KHR_shader_atomic_counter_ops, Extension::kSPV_KHR_shader_ballot, Extension::kSPV_KHR_shader_clock, Extension::kSPV_KHR_shader_draw_parameters, Extension::kSPV_KHR_storage_buffer_storage_class, Extension::kSPV_KHR_subgroup_vote, Extension::kSPV_KHR_variable_pointers, Extension::kSPV_KHR_vulkan_memory_model, Extension::kSPV_NVX_multiview_per_view_attributes, Extension::kSPV_NV_compute_shader_derivatives, Extension::kSPV_NV_cooperative_matrix, Extension::kSPV_NV_fragment_shader_barycentric, Extension::kSPV_NV_geometry_shader_passthrough, Extension::kSPV_NV_mesh_shader, Extension::kSPV_NV_ray_tracing, Extension::kSPV_NV_sample_mask_override_coverage, Extension::kSPV_NV_shader_image_footprint, Extension::kSPV_NV_shader_sm_builtins, Extension::kSPV_NV_shader_subgroup_partitioned, Extension::kSPV_NV_shading_rate, Extension::kSPV_NV_stereo_view_rendering, Extension::kSPV_NV_viewport_array2, Extension::kSPV_VALIDATOR_ignore_type_decl_unique };
const auto b = std::begin(known_ext_strs);
const auto e = std::end(known_ext_strs);
const auto found = std::equal_range(
b, e, str, [](const char* str1, const char* str2) {
return std::strcmp(str1, str2) < 0;
});
if (found.first == e || found.first == found.second) return false;
*extension = known_ext_ids[found.first - b];
return true;
}
const char* CapabilityToString(SpvCapability capability) {
switch (capability) {
case SpvCapabilityMatrix:
return "Matrix";
case SpvCapabilityShader:
return "Shader";
case SpvCapabilityGeometry:
return "Geometry";
case SpvCapabilityTessellation:
return "Tessellation";
case SpvCapabilityAddresses:
return "Addresses";
case SpvCapabilityLinkage:
return "Linkage";
case SpvCapabilityKernel:
return "Kernel";
case SpvCapabilityVector16:
return "Vector16";
case SpvCapabilityFloat16Buffer:
return "Float16Buffer";
case SpvCapabilityFloat16:
return "Float16";
case SpvCapabilityFloat64:
return "Float64";
case SpvCapabilityInt64:
return "Int64";
case SpvCapabilityInt64Atomics:
return "Int64Atomics";
case SpvCapabilityImageBasic:
return "ImageBasic";
case SpvCapabilityImageReadWrite:
return "ImageReadWrite";
case SpvCapabilityImageMipmap:
return "ImageMipmap";
case SpvCapabilityPipes:
return "Pipes";
case SpvCapabilityGroups:
return "Groups";
case SpvCapabilityDeviceEnqueue:
return "DeviceEnqueue";
case SpvCapabilityLiteralSampler:
return "LiteralSampler";
case SpvCapabilityAtomicStorage:
return "AtomicStorage";
case SpvCapabilityInt16:
return "Int16";
case SpvCapabilityTessellationPointSize:
return "TessellationPointSize";
case SpvCapabilityGeometryPointSize:
return "GeometryPointSize";
case SpvCapabilityImageGatherExtended:
return "ImageGatherExtended";
case SpvCapabilityStorageImageMultisample:
return "StorageImageMultisample";
case SpvCapabilityUniformBufferArrayDynamicIndexing:
return "UniformBufferArrayDynamicIndexing";
case SpvCapabilitySampledImageArrayDynamicIndexing:
return "SampledImageArrayDynamicIndexing";
case SpvCapabilityStorageBufferArrayDynamicIndexing:
return "StorageBufferArrayDynamicIndexing";
case SpvCapabilityStorageImageArrayDynamicIndexing:
return "StorageImageArrayDynamicIndexing";
case SpvCapabilityClipDistance:
return "ClipDistance";
case SpvCapabilityCullDistance:
return "CullDistance";
case SpvCapabilityImageCubeArray:
return "ImageCubeArray";
case SpvCapabilitySampleRateShading:
return "SampleRateShading";
case SpvCapabilityImageRect:
return "ImageRect";
case SpvCapabilitySampledRect:
return "SampledRect";
case SpvCapabilityGenericPointer:
return "GenericPointer";
case SpvCapabilityInt8:
return "Int8";
case SpvCapabilityInputAttachment:
return "InputAttachment";
case SpvCapabilitySparseResidency:
return "SparseResidency";
case SpvCapabilityMinLod:
return "MinLod";
case SpvCapabilitySampled1D:
return "Sampled1D";
case SpvCapabilityImage1D:
return "Image1D";
case SpvCapabilitySampledCubeArray:
return "SampledCubeArray";
case SpvCapabilitySampledBuffer:
return "SampledBuffer";
case SpvCapabilityImageBuffer:
return "ImageBuffer";
case SpvCapabilityImageMSArray:
return "ImageMSArray";
case SpvCapabilityStorageImageExtendedFormats:
return "StorageImageExtendedFormats";
case SpvCapabilityImageQuery:
return "ImageQuery";
case SpvCapabilityDerivativeControl:
return "DerivativeControl";
case SpvCapabilityInterpolationFunction:
return "InterpolationFunction";
case SpvCapabilityTransformFeedback:
return "TransformFeedback";
case SpvCapabilityGeometryStreams:
return "GeometryStreams";
case SpvCapabilityStorageImageReadWithoutFormat:
return "StorageImageReadWithoutFormat";
case SpvCapabilityStorageImageWriteWithoutFormat:
return "StorageImageWriteWithoutFormat";
case SpvCapabilityMultiViewport:
return "MultiViewport";
case SpvCapabilitySubgroupDispatch:
return "SubgroupDispatch";
case SpvCapabilityNamedBarrier:
return "NamedBarrier";
case SpvCapabilityPipeStorage:
return "PipeStorage";
case SpvCapabilityGroupNonUniform:
return "GroupNonUniform";
case SpvCapabilityGroupNonUniformVote:
return "GroupNonUniformVote";
case SpvCapabilityGroupNonUniformArithmetic:
return "GroupNonUniformArithmetic";
case SpvCapabilityGroupNonUniformBallot:
return "GroupNonUniformBallot";
case SpvCapabilityGroupNonUniformShuffle:
return "GroupNonUniformShuffle";
case SpvCapabilityGroupNonUniformShuffleRelative:
return "GroupNonUniformShuffleRelative";
case SpvCapabilityGroupNonUniformClustered:
return "GroupNonUniformClustered";
case SpvCapabilityGroupNonUniformQuad:
return "GroupNonUniformQuad";
case SpvCapabilityShaderLayer:
return "ShaderLayer";
case SpvCapabilityShaderViewportIndex:
return "ShaderViewportIndex";
case SpvCapabilitySubgroupBallotKHR:
return "SubgroupBallotKHR";
case SpvCapabilityDrawParameters:
return "DrawParameters";
case SpvCapabilitySubgroupVoteKHR:
return "SubgroupVoteKHR";
case SpvCapabilityStorageBuffer16BitAccess:
return "StorageBuffer16BitAccess";
case SpvCapabilityUniformAndStorageBuffer16BitAccess:
return "UniformAndStorageBuffer16BitAccess";
case SpvCapabilityStoragePushConstant16:
return "StoragePushConstant16";
case SpvCapabilityStorageInputOutput16:
return "StorageInputOutput16";
case SpvCapabilityDeviceGroup:
return "DeviceGroup";
case SpvCapabilityMultiView:
return "MultiView";
case SpvCapabilityVariablePointersStorageBuffer:
return "VariablePointersStorageBuffer";
case SpvCapabilityVariablePointers:
return "VariablePointers";
case SpvCapabilityAtomicStorageOps:
return "AtomicStorageOps";
case SpvCapabilitySampleMaskPostDepthCoverage:
return "SampleMaskPostDepthCoverage";
case SpvCapabilityStorageBuffer8BitAccess:
return "StorageBuffer8BitAccess";
case SpvCapabilityUniformAndStorageBuffer8BitAccess:
return "UniformAndStorageBuffer8BitAccess";
case SpvCapabilityStoragePushConstant8:
return "StoragePushConstant8";
case SpvCapabilityDenormPreserve:
return "DenormPreserve";
case SpvCapabilityDenormFlushToZero:
return "DenormFlushToZero";
case SpvCapabilitySignedZeroInfNanPreserve:
return "SignedZeroInfNanPreserve";
case SpvCapabilityRoundingModeRTE:
return "RoundingModeRTE";
case SpvCapabilityRoundingModeRTZ:
return "RoundingModeRTZ";
case SpvCapabilityFloat16ImageAMD:
return "Float16ImageAMD";
case SpvCapabilityImageGatherBiasLodAMD:
return "ImageGatherBiasLodAMD";
case SpvCapabilityFragmentMaskAMD:
return "FragmentMaskAMD";
case SpvCapabilityStencilExportEXT:
return "StencilExportEXT";
case SpvCapabilityImageReadWriteLodAMD:
return "ImageReadWriteLodAMD";
case SpvCapabilityShaderClockKHR:
return "ShaderClockKHR";
case SpvCapabilitySampleMaskOverrideCoverageNV:
return "SampleMaskOverrideCoverageNV";
case SpvCapabilityGeometryShaderPassthroughNV:
return "GeometryShaderPassthroughNV";
case SpvCapabilityShaderViewportIndexLayerEXT:
return "ShaderViewportIndexLayerEXT";
case SpvCapabilityShaderViewportMaskNV:
return "ShaderViewportMaskNV";
case SpvCapabilityShaderStereoViewNV:
return "ShaderStereoViewNV";
case SpvCapabilityPerViewAttributesNV:
return "PerViewAttributesNV";
case SpvCapabilityFragmentFullyCoveredEXT:
return "FragmentFullyCoveredEXT";
case SpvCapabilityMeshShadingNV:
return "MeshShadingNV";
case SpvCapabilityImageFootprintNV:
return "ImageFootprintNV";
case SpvCapabilityFragmentBarycentricNV:
return "FragmentBarycentricNV";
case SpvCapabilityComputeDerivativeGroupQuadsNV:
return "ComputeDerivativeGroupQuadsNV";
case SpvCapabilityFragmentDensityEXT:
return "FragmentDensityEXT";
case SpvCapabilityGroupNonUniformPartitionedNV:
return "GroupNonUniformPartitionedNV";
case SpvCapabilityShaderNonUniform:
return "ShaderNonUniform";
case SpvCapabilityRuntimeDescriptorArray:
return "RuntimeDescriptorArray";
case SpvCapabilityInputAttachmentArrayDynamicIndexing:
return "InputAttachmentArrayDynamicIndexing";
case SpvCapabilityUniformTexelBufferArrayDynamicIndexing:
return "UniformTexelBufferArrayDynamicIndexing";
case SpvCapabilityStorageTexelBufferArrayDynamicIndexing:
return "StorageTexelBufferArrayDynamicIndexing";
case SpvCapabilityUniformBufferArrayNonUniformIndexing:
return "UniformBufferArrayNonUniformIndexing";
case SpvCapabilitySampledImageArrayNonUniformIndexing:
return "SampledImageArrayNonUniformIndexing";
case SpvCapabilityStorageBufferArrayNonUniformIndexing:
return "StorageBufferArrayNonUniformIndexing";
case SpvCapabilityStorageImageArrayNonUniformIndexing:
return "StorageImageArrayNonUniformIndexing";
case SpvCapabilityInputAttachmentArrayNonUniformIndexing:
return "InputAttachmentArrayNonUniformIndexing";
case SpvCapabilityUniformTexelBufferArrayNonUniformIndexing:
return "UniformTexelBufferArrayNonUniformIndexing";
case SpvCapabilityStorageTexelBufferArrayNonUniformIndexing:
return "StorageTexelBufferArrayNonUniformIndexing";
case SpvCapabilityRayTracingNV:
return "RayTracingNV";
case SpvCapabilityVulkanMemoryModel:
return "VulkanMemoryModel";
case SpvCapabilityVulkanMemoryModelDeviceScope:
return "VulkanMemoryModelDeviceScope";
case SpvCapabilityPhysicalStorageBufferAddresses:
return "PhysicalStorageBufferAddresses";
case SpvCapabilityComputeDerivativeGroupLinearNV:
return "ComputeDerivativeGroupLinearNV";
case SpvCapabilityCooperativeMatrixNV:
return "CooperativeMatrixNV";
case SpvCapabilityFragmentShaderSampleInterlockEXT:
return "FragmentShaderSampleInterlockEXT";
case SpvCapabilityFragmentShaderShadingRateInterlockEXT:
return "FragmentShaderShadingRateInterlockEXT";
case SpvCapabilityShaderSMBuiltinsNV:
return "ShaderSMBuiltinsNV";
case SpvCapabilityFragmentShaderPixelInterlockEXT:
return "FragmentShaderPixelInterlockEXT";
case SpvCapabilityDemoteToHelperInvocationEXT:
return "DemoteToHelperInvocationEXT";
case SpvCapabilitySubgroupShuffleINTEL:
return "SubgroupShuffleINTEL";
case SpvCapabilitySubgroupBufferBlockIOINTEL:
return "SubgroupBufferBlockIOINTEL";
case SpvCapabilitySubgroupImageBlockIOINTEL:
return "SubgroupImageBlockIOINTEL";
case SpvCapabilitySubgroupImageMediaBlockIOINTEL:
return "SubgroupImageMediaBlockIOINTEL";
case SpvCapabilityIntegerFunctions2INTEL:
return "IntegerFunctions2INTEL";
case SpvCapabilitySubgroupAvcMotionEstimationINTEL:
return "SubgroupAvcMotionEstimationINTEL";
case SpvCapabilitySubgroupAvcMotionEstimationIntraINTEL:
return "SubgroupAvcMotionEstimationIntraINTEL";
case SpvCapabilitySubgroupAvcMotionEstimationChromaINTEL:
return "SubgroupAvcMotionEstimationChromaINTEL";
case SpvCapabilityMax:
assert(0 && "Attempting to convert SpvCapabilityMax to string");
return "";
};
return "";
} | {
"pile_set_name": "Github"
} |
commandlinefu_id: 6853
translator:
weibo: ''
hide: true
command: |-
nmap -p 22 10.3.1.1/16 | grep -B 4 "open"
summary: |-
Get a list of ssh servers on the local subnet
| {
"pile_set_name": "Github"
} |
using System.IO;
using System.Net;
using System.Security.Principal;
using System.Web;
using NUnit.Framework;
using Umbraco.Web.WebApi.Filters;
namespace Umbraco.Tests.Web.AngularIntegration
{
[TestFixture]
public class AngularAntiForgeryTests
{
[TearDown]
public void TearDown()
{
HttpContext.Current = null;
}
[Test]
public void Can_Validate_Generated_Tokens()
{
using (var writer = new StringWriter())
{
HttpContext.Current = new HttpContext(new HttpRequest("test.html", "http://test/", ""), new HttpResponse(writer));
string cookieToken, headerToken;
AngularAntiForgeryHelper.GetTokens(out cookieToken, out headerToken);
Assert.IsTrue(AngularAntiForgeryHelper.ValidateTokens(cookieToken, headerToken));
}
}
[Test]
public void Can_Validate_Generated_Tokens_With_User()
{
using (var writer = new StringWriter())
{
HttpContext.Current = new HttpContext(new HttpRequest("test.html", "http://test/", ""), new HttpResponse(writer))
{
User = new GenericPrincipal(new HttpListenerBasicIdentity("test", "test"), new string[] {})
};
string cookieToken, headerToken;
AngularAntiForgeryHelper.GetTokens(out cookieToken, out headerToken);
Assert.IsTrue(AngularAntiForgeryHelper.ValidateTokens(cookieToken, headerToken));
}
}
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2017 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.
*/
// This package has the automatically generated typed clients.
package v1alpha1
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2010 Yahoo! Inc. 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. See accompanying LICENSE file.
*/
package org.apache.oozie.command.bundle;
import org.apache.oozie.BundleJobBean;
import org.apache.oozie.client.Job;
import org.apache.oozie.command.CommandException;
import org.apache.oozie.executor.jpa.BundleJobGetJPAExecutor;
import org.apache.oozie.service.JPAService;
import org.apache.oozie.service.Services;
import org.apache.oozie.test.XDataTestCase;
public class TestBundleJobXCommand extends XDataTestCase {
private Services services;
@Override
protected void setUp() throws Exception {
super.setUp();
services = new Services();
services.init();
cleanUpDBTables();
}
@Override
protected void tearDown() throws Exception {
services.destroy();
super.tearDown();
}
/**
* Test: submit bundle job, then check job info
*
* @throws Exception
*/
public void testBundleJobInfo1() throws Exception {
BundleJobBean job = this.addRecordToBundleJobTable(Job.Status.PREP, false);
JPAService jpaService = Services.get().get(JPAService.class);
assertNotNull(jpaService);
BundleJobGetJPAExecutor bundleJobGetjpa = new BundleJobGetJPAExecutor(job.getId());
job = jpaService.execute(bundleJobGetjpa);
assertEquals(job.getStatus(), Job.Status.PREP);
BundleJobBean bundleJob = (new BundleJobXCommand(job.getId())).call();
assertEquals(0, bundleJob.getCoordinators().size());
assertEquals(bundleJob.getStatus(), Job.Status.PREP);
assertEquals(bundleJob.getId(), job.getId());
}
/**
* Test: jobId is wrong
*
* @throws Exception
*/
public void testBundleJobInfoFailed() throws Exception {
this.addRecordToBundleJobTable(Job.Status.PREP, false);
try {
new BundleJobXCommand("bundle-id").call();
fail("Job doesn't exist. Should fail.");
}
catch (CommandException ce) {
// Job doesn't exist. Exception is expected.
}
}
} | {
"pile_set_name": "Github"
} |
import * as React from 'react'
import { StyleContext, TypeContext } from '../Lines';
import { classes, addClass } from '../Globals';
import "./Lines.css"
export interface FormGroupProps {
labelText?: React.ReactChild;
controlId?: string;
ctx: StyleContext;
labelHtmlAttributes?: React.HTMLAttributes<HTMLLabelElement>;
htmlAttributes?: React.HTMLAttributes<HTMLDivElement>;
helpText?: React.ReactChild;
children?: React.ReactNode;
}
export function FormGroup(p: FormGroupProps) {
const ctx = p.ctx;
const tCtx = ctx as TypeContext<any>;
const errorClass = tCtx.errorClass;
const errorAtts = tCtx.errorAttributes && tCtx.errorAttributes();
if (ctx.formGroupStyle == "None") {
const c = p.children as React.ReactElement<any>;
return (
<span {...p.htmlAttributes} className={errorClass} {...errorAtts}>
{c}
</span>
);
}
const labelClasses = classes(
ctx.formGroupStyle == "SrOnly" && "sr-only",
ctx.formGroupStyle == "LabelColumns" && ctx.labelColumnsCss,
ctx.formGroupStyle == "LabelColumns" ? ctx.colFormLabelClass : ctx.labelClass,
);
let pr = tCtx.propertyRoute;
var labelText = p.labelText ?? (pr?.member?.niceName);
const label = (
<label htmlFor={p.controlId} {...p.labelHtmlAttributes} className={addClass(p.labelHtmlAttributes, labelClasses)} >
{labelText}
</label>
);
const formGroupClasses = classes(p.ctx.formGroupClass, p.ctx.formGroupStyle == "LabelColumns" ? "row" : undefined, errorClass);
return (
<div
title={ctx.titleLabels && typeof labelText == "string" ? labelText : undefined}
{...p.htmlAttributes}
className={addClass(p.htmlAttributes, formGroupClasses)}
{...errorAtts}>
{ctx.formGroupStyle != "BasicDown" && label}
{
ctx.formGroupStyle != "LabelColumns" ? p.children :
(
<div className={p.ctx.valueColumnsCss} >
{p.children}
{p.helpText && ctx.formGroupStyle == "LabelColumns" && <small className="form-text text-muted">{p.helpText}</small>}
</div>
)
}
{ctx.formGroupStyle == "BasicDown" && label}
{p.helpText && ctx.formGroupStyle != "LabelColumns" && <small className="form-text text-muted">{p.helpText}</small>}
</div>
);
}
| {
"pile_set_name": "Github"
} |
form=未知
tags=
暮云凝冻,
耸玉楼、拈断冰髯知几。
今岁天公悭破白,
未放六霙呈瑞。
瘗马发祥,
妖麋应祷,
终解从人意。
腊前三白,
瑶光一瞬千里。
便好翦刻漫空,
落花飞絮,
滚滚随风起。
莫待东皇催整驾,
点点消成春水。
巧思裁云,
新词胜雪,
引动眉间喜。
欺梅压竹,
看看还助吟醉。
| {
"pile_set_name": "Github"
} |
import { default as Wallet } from 'ethereumjs-wallet';
const worker: Worker = self as any;
interface DecryptionParameters {
keystore: string;
password: string;
nonStrict: boolean;
}
worker.onmessage = (event: MessageEvent) => {
const info: DecryptionParameters = event.data;
try {
const rawKeystore: Wallet = Wallet.fromV3(info.keystore, info.password, info.nonStrict);
worker.postMessage(rawKeystore.getPrivateKeyString());
} catch (e) {
worker.postMessage(e.message);
}
};
| {
"pile_set_name": "Github"
} |
AsciiDoc User Guide
===================
Stuart Rackham <[email protected]>
:Author Initials: SJR
:toc:
:icons:
:numbered:
:website: http://www.methods.co.nz/asciidoc/
AsciiDoc is a text document format for writing notes, documentation,
articles, books, ebooks, slideshows, web pages, blogs and UNIX man
pages.
.This document
**********************************************************************
This is an overly large document, it probably needs to be refactored
into a Tutorial, Quick Reference and Formal Reference.
If you're new to AsciiDoc read this section and the <<X6,Getting
Started>> section and take a look at the example AsciiDoc (`*.txt`)
source files in the distribution `doc` directory.
**********************************************************************
Introduction
------------
AsciiDoc is a plain text human readable/writable document format that
can be translated to DocBook or HTML using the asciidoc(1) command.
asciidoc(1) comes with a set of configuration files to translate
AsciiDoc articles, books and man pages to HTML or DocBook backend
formats.
.My AsciiDoc Itch
**********************************************************************
DocBook has emerged as the de facto standard Open Source documentation
format. But DocBook is a complex language, the markup is difficult to
read and even more difficult to write directly -- I found I was
and fixing syntax errors, than I was writing the documentation.
**********************************************************************
[[X6]]
Getting Started
---------------
Installing AsciiDoc
~~~~~~~~~~~~~~~~~~~
See the `README` and `INSTALL` files for install prerequisites and
procedures. Packagers take a look at <<X38,Packager Notes>>.
[[X11]]
Example AsciiDoc Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~
The best way to quickly get a feel for AsciiDoc is to view the
AsciiDoc web site and/or distributed examples:
- Take a look at the linked examples on the AsciiDoc web site home
page {website}. Press the 'Page Source' sidebar menu item to view
corresponding AsciiDoc source.
- Read the `*.txt` source files in the distribution `./doc` directory
along with the corresponding HTML and DocBook XML files.
AsciiDoc Document Types
-----------------------
There are three types of AsciiDoc documents: article, book and
manpage.
Use the asciidoc(1) `-d` (`--doctype`) option to specify the AsciiDoc
document type -- the default document type is 'article'.
article
~~~~~~~
Used for short documents, articles and general documentation. See the
AsciiDoc distribution `./doc/article.txt` example.
AsciiDoc defines standard DocBook article frontmatter and backmatter
<<X93,section markup templates>> (appendix, abstract, bibliography,
glossary, index).
book
~~~~
Books share the same format as articles, with the following
differences:
- The part titles in multi-part books are <<X17,top level titles>>
(same level as book title).
- Some sections are book specific e.g. preface and colophon.
Book documents will normally be used to produce DocBook output since
DocBook processors can automatically generate footnotes, table of
contents, list of tables, list of figures, list of examples and
indexes.
AsciiDoc defines standard DocBook book frontmatter and backmatter
<<X93,section markup templates>> (appendix, dedication, preface,
bibliography, glossary, index, colophon).
.Example book documents
Book::
The `./doc/book.txt` file in the AsciiDoc distribution.
Multi-part book::
The `./doc/book-multi.txt` file in the AsciiDoc distribution.
| {
"pile_set_name": "Github"
} |
-- Run-Length Encoding Compression algorithm implementation
-- See: https://en.wikipedia.org/wiki/Run-length_encoding
-- Compresses an input string using RLE algorithm
-- @str : an input string to be compressed
-- returns : the encoded string
function rle_encode(str)
local prev = str:sub(1,1)
local count = 0
local encoded = ''
for char in str:gmatch('.') do
if char == prev then
count = count + 1
else
encoded = encoded .. (count .. prev)
prev = char
count = 1
end
end
return encoded .. (count .. prev)
end
-- Decodes a given input
-- @str : an encoded string
-- returns : the original string
function rle_decode(str)
local decoded_str = ''
for count, match in str:gmatch('(%d+)([^%d]+)') do
decoded_str = decoded_str .. (match:rep(count))
end
return decoded_str
end
return {
encode = rle_encode,
decode = rle_decode,
}
| {
"pile_set_name": "Github"
} |
export interface LinkingCrossPlatform {
addEventListener: (
event: 'url',
handler: (payload: { url: string }) => void,
) => void
removeEventListener: (
event: 'url',
handler: (payload: { url: string }) => void,
) => void
canOpenURL(url: string): Promise<boolean>
clearCurrentURL(): void
getCurrentURL(): string
getInitialURL(): string
openURL(url: string): Promise<void>
}
export const Linking: LinkingCrossPlatform
| {
"pile_set_name": "Github"
} |
require('../../modules/es7.object.entries');
module.exports = require('../../modules/_core').Object.entries;
| {
"pile_set_name": "Github"
} |
// Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <optional>
#include <boost/icl/interval_set.hpp>
#include <boost/serialization/set.hpp>
#include "common/common_types.h"
#include "common/serialization/boost_interval_set.hpp"
namespace Kernel {
struct AddressMapping;
class VMManager;
struct MemoryRegionInfo {
u32 base; // Not an address, but offset from start of FCRAM
u32 size;
u32 used;
// The domain of the interval_set are offsets from start of FCRAM
using IntervalSet = boost::icl::interval_set<u32>;
using Interval = IntervalSet::interval_type;
IntervalSet free_blocks;
/**
* Reset the allocator state
* @param base The base offset the beginning of FCRAM.
* @param size The region size this allocator manages
*/
void Reset(u32 base, u32 size);
/**
* Allocates memory from the heap.
* @param size The size of memory to allocate.
* @returns The set of blocks that make up the allocation request. Empty set if there is no
* enough space.
*/
IntervalSet HeapAllocate(u32 size);
/**
* Allocates memory from the linear heap with specific address and size.
* @param offset the address offset to the beginning of FCRAM.
* @param size size of the memory to allocate.
* @returns true if the allocation is successful. false if the requested region is not free.
*/
bool LinearAllocate(u32 offset, u32 size);
/**
* Allocates memory from the linear heap with only size specified.
* @param size size of the memory to allocate.
* @returns the address offset to the beginning of FCRAM; null if there is no enough space
*/
std::optional<u32> LinearAllocate(u32 size);
/**
* Frees one segment of memory. The memory must have been allocated as heap or linear heap.
* @param offset the region address offset to the beginning of FCRAM.
* @param size the size of the region to free.
*/
void Free(u32 offset, u32 size);
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int file_version) {
ar& base;
ar& size;
ar& used;
ar& free_blocks;
}
};
} // namespace Kernel
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><div> with role alert; inherited supported state or property "aria-expanded" value
of "false"
</title>
</head>
<body>
<div id="test" role="alert" aria-expanded="false">Placeholder content</div>
<div id="obj1">obj1</div>
<div id="obj2">obj2</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
---
- name: copy waybar configuration
tags: waybar
synchronize:
src: waybar
dest: ~/.config/
- name: template styles.css
template:
src: style.j2
dest: ~/.config/waybar/style.css
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 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.
-->
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#ff9cdfd9">
<item>
<shape android:shape="oval">
<solid android:color="#9cc8c4" />
<size android:width="@dimen/recents_lock_to_app_size"
android:height="@dimen/recents_lock_to_app_size" />
</shape>
</item>
</ripple> | {
"pile_set_name": "Github"
} |
#include "apue.h"
#include <ctype.h>
int main() {
int c;
while ((c = getchar()) != EOF) {
if (isupper(c)) {
c = tolower(c);
}
if (putchar(c) == EOF) {
err_sys("output error");
}
if (c == '\n') {
fflush(stdout);
}
}
exit(0);
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{5ADECD4D-5FD3-4D0F-AF9A-DD809EFE2A21}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DeptCtrl_BackEnd_Tesselate</RootNamespace>
<AssemblyName>DeptCtrl_BackEnd_Tesselate</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<LangVersion>8.0</LangVersion>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="..\..\PixelFarm\BackEnd.Tesselate_SH\BackEnd.Tesselate_SH.projitems" Label="Shared" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> | {
"pile_set_name": "Github"
} |
package security
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// IoTSecuritySolutionsAnalyticsRecommendationClient is the API spec for Microsoft.Security (Azure Security Center)
// resource provider
type IoTSecuritySolutionsAnalyticsRecommendationClient struct {
BaseClient
}
// NewIoTSecuritySolutionsAnalyticsRecommendationClient creates an instance of the
// IoTSecuritySolutionsAnalyticsRecommendationClient client.
func NewIoTSecuritySolutionsAnalyticsRecommendationClient(subscriptionID string, ascLocation string) IoTSecuritySolutionsAnalyticsRecommendationClient {
return NewIoTSecuritySolutionsAnalyticsRecommendationClientWithBaseURI(DefaultBaseURI, subscriptionID, ascLocation)
}
// NewIoTSecuritySolutionsAnalyticsRecommendationClientWithBaseURI creates an instance of the
// IoTSecuritySolutionsAnalyticsRecommendationClient client using a custom endpoint. Use this when interacting with an
// Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewIoTSecuritySolutionsAnalyticsRecommendationClientWithBaseURI(baseURI string, subscriptionID string, ascLocation string) IoTSecuritySolutionsAnalyticsRecommendationClient {
return IoTSecuritySolutionsAnalyticsRecommendationClient{NewWithBaseURI(baseURI, subscriptionID, ascLocation)}
}
// Get security Analytics of a security solution
// Parameters:
// resourceGroupName - the name of the resource group within the user's subscription. The name is case
// insensitive.
// solutionName - the solution manager name
// aggregatedRecommendationName - identifier of the aggregated recommendation
func (client IoTSecuritySolutionsAnalyticsRecommendationClient) Get(ctx context.Context, resourceGroupName string, solutionName string, aggregatedRecommendationName string) (result IoTSecurityAggregatedRecommendation, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/IoTSecuritySolutionsAnalyticsRecommendationClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.Pattern, Rule: `^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$`, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("security.IoTSecuritySolutionsAnalyticsRecommendationClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, resourceGroupName, solutionName, aggregatedRecommendationName)
if err != nil {
err = autorest.NewErrorWithError(err, "security.IoTSecuritySolutionsAnalyticsRecommendationClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "security.IoTSecuritySolutionsAnalyticsRecommendationClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "security.IoTSecuritySolutionsAnalyticsRecommendationClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client IoTSecuritySolutionsAnalyticsRecommendationClient) GetPreparer(ctx context.Context, resourceGroupName string, solutionName string, aggregatedRecommendationName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"aggregatedRecommendationName": autorest.Encode("path", aggregatedRecommendationName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"solutionName": autorest.Encode("path", solutionName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-08-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/iotSecuritySolutions/{solutionName}/analyticsModels/default/aggregatedRecommendations/{aggregatedRecommendationName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client IoTSecuritySolutionsAnalyticsRecommendationClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client IoTSecuritySolutionsAnalyticsRecommendationClient) GetResponder(resp *http.Response) (result IoTSecurityAggregatedRecommendation, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| {
"pile_set_name": "Github"
} |
version https://git-lfs.github.com/spec/v1
oid sha256:8979a022c2ee477f6d147568167d51a38fcbe6faee3a2f2a8a19394e0460973c
size 8403
| {
"pile_set_name": "Github"
} |
/* SpagoBI, the Open Source Business Intelligence suite
* Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice.
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package it.eng.spagobi.tools.dataset.common.metadata;
import java.util.Map;
/**
* @author Andrea Gioia ([email protected])
* Davide Zerbetto ([email protected])
*
*/
public interface IFieldMetaData {
public static final String DECIMALPRECISION = "decimalPrecision";
public static final String ORDERTYPE = "oprdertype";
public static final String PROPERTY_ATTRIBUTE_PRESENTATION = "attributePresentation";
public static final String PROPERTY_ATTRIBUTE_PRESENTATION_CODE = "code";
public static final String PROPERTY_ATTRIBUTE_PRESENTATION_DESCRIPTION = "description";
public static final String PROPERTY_ATTRIBUTE_PRESENTATION_CODE_AND_DESCRIPTION = "both";
public enum FieldType {ATTRIBUTE, MEASURE}
String getName();
String getAlias();
Class getType();
FieldType getFieldType();
Object getProperty(String propertyName);
void setName(String name);
void setAlias(String alias);
void setType(Class type);
void setProperty(String propertyName, Object propertyValue);
void setFieldType(FieldType fieldType);
void deleteProperty(String propertyName);
Map getProperties();
void setProperties(Map properties);
}
| {
"pile_set_name": "Github"
} |