text
stringlengths 2
100k
| meta
dict |
---|---|
/***************************************************************************/
/* */
/* t1parse.c */
/* */
/* Type 1 parser (body). */
/* */
/* Copyright 1996-2016 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/*************************************************************************/
/* */
/* The Type 1 parser is in charge of the following: */
/* */
/* - provide an implementation of a growing sequence of objects called */
/* a `T1_Table' (used to build various tables needed by the loader). */
/* */
/* - opening .pfb and .pfa files to extract their top-level and private */
/* dictionaries. */
/* */
/* - read numbers, arrays & strings from any dictionary. */
/* */
/* See `t1load.c' to see how data is loaded from the font file. */
/* */
/*************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_POSTSCRIPT_AUX_H
#include "t1parse.h"
#include "t1errors.h"
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_t1parse
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** INPUT STREAM PARSER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* see Adobe Technical Note 5040.Download_Fonts.pdf */
static FT_Error
read_pfb_tag( FT_Stream stream,
FT_UShort *atag,
FT_ULong *asize )
{
FT_Error error;
FT_UShort tag;
FT_ULong size;
*atag = 0;
*asize = 0;
if ( !FT_READ_USHORT( tag ) )
{
if ( tag == 0x8001U || tag == 0x8002U )
{
if ( !FT_READ_ULONG_LE( size ) )
*asize = size;
}
*atag = tag;
}
return error;
}
static FT_Error
check_type1_format( FT_Stream stream,
const char* header_string,
size_t header_length )
{
FT_Error error;
FT_UShort tag;
FT_ULong dummy;
if ( FT_STREAM_SEEK( 0 ) )
goto Exit;
error = read_pfb_tag( stream, &tag, &dummy );
if ( error )
goto Exit;
/* We assume that the first segment in a PFB is always encoded as */
/* text. This might be wrong (and the specification doesn't insist */
/* on that), but we have never seen a counterexample. */
if ( tag != 0x8001U && FT_STREAM_SEEK( 0 ) )
goto Exit;
if ( !FT_FRAME_ENTER( header_length ) )
{
error = FT_Err_Ok;
if ( ft_memcmp( stream->cursor, header_string, header_length ) != 0 )
error = FT_THROW( Unknown_File_Format );
FT_FRAME_EXIT();
}
Exit:
return error;
}
FT_LOCAL_DEF( FT_Error )
T1_New_Parser( T1_Parser parser,
FT_Stream stream,
FT_Memory memory,
PSAux_Service psaux )
{
FT_Error error;
FT_UShort tag;
FT_ULong size;
psaux->ps_parser_funcs->init( &parser->root, NULL, NULL, memory );
parser->stream = stream;
parser->base_len = 0;
parser->base_dict = NULL;
parser->private_len = 0;
parser->private_dict = NULL;
parser->in_pfb = 0;
parser->in_memory = 0;
parser->single_block = 0;
/* check the header format */
error = check_type1_format( stream, "%!PS-AdobeFont", 14 );
if ( error )
{
if ( FT_ERR_NEQ( error, Unknown_File_Format ) )
goto Exit;
error = check_type1_format( stream, "%!FontType", 10 );
if ( error )
{
FT_TRACE2(( " not a Type 1 font\n" ));
goto Exit;
}
}
/******************************************************************/
/* */
/* Here a short summary of what is going on: */
/* */
/* When creating a new Type 1 parser, we try to locate and load */
/* the base dictionary if this is possible (i.e., for PFB */
/* files). Otherwise, we load the whole font into memory. */
/* */
/* When `loading' the base dictionary, we only setup pointers */
/* in the case of a memory-based stream. Otherwise, we */
/* allocate and load the base dictionary in it. */
/* */
/* parser->in_pfb is set if we are in a binary (`.pfb') font. */
/* parser->in_memory is set if we have a memory stream. */
/* */
/* try to compute the size of the base dictionary; */
/* look for a Postscript binary file tag, i.e., 0x8001 */
if ( FT_STREAM_SEEK( 0L ) )
goto Exit;
error = read_pfb_tag( stream, &tag, &size );
if ( error )
goto Exit;
if ( tag != 0x8001U )
{
/* assume that this is a PFA file for now; an error will */
/* be produced later when more things are checked */
if ( FT_STREAM_SEEK( 0L ) )
goto Exit;
size = stream->size;
}
else
parser->in_pfb = 1;
/* now, try to load `size' bytes of the `base' dictionary we */
/* found previously */
/* if it is a memory-based resource, set up pointers */
if ( !stream->read )
{
parser->base_dict = (FT_Byte*)stream->base + stream->pos;
parser->base_len = size;
parser->in_memory = 1;
/* check that the `size' field is valid */
if ( FT_STREAM_SKIP( size ) )
goto Exit;
}
else
{
/* read segment in memory -- this is clumsy, but so does the format */
if ( FT_ALLOC( parser->base_dict, size ) ||
FT_STREAM_READ( parser->base_dict, size ) )
goto Exit;
parser->base_len = size;
}
parser->root.base = parser->base_dict;
parser->root.cursor = parser->base_dict;
parser->root.limit = parser->root.cursor + parser->base_len;
Exit:
if ( error && !parser->in_memory )
FT_FREE( parser->base_dict );
return error;
}
FT_LOCAL_DEF( void )
T1_Finalize_Parser( T1_Parser parser )
{
FT_Memory memory = parser->root.memory;
/* always free the private dictionary */
FT_FREE( parser->private_dict );
/* free the base dictionary only when we have a disk stream */
if ( !parser->in_memory )
FT_FREE( parser->base_dict );
parser->root.funcs.done( &parser->root );
}
FT_LOCAL_DEF( FT_Error )
T1_Get_Private_Dict( T1_Parser parser,
PSAux_Service psaux )
{
FT_Stream stream = parser->stream;
FT_Memory memory = parser->root.memory;
FT_Error error = FT_Err_Ok;
FT_ULong size;
if ( parser->in_pfb )
{
/* in the case of the PFB format, the private dictionary can be */
/* made of several segments. We thus first read the number of */
/* segments to compute the total size of the private dictionary */
/* then re-read them into memory. */
FT_ULong start_pos = FT_STREAM_POS();
FT_UShort tag;
parser->private_len = 0;
for (;;)
{
error = read_pfb_tag( stream, &tag, &size );
if ( error )
goto Fail;
if ( tag != 0x8002U )
break;
parser->private_len += size;
if ( FT_STREAM_SKIP( size ) )
goto Fail;
}
/* Check that we have a private dictionary there */
/* and allocate private dictionary buffer */
if ( parser->private_len == 0 )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" invalid private dictionary section\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( FT_STREAM_SEEK( start_pos ) ||
FT_ALLOC( parser->private_dict, parser->private_len ) )
goto Fail;
parser->private_len = 0;
for (;;)
{
error = read_pfb_tag( stream, &tag, &size );
if ( error || tag != 0x8002U )
{
error = FT_Err_Ok;
break;
}
if ( FT_STREAM_READ( parser->private_dict + parser->private_len,
size ) )
goto Fail;
parser->private_len += size;
}
}
else
{
/* We have already `loaded' the whole PFA font file into memory; */
/* if this is a memory resource, allocate a new block to hold */
/* the private dict. Otherwise, simply overwrite into the base */
/* dictionary block in the heap. */
/* first of all, look at the `eexec' keyword */
FT_Byte* cur = parser->base_dict;
FT_Byte* limit = cur + parser->base_len;
FT_Pointer pos_lf;
FT_Bool test_cr;
Again:
for (;;)
{
if ( cur[0] == 'e' &&
cur + 9 < limit ) /* 9 = 5 letters for `eexec' + */
/* whitespace + 4 chars */
{
if ( cur[1] == 'e' &&
cur[2] == 'x' &&
cur[3] == 'e' &&
cur[4] == 'c' )
break;
}
cur++;
if ( cur >= limit )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" could not find `eexec' keyword\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
}
/* check whether `eexec' was real -- it could be in a comment */
/* or string (as e.g. in u003043t.gsf from ghostscript) */
parser->root.cursor = parser->base_dict;
/* set limit to `eexec' + whitespace + 4 characters */
parser->root.limit = cur + 10;
cur = parser->root.cursor;
limit = parser->root.limit;
while ( cur < limit )
{
if ( cur[0] == 'e' &&
cur + 5 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'x' &&
cur[3] == 'e' &&
cur[4] == 'c' )
goto Found;
}
T1_Skip_PS_Token( parser );
if ( parser->root.error )
break;
T1_Skip_Spaces ( parser );
cur = parser->root.cursor;
}
/* we haven't found the correct `eexec'; go back and continue */
/* searching */
cur = limit;
limit = parser->base_dict + parser->base_len;
if ( cur >= limit )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" premature end in private dictionary\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
goto Again;
/* now determine where to write the _encrypted_ binary private */
/* dictionary. We overwrite the base dictionary for disk-based */
/* resources and allocate a new block otherwise */
Found:
parser->root.limit = parser->base_dict + parser->base_len;
T1_Skip_PS_Token( parser );
cur = parser->root.cursor;
limit = parser->root.limit;
/* According to the Type 1 spec, the first cipher byte must not be */
/* an ASCII whitespace character code (blank, tab, carriage return */
/* or line feed). We have seen Type 1 fonts with two line feed */
/* characters... So skip now all whitespace character codes. */
/* */
/* On the other hand, Adobe's Type 1 parser handles fonts just */
/* fine that are violating this limitation, so we add a heuristic */
/* test to stop at \r only if it is not used for EOL. */
pos_lf = ft_memchr( cur, '\n', (size_t)( limit - cur ) );
test_cr = FT_BOOL( !pos_lf ||
pos_lf > ft_memchr( cur,
'\r',
(size_t)( limit - cur ) ) );
while ( cur < limit &&
( *cur == ' ' ||
*cur == '\t' ||
(test_cr && *cur == '\r' ) ||
*cur == '\n' ) )
++cur;
if ( cur >= limit )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" `eexec' not properly terminated\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
size = parser->base_len - (FT_ULong)( cur - parser->base_dict );
if ( parser->in_memory )
{
/* note that we allocate one more byte to put a terminating `0' */
if ( FT_ALLOC( parser->private_dict, size + 1 ) )
goto Fail;
parser->private_len = size;
}
else
{
parser->single_block = 1;
parser->private_dict = parser->base_dict;
parser->private_len = size;
parser->base_dict = NULL;
parser->base_len = 0;
}
/* now determine whether the private dictionary is encoded in binary */
/* or hexadecimal ASCII format -- decode it accordingly */
/* we need to access the next 4 bytes (after the final whitespace */
/* following the `eexec' keyword); if they all are hexadecimal */
/* digits, then we have a case of ASCII storage */
if ( cur + 3 < limit &&
ft_isxdigit( cur[0] ) && ft_isxdigit( cur[1] ) &&
ft_isxdigit( cur[2] ) && ft_isxdigit( cur[3] ) )
{
/* ASCII hexadecimal encoding */
FT_ULong len;
parser->root.cursor = cur;
(void)psaux->ps_parser_funcs->to_bytes( &parser->root,
parser->private_dict,
parser->private_len,
&len,
0 );
parser->private_len = len;
/* put a safeguard */
parser->private_dict[len] = '\0';
}
else
/* binary encoding -- copy the private dict */
FT_MEM_MOVE( parser->private_dict, cur, size );
}
/* we now decrypt the encoded binary private dictionary */
psaux->t1_decrypt( parser->private_dict, parser->private_len, 55665U );
if ( parser->private_len < 4 )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" invalid private dictionary section\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* replace the four random bytes at the beginning with whitespace */
parser->private_dict[0] = ' ';
parser->private_dict[1] = ' ';
parser->private_dict[2] = ' ';
parser->private_dict[3] = ' ';
parser->root.base = parser->private_dict;
parser->root.cursor = parser->private_dict;
parser->root.limit = parser->root.cursor + parser->private_len;
Fail:
Exit:
return error;
}
/* END */
| {
"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("NerdDinner")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NerdDinner")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("7db0d577-9a82-4a95-8a0b-1c3987a25d2f")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"pile_set_name": "Github"
} |
/* Hash tables for Objective C method dispatch.
Copyright (C) 1993, 1995, 1996, 2004 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GCC 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 GCC; see the file COPYING. If not, write to
the Free Software Foundation, 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA. */
/* As a special exception, if you link this library with files
compiled with GCC to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public License.
This exception does not however invalidate any other reasons why
the executable file might be covered by the GNU General Public License. */
#ifndef __hash_INCLUDE_GNU
#define __hash_INCLUDE_GNU
#include <stddef.h>
#include <string.h>
#include "objc.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* This data structure is used to hold items
* stored in a hash table. Each node holds
* a key/value pair.
*
* Items in the cache are really of type void *.
*/
typedef struct cache_node
{
struct cache_node *next; /* Pointer to next entry on the list.
NULL indicates end of list. */
const void *key; /* Key used to locate the value. Used
to locate value when more than one
key computes the same hash
value. */
void *value; /* Value stored for the key. */
} *node_ptr;
/*
* This data type is the function that computes a hash code given a key.
* Therefore, the key can be a pointer to anything and the function specific
* to the key type.
*
* Unfortunately there is a mutual data structure reference problem with this
* typedef. Therefore, to remove compiler warnings the functions passed to
* objc_hash_new will have to be casted to this type.
*/
typedef unsigned int (*hash_func_type) (void *, const void *);
/*
* This data type is the function that compares two hash keys and returns an
* integer greater than, equal to, or less than 0, according as the first
* parameter is lexicographically greater than, equal to, or less than the
* second.
*/
typedef int (*compare_func_type) (const void *, const void *);
/*
* This data structure is the cache.
*
* It must be passed to all of the hashing routines
* (except for new).
*/
typedef struct cache
{
/* Variables used to implement the hash itself. */
node_ptr *node_table; /* Pointer to an array of hash nodes. */
/* Variables used to track the size of the hash table so to determine
when to resize it. */
unsigned int size; /* Number of buckets allocated for the hash table
(number of array entries allocated for
"node_table"). Must be a power of two. */
unsigned int used; /* Current number of entries in the hash table. */
unsigned int mask; /* Precomputed mask. */
/* Variables used to implement indexing through the hash table. */
unsigned int last_bucket; /* Tracks which entry in the array where
the last value was returned. */
/* Function used to compute a hash code given a key.
This function is specified when the hash table is created. */
hash_func_type hash_func;
/* Function used to compare two hash keys to see if they are equal. */
compare_func_type compare_func;
} *cache_ptr;
/* Two important hash tables. */
extern cache_ptr module_hash_table, class_hash_table;
/* Allocate and initialize a hash table. */
cache_ptr objc_hash_new (unsigned int size,
hash_func_type hash_func,
compare_func_type compare_func);
/* Deallocate all of the hash nodes and the cache itself. */
void objc_hash_delete (cache_ptr cache);
/* Add the key/value pair to the hash table. If the
hash table reaches a level of fullness then it will be resized.
assert if the key is already in the hash. */
void objc_hash_add (cache_ptr *cachep, const void *key, void *value);
/* Remove the key/value pair from the hash table.
assert if the key isn't in the table. */
void objc_hash_remove (cache_ptr cache, const void *key);
/* Used to index through the hash table. Start with NULL
to get the first entry.
Successive calls pass the value returned previously.
** Don't modify the hash during this operation ***
Cache nodes are returned such that key or value can
be extracted. */
node_ptr objc_hash_next (cache_ptr cache, node_ptr node);
/* Used to return a value from a hash table using a given key. */
void *objc_hash_value_for_key (cache_ptr cache, const void *key);
/* Used to determine if the given key exists in the hash table */
BOOL objc_hash_is_key_in_hash (cache_ptr cache, const void *key);
/************************************************
Useful hashing functions.
Declared inline for your pleasure.
************************************************/
/* Calculate a hash code by performing some
manipulation of the key pointer. (Use the lowest bits
except for those likely to be 0 due to alignment.) */
static inline unsigned int
objc_hash_ptr (cache_ptr cache, const void *key)
{
return ((size_t)key / sizeof (void *)) & cache->mask;
}
/* Calculate a hash code by iterating over a NULL
terminate string. */
static inline unsigned int
objc_hash_string (cache_ptr cache, const void *key)
{
unsigned int ret = 0;
unsigned int ctr = 0;
const char *ckey = (const char *) key;
while (*ckey) {
ret ^= *ckey++ << ctr;
ctr = (ctr + 1) % sizeof (void *);
}
return ret & cache->mask;
}
/* Compare two pointers for equality. */
static inline int
objc_compare_ptrs (const void *k1, const void *k2)
{
return (k1 == k2);
}
/* Compare two strings. */
static inline int
objc_compare_strings (const void *k1, const void *k2)
{
if (k1 == k2)
return 1;
else if (k1 == 0 || k2 == 0)
return 0;
else
return ! strcmp ((const char *) k1, (const char *) k2);
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* not __hash_INCLUDE_GNU */
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- dialog animation -->
<style name="mvvmframe_dialog_animation" parent="android:style/Animation.Dialog">
<item name="android:windowEnterAnimation">@anim/mvvmframe_dialog_in</item>
<item name="android:windowExitAnimation">@anim/mvvmframe_dialog_out</item>
</style>
<!-- dialog style -->
<style name="mvvmframe_dialog" parent="android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:windowAnimationStyle">@style/mvvmframe_dialog_animation</item>
</style>
<!-- progress dialog style -->
<style name="mvvmframe_progress_dialog" parent="android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:backgroundDimEnabled">false</item>
<item name="android:windowAnimationStyle">@style/mvvmframe_dialog_animation</item>
<item name="android:progressBarStyle">@android:style/Widget.ProgressBar.Horizontal</item>
</style>
</resources> | {
"pile_set_name": "Github"
} |
{
"meta:license": [
"Copyright 2018 Adobe Systems Incorporated. All rights reserved.",
"This work is licensed under a Creative Commons Attribution 4.0 International (CC BY 4.0) license",
"you may not use this file except in compliance with the License. You may obtain a copy",
"of the License at https://creativecommons.org/licenses/by/4.0/"
],
"$schema": "http://json-schema.org/draft-06/schema#",
"$id": "https://ns.adobe.com/experience/offer-management/offer-activity",
"meta:abstract": false,
"meta:extensible": true,
"type": "object",
"title": "Activity",
"description": "An offer activity is used to control the decisioning process. It specifies the filter applied to the total inventory to narrow down offers by topic/category, the placement to narrow down the inventory to those offers that technically fit into the reserved space for the offer and specifies a fall back option should the combined constraints disqualify all available personalization options (offers).",
"definitions": {
"offer-activity": {
"properties": {
"@id": {
"type": "string",
"format": "uri-reference",
"title": "ID",
"description": "The unique identifier of the offer activity. This @id must be unique across for objects that are not semantically the same, otherwise it is interpreted as referring to the same object. "
},
"xdm:name": {
"type": "string",
"title": "Name",
"description": "Activity name. The name is displayed in various user interfaces."
},
"xdm:status": {
"type": "string",
"title": "Status",
"description": "Activity Status",
"enum": [
"draft",
"live",
"complete",
"archived"
],
"meta:enum": {
"draft": "Draft",
"live": "Live",
"complete": "Complete",
"archived": "Archived"
}
},
"xdm:startDate": {
"type": "string",
"format": "date-time",
"title": "Start Date",
"description": "Activity Start Date"
},
"xdm:endDate": {
"type": "string",
"format": "date-time",
"title": "End Date",
"description": "Activity End Date"
},
"xdm:placement": {
"type": "string",
"format": "uri",
"title": "Offer Placement",
"description": "The reference to an offer placement instance. Offer placements are used by offer activities to limit the offer selection to those offers that have a representation that complies with the offer placement restrictions. The value is the URI (@id) of the offer placement that is referenced. See schema https://ns.adobe.com/experience/offer-management/offer-placement"
},
"xdm:filter": {
"type": "string",
"format": "uri",
"title": "Offer Filter",
"description": "The reference to a filter that is applied to the inventory when a decisioning is made the context of this activity. The value is the URI (@id) of the offer filter that is referenced. See schema https://ns.adobe.com/experience/offer-management/offer-filter"
},
"xdm:fallback": {
"type": "string",
"format": "uri",
"title": "Fallback Offer",
"description": "The reference to a fallback offer that is used when decisioning in the context of this activity does not qualify any of the offers specified in the fallback offer. The value is the URI (@id) of the fallback offer that is referenced. See schema https://ns.adobe.com/experience/offer-management/fallback-offer"
}
}
}
},
"allOf": [
{
"$ref": "#/definitions/offer-activity"
},
{
"required": [
"xdm:name",
"xdm:status",
"xdm:placement",
"xdm:filter",
"xdm:fallback"
]
}
]
} | {
"pile_set_name": "Github"
} |
const path = require('path');
// Babel plugins list for jsx plus
const babelPlugins = [
'babel-plugin-transform-jsx-list',
'babel-plugin-transform-jsx-condition',
'babel-plugin-transform-jsx-memo',
'babel-plugin-transform-jsx-slot',
['babel-plugin-transform-jsx-fragment', { moduleName: 'react' }],
'babel-plugin-transform-jsx-class',
];
module.exports = ({ onGetWebpackConfig }) => {
onGetWebpackConfig(config => {
// modify babel config to add jsx plus plugins
['jsx', 'tsx'].forEach(rule => {
config.module
.rule(rule)
.use('babel-loader')
.tap(options => {
babelPlugins.forEach(plugin => {
if (typeof plugin === 'string') {
options.plugins.push(require.resolve(plugin));
} else if (Array.isArray(plugin)) {
const [pluginName, pluginOption] = plugin;
options.plugins.push([require.resolve(pluginName), pluginOption]);
}
});
return options;
});
});
// add resolve modules for babel-runtime-jsx-plus
const runtimePath = require.resolve('babel-runtime-jsx-plus');
const pathArr = runtimePath.split('node_modules');
pathArr.pop(); // pop file path
config.resolve.modules.add(path.join(pathArr.join('node_modules'), 'node_modules'));
});
};
| {
"pile_set_name": "Github"
} |
function varargout = gui(object, varargin)
%gui_test_runner/gui execute the graphical user interface of mlUnit.
% The graphical user interface is realized with guide and therefore
% a file gui.fig exists containing the figure and all the handles.
%
% Example
% =======
% Start the gui_test_runner:
% gui(gui_test_runner);
%
% See also GUI_TEST_RESULT, GUI_TEST_RUNNER.
% This Software and all associated files are released unter the
% GNU General Public License (GPL), see LICENSE for details.
%
% §Author: Thomas Dohmke <[email protected]> §
% $Id: gui.m 267 2007-03-10 12:38:34Z thomi $
global self;
if ((object.callback ~= 1) && (isempty(self) || (isempty(get_object(self)))))
self = object;
elseif ((object.callback == 1) && (isempty(self)))
handles = guidata(gcbo);
try
self = get(handles.gui_window, 'UserData');
catch
end;
end;
gui_singleton = 1;
gui_state = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_singleton, ...
'gui_OpeningFcn', @gui_openingfcn, ...
'gui_OutputFcn', @gui_outputfcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if ((nargin > 1) && (ischar(varargin{1})))
gui_state.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_state, varargin{:});
else
gui_mainfcn(gui_state, varargin{:});
end
function gui_openingfcn(hobject, eventdata, handles, varargin) %#ok
global self;
handles.output = hobject;
guidata(hobject, handles);
self.handle = handles.gui_window;
self.handles = handles;
set(handles.gui_progress_bar, 'XTick', [], 'XTickLabel', []);
set(handles.gui_progress_bar, 'YTick', [], 'YTickLabel', []);
menu = uicontextmenu;
set(self.handle, 'UIContextMenu', menu);
self.handles.menu_dock = uimenu(menu, 'Label', 'Dock Window', 'Callback', ...
@(hobject, eventdata)gui(gui_test_runner(1), 'gui_dock_callback', hobject, [], handles));
self.handles.menu_shorten = uimenu(menu, 'Label', 'Short Directory Names', 'Callback', ...
@(hobject, eventdata)gui(gui_test_runner(1), 'gui_shorten_callback', hobject, [], handles));
if (~isempty(self.dock) && isnumeric(self.dock) && self.dock)
set(handles.gui_window, 'WindowStyle', 'Docked');
set(self.handles.menu_dock, 'Label', 'Undock Window');
end;
if (~ischar(self.test_case))
try
test_str = str(self.test_case);
catch
test_str = '';
end;
else
test_str = self.test_case;
end;
if (ischar(test_str) && (length(test_str) > 0))
set(handles.gui_test_case, 'String', test_str);
gui_run_callback(hobject, eventdata, handles);
self.test_case = '';
end;
set(self.handle, 'UserData', self);
function varargout = gui_outputfcn(hobject, eventdata, handles) %#ok
varargout{1} = handles.output;
function gui_resize_callback(hobject, eventdata, handles) %#ok
position = get(hobject, 'Position');
if (position(4) < 20)
position(4) = 20;
end;
if (position(3) < 50)
position(3) = 50;
end;
space = position(4) - 30.0;
set(handles.gui_text_name, 'Position', [2.5 position(4) - 2.5 20.0 1]);
set(handles.gui_test_case, 'Position', [2.5 position(4) - 4.5 position(3) - 15 1.6]);
set(handles.gui_run, 'Position', [position(3) - 12.5 position(4) - 4.5 10.0 1.6]);
set(handles.gui_show, 'Position', [position(3) - 12.5 position(4) - 28.8 - space 10.0 1.6]);
set(handles.gui_progress_bar, 'Position', [2.5 position(4) - 7.5 position(3) - 5.0 1.6]);
set(handles.gui_text_runs, 'Position', [2.5 position(4) - 9.5 40.0 1]);
set(handles.gui_text_error_list, 'Position', [2.5 position(4) - 12 20.0 1]);
set(handles.gui_error_list, 'Position', [2.5 position(4) - 19.5 - space / 2 position(3) - 5.0 7 + space / 2]);
set(handles.gui_error, 'Position', [2.5 position(4) - 27 - space position(3) - 5.0 7 + space / 2]);
set(handles.gui_text_time, 'Position', [2.5 1.0 48.0 1]);
function gui_test_case_callback(hobject, eventdata, handles) %#ok
if (double(get(handles.gui_window, 'CurrentCharacter')) == 13)
gui_run_callback(hobject, eventdata, handles);
end;
function gui_test_case_createfcn(hobject, eventdata, handles) %#ok
if ispc && isequal(get(hobject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hobject,'BackgroundColor','white');
end
function gui_run_callback(hobject, eventdata, handles) %#ok
global self;
t = clock;
set(handles.gui_show, 'Enable', 'off');
set(handles.gui_error, 'String', '');
set(handles.gui_error, 'String', '');
set(handles.gui_text_time, 'String', '');
test_case = get(handles.gui_test_case, 'String');
if (isempty(test_case))
result = gui_test_result(handles.gui_progress_bar, ...
handles.gui_text_runs, ...
handles.gui_error_list, ...
1);
update(result);
return;
end;
instance = 0;
error1 = [];
error2 = [];
try
instance = eval([test_case, ';']);
catch
error1 = lasterror;
try
loader = test_loader;
instance = load_tests_from_test_case(loader, test_case);
catch
error2 = lasterror;
end;
end;
if ((strcmp(class(instance), 'double') && (isempty(instance))) || ...
(~isempty(error2)))
result = gui_test_result(handles.gui_progress_bar, ...
handles.gui_text_runs, ...
handles.gui_error_list, ...
1);
if (~isempty(error1))
result = add_error_with_stack(result, self, error1);
end;
if (~isempty(error2))
result = add_error_with_stack(result, self, error2); %#ok
end;
else
result = gui_test_result(handles.gui_progress_bar, ...
handles.gui_text_runs, ...
handles.gui_error_list, ...
count_test_cases(instance));
[test, result] = run(instance, result); %#ok
end;
time = etime(clock, t);
set(handles.gui_text_time, 'String', sprintf('Finished: %.3fs.\n', time));
gui_error_list_callback(handles.gui_error_list, eventdata, handles);
function gui_error_list_callback(hobject, eventdata, handles) %#ok
global self;
data = get(handles.gui_error_list, 'UserData');
selected = get(handles.gui_error_list, 'Value');
if (length(data) > 0)
set(handles.gui_error, 'String', shorten_error_text(self, data{selected}));
[tokens] = regexp(data{selected}, get_line_expression(self), 'tokens', 'once'); %, 'dotexceptnewline');
if (length(tokens) == 2)
set(handles.gui_show, 'Enable', 'on');
set(handles.gui_show, 'UserData', tokens);
else
set(handles.gui_show, 'Enable', 'off');
end;
end;
function gui_error_list_createfcn(hobject, eventdata, handles) %#ok
if ispc && isequal(get(hobject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hobject,'BackgroundColor','white');
end
function gui_error_createfcn(hobject, eventdata, handles) %#ok
if ispc && isequal(get(hobject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hobject,'BackgroundColor','white');
end
function gui_dock_callback(hObject, eventdata, handles) %#ok
global self;
docked = get(handles.gui_window, 'WindowStyle');
if (strcmp(docked, 'docked'))
set(handles.gui_window, 'WindowStyle', 'Normal');
set(self.handles.menu_dock, 'Label', 'Dock Window');
self.dock = 0;
else
set(handles.gui_window, 'WindowStyle', 'Docked');
set(self.handles.menu_dock, 'Label', 'Undock Window');
self.dock = 1;
end;
set(handles.gui_window, 'UserData', self);
function gui_shorten_callback(hObject, eventdata, handles) %#ok
global self;
if (self.shorten == 0)
self.shorten = 1;
set(self.handles.menu_shorten, 'Label', 'Long Directory Names');
else
self.shorten = 0;
set(self.handles.menu_shorten, 'Label', 'Short Directory Names');
end;
set(handles.gui_window, 'UserData', self);
gui_error_list_callback(hObject, eventdata, self.handles);
function gui_show_Callback(hObject, eventdata, handles) %#ok
tokens = get(hObject, 'UserData');
if ((length(tokens) == 3) && (etime(clock, tokens{3}) < 1))
data = get(handles.gui_error_list, 'UserData');
selected = get(handles.gui_error_list, 'Value');
[tokens] = regexp(data{selected}, get_line_expression(self), 'tokens', 'once'); %, 'dotexceptnewline');
if (length(tokens) > 1)
second = tokens{2};
com.mathworks.mlservices.MLEditorServices.openDocumentToLine(second{1},str2num(second{2})); %#ok
end;
else
com.mathworks.mlservices.MLEditorServices.openDocumentToLine(tokens{1},str2num(tokens{2})); %#ok
tokens{3} = clock;
set(hObject, 'UserData', tokens);
end;
| {
"pile_set_name": "Github"
} |
<html>
<head>
<title>Bit Selector</title>
</head>
<body bgcolor="FFFFFF">
<h1><img align="center" height="32" width="32" src="../../../icons/bitSelector.gif">
<em>Bit Selector</em></h1>
<p><table>
<tr><td><strong>Library:</strong></td>
<td><a href="index.html">Plexers</a></td></tr>
<tr><td><strong>Introduced:</strong></td>
<td>2.0.5</td></tr>
<tr><td valign="top"><strong>Appearance:</strong></td>
<td valign="top"><img src="../../../img-libs/selector.png"></td></tr>
</table></p>
<h2>Behavior</h2>
<p>Given an input of several bits, this will divide it into several
equal-sized groups (starting from the lowest-order bit) and output
the group selected by the select input.</p>
<p>For example, if we have an eight-bit input 01010101, and we are to have
a three-bit output, then group 0 will be the lowest-order three bits 101,
group 1 will be the next three bits, 010, and group 2 will be the next three
bits 001. (Any bits beyond the top are filled in with 0.) The select
input will be a two-bit number that selects which of these three groups
to output; if the select input is 3, then 000 will be the output.</p>
<h2>Pins (assuming component faces east)</h2>
<dl>
<dt>West edge (input, bit width matches Data Bits attribute)</dt>
<dd>Data value from which bits should be selected for the output.</dd>
<dt>East edge (output, bit width matches Output Bits attribute)</dt>
<dd>A group of bits from the data value, as selected by the select
input.</dd>
<dt>South edge (input, bit width is quotient of Data Bits and Output Bits, rounded up)</dt>
<dd>Select input: Determines which of the bit groups should be routed
to the output.</dd>
</dl>
<h2>Attributes</h2>
<p>When the component is selected or being added,
the digits '0' through '9' alter its <q>Output Bits</q> attribute,
Alt-0 through Alt-9 alter its <q>Data Bits</q> attribute,
and the arrow keys alter its <q>Facing</q> attribute.</p>
<dl>
<dt>Facing</dt>
<dd>The direction of the component (its output relative to its input).</dd>
<dt>Data Bits</dt>
<dd>The bit width of the component's data input.</dd>
<dt>Output Bits</dt>
<dd>The bit width of the component's output.</dd>
</dl>
<h2>Poke Tool Behavior</h2>
<p>None.</p>
<h2>Text Tool Behavior</h2>
<p>None.</p>
<p><a href="../index.html">Back to <em>Library Reference</em></a></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
# /* Copyright (C) 2001
# * Housemarque Oy
# * http://www.housemarque.com
# *
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# */
#
# /* Revised by Paul Mensonides (2002) */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_LOGICAL_NOT_HPP
# define BOOST_PREPROCESSOR_LOGICAL_NOT_HPP
#
# include <boost/preprocessor/config/config.hpp>
# include <boost/preprocessor/logical/bool.hpp>
# include <boost/preprocessor/logical/compl.hpp>
#
# /* BOOST_PP_NOT */
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
# define BOOST_PP_NOT(x) BOOST_PP_COMPL(BOOST_PP_BOOL(x))
# else
# define BOOST_PP_NOT(x) BOOST_PP_NOT_I(x)
# define BOOST_PP_NOT_I(x) BOOST_PP_COMPL(BOOST_PP_BOOL(x))
# endif
#
# endif
| {
"pile_set_name": "Github"
} |
source ENV['GEM_SOURCE'] || 'https://artifactory.delivery.puppetlabs.net/artifactory/api/gems/rubygems/'
def location_for(place, fake_version = nil)
if place =~ /^(git:[^#]*)#(.*)/
[fake_version, { :git => $1, :branch => $2, :require => false }].compact
elsif place =~ /^file:\/\/(.*)/
['>= 0', { :path => File.expand_path($1), :require => false }]
else
[place, { :require => false }]
end
end
gem 'beaker', *location_for(ENV['BEAKER_VERSION'] || '~> 4.5')
gem 'beaker-pe', '~> 2.0'
gem 'beaker-answers'
gem 'beaker-hostgenerator', *location_for(ENV['BEAKER_HOSTGENERATOR_VERSION'] || '~> 1.1')
gem 'beaker-abs', *location_for(ENV['BEAKER_ABS_VERSION'] || '~> 0.4')
gem 'rototiller', '= 0.1.0'
gem 'beaker-qa-i18n'
| {
"pile_set_name": "Github"
} |
<div class="{{styles.<%= componentClassName %>}}">
<div class="{{styles.container}}">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white {{styles.row}}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<span class="ms-font-xl ms-fontColor-white">Welcome to SharePoint!</span>
<p class="ms-font-l ms-fontColor-white">Customize SharePoint experiences using Web Parts.</p>
<p class="ms-font-l ms-fontColor-white">{{description}}</p>
<a href="https://aka.ms/spfx" class="{{styles.button}}">
<span class="{{styles.label}}">Learn more</span>
</a>
</div>
</div>
</div>
</div> | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{2f06c416-72fb-449e-b517-eda9c6897515}</ProjectGuid>
<Keyword>DirectXApp</Keyword>
<RootNamespace>Social</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<WindowsTargetPlatformVersion>10.0.14393.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.10586.0</WindowsTargetPlatformMinVersion>
<ApplicationTypeRevision>10.0</ApplicationTypeRevision>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<Import Project="..\..\..\..\xsapi.staticlib.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v140</PlatformToolset>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v140</PlatformToolset>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v140</PlatformToolset>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
<Import Project="$(VSINSTALLDIR)\Common7\IDE\Extensions\Microsoft\VsGraphics\ImageContentTask.props" />
<Import Project="$(VSINSTALLDIR)\Common7\IDE\Extensions\Microsoft\VsGraphics\MeshContentTask.props" />
<Import Project="$(VSINSTALLDIR)\Common7\IDE\Extensions\Microsoft\VsGraphics\ShaderGraphContentTask.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<Link>
<AdditionalDependencies>d2d1.lib; d3d11.lib; dxgi.lib; windowscodecs.lib; dwrite.lib; %(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store\arm; $(VCInstallDir)\lib\arm</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<Link>
<AdditionalDependencies>d2d1.lib; d3d11.lib; dxgi.lib; windowscodecs.lib; dwrite.lib; %(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store\arm; $(VCInstallDir)\lib\arm</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Link>
<AdditionalDependencies>d2d1.lib; d3d11.lib; dxgi.lib; windowscodecs.lib; dwrite.lib; %(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store; $(VCInstallDir)\lib</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Link>
<AdditionalDependencies>d2d1.lib; d3d11.lib; dxgi.lib; windowscodecs.lib; dwrite.lib; %(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store; $(VCInstallDir)\lib</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>d2d1.lib; d3d11.lib; dxgi.lib; windowscodecs.lib; dwrite.lib; %(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store\amd64; $(VCInstallDir)\lib\amd64</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>d2d1.lib; d3d11.lib; dxgi.lib; windowscodecs.lib; dwrite.lib; %(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store\amd64; $(VCInstallDir)\lib\amd64</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(ProjectDir)..\..\..\..\InProgressSamples\Kits\;$(ProjectDir)..\..\..\..\InProgressSamples\Kits\DirectXTK\Inc\;$(ProjectDir);$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="App.h" />
<ClInclude Include="Common\DeviceResources.h" />
<ClInclude Include="Common\DirectXHelper.h" />
<ClInclude Include="Common\StepTimer.h" />
<ClInclude Include="GameLogic\Game.h" />
<ClInclude Include="GameLogic\GameData.h" />
<ClInclude Include="GameLogic\Renderer.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="Utils\Input.h" />
<ClInclude Include="Utils\PerformanceCounters.h" />
<ClInclude Include="Utils\Utils.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="App.cpp" />
<ClCompile Include="Common\DeviceResources.cpp" />
<ClCompile Include="GameLogic\Game.cpp" />
<ClCompile Include="GameLogic\GameData.cpp" />
<ClCompile Include="GameLogic\Renderer.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="SocialManagerIntegration.cpp" />
<ClCompile Include="Utils\Input.cpp" />
<ClCompile Include="Utils\PerformanceCounters.cpp" />
<ClCompile Include="Utils\Utils.cpp" />
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\Build\Microsoft.Xbox.Services.140.UWP.Cpp\Microsoft.Xbox.Services.140.UWP.Cpp.vcxproj">
<Project>{8f96710e-5169-4917-8874-7de248f4d243}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\External\cpprestsdk\Release\src\build\vs14.uwp\cpprestsdk140.uwp.static.vcxproj">
<Project>{9ad285a2-301e-47a0-a299-14ad5d4f2758}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\InProgressSamples\Kits\DirectXTK\DirectXTK_Windows10_2015.vcxproj">
<Project>{f4776924-619c-42c7-88b2-82c947ccc9e7}</Project>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Image Include="Assets\background.jpg" />
<Image Include="Assets\Logo.scale-100.png" />
<Image Include="Assets\SmallLogo.scale-100.png" />
<Image Include="Assets\SplashScreen.scale-100.png" />
<Image Include="Assets\StoreLogo.scale-100.png" />
<Image Include="Assets\WideLogo.scale-100.png" />
<Image Include="Assets\windowslogo.dds" />
<None Include="xboxservices.config">
<DeploymentContent>true</DeploymentContent>
</None>
</ItemGroup>
<ItemGroup>
<None Include="Assets\italic.spritefont">
<DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
<DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
<DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
<DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
<DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
<DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
</None>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="$(VSINSTALLDIR)\Common7\IDE\Extensions\Microsoft\VsGraphics\ImageContentTask.targets" />
<Import Project="$(VSINSTALLDIR)\Common7\IDE\Extensions\Microsoft\VsGraphics\MeshContentTask.targets" />
<Import Project="$(VSINSTALLDIR)\Common7\IDE\Extensions\Microsoft\VsGraphics\ShaderGraphContentTask.targets" />
</ImportGroup>
</Project> | {
"pile_set_name": "Github"
} |
var _concat = require('./internal/_concat');
var _curry2 = require('./internal/_curry2');
var curryN = require('./curryN');
/**
* Wrap a function inside another to allow you to make adjustments to the parameters, or do
* other processing either before the internal function is called or with its results.
*
* @func
* @memberOf R
* @category Function
* @sig (a... -> b) -> ((a... -> b) -> a... -> c) -> (a... -> c)
* @param {Function} fn The function to wrap.
* @param {Function} wrapper The wrapper function.
* @return {Function} The wrapped function.
* @example
*
* var greet = function(name) {return 'Hello ' + name;};
*
* var shoutedGreet = R.wrap(greet, function(gr, name) {
* return gr(name).toUpperCase();
* });
* shoutedGreet("Kathy"); //=> "HELLO KATHY"
*
* var shortenedGreet = R.wrap(greet, function(gr, name) {
* return gr(name.substring(0, 3));
* });
* shortenedGreet("Robert"); //=> "Hello Rob"
*/
module.exports = _curry2(function wrap(fn, wrapper) {
return curryN(fn.length, function() {
return wrapper.apply(this, _concat([fn], arguments));
});
});
| {
"pile_set_name": "Github"
} |
//-------------------------------------------------------------------------
/*
Copyright (C) 2005 Jonathon Fowler <[email protected]>
This file is part of JFShadowWarrior
Shadow Warrior 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include "ns.h"
#include "compat.h"
#include "tarray.h"
#include "debugbreak.h"
BEGIN_SW_NS
#include "saveable.h"
static TArray<saveable_module*> saveablemodules;
void Saveable_Init(void)
{
if (saveablemodules.Size() > 0) return;
Saveable_Init_Dynamic();
#define MODULE(x) { \
extern saveable_module saveable_ ## x; \
saveablemodules.Push(&saveable_ ## x); \
}
MODULE(actor)
MODULE(ai)
MODULE(build)
MODULE(bunny)
MODULE(coolg)
MODULE(coolie)
MODULE(eel)
MODULE(girlninj)
MODULE(goro)
MODULE(hornet)
MODULE(jweapon)
MODULE(lava)
MODULE(miscactr)
MODULE(morph)
MODULE(ninja)
MODULE(panel)
MODULE(player)
MODULE(quake)
MODULE(ripper)
MODULE(ripper2)
MODULE(rotator)
MODULE(serp)
MODULE(skel)
MODULE(skull)
MODULE(slidor)
MODULE(spike)
MODULE(sprite)
MODULE(sumo)
MODULE(track)
MODULE(vator)
MODULE(wallmove)
MODULE(weapon)
MODULE(zilla)
MODULE(zombie)
MODULE(sector)
}
int Saveable_FindCodeSym(void *ptr, savedcodesym *sym)
{
unsigned m,i;
if (!ptr)
{
sym->module = 0; // module 0 is the "null module" for null pointers
sym->index = 0;
return 0;
}
for (m=0; m<saveablemodules.Size(); m++)
{
for (i=0; i<saveablemodules[m]->numcode; i++)
{
if (ptr != saveablemodules[m]->code[i]) continue;
sym->module = 1+m;
sym->index = i;
return 0;
}
}
debug_break();
return -1;
}
int Saveable_FindDataSym(void *ptr, saveddatasym *sym)
{
unsigned m,i;
if (!ptr)
{
sym->module = 0;
sym->index = 0;
sym->offset = 0;
return 0;
}
for (m = 0; m < saveablemodules.Size(); m++)
{
for (i=0; i<saveablemodules[m]->numdata; i++)
{
if (ptr < saveablemodules[m]->data[i].base) continue;
if (ptr >= (void *)((intptr_t)saveablemodules[m]->data[i].base +
saveablemodules[m]->data[i].size)) continue;
sym->module = 1+m;
sym->index = i;
sym->offset = (intptr_t)ptr - (intptr_t)saveablemodules[m]->data[i].base;
return 0;
}
}
debug_break();
return -1;
}
int Saveable_RestoreCodeSym(savedcodesym *sym, void **ptr)
{
if (sym->module == 0)
{
*ptr = NULL;
return 0;
}
if (sym->module > saveablemodules.Size())
{
debug_break();
return -1;
}
if (sym->index >= saveablemodules[sym->module-1]->numcode)
{
debug_break();
return -1;
}
*ptr = saveablemodules[sym->module-1]->code[sym->index];
return 0;
}
int Saveable_RestoreDataSym(saveddatasym *sym, void **ptr)
{
if (sym->module == 0)
{
*ptr = NULL;
return 0;
}
if (sym->module > saveablemodules.Size())
{
debug_break();
return -1;
}
if (sym->index >= saveablemodules[sym->module-1]->numdata)
{
debug_break();
return -1;
}
if (sym->offset >= saveablemodules[sym->module-1]->data[sym->index].size)
{
debug_break();
return -1;
}
*ptr = (void *)((intptr_t)saveablemodules[sym->module-1]->data[sym->index].base + sym->offset);
return 0;
}
END_SW_NS
| {
"pile_set_name": "Github"
} |
package io.scalajs.nodejs.tty
import io.scalajs.nodejs.FileDescriptor
import io.scalajs.nodejs.net.Socket
import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
/**
* The tty.WriteStream class is a subclass of net.Socket that represents the writable side of a TTY.
* In normal circumstances, process.stdout and process.stderr will be the only tty.WriteStream instances
* created for a Node.js process and there should be no reason to create additional instances.
* @see https://nodejs.org/api/tty.html
* @since 0.5.8
*/
@js.native
@JSImport("tty", "WriteStream")
class WriteStream(fd: FileDescriptor) extends Socket {
/////////////////////////////////////////////////////////////////////////////////
// Properties
/////////////////////////////////////////////////////////////////////////////////
/**
* A number specifying the number of columns the TTY currently has. This property is updated whenever
* the 'resize' event is emitted.
* @see [[WriteStreamEvents.onResize]]
* @since 0.7.7
*/
def columns: Int = js.native
/**
* Indicates whether the stream is a TTY
*/
def isTTY: Boolean = js.native
/**
* A number specifying the number of rows the TTY currently has. This property is updated whenever the
* 'resize' event is emitted.
* @see [[WriteStreamEvents.onResize]]
* @since 0.7.7
*/
def rows: Int = js.native
} | {
"pile_set_name": "Github"
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using BasicWebSite.Models;
using Microsoft.AspNetCore.Mvc;
namespace BasicWebSite.Controllers.ActionConstraints
{
[Route("ConsumesAttribute_Company/[action]")]
public class ConsumesAttribute_WithFallbackActionController : Controller
{
[Consumes("application/json")]
[ActionName("CreateProduct")]
public IActionResult CreateProductJson()
{
return Content("CreateProduct_Product_Json");
}
[Consumes("application/xml")]
[ActionName("CreateProduct")]
public IActionResult CreateProductXml()
{
return Content("CreateProduct_Product_Xml");
}
public IActionResult CreateProduct()
{
return Content("CreateProduct_Product_Text");
}
}
} | {
"pile_set_name": "Github"
} |
--TEST--
phpunit --exclude-group balanceIsInitiallyZero BankAccountTest ../_files/BankAccountTest.php
--FILE--
<?php
$_SERVER['argv'][1] = '--no-configuration';
$_SERVER['argv'][2] = '--exclude-group';
$_SERVER['argv'][3] = 'balanceIsInitiallyZero';
$_SERVER['argv'][4] = 'BankAccountTest';
$_SERVER['argv'][5] = dirname(__FILE__) . '/../_files/BankAccountTest.php';
require __DIR__ . '/../bootstrap.php';
PHPUnit_TextUI_Command::main();
?>
--EXPECTF--
PHPUnit %s by Sebastian Bergmann and contributors.
..
Time: %s, Memory: %s
OK (2 tests, 2 assertions)
| {
"pile_set_name": "Github"
} |
/**
* This file contains the variables used in other gulp files
* which defines tasks
* By design, we only put there very generic config values
* which are used in several places to keep good readability
* of the tasks
*/
var gutil = require('gulp-util');
/**
* The main paths of your project handle these with care
*/
exports.paths = {
src: 'src',
dist: 'docs',
tmp: '.tmp',
e2e: 'e2e',
template: '/app/**/*.html',
index: '/app/index.module.js',
templateRoot: 'app/',
cssRoot: 'app/',
bowerJson: '../bowerDocs.json',
};
exports.names = {
module: 'AngularjsDropdownMultiselectExample',
}
/**
* Wiredep is the lib which inject bower dependencies in your project
* Mainly used to inject script tags in the index.html but also used
* to inject css preprocessor deps and js files in karma
*/
exports.wiredep = {
exclude: [/\/bootstrap\.js$/, /\/bootstrap-sass\/.*\.js/, /\/bootstrap\.css/],
directory: 'bower_components',
bowerJson: require('../bowerDocs.json'),
};
/**
* Common implementation for an error handler of a Gulp plugin
*/
exports.errorHandler = function(title) {
'use strict';
return function(err) {
gutil.log(gutil.colors.red('[' + title + ']'), err.toString());
this.emit('end');
};
};
| {
"pile_set_name": "Github"
} |
import React from 'react';
import { render } from 'react-dom';
import { css, include, styles } from 'linaria';
const container = css`
text-align: center;
`;
const button = css`
background-color: #ff0000;
width: 320px;
padding: 20px;
border-radius: 5px;
border: none;
outline: none;
&:hover {
color: #fff;
}
&:active {
position: relative;
top: 2px;
}
@media (max-width: 480px) {
width: 160px;
}
`;
const App = () => (
<div {...styles(container)}>
<button {...styles(button)}>
Click me!
</button>
</div>
);
render(<App />, document.getElementById('content'));
| {
"pile_set_name": "Github"
} |
// =============================================================================
// Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
// Copyright (C) 2012 - DIGITEO - Vincent COUVERT
//
// This file is distributed under the same license as the Scilab package.
// =============================================================================
//
// <-- CLI SHELL MODE -->
//
// <-- Non-regression test for bug 10946 -->
// <-- Short Description -->
// load function (hdf5 based) cannot load a tlist.
//
// <-- Bugzilla URL -->
// http://bugzilla.scilab.org/show_bug.cgi?id=10946
//
// Try to load ref file
lst_reference = tlist(['random numbers';'Name';'Example'], 'Uniform',ones(1,2, 3));
load(SCI+"/modules/hdf5/tests/sample_scilab_data/tlist.sod");
assert_checkequal(lst,lst_reference);
// Try to save the tlist
save(TMPDIR + filesep() + "bug_10946.sod", "lst");
clear lst
load(TMPDIR + filesep() + "bug_10946.sod");
assert_checkequal(lst,lst_reference);
| {
"pile_set_name": "Github"
} |
// Generated by CoffeeScript 1.3.3
(function() {
var BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HEREDOC, HEREDOC_ILLEGAL, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDEXABLE, INVERSES, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NOT_REGEX, NOT_SPACED_REGEX, NUMBER, OPERATOR, REGEX, RELATION, RESERVED, Rewriter, SHIFT, SIMPLESTR, STRICT_PROSCRIBED, TRAILING_SPACES, UNARY, WHITESPACE, compact, count, key, last, starts, _ref, _ref1,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
_ref = require('./rewriter'), Rewriter = _ref.Rewriter, INVERSES = _ref.INVERSES;
_ref1 = require('./helpers'), count = _ref1.count, starts = _ref1.starts, compact = _ref1.compact, last = _ref1.last;
exports.Lexer = Lexer = (function() {
function Lexer() {}
Lexer.prototype.tokenize = function(code, opts) {
var i, tag;
if (opts == null) {
opts = {};
}
if (WHITESPACE.test(code)) {
code = "\n" + code;
}
code = code.replace(/\r/g, '').replace(TRAILING_SPACES, '');
this.code = code;
this.line = opts.line || 0;
this.indent = 0;
this.indebt = 0;
this.outdebt = 0;
this.indents = [];
this.ends = [];
this.tokens = [];
i = 0;
while (this.chunk = code.slice(i)) {
i += this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.heredocToken() || this.stringToken() || this.numberToken() || this.regexToken() || this.jsToken() || this.literalToken();
}
this.closeIndentation();
if (tag = this.ends.pop()) {
this.error("missing " + tag);
}
if (opts.rewrite === false) {
return this.tokens;
}
return (new Rewriter).rewrite(this.tokens);
};
Lexer.prototype.identifierToken = function() {
var colon, forcedIdentifier, id, input, match, prev, tag, _ref2, _ref3;
if (!(match = IDENTIFIER.exec(this.chunk))) {
return 0;
}
input = match[0], id = match[1], colon = match[2];
if (id === 'own' && this.tag() === 'FOR') {
this.token('OWN', id);
return id.length;
}
forcedIdentifier = colon || (prev = last(this.tokens)) && (((_ref2 = prev[0]) === '.' || _ref2 === '?.' || _ref2 === '::') || !prev.spaced && prev[0] === '@');
tag = 'IDENTIFIER';
if (!forcedIdentifier && (__indexOf.call(JS_KEYWORDS, id) >= 0 || __indexOf.call(COFFEE_KEYWORDS, id) >= 0)) {
tag = id.toUpperCase();
if (tag === 'WHEN' && (_ref3 = this.tag(), __indexOf.call(LINE_BREAK, _ref3) >= 0)) {
tag = 'LEADING_WHEN';
} else if (tag === 'FOR') {
this.seenFor = true;
} else if (tag === 'UNLESS') {
tag = 'IF';
} else if (__indexOf.call(UNARY, tag) >= 0) {
tag = 'UNARY';
} else if (__indexOf.call(RELATION, tag) >= 0) {
if (tag !== 'INSTANCEOF' && this.seenFor) {
tag = 'FOR' + tag;
this.seenFor = false;
} else {
tag = 'RELATION';
if (this.value() === '!') {
this.tokens.pop();
id = '!' + id;
}
}
}
}
if (__indexOf.call(JS_FORBIDDEN, id) >= 0) {
if (forcedIdentifier) {
tag = 'IDENTIFIER';
id = new String(id);
id.reserved = true;
} else if (__indexOf.call(RESERVED, id) >= 0) {
this.error("reserved word \"" + id + "\"");
}
}
if (!forcedIdentifier) {
if (__indexOf.call(COFFEE_ALIASES, id) >= 0) {
id = COFFEE_ALIAS_MAP[id];
}
tag = (function() {
switch (id) {
case '!':
return 'UNARY';
case '==':
case '!=':
return 'COMPARE';
case '&&':
case '||':
return 'LOGIC';
case 'true':
case 'false':
return 'BOOL';
case 'break':
case 'continue':
return 'STATEMENT';
default:
return tag;
}
})();
}
this.token(tag, id);
if (colon) {
this.token(':', ':');
}
return input.length;
};
Lexer.prototype.numberToken = function() {
var binaryLiteral, lexedLength, match, number, octalLiteral;
if (!(match = NUMBER.exec(this.chunk))) {
return 0;
}
number = match[0];
if (/^0[BOX]/.test(number)) {
this.error("radix prefix '" + number + "' must be lowercase");
} else if (/E/.test(number) && !/^0x/.test(number)) {
this.error("exponential notation '" + number + "' must be indicated with a lowercase 'e'");
} else if (/^0\d*[89]/.test(number)) {
this.error("decimal literal '" + number + "' must not be prefixed with '0'");
} else if (/^0\d+/.test(number)) {
this.error("octal literal '" + number + "' must be prefixed with '0o'");
}
lexedLength = number.length;
if (octalLiteral = /^0o([0-7]+)/.exec(number)) {
number = '0x' + (parseInt(octalLiteral[1], 8)).toString(16);
}
if (binaryLiteral = /^0b([01]+)/.exec(number)) {
number = '0x' + (parseInt(binaryLiteral[1], 2)).toString(16);
}
this.token('NUMBER', number);
return lexedLength;
};
Lexer.prototype.stringToken = function() {
var match, octalEsc, string;
switch (this.chunk.charAt(0)) {
case "'":
if (!(match = SIMPLESTR.exec(this.chunk))) {
return 0;
}
this.token('STRING', (string = match[0]).replace(MULTILINER, '\\\n'));
break;
case '"':
if (!(string = this.balancedString(this.chunk, '"'))) {
return 0;
}
if (0 < string.indexOf('#{', 1)) {
this.interpolateString(string.slice(1, -1));
} else {
this.token('STRING', this.escapeLines(string));
}
break;
default:
return 0;
}
if (octalEsc = /^(?:\\.|[^\\])*\\(?:0[0-7]|[1-7])/.test(string)) {
this.error("octal escape sequences " + string + " are not allowed");
}
this.line += count(string, '\n');
return string.length;
};
Lexer.prototype.heredocToken = function() {
var doc, heredoc, match, quote;
if (!(match = HEREDOC.exec(this.chunk))) {
return 0;
}
heredoc = match[0];
quote = heredoc.charAt(0);
doc = this.sanitizeHeredoc(match[2], {
quote: quote,
indent: null
});
if (quote === '"' && 0 <= doc.indexOf('#{')) {
this.interpolateString(doc, {
heredoc: true
});
} else {
this.token('STRING', this.makeString(doc, quote, true));
}
this.line += count(heredoc, '\n');
return heredoc.length;
};
Lexer.prototype.commentToken = function() {
var comment, here, match;
if (!(match = this.chunk.match(COMMENT))) {
return 0;
}
comment = match[0], here = match[1];
if (here) {
this.token('HERECOMMENT', this.sanitizeHeredoc(here, {
herecomment: true,
indent: Array(this.indent + 1).join(' ')
}));
}
this.line += count(comment, '\n');
return comment.length;
};
Lexer.prototype.jsToken = function() {
var match, script;
if (!(this.chunk.charAt(0) === '`' && (match = JSTOKEN.exec(this.chunk)))) {
return 0;
}
this.token('JS', (script = match[0]).slice(1, -1));
return script.length;
};
Lexer.prototype.regexToken = function() {
var flags, length, match, prev, regex, _ref2, _ref3;
if (this.chunk.charAt(0) !== '/') {
return 0;
}
if (match = HEREGEX.exec(this.chunk)) {
length = this.heregexToken(match);
this.line += count(match[0], '\n');
return length;
}
prev = last(this.tokens);
if (prev && (_ref2 = prev[0], __indexOf.call((prev.spaced ? NOT_REGEX : NOT_SPACED_REGEX), _ref2) >= 0)) {
return 0;
}
if (!(match = REGEX.exec(this.chunk))) {
return 0;
}
_ref3 = match, match = _ref3[0], regex = _ref3[1], flags = _ref3[2];
if (regex.slice(0, 2) === '/*') {
this.error('regular expressions cannot begin with `*`');
}
if (regex === '//') {
regex = '/(?:)/';
}
this.token('REGEX', "" + regex + flags);
return match.length;
};
Lexer.prototype.heregexToken = function(match) {
var body, flags, heregex, re, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4, _ref5;
heregex = match[0], body = match[1], flags = match[2];
if (0 > body.indexOf('#{')) {
re = body.replace(HEREGEX_OMIT, '').replace(/\//g, '\\/');
if (re.match(/^\*/)) {
this.error('regular expressions cannot begin with `*`');
}
this.token('REGEX', "/" + (re || '(?:)') + "/" + flags);
return heregex.length;
}
this.token('IDENTIFIER', 'RegExp');
this.tokens.push(['CALL_START', '(']);
tokens = [];
_ref2 = this.interpolateString(body, {
regex: true
});
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
_ref3 = _ref2[_i], tag = _ref3[0], value = _ref3[1];
if (tag === 'TOKENS') {
tokens.push.apply(tokens, value);
} else {
if (!(value = value.replace(HEREGEX_OMIT, ''))) {
continue;
}
value = value.replace(/\\/g, '\\\\');
tokens.push(['STRING', this.makeString(value, '"', true)]);
}
tokens.push(['+', '+']);
}
tokens.pop();
if (((_ref4 = tokens[0]) != null ? _ref4[0] : void 0) !== 'STRING') {
this.tokens.push(['STRING', '""'], ['+', '+']);
}
(_ref5 = this.tokens).push.apply(_ref5, tokens);
if (flags) {
this.tokens.push([',', ','], ['STRING', '"' + flags + '"']);
}
this.token(')', ')');
return heregex.length;
};
Lexer.prototype.lineToken = function() {
var diff, indent, match, noNewlines, prev, size;
if (!(match = MULTI_DENT.exec(this.chunk))) {
return 0;
}
indent = match[0];
this.line += count(indent, '\n');
this.seenFor = false;
prev = last(this.tokens, 1);
size = indent.length - 1 - indent.lastIndexOf('\n');
noNewlines = this.unfinished();
if (size - this.indebt === this.indent) {
if (noNewlines) {
this.suppressNewlines();
} else {
this.newlineToken();
}
return indent.length;
}
if (size > this.indent) {
if (noNewlines) {
this.indebt = size - this.indent;
this.suppressNewlines();
return indent.length;
}
diff = size - this.indent + this.outdebt;
this.token('INDENT', diff);
this.indents.push(diff);
this.ends.push('OUTDENT');
this.outdebt = this.indebt = 0;
} else {
this.indebt = 0;
this.outdentToken(this.indent - size, noNewlines);
}
this.indent = size;
return indent.length;
};
Lexer.prototype.outdentToken = function(moveOut, noNewlines) {
var dent, len;
while (moveOut > 0) {
len = this.indents.length - 1;
if (this.indents[len] === void 0) {
moveOut = 0;
} else if (this.indents[len] === this.outdebt) {
moveOut -= this.outdebt;
this.outdebt = 0;
} else if (this.indents[len] < this.outdebt) {
this.outdebt -= this.indents[len];
moveOut -= this.indents[len];
} else {
dent = this.indents.pop() - this.outdebt;
moveOut -= dent;
this.outdebt = 0;
this.pair('OUTDENT');
this.token('OUTDENT', dent);
}
}
if (dent) {
this.outdebt -= moveOut;
}
while (this.value() === ';') {
this.tokens.pop();
}
if (!(this.tag() === 'TERMINATOR' || noNewlines)) {
this.token('TERMINATOR', '\n');
}
return this;
};
Lexer.prototype.whitespaceToken = function() {
var match, nline, prev;
if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) {
return 0;
}
prev = last(this.tokens);
if (prev) {
prev[match ? 'spaced' : 'newLine'] = true;
}
if (match) {
return match[0].length;
} else {
return 0;
}
};
Lexer.prototype.newlineToken = function() {
while (this.value() === ';') {
this.tokens.pop();
}
if (this.tag() !== 'TERMINATOR') {
this.token('TERMINATOR', '\n');
}
return this;
};
Lexer.prototype.suppressNewlines = function() {
if (this.value() === '\\') {
this.tokens.pop();
}
return this;
};
Lexer.prototype.literalToken = function() {
var match, prev, tag, value, _ref2, _ref3, _ref4, _ref5;
if (match = OPERATOR.exec(this.chunk)) {
value = match[0];
if (CODE.test(value)) {
this.tagParameters();
}
} else {
value = this.chunk.charAt(0);
}
tag = value;
prev = last(this.tokens);
if (value === '=' && prev) {
if (!prev[1].reserved && (_ref2 = prev[1], __indexOf.call(JS_FORBIDDEN, _ref2) >= 0)) {
this.error("reserved word \"" + (this.value()) + "\" can't be assigned");
}
if ((_ref3 = prev[1]) === '||' || _ref3 === '&&') {
prev[0] = 'COMPOUND_ASSIGN';
prev[1] += '=';
return value.length;
}
}
if (value === ';') {
this.seenFor = false;
tag = 'TERMINATOR';
} else if (__indexOf.call(MATH, value) >= 0) {
tag = 'MATH';
} else if (__indexOf.call(COMPARE, value) >= 0) {
tag = 'COMPARE';
} else if (__indexOf.call(COMPOUND_ASSIGN, value) >= 0) {
tag = 'COMPOUND_ASSIGN';
} else if (__indexOf.call(UNARY, value) >= 0) {
tag = 'UNARY';
} else if (__indexOf.call(SHIFT, value) >= 0) {
tag = 'SHIFT';
} else if (__indexOf.call(LOGIC, value) >= 0 || value === '?' && (prev != null ? prev.spaced : void 0)) {
tag = 'LOGIC';
} else if (prev && !prev.spaced) {
if (value === '(' && (_ref4 = prev[0], __indexOf.call(CALLABLE, _ref4) >= 0)) {
if (prev[0] === '?') {
prev[0] = 'FUNC_EXIST';
}
tag = 'CALL_START';
} else if (value === '[' && (_ref5 = prev[0], __indexOf.call(INDEXABLE, _ref5) >= 0)) {
tag = 'INDEX_START';
switch (prev[0]) {
case '?':
prev[0] = 'INDEX_SOAK';
}
}
}
switch (value) {
case '(':
case '{':
case '[':
this.ends.push(INVERSES[value]);
break;
case ')':
case '}':
case ']':
this.pair(value);
}
this.token(tag, value);
return value.length;
};
Lexer.prototype.sanitizeHeredoc = function(doc, options) {
var attempt, herecomment, indent, match, _ref2;
indent = options.indent, herecomment = options.herecomment;
if (herecomment) {
if (HEREDOC_ILLEGAL.test(doc)) {
this.error("block comment cannot contain \"*/\", starting");
}
if (doc.indexOf('\n') <= 0) {
return doc;
}
} else {
while (match = HEREDOC_INDENT.exec(doc)) {
attempt = match[1];
if (indent === null || (0 < (_ref2 = attempt.length) && _ref2 < indent.length)) {
indent = attempt;
}
}
}
if (indent) {
doc = doc.replace(RegExp("\\n" + indent, "g"), '\n');
}
if (!herecomment) {
doc = doc.replace(/^\n/, '');
}
return doc;
};
Lexer.prototype.tagParameters = function() {
var i, stack, tok, tokens;
if (this.tag() !== ')') {
return this;
}
stack = [];
tokens = this.tokens;
i = tokens.length;
tokens[--i][0] = 'PARAM_END';
while (tok = tokens[--i]) {
switch (tok[0]) {
case ')':
stack.push(tok);
break;
case '(':
case 'CALL_START':
if (stack.length) {
stack.pop();
} else if (tok[0] === '(') {
tok[0] = 'PARAM_START';
return this;
} else {
return this;
}
}
}
return this;
};
Lexer.prototype.closeIndentation = function() {
return this.outdentToken(this.indent);
};
Lexer.prototype.balancedString = function(str, end) {
var continueCount, i, letter, match, prev, stack, _i, _ref2;
continueCount = 0;
stack = [end];
for (i = _i = 1, _ref2 = str.length; 1 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 1 <= _ref2 ? ++_i : --_i) {
if (continueCount) {
--continueCount;
continue;
}
switch (letter = str.charAt(i)) {
case '\\':
++continueCount;
continue;
case end:
stack.pop();
if (!stack.length) {
return str.slice(0, i + 1 || 9e9);
}
end = stack[stack.length - 1];
continue;
}
if (end === '}' && (letter === '"' || letter === "'")) {
stack.push(end = letter);
} else if (end === '}' && letter === '/' && (match = HEREGEX.exec(str.slice(i)) || REGEX.exec(str.slice(i)))) {
continueCount += match[0].length - 1;
} else if (end === '}' && letter === '{') {
stack.push(end = '}');
} else if (end === '"' && prev === '#' && letter === '{') {
stack.push(end = '}');
}
prev = letter;
}
return this.error("missing " + (stack.pop()) + ", starting");
};
Lexer.prototype.interpolateString = function(str, options) {
var expr, heredoc, i, inner, interpolated, len, letter, nested, pi, regex, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4;
if (options == null) {
options = {};
}
heredoc = options.heredoc, regex = options.regex;
tokens = [];
pi = 0;
i = -1;
while (letter = str.charAt(i += 1)) {
if (letter === '\\') {
i += 1;
continue;
}
if (!(letter === '#' && str.charAt(i + 1) === '{' && (expr = this.balancedString(str.slice(i + 1), '}')))) {
continue;
}
if (pi < i) {
tokens.push(['NEOSTRING', str.slice(pi, i)]);
}
inner = expr.slice(1, -1);
if (inner.length) {
nested = new Lexer().tokenize(inner, {
line: this.line,
rewrite: false
});
nested.pop();
if (((_ref2 = nested[0]) != null ? _ref2[0] : void 0) === 'TERMINATOR') {
nested.shift();
}
if (len = nested.length) {
if (len > 1) {
nested.unshift(['(', '(', this.line]);
nested.push([')', ')', this.line]);
}
tokens.push(['TOKENS', nested]);
}
}
i += expr.length;
pi = i + 1;
}
if ((i > pi && pi < str.length)) {
tokens.push(['NEOSTRING', str.slice(pi)]);
}
if (regex) {
return tokens;
}
if (!tokens.length) {
return this.token('STRING', '""');
}
if (tokens[0][0] !== 'NEOSTRING') {
tokens.unshift(['', '']);
}
if (interpolated = tokens.length > 1) {
this.token('(', '(');
}
for (i = _i = 0, _len = tokens.length; _i < _len; i = ++_i) {
_ref3 = tokens[i], tag = _ref3[0], value = _ref3[1];
if (i) {
this.token('+', '+');
}
if (tag === 'TOKENS') {
(_ref4 = this.tokens).push.apply(_ref4, value);
} else {
this.token('STRING', this.makeString(value, '"', heredoc));
}
}
if (interpolated) {
this.token(')', ')');
}
return tokens;
};
Lexer.prototype.pair = function(tag) {
var size, wanted;
if (tag !== (wanted = last(this.ends))) {
if ('OUTDENT' !== wanted) {
this.error("unmatched " + tag);
}
this.indent -= size = last(this.indents);
this.outdentToken(size, true);
return this.pair(tag);
}
return this.ends.pop();
};
Lexer.prototype.token = function(tag, value) {
return this.tokens.push([tag, value, this.line]);
};
Lexer.prototype.tag = function(index, tag) {
var tok;
return (tok = last(this.tokens, index)) && (tag ? tok[0] = tag : tok[0]);
};
Lexer.prototype.value = function(index, val) {
var tok;
return (tok = last(this.tokens, index)) && (val ? tok[1] = val : tok[1]);
};
Lexer.prototype.unfinished = function() {
var _ref2;
return LINE_CONTINUER.test(this.chunk) || ((_ref2 = this.tag()) === '\\' || _ref2 === '.' || _ref2 === '?.' || _ref2 === 'UNARY' || _ref2 === 'MATH' || _ref2 === '+' || _ref2 === '-' || _ref2 === 'SHIFT' || _ref2 === 'RELATION' || _ref2 === 'COMPARE' || _ref2 === 'LOGIC' || _ref2 === 'THROW' || _ref2 === 'EXTENDS');
};
Lexer.prototype.escapeLines = function(str, heredoc) {
return str.replace(MULTILINER, heredoc ? '\\n' : '');
};
Lexer.prototype.makeString = function(body, quote, heredoc) {
if (!body) {
return quote + quote;
}
body = body.replace(/\\([\s\S])/g, function(match, contents) {
if (contents === '\n' || contents === quote) {
return contents;
} else {
return match;
}
});
body = body.replace(RegExp("" + quote, "g"), '\\$&');
return quote + this.escapeLines(body, heredoc) + quote;
};
Lexer.prototype.error = function(message) {
throw SyntaxError("" + message + " on line " + (this.line + 1));
};
return Lexer;
})();
JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super'];
COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when'];
COFFEE_ALIAS_MAP = {
and: '&&',
or: '||',
is: '==',
isnt: '!=',
not: '!',
yes: 'true',
no: 'false',
on: 'true',
off: 'false'
};
COFFEE_ALIASES = (function() {
var _results;
_results = [];
for (key in COFFEE_ALIAS_MAP) {
_results.push(key);
}
return _results;
})();
COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES);
RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind', '__indexOf', 'implements', 'interface', 'let', 'package', 'private', 'protected', 'public', 'static', 'yield'];
STRICT_PROSCRIBED = ['arguments', 'eval'];
JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED);
exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED);
exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED;
IDENTIFIER = /^([$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)([^\n\S]*:(?!:))?/;
NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i;
HEREDOC = /^("""|''')([\s\S]*?)(?:\n[^\n\S]*)?\1/;
OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/;
WHITESPACE = /^[^\n\S]+/;
COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|(?:###)?$)|^(?:\s*#(?!##[^#]).*)+/;
CODE = /^[-=]>/;
MULTI_DENT = /^(?:\n[^\n\S]*)+/;
SIMPLESTR = /^'[^\\']*(?:\\.[^\\']*)*'/;
JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/;
REGEX = /^(\/(?![\s=])[^[\/\n\\]*(?:(?:\\[\s\S]|\[[^\]\n\\]*(?:\\[\s\S][^\]\n\\]*)*])[^[\/\n\\]*)*\/)([imgy]{0,4})(?!\w)/;
HEREGEX = /^\/{3}([\s\S]+?)\/{3}([imgy]{0,4})(?!\w)/;
HEREGEX_OMIT = /\s+(?:#.*)?/g;
MULTILINER = /\n/g;
HEREDOC_INDENT = /\n+([^\n\S]*)/g;
HEREDOC_ILLEGAL = /\*\//;
LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/;
TRAILING_SPACES = /\s+$/;
COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|='];
UNARY = ['!', '~', 'NEW', 'TYPEOF', 'DELETE', 'DO'];
LOGIC = ['&&', '||', '&', '|', '^'];
SHIFT = ['<<', '>>', '>>>'];
COMPARE = ['==', '!=', '<', '>', '<=', '>='];
MATH = ['*', '/', '%'];
RELATION = ['IN', 'OF', 'INSTANCEOF'];
BOOL = ['TRUE', 'FALSE'];
NOT_REGEX = ['NUMBER', 'REGEX', 'BOOL', 'NULL', 'UNDEFINED', '++', '--', ']'];
NOT_SPACED_REGEX = NOT_REGEX.concat(')', '}', 'THIS', 'IDENTIFIER', 'STRING');
CALLABLE = ['IDENTIFIER', 'STRING', 'REGEX', ')', ']', '}', '?', '::', '@', 'THIS', 'SUPER'];
INDEXABLE = CALLABLE.concat('NUMBER', 'BOOL', 'NULL', 'UNDEFINED');
LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR'];
}).call(this);
| {
"pile_set_name": "Github"
} |
// Copyright(c) 2017 POLYGONTEK
//
// 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.
#pragma once
#include "Core/Object.h"
BE_NAMESPACE_BEGIN
class TagLayerSettings : public Object {
friend class GameSettings;
public:
struct BuiltInLayer {
enum Enum {
Default,
Editor,
UI,
Reserved0,
Reserved1,
Reserved2,
Count
};
};
OBJECT_PROTOTYPE(TagLayerSettings);
TagLayerSettings();
int32_t FindTag(const char *tagName) const;
int32_t FindLayer(const char *layerName) const;
static TagLayerSettings * Load(const char *filename);
private:
Array<Str> tags;
Array<Str> layers;
};
BE_NAMESPACE_END
| {
"pile_set_name": "Github"
} |
/**************************************************************************
***
*** Copyright (c) 1995-2000 Regents of the University of California,
*** Andrew E. Caldwell, Andrew B. Kahng and Igor L. Markov
*** Copyright (c) 2000-2010 Regents of the University of Michigan,
*** Saurabh N. Adya, Jarrod A. Roy, David A. Papa and
*** Igor L. Markov
***
*** Contact author(s): [email protected], [email protected]
*** Original Affiliation: UCLA, Computer Science Department,
*** Los Angeles, CA 90095-1596 USA
***
*** 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.
***
***
***************************************************************************/
//! author="Igor Markov, June 15, 1997"
/*
970622 ilm Added conversions into double and char * for Param
970622 ilm Added type NOPARAM for no parameters.
970723 ilm Changed #include <bool.h> to #include <stl_config.h>
for STL 2.01 compliance
970820 ilm moved enum ParamType inside class Param
added new ctor for use with NOPARAM
allowed for +option as well as -option
added member bool on() to tell if it was +option
970824 ilm took off conversions in class Param
defined classes NoParams, BoolParam, UnsignedParam etc
with unambiguous conversions and clever found()
980313 ilm fixed const-correctness
*/
#ifndef _PARAMPROC_H_
#define _PARAMPROC_H_
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <limits.h>
//#ifndef _MSC_VER
///* Includes from STL for min/max/abs/bool/true/false/etc */
//#include <stl_config.h>
//#endif
#include "abkassert.h"
//:(base class) Catches a given parameter from the command line
class Param
{
public:
enum Type { NOPARAM, BOOL, INT, UNSIGNED, DOUBLE, STRING };
// NOPARAM means "empty command line"
// BOOL means "no value: either found in command line or not"
private:
bool _b; // found
bool _on;
int _i;
unsigned _u;
double _d;
const char * _s;
Type _pt;
const char * _key;
public:
Param(const char * keyy, Type part, int argc, const char * const argv[]);
Param(Type part, int argc, const char * const argv[]); // for NOPARAM only
~Param() {};
bool found() const;
// for any Param::Type, always need to check before anything else
bool on() const;
// for any Param::Type; true if the option was invoked with +
int getInt() const;
unsigned getUnsigned() const;
double getDouble() const;
const char* getString() const;
/* operator double() const; // deprecated : use below classes */
/* operator char* () const; // instead of Param */
};
//:Constructed from argc/argv, returns to true
// if the command line had no parameters
class NoParams : private Param
{
public:
NoParams(int argc, const char * const argv[]):Param(Param::NOPARAM,argc,argv) {}
bool found() const { return Param::found(); }
operator bool() const { return Param::found(); }
using Param::on; // base class member access adjustment
};
//: Catches a given boolean parameter
class BoolParam : private Param
{
public:
BoolParam(const char * key, int argc, const char * const argv[])
: Param(key,Param::BOOL,argc,argv) {}
bool found() const { return Param::found(); }
operator bool() const { return Param::found(); }
using Param::on; // base class member access adjustment
};
//: Catches a given Unsigned parameter
class UnsignedParam : private Param
{
public:
UnsignedParam(const char * key, int argc, const char *const argv[])
: Param(key,Param::UNSIGNED,argc,argv) {}
bool found() const { return Param::found() && getUnsigned()!=unsigned(-1); }
operator unsigned() const { return getUnsigned(); }
using Param::on; // base class member access adjustment
};
//: Catches a given integer parameter
class IntParam : private Param
{
public:
IntParam(const char * key, int argc, const char * const argv[])
: Param(key,Param::INT,argc,argv) {}
bool found() const { return Param::found(); }
operator int() const { return getInt(); }
using Param::on; // base class member access adjustment
};
//: Catches a given double parameter
class DoubleParam : private Param
{
public:
DoubleParam(const char * key, int argc, const char * const argv[])
: Param(key,Param::DOUBLE,argc,argv) {}
bool found() const { return Param::found() && getDouble()!=-1.29384756657; }
operator double() const { return getDouble(); }
using Param::on; // base class member access adjustment
};
//: Catches a given string parameter
class StringParam : private Param
{
public:
StringParam(const char * key, int argc, const char * const argv[])
: Param(key,Param::STRING,argc,argv) {}
bool found() const
{ return Param::found() && strcmp(getString(),"Uninitialized"); }
operator const char*() const { return getString(); }
using Param::on; // base class member access adjustment
};
#endif
| {
"pile_set_name": "Github"
} |
import QtQuick 2.0
import QtQuick.Layouts 1.1
import QuickAndroid 0.1
Page {
actionBar: ActionBar {
title: "Tabs Demonstration"
onActionButtonClicked: back();
height: material.unitHeight + tabs.height
TabBar {
id: tabs
width: parent.width
tabs: colorModel
anchors.bottom: parent.bottom
}
}
property var colorModel: [
{ title: "Blue" },
{ title: "Green" },
{ title: "Yellow" }
]
TabView {
id: tabView
tabBar:tabs
anchors.fill: parent
model: VisualDataModel {
model: colorModel
delegate: Rectangle {
width: tabView.width
height: tabView.height
color: modelData.title
}
}
}
}
| {
"pile_set_name": "Github"
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.protocol;
import java.io.IOException;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
/**
* Exception indicating that a replica is already being recovery.
*/
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class RecoveryInProgressException extends IOException {
private static final long serialVersionUID = 1L;
public RecoveryInProgressException(String msg) {
super(msg);
}
} | {
"pile_set_name": "Github"
} |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2020 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_RENDER_OGL && !SDL_RENDER_DISABLED
#include "SDL_hints.h"
#include "SDL_log.h"
#include "SDL_assert.h"
#include "SDL_opengl.h"
#include "../SDL_sysrender.h"
#include "SDL_shaders_gl.h"
#ifdef __MACOSX__
#include <OpenGL/OpenGL.h>
#endif
/* To prevent unnecessary window recreation,
* these should match the defaults selected in SDL_GL_ResetAttributes
*/
#define RENDERER_CONTEXT_MAJOR 2
#define RENDERER_CONTEXT_MINOR 1
/* OpenGL renderer implementation */
/* Details on optimizing the texture path on Mac OS X:
http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_texturedata/opengl_texturedata.html
*/
/* Used to re-create the window with OpenGL capability */
extern int SDL_RecreateWindow(SDL_Window * window, Uint32 flags);
static const float inv255f = 1.0f / 255.0f;
typedef struct GL_FBOList GL_FBOList;
struct GL_FBOList
{
Uint32 w, h;
GLuint FBO;
GL_FBOList *next;
};
typedef struct
{
SDL_bool viewport_dirty;
SDL_Rect viewport;
SDL_Texture *texture;
SDL_Texture *target;
int drawablew;
int drawableh;
SDL_BlendMode blend;
GL_Shader shader;
SDL_bool cliprect_enabled_dirty;
SDL_bool cliprect_enabled;
SDL_bool cliprect_dirty;
SDL_Rect cliprect;
SDL_bool texturing;
Uint32 color;
Uint32 clear_color;
} GL_DrawStateCache;
typedef struct
{
SDL_GLContext context;
SDL_bool debug_enabled;
SDL_bool GL_ARB_debug_output_supported;
int errors;
char **error_messages;
GLDEBUGPROCARB next_error_callback;
GLvoid *next_error_userparam;
GLenum textype;
SDL_bool GL_ARB_texture_non_power_of_two_supported;
SDL_bool GL_ARB_texture_rectangle_supported;
SDL_bool GL_EXT_framebuffer_object_supported;
GL_FBOList *framebuffers;
/* OpenGL functions */
#define SDL_PROC(ret,func,params) ret (APIENTRY *func) params;
#include "SDL_glfuncs.h"
#undef SDL_PROC
/* Multitexture support */
SDL_bool GL_ARB_multitexture_supported;
PFNGLACTIVETEXTUREARBPROC glActiveTextureARB;
GLint num_texture_units;
PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT;
PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT;
PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT;
PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT;
PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT;
/* Shader support */
GL_ShaderContext *shaders;
GL_DrawStateCache drawstate;
} GL_RenderData;
typedef struct
{
GLuint texture;
GLfloat texw;
GLfloat texh;
GLenum format;
GLenum formattype;
void *pixels;
int pitch;
SDL_Rect locked_rect;
/* YUV texture support */
SDL_bool yuv;
SDL_bool nv12;
GLuint utexture;
GLuint vtexture;
GL_FBOList *fbo;
} GL_TextureData;
SDL_FORCE_INLINE const char*
GL_TranslateError (GLenum error)
{
#define GL_ERROR_TRANSLATE(e) case e: return #e;
switch (error) {
GL_ERROR_TRANSLATE(GL_INVALID_ENUM)
GL_ERROR_TRANSLATE(GL_INVALID_VALUE)
GL_ERROR_TRANSLATE(GL_INVALID_OPERATION)
GL_ERROR_TRANSLATE(GL_OUT_OF_MEMORY)
GL_ERROR_TRANSLATE(GL_NO_ERROR)
GL_ERROR_TRANSLATE(GL_STACK_OVERFLOW)
GL_ERROR_TRANSLATE(GL_STACK_UNDERFLOW)
GL_ERROR_TRANSLATE(GL_TABLE_TOO_LARGE)
default:
return "UNKNOWN";
}
#undef GL_ERROR_TRANSLATE
}
SDL_FORCE_INLINE void
GL_ClearErrors(SDL_Renderer *renderer)
{
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
if (!data->debug_enabled)
{
return;
}
if (data->GL_ARB_debug_output_supported) {
if (data->errors) {
int i;
for (i = 0; i < data->errors; ++i) {
SDL_free(data->error_messages[i]);
}
SDL_free(data->error_messages);
data->errors = 0;
data->error_messages = NULL;
}
} else if (data->glGetError != NULL) {
while (data->glGetError() != GL_NO_ERROR) {
/* continue; */
}
}
}
SDL_FORCE_INLINE int
GL_CheckAllErrors (const char *prefix, SDL_Renderer *renderer, const char *file, int line, const char *function)
{
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
int ret = 0;
if (!data->debug_enabled)
{
return 0;
}
if (data->GL_ARB_debug_output_supported) {
if (data->errors) {
int i;
for (i = 0; i < data->errors; ++i) {
SDL_SetError("%s: %s (%d): %s %s", prefix, file, line, function, data->error_messages[i]);
ret = -1;
}
GL_ClearErrors(renderer);
}
} else {
/* check gl errors (can return multiple errors) */
for (;;) {
GLenum error = data->glGetError();
if (error != GL_NO_ERROR) {
if (prefix == NULL || prefix[0] == '\0') {
prefix = "generic";
}
SDL_SetError("%s: %s (%d): %s %s (0x%X)", prefix, file, line, function, GL_TranslateError(error), error);
ret = -1;
} else {
break;
}
}
}
return ret;
}
#if 0
#define GL_CheckError(prefix, renderer)
#else
#define GL_CheckError(prefix, renderer) GL_CheckAllErrors(prefix, renderer, SDL_FILE, SDL_LINE, SDL_FUNCTION)
#endif
static int
GL_LoadFunctions(GL_RenderData * data)
{
#ifdef __SDL_NOGETPROCADDR__
#define SDL_PROC(ret,func,params) data->func=func;
#else
int retval = 0;
#define SDL_PROC(ret,func,params) \
do { \
data->func = SDL_GL_GetProcAddress(#func); \
if ( ! data->func ) { \
retval = SDL_SetError("Couldn't load GL function %s: %s", #func, SDL_GetError()); \
} \
} while ( 0 );
#endif /* __SDL_NOGETPROCADDR__ */
#include "SDL_glfuncs.h"
#undef SDL_PROC
return retval;
}
static int
GL_ActivateRenderer(SDL_Renderer * renderer)
{
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
if (SDL_GL_GetCurrentContext() != data->context) {
if (SDL_GL_MakeCurrent(renderer->window, data->context) < 0) {
return -1;
}
}
GL_ClearErrors(renderer);
return 0;
}
static void APIENTRY
GL_HandleDebugMessage(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char *message, const void *userParam)
{
SDL_Renderer *renderer = (SDL_Renderer *) userParam;
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
if (type == GL_DEBUG_TYPE_ERROR_ARB) {
/* Record this error */
int errors = data->errors + 1;
char **error_messages = SDL_realloc(data->error_messages, errors * sizeof(*data->error_messages));
if (error_messages) {
data->errors = errors;
data->error_messages = error_messages;
data->error_messages[data->errors-1] = SDL_strdup(message);
}
}
/* If there's another error callback, pass it along, otherwise log it */
if (data->next_error_callback) {
data->next_error_callback(source, type, id, severity, length, message, data->next_error_userparam);
} else {
if (type == GL_DEBUG_TYPE_ERROR_ARB) {
SDL_LogError(SDL_LOG_CATEGORY_RENDER, "%s", message);
} else {
SDL_LogDebug(SDL_LOG_CATEGORY_RENDER, "%s", message);
}
}
}
static GL_FBOList *
GL_GetFBO(GL_RenderData *data, Uint32 w, Uint32 h)
{
GL_FBOList *result = data->framebuffers;
while (result && ((result->w != w) || (result->h != h))) {
result = result->next;
}
if (!result) {
result = SDL_malloc(sizeof(GL_FBOList));
if (result) {
result->w = w;
result->h = h;
data->glGenFramebuffersEXT(1, &result->FBO);
result->next = data->framebuffers;
data->framebuffers = result;
}
}
return result;
}
static int
GL_GetOutputSize(SDL_Renderer * renderer, int *w, int *h)
{
SDL_GL_GetDrawableSize(renderer->window, w, h);
return 0;
}
static GLenum GetBlendFunc(SDL_BlendFactor factor)
{
switch (factor) {
case SDL_BLENDFACTOR_ZERO:
return GL_ZERO;
case SDL_BLENDFACTOR_ONE:
return GL_ONE;
case SDL_BLENDFACTOR_SRC_COLOR:
return GL_SRC_COLOR;
case SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR:
return GL_ONE_MINUS_SRC_COLOR;
case SDL_BLENDFACTOR_SRC_ALPHA:
return GL_SRC_ALPHA;
case SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA:
return GL_ONE_MINUS_SRC_ALPHA;
case SDL_BLENDFACTOR_DST_COLOR:
return GL_DST_COLOR;
case SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR:
return GL_ONE_MINUS_DST_COLOR;
case SDL_BLENDFACTOR_DST_ALPHA:
return GL_DST_ALPHA;
case SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA:
return GL_ONE_MINUS_DST_ALPHA;
default:
return GL_INVALID_ENUM;
}
}
static GLenum GetBlendEquation(SDL_BlendOperation operation)
{
switch (operation) {
case SDL_BLENDOPERATION_ADD:
return GL_FUNC_ADD;
case SDL_BLENDOPERATION_SUBTRACT:
return GL_FUNC_SUBTRACT;
case SDL_BLENDOPERATION_REV_SUBTRACT:
return GL_FUNC_REVERSE_SUBTRACT;
default:
return GL_INVALID_ENUM;
}
}
static SDL_bool
GL_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode)
{
SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode);
SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode);
SDL_BlendOperation colorOperation = SDL_GetBlendModeColorOperation(blendMode);
SDL_BlendFactor dstColorFactor = SDL_GetBlendModeDstColorFactor(blendMode);
SDL_BlendFactor dstAlphaFactor = SDL_GetBlendModeDstAlphaFactor(blendMode);
SDL_BlendOperation alphaOperation = SDL_GetBlendModeAlphaOperation(blendMode);
if (GetBlendFunc(srcColorFactor) == GL_INVALID_ENUM ||
GetBlendFunc(srcAlphaFactor) == GL_INVALID_ENUM ||
GetBlendEquation(colorOperation) == GL_INVALID_ENUM ||
GetBlendFunc(dstColorFactor) == GL_INVALID_ENUM ||
GetBlendFunc(dstAlphaFactor) == GL_INVALID_ENUM ||
GetBlendEquation(alphaOperation) == GL_INVALID_ENUM) {
return SDL_FALSE;
}
if (colorOperation != alphaOperation) {
return SDL_FALSE;
}
return SDL_TRUE;
}
SDL_FORCE_INLINE int
power_of_2(int input)
{
int value = 1;
while (value < input) {
value <<= 1;
}
return value;
}
SDL_FORCE_INLINE SDL_bool
convert_format(GL_RenderData *renderdata, Uint32 pixel_format,
GLint* internalFormat, GLenum* format, GLenum* type)
{
switch (pixel_format) {
case SDL_PIXELFORMAT_ARGB8888:
case SDL_PIXELFORMAT_RGB888:
*internalFormat = GL_RGBA8;
*format = GL_BGRA;
*type = GL_UNSIGNED_INT_8_8_8_8_REV;
break;
case SDL_PIXELFORMAT_ABGR8888:
case SDL_PIXELFORMAT_BGR888:
*internalFormat = GL_RGBA8;
*format = GL_RGBA;
*type = GL_UNSIGNED_INT_8_8_8_8_REV;
break;
case SDL_PIXELFORMAT_YV12:
case SDL_PIXELFORMAT_IYUV:
case SDL_PIXELFORMAT_NV12:
case SDL_PIXELFORMAT_NV21:
*internalFormat = GL_LUMINANCE;
*format = GL_LUMINANCE;
*type = GL_UNSIGNED_BYTE;
break;
#ifdef __MACOSX__
case SDL_PIXELFORMAT_UYVY:
*internalFormat = GL_RGB8;
*format = GL_YCBCR_422_APPLE;
*type = GL_UNSIGNED_SHORT_8_8_APPLE;
break;
#endif
default:
return SDL_FALSE;
}
return SDL_TRUE;
}
static int
GL_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
GL_RenderData *renderdata = (GL_RenderData *) renderer->driverdata;
const GLenum textype = renderdata->textype;
GL_TextureData *data;
GLint internalFormat;
GLenum format, type;
int texture_w, texture_h;
GLenum scaleMode;
GL_ActivateRenderer(renderer);
renderdata->drawstate.texture = NULL; /* we trash this state. */
if (texture->access == SDL_TEXTUREACCESS_TARGET &&
!renderdata->GL_EXT_framebuffer_object_supported) {
return SDL_SetError("Render targets not supported by OpenGL");
}
if (!convert_format(renderdata, texture->format, &internalFormat,
&format, &type)) {
return SDL_SetError("Texture format %s not supported by OpenGL",
SDL_GetPixelFormatName(texture->format));
}
data = (GL_TextureData *) SDL_calloc(1, sizeof(*data));
if (!data) {
return SDL_OutOfMemory();
}
if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
size_t size;
data->pitch = texture->w * SDL_BYTESPERPIXEL(texture->format);
size = texture->h * data->pitch;
if (texture->format == SDL_PIXELFORMAT_YV12 ||
texture->format == SDL_PIXELFORMAT_IYUV) {
/* Need to add size for the U and V planes */
size += 2 * ((texture->h + 1) / 2) * ((data->pitch + 1) / 2);
}
if (texture->format == SDL_PIXELFORMAT_NV12 ||
texture->format == SDL_PIXELFORMAT_NV21) {
/* Need to add size for the U/V plane */
size += 2 * ((texture->h + 1) / 2) * ((data->pitch + 1) / 2);
}
data->pixels = SDL_calloc(1, size);
if (!data->pixels) {
SDL_free(data);
return SDL_OutOfMemory();
}
}
if (texture->access == SDL_TEXTUREACCESS_TARGET) {
data->fbo = GL_GetFBO(renderdata, texture->w, texture->h);
} else {
data->fbo = NULL;
}
GL_CheckError("", renderer);
renderdata->glGenTextures(1, &data->texture);
if (GL_CheckError("glGenTextures()", renderer) < 0) {
if (data->pixels) {
SDL_free(data->pixels);
}
SDL_free(data);
return -1;
}
texture->driverdata = data;
if (renderdata->GL_ARB_texture_non_power_of_two_supported) {
texture_w = texture->w;
texture_h = texture->h;
data->texw = 1.0f;
data->texh = 1.0f;
} else if (renderdata->GL_ARB_texture_rectangle_supported) {
texture_w = texture->w;
texture_h = texture->h;
data->texw = (GLfloat) texture_w;
data->texh = (GLfloat) texture_h;
} else {
texture_w = power_of_2(texture->w);
texture_h = power_of_2(texture->h);
data->texw = (GLfloat) (texture->w) / texture_w;
data->texh = (GLfloat) texture->h / texture_h;
}
data->format = format;
data->formattype = type;
scaleMode = (texture->scaleMode == SDL_ScaleModeNearest) ? GL_NEAREST : GL_LINEAR;
renderdata->glEnable(textype);
renderdata->glBindTexture(textype, data->texture);
renderdata->glTexParameteri(textype, GL_TEXTURE_MIN_FILTER, scaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_MAG_FILTER, scaleMode);
/* According to the spec, CLAMP_TO_EDGE is the default for TEXTURE_RECTANGLE
and setting it causes an INVALID_ENUM error in the latest NVidia drivers.
*/
if (textype != GL_TEXTURE_RECTANGLE_ARB) {
renderdata->glTexParameteri(textype, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
renderdata->glTexParameteri(textype, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
}
#ifdef __MACOSX__
#ifndef GL_TEXTURE_STORAGE_HINT_APPLE
#define GL_TEXTURE_STORAGE_HINT_APPLE 0x85BC
#endif
#ifndef STORAGE_CACHED_APPLE
#define STORAGE_CACHED_APPLE 0x85BE
#endif
#ifndef STORAGE_SHARED_APPLE
#define STORAGE_SHARED_APPLE 0x85BF
#endif
if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
renderdata->glTexParameteri(textype, GL_TEXTURE_STORAGE_HINT_APPLE,
GL_STORAGE_SHARED_APPLE);
} else {
renderdata->glTexParameteri(textype, GL_TEXTURE_STORAGE_HINT_APPLE,
GL_STORAGE_CACHED_APPLE);
}
if (texture->access == SDL_TEXTUREACCESS_STREAMING
&& texture->format == SDL_PIXELFORMAT_ARGB8888
&& (texture->w % 8) == 0) {
renderdata->glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
renderdata->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH,
(data->pitch / SDL_BYTESPERPIXEL(texture->format)));
renderdata->glTexImage2D(textype, 0, internalFormat, texture_w,
texture_h, 0, format, type, data->pixels);
renderdata->glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
}
else
#endif
{
renderdata->glTexImage2D(textype, 0, internalFormat, texture_w,
texture_h, 0, format, type, NULL);
}
renderdata->glDisable(textype);
if (GL_CheckError("glTexImage2D()", renderer) < 0) {
return -1;
}
if (texture->format == SDL_PIXELFORMAT_YV12 ||
texture->format == SDL_PIXELFORMAT_IYUV) {
data->yuv = SDL_TRUE;
renderdata->glGenTextures(1, &data->utexture);
renderdata->glGenTextures(1, &data->vtexture);
renderdata->glEnable(textype);
renderdata->glBindTexture(textype, data->utexture);
renderdata->glTexParameteri(textype, GL_TEXTURE_MIN_FILTER,
scaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_MAG_FILTER,
scaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
renderdata->glTexParameteri(textype, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
renderdata->glTexImage2D(textype, 0, internalFormat, (texture_w+1)/2,
(texture_h+1)/2, 0, format, type, NULL);
renderdata->glBindTexture(textype, data->vtexture);
renderdata->glTexParameteri(textype, GL_TEXTURE_MIN_FILTER,
scaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_MAG_FILTER,
scaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
renderdata->glTexParameteri(textype, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
renderdata->glTexImage2D(textype, 0, internalFormat, (texture_w+1)/2,
(texture_h+1)/2, 0, format, type, NULL);
renderdata->glDisable(textype);
}
if (texture->format == SDL_PIXELFORMAT_NV12 ||
texture->format == SDL_PIXELFORMAT_NV21) {
data->nv12 = SDL_TRUE;
renderdata->glGenTextures(1, &data->utexture);
renderdata->glEnable(textype);
renderdata->glBindTexture(textype, data->utexture);
renderdata->glTexParameteri(textype, GL_TEXTURE_MIN_FILTER,
scaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_MAG_FILTER,
scaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
renderdata->glTexParameteri(textype, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
renderdata->glTexImage2D(textype, 0, GL_LUMINANCE_ALPHA, (texture_w+1)/2,
(texture_h+1)/2, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, NULL);
renderdata->glDisable(textype);
}
return GL_CheckError("", renderer);
}
static int
GL_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
const SDL_Rect * rect, const void *pixels, int pitch)
{
GL_RenderData *renderdata = (GL_RenderData *) renderer->driverdata;
const GLenum textype = renderdata->textype;
GL_TextureData *data = (GL_TextureData *) texture->driverdata;
const int texturebpp = SDL_BYTESPERPIXEL(texture->format);
SDL_assert(texturebpp != 0); /* otherwise, division by zero later. */
GL_ActivateRenderer(renderer);
renderdata->drawstate.texture = NULL; /* we trash this state. */
renderdata->glEnable(textype);
renderdata->glBindTexture(textype, data->texture);
renderdata->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, (pitch / texturebpp));
renderdata->glTexSubImage2D(textype, 0, rect->x, rect->y, rect->w,
rect->h, data->format, data->formattype,
pixels);
if (data->yuv) {
renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, ((pitch + 1) / 2));
/* Skip to the correct offset into the next texture */
pixels = (const void*)((const Uint8*)pixels + rect->h * pitch);
if (texture->format == SDL_PIXELFORMAT_YV12) {
renderdata->glBindTexture(textype, data->vtexture);
} else {
renderdata->glBindTexture(textype, data->utexture);
}
renderdata->glTexSubImage2D(textype, 0, rect->x/2, rect->y/2,
(rect->w+1)/2, (rect->h+1)/2,
data->format, data->formattype, pixels);
/* Skip to the correct offset into the next texture */
pixels = (const void*)((const Uint8*)pixels + ((rect->h + 1) / 2) * ((pitch + 1) / 2));
if (texture->format == SDL_PIXELFORMAT_YV12) {
renderdata->glBindTexture(textype, data->utexture);
} else {
renderdata->glBindTexture(textype, data->vtexture);
}
renderdata->glTexSubImage2D(textype, 0, rect->x/2, rect->y/2,
(rect->w+1)/2, (rect->h+1)/2,
data->format, data->formattype, pixels);
}
if (data->nv12) {
renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, ((pitch + 1) / 2));
/* Skip to the correct offset into the next texture */
pixels = (const void*)((const Uint8*)pixels + rect->h * pitch);
renderdata->glBindTexture(textype, data->utexture);
renderdata->glTexSubImage2D(textype, 0, rect->x/2, rect->y/2,
(rect->w + 1)/2, (rect->h + 1)/2,
GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, pixels);
}
renderdata->glDisable(textype);
return GL_CheckError("glTexSubImage2D()", renderer);
}
static int
GL_UpdateTextureYUV(SDL_Renderer * renderer, SDL_Texture * texture,
const SDL_Rect * rect,
const Uint8 *Yplane, int Ypitch,
const Uint8 *Uplane, int Upitch,
const Uint8 *Vplane, int Vpitch)
{
GL_RenderData *renderdata = (GL_RenderData *) renderer->driverdata;
const GLenum textype = renderdata->textype;
GL_TextureData *data = (GL_TextureData *) texture->driverdata;
GL_ActivateRenderer(renderer);
renderdata->drawstate.texture = NULL; /* we trash this state. */
renderdata->glEnable(textype);
renderdata->glBindTexture(textype, data->texture);
renderdata->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, Ypitch);
renderdata->glTexSubImage2D(textype, 0, rect->x, rect->y, rect->w,
rect->h, data->format, data->formattype,
Yplane);
renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, Upitch);
renderdata->glBindTexture(textype, data->utexture);
renderdata->glTexSubImage2D(textype, 0, rect->x/2, rect->y/2,
(rect->w + 1)/2, (rect->h + 1)/2,
data->format, data->formattype, Uplane);
renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, Vpitch);
renderdata->glBindTexture(textype, data->vtexture);
renderdata->glTexSubImage2D(textype, 0, rect->x/2, rect->y/2,
(rect->w + 1)/2, (rect->h + 1)/2,
data->format, data->formattype, Vplane);
renderdata->glDisable(textype);
return GL_CheckError("glTexSubImage2D()", renderer);
}
static int
GL_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture,
const SDL_Rect * rect, void **pixels, int *pitch)
{
GL_TextureData *data = (GL_TextureData *) texture->driverdata;
data->locked_rect = *rect;
*pixels =
(void *) ((Uint8 *) data->pixels + rect->y * data->pitch +
rect->x * SDL_BYTESPERPIXEL(texture->format));
*pitch = data->pitch;
return 0;
}
static void
GL_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
GL_TextureData *data = (GL_TextureData *) texture->driverdata;
const SDL_Rect *rect;
void *pixels;
rect = &data->locked_rect;
pixels =
(void *) ((Uint8 *) data->pixels + rect->y * data->pitch +
rect->x * SDL_BYTESPERPIXEL(texture->format));
GL_UpdateTexture(renderer, texture, rect, pixels, data->pitch);
}
static void
GL_SetTextureScaleMode(SDL_Renderer * renderer, SDL_Texture * texture, SDL_ScaleMode scaleMode)
{
GL_RenderData *renderdata = (GL_RenderData *) renderer->driverdata;
const GLenum textype = renderdata->textype;
GL_TextureData *data = (GL_TextureData *) texture->driverdata;
GLenum glScaleMode = (scaleMode == SDL_ScaleModeNearest) ? GL_NEAREST : GL_LINEAR;
renderdata->glEnable(textype);
renderdata->glBindTexture(textype, data->texture);
renderdata->glTexParameteri(textype, GL_TEXTURE_MIN_FILTER, glScaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_MAG_FILTER, glScaleMode);
renderdata->glDisable(textype);
if (texture->format == SDL_PIXELFORMAT_YV12 ||
texture->format == SDL_PIXELFORMAT_IYUV) {
renderdata->glEnable(textype);
renderdata->glBindTexture(textype, data->utexture);
renderdata->glTexParameteri(textype, GL_TEXTURE_MIN_FILTER, glScaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_MAG_FILTER, glScaleMode);
renderdata->glBindTexture(textype, data->vtexture);
renderdata->glTexParameteri(textype, GL_TEXTURE_MIN_FILTER, glScaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_MAG_FILTER, glScaleMode);
renderdata->glDisable(textype);
}
if (texture->format == SDL_PIXELFORMAT_NV12 ||
texture->format == SDL_PIXELFORMAT_NV21) {
renderdata->glEnable(textype);
renderdata->glBindTexture(textype, data->utexture);
renderdata->glTexParameteri(textype, GL_TEXTURE_MIN_FILTER, glScaleMode);
renderdata->glTexParameteri(textype, GL_TEXTURE_MAG_FILTER, glScaleMode);
renderdata->glDisable(textype);
}
}
static int
GL_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture)
{
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
GL_TextureData *texturedata;
GLenum status;
GL_ActivateRenderer(renderer);
if (!data->GL_EXT_framebuffer_object_supported) {
return SDL_SetError("Render targets not supported by OpenGL");
}
data->drawstate.viewport_dirty = SDL_TRUE;
if (texture == NULL) {
data->glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
return 0;
}
texturedata = (GL_TextureData *) texture->driverdata;
data->glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, texturedata->fbo->FBO);
/* TODO: check if texture pixel format allows this operation */
data->glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, data->textype, texturedata->texture, 0);
/* Check FBO status */
status = data->glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
return SDL_SetError("glFramebufferTexture2DEXT() failed");
}
return 0;
}
/* !!! FIXME: all these Queue* calls set up the vertex buffer the way the immediate mode
!!! FIXME: renderer wants it, but this might want to operate differently if we move to
!!! FIXME: VBOs at some point. */
static int
GL_QueueSetViewport(SDL_Renderer * renderer, SDL_RenderCommand *cmd)
{
return 0; /* nothing to do in this backend. */
}
static int
GL_QueueDrawPoints(SDL_Renderer * renderer, SDL_RenderCommand *cmd, const SDL_FPoint * points, int count)
{
GLfloat *verts = (GLfloat *) SDL_AllocateRenderVertices(renderer, count * 2 * sizeof (GLfloat), 0, &cmd->data.draw.first);
int i;
if (!verts) {
return -1;
}
cmd->data.draw.count = count;
for (i = 0; i < count; i++) {
*(verts++) = 0.5f + points[i].x;
*(verts++) = 0.5f + points[i].y;
}
return 0;
}
static int
GL_QueueFillRects(SDL_Renderer * renderer, SDL_RenderCommand *cmd, const SDL_FRect * rects, int count)
{
GLfloat *verts = (GLfloat *) SDL_AllocateRenderVertices(renderer, count * 4 * sizeof (GLfloat), 0, &cmd->data.draw.first);
int i;
if (!verts) {
return -1;
}
cmd->data.draw.count = count;
for (i = 0; i < count; i++) {
const SDL_FRect *rect = &rects[i];
*(verts++) = rect->x;
*(verts++) = rect->y;
*(verts++) = rect->x + rect->w;
*(verts++) = rect->y + rect->h;
}
return 0;
}
static int
GL_QueueCopy(SDL_Renderer * renderer, SDL_RenderCommand *cmd, SDL_Texture * texture,
const SDL_Rect * srcrect, const SDL_FRect * dstrect)
{
GL_TextureData *texturedata = (GL_TextureData *) texture->driverdata;
GLfloat minx, miny, maxx, maxy;
GLfloat minu, maxu, minv, maxv;
GLfloat *verts = (GLfloat *) SDL_AllocateRenderVertices(renderer, 8 * sizeof (GLfloat), 0, &cmd->data.draw.first);
if (!verts) {
return -1;
}
cmd->data.draw.count = 1;
minx = dstrect->x;
miny = dstrect->y;
maxx = dstrect->x + dstrect->w;
maxy = dstrect->y + dstrect->h;
minu = (GLfloat) srcrect->x / texture->w;
minu *= texturedata->texw;
maxu = (GLfloat) (srcrect->x + srcrect->w) / texture->w;
maxu *= texturedata->texw;
minv = (GLfloat) srcrect->y / texture->h;
minv *= texturedata->texh;
maxv = (GLfloat) (srcrect->y + srcrect->h) / texture->h;
maxv *= texturedata->texh;
cmd->data.draw.count = 1;
*(verts++) = minx;
*(verts++) = miny;
*(verts++) = maxx;
*(verts++) = maxy;
*(verts++) = minu;
*(verts++) = maxu;
*(verts++) = minv;
*(verts++) = maxv;
return 0;
}
static int
GL_QueueCopyEx(SDL_Renderer * renderer, SDL_RenderCommand *cmd, SDL_Texture * texture,
const SDL_Rect * srcrect, const SDL_FRect * dstrect,
const double angle, const SDL_FPoint *center, const SDL_RendererFlip flip)
{
GL_TextureData *texturedata = (GL_TextureData *) texture->driverdata;
GLfloat minx, miny, maxx, maxy;
GLfloat centerx, centery;
GLfloat minu, maxu, minv, maxv;
GLfloat *verts = (GLfloat *) SDL_AllocateRenderVertices(renderer, 11 * sizeof (GLfloat), 0, &cmd->data.draw.first);
if (!verts) {
return -1;
}
centerx = center->x;
centery = center->y;
if (flip & SDL_FLIP_HORIZONTAL) {
minx = dstrect->w - centerx;
maxx = -centerx;
}
else {
minx = -centerx;
maxx = dstrect->w - centerx;
}
if (flip & SDL_FLIP_VERTICAL) {
miny = dstrect->h - centery;
maxy = -centery;
}
else {
miny = -centery;
maxy = dstrect->h - centery;
}
minu = (GLfloat) srcrect->x / texture->w;
minu *= texturedata->texw;
maxu = (GLfloat) (srcrect->x + srcrect->w) / texture->w;
maxu *= texturedata->texw;
minv = (GLfloat) srcrect->y / texture->h;
minv *= texturedata->texh;
maxv = (GLfloat) (srcrect->y + srcrect->h) / texture->h;
maxv *= texturedata->texh;
cmd->data.draw.count = 1;
*(verts++) = minx;
*(verts++) = miny;
*(verts++) = maxx;
*(verts++) = maxy;
*(verts++) = minu;
*(verts++) = maxu;
*(verts++) = minv;
*(verts++) = maxv;
*(verts++) = (GLfloat) dstrect->x + centerx;
*(verts++) = (GLfloat) dstrect->y + centery;
*(verts++) = (GLfloat) angle;
return 0;
}
static void
SetDrawState(GL_RenderData *data, const SDL_RenderCommand *cmd, const GL_Shader shader)
{
const SDL_BlendMode blend = cmd->data.draw.blend;
if (data->drawstate.viewport_dirty) {
const SDL_bool istarget = data->drawstate.target != NULL;
const SDL_Rect *viewport = &data->drawstate.viewport;
data->glMatrixMode(GL_PROJECTION);
data->glLoadIdentity();
data->glViewport(viewport->x,
istarget ? viewport->y : (data->drawstate.drawableh - viewport->y - viewport->h),
viewport->w, viewport->h);
if (viewport->w && viewport->h) {
data->glOrtho((GLdouble) 0, (GLdouble) viewport->w,
(GLdouble) istarget ? 0 : viewport->h,
(GLdouble) istarget ? viewport->h : 0,
0.0, 1.0);
}
data->glMatrixMode(GL_MODELVIEW);
data->drawstate.viewport_dirty = SDL_FALSE;
}
if (data->drawstate.cliprect_enabled_dirty) {
if (!data->drawstate.cliprect_enabled) {
data->glDisable(GL_SCISSOR_TEST);
} else {
data->glEnable(GL_SCISSOR_TEST);
}
data->drawstate.cliprect_enabled_dirty = SDL_FALSE;
}
if (data->drawstate.cliprect_enabled && data->drawstate.cliprect_dirty) {
const SDL_Rect *viewport = &data->drawstate.viewport;
const SDL_Rect *rect = &data->drawstate.cliprect;
data->glScissor(viewport->x + rect->x,
data->drawstate.target ? viewport->y + rect->y : data->drawstate.drawableh - viewport->y - rect->y - rect->h,
rect->w, rect->h);
data->drawstate.cliprect_dirty = SDL_FALSE;
}
if (blend != data->drawstate.blend) {
if (blend == SDL_BLENDMODE_NONE) {
data->glDisable(GL_BLEND);
} else {
data->glEnable(GL_BLEND);
data->glBlendFuncSeparate(GetBlendFunc(SDL_GetBlendModeSrcColorFactor(blend)),
GetBlendFunc(SDL_GetBlendModeDstColorFactor(blend)),
GetBlendFunc(SDL_GetBlendModeSrcAlphaFactor(blend)),
GetBlendFunc(SDL_GetBlendModeDstAlphaFactor(blend)));
data->glBlendEquation(GetBlendEquation(SDL_GetBlendModeColorOperation(blend)));
}
data->drawstate.blend = blend;
}
if (data->shaders && (shader != data->drawstate.shader)) {
GL_SelectShader(data->shaders, shader);
data->drawstate.shader = shader;
}
if ((cmd->data.draw.texture != NULL) != data->drawstate.texturing) {
if (cmd->data.draw.texture == NULL) {
data->glDisable(data->textype);
data->drawstate.texturing = SDL_FALSE;
} else {
data->glEnable(data->textype);
data->drawstate.texturing = SDL_TRUE;
}
}
}
static void
SetCopyState(GL_RenderData *data, const SDL_RenderCommand *cmd)
{
SDL_Texture *texture = cmd->data.draw.texture;
const GL_TextureData *texturedata = (GL_TextureData *) texture->driverdata;
GL_Shader shader;
if (texture->format == SDL_PIXELFORMAT_ABGR8888 || texture->format == SDL_PIXELFORMAT_ARGB8888) {
shader = SHADER_RGBA;
} else {
shader = SHADER_RGB;
}
if (data->shaders) {
if (texturedata->yuv || texturedata->nv12) {
switch (SDL_GetYUVConversionModeForResolution(texture->w, texture->h)) {
case SDL_YUV_CONVERSION_JPEG:
if (texturedata->yuv) {
shader = SHADER_YUV_JPEG;
} else if (texture->format == SDL_PIXELFORMAT_NV12) {
shader = SHADER_NV12_JPEG;
} else {
shader = SHADER_NV21_JPEG;
}
break;
case SDL_YUV_CONVERSION_BT601:
if (texturedata->yuv) {
shader = SHADER_YUV_BT601;
} else if (texture->format == SDL_PIXELFORMAT_NV12) {
shader = SHADER_NV12_BT601;
} else {
shader = SHADER_NV21_BT601;
}
break;
case SDL_YUV_CONVERSION_BT709:
if (texturedata->yuv) {
shader = SHADER_YUV_BT709;
} else if (texture->format == SDL_PIXELFORMAT_NV12) {
shader = SHADER_NV12_BT709;
} else {
shader = SHADER_NV21_BT709;
}
break;
default:
SDL_assert(!"unsupported YUV conversion mode");
break;
}
}
}
SetDrawState(data, cmd, shader);
if (texture != data->drawstate.texture) {
const GLenum textype = data->textype;
if (texturedata->yuv) {
data->glActiveTextureARB(GL_TEXTURE2_ARB);
data->glBindTexture(textype, texturedata->vtexture);
data->glActiveTextureARB(GL_TEXTURE1_ARB);
data->glBindTexture(textype, texturedata->utexture);
}
if (texturedata->nv12) {
data->glActiveTextureARB(GL_TEXTURE1_ARB);
data->glBindTexture(textype, texturedata->utexture);
}
data->glActiveTextureARB(GL_TEXTURE0_ARB);
data->glBindTexture(textype, texturedata->texture);
data->drawstate.texture = texture;
}
}
static int
GL_RunCommandQueue(SDL_Renderer * renderer, SDL_RenderCommand *cmd, void *vertices, size_t vertsize)
{
/* !!! FIXME: it'd be nice to use a vertex buffer instead of immediate mode... */
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
size_t i;
if (GL_ActivateRenderer(renderer) < 0) {
return -1;
}
data->drawstate.target = renderer->target;
if (!data->drawstate.target) {
SDL_GL_GetDrawableSize(renderer->window, &data->drawstate.drawablew, &data->drawstate.drawableh);
}
while (cmd) {
switch (cmd->command) {
case SDL_RENDERCMD_SETDRAWCOLOR: {
const Uint8 r = cmd->data.color.r;
const Uint8 g = cmd->data.color.g;
const Uint8 b = cmd->data.color.b;
const Uint8 a = cmd->data.color.a;
const Uint32 color = ((a << 24) | (r << 16) | (g << 8) | b);
if (color != data->drawstate.color) {
data->glColor4f((GLfloat) r * inv255f,
(GLfloat) g * inv255f,
(GLfloat) b * inv255f,
(GLfloat) a * inv255f);
data->drawstate.color = color;
}
break;
}
case SDL_RENDERCMD_SETVIEWPORT: {
SDL_Rect *viewport = &data->drawstate.viewport;
if (SDL_memcmp(viewport, &cmd->data.viewport.rect, sizeof (SDL_Rect)) != 0) {
SDL_memcpy(viewport, &cmd->data.viewport.rect, sizeof (SDL_Rect));
data->drawstate.viewport_dirty = SDL_TRUE;
}
break;
}
case SDL_RENDERCMD_SETCLIPRECT: {
const SDL_Rect *rect = &cmd->data.cliprect.rect;
if (data->drawstate.cliprect_enabled != cmd->data.cliprect.enabled) {
data->drawstate.cliprect_enabled = cmd->data.cliprect.enabled;
data->drawstate.cliprect_enabled_dirty = SDL_TRUE;
}
if (SDL_memcmp(&data->drawstate.cliprect, rect, sizeof (SDL_Rect)) != 0) {
SDL_memcpy(&data->drawstate.cliprect, rect, sizeof (SDL_Rect));
data->drawstate.cliprect_dirty = SDL_TRUE;
}
break;
}
case SDL_RENDERCMD_CLEAR: {
const Uint8 r = cmd->data.color.r;
const Uint8 g = cmd->data.color.g;
const Uint8 b = cmd->data.color.b;
const Uint8 a = cmd->data.color.a;
const Uint32 color = ((a << 24) | (r << 16) | (g << 8) | b);
if (color != data->drawstate.clear_color) {
const GLfloat fr = ((GLfloat) r) * inv255f;
const GLfloat fg = ((GLfloat) g) * inv255f;
const GLfloat fb = ((GLfloat) b) * inv255f;
const GLfloat fa = ((GLfloat) a) * inv255f;
data->glClearColor(fr, fg, fb, fa);
data->drawstate.clear_color = color;
}
if (data->drawstate.cliprect_enabled || data->drawstate.cliprect_enabled_dirty) {
data->glDisable(GL_SCISSOR_TEST);
data->drawstate.cliprect_enabled_dirty = data->drawstate.cliprect_enabled;
}
data->glClear(GL_COLOR_BUFFER_BIT);
break;
}
case SDL_RENDERCMD_DRAW_POINTS: {
const size_t count = cmd->data.draw.count;
const GLfloat *verts = (GLfloat *) (((Uint8 *) vertices) + cmd->data.draw.first);
SetDrawState(data, cmd, SHADER_SOLID);
data->glBegin(GL_POINTS);
for (i = 0; i < count; i++, verts += 2) {
data->glVertex2f(verts[0], verts[1]);
}
data->glEnd();
break;
}
case SDL_RENDERCMD_DRAW_LINES: {
const GLfloat *verts = (GLfloat *) (((Uint8 *) vertices) + cmd->data.draw.first);
const size_t count = cmd->data.draw.count;
SetDrawState(data, cmd, SHADER_SOLID);
if (count > 2 && (verts[0] == verts[(count-1)*2]) && (verts[1] == verts[(count*2)-1])) {
data->glBegin(GL_LINE_LOOP);
/* GL_LINE_LOOP takes care of the final segment */
for (i = 1; i < count; ++i, verts += 2) {
data->glVertex2f(verts[0], verts[1]);
}
data->glEnd();
} else {
#if defined(__MACOSX__) || defined(__WIN32__)
#else
int x1, y1, x2, y2;
#endif
data->glBegin(GL_LINE_STRIP);
for (i = 0; i < count; ++i, verts += 2) {
data->glVertex2f(verts[0], verts[1]);
}
data->glEnd();
verts -= 2 * count;
/* The line is half open, so we need one more point to complete it.
* http://www.opengl.org/documentation/specs/version1.1/glspec1.1/node47.html
* If we have to, we can use vertical line and horizontal line textures
* for vertical and horizontal lines, and then create custom textures
* for diagonal lines and software render those. It's terrible, but at
* least it would be pixel perfect.
*/
data->glBegin(GL_POINTS);
#if defined(__MACOSX__) || defined(__WIN32__)
/* Mac OS X and Windows seem to always leave the last point open */
data->glVertex2f(verts[(count-1)*2], verts[(count*2)-1]);
#else
/* Linux seems to leave the right-most or bottom-most point open */
x1 = verts[0];
y1 = verts[1];
x2 = verts[(count-1)*2];
y2 = verts[(count*2)-1];
if (x1 > x2) {
data->glVertex2f(x1, y1);
} else if (x2 > x1) {
data->glVertex2f(x2, y2);
}
if (y1 > y2) {
data->glVertex2f(x1, y1);
} else if (y2 > y1) {
data->glVertex2f(x2, y2);
}
#endif
data->glEnd();
}
break;
}
case SDL_RENDERCMD_FILL_RECTS: {
const size_t count = cmd->data.draw.count;
const GLfloat *verts = (GLfloat *) (((Uint8 *) vertices) + cmd->data.draw.first);
SetDrawState(data, cmd, SHADER_SOLID);
for (i = 0; i < count; ++i, verts += 4) {
data->glRectf(verts[0], verts[1], verts[2], verts[3]);
}
break;
}
case SDL_RENDERCMD_COPY: {
const GLfloat *verts = (GLfloat *) (((Uint8 *) vertices) + cmd->data.draw.first);
const GLfloat minx = verts[0];
const GLfloat miny = verts[1];
const GLfloat maxx = verts[2];
const GLfloat maxy = verts[3];
const GLfloat minu = verts[4];
const GLfloat maxu = verts[5];
const GLfloat minv = verts[6];
const GLfloat maxv = verts[7];
SetCopyState(data, cmd);
data->glBegin(GL_TRIANGLE_STRIP);
data->glTexCoord2f(minu, minv);
data->glVertex2f(minx, miny);
data->glTexCoord2f(maxu, minv);
data->glVertex2f(maxx, miny);
data->glTexCoord2f(minu, maxv);
data->glVertex2f(minx, maxy);
data->glTexCoord2f(maxu, maxv);
data->glVertex2f(maxx, maxy);
data->glEnd();
break;
}
case SDL_RENDERCMD_COPY_EX: {
const GLfloat *verts = (GLfloat *) (((Uint8 *) vertices) + cmd->data.draw.first);
const GLfloat minx = verts[0];
const GLfloat miny = verts[1];
const GLfloat maxx = verts[2];
const GLfloat maxy = verts[3];
const GLfloat minu = verts[4];
const GLfloat maxu = verts[5];
const GLfloat minv = verts[6];
const GLfloat maxv = verts[7];
const GLfloat translatex = verts[8];
const GLfloat translatey = verts[9];
const GLdouble angle = verts[10];
SetCopyState(data, cmd);
/* Translate to flip, rotate, translate to position */
data->glPushMatrix();
data->glTranslatef(translatex, translatey, 0.0f);
data->glRotated(angle, 0.0, 0.0, 1.0);
data->glBegin(GL_TRIANGLE_STRIP);
data->glTexCoord2f(minu, minv);
data->glVertex2f(minx, miny);
data->glTexCoord2f(maxu, minv);
data->glVertex2f(maxx, miny);
data->glTexCoord2f(minu, maxv);
data->glVertex2f(minx, maxy);
data->glTexCoord2f(maxu, maxv);
data->glVertex2f(maxx, maxy);
data->glEnd();
data->glPopMatrix();
break;
}
case SDL_RENDERCMD_NO_OP:
break;
}
cmd = cmd->next;
}
return GL_CheckError("", renderer);
}
static int
GL_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
Uint32 pixel_format, void * pixels, int pitch)
{
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
Uint32 temp_format = renderer->target ? renderer->target->format : SDL_PIXELFORMAT_ARGB8888;
void *temp_pixels;
int temp_pitch;
GLint internalFormat;
GLenum format, type;
Uint8 *src, *dst, *tmp;
int w, h, length, rows;
int status;
GL_ActivateRenderer(renderer);
if (!convert_format(data, temp_format, &internalFormat, &format, &type)) {
return SDL_SetError("Texture format %s not supported by OpenGL",
SDL_GetPixelFormatName(temp_format));
}
if (!rect->w || !rect->h) {
return 0; /* nothing to do. */
}
temp_pitch = rect->w * SDL_BYTESPERPIXEL(temp_format);
temp_pixels = SDL_malloc(rect->h * temp_pitch);
if (!temp_pixels) {
return SDL_OutOfMemory();
}
SDL_GetRendererOutputSize(renderer, &w, &h);
data->glPixelStorei(GL_PACK_ALIGNMENT, 1);
data->glPixelStorei(GL_PACK_ROW_LENGTH,
(temp_pitch / SDL_BYTESPERPIXEL(temp_format)));
data->glReadPixels(rect->x, renderer->target ? rect->y : (h-rect->y)-rect->h,
rect->w, rect->h, format, type, temp_pixels);
if (GL_CheckError("glReadPixels()", renderer) < 0) {
SDL_free(temp_pixels);
return -1;
}
/* Flip the rows to be top-down if necessary */
if (!renderer->target) {
SDL_bool isstack;
length = rect->w * SDL_BYTESPERPIXEL(temp_format);
src = (Uint8*)temp_pixels + (rect->h-1)*temp_pitch;
dst = (Uint8*)temp_pixels;
tmp = SDL_small_alloc(Uint8, length, &isstack);
rows = rect->h / 2;
while (rows--) {
SDL_memcpy(tmp, dst, length);
SDL_memcpy(dst, src, length);
SDL_memcpy(src, tmp, length);
dst += temp_pitch;
src -= temp_pitch;
}
SDL_small_free(tmp, isstack);
}
status = SDL_ConvertPixels(rect->w, rect->h,
temp_format, temp_pixels, temp_pitch,
pixel_format, pixels, pitch);
SDL_free(temp_pixels);
return status;
}
static void
GL_RenderPresent(SDL_Renderer * renderer)
{
GL_ActivateRenderer(renderer);
SDL_GL_SwapWindow(renderer->window);
}
static void
GL_DestroyTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
GL_RenderData *renderdata = (GL_RenderData *) renderer->driverdata;
GL_TextureData *data = (GL_TextureData *) texture->driverdata;
GL_ActivateRenderer(renderer);
if (renderdata->drawstate.texture == texture) {
renderdata->drawstate.texture = NULL;
}
if (renderdata->drawstate.target == texture) {
renderdata->drawstate.target = NULL;
}
if (!data) {
return;
}
if (data->texture) {
renderdata->glDeleteTextures(1, &data->texture);
}
if (data->yuv) {
renderdata->glDeleteTextures(1, &data->utexture);
renderdata->glDeleteTextures(1, &data->vtexture);
}
SDL_free(data->pixels);
SDL_free(data);
texture->driverdata = NULL;
}
static void
GL_DestroyRenderer(SDL_Renderer * renderer)
{
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
if (data) {
if (data->context != NULL) {
/* make sure we delete the right resources! */
GL_ActivateRenderer(renderer);
}
GL_ClearErrors(renderer);
if (data->GL_ARB_debug_output_supported) {
PFNGLDEBUGMESSAGECALLBACKARBPROC glDebugMessageCallbackARBFunc = (PFNGLDEBUGMESSAGECALLBACKARBPROC) SDL_GL_GetProcAddress("glDebugMessageCallbackARB");
/* Uh oh, we don't have a safe way of removing ourselves from the callback chain, if it changed after we set our callback. */
/* For now, just always replace the callback with the original one */
glDebugMessageCallbackARBFunc(data->next_error_callback, data->next_error_userparam);
}
if (data->shaders) {
GL_DestroyShaderContext(data->shaders);
}
if (data->context) {
while (data->framebuffers) {
GL_FBOList *nextnode = data->framebuffers->next;
/* delete the framebuffer object */
data->glDeleteFramebuffersEXT(1, &data->framebuffers->FBO);
GL_CheckError("", renderer);
SDL_free(data->framebuffers);
data->framebuffers = nextnode;
}
SDL_GL_DeleteContext(data->context);
}
SDL_free(data);
}
SDL_free(renderer);
}
static int
GL_BindTexture (SDL_Renderer * renderer, SDL_Texture *texture, float *texw, float *texh)
{
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
GL_TextureData *texturedata = (GL_TextureData *) texture->driverdata;
const GLenum textype = data->textype;
GL_ActivateRenderer(renderer);
data->glEnable(textype);
if (texturedata->yuv) {
data->glActiveTextureARB(GL_TEXTURE2_ARB);
data->glBindTexture(textype, texturedata->vtexture);
data->glActiveTextureARB(GL_TEXTURE1_ARB);
data->glBindTexture(textype, texturedata->utexture);
data->glActiveTextureARB(GL_TEXTURE0_ARB);
}
data->glBindTexture(textype, texturedata->texture);
data->drawstate.texturing = SDL_TRUE;
data->drawstate.texture = texture;
if(texw) *texw = (float)texturedata->texw;
if(texh) *texh = (float)texturedata->texh;
return 0;
}
static int
GL_UnbindTexture (SDL_Renderer * renderer, SDL_Texture *texture)
{
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
GL_TextureData *texturedata = (GL_TextureData *) texture->driverdata;
const GLenum textype = data->textype;
GL_ActivateRenderer(renderer);
if (texturedata->yuv) {
data->glActiveTextureARB(GL_TEXTURE2_ARB);
data->glDisable(textype);
data->glActiveTextureARB(GL_TEXTURE1_ARB);
data->glDisable(textype);
data->glActiveTextureARB(GL_TEXTURE0_ARB);
}
data->glDisable(textype);
data->drawstate.texturing = SDL_FALSE;
data->drawstate.texture = NULL;
return 0;
}
SDL_Renderer *
GL_CreateRenderer(SDL_Window * window, Uint32 flags)
{
SDL_Renderer *renderer;
GL_RenderData *data;
GLint value;
Uint32 window_flags;
int profile_mask = 0, major = 0, minor = 0;
SDL_bool changed_window = SDL_FALSE;
SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &profile_mask);
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &major);
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &minor);
window_flags = SDL_GetWindowFlags(window);
if (!(window_flags & SDL_WINDOW_OPENGL) ||
profile_mask == SDL_GL_CONTEXT_PROFILE_ES || major != RENDERER_CONTEXT_MAJOR || minor != RENDERER_CONTEXT_MINOR) {
changed_window = SDL_TRUE;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, RENDERER_CONTEXT_MAJOR);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, RENDERER_CONTEXT_MINOR);
if (SDL_RecreateWindow(window, window_flags | SDL_WINDOW_OPENGL) < 0) {
goto error;
}
}
renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer));
if (!renderer) {
SDL_OutOfMemory();
goto error;
}
data = (GL_RenderData *) SDL_calloc(1, sizeof(*data));
if (!data) {
SDL_free(renderer);
SDL_OutOfMemory();
goto error;
}
renderer->GetOutputSize = GL_GetOutputSize;
renderer->SupportsBlendMode = GL_SupportsBlendMode;
renderer->CreateTexture = GL_CreateTexture;
renderer->UpdateTexture = GL_UpdateTexture;
renderer->UpdateTextureYUV = GL_UpdateTextureYUV;
renderer->LockTexture = GL_LockTexture;
renderer->UnlockTexture = GL_UnlockTexture;
renderer->SetTextureScaleMode = GL_SetTextureScaleMode;
renderer->SetRenderTarget = GL_SetRenderTarget;
renderer->QueueSetViewport = GL_QueueSetViewport;
renderer->QueueSetDrawColor = GL_QueueSetViewport; /* SetViewport and SetDrawColor are (currently) no-ops. */
renderer->QueueDrawPoints = GL_QueueDrawPoints;
renderer->QueueDrawLines = GL_QueueDrawPoints; /* lines and points queue vertices the same way. */
renderer->QueueFillRects = GL_QueueFillRects;
renderer->QueueCopy = GL_QueueCopy;
renderer->QueueCopyEx = GL_QueueCopyEx;
renderer->RunCommandQueue = GL_RunCommandQueue;
renderer->RenderReadPixels = GL_RenderReadPixels;
renderer->RenderPresent = GL_RenderPresent;
renderer->DestroyTexture = GL_DestroyTexture;
renderer->DestroyRenderer = GL_DestroyRenderer;
renderer->GL_BindTexture = GL_BindTexture;
renderer->GL_UnbindTexture = GL_UnbindTexture;
renderer->info = GL_RenderDriver.info;
renderer->info.flags = SDL_RENDERER_ACCELERATED;
renderer->driverdata = data;
renderer->window = window;
data->context = SDL_GL_CreateContext(window);
if (!data->context) {
SDL_free(renderer);
SDL_free(data);
goto error;
}
if (SDL_GL_MakeCurrent(window, data->context) < 0) {
SDL_GL_DeleteContext(data->context);
SDL_free(renderer);
SDL_free(data);
goto error;
}
if (GL_LoadFunctions(data) < 0) {
SDL_GL_DeleteContext(data->context);
SDL_free(renderer);
SDL_free(data);
goto error;
}
#ifdef __MACOSX__
/* Enable multi-threaded rendering */
/* Disabled until Ryan finishes his VBO/PBO code...
CGLEnable(CGLGetCurrentContext(), kCGLCEMPEngine);
*/
#endif
if (flags & SDL_RENDERER_PRESENTVSYNC) {
SDL_GL_SetSwapInterval(1);
} else {
SDL_GL_SetSwapInterval(0);
}
if (SDL_GL_GetSwapInterval() > 0) {
renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC;
}
/* Check for debug output support */
if (SDL_GL_GetAttribute(SDL_GL_CONTEXT_FLAGS, &value) == 0 &&
(value & SDL_GL_CONTEXT_DEBUG_FLAG)) {
data->debug_enabled = SDL_TRUE;
}
if (data->debug_enabled && SDL_GL_ExtensionSupported("GL_ARB_debug_output")) {
PFNGLDEBUGMESSAGECALLBACKARBPROC glDebugMessageCallbackARBFunc = (PFNGLDEBUGMESSAGECALLBACKARBPROC) SDL_GL_GetProcAddress("glDebugMessageCallbackARB");
data->GL_ARB_debug_output_supported = SDL_TRUE;
data->glGetPointerv(GL_DEBUG_CALLBACK_FUNCTION_ARB, (GLvoid **)(char *)&data->next_error_callback);
data->glGetPointerv(GL_DEBUG_CALLBACK_USER_PARAM_ARB, &data->next_error_userparam);
glDebugMessageCallbackARBFunc(GL_HandleDebugMessage, renderer);
/* Make sure our callback is called when errors actually happen */
data->glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
}
data->textype = GL_TEXTURE_2D;
if (SDL_GL_ExtensionSupported("GL_ARB_texture_non_power_of_two")) {
data->GL_ARB_texture_non_power_of_two_supported = SDL_TRUE;
} else if (SDL_GL_ExtensionSupported("GL_ARB_texture_rectangle") ||
SDL_GL_ExtensionSupported("GL_EXT_texture_rectangle")) {
data->GL_ARB_texture_rectangle_supported = SDL_TRUE;
data->textype = GL_TEXTURE_RECTANGLE_ARB;
}
if (data->GL_ARB_texture_rectangle_supported) {
data->glGetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB, &value);
renderer->info.max_texture_width = value;
renderer->info.max_texture_height = value;
} else {
data->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &value);
renderer->info.max_texture_width = value;
renderer->info.max_texture_height = value;
}
/* Check for multitexture support */
if (SDL_GL_ExtensionSupported("GL_ARB_multitexture")) {
data->glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC) SDL_GL_GetProcAddress("glActiveTextureARB");
if (data->glActiveTextureARB) {
data->GL_ARB_multitexture_supported = SDL_TRUE;
data->glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &data->num_texture_units);
}
}
/* Check for shader support */
if (SDL_GetHintBoolean(SDL_HINT_RENDER_OPENGL_SHADERS, SDL_TRUE)) {
data->shaders = GL_CreateShaderContext();
}
SDL_LogInfo(SDL_LOG_CATEGORY_RENDER, "OpenGL shaders: %s",
data->shaders ? "ENABLED" : "DISABLED");
/* We support YV12 textures using 3 textures and a shader */
if (data->shaders && data->num_texture_units >= 3) {
renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_YV12;
renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_IYUV;
renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_NV12;
renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_NV21;
}
#ifdef __MACOSX__
renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_UYVY;
#endif
if (SDL_GL_ExtensionSupported("GL_EXT_framebuffer_object")) {
data->GL_EXT_framebuffer_object_supported = SDL_TRUE;
data->glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)
SDL_GL_GetProcAddress("glGenFramebuffersEXT");
data->glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)
SDL_GL_GetProcAddress("glDeleteFramebuffersEXT");
data->glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)
SDL_GL_GetProcAddress("glFramebufferTexture2DEXT");
data->glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)
SDL_GL_GetProcAddress("glBindFramebufferEXT");
data->glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)
SDL_GL_GetProcAddress("glCheckFramebufferStatusEXT");
renderer->info.flags |= SDL_RENDERER_TARGETTEXTURE;
}
data->framebuffers = NULL;
/* Set up parameters for rendering */
data->glMatrixMode(GL_MODELVIEW);
data->glLoadIdentity();
data->glDisable(GL_DEPTH_TEST);
data->glDisable(GL_CULL_FACE);
data->glDisable(GL_SCISSOR_TEST);
data->glDisable(data->textype);
data->glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
data->glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
/* This ended up causing video discrepancies between OpenGL and Direct3D */
/* data->glEnable(GL_LINE_SMOOTH); */
data->drawstate.blend = SDL_BLENDMODE_INVALID;
data->drawstate.shader = SHADER_INVALID;
data->drawstate.color = 0xFFFFFFFF;
data->drawstate.clear_color = 0xFFFFFFFF;
return renderer;
error:
if (changed_window) {
/* Uh oh, better try to put it back... */
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profile_mask);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor);
SDL_RecreateWindow(window, window_flags);
}
return NULL;
}
SDL_RenderDriver GL_RenderDriver = {
GL_CreateRenderer,
{
"opengl",
(SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE),
4,
{
SDL_PIXELFORMAT_ARGB8888,
SDL_PIXELFORMAT_ABGR8888,
SDL_PIXELFORMAT_RGB888,
SDL_PIXELFORMAT_BGR888
},
0,
0}
};
#endif /* SDL_VIDEO_RENDER_OGL && !SDL_RENDER_DISABLED */
/* vi: set ts=4 sw=4 expandtab: */
| {
"pile_set_name": "Github"
} |
.PHONY: all
all: clean
$(JAVAC) -processor org.checkerframework.checker.nullness.NullnessChecker Issue502.java
# TODO: This test is rather unstable, as Expected.txt relies on
# @SideEffectFree being constant #12().
$(JAVAP) -v Issue502.class | grep "RuntimeVisibleAnnotations:" -A 2 > Out.txt 2>&1
diff -u Expected.txt Out.txt
clean:
rm -f Issue502.class Out.txt
| {
"pile_set_name": "Github"
} |
//--------------------------------------------------------------------------------------
// File: DynamicShaderLinkageFX11_LightPSH.h
//
// The pixel shader light header file for the DynamicShaderLinkageFX11 sample.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
// Interfaces
//--------------------------------------------------------------------------------------
interface iBaseLight
{
float3 IlluminateAmbient(float3 vNormal);
float3 IlluminateDiffuse(float3 vNormal);
float3 IlluminateSpecular(float3 vNormal, int specularPower );
};
//--------------------------------------------------------------------------------------
// Classes
//--------------------------------------------------------------------------------------
class cAmbientLight : iBaseLight
{
float3 m_vLightColor;
bool m_bEnable;
float3 IlluminateAmbient(float3 vNormal);
float3 IlluminateDiffuse(float3 vNormal)
{
return (float3)0;
}
float3 IlluminateSpecular(float3 vNormal, int specularPower )
{
return (float3)0;
}
};
class cHemiAmbientLight : cAmbientLight
{
// inherited float4 m_vLightColor is the SkyColor
float4 m_vGroundColor;
float4 m_vDirUp;
float3 IlluminateAmbient(float3 vNormal);
};
class cDirectionalLight : cAmbientLight
{
// inherited float4 m_vLightColor is the LightColor
float4 m_vLightDir;
float3 IlluminateDiffuse( float3 vNormal );
float3 IlluminateSpecular( float3 vNormal, int specularPower );
};
class cOmniLight : cAmbientLight
{
float3 m_vLightPosition;
float radius;
float3 IlluminateDiffuse( float3 vNormal );
};
class cSpotLight : cAmbientLight
{
float3 m_vLightPosition;
float3 m_vLightDir;
};
class cEnvironmentLight : cAmbientLight
{
float3 IlluminateSpecular( float3 vNormal, int specularPower );
};
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0
/*
* Zynq UltraScale+ MPSoC PLL driver
*
* Copyright (C) 2016-2018 Xilinx
*/
#include <linux/clk.h>
#include <linux/clk-provider.h>
#include <linux/slab.h>
#include "clk-zynqmp.h"
/**
* struct zynqmp_pll - PLL clock
* @hw: Handle between common and hardware-specific interfaces
* @clk_id: PLL clock ID
*/
struct zynqmp_pll {
struct clk_hw hw;
u32 clk_id;
};
#define to_zynqmp_pll(_hw) container_of(_hw, struct zynqmp_pll, hw)
#define PLL_FBDIV_MIN 25
#define PLL_FBDIV_MAX 125
#define PS_PLL_VCO_MIN 1500000000
#define PS_PLL_VCO_MAX 3000000000UL
enum pll_mode {
PLL_MODE_INT,
PLL_MODE_FRAC,
};
#define FRAC_OFFSET 0x8
#define PLLFCFG_FRAC_EN BIT(31)
#define FRAC_DIV BIT(16) /* 2^16 */
/**
* zynqmp_pll_get_mode() - Get mode of PLL
* @hw: Handle between common and hardware-specific interfaces
*
* Return: Mode of PLL
*/
static inline enum pll_mode zynqmp_pll_get_mode(struct clk_hw *hw)
{
struct zynqmp_pll *clk = to_zynqmp_pll(hw);
u32 clk_id = clk->clk_id;
const char *clk_name = clk_hw_get_name(hw);
u32 ret_payload[PAYLOAD_ARG_CNT];
int ret;
ret = zynqmp_pm_get_pll_frac_mode(clk_id, ret_payload);
if (ret)
pr_warn_once("%s() PLL get frac mode failed for %s, ret = %d\n",
__func__, clk_name, ret);
return ret_payload[1];
}
/**
* zynqmp_pll_set_mode() - Set the PLL mode
* @hw: Handle between common and hardware-specific interfaces
* @on: Flag to determine the mode
*/
static inline void zynqmp_pll_set_mode(struct clk_hw *hw, bool on)
{
struct zynqmp_pll *clk = to_zynqmp_pll(hw);
u32 clk_id = clk->clk_id;
const char *clk_name = clk_hw_get_name(hw);
int ret;
u32 mode;
if (on)
mode = PLL_MODE_FRAC;
else
mode = PLL_MODE_INT;
ret = zynqmp_pm_set_pll_frac_mode(clk_id, mode);
if (ret)
pr_warn_once("%s() PLL set frac mode failed for %s, ret = %d\n",
__func__, clk_name, ret);
}
/**
* zynqmp_pll_round_rate() - Round a clock frequency
* @hw: Handle between common and hardware-specific interfaces
* @rate: Desired clock frequency
* @prate: Clock frequency of parent clock
*
* Return: Frequency closest to @rate the hardware can generate
*/
static long zynqmp_pll_round_rate(struct clk_hw *hw, unsigned long rate,
unsigned long *prate)
{
u32 fbdiv;
long rate_div, f;
/* Enable the fractional mode if needed */
rate_div = (rate * FRAC_DIV) / *prate;
f = rate_div % FRAC_DIV;
zynqmp_pll_set_mode(hw, !!f);
if (zynqmp_pll_get_mode(hw) == PLL_MODE_FRAC) {
if (rate > PS_PLL_VCO_MAX) {
fbdiv = rate / PS_PLL_VCO_MAX;
rate = rate / (fbdiv + 1);
}
if (rate < PS_PLL_VCO_MIN) {
fbdiv = DIV_ROUND_UP(PS_PLL_VCO_MIN, rate);
rate = rate * fbdiv;
}
return rate;
}
fbdiv = DIV_ROUND_CLOSEST(rate, *prate);
fbdiv = clamp_t(u32, fbdiv, PLL_FBDIV_MIN, PLL_FBDIV_MAX);
return *prate * fbdiv;
}
/**
* zynqmp_pll_recalc_rate() - Recalculate clock frequency
* @hw: Handle between common and hardware-specific interfaces
* @parent_rate: Clock frequency of parent clock
*
* Return: Current clock frequency
*/
static unsigned long zynqmp_pll_recalc_rate(struct clk_hw *hw,
unsigned long parent_rate)
{
struct zynqmp_pll *clk = to_zynqmp_pll(hw);
u32 clk_id = clk->clk_id;
const char *clk_name = clk_hw_get_name(hw);
u32 fbdiv, data;
unsigned long rate, frac;
u32 ret_payload[PAYLOAD_ARG_CNT];
int ret;
ret = zynqmp_pm_clock_getdivider(clk_id, &fbdiv);
if (ret)
pr_warn_once("%s() get divider failed for %s, ret = %d\n",
__func__, clk_name, ret);
rate = parent_rate * fbdiv;
if (zynqmp_pll_get_mode(hw) == PLL_MODE_FRAC) {
zynqmp_pm_get_pll_frac_data(clk_id, ret_payload);
data = ret_payload[1];
frac = (parent_rate * data) / FRAC_DIV;
rate = rate + frac;
}
return rate;
}
/**
* zynqmp_pll_set_rate() - Set rate of PLL
* @hw: Handle between common and hardware-specific interfaces
* @rate: Frequency of clock to be set
* @parent_rate: Clock frequency of parent clock
*
* Set PLL divider to set desired rate.
*
* Returns: rate which is set on success else error code
*/
static int zynqmp_pll_set_rate(struct clk_hw *hw, unsigned long rate,
unsigned long parent_rate)
{
struct zynqmp_pll *clk = to_zynqmp_pll(hw);
u32 clk_id = clk->clk_id;
const char *clk_name = clk_hw_get_name(hw);
u32 fbdiv;
long rate_div, frac, m, f;
int ret;
if (zynqmp_pll_get_mode(hw) == PLL_MODE_FRAC) {
rate_div = (rate * FRAC_DIV) / parent_rate;
m = rate_div / FRAC_DIV;
f = rate_div % FRAC_DIV;
m = clamp_t(u32, m, (PLL_FBDIV_MIN), (PLL_FBDIV_MAX));
rate = parent_rate * m;
frac = (parent_rate * f) / FRAC_DIV;
ret = zynqmp_pm_clock_setdivider(clk_id, m);
if (ret == -EUSERS)
WARN(1, "More than allowed devices are using the %s, which is forbidden\n",
clk_name);
else if (ret)
pr_warn_once("%s() set divider failed for %s, ret = %d\n",
__func__, clk_name, ret);
zynqmp_pm_set_pll_frac_data(clk_id, f);
return rate + frac;
}
fbdiv = DIV_ROUND_CLOSEST(rate, parent_rate);
fbdiv = clamp_t(u32, fbdiv, PLL_FBDIV_MIN, PLL_FBDIV_MAX);
ret = zynqmp_pm_clock_setdivider(clk_id, fbdiv);
if (ret)
pr_warn_once("%s() set divider failed for %s, ret = %d\n",
__func__, clk_name, ret);
return parent_rate * fbdiv;
}
/**
* zynqmp_pll_is_enabled() - Check if a clock is enabled
* @hw: Handle between common and hardware-specific interfaces
*
* Return: 1 if the clock is enabled, 0 otherwise
*/
static int zynqmp_pll_is_enabled(struct clk_hw *hw)
{
struct zynqmp_pll *clk = to_zynqmp_pll(hw);
const char *clk_name = clk_hw_get_name(hw);
u32 clk_id = clk->clk_id;
unsigned int state;
int ret;
ret = zynqmp_pm_clock_getstate(clk_id, &state);
if (ret) {
pr_warn_once("%s() clock get state failed for %s, ret = %d\n",
__func__, clk_name, ret);
return -EIO;
}
return state ? 1 : 0;
}
/**
* zynqmp_pll_enable() - Enable clock
* @hw: Handle between common and hardware-specific interfaces
*
* Return: 0 on success else error code
*/
static int zynqmp_pll_enable(struct clk_hw *hw)
{
struct zynqmp_pll *clk = to_zynqmp_pll(hw);
const char *clk_name = clk_hw_get_name(hw);
u32 clk_id = clk->clk_id;
int ret;
if (zynqmp_pll_is_enabled(hw))
return 0;
ret = zynqmp_pm_clock_enable(clk_id);
if (ret)
pr_warn_once("%s() clock enable failed for %s, ret = %d\n",
__func__, clk_name, ret);
return ret;
}
/**
* zynqmp_pll_disable() - Disable clock
* @hw: Handle between common and hardware-specific interfaces
*/
static void zynqmp_pll_disable(struct clk_hw *hw)
{
struct zynqmp_pll *clk = to_zynqmp_pll(hw);
const char *clk_name = clk_hw_get_name(hw);
u32 clk_id = clk->clk_id;
int ret;
if (!zynqmp_pll_is_enabled(hw))
return;
ret = zynqmp_pm_clock_disable(clk_id);
if (ret)
pr_warn_once("%s() clock disable failed for %s, ret = %d\n",
__func__, clk_name, ret);
}
static const struct clk_ops zynqmp_pll_ops = {
.enable = zynqmp_pll_enable,
.disable = zynqmp_pll_disable,
.is_enabled = zynqmp_pll_is_enabled,
.round_rate = zynqmp_pll_round_rate,
.recalc_rate = zynqmp_pll_recalc_rate,
.set_rate = zynqmp_pll_set_rate,
};
/**
* zynqmp_clk_register_pll() - Register PLL with the clock framework
* @name: PLL name
* @clk_id: Clock ID
* @parents: Name of this clock's parents
* @num_parents: Number of parents
* @nodes: Clock topology node
*
* Return: clock hardware to the registered clock
*/
struct clk_hw *zynqmp_clk_register_pll(const char *name, u32 clk_id,
const char * const *parents,
u8 num_parents,
const struct clock_topology *nodes)
{
struct zynqmp_pll *pll;
struct clk_hw *hw;
struct clk_init_data init;
int ret;
init.name = name;
init.ops = &zynqmp_pll_ops;
init.flags = nodes->flag;
init.parent_names = parents;
init.num_parents = 1;
pll = kzalloc(sizeof(*pll), GFP_KERNEL);
if (!pll)
return ERR_PTR(-ENOMEM);
pll->hw.init = &init;
pll->clk_id = clk_id;
hw = &pll->hw;
ret = clk_hw_register(NULL, hw);
if (ret) {
kfree(pll);
return ERR_PTR(ret);
}
clk_hw_set_rate_range(hw, PS_PLL_VCO_MIN, PS_PLL_VCO_MAX);
if (ret < 0)
pr_err("%s:ERROR clk_set_rate_range failed %d\n", name, ret);
return hw;
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package install installs the certificates API group, making it available as
// an option to all of the API encoding/decoding machinery.
package install
import (
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/apis/certificates"
v1 "k8s.io/kubernetes/pkg/apis/certificates/v1"
"k8s.io/kubernetes/pkg/apis/certificates/v1beta1"
)
func init() {
Install(legacyscheme.Scheme)
}
// Install registers the API group and adds types to a scheme
func Install(scheme *runtime.Scheme) {
utilruntime.Must(certificates.AddToScheme(scheme))
utilruntime.Must(v1.AddToScheme(scheme))
utilruntime.Must(v1beta1.AddToScheme(scheme))
// TODO(liggitt): prefer v1 in 1.20
utilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion, v1.SchemeGroupVersion))
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.test.standalone.pvm;
import static org.junit.Assert.assertNotNull;
import org.camunda.bpm.engine.impl.pvm.ProcessDefinitionBuilder;
import org.camunda.bpm.engine.impl.pvm.PvmExecution;
import org.camunda.bpm.engine.impl.pvm.PvmProcessDefinition;
import org.camunda.bpm.engine.impl.pvm.PvmProcessInstance;
import org.camunda.bpm.engine.test.standalone.pvm.activities.Automatic;
import org.camunda.bpm.engine.test.standalone.pvm.activities.Decision;
import org.camunda.bpm.engine.test.standalone.pvm.activities.WaitState;
import org.junit.Test;
/**
* @author Tom Baeyens
*/
public class PvmTest {
@Test
public void testPvmWaitState() {
PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder()
.createActivity("a")
.initial()
.behavior(new WaitState())
.transition("b")
.endActivity()
.createActivity("b")
.behavior(new WaitState())
.transition("c")
.endActivity()
.createActivity("c")
.behavior(new WaitState())
.endActivity()
.buildProcessDefinition();
PvmProcessInstance processInstance = processDefinition.createProcessInstance();
processInstance.start();
PvmExecution activityInstance = processInstance.findExecution("a");
assertNotNull(activityInstance);
activityInstance.signal(null, null);
activityInstance = processInstance.findExecution("b");
assertNotNull(activityInstance);
activityInstance.signal(null, null);
activityInstance = processInstance.findExecution("c");
assertNotNull(activityInstance);
}
@Test
public void testPvmAutomatic() {
PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder()
.createActivity("a")
.initial()
.behavior(new Automatic())
.transition("b")
.endActivity()
.createActivity("b")
.behavior(new Automatic())
.transition("c")
.endActivity()
.createActivity("c")
.behavior(new WaitState())
.endActivity()
.buildProcessDefinition();
PvmProcessInstance processInstance = processDefinition.createProcessInstance();
processInstance.start();
assertNotNull(processInstance.findExecution("c"));
}
@Test
public void testPvmDecision() {
PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder()
.createActivity("start")
.initial()
.behavior(new Automatic())
.transition("checkCredit")
.endActivity()
.createActivity("checkCredit")
.behavior(new Decision())
.transition("askDaughterOut", "wow")
.transition("takeToGolf", "nice")
.transition("ignore", "default")
.endActivity()
.createActivity("takeToGolf")
.behavior(new WaitState())
.endActivity()
.createActivity("askDaughterOut")
.behavior(new WaitState())
.endActivity()
.createActivity("ignore")
.behavior(new WaitState())
.endActivity()
.buildProcessDefinition();
PvmProcessInstance processInstance = processDefinition.createProcessInstance();
processInstance.setVariable("creditRating", "Aaa-");
processInstance.start();
assertNotNull(processInstance.findExecution("takeToGolf"));
processInstance = processDefinition.createProcessInstance();
processInstance.setVariable("creditRating", "AAA+");
processInstance.start();
assertNotNull(processInstance.findExecution("askDaughterOut"));
processInstance = processDefinition.createProcessInstance();
processInstance.setVariable("creditRating", "bb-");
processInstance.start();
assertNotNull(processInstance.findExecution("ignore"));
}
}
| {
"pile_set_name": "Github"
} |
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the MIT License.
//---------------------------------------------------------------------
/*!
\file sniffer/Range.h
MIME sniffer range declarations
*/
#ifndef _SNIFFER_RANGE_H
#define _SNIFFER_RANGE_H
#include <SupportDefs.h>
namespace BPrivate {
namespace Storage {
namespace Sniffer {
class Err;
//! A range of byte offsets from which to check a pattern against a data stream.
class Range {
public:
Range(int32 start, int32 end);
status_t InitCheck() const;
Err* GetErr() const;
int32 Start() const;
int32 End() const;
void SetTo(int32 start, int32 end);
private:
int32 fStart;
int32 fEnd;
status_t fCStatus;
};
}; // namespace Sniffer
}; // namespace Storage
}; // namespace BPrivate
#endif // _SNIFFER_RANGE_H
| {
"pile_set_name": "Github"
} |
<resources>
<string name="app_name">掘金[MVVM]</string>
<string name="g_view">阅读</string>
<string name="g_dot"> ・ </string>
<string name="g_like">喜欢</string>
<string name="g_comment">评论</string>
</resources>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>AnimationType Enum Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset='utf-8'>
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Enum/AnimationType" class="dashAnchor"></a>
<a title="AnimationType Enum Reference"></a>
<header>
<div class="content-wrapper">
<p><a href="../index.html">Katana Docs</a> (100% documented)</p>
<p class="header-right"><a href="https://github.com/BendingSpoons/katana-swift"><img src="../img/gh.png"/>View on GitHub</a></p>
</div>
</header>
<div class="content-wrapper">
<p id="breadcrumbs">
<a href="../index.html">Katana Reference</a>
<img id="carat" src="../img/carat.png" />
AnimationType Enum Reference
</p>
</div>
<div class="content-wrapper">
<nav class="sidebar">
<ul class="nav-groups">
<li class="nav-group-name">
<a href="../Classes.html">Classes</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Classes/EmptySideEffectDependencyContainer.html">EmptySideEffectDependencyContainer</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Node.html">Node</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PlasticNode.html">PlasticNode</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PlasticView.html">PlasticView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Renderer.html">Renderer</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Store.html">Store</a>
</li>
<li class="nav-group-task">
<a href="../Classes/ViewsContainer.html">ViewsContainer</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Enums.html">Enums</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Enums/AnimationType.html">AnimationType</a>
</li>
<li class="nav-group-task">
<a href="../Enums/AsyncActionState.html">AsyncActionState</a>
</li>
<li class="nav-group-task">
<a href="../Enums.html#/s:O6Katana9EmptyKeys">EmptyKeys</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Extensions.html">Extensions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Extensions/Array.html">Array</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CGSize.html">CGSize</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIView.html">UIView</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Protocols/Action.html">Action</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ActionWithSideEffect.html">ActionWithSideEffect</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyAsyncAction.html">AnyAsyncAction</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyConnectedNodeDescription.html">AnyConnectedNodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyNode.html">AnyNode</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyNodeDescription.html">AnyNodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyNodeDescriptionProps.html">AnyNodeDescriptionProps</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyNodeDescriptionWithChildren.html">AnyNodeDescriptionWithChildren</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyPlasticNodeDescription.html">AnyPlasticNodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnyStore.html">AnyStore</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AsyncAction.html">AsyncAction</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/Childrenable.html">Childrenable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ConnectedNodeDescription.html">ConnectedNodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/LinkeableAction.html">LinkeableAction</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/NodeDescription.html">NodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/NodeDescriptionProps.html">NodeDescriptionProps</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/NodeDescriptionState.html">NodeDescriptionState</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/NodeDescriptionWithChildren.html">NodeDescriptionWithChildren</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/PlasticNodeDescription.html">PlasticNodeDescription</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/PlasticReferenceSizeable.html">PlasticReferenceSizeable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/PlatformNativeView.html">PlatformNativeView</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/SideEffectDependencyContainer.html">SideEffectDependencyContainer</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/State.html">State</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Structs.html">Structs</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Structs/ActionLinker.html">ActionLinker</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ActionLinks.html">ActionLinks</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Anchor.html">Anchor</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Anchor/Kind.html">– Kind</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Animation.html">Animation</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AnimationContainer.html">AnimationContainer</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AnimationOptions.html">AnimationOptions</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AnimationProps.html">AnimationProps</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ChildrenAnimations.html">ChildrenAnimations</a>
</li>
<li class="nav-group-task">
<a href="../Structs/EdgeInsets.html">EdgeInsets</a>
</li>
<li class="nav-group-task">
<a href="../Structs/EmptyProps.html">EmptyProps</a>
</li>
<li class="nav-group-task">
<a href="../Structs/EmptyState.html">EmptyState</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Size.html">Size</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Value.html">Value</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Typealiases.html">Typealiases</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Typealiases.html#/s:6Katana25AnimationPropsTransformer">AnimationPropsTransformer</a>
</li>
<li class="nav-group-task">
<a href="../Typealiases.html#/s:6Katana20NodeUpdateCompletion">NodeUpdateCompletion</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Associated Types.html">Associated Types</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Associated Types.html#/s:P6Katana27NodeDescriptionWithChildren9PropsType">PropsType</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section>
<section class="section">
<h1>AnimationType</h1>
<div class="declaration">
<div class="language">
<pre class="highlight"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">AnimationType</span></code></pre>
</div>
</div>
<p>Enum that represents the animations that can be used to animate an UI update</p>
</section>
<section class="section task-group-section">
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:FO6Katana13AnimationType4noneFMS0_S0_"></a>
<a name="//apple_ref/swift/Element/none" class="dashAnchor"></a>
<a class="token" href="#/s:FO6Katana13AnimationType4noneFMS0_S0_">none</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>No animation</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">case</span> <span class="k">none</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.1/Katana/Core/Animations/AnimationType.swift#L139">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:FO6Katana13AnimationType6linearFMS0_FT8durationSd_S0_"></a>
<a name="//apple_ref/swift/Element/linear" class="dashAnchor"></a>
<a class="token" href="#/s:FO6Katana13AnimationType6linearFMS0_FT8durationSd_S0_">linear</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Linear animation with a given duration</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">case</span> <span class="nf">linear</span><span class="p">(</span><span class="nv">duration</span><span class="p">:</span> <span class="kt">TimeInterval</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.1/Katana/Core/Animations/AnimationType.swift#L142">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:FO6Katana13AnimationType17linearWithOptionsFMS0_FT8durationSd7optionsVS_16AnimationOptions_S0_"></a>
<a name="//apple_ref/swift/Element/linearWithOptions" class="dashAnchor"></a>
<a class="token" href="#/s:FO6Katana13AnimationType17linearWithOptionsFMS0_FT8durationSd7optionsVS_16AnimationOptions_S0_">linearWithOptions</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Linear animation with given duration and options</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">case</span> <span class="nf">linearWithOptions</span><span class="p">(</span><span class="nv">duration</span><span class="p">:</span> <span class="kt">TimeInterval</span><span class="p">,</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.1/Katana/Core/Animations/AnimationType.swift#L145">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:FO6Katana13AnimationType15linearWithDelayFMS0_FT8durationSd7optionsVS_16AnimationOptions5delaySd_S0_"></a>
<a name="//apple_ref/swift/Element/linearWithDelay" class="dashAnchor"></a>
<a class="token" href="#/s:FO6Katana13AnimationType15linearWithDelayFMS0_FT8durationSd7optionsVS_16AnimationOptions5delaySd_S0_">linearWithDelay</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Liear animation with given duration, options and delay</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">case</span> <span class="nf">linearWithDelay</span><span class="p">(</span><span class="nv">duration</span><span class="p">:</span> <span class="kt">TimeInterval</span><span class="p">,</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.1/Katana/Core/Animations/AnimationType.swift#L149">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:FO6Katana13AnimationType6springFMS0_FT8durationSd7dampingV12CoreGraphics7CGFloat15initialVelocityS2__S0_"></a>
<a name="//apple_ref/swift/Element/spring" class="dashAnchor"></a>
<a class="token" href="#/s:FO6Katana13AnimationType6springFMS0_FT8durationSd7dampingV12CoreGraphics7CGFloat15initialVelocityS2__S0_">spring</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Spring animation with duration, damping and initialVelocity</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">case</span> <span class="nf">spring</span><span class="p">(</span><span class="nv">duration</span><span class="p">:</span> <span class="kt">TimeInterval</span><span class="p">,</span> <span class="nv">damping</span><span class="p">:</span> <span class="kt">CGFloat</span><span class="p">,</span> <span class="nv">initialVelocity</span><span class="p">:</span> <span class="kt">CGFloat</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.1/Katana/Core/Animations/AnimationType.swift#L154">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:FO6Katana13AnimationType17springWithOptionsFMS0_FT8durationSd7dampingV12CoreGraphics7CGFloat15initialVelocityS2_7optionsVS_16AnimationOptions_S0_"></a>
<a name="//apple_ref/swift/Element/springWithOptions" class="dashAnchor"></a>
<a class="token" href="#/s:FO6Katana13AnimationType17springWithOptionsFMS0_FT8durationSd7dampingV12CoreGraphics7CGFloat15initialVelocityS2_7optionsVS_16AnimationOptions_S0_">springWithOptions</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Spring animation with duration, damping, initialVelocity and options</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">case</span> <span class="nf">springWithOptions</span><span class="p">(</span><span class="nv">duration</span><span class="p">:</span> <span class="kt">TimeInterval</span><span class="p">,</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.1/Katana/Core/Animations/AnimationType.swift#L157">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:FO6Katana13AnimationType15springWithDelayFMS0_FT8durationSd7dampingV12CoreGraphics7CGFloat15initialVelocityS2_7optionsVS_16AnimationOptions5delaySd_S0_"></a>
<a name="//apple_ref/swift/Element/springWithDelay" class="dashAnchor"></a>
<a class="token" href="#/s:FO6Katana13AnimationType15springWithDelayFMS0_FT8durationSd7dampingV12CoreGraphics7CGFloat15initialVelocityS2_7optionsVS_16AnimationOptions5delaySd_S0_">springWithDelay</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Spring animation with duration, damping, initialVelocity, options and delay</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="k">case</span> <span class="nf">springWithDelay</span><span class="p">(</span><span class="nv">duration</span><span class="p">:</span> <span class="kt">TimeInterval</span><span class="p">,</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/BendingSpoons/katana-swift/tree/0.7.1/Katana/Core/Animations/AnimationType.swift#L163">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
</section>
</section>
<section id="footer">
<p>© 2017 <a class="link" href="http://bendingspoons.com" target="_blank" rel="external">Bending Spoons Team</a>. All rights reserved. (Last updated: 2017-02-12)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.7.3</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</article>
</div>
</body>
</div>
</html>
| {
"pile_set_name": "Github"
} |
#
# Example config for cross compiling
#
# In this config, it is expected that the tool chains from:
#
# https://kernel.org/pub/tools/crosstool/files/bin/x86_64/
#
# running on a x86_64 system have been downloaded and installed into:
#
# /usr/local/
#
# such that the compiler binaries are something like:
#
# /usr/local/gcc-4.5.2-nolibc/mips-linux/bin/mips-linux-gcc
#
# Some of the archs will use gcc-4.5.1 instead of gcc-4.5.2
# this config uses variables to differentiate them.
#
# Comments describe some of the options, but full descriptions of
# options are described in the samples.conf file.
# ${PWD} is defined by ktest.pl to be the directory that the user
# was in when they executed ktest.pl. It may be better to hardcode the
# path name here. THIS_DIR is the variable used through out the config file
# in case you want to change it.
THIS_DIR := ${PWD}
# Update the BUILD_DIR option to the location of your git repo you want to test.
BUILD_DIR = ${THIS_DIR}/linux.git
# The build will go into this directory. It will be created when you run the test.
OUTPUT_DIR = ${THIS_DIR}/cross-compile
# The build will be compiled with -j8
BUILD_OPTIONS = -j8
# The test will not stop when it hits a failure.
DIE_ON_FAILURE = 0
# If you want to have ktest.pl store the failure somewhere, uncomment this option
# and change the directory where ktest should store the failures.
#STORE_FAILURES = ${THIS_DIR}/failures
# The log file is stored in the OUTPUT_DIR called cross.log
# If you enable this, you need to create the OUTPUT_DIR. It wont be created for you.
LOG_FILE = ${OUTPUT_DIR}/cross.log
# The log file will be cleared each time you run ktest.
CLEAR_LOG = 1
# As some archs do not build with the defconfig, they have been marked
# to be ignored. If you want to test them anyway, change DO_FAILED to 1.
# If a test that has been marked as DO_FAILED passes, then you should change
# that test to be DO_DEFAULT
DO_FAILED := 0
DO_DEFAULT := 1
# By setting both DO_FAILED and DO_DEFAULT to zero, you can pick a single
# arch that you want to test. (uncomment RUN and chose your arch)
#RUN := arm
# At the bottom of the config file exists a bisect test. You can update that
# test and set DO_FAILED and DO_DEFAULT to zero, and uncomment this variable
# to run the bisect on the arch.
#RUN := bisect
# By default all tests will be running gcc 4.5.2. Some tests are using 4.5.1
# and they select that in the test.
# Note: GCC_VER is declared as on option and not a variable ('=' instead of ':=')
# This is important. A variable is used only in the config file and if it is set
# it stays that way for the rest of the config file until it is change again.
# Here we want GCC_VER to remain persistent and change for each test, as it is used in
# the MAKE_CMD. By using '=' instead of ':=' we achieve our goal.
GCC_VER = 4.5.2
MAKE_CMD = PATH=/usr/local/gcc-${GCC_VER}-nolibc/${CROSS}/bin:$PATH CROSS_COMPILE=${CROSS}- make ARCH=${ARCH}
# all tests are only doing builds.
TEST_TYPE = build
# If you want to add configs on top of the defconfig, you can add those configs into
# the add-config file and uncomment this option. This is useful if you want to test
# all cross compiles with PREEMPT set, or TRACING on, etc.
#ADD_CONFIG = ${THIS_DIR}/add-config
# All tests are using defconfig
BUILD_TYPE = defconfig
# The test names will have the arch and cross compiler used. This will be shown in
# the results.
TEST_NAME = ${ARCH} ${CROSS}
# alpha
TEST_START IF ${RUN} == alpha || ${DO_DEFAULT}
# Notice that CROSS and ARCH are also options and not variables (again '=' instead
# of ':='). This is because TEST_NAME and MAKE_CMD wil use them for each test.
# Only options are available during runs. Variables are only present in parsing the
# config file.
CROSS = alpha-linux
ARCH = alpha
# arm
TEST_START IF ${RUN} == arm || ${DO_DEFAULT}
CROSS = arm-unknown-linux-gnueabi
ARCH = arm
# ia64
TEST_START IF ${RUN} == ia64 || ${DO_DEFAULT}
CROSS = ia64-linux
ARCH = ia64
# m68k fails with error?
TEST_START IF ${RUN} == m68k || ${DO_DEFAULT}
CROSS = m68k-linux
ARCH = m68k
# mips64
TEST_START IF ${RUN} == mips || ${RUN} == mips64 || ${DO_DEFAULT}
CROSS = mips64-linux
ARCH = mips
# mips32
TEST_START IF ${RUN} == mips || ${RUN} == mips32 || ${DO_DEFAULT}
CROSS = mips-linux
ARCH = mips
# parisc64 failed?
TEST_START IF ${RUN} == hppa || ${RUN} == hppa64 || ${DO_FAILED}
CROSS = hppa64-linux
ARCH = parisc
# parisc
TEST_START IF ${RUN} == hppa || ${RUN} == hppa32 || ${DO_FAILED}
CROSS = hppa-linux
ARCH = parisc
# ppc
TEST_START IF ${RUN} == ppc || ${RUN} == ppc32 || ${DO_DEFAULT}
CROSS = powerpc-linux
ARCH = powerpc
# ppc64
TEST_START IF ${RUN} == ppc || ${RUN} == ppc64 || ${DO_DEFAULT}
CROSS = powerpc64-linux
ARCH = powerpc
# s390
TEST_START IF ${RUN} == s390 || ${DO_DEFAULT}
CROSS = s390x-linux
ARCH = s390
# sh
TEST_START IF ${RUN} == sh || ${DO_DEFAULT}
CROSS = sh4-linux
ARCH = sh
# sparc64
TEST_START IF ${RUN} == sparc || ${RUN} == sparc64 || ${DO_DEFAULT}
CROSS = sparc64-linux
ARCH = sparc64
# sparc
TEST_START IF ${RUN} == sparc || ${RUN} == sparc32 || ${DO_DEFAULT}
CROSS = sparc-linux
ARCH = sparc
# xtensa failed
TEST_START IF ${RUN} == xtensa || ${DO_FAILED}
CROSS = xtensa-linux
ARCH = xtensa
# UML
TEST_START IF ${RUN} == uml || ${DO_DEFAULT}
MAKE_CMD = make ARCH=um SUBARCH=x86_64
ARCH = uml
CROSS =
TEST_START IF ${RUN} == x86 || ${RUN} == i386 || ${DO_DEFAULT}
MAKE_CMD = make ARCH=i386
ARCH = i386
CROSS =
TEST_START IF ${RUN} == x86 || ${RUN} == x86_64 || ${DO_DEFAULT}
MAKE_CMD = make ARCH=x86_64
ARCH = x86_64
CROSS =
#################################
# This is a bisect if needed. You need to give it a MIN_CONFIG that
# will be the config file it uses. Basically, just copy the created defconfig
# for the arch someplace and point MIN_CONFIG to it.
TEST_START IF ${RUN} == bisect
MIN_CONFIG = ${THIS_DIR}/min-config
CROSS = s390x-linux
ARCH = s390
TEST_TYPE = bisect
BISECT_TYPE = build
BISECT_GOOD = v3.1
BISECT_BAD = v3.2
CHECKOUT = v3.2
#################################
# These defaults are needed to keep ktest.pl from complaining. They are
# ignored because the test does not go pass the build. No install or
# booting of the target images.
DEFAULTS
MACHINE = crosstest
SSH_USER = root
BUILD_TARGET = cross
TARGET_IMAGE = image
POWER_CYCLE = cycle
CONSOLE = console
LOCALVERSION = version
GRUB_MENU = grub
REBOOT_ON_ERROR = 0
POWEROFF_ON_ERROR = 0
POWEROFF_ON_SUCCESS = 0
REBOOT_ON_SUCCESS = 0
| {
"pile_set_name": "Github"
} |
#include <iostream>
#include <fstream>
#include <cstring>
#include "BenchmarkSets.hpp"
#include "datastructures/treemaps/NatarajanTreeHE.hpp"
#include "datastructures/treemaps/OFLFRedBlackTree.hpp"
#include "datastructures/treemaps/OFWFRedBlackTree.hpp"
// Macros suck, but it's either TinySTM or ESTM, we can't have both at the same time
#ifdef USE_TINY
#include "datastructures/treemaps/TinySTMRedBlackTree.hpp"
#define DATA_FILENAME "data/set-tree-1k-tiny.txt"
#else
//#include "datastructures/trevor_brown_abtree/TrevorBrownABTree.hpp"
//#include "datastructures/trevor_brown_natarajan/TrevorBrownNatarajanTree.hpp"
#include "datastructures/treemaps/ESTMRedBlackTree.hpp"
#define DATA_FILENAME "data/set-tree-1k.txt"
#endif
int main(void) {
const std::string dataFilename {DATA_FILENAME};
vector<int> threadList = { 1, 2, 4, 8, 16, 32, 48, 64 }; // For the laptop or AWS c5.9xlarge
vector<int> ratioList = { 1000, 500, 100, 10, 1, 0 }; // Permil ratio: 100%, 50%, 10%, 1%, 0.1%, 0%
const int numElements = 1000; // Number of keys in the set
const int numRuns = 1; // 5 runs for the paper
const seconds testLength = 20s; // 20s for the paper
const int EMAX_CLASS = 10;
uint64_t results[EMAX_CLASS][threadList.size()][ratioList.size()];
std::string cNames[EMAX_CLASS];
int maxClass = 0;
// Reset results
std::memset(results, 0, sizeof(uint64_t)*EMAX_CLASS*threadList.size()*ratioList.size());
double totalHours = (double)EMAX_CLASS*ratioList.size()*threadList.size()*testLength.count()*numRuns/(60.*60.);
std::cout << "This benchmark is going to take about " << totalHours << " hours to complete\n";
for (unsigned iratio = 0; iratio < ratioList.size(); iratio++) {
auto ratio = ratioList[iratio];
for (unsigned it = 0; it < threadList.size(); it++) {
auto nThreads = threadList[it];
int ic = 0;
BenchmarkSets bench(nThreads);
std::cout << "\n----- Sets (Trees) numElements=" << numElements << " ratio=" << ratio/10. << "% threads=" << nThreads << " runs=" << numRuns << " length=" << testLength.count() << "s -----\n";
#ifdef USE_TINY
results[ic][it][iratio] = bench.benchmark<TinySTMRedBlackTree<uint64_t,uint64_t>,uint64_t> (cNames[ic], ratio, testLength, numRuns, numElements, false);
ic++;
#else
results[ic][it][iratio] = bench.benchmark<OFLFRedBlackTree<uint64_t,uint64_t>,uint64_t> (cNames[ic], ratio, testLength, numRuns, numElements, false);
ic++;
results[ic][it][iratio] = bench.benchmark<OFWFRedBlackTree<uint64_t,uint64_t>,uint64_t> (cNames[ic], ratio, testLength, numRuns, numElements, false);
ic++;
results[ic][it][iratio] = bench.benchmark<ESTMRedBlackTree<uint64_t,uint64_t>,uint64_t> (cNames[ic], ratio, testLength, numRuns, numElements, false);
ic++;
results[ic][it][iratio] = bench.benchmark<NatarajanTreeHE<uint64_t,uint64_t>,uint64_t> (cNames[ic], ratio, testLength, numRuns, numElements, false);
ic++;
//results[ic][it][iratio] = bench.benchmark<TrevorBrownABTree<uint64_t>,uint64_t> (cNames[ic], ratio, testLength, numRuns, numElements, false);
//ic++;
//results[ic][it][iratio] = bench.benchmark<TrevorBrownNatarajanTree<uint64_t>,uint64_t> (cNames[ic], ratio, testLength, numRuns, numElements, false);
//ic++;
#endif
maxClass = ic;
}
}
// Export tab-separated values to a file to be imported in gnuplot or excel
ofstream dataFile;
dataFile.open(dataFilename);
dataFile << "Threads\t";
// Printf class names and ratios for each column
for (unsigned ir = 0; ir < ratioList.size(); ir++) {
auto ratio = ratioList[ir];
for (int ic = 0; ic < maxClass; ic++) dataFile << cNames[ic] << "-" << ratio/10. << "%"<< "\t";
}
dataFile << "\n";
for (int it = 0; it < threadList.size(); it++) {
dataFile << threadList[it] << "\t";
for (unsigned ir = 0; ir < ratioList.size(); ir++) {
for (int ic = 0; ic < maxClass; ic++) dataFile << results[ic][it][ir] << "\t";
}
dataFile << "\n";
}
dataFile.close();
std::cout << "\nSuccessfuly saved results in " << dataFilename << "\n";
return 0;
}
| {
"pile_set_name": "Github"
} |
{
"info" : {
"version" : 1,
"author" : "xcode"
},
"colors" : [
{
"idiom" : "universal",
"color" : {
"color-space" : "extended-gray",
"components" : {
"white" : "0.839",
"alpha" : "0.300"
}
}
}
]
} | {
"pile_set_name": "Github"
} |
#include <common.h>
#include <mpc8xx.h>
#include <pcmcia.h>
#undef CONFIG_PCMCIA
#if defined(CONFIG_CMD_PCMCIA)
#define CONFIG_PCMCIA
#endif
#if defined(CONFIG_CMD_IDE) && defined(CONFIG_IDE_8xx_PCCARD)
#define CONFIG_PCMCIA
#endif
#ifdef CONFIG_PCMCIA
#define PCMCIA_BOARD_MSG "C2MON"
static void cfg_ports (void)
{
volatile immap_t *immap;
volatile cpm8xx_t *cp;
ushort sreg;
immap = (immap_t *)CONFIG_SYS_IMMR;
cp = (cpm8xx_t *)(&(((immap_t *)CONFIG_SYS_IMMR)->im_cpm));
/*
* Configure Port C for TPS2211 PC-Card Power-Interface Switch
*
* Switch off all voltages, assert shutdown
*/
sreg = immap->im_ioport.iop_pcdat;
sreg |= (TPS2211_VPPD0 | TPS2211_VPPD1); /* VAVPP => Hi-Z */
sreg &= ~(TPS2211_VCCD0 | TPS2211_VCCD1); /* 3V and 5V off */
immap->im_ioport.iop_pcdat = sreg;
immap->im_ioport.iop_pcpar &= ~(TPS2211_OUTPUTS);
immap->im_ioport.iop_pcdir |= TPS2211_OUTPUTS;
debug ("Set Port C: PAR: %04x DIR: %04x DAT: %04x\n",
immap->im_ioport.iop_pcpar,
immap->im_ioport.iop_pcdir,
immap->im_ioport.iop_pcdat);
/*
* Configure Port B for TPS2211 PC-Card Power-Interface Switch
*
* Over-Current Input only
*/
cp->cp_pbpar &= ~(TPS2211_INPUTS);
cp->cp_pbdir &= ~(TPS2211_INPUTS);
debug ("Set Port B: PAR: %08x DIR: %08x DAT: %08x\n",
cp->cp_pbpar, cp->cp_pbdir, cp->cp_pbdat);
}
int pcmcia_hardware_enable(int slot)
{
volatile immap_t *immap;
volatile cpm8xx_t *cp;
volatile pcmconf8xx_t *pcmp;
volatile sysconf8xx_t *sysp;
uint reg, pipr, mask;
ushort sreg;
int i;
debug ("hardware_enable: " PCMCIA_BOARD_MSG " Slot %c\n", 'A'+slot);
udelay(10000);
immap = (immap_t *)CONFIG_SYS_IMMR;
sysp = (sysconf8xx_t *)(&(((immap_t *)CONFIG_SYS_IMMR)->im_siu_conf));
pcmp = (pcmconf8xx_t *)(&(((immap_t *)CONFIG_SYS_IMMR)->im_pcmcia));
cp = (cpm8xx_t *)(&(((immap_t *)CONFIG_SYS_IMMR)->im_cpm));
/* Configure Ports for TPS2211A PC-Card Power-Interface Switch */
cfg_ports ();
/*
* Configure SIUMCR to enable PCMCIA port B
* (VFLS[0:1] are not used for debugging, we connect FRZ# instead)
*/
sysp->sc_siumcr &= ~SIUMCR_DBGC11; /* set DBGC to 00 */
/* clear interrupt state, and disable interrupts */
pcmp->pcmc_pscr = PCMCIA_MASK(_slot_);
pcmp->pcmc_per &= ~PCMCIA_MASK(_slot_);
/*
* Disable interrupts, DMA, and PCMCIA buffers
* (isolate the interface) and assert RESET signal
*/
debug ("Disable PCMCIA buffers and assert RESET\n");
reg = 0;
reg |= __MY_PCMCIA_GCRX_CXRESET; /* active high */
reg |= __MY_PCMCIA_GCRX_CXOE; /* active low */
PCMCIA_PGCRX(_slot_) = reg;
udelay(500);
/*
* Make sure there is a card in the slot, then configure the interface.
*/
udelay(10000);
debug ("[%d] %s: PIPR(%p)=0x%x\n",
__LINE__,__FUNCTION__,
&(pcmp->pcmc_pipr),pcmp->pcmc_pipr);
if (pcmp->pcmc_pipr & (0x18000000 >> (slot << 4))) {
printf (" No Card found\n");
return (1);
}
/*
* Power On: Set VAVCC to 3.3V or 5V, set VAVPP to Hi-Z
*/
mask = PCMCIA_VS1(slot) | PCMCIA_VS2(slot);
pipr = pcmp->pcmc_pipr;
debug ("PIPR: 0x%x ==> VS1=o%s, VS2=o%s\n",
pipr,
(reg&PCMCIA_VS1(slot))?"n":"ff",
(reg&PCMCIA_VS2(slot))?"n":"ff");
sreg = immap->im_ioport.iop_pcdat;
if ((pipr & mask) == mask) {
sreg |= (TPS2211_VPPD0 | TPS2211_VPPD1 | /* VAVPP => Hi-Z */
TPS2211_VCCD1); /* 5V on */
sreg &= ~(TPS2211_VCCD0); /* 3V off */
puts (" 5.0V card found: ");
} else {
sreg |= (TPS2211_VPPD0 | TPS2211_VPPD1 | /* VAVPP => Hi-Z */
TPS2211_VCCD0); /* 3V on */
sreg &= ~(TPS2211_VCCD1); /* 5V off */
puts (" 3.3V card found: ");
}
debug ("\nPC DAT: %04x -> 3.3V %s 5.0V %s\n",
sreg,
( (sreg & TPS2211_VCCD0) && !(sreg & TPS2211_VCCD1)) ? "on" : "off",
(!(sreg & TPS2211_VCCD0) && (sreg & TPS2211_VCCD1)) ? "on" : "off"
);
immap->im_ioport.iop_pcdat = sreg;
/* Wait 500 ms; use this to check for over-current */
for (i=0; i<5000; ++i) {
if ((cp->cp_pbdat & TPS2211_OC) == 0) {
printf (" *** Overcurrent - Safety shutdown ***\n");
immap->im_ioport.iop_pcdat &= ~(TPS2211_VCCD0|TPS2211_VCCD1);
return (1);
}
udelay (100);
}
debug ("Enable PCMCIA buffers and stop RESET\n");
reg = PCMCIA_PGCRX(_slot_);
reg &= ~__MY_PCMCIA_GCRX_CXRESET; /* active high */
reg &= ~__MY_PCMCIA_GCRX_CXOE; /* active low */
PCMCIA_PGCRX(_slot_) = reg;
udelay(250000); /* some cards need >150 ms to come up :-( */
debug ("# hardware_enable done\n");
return (0);
}
#if defined(CONFIG_CMD_PCMCIA)
int pcmcia_hardware_disable(int slot)
{
volatile immap_t *immap;
volatile cpm8xx_t *cp;
volatile pcmconf8xx_t *pcmp;
u_long reg;
debug ("hardware_disable: " PCMCIA_BOARD_MSG " Slot %c\n", 'A'+slot);
immap = (immap_t *)CONFIG_SYS_IMMR;
pcmp = (pcmconf8xx_t *)(&(((immap_t *)CONFIG_SYS_IMMR)->im_pcmcia));
/* Configure PCMCIA General Control Register */
debug ("Disable PCMCIA buffers and assert RESET\n");
reg = 0;
reg |= __MY_PCMCIA_GCRX_CXRESET; /* active high */
reg |= __MY_PCMCIA_GCRX_CXOE; /* active low */
PCMCIA_PGCRX(_slot_) = reg;
/* ALl voltages off / Hi-Z */
immap->im_ioport.iop_pcdat |= (TPS2211_VPPD0 | TPS2211_VPPD1 |
TPS2211_VCCD0 | TPS2211_VCCD1 );
udelay(10000);
return (0);
}
#endif
int pcmcia_voltage_set(int slot, int vcc, int vpp)
{
volatile immap_t *immap;
volatile cpm8xx_t *cp;
volatile pcmconf8xx_t *pcmp;
u_long reg;
ushort sreg;
debug ("voltage_set: "
PCMCIA_BOARD_MSG
" Slot %c, Vcc=%d.%d, Vpp=%d.%d\n",
'A'+slot, vcc/10, vcc%10, vpp/10, vcc%10);
immap = (immap_t *)CONFIG_SYS_IMMR;
cp = (cpm8xx_t *)(&(((immap_t *)CONFIG_SYS_IMMR)->im_cpm));
pcmp = (pcmconf8xx_t *)(&(((immap_t *)CONFIG_SYS_IMMR)->im_pcmcia));
/*
* Disable PCMCIA buffers (isolate the interface)
* and assert RESET signal
*/
debug ("Disable PCMCIA buffers and assert RESET\n");
reg = PCMCIA_PGCRX(_slot_);
reg |= __MY_PCMCIA_GCRX_CXRESET; /* active high */
reg |= __MY_PCMCIA_GCRX_CXOE; /* active low */
PCMCIA_PGCRX(_slot_) = reg;
udelay(500);
/*
* Configure Port C pins for
* 5 Volts Enable and 3 Volts enable,
* Turn all power pins to Hi-Z
*/
debug ("PCMCIA power OFF\n");
cfg_ports (); /* Enables switch, but all in Hi-Z */
sreg = immap->im_ioport.iop_pcdat;
sreg |= TPS2211_VPPD0 | TPS2211_VPPD1; /* VAVPP always Hi-Z */
switch(vcc) {
case 0: break; /* Switch off */
case 33: sreg |= TPS2211_VCCD0; /* Switch on 3.3V */
sreg &= ~TPS2211_VCCD1;
break;
case 50: sreg &= ~TPS2211_VCCD0; /* Switch on 5.0V */
sreg |= TPS2211_VCCD1;
break;
default: goto done;
}
/* Checking supported voltages */
debug ("PIPR: 0x%x --> %s\n",
pcmp->pcmc_pipr,
(pcmp->pcmc_pipr & 0x00008000) ? "only 5 V" : "can do 3.3V");
immap->im_ioport.iop_pcdat = sreg;
#ifdef DEBUG
{
char *s;
if ((sreg & TPS2211_VCCD0) && !(sreg & TPS2211_VCCD1)) {
s = "at 3.3V";
} else if (!(sreg & TPS2211_VCCD0) && (sreg & TPS2211_VCCD1)) {
s = "at 5.0V";
} else {
s = "down";
}
printf ("PCMCIA powered %s\n", s);
}
#endif
done:
debug ("Enable PCMCIA buffers and stop RESET\n");
reg = PCMCIA_PGCRX(_slot_);
reg &= ~__MY_PCMCIA_GCRX_CXRESET; /* active high */
reg &= ~__MY_PCMCIA_GCRX_CXOE; /* active low */
PCMCIA_PGCRX(_slot_) = reg;
udelay(500);
debug ("voltage_set: " PCMCIA_BOARD_MSG " Slot %c, DONE\n",
slot+'A');
return (0);
}
#endif /* CONFIG_PCMCIA */
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" ?>
<ROOT>
-- Daots_test_tableA_S4_Delete
-- 2014/2/9 日立 太郎
DELETE FROM
[ts_test_tableA]
<WHERE>
WHERE
[id] = @id
AND [ts] = @ts
</WHERE>
</ROOT>
| {
"pile_set_name": "Github"
} |
title: Carthage
summary: Runs selected Carthage command.
description: |-
Runs selected Carthage command.
For more information about Carthage, visit the [Carthage GitHub page](https://github.com/Carthage/Carthage).
website: https://github.com/bitrise-steplib/steps-carthage
source_code_url: https://github.com/bitrise-steplib/steps-carthage
support_url: https://github.com/bitrise-steplib/steps-carthage/issues
published_at: 2016-11-18T12:28:37.362873487+01:00
source:
git: https://github.com/bitrise-steplib/steps-carthage.git
commit: e8e99608cd4dbf06b49ef79447faf654cbe97c1b
host_os_tags:
- osx-10.10
project_type_tags:
- ios
type_tags:
- carthage
- system
toolkit:
go:
package_name: github.com/bitrise-steplib/steps-carthage
deps:
brew:
- name: go
- name: carthage
apt_get:
- name: golang
bin_name: go
is_requires_admin_user: false
is_always_run: false
is_skippable: false
inputs:
- github_access_token: $GITHUB_ACCESS_TOKEN
opts:
description: "Use this input to avoid Github rate limit issues.\n\nSee the github's
guide: [Creating an access token for command-line use](https://help.github.com/articles/creating-an-access-token-for-command-line-use/),
\ \nhow to create Personal Access Token.\n\n__UNCHECK EVERY SCOPE BOX__ when
creating this token. There is no reason this token needs access to private information."
title: Github Personal Access Token
- carthage_command: update
opts:
description: |-
Select a command to set up your dependencies with.
To see available commands run: `carthage help` on your local machine.
summary: Select a command to set up your dependencies with.
title: Carthage command to run
- carthage_options: null
opts:
description: "Options added to the end of the Carthage call.\nYou can use multiple
options, separated by a space character.\n\nTo see available command's options,
call: `carthage help COMMAND` \n\nFormat example: `--platform ios`"
title: Additional options for `carthage` command
| {
"pile_set_name": "Github"
} |
<!DOCTYPE refentry [ <!ENTITY % mathent SYSTEM "math.ent"> %mathent; ]>
<!-- Converted by db4-upgrade version 1.1 -->
<refentry xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="glDrawRangeElementsBaseVertex">
<info>
<copyright>
<year>2010-2015</year>
<holder>Khronos Group</holder>
</copyright>
</info>
<refmeta>
<refentrytitle>glDrawRangeElementsBaseVertex</refentrytitle>
<manvolnum>3G</manvolnum>
</refmeta>
<refnamediv>
<refname>glDrawRangeElementsBaseVertex</refname>
<refpurpose>render primitives from array data with a per-element offset</refpurpose>
</refnamediv>
<refsynopsisdiv><title>C Specification</title>
<funcsynopsis>
<funcprototype>
<funcdef>void <function>glDrawRangeElementsBaseVertex</function></funcdef>
<paramdef>GLenum <parameter>mode</parameter></paramdef>
<paramdef>GLuint <parameter>start</parameter></paramdef>
<paramdef>GLuint <parameter>end</parameter></paramdef>
<paramdef>GLsizei <parameter>count</parameter></paramdef>
<paramdef>GLenum <parameter>type</parameter></paramdef>
<paramdef>void *<parameter>indices</parameter></paramdef>
<paramdef>GLint <parameter>basevertex</parameter></paramdef>
</funcprototype>
</funcsynopsis>
</refsynopsisdiv>
<refsect1 xml:id="parameters"><title>Parameters</title>
<variablelist>
<varlistentry>
<term><parameter>mode</parameter></term>
<listitem>
<para>
Specifies what kind of primitives to render.
Symbolic constants
<constant>GL_POINTS</constant>, <constant>GL_LINE_STRIP</constant>, <constant>GL_LINE_LOOP</constant>,
<constant>GL_LINES</constant>, <constant>GL_TRIANGLE_STRIP</constant>, <constant>GL_TRIANGLE_FAN</constant>,
<constant>GL_TRIANGLES</constant>, <constant>GL_LINES_ADJACENCY</constant>, <constant>GL_LINE_STRIP_ADJACENCY</constant>,
<constant>GL_TRIANGLES_ADJACENCY</constant>, <constant>GL_TRIANGLE_STRIP_ADJACENCY</constant> and <constant>GL_PATCHES</constant> are accepted.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>start</parameter></term>
<listitem>
<para>
Specifies the minimum array index contained in <parameter>indices</parameter>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>end</parameter></term>
<listitem>
<para>
Specifies the maximum array index contained in <parameter>indices</parameter>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>count</parameter></term>
<listitem>
<para>
Specifies the number of elements to be rendered.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>type</parameter></term>
<listitem>
<para>
Specifies the type of the values in indices. Must be one of <constant>GL_UNSIGNED_BYTE</constant>,
<constant>GL_UNSIGNED_SHORT</constant>, or <constant>GL_UNSIGNED_INT</constant>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>indices</parameter></term>
<listitem>
<para>
Specifies a pointer to the location where the indices are stored.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>basevertex</parameter></term>
<listitem>
<para>
Specifies a constant that should be added to each element of <parameter>indices</parameter>
when chosing elements from the enabled vertex arrays.
</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1 xml:id="description"><title>Description</title>
<para>
<function>glDrawRangeElementsBaseVertex</function> is a restricted form of
<citerefentry><refentrytitle>glDrawElementsBaseVertex</refentrytitle></citerefentry>. <parameter>mode</parameter>,
<parameter>count</parameter> and <parameter>basevertex</parameter> match
the corresponding arguments to <citerefentry><refentrytitle>glDrawElementsBaseVertex</refentrytitle></citerefentry>, with the additional
constraint that all values in the array <parameter>indices</parameter> must lie between <parameter>start</parameter> and <parameter>end</parameter>,
inclusive, prior to adding <parameter>basevertex</parameter>. Index values lying outside the range [<parameter>start</parameter>, <parameter>end</parameter>]
are treated in the same way as <citerefentry><refentrytitle>glDrawElementsBaseVertex</refentrytitle></citerefentry>. The <emphasis>i</emphasis>th element
transferred by the corresponding draw call will be taken from element <parameter>indices</parameter>[i] + <parameter>basevertex</parameter> of each enabled
array. If the resulting value is larger than the maximum value representable by <parameter>type</parameter>, it is as if the calculation were upconverted to
32-bit unsigned integers (with wrapping on overflow conditions). The operation is undefined if the sum would be negative.
</para>
</refsect1>
<refsect1 xml:id="errors"><title>Errors</title>
<para>
<constant>GL_INVALID_ENUM</constant> is generated if <parameter>mode</parameter> is not an accepted value.
</para>
<para>
<constant>GL_INVALID_VALUE</constant> is generated if <parameter>count</parameter> is negative.
</para>
<para>
<constant>GL_INVALID_VALUE</constant> is generated if <parameter>end</parameter> < <parameter>start</parameter>.
</para>
<para>
<constant>GL_INVALID_OPERATION</constant> is generated if a geometry shader is active and <parameter>mode</parameter>
is incompatible with the input primitive type of the geometry shader in the currently installed program object.
</para>
<para>
<constant>GL_INVALID_OPERATION</constant> is generated if a non-zero buffer object name is bound to an
enabled array or the element array and the buffer object's data store is currently mapped.
</para>
</refsect1>
<refsect1 xml:id="versions"><title>Version Support</title>
<informaltable>
<tgroup cols="5" align="left">
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apifunchead.xml" xpointer="xpointer(/*/*)"/>
<tbody>
<row>
<entry><function>glDrawRangeElementsBaseVertex</function></entry>
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='es32']/*)"/>
</row>
</tbody>
</tgroup>
</informaltable>
</refsect1>
<refsect1 xml:id="seealso"><title>See Also</title>
<para>
<citerefentry><refentrytitle>glDrawElements</refentrytitle></citerefentry>,
<citerefentry><refentrytitle>glDrawElementsBaseVertex</refentrytitle></citerefentry>,
<citerefentry><refentrytitle>glDrawRangeElements</refentrytitle></citerefentry>,
<citerefentry><refentrytitle>glDrawElementsInstanced</refentrytitle></citerefentry>,
<citerefentry><refentrytitle>glDrawElementsInstancedBaseVertex</refentrytitle></citerefentry>
</para>
</refsect1>
<refsect1 xml:id="Copyright"><title>Copyright</title>
<para>
Copyright <trademark class="copyright"/> 2010-2015 Khronos Group.
This material may be distributed subject to the terms and conditions set forth in
the Open Publication License, v 1.0, 8 June 1999.
<link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://opencontent.org/openpub/">http://opencontent.org/openpub/</link>.
</para>
</refsect1>
</refentry>
| {
"pile_set_name": "Github"
} |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveGeneric #-}
module Codec.Xlsx.Types.AutoFilter where
import Control.Arrow (first)
import Control.DeepSeq (NFData)
import Control.Lens (makeLenses)
import Data.Bool (bool)
import Data.ByteString (ByteString)
import Data.Default
import Data.Foldable (asum)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Generics (Generic)
import Text.XML
import Text.XML.Cursor hiding (bool)
import qualified Xeno.DOM as Xeno
import Codec.Xlsx.Parser.Internal
import Codec.Xlsx.Types.Common
import Codec.Xlsx.Types.ConditionalFormatting (IconSetType)
import Codec.Xlsx.Writer.Internal
-- | The filterColumn collection identifies a particular column in the
-- AutoFilter range and specifies filter information that has been
-- applied to this column. If a column in the AutoFilter range has no
-- criteria specified, then there is no corresponding filterColumn
-- collection expressed for that column.
--
-- See 18.3.2.7 "filterColumn (AutoFilter Column)" (p. 1717)
data FilterColumn
= Filters FilterByBlank [FilterCriterion]
| ColorFilter ColorFilterOptions
| ACustomFilter CustomFilter
| CustomFiltersOr CustomFilter CustomFilter
| CustomFiltersAnd CustomFilter CustomFilter
| DynamicFilter DynFilterOptions
| IconFilter (Maybe Int) IconSetType
-- ^ Specifies the icon set and particular icon within that set to
-- filter by. Icon is specified using zero-based index of an icon in
-- an icon set. 'Nothing' means "no icon"
| BottomNFilter EdgeFilterOptions
-- ^ Specifies the bottom N (percent or number of items) to filter by
| TopNFilter EdgeFilterOptions
-- ^ Specifies the top N (percent or number of items) to filter by
deriving (Eq, Show, Generic)
instance NFData FilterColumn
data FilterByBlank
= FilterByBlank
| DontFilterByBlank
deriving (Eq, Show, Generic)
instance NFData FilterByBlank
data FilterCriterion
= FilterValue Text
| FilterDateGroup DateGroup
deriving (Eq, Show, Generic)
instance NFData FilterCriterion
-- | Used to express a group of dates or times which are used in an
-- AutoFilter criteria
--
-- Section 18.3.2.4 "dateGroupItem (Date Grouping)" (p. 1714)
data DateGroup
= DateGroupByYear Int
| DateGroupByMonth Int Int
| DateGroupByDay Int Int Int
| DateGroupByHour Int Int Int Int
| DateGroupByMinute Int Int Int Int Int
| DateGroupBySecond Int Int Int Int Int Int
deriving (Eq, Show, Generic)
instance NFData DateGroup
data CustomFilter = CustomFilter
{ cfltOperator :: CustomFilterOperator
, cfltValue :: Text
} deriving (Eq, Show, Generic)
instance NFData CustomFilter
data CustomFilterOperator
= FltrEqual
-- ^ Show results which are equal to criteria.
| FltrGreaterThan
-- ^ Show results which are greater than criteria.
| FltrGreaterThanOrEqual
-- ^ Show results which are greater than or equal to criteria.
| FltrLessThan
-- ^ Show results which are less than criteria.
| FltrLessThanOrEqual
-- ^ Show results which are less than or equal to criteria.
| FltrNotEqual
-- ^ Show results which are not equal to criteria.
deriving (Eq, Show, Generic)
instance NFData CustomFilterOperator
data EdgeFilterOptions = EdgeFilterOptions
{ _efoUsePercents :: Bool
-- ^ Flag indicating whether or not to filter by percent value of
-- the column. A false value filters by number of items.
, _efoVal :: Double
-- ^ Top or bottom value to use as the filter criteria.
-- Example: "Filter by Top 10 Percent" or "Filter by Top 5 Items"
, _efoFilterVal :: Maybe Double
-- ^ The actual cell value in the range which is used to perform the
-- comparison for this filter.
} deriving (Eq, Show, Generic)
instance NFData EdgeFilterOptions
-- | Specifies the color to filter by and whether to use the cell's
-- fill or font color in the filter criteria. If the cell's font or
-- fill color does not match the color specified in the criteria, the
-- rows corresponding to those cells are hidden from view.
--
-- See 18.3.2.1 "colorFilter (Color Filter Criteria)" (p. 1712)
data ColorFilterOptions = ColorFilterOptions
{ _cfoCellColor :: Bool
-- ^ Flag indicating whether or not to filter by the cell's fill
-- color. 'True' indicates to filter by cell fill. 'False' indicates
-- to filter by the cell's font color.
--
-- For rich text in cells, if the color specified appears in the
-- cell at all, it shall be included in the filter.
, _cfoDxfId :: Maybe Int
-- ^ Id of differential format record (dxf) in the Styles Part (see
-- '_styleSheetDxfs') which expresses the color value to filter by.
} deriving (Eq, Show, Generic)
instance NFData ColorFilterOptions
-- | Specifies dynamic filter criteria. These criteria are considered
-- dynamic because they can change, either with the data itself (e.g.,
-- "above average") or with the current system date (e.g., show values
-- for "today"). For any cells whose values do not meet the specified
-- criteria, the corresponding rows shall be hidden from view when the
-- filter is applied.
--
-- '_dfoMaxVal' shall be required for 'DynFilterTday',
-- 'DynFilterYesterday', 'DynFilterTomorrow', 'DynFilterNextWeek',
-- 'DynFilterThisWeek', 'DynFilterLastWeek', 'DynFilterNextMonth',
-- 'DynFilterThisMonth', 'DynFilterLastMonth', 'DynFilterNextQuarter',
-- 'DynFilterThisQuarter', 'DynFilterLastQuarter',
-- 'DynFilterNextYear', 'DynFilterThisYear', 'DynFilterLastYear', and
-- 'DynFilterYearToDate.
--
-- The above criteria are based on a value range; that is, if today's
-- date is September 22nd, then the range for thisWeek is the values
-- greater than or equal to September 17 and less than September
-- 24. In the thisWeek range, the lower value is expressed
-- '_dfoval'. The higher value is expressed using '_dfoMmaxVal'.
--
-- These dynamic filters shall not require '_dfoVal or '_dfoMaxVal':
-- 'DynFilterQ1', 'DynFilterQ2', 'DynFilterQ3', 'DynFilterQ4',
-- 'DynFilterM1', 'DynFilterM2', 'DynFilterM3', 'DynFilterM4',
-- 'DynFilterM5', 'DynFilterM6', 'DynFilterM7', 'DynFilterM8',
-- 'DynFilterM9', 'DynFilterM10', 'DynFilterM11' and 'DynFilterM12'.
--
-- The above criteria shall not specify the range using valIso and
-- maxValIso because Q1 always starts from M1 to M3, and M1 is always
-- January.
--
-- These types of dynamic filters shall use valIso and shall not use
-- '_dfoMaxVal': 'DynFilterAboveAverage' and 'DynFilterBelowAverage'
--
-- /Note:/ Specification lists 'valIso' and 'maxIso' to store datetime
-- values but it appears that Excel doesn't use them and stored them
-- as numeric values (as it does for datetimes in cell values)
--
-- See 18.3.2.5 "dynamicFilter (Dynamic Filter)" (p. 1715)
data DynFilterOptions = DynFilterOptions
{ _dfoType :: DynFilterType
, _dfoVal :: Maybe Double
-- ^ A minimum numeric value for dynamic filter.
, _dfoMaxVal :: Maybe Double
-- ^ A maximum value for dynamic filter.
} deriving (Eq, Show, Generic)
instance NFData DynFilterOptions
-- | Specifies concrete type of dynamic filter used
--
-- See 18.18.26 "ST_DynamicFilterType (Dynamic Filter)" (p. 2452)
data DynFilterType
= DynFilterAboveAverage
-- ^ Shows values that are above average.
| DynFilterBelowAverage
-- ^ Shows values that are below average.
| DynFilterLastMonth
-- ^ Shows last month's dates.
| DynFilterLastQuarter
-- ^ Shows last calendar quarter's dates.
| DynFilterLastWeek
-- ^ Shows last week's dates, using Sunday as the first weekday.
| DynFilterLastYear
-- ^ Shows last year's dates.
| DynFilterM1
-- ^ Shows the dates that are in January, regardless of year.
| DynFilterM10
-- ^ Shows the dates that are in October, regardless of year.
| DynFilterM11
-- ^ Shows the dates that are in November, regardless of year.
| DynFilterM12
-- ^ Shows the dates that are in December, regardless of year.
| DynFilterM2
-- ^ Shows the dates that are in February, regardless of year.
| DynFilterM3
-- ^ Shows the dates that are in March, regardless of year.
| DynFilterM4
-- ^ Shows the dates that are in April, regardless of year.
| DynFilterM5
-- ^ Shows the dates that are in May, regardless of year.
| DynFilterM6
-- ^ Shows the dates that are in June, regardless of year.
| DynFilterM7
-- ^ Shows the dates that are in July, regardless of year.
| DynFilterM8
-- ^ Shows the dates that are in August, regardless of year.
| DynFilterM9
-- ^ Shows the dates that are in September, regardless of year.
| DynFilterNextMonth
-- ^ Shows next month's dates.
| DynFilterNextQuarter
-- ^ Shows next calendar quarter's dates.
| DynFilterNextWeek
-- ^ Shows next week's dates, using Sunday as the first weekday.
| DynFilterNextYear
-- ^ Shows next year's dates.
| DynFilterNull
-- ^ Common filter type not available.
| DynFilterQ1
-- ^ Shows the dates that are in the 1st calendar quarter,
-- regardless of year.
| DynFilterQ2
-- ^ Shows the dates that are in the 2nd calendar quarter,
-- regardless of year.
| DynFilterQ3
-- ^ Shows the dates that are in the 3rd calendar quarter,
-- regardless of year.
| DynFilterQ4
-- ^ Shows the dates that are in the 4th calendar quarter,
-- regardless of year.
| DynFilterThisMonth
-- ^ Shows this month's dates.
| DynFilterThisQuarter
-- ^ Shows this calendar quarter's dates.
| DynFilterThisWeek
-- ^ Shows this week's dates, using Sunday as the first weekday.
| DynFilterThisYear
-- ^ Shows this year's dates.
| DynFilterToday
-- ^ Shows today's dates.
| DynFilterTomorrow
-- ^ Shows tomorrow's dates.
| DynFilterYearToDate
-- ^ Shows the dates between the beginning of the year and today, inclusive.
| DynFilterYesterday
-- ^ Shows yesterday's dates.
deriving (Eq, Show, Generic)
instance NFData DynFilterType
-- | AutoFilter temporarily hides rows based on a filter criteria,
-- which is applied column by column to a table of datain the
-- worksheet.
--
-- TODO: sortState, extList
--
-- See 18.3.1.2 "autoFilter (AutoFilter Settings)" (p. 1596)
data AutoFilter = AutoFilter
{ _afRef :: Maybe CellRef
, _afFilterColumns :: Map Int FilterColumn
} deriving (Eq, Show, Generic)
instance NFData AutoFilter
makeLenses ''AutoFilter
{-------------------------------------------------------------------------------
Default instances
-------------------------------------------------------------------------------}
instance Default AutoFilter where
def = AutoFilter Nothing M.empty
{-------------------------------------------------------------------------------
Parsing
-------------------------------------------------------------------------------}
instance FromCursor AutoFilter where
fromCursor cur = do
_afRef <- maybeAttribute "ref" cur
let _afFilterColumns = M.fromList $ cur $/ element (n_ "filterColumn") >=> \c -> do
colId <- fromAttribute "colId" c
fcol <- c $/ anyElement >=> fltColFromNode . node
return (colId, fcol)
return AutoFilter {..}
instance FromXenoNode AutoFilter where
fromXenoNode root = do
_afRef <- parseAttributes root $ maybeAttr "ref"
_afFilterColumns <-
fmap M.fromList . collectChildren root $ fromChildList "filterColumn"
return AutoFilter {..}
instance FromXenoNode (Int, FilterColumn) where
fromXenoNode root = do
colId <- parseAttributes root $ fromAttr "colId"
fCol <-
collectChildren root $ asum [filters, color, custom, dynamic, icon, top10]
return (colId, fCol)
where
filters =
requireAndParse "filters" $ \node -> do
filterBlank <-
parseAttributes node $ fromAttrDef "blank" DontFilterByBlank
filterCriteria <- childListAny node
return $ Filters filterBlank filterCriteria
color =
requireAndParse "colorFilter" $ \node ->
parseAttributes node $ do
_cfoCellColor <- fromAttrDef "cellColor" True
_cfoDxfId <- maybeAttr "dxfId"
return $ ColorFilter ColorFilterOptions {..}
custom =
requireAndParse "customFilters" $ \node -> do
isAnd <- parseAttributes node $ fromAttrDef "and" False
cfilters <- collectChildren node $ fromChildList "customFilter"
case cfilters of
[f] -> return $ ACustomFilter f
[f1, f2] ->
if isAnd
then return $ CustomFiltersAnd f1 f2
else return $ CustomFiltersOr f1 f2
_ ->
Left $
"expected 1 or 2 custom filters but found " <>
T.pack (show $ length cfilters)
dynamic =
requireAndParse "dynamicFilter" . flip parseAttributes $ do
_dfoType <- fromAttr "type"
_dfoVal <- maybeAttr "val"
_dfoMaxVal <- maybeAttr "maxVal"
return $ DynamicFilter DynFilterOptions {..}
icon =
requireAndParse "iconFilter" . flip parseAttributes $
IconFilter <$> maybeAttr "iconId" <*> fromAttr "iconSet"
top10 =
requireAndParse "top10" . flip parseAttributes $ do
top <- fromAttrDef "top" True
percent <- fromAttrDef "percent" False
val <- fromAttr "val"
filterVal <- maybeAttr "filterVal"
let opts = EdgeFilterOptions percent val filterVal
if top
then return $ TopNFilter opts
else return $ BottomNFilter opts
instance FromXenoNode CustomFilter where
fromXenoNode root =
parseAttributes root $
CustomFilter <$> fromAttrDef "operator" FltrEqual <*> fromAttr "val"
fltColFromNode :: Node -> [FilterColumn]
fltColFromNode n | n `nodeElNameIs` (n_ "filters") = do
let filterCriteria = cur $/ anyElement >=> fromCursor
filterBlank <- fromAttributeDef "blank" DontFilterByBlank cur
return $ Filters filterBlank filterCriteria
| n `nodeElNameIs` (n_ "colorFilter") = do
_cfoCellColor <- fromAttributeDef "cellColor" True cur
_cfoDxfId <- maybeAttribute "dxfId" cur
return $ ColorFilter ColorFilterOptions {..}
| n `nodeElNameIs` (n_ "customFilters") = do
isAnd <- fromAttributeDef "and" False cur
let cFilters = cur $/ element (n_ "customFilter") >=> \c -> do
op <- fromAttributeDef "operator" FltrEqual c
val <- fromAttribute "val" c
return $ CustomFilter op val
case cFilters of
[f] ->
return $ ACustomFilter f
[f1, f2] ->
if isAnd
then return $ CustomFiltersAnd f1 f2
else return $ CustomFiltersOr f1 f2
_ ->
fail "bad custom filter"
| n `nodeElNameIs` (n_ "dynamicFilter") = do
_dfoType <- fromAttribute "type" cur
_dfoVal <- maybeAttribute "val" cur
_dfoMaxVal <- maybeAttribute "maxVal" cur
return $ DynamicFilter DynFilterOptions{..}
| n `nodeElNameIs` (n_ "iconFilter") = do
iconId <- maybeAttribute "iconId" cur
iconSet <- fromAttribute "iconSet" cur
return $ IconFilter iconId iconSet
| n `nodeElNameIs` (n_ "top10") = do
top <- fromAttributeDef "top" True cur
let percent = fromAttributeDef "percent" False cur
val = fromAttribute "val" cur
filterVal = maybeAttribute "filterVal" cur
if top
then fmap TopNFilter $
EdgeFilterOptions <$> percent <*> val <*> filterVal
else fmap BottomNFilter $
EdgeFilterOptions <$> percent <*> val <*> filterVal
| otherwise = fail "no matching nodes"
where
cur = fromNode n
instance FromCursor FilterCriterion where
fromCursor = filterCriterionFromNode . node
instance FromXenoNode FilterCriterion where
fromXenoNode root =
case Xeno.name root of
"filter" -> parseAttributes root $ do FilterValue <$> fromAttr "val"
"dateGroupItem" ->
parseAttributes root $ do
grouping <- fromAttr "dateTimeGrouping"
group <- case grouping of
("year" :: ByteString) ->
DateGroupByYear <$> fromAttr "year"
"month" ->
DateGroupByMonth <$> fromAttr "year"
<*> fromAttr "month"
"day" ->
DateGroupByDay <$> fromAttr "year"
<*> fromAttr "month"
<*> fromAttr "day"
"hour" ->
DateGroupByHour <$> fromAttr "year"
<*> fromAttr "month"
<*> fromAttr "day"
<*> fromAttr "hour"
"minute" ->
DateGroupByMinute <$> fromAttr "year"
<*> fromAttr "month"
<*> fromAttr "day"
<*> fromAttr "hour"
<*> fromAttr "minute"
"second" ->
DateGroupBySecond <$> fromAttr "year"
<*> fromAttr "month"
<*> fromAttr "day"
<*> fromAttr "hour"
<*> fromAttr "minute"
<*> fromAttr "second"
_ -> toAttrParser . Left $ "Unexpected date grouping"
return $ FilterDateGroup group
_ -> Left "Bad FilterCriterion"
-- TODO: follow the spec about the fact that dategroupitem always go after filter
filterCriterionFromNode :: Node -> [FilterCriterion]
filterCriterionFromNode n
| n `nodeElNameIs` (n_ "filter") = do
v <- fromAttribute "val" cur
return $ FilterValue v
| n `nodeElNameIs` (n_ "dateGroupItem") = do
g <- fromAttribute "dateTimeGrouping" cur
let year = fromAttribute "year" cur
month = fromAttribute "month" cur
day = fromAttribute "day" cur
hour = fromAttribute "hour" cur
minute = fromAttribute "minute" cur
second = fromAttribute "second" cur
FilterDateGroup <$>
case g of
"year" -> DateGroupByYear <$> year
"month" -> DateGroupByMonth <$> year <*> month
"day" -> DateGroupByDay <$> year <*> month <*> day
"hour" -> DateGroupByHour <$> year <*> month <*> day <*> hour
"minute" ->
DateGroupByMinute <$> year <*> month <*> day <*> hour <*> minute
"second" ->
DateGroupBySecond <$> year <*> month <*> day <*> hour <*> minute <*>
second
_ -> fail $ "unexpected dateTimeGrouping " ++ show (g :: Text)
| otherwise = fail "no matching nodes"
where
cur = fromNode n
instance FromAttrVal CustomFilterOperator where
fromAttrVal "equal" = readSuccess FltrEqual
fromAttrVal "greaterThan" = readSuccess FltrGreaterThan
fromAttrVal "greaterThanOrEqual" = readSuccess FltrGreaterThanOrEqual
fromAttrVal "lessThan" = readSuccess FltrLessThan
fromAttrVal "lessThanOrEqual" = readSuccess FltrLessThanOrEqual
fromAttrVal "notEqual" = readSuccess FltrNotEqual
fromAttrVal t = invalidText "CustomFilterOperator" t
instance FromAttrBs CustomFilterOperator where
fromAttrBs "equal" = return FltrEqual
fromAttrBs "greaterThan" = return FltrGreaterThan
fromAttrBs "greaterThanOrEqual" = return FltrGreaterThanOrEqual
fromAttrBs "lessThan" = return FltrLessThan
fromAttrBs "lessThanOrEqual" = return FltrLessThanOrEqual
fromAttrBs "notEqual" = return FltrNotEqual
fromAttrBs x = unexpectedAttrBs "CustomFilterOperator" x
instance FromAttrVal FilterByBlank where
fromAttrVal =
fmap (first $ bool DontFilterByBlank FilterByBlank) . fromAttrVal
instance FromAttrBs FilterByBlank where
fromAttrBs = fmap (bool DontFilterByBlank FilterByBlank) . fromAttrBs
instance FromAttrVal DynFilterType where
fromAttrVal "aboveAverage" = readSuccess DynFilterAboveAverage
fromAttrVal "belowAverage" = readSuccess DynFilterBelowAverage
fromAttrVal "lastMonth" = readSuccess DynFilterLastMonth
fromAttrVal "lastQuarter" = readSuccess DynFilterLastQuarter
fromAttrVal "lastWeek" = readSuccess DynFilterLastWeek
fromAttrVal "lastYear" = readSuccess DynFilterLastYear
fromAttrVal "M1" = readSuccess DynFilterM1
fromAttrVal "M10" = readSuccess DynFilterM10
fromAttrVal "M11" = readSuccess DynFilterM11
fromAttrVal "M12" = readSuccess DynFilterM12
fromAttrVal "M2" = readSuccess DynFilterM2
fromAttrVal "M3" = readSuccess DynFilterM3
fromAttrVal "M4" = readSuccess DynFilterM4
fromAttrVal "M5" = readSuccess DynFilterM5
fromAttrVal "M6" = readSuccess DynFilterM6
fromAttrVal "M7" = readSuccess DynFilterM7
fromAttrVal "M8" = readSuccess DynFilterM8
fromAttrVal "M9" = readSuccess DynFilterM9
fromAttrVal "nextMonth" = readSuccess DynFilterNextMonth
fromAttrVal "nextQuarter" = readSuccess DynFilterNextQuarter
fromAttrVal "nextWeek" = readSuccess DynFilterNextWeek
fromAttrVal "nextYear" = readSuccess DynFilterNextYear
fromAttrVal "null" = readSuccess DynFilterNull
fromAttrVal "Q1" = readSuccess DynFilterQ1
fromAttrVal "Q2" = readSuccess DynFilterQ2
fromAttrVal "Q3" = readSuccess DynFilterQ3
fromAttrVal "Q4" = readSuccess DynFilterQ4
fromAttrVal "thisMonth" = readSuccess DynFilterThisMonth
fromAttrVal "thisQuarter" = readSuccess DynFilterThisQuarter
fromAttrVal "thisWeek" = readSuccess DynFilterThisWeek
fromAttrVal "thisYear" = readSuccess DynFilterThisYear
fromAttrVal "today" = readSuccess DynFilterToday
fromAttrVal "tomorrow" = readSuccess DynFilterTomorrow
fromAttrVal "yearToDate" = readSuccess DynFilterYearToDate
fromAttrVal "yesterday" = readSuccess DynFilterYesterday
fromAttrVal t = invalidText "DynFilterType" t
instance FromAttrBs DynFilterType where
fromAttrBs "aboveAverage" = return DynFilterAboveAverage
fromAttrBs "belowAverage" = return DynFilterBelowAverage
fromAttrBs "lastMonth" = return DynFilterLastMonth
fromAttrBs "lastQuarter" = return DynFilterLastQuarter
fromAttrBs "lastWeek" = return DynFilterLastWeek
fromAttrBs "lastYear" = return DynFilterLastYear
fromAttrBs "M1" = return DynFilterM1
fromAttrBs "M10" = return DynFilterM10
fromAttrBs "M11" = return DynFilterM11
fromAttrBs "M12" = return DynFilterM12
fromAttrBs "M2" = return DynFilterM2
fromAttrBs "M3" = return DynFilterM3
fromAttrBs "M4" = return DynFilterM4
fromAttrBs "M5" = return DynFilterM5
fromAttrBs "M6" = return DynFilterM6
fromAttrBs "M7" = return DynFilterM7
fromAttrBs "M8" = return DynFilterM8
fromAttrBs "M9" = return DynFilterM9
fromAttrBs "nextMonth" = return DynFilterNextMonth
fromAttrBs "nextQuarter" = return DynFilterNextQuarter
fromAttrBs "nextWeek" = return DynFilterNextWeek
fromAttrBs "nextYear" = return DynFilterNextYear
fromAttrBs "null" = return DynFilterNull
fromAttrBs "Q1" = return DynFilterQ1
fromAttrBs "Q2" = return DynFilterQ2
fromAttrBs "Q3" = return DynFilterQ3
fromAttrBs "Q4" = return DynFilterQ4
fromAttrBs "thisMonth" = return DynFilterThisMonth
fromAttrBs "thisQuarter" = return DynFilterThisQuarter
fromAttrBs "thisWeek" = return DynFilterThisWeek
fromAttrBs "thisYear" = return DynFilterThisYear
fromAttrBs "today" = return DynFilterToday
fromAttrBs "tomorrow" = return DynFilterTomorrow
fromAttrBs "yearToDate" = return DynFilterYearToDate
fromAttrBs "yesterday" = return DynFilterYesterday
fromAttrBs x = unexpectedAttrBs "DynFilterType" x
{-------------------------------------------------------------------------------
Rendering
-------------------------------------------------------------------------------}
instance ToElement AutoFilter where
toElement nm AutoFilter {..} =
elementList
nm
(catMaybes ["ref" .=? _afRef])
[ elementList
(n_ "filterColumn")
["colId" .= colId]
[fltColToElement fCol]
| (colId, fCol) <- M.toList _afFilterColumns
]
fltColToElement :: FilterColumn -> Element
fltColToElement (Filters filterBlank filterCriteria) =
let attrs = catMaybes ["blank" .=? justNonDef DontFilterByBlank filterBlank]
in elementList
(n_ "filters") attrs $ map filterCriterionToElement filterCriteria
fltColToElement (ColorFilter opts) = toElement (n_ "colorFilter") opts
fltColToElement (ACustomFilter f) =
elementListSimple (n_ "customFilters") [toElement (n_ "customFilter") f]
fltColToElement (CustomFiltersOr f1 f2) =
elementListSimple
(n_ "customFilters")
[toElement (n_ "customFilter") f | f <- [f1, f2]]
fltColToElement (CustomFiltersAnd f1 f2) =
elementList
(n_ "customFilters")
["and" .= True]
[toElement (n_ "customFilter") f | f <- [f1, f2]]
fltColToElement (DynamicFilter opts) = toElement (n_ "dynamicFilter") opts
fltColToElement (IconFilter iconId iconSet) =
leafElement (n_ "iconFilter") $
["iconSet" .= iconSet] ++ catMaybes ["iconId" .=? iconId]
fltColToElement (BottomNFilter opts) = edgeFilter False opts
fltColToElement (TopNFilter opts) = edgeFilter True opts
edgeFilter :: Bool -> EdgeFilterOptions -> Element
edgeFilter top EdgeFilterOptions {..} =
leafElement (n_ "top10") $
["top" .= top, "percent" .= _efoUsePercents, "val" .= _efoVal] ++
catMaybes ["filterVal" .=? _efoFilterVal]
filterCriterionToElement :: FilterCriterion -> Element
filterCriterionToElement (FilterValue v) =
leafElement (n_ "filter") ["val" .= v]
filterCriterionToElement (FilterDateGroup (DateGroupByYear y)) =
leafElement
(n_ "dateGroupItem")
["dateTimeGrouping" .= ("year" :: Text), "year" .= y]
filterCriterionToElement (FilterDateGroup (DateGroupByMonth y m)) =
leafElement
(n_ "dateGroupItem")
["dateTimeGrouping" .= ("month" :: Text), "year" .= y, "month" .= m]
filterCriterionToElement (FilterDateGroup (DateGroupByDay y m d)) =
leafElement
(n_ "dateGroupItem")
["dateTimeGrouping" .= ("day" :: Text), "year" .= y, "month" .= m, "day" .= d]
filterCriterionToElement (FilterDateGroup (DateGroupByHour y m d h)) =
leafElement
(n_ "dateGroupItem")
[ "dateTimeGrouping" .= ("hour" :: Text)
, "year" .= y
, "month" .= m
, "day" .= d
, "hour" .= h
]
filterCriterionToElement (FilterDateGroup (DateGroupByMinute y m d h mi)) =
leafElement
(n_ "dateGroupItem")
[ "dateTimeGrouping" .= ("minute" :: Text)
, "year" .= y
, "month" .= m
, "day" .= d
, "hour" .= h
, "minute" .= mi
]
filterCriterionToElement (FilterDateGroup (DateGroupBySecond y m d h mi s)) =
leafElement
(n_ "dateGroupItem")
[ "dateTimeGrouping" .= ("second" :: Text)
, "year" .= y
, "month" .= m
, "day" .= d
, "hour" .= h
, "minute" .= mi
, "second" .= s
]
instance ToElement CustomFilter where
toElement nm CustomFilter {..} =
leafElement nm ["operator" .= cfltOperator, "val" .= cfltValue]
instance ToAttrVal CustomFilterOperator where
toAttrVal FltrEqual = "equal"
toAttrVal FltrGreaterThan = "greaterThan"
toAttrVal FltrGreaterThanOrEqual = "greaterThanOrEqual"
toAttrVal FltrLessThan = "lessThan"
toAttrVal FltrLessThanOrEqual = "lessThanOrEqual"
toAttrVal FltrNotEqual = "notEqual"
instance ToAttrVal FilterByBlank where
toAttrVal FilterByBlank = toAttrVal True
toAttrVal DontFilterByBlank = toAttrVal False
instance ToElement ColorFilterOptions where
toElement nm ColorFilterOptions {..} =
leafElement nm $
catMaybes ["cellColor" .=? justFalse _cfoCellColor, "dxfId" .=? _cfoDxfId]
instance ToElement DynFilterOptions where
toElement nm DynFilterOptions {..} =
leafElement nm $
["type" .= _dfoType] ++
catMaybes ["val" .=? _dfoVal, "maxVal" .=? _dfoMaxVal]
instance ToAttrVal DynFilterType where
toAttrVal DynFilterAboveAverage = "aboveAverage"
toAttrVal DynFilterBelowAverage = "belowAverage"
toAttrVal DynFilterLastMonth = "lastMonth"
toAttrVal DynFilterLastQuarter = "lastQuarter"
toAttrVal DynFilterLastWeek = "lastWeek"
toAttrVal DynFilterLastYear = "lastYear"
toAttrVal DynFilterM1 = "M1"
toAttrVal DynFilterM10 = "M10"
toAttrVal DynFilterM11 = "M11"
toAttrVal DynFilterM12 = "M12"
toAttrVal DynFilterM2 = "M2"
toAttrVal DynFilterM3 = "M3"
toAttrVal DynFilterM4 = "M4"
toAttrVal DynFilterM5 = "M5"
toAttrVal DynFilterM6 = "M6"
toAttrVal DynFilterM7 = "M7"
toAttrVal DynFilterM8 = "M8"
toAttrVal DynFilterM9 = "M9"
toAttrVal DynFilterNextMonth = "nextMonth"
toAttrVal DynFilterNextQuarter = "nextQuarter"
toAttrVal DynFilterNextWeek = "nextWeek"
toAttrVal DynFilterNextYear = "nextYear"
toAttrVal DynFilterNull = "null"
toAttrVal DynFilterQ1 = "Q1"
toAttrVal DynFilterQ2 = "Q2"
toAttrVal DynFilterQ3 = "Q3"
toAttrVal DynFilterQ4 = "Q4"
toAttrVal DynFilterThisMonth = "thisMonth"
toAttrVal DynFilterThisQuarter = "thisQuarter"
toAttrVal DynFilterThisWeek = "thisWeek"
toAttrVal DynFilterThisYear = "thisYear"
toAttrVal DynFilterToday = "today"
toAttrVal DynFilterTomorrow = "tomorrow"
toAttrVal DynFilterYearToDate = "yearToDate"
toAttrVal DynFilterYesterday = "yesterday"
| {
"pile_set_name": "Github"
} |
CREATE TABLE "PersistentMessage" (
"PeerId" ascii,
"BucketId" bigint,
"UniqueTimestampInTicks" bigint,
"IsAcked" boolean,
"TransportMessage" blob,
PRIMARY KEY (( "PeerId", "BucketId" ), "UniqueTimestampInTicks")
); | {
"pile_set_name": "Github"
} |
package org.incode.platform.dom.document.integtests.demo.dom.order;
import java.math.BigDecimal;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.VersionStrategy;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.google.common.collect.Ordering;
import org.apache.isis.applib.annotation.BookmarkPolicy;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.DomainObjectLayout;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.Property;
import org.apache.isis.applib.annotation.Title;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.schema.utils.jaxbadapters.PersistentEntityAdapter;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@javax.jdo.annotations.PersistenceCapable(
identityType=IdentityType.DATASTORE,
schema = "exampleDemoDocument"
)
@javax.jdo.annotations.DatastoreIdentity(
strategy=javax.jdo.annotations.IdGeneratorStrategy.IDENTITY,
column="id")
@javax.jdo.annotations.Version(
strategy=VersionStrategy.VERSION_NUMBER,
column="version")
@DomainObject()
@DomainObjectLayout(
bookmarking = BookmarkPolicy.AS_CHILD
)
@AllArgsConstructor
@Builder
@XmlJavaTypeAdapter(PersistentEntityAdapter.class)
public class DemoOrderLine implements Comparable<DemoOrderLine> {
@javax.jdo.annotations.Column(allowsNull="false")
@Property(hidden = Where.REFERENCES_PARENT)
@MemberOrder(sequence = "1")
@Getter @Setter
private DemoOrder order;
@javax.jdo.annotations.Column(allowsNull="false")
@Title(sequence="1")
@MemberOrder(sequence="2")
@Getter @Setter
private String description;
@Getter @Setter
@MemberOrder(sequence = "3")
private int quantity;
@javax.jdo.annotations.Column(allowsNull="true", scale=2)
@javax.validation.constraints.Digits(integer=10, fraction=2)
@MemberOrder(sequence = "4")
@Getter @Setter
private BigDecimal cost;
@Override
public int compareTo(DemoOrderLine other) {
return Ordering.natural().onResultOf(DemoOrderLine::getDescription).compare(this, other);
}
}
| {
"pile_set_name": "Github"
} |
/**
* Toolbar
* A basic navigation element, primary used for top level navigation
*/
$am-toolbar-base-font-size : am-sp(14) !default;
$am-toolbar-title-font-size : am-sp(20) !default;
$am-toolbar-keyline-small : am-unit(7) !default;
$am-toolbar-keyline-medium : $am-toolbar-keyline-small + 8px !default;
@mixin am-toolbar {
@include am-type-smooth;
align-items: center;
display: flex;
flex-wrap: wrap;
font-size: $am-toolbar-base-font-size;
position: relative;
}
@mixin am-toolbar-primary {
@include am-fill(primary);
@include am-color(text-light);
}
@mixin am-toolbar-title {
font-size: $am-toolbar-title-font-size;
font-weight: $am-font-weight-medium;
line-height: am-unit(2);
padding: am-unit(2);
width: 100%;
text-align: left;
@include am-min-breakpoint($am-breakpoint-medium) {
width: auto;
}
}
@mixin am-toolbar-list {
margin: 0 0 0 am-unit(2);
padding: 0;
text-align: left;
}
@mixin am-toolbar-item {
@include am-link-no-decoration;
@include am-color(text);
display: inline-block;
font-weight: $am-font-weight-medium;
line-height: am-unit(3);
margin: 0;
}
@mixin am-toolbar-item-primary {
@include am-link-no-decoration;
@include am-color(text-light);
display: block;
line-height: am-unit(2);
padding: am-unit(2) am-unit(1);
text-align: center;
&:hover,
&:focus {
@include am-color(accent);
}
}
@mixin am-toolbar-item-primary-active {
@include am-color(accent);
font-weight: $am-font-weight-semi-bold;
}
| {
"pile_set_name": "Github"
} |
export * from './ScrollContainer';
| {
"pile_set_name": "Github"
} |
<?php
namespace GV;
/** If this file is called directly, abort. */
if ( ! defined( 'GRAVITYVIEW_DIR' ) ) {
die();
}
/**
* A generic Settings base class.
*/
class Settings {
/**
* @var array Main storage for key-values in this collection.
*/
private $settings = array();
/**
* Create with new.
*
* @api
* @since 2.0
*
* @param array $settings Initial settings. Default: none.
* @return \GV\Settings
*/
public function __construct( $settings = array() ) {
if ( is_array( $settings ) && ! empty( $settings ) ) {
$this->update( $settings );
}
}
/**
* Mass update values from the allowed ones.
*
* @api
* @since 2.0
*
* @param array $settings An array of settings to update.
* @return \GV\Settings self chain.
*/
public function update( $settings ) {
foreach ( $settings as $key => $value ) {
$this->set( $key, $value );
}
return $this;
}
/**
* Set a setting.
*
* @param mixed $key The key the value should be added under.
* @param mixed $value The value to be added to the key.
*
* @api
* @since 2.0
* @return void
*/
public function set( $key, $value ) {
$this->settings[ $key ] = $value;
}
/**
* Set an setting.
*
* @param mixed $key The key in this setting to retrieve.
* @param mixed $default A default in case the key is not set.
*
* @api
* @since 2.0
* @return mixed|null
*/
public function get( $key, $default = null ) {
return Utils::get( $this->settings, $key, $default );
}
/**
* Returns all the objects in this collection as an an array.
*
* @api
* @since 2.0
* @return array The objects in this collection.
*/
public function all() {
return $this->settings;
}
}
| {
"pile_set_name": "Github"
} |
/* plugin_common - Routines common to several plugins
* Copyright (C) 2002-2009 Josh Coalson
* Copyright (C) 2011-2016 Xiph.Org Foundation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef FLAC__PLUGIN_COMMON__TAGS_H
#define FLAC__PLUGIN_COMMON__TAGS_H
#include "FLAC/format.h"
FLAC__bool FLAC_plugin__tags_get(const char *filename, FLAC__StreamMetadata **tags);
FLAC__bool FLAC_plugin__tags_set(const char *filename, const FLAC__StreamMetadata *tags);
/*
* Deletes the tags object and sets '*tags' to NULL.
*/
void FLAC_plugin__tags_destroy(FLAC__StreamMetadata **tags);
/*
* Gets the value (in UTF-8) of the first tag with the given name (NULL if no
* such tag exists).
*/
const char *FLAC_plugin__tags_get_tag_utf8(const FLAC__StreamMetadata *tags, const char *name);
/*
* Gets the value (in UCS-2) of the first tag with the given name (NULL if no
* such tag exists).
*
* NOTE: the returned string is malloc()ed and must be free()d by the caller.
*/
FLAC__uint16 *FLAC_plugin__tags_get_tag_ucs2(const FLAC__StreamMetadata *tags, const char *name);
/*
* Removes all tags with the given 'name'. Returns the number of tags removed,
* or -1 on memory allocation error.
*/
int FLAC_plugin__tags_delete_tag(FLAC__StreamMetadata *tags, const char *name);
/*
* Removes all tags. Returns the number of tags removed, or -1 on memory
* allocation error.
*/
int FLAC_plugin__tags_delete_all(FLAC__StreamMetadata *tags);
/*
* Adds a "name=value" tag to the tags. 'value' must be in UTF-8. If
* 'separator' is non-NULL and 'tags' already contains a tag for 'name', the
* first such tag's value is appended with separator, then value.
*/
FLAC__bool FLAC_plugin__tags_add_tag_utf8(FLAC__StreamMetadata *tags, const char *name, const char *value, const char *separator);
/*
* Adds a "name=value" tag to the tags. 'value' must be in UCS-2. If 'tags'
* already contains a tag or tags for 'name', then they will be replaced
* according to 'replace_all': if 'replace_all' is false, only the first such
* tag will be replaced; if true, all matching tags will be replaced by the one
* new tag.
*/
FLAC__bool FLAC_plugin__tags_set_tag_ucs2(FLAC__StreamMetadata *tags, const char *name, const FLAC__uint16 *value, FLAC__bool replace_all);
#endif
| {
"pile_set_name": "Github"
} |
/*
* Component: Project list view
*/
@media only screen and (min-width: 768px){
.project-list-view {
.pm-project-column {
flex-basis: 100% !important;
max-width: 100% !important;
}
.pm-project-item {
display: flex;
flex-wrap: wrap;
align-items: center;
position: relative;
}
.pm-project-item-header {
flex-basis: 20% !important;
max-width: 20% !important;
.pm-project-settings {
position: absolute;
right: 15px;
top: calc(50% - 13px);
}
.pm-project-title {
margin-bottom: 0;
}
}
.pm-project-item-body {
flex-basis: calc(80% - 50px) !important;
max-width: calc(80% - 50px) !important;
}
.pm-project-info {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
.pm-project-description {
display: none;
}
.pm-project-meta-counters {
margin-bottom: -10px !important;
}
.pm-project-users {
margin-top: 0 !important;
margin-left: 40px;
margin-bottom: -8px;
}
.pm-project-meta-counters,
.pm-project-progress,
.pm-project-users {
flex-grow: 4;
}
.pm-project-progress {
width: auto !important;
display: inherit !important;
min-width: 120px;
margin: 0 40px !important;
order: 2;
}
}
}
} | {
"pile_set_name": "Github"
} |
\begin{code}
data (a :: k1) :<< (b :: k2)
infixr 5 :<<
\end{code}
| {
"pile_set_name": "Github"
} |
/**
* jQuery EasyUI 1.3.3
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: [email protected]
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
*/
(function ($) {
function _1(el, _2, _3, _4) {
var _5 = $(el).window("window");
if (!_5) {
return;
}
switch (_2) {
case null:
_5.show();
break;
case "slide":
_5.slideDown(_3);
break;
case "fade":
_5.fadeIn(_3);
break;
case "show":
_5.show(_3);
break;
}
var _6 = null;
if (_4 > 0) {
_6 = setTimeout(function () {
_7(el, _2, _3);
}, _4);
}
_5.hover(function () {
if (_6) {
clearTimeout(_6);
}
}, function () {
if (_4 > 0) {
_6 = setTimeout(function () {
_7(el, _2, _3);
}, _4);
}
});
};
function _7(el, _8, _9) {
if (el.locked == true) {
return;
}
el.locked = true;
var _a = $(el).window("window");
if (!_a) {
return;
}
switch (_8) {
case null:
_a.hide();
break;
case "slide":
_a.slideUp(_9);
break;
case "fade":
_a.fadeOut(_9);
break;
case "show":
_a.hide(_9);
break;
}
setTimeout(function () {
$(el).window("destroy");
}, _9);
};
function _b(_c) {
var _d = $.extend({}, $.fn.window.defaults, {
collapsible: false,
minimizable: false,
maximizable: false,
shadow: false,
draggable: false,
resizable: false,
closed: true,
style: {
left: "",
top: "",
right: 0,
zIndex: $.fn.window.defaults.zIndex++,
bottom: -document.body.scrollTop - document.documentElement.scrollTop
},
onBeforeOpen: function () {
_1(this, _d.showType, _d.showSpeed, _d.timeout);
return false;
},
onBeforeClose: function () {
_7(this, _d.showType, _d.showSpeed);
return false;
}
}, {title: "", width: 250, height: 100, showType: "slide", showSpeed: 600, msg: "", timeout: 4000}, _c);
_d.style.zIndex = $.fn.window.defaults.zIndex++;
var _e = $("<div class=\"messager-body\"></div>").html(_d.msg).appendTo("body");
_e.window(_d);
_e.window("window").css(_d.style);
_e.window("open");
return _e;
};
function _f(_10, _11, _12) {
var win = $("<div class=\"messager-body\"></div>").appendTo("body");
win.append(_11);
if (_12) {
var tb = $("<div class=\"messager-button\"></div>").appendTo(win);
for (var _13 in _12) {
$("<a></a>").attr("href", "javascript:void(0)").text(_13).css("margin-left", 10).bind("click", eval(_12[_13])).appendTo(tb).linkbutton();
}
}
win.window({
title: _10,
noheader: (_10 ? false : true),
width: 300,
height: "auto",
modal: true,
collapsible: false,
minimizable: false,
maximizable: false,
resizable: false,
onClose: function () {
setTimeout(function () {
win.window("destroy");
}, 100);
}
});
win.window("window").addClass("messager-window");
win.children("div.messager-button").children("a:first").focus();
return win;
};
$.messager = {
show: function (_14) {
return _b(_14);
}, alert: function (_15, msg, _16, fn) {
var _17 = "<div>" + msg + "</div>";
switch (_16) {
case "error":
_17 = "<div class=\"messager-icon messager-error\"></div>" + _17;
break;
case "info":
_17 = "<div class=\"messager-icon messager-info\"></div>" + _17;
break;
case "question":
_17 = "<div class=\"messager-icon messager-question\"></div>" + _17;
break;
case "warning":
_17 = "<div class=\"messager-icon messager-warning\"></div>" + _17;
break;
}
_17 += "<div style=\"clear:both;\"/>";
var _18 = {};
_18[$.messager.defaults.ok] = function () {
win.window("close");
if (fn) {
fn();
return false;
}
};
var win = _f(_15, _17, _18);
return win;
}, confirm: function (_19, msg, fn) {
var _1a = "<div class=\"messager-icon messager-question\"></div>" + "<div>" + msg + "</div>" + "<div style=\"clear:both;\"/>";
var _1b = {};
_1b[$.messager.defaults.ok] = function () {
win.window("close");
if (fn) {
fn(true);
return false;
}
};
_1b[$.messager.defaults.cancel] = function () {
win.window("close");
if (fn) {
fn(false);
return false;
}
};
var win = _f(_19, _1a, _1b);
return win;
}, prompt: function (_1c, msg, fn) {
var _1d = "<div class=\"messager-icon messager-question\"></div>" + "<div>" + msg + "</div>" + "<br/>" + "<div style=\"clear:both;\"/>" + "<div><input class=\"messager-input\" type=\"text\"/></div>";
var _1e = {};
_1e[$.messager.defaults.ok] = function () {
win.window("close");
if (fn) {
fn($(".messager-input", win).val());
return false;
}
};
_1e[$.messager.defaults.cancel] = function () {
win.window("close");
if (fn) {
fn();
return false;
}
};
var win = _f(_1c, _1d, _1e);
win.children("input.messager-input").focus();
return win;
}, progress: function (_1f) {
var _20 = {
bar: function () {
return $("body>div.messager-window").find("div.messager-p-bar");
}, close: function () {
var win = $("body>div.messager-window>div.messager-body:has(div.messager-progress)");
if (win.length) {
win.window("close");
}
}
};
if (typeof _1f == "string") {
var _21 = _20[_1f];
return _21();
}
var _22 = $.extend({title: "", msg: "", text: undefined, interval: 300}, _1f || {});
var _23 = "<div class=\"messager-progress\"><div class=\"messager-p-msg\"></div><div class=\"messager-p-bar\"></div></div>";
var win = _f(_22.title, _23, null);
win.find("div.messager-p-msg").html(_22.msg);
var bar = win.find("div.messager-p-bar");
bar.progressbar({text: _22.text});
win.window({
closable: false, onClose: function () {
if (this.timer) {
clearInterval(this.timer);
}
$(this).window("destroy");
}
});
if (_22.interval) {
win[0].timer = setInterval(function () {
var v = bar.progressbar("getValue");
v += 10;
if (v > 100) {
v = 0;
}
bar.progressbar("setValue", v);
}, _22.interval);
}
return win;
}
};
$.messager.defaults = {ok: "Ok", cancel: "Cancel"};
})(jQuery);
| {
"pile_set_name": "Github"
} |
// Display Library for SPI e-paper panels from Dalian Good Display and boards from Waveshare.
// Requires HW SPI and Adafruit_GFX. Caution: the e-paper panels require 3.3V supply AND data lines!
//
// based on Demo Example from Good Display, available here: http://www.e-paper-display.com/download_detail/downloadsId=806.html
// Panel: GDEW0154M09 : http://www.e-paper-display.com/products_detail/productId=513.html
// Controller : JD79653A : http://www.e-paper-display.com/download_detail/downloadsId%3d943.html
//
// Author: Jean-Marc Zingg
//
// Version: see library.properties
//
// Library: https://github.com/ZinggJM/GxEPD2
#ifndef _GxEPD2_154_M09_H_
#define _GxEPD2_154_M09_H_
#include "../GxEPD2_EPD.h"
class GxEPD2_154_M09 : public GxEPD2_EPD
{
public:
// attributes
static const uint16_t WIDTH = 200;
static const uint16_t HEIGHT = 200;
static const GxEPD2::Panel panel = GxEPD2::GDEW0154M09;
static const bool hasColor = false;
static const bool hasPartialUpdate = true;
static const bool hasFastPartialUpdate = true;
static const uint16_t power_on_time = 250; // ms, e.g. 206410us
static const uint16_t power_off_time = 100; // ms, e.g. 62091us
static const uint16_t full_refresh_time = 1000; // ms, e.g. 924485us
static const uint16_t partial_refresh_time = 400; // ms, e.g. 324440us
// constructor
GxEPD2_154_M09(int8_t cs, int8_t dc, int8_t rst, int8_t busy);
// methods (virtual)
// Support for Bitmaps (Sprites) to Controller Buffer and to Screen
void clearScreen(uint8_t value = 0xFF); // init controller memory and screen (default white)
void writeScreenBuffer(uint8_t value = 0xFF); // init controller memory (default white)
void writeScreenBufferAgain(uint8_t value = 0xFF); // init previous buffer controller memory (default white)
// write to controller memory, without screen refresh; x and w should be multiple of 8
void writeImage(const uint8_t bitmap[], int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
void writeImagePart(const uint8_t bitmap[], int16_t x_part, int16_t y_part, int16_t w_bitmap, int16_t h_bitmap,
int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
void writeImage(const uint8_t* black, const uint8_t* color, int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
void writeImagePart(const uint8_t* black, const uint8_t* color, int16_t x_part, int16_t y_part, int16_t w_bitmap, int16_t h_bitmap,
int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
// write sprite of native data to controller memory, without screen refresh; x and w should be multiple of 8
void writeNative(const uint8_t* data1, const uint8_t* data2, int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
// write to controller memory, with screen refresh; x and w should be multiple of 8
void drawImage(const uint8_t bitmap[], int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
void drawImagePart(const uint8_t bitmap[], int16_t x_part, int16_t y_part, int16_t w_bitmap, int16_t h_bitmap,
int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
//for differential update: set current and previous buffers equal (for fast partial update to work correctly)
void writeImageAgain(const uint8_t bitmap[], int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
void writeImagePartAgain(const uint8_t bitmap[], int16_t x_part, int16_t y_part, int16_t w_bitmap, int16_t h_bitmap,
int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
void drawImage(const uint8_t* black, const uint8_t* color, int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
void drawImagePart(const uint8_t* black, const uint8_t* color, int16_t x_part, int16_t y_part, int16_t w_bitmap, int16_t h_bitmap,
int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
// write sprite of native data to controller memory, with screen refresh; x and w should be multiple of 8
void drawNative(const uint8_t* data1, const uint8_t* data2, int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
void refresh(bool partial_update_mode = false); // screen refresh from controller memory to full screen
void refresh(int16_t x, int16_t y, int16_t w, int16_t h); // screen refresh from controller memory, partial screen
void powerOff(); // turns off generation of panel driving voltages, avoids screen fading over time
void hibernate(); // turns powerOff() and sets controller to deep sleep for minimum power use, ONLY if wakeable by RST (rst >= 0)
private:
void _writeScreenBuffer(uint8_t command, uint8_t value);
void _writeImage(uint8_t command, const uint8_t bitmap[], int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
void _writeImagePart(uint8_t command, const uint8_t bitmap[], int16_t x_part, int16_t y_part, int16_t w_bitmap, int16_t h_bitmap,
int16_t x, int16_t y, int16_t w, int16_t h, bool invert = false, bool mirror_y = false, bool pgm = false);
void _setPartialRamArea(uint16_t x, uint16_t y, uint16_t w, uint16_t h);
void _PowerOn();
void _PowerOff();
void _InitDisplay();
void _Init_Full();
void _Init_Part();
void _Update_Full();
void _Update_Part();
private:
static const unsigned char lut_20_vcomDC[];
static const unsigned char lut_21_ww[];
static const unsigned char lut_22_bw[];
static const unsigned char lut_23_wb[];
static const unsigned char lut_24_bb[];
static const unsigned char lut_20_vcomDC_partial[];
static const unsigned char lut_21_ww_partial[];
static const unsigned char lut_22_bw_partial[];
static const unsigned char lut_23_wb_partial[];
static const unsigned char lut_24_bb_partial[];
};
#endif
| {
"pile_set_name": "Github"
} |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("sortablejs"));
else if(typeof define === 'function' && define.amd)
define(["sortablejs"], factory);
else if(typeof exports === 'object')
exports["vuedraggable"] = factory(require("sortablejs"));
else
root["vuedraggable"] = factory(root["Sortable"]);
})((typeof self !== 'undefined' ? self : this), function(__WEBPACK_EXTERNAL_MODULE_a352__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "fb15");
/******/ })
/************************************************************************/
/******/ ({
/***/ "02f4":
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__("4588");
var defined = __webpack_require__("be13");
// true -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
return function (that, pos) {
var s = String(defined(that));
var i = toInteger(pos);
var l = s.length;
var a, b;
if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ }),
/***/ "0390":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var at = __webpack_require__("02f4")(true);
// `AdvanceStringIndex` abstract operation
// https://tc39.github.io/ecma262/#sec-advancestringindex
module.exports = function (S, index, unicode) {
return index + (unicode ? at(S, index).length : 1);
};
/***/ }),
/***/ "07e3":
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
/***/ }),
/***/ "0bfb":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.2.5.3 get RegExp.prototype.flags
var anObject = __webpack_require__("cb7c");
module.exports = function () {
var that = anObject(this);
var result = '';
if (that.global) result += 'g';
if (that.ignoreCase) result += 'i';
if (that.multiline) result += 'm';
if (that.unicode) result += 'u';
if (that.sticky) result += 'y';
return result;
};
/***/ }),
/***/ "0fc9":
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__("3a38");
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ }),
/***/ "1654":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $at = __webpack_require__("71c1")(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__("30f1")(String, 'String', function (iterated) {
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
var O = this._t;
var index = this._i;
var point;
if (index >= O.length) return { value: undefined, done: true };
point = $at(O, index);
this._i += point.length;
return { value: point, done: false };
});
/***/ }),
/***/ "1691":
/***/ (function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ }),
/***/ "1af6":
/***/ (function(module, exports, __webpack_require__) {
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = __webpack_require__("63b6");
$export($export.S, 'Array', { isArray: __webpack_require__("9003") });
/***/ }),
/***/ "1bc3":
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__("f772");
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/***/ "1ec9":
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__("f772");
var document = __webpack_require__("e53d").document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
/***/ }),
/***/ "20fd":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $defineProperty = __webpack_require__("d9f6");
var createDesc = __webpack_require__("aebd");
module.exports = function (object, index, value) {
if (index in object) $defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
/***/ }),
/***/ "214f":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
__webpack_require__("b0c5");
var redefine = __webpack_require__("2aba");
var hide = __webpack_require__("32e9");
var fails = __webpack_require__("79e5");
var defined = __webpack_require__("be13");
var wks = __webpack_require__("2b4c");
var regexpExec = __webpack_require__("520a");
var SPECIES = wks('species');
var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
// #replace needs built-in support for named groups.
// #match works fine because it just return the exec results, even if it has
// a "grops" property.
var re = /./;
re.exec = function () {
var result = [];
result.groups = { a: '7' };
return result;
};
return ''.replace(re, '$<a>') !== '7';
});
var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = (function () {
// Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
var re = /(?:)/;
var originalExec = re.exec;
re.exec = function () { return originalExec.apply(this, arguments); };
var result = 'ab'.split(re);
return result.length === 2 && result[0] === 'a' && result[1] === 'b';
})();
module.exports = function (KEY, length, exec) {
var SYMBOL = wks(KEY);
var DELEGATES_TO_SYMBOL = !fails(function () {
// String methods call symbol-named RegEp methods
var O = {};
O[SYMBOL] = function () { return 7; };
return ''[KEY](O) != 7;
});
var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL ? !fails(function () {
// Symbol-named RegExp methods call .exec
var execCalled = false;
var re = /a/;
re.exec = function () { execCalled = true; return null; };
if (KEY === 'split') {
// RegExp[@@split] doesn't call the regex's exec method, but first creates
// a new one. We need to return the patched regex when creating the new one.
re.constructor = {};
re.constructor[SPECIES] = function () { return re; };
}
re[SYMBOL]('');
return !execCalled;
}) : undefined;
if (
!DELEGATES_TO_SYMBOL ||
!DELEGATES_TO_EXEC ||
(KEY === 'replace' && !REPLACE_SUPPORTS_NAMED_GROUPS) ||
(KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC)
) {
var nativeRegExpMethod = /./[SYMBOL];
var fns = exec(
defined,
SYMBOL,
''[KEY],
function maybeCallNative(nativeMethod, regexp, str, arg2, forceStringMethod) {
if (regexp.exec === regexpExec) {
if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
// The native String method already delegates to @@method (this
// polyfilled function), leasing to infinite recursion.
// We avoid it by directly calling the native @@method method.
return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) };
}
return { done: true, value: nativeMethod.call(str, regexp, arg2) };
}
return { done: false };
}
);
var strfn = fns[0];
var rxfn = fns[1];
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function (string, arg) { return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function (string) { return rxfn.call(string, this); }
);
}
};
/***/ }),
/***/ "230e":
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__("d3f4");
var document = __webpack_require__("7726").document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
/***/ }),
/***/ "23c6":
/***/ (function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__("2d95");
var TAG = __webpack_require__("2b4c")('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (e) { /* empty */ }
};
module.exports = function (it) {
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ }),
/***/ "241e":
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__("25eb");
module.exports = function (it) {
return Object(defined(it));
};
/***/ }),
/***/ "25eb":
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/***/ "294c":
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
/***/ }),
/***/ "2aba":
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__("7726");
var hide = __webpack_require__("32e9");
var has = __webpack_require__("69a8");
var SRC = __webpack_require__("ca5a")('src');
var $toString = __webpack_require__("fa5b");
var TO_STRING = 'toString';
var TPL = ('' + $toString).split(TO_STRING);
__webpack_require__("8378").inspectSource = function (it) {
return $toString.call(it);
};
(module.exports = function (O, key, val, safe) {
var isFunction = typeof val == 'function';
if (isFunction) has(val, 'name') || hide(val, 'name', key);
if (O[key] === val) return;
if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if (O === global) {
O[key] = val;
} else if (!safe) {
delete O[key];
hide(O, key, val);
} else if (O[key]) {
O[key] = val;
} else {
hide(O, key, val);
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString() {
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
/***/ }),
/***/ "2b4c":
/***/ (function(module, exports, __webpack_require__) {
var store = __webpack_require__("5537")('wks');
var uid = __webpack_require__("ca5a");
var Symbol = __webpack_require__("7726").Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ }),
/***/ "2d00":
/***/ (function(module, exports) {
module.exports = false;
/***/ }),
/***/ "2d95":
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
/***/ }),
/***/ "2fdb":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
var $export = __webpack_require__("5ca1");
var context = __webpack_require__("d2c8");
var INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__("5147")(INCLUDES), 'String', {
includes: function includes(searchString /* , position = 0 */) {
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/***/ "30f1":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__("b8e3");
var $export = __webpack_require__("63b6");
var redefine = __webpack_require__("9138");
var hide = __webpack_require__("35e8");
var Iterators = __webpack_require__("481b");
var $iterCreate = __webpack_require__("8f60");
var setToStringTag = __webpack_require__("45f2");
var getPrototypeOf = __webpack_require__("53e2");
var ITERATOR = __webpack_require__("5168")('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';
var returnThis = function () { return this; };
module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
var getMethod = function (kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS: return function keys() { return new Constructor(this, kind); };
case VALUES: return function values() { return new Constructor(this, kind); };
} return function entries() { return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator';
var DEF_VALUES = DEFAULT == VALUES;
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
var $default = $native || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
// Fix native
if ($anyNative) {
IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEF_VALUES && $native && $native.name !== VALUES) {
VALUES_BUG = true;
$default = function values() { return $native.call(this); };
}
// Define iterator
if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if (DEFAULT) {
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if (FORCED) for (key in methods) {
if (!(key in proto)) redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ }),
/***/ "32a6":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__("241e");
var $keys = __webpack_require__("c3a1");
__webpack_require__("ce7e")('keys', function () {
return function keys(it) {
return $keys(toObject(it));
};
});
/***/ }),
/***/ "32e9":
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__("86cc");
var createDesc = __webpack_require__("4630");
module.exports = __webpack_require__("9e1e") ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/***/ "32fc":
/***/ (function(module, exports, __webpack_require__) {
var document = __webpack_require__("e53d").document;
module.exports = document && document.documentElement;
/***/ }),
/***/ "335c":
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__("6b4c");
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/***/ "355d":
/***/ (function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ }),
/***/ "35e8":
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__("d9f6");
var createDesc = __webpack_require__("aebd");
module.exports = __webpack_require__("8e60") ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/***/ "36c3":
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__("335c");
var defined = __webpack_require__("25eb");
module.exports = function (it) {
return IObject(defined(it));
};
/***/ }),
/***/ "3702":
/***/ (function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__("481b");
var ITERATOR = __webpack_require__("5168")('iterator');
var ArrayProto = Array.prototype;
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ }),
/***/ "3a38":
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/***/ "40c3":
/***/ (function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__("6b4c");
var TAG = __webpack_require__("5168")('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (e) { /* empty */ }
};
module.exports = function (it) {
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ }),
/***/ "4588":
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/***/ "45f2":
/***/ (function(module, exports, __webpack_require__) {
var def = __webpack_require__("d9f6").f;
var has = __webpack_require__("07e3");
var TAG = __webpack_require__("5168")('toStringTag');
module.exports = function (it, tag, stat) {
if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};
/***/ }),
/***/ "4630":
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/***/ "469f":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("6c1c");
__webpack_require__("1654");
module.exports = __webpack_require__("7d7b");
/***/ }),
/***/ "481b":
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/***/ "4aa6":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("dc62");
/***/ }),
/***/ "4bf8":
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__("be13");
module.exports = function (it) {
return Object(defined(it));
};
/***/ }),
/***/ "4ee1":
/***/ (function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__("5168")('iterator');
var SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function () { SAFE_CLOSING = true; };
// eslint-disable-next-line no-throw-literal
Array.from(riter, function () { throw 2; });
} catch (e) { /* empty */ }
module.exports = function (exec, skipClosing) {
if (!skipClosing && !SAFE_CLOSING) return false;
var safe = false;
try {
var arr = [7];
var iter = arr[ITERATOR]();
iter.next = function () { return { done: safe = true }; };
arr[ITERATOR] = function () { return iter; };
exec(arr);
} catch (e) { /* empty */ }
return safe;
};
/***/ }),
/***/ "50ed":
/***/ (function(module, exports) {
module.exports = function (done, value) {
return { value: value, done: !!done };
};
/***/ }),
/***/ "5147":
/***/ (function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__("2b4c")('match');
module.exports = function (KEY) {
var re = /./;
try {
'/./'[KEY](re);
} catch (e) {
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch (f) { /* empty */ }
} return true;
};
/***/ }),
/***/ "5168":
/***/ (function(module, exports, __webpack_require__) {
var store = __webpack_require__("dbdb")('wks');
var uid = __webpack_require__("62a0");
var Symbol = __webpack_require__("e53d").Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ }),
/***/ "5176":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("51b6");
/***/ }),
/***/ "51b6":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("a3c3");
module.exports = __webpack_require__("584a").Object.assign;
/***/ }),
/***/ "520a":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var regexpFlags = __webpack_require__("0bfb");
var nativeExec = RegExp.prototype.exec;
// This always refers to the native implementation, because the
// String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,
// which loads this file before patching the method.
var nativeReplace = String.prototype.replace;
var patchedExec = nativeExec;
var LAST_INDEX = 'lastIndex';
var UPDATES_LAST_INDEX_WRONG = (function () {
var re1 = /a/,
re2 = /b*/g;
nativeExec.call(re1, 'a');
nativeExec.call(re2, 'a');
return re1[LAST_INDEX] !== 0 || re2[LAST_INDEX] !== 0;
})();
// nonparticipating capturing group, copied from es5-shim's String#split patch.
var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED;
if (PATCH) {
patchedExec = function exec(str) {
var re = this;
var lastIndex, reCopy, match, i;
if (NPCG_INCLUDED) {
reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re));
}
if (UPDATES_LAST_INDEX_WRONG) lastIndex = re[LAST_INDEX];
match = nativeExec.call(re, str);
if (UPDATES_LAST_INDEX_WRONG && match) {
re[LAST_INDEX] = re.global ? match.index + match[0].length : lastIndex;
}
if (NPCG_INCLUDED && match && match.length > 1) {
// Fix browsers whose `exec` methods don't consistently return `undefined`
// for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
// eslint-disable-next-line no-loop-func
nativeReplace.call(match[0], reCopy, function () {
for (i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) match[i] = undefined;
}
});
}
return match;
};
}
module.exports = patchedExec;
/***/ }),
/***/ "53e2":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__("07e3");
var toObject = __webpack_require__("241e");
var IE_PROTO = __webpack_require__("5559")('IE_PROTO');
var ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function (O) {
O = toObject(O);
if (has(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ }),
/***/ "549b":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ctx = __webpack_require__("d864");
var $export = __webpack_require__("63b6");
var toObject = __webpack_require__("241e");
var call = __webpack_require__("b0dc");
var isArrayIter = __webpack_require__("3702");
var toLength = __webpack_require__("b447");
var createProperty = __webpack_require__("20fd");
var getIterFn = __webpack_require__("7cd6");
$export($export.S + $export.F * !__webpack_require__("4ee1")(function (iter) { Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var index = 0;
var iterFn = getIterFn(O);
var length, result, step, iterator;
if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for (result = new C(length); length > index; index++) {
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
/***/ }),
/***/ "54a1":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("6c1c");
__webpack_require__("1654");
module.exports = __webpack_require__("95d5");
/***/ }),
/***/ "5537":
/***/ (function(module, exports, __webpack_require__) {
var core = __webpack_require__("8378");
var global = __webpack_require__("7726");
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: core.version,
mode: __webpack_require__("2d00") ? 'pure' : 'global',
copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});
/***/ }),
/***/ "5559":
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__("dbdb")('keys');
var uid = __webpack_require__("62a0");
module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
/***/ }),
/***/ "584a":
/***/ (function(module, exports) {
var core = module.exports = { version: '2.6.5' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
/***/ }),
/***/ "5b4e":
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__("36c3");
var toLength = __webpack_require__("b447");
var toAbsoluteIndex = __webpack_require__("0fc9");
module.exports = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) if (IS_INCLUDES || index in O) {
if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ }),
/***/ "5ca1":
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__("7726");
var core = __webpack_require__("8378");
var hide = __webpack_require__("32e9");
var redefine = __webpack_require__("2aba");
var ctx = __webpack_require__("9b43");
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
var key, own, out, exp;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if (target) redefine(target, key, out, type & $export.U);
// export
if (exports[key] != out) hide(exports, key, exp);
if (IS_PROTO && expProto[key] != out) expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/***/ "5d73":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("469f");
/***/ }),
/***/ "5f1b":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var classof = __webpack_require__("23c6");
var builtinExec = RegExp.prototype.exec;
// `RegExpExec` abstract operation
// https://tc39.github.io/ecma262/#sec-regexpexec
module.exports = function (R, S) {
var exec = R.exec;
if (typeof exec === 'function') {
var result = exec.call(R, S);
if (typeof result !== 'object') {
throw new TypeError('RegExp exec method returned something other than an Object or null');
}
return result;
}
if (classof(R) !== 'RegExp') {
throw new TypeError('RegExp#exec called on incompatible receiver');
}
return builtinExec.call(R, S);
};
/***/ }),
/***/ "626a":
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__("2d95");
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/***/ "62a0":
/***/ (function(module, exports) {
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/***/ "63b6":
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__("e53d");
var core = __webpack_require__("584a");
var ctx = __webpack_require__("d864");
var hide = __webpack_require__("35e8");
var has = __webpack_require__("07e3");
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var IS_WRAP = type & $export.W;
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE];
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
var key, own, out;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if (own && has(exports, key)) continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function (C) {
var F = function (a, b, c) {
if (this instanceof C) {
switch (arguments.length) {
case 0: return new C();
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if (IS_PROTO) {
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/***/ "6762":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/Array.prototype.includes
var $export = __webpack_require__("5ca1");
var $includes = __webpack_require__("c366")(true);
$export($export.P, 'Array', {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__("9c6c")('includes');
/***/ }),
/***/ "6821":
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__("626a");
var defined = __webpack_require__("be13");
module.exports = function (it) {
return IObject(defined(it));
};
/***/ }),
/***/ "69a8":
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
/***/ }),
/***/ "6a99":
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__("d3f4");
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/***/ "6b4c":
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
/***/ }),
/***/ "6c1c":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("c367");
var global = __webpack_require__("e53d");
var hide = __webpack_require__("35e8");
var Iterators = __webpack_require__("481b");
var TO_STRING_TAG = __webpack_require__("5168")('toStringTag');
var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
'TextTrackList,TouchList').split(',');
for (var i = 0; i < DOMIterables.length; i++) {
var NAME = DOMIterables[i];
var Collection = global[NAME];
var proto = Collection && Collection.prototype;
if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = Iterators.Array;
}
/***/ }),
/***/ "71c1":
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__("3a38");
var defined = __webpack_require__("25eb");
// true -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
return function (that, pos) {
var s = String(defined(that));
var i = toInteger(pos);
var l = s.length;
var a, b;
if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ }),
/***/ "7726":
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
/***/ }),
/***/ "774e":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("d2d5");
/***/ }),
/***/ "77f1":
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__("4588");
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ }),
/***/ "794b":
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__("8e60") && !__webpack_require__("294c")(function () {
return Object.defineProperty(__webpack_require__("1ec9")('div'), 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/***/ "79aa":
/***/ (function(module, exports) {
module.exports = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
/***/ }),
/***/ "79e5":
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
/***/ }),
/***/ "7cd6":
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__("40c3");
var ITERATOR = __webpack_require__("5168")('iterator');
var Iterators = __webpack_require__("481b");
module.exports = __webpack_require__("584a").getIteratorMethod = function (it) {
if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ }),
/***/ "7d7b":
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__("e4ae");
var get = __webpack_require__("7cd6");
module.exports = __webpack_require__("584a").getIterator = function (it) {
var iterFn = get(it);
if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!');
return anObject(iterFn.call(it));
};
/***/ }),
/***/ "7e90":
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__("d9f6");
var anObject = __webpack_require__("e4ae");
var getKeys = __webpack_require__("c3a1");
module.exports = __webpack_require__("8e60") ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = getKeys(Properties);
var length = keys.length;
var i = 0;
var P;
while (length > i) dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ }),
/***/ "8378":
/***/ (function(module, exports) {
var core = module.exports = { version: '2.6.5' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
/***/ }),
/***/ "8436":
/***/ (function(module, exports) {
module.exports = function () { /* empty */ };
/***/ }),
/***/ "86cc":
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__("cb7c");
var IE8_DOM_DEFINE = __webpack_require__("c69a");
var toPrimitive = __webpack_require__("6a99");
var dP = Object.defineProperty;
exports.f = __webpack_require__("9e1e") ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/***/ "8aae":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("32a6");
module.exports = __webpack_require__("584a").Object.keys;
/***/ }),
/***/ "8e60":
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__("294c")(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/***/ "8f60":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var create = __webpack_require__("a159");
var descriptor = __webpack_require__("aebd");
var setToStringTag = __webpack_require__("45f2");
var IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__("35e8")(IteratorPrototype, __webpack_require__("5168")('iterator'), function () { return this; });
module.exports = function (Constructor, NAME, next) {
Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ }),
/***/ "9003":
/***/ (function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__("6b4c");
module.exports = Array.isArray || function isArray(arg) {
return cof(arg) == 'Array';
};
/***/ }),
/***/ "9138":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("35e8");
/***/ }),
/***/ "9306":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__("c3a1");
var gOPS = __webpack_require__("9aa9");
var pIE = __webpack_require__("355d");
var toObject = __webpack_require__("241e");
var IObject = __webpack_require__("335c");
var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__("294c")(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var S = Symbol();
var K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var aLen = arguments.length;
var index = 1;
var getSymbols = gOPS.f;
var isEnum = pIE.f;
while (aLen > index) {
var S = IObject(arguments[index++]);
var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
} return T;
} : $assign;
/***/ }),
/***/ "9427":
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__("63b6");
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', { create: __webpack_require__("a159") });
/***/ }),
/***/ "95d5":
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__("40c3");
var ITERATOR = __webpack_require__("5168")('iterator');
var Iterators = __webpack_require__("481b");
module.exports = __webpack_require__("584a").isIterable = function (it) {
var O = Object(it);
return O[ITERATOR] !== undefined
|| '@@iterator' in O
// eslint-disable-next-line no-prototype-builtins
|| Iterators.hasOwnProperty(classof(O));
};
/***/ }),
/***/ "9aa9":
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/***/ "9b43":
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__("d8e8");
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/***/ "9c6c":
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = __webpack_require__("2b4c")('unscopables');
var ArrayProto = Array.prototype;
if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__("32e9")(ArrayProto, UNSCOPABLES, {});
module.exports = function (key) {
ArrayProto[UNSCOPABLES][key] = true;
};
/***/ }),
/***/ "9def":
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__("4588");
var min = Math.min;
module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ }),
/***/ "9e1e":
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__("79e5")(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/***/ "a159":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__("e4ae");
var dPs = __webpack_require__("7e90");
var enumBugKeys = __webpack_require__("1691");
var IE_PROTO = __webpack_require__("5559")('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__("1ec9")('iframe');
var i = enumBugKeys.length;
var lt = '<';
var gt = '>';
var iframeDocument;
iframe.style.display = 'none';
__webpack_require__("32fc").appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ }),
/***/ "a352":
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_a352__;
/***/ }),
/***/ "a3c3":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__("63b6");
$export($export.S + $export.F, 'Object', { assign: __webpack_require__("9306") });
/***/ }),
/***/ "a481":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var anObject = __webpack_require__("cb7c");
var toObject = __webpack_require__("4bf8");
var toLength = __webpack_require__("9def");
var toInteger = __webpack_require__("4588");
var advanceStringIndex = __webpack_require__("0390");
var regExpExec = __webpack_require__("5f1b");
var max = Math.max;
var min = Math.min;
var floor = Math.floor;
var SUBSTITUTION_SYMBOLS = /\$([$&`']|\d\d?|<[^>]*>)/g;
var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&`']|\d\d?)/g;
var maybeToString = function (it) {
return it === undefined ? it : String(it);
};
// @@replace logic
__webpack_require__("214f")('replace', 2, function (defined, REPLACE, $replace, maybeCallNative) {
return [
// `String.prototype.replace` method
// https://tc39.github.io/ecma262/#sec-string.prototype.replace
function replace(searchValue, replaceValue) {
var O = defined(this);
var fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
},
// `RegExp.prototype[@@replace]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace
function (regexp, replaceValue) {
var res = maybeCallNative($replace, regexp, this, replaceValue);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var functionalReplace = typeof replaceValue === 'function';
if (!functionalReplace) replaceValue = String(replaceValue);
var global = rx.global;
if (global) {
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
}
var results = [];
while (true) {
var result = regExpExec(rx, S);
if (result === null) break;
results.push(result);
if (!global) break;
var matchStr = String(result[0]);
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
}
var accumulatedResult = '';
var nextSourcePosition = 0;
for (var i = 0; i < results.length; i++) {
result = results[i];
var matched = String(result[0]);
var position = max(min(toInteger(result.index), S.length), 0);
var captures = [];
// NOTE: This is equivalent to
// captures = result.slice(1).map(maybeToString)
// but for some reason `nativeSlice.call(result, 1, result.length)` (called in
// the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
// causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
var namedCaptures = result.groups;
if (functionalReplace) {
var replacerArgs = [matched].concat(captures, position, S);
if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
var replacement = String(replaceValue.apply(undefined, replacerArgs));
} else {
replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
}
if (position >= nextSourcePosition) {
accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
nextSourcePosition = position + matched.length;
}
}
return accumulatedResult + S.slice(nextSourcePosition);
}
];
// https://tc39.github.io/ecma262/#sec-getsubstitution
function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
var tailPos = position + matched.length;
var m = captures.length;
var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
if (namedCaptures !== undefined) {
namedCaptures = toObject(namedCaptures);
symbols = SUBSTITUTION_SYMBOLS;
}
return $replace.call(replacement, symbols, function (match, ch) {
var capture;
switch (ch.charAt(0)) {
case '$': return '$';
case '&': return matched;
case '`': return str.slice(0, position);
case "'": return str.slice(tailPos);
case '<':
capture = namedCaptures[ch.slice(1, -1)];
break;
default: // \d\d?
var n = +ch;
if (n === 0) return match;
if (n > m) {
var f = floor(n / 10);
if (f === 0) return match;
if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
return match;
}
capture = captures[n - 1];
}
return capture === undefined ? '' : capture;
});
}
});
/***/ }),
/***/ "a4bb":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("8aae");
/***/ }),
/***/ "a745":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("f410");
/***/ }),
/***/ "aae3":
/***/ (function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__("d3f4");
var cof = __webpack_require__("2d95");
var MATCH = __webpack_require__("2b4c")('match');
module.exports = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
/***/ }),
/***/ "aebd":
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/***/ "b0c5":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var regexpExec = __webpack_require__("520a");
__webpack_require__("5ca1")({
target: 'RegExp',
proto: true,
forced: regexpExec !== /./.exec
}, {
exec: regexpExec
});
/***/ }),
/***/ "b0dc":
/***/ (function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__("e4ae");
module.exports = function (iterator, fn, value, entries) {
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch (e) {
var ret = iterator['return'];
if (ret !== undefined) anObject(ret.call(iterator));
throw e;
}
};
/***/ }),
/***/ "b447":
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__("3a38");
var min = Math.min;
module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ }),
/***/ "b8e3":
/***/ (function(module, exports) {
module.exports = true;
/***/ }),
/***/ "be13":
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/***/ "c366":
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__("6821");
var toLength = __webpack_require__("9def");
var toAbsoluteIndex = __webpack_require__("77f1");
module.exports = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) if (IS_INCLUDES || index in O) {
if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ }),
/***/ "c367":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var addToUnscopables = __webpack_require__("8436");
var step = __webpack_require__("50ed");
var Iterators = __webpack_require__("481b");
var toIObject = __webpack_require__("36c3");
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__("30f1")(Array, 'Array', function (iterated, kind) {
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
var O = this._t;
var kind = this._k;
var index = this._i++;
if (!O || index >= O.length) {
this._t = undefined;
return step(1);
}
if (kind == 'keys') return step(0, index);
if (kind == 'values') return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ }),
/***/ "c3a1":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__("e6f3");
var enumBugKeys = __webpack_require__("1691");
module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
/***/ }),
/***/ "c649":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return insertNodeAt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return camelize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return console; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return removeNode; });
/* harmony import */ var core_js_modules_es6_regexp_replace__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("a481");
/* harmony import */ var core_js_modules_es6_regexp_replace__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es6_regexp_replace__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var F_source_Vue_Draggable_node_modules_babel_runtime_corejs2_core_js_object_create__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("4aa6");
/* harmony import */ var F_source_Vue_Draggable_node_modules_babel_runtime_corejs2_core_js_object_create__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(F_source_Vue_Draggable_node_modules_babel_runtime_corejs2_core_js_object_create__WEBPACK_IMPORTED_MODULE_1__);
function getConsole() {
if (typeof window !== "undefined") {
return window.console;
}
return global.console;
}
var console = getConsole();
function cached(fn) {
var cache = F_source_Vue_Draggable_node_modules_babel_runtime_corejs2_core_js_object_create__WEBPACK_IMPORTED_MODULE_1___default()(null);
return function cachedFn(str) {
var hit = cache[str];
return hit || (cache[str] = fn(str));
};
}
var regex = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(regex, function (_, c) {
return c ? c.toUpperCase() : "";
});
});
function removeNode(node) {
if (node.parentElement !== null) {
node.parentElement.removeChild(node);
}
}
function insertNodeAt(fatherNode, node, position) {
var refNode = position === 0 ? fatherNode.children[0] : fatherNode.children[position - 1].nextSibling;
fatherNode.insertBefore(node, refNode);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("c8ba")))
/***/ }),
/***/ "c69a":
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__("9e1e") && !__webpack_require__("79e5")(function () {
return Object.defineProperty(__webpack_require__("230e")('div'), 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/***/ "c8ba":
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/***/ "c8bb":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("54a1");
/***/ }),
/***/ "ca5a":
/***/ (function(module, exports) {
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/***/ "cb7c":
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__("d3f4");
module.exports = function (it) {
if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/***/ "ce7e":
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__("63b6");
var core = __webpack_require__("584a");
var fails = __webpack_require__("294c");
module.exports = function (KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY];
var exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
/***/ }),
/***/ "d2c8":
/***/ (function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__("aae3");
var defined = __webpack_require__("be13");
module.exports = function (that, searchString, NAME) {
if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
/***/ }),
/***/ "d2d5":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("1654");
__webpack_require__("549b");
module.exports = __webpack_require__("584a").Array.from;
/***/ }),
/***/ "d3f4":
/***/ (function(module, exports) {
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/***/ "d864":
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__("79aa");
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/***/ "d8e8":
/***/ (function(module, exports) {
module.exports = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
/***/ }),
/***/ "d9f6":
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__("e4ae");
var IE8_DOM_DEFINE = __webpack_require__("794b");
var toPrimitive = __webpack_require__("1bc3");
var dP = Object.defineProperty;
exports.f = __webpack_require__("8e60") ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/***/ "dbdb":
/***/ (function(module, exports, __webpack_require__) {
var core = __webpack_require__("584a");
var global = __webpack_require__("e53d");
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: core.version,
mode: __webpack_require__("b8e3") ? 'pure' : 'global',
copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});
/***/ }),
/***/ "dc62":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("9427");
var $Object = __webpack_require__("584a").Object;
module.exports = function create(P, D) {
return $Object.create(P, D);
};
/***/ }),
/***/ "e4ae":
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__("f772");
module.exports = function (it) {
if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/***/ "e53d":
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
/***/ }),
/***/ "e6f3":
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__("07e3");
var toIObject = __webpack_require__("36c3");
var arrayIndexOf = __webpack_require__("5b4e")(false);
var IE_PROTO = __webpack_require__("5559")('IE_PROTO');
module.exports = function (object, names) {
var O = toIObject(object);
var i = 0;
var result = [];
var key;
for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/***/ "f410":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("1af6");
module.exports = __webpack_require__("584a").Array.isArray;
/***/ }),
/***/ "f559":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
var $export = __webpack_require__("5ca1");
var toLength = __webpack_require__("9def");
var context = __webpack_require__("d2c8");
var STARTS_WITH = 'startsWith';
var $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__("5147")(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = context(this, searchString, STARTS_WITH);
var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
/***/ }),
/***/ "f772":
/***/ (function(module, exports) {
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/***/ "fa5b":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("5537")('native-function-to-string', Function.toString);
/***/ }),
/***/ "fb15":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/setPublicPath.js
// This file is imported into lib/wc client bundles.
if (typeof window !== 'undefined') {
var setPublicPath_i
if ((setPublicPath_i = window.document.currentScript) && (setPublicPath_i = setPublicPath_i.src.match(/(.+\/)[^/]+\.js(\?.*)?$/))) {
__webpack_require__.p = setPublicPath_i[1] // eslint-disable-line
}
}
// Indicate to webpack that this file can be concatenated
/* harmony default export */ var setPublicPath = (null);
// EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/object/assign.js
var object_assign = __webpack_require__("5176");
var assign_default = /*#__PURE__*/__webpack_require__.n(object_assign);
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.string.starts-with.js
var es6_string_starts_with = __webpack_require__("f559");
// EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/object/keys.js
var keys = __webpack_require__("a4bb");
var keys_default = /*#__PURE__*/__webpack_require__.n(keys);
// EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/array/is-array.js
var is_array = __webpack_require__("a745");
var is_array_default = /*#__PURE__*/__webpack_require__.n(is_array);
// CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/arrayWithHoles.js
function _arrayWithHoles(arr) {
if (is_array_default()(arr)) return arr;
}
// EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/get-iterator.js
var get_iterator = __webpack_require__("5d73");
var get_iterator_default = /*#__PURE__*/__webpack_require__.n(get_iterator);
// CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/iterableToArrayLimit.js
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = get_iterator_default()(arr), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/nonIterableRest.js
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/slicedToArray.js
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
// EXTERNAL MODULE: ./node_modules/core-js/modules/es7.array.includes.js
var es7_array_includes = __webpack_require__("6762");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.string.includes.js
var es6_string_includes = __webpack_require__("2fdb");
// CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/arrayWithoutHoles.js
function _arrayWithoutHoles(arr) {
if (is_array_default()(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
}
}
// EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/array/from.js
var from = __webpack_require__("774e");
var from_default = /*#__PURE__*/__webpack_require__.n(from);
// EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/is-iterable.js
var is_iterable = __webpack_require__("c8bb");
var is_iterable_default = /*#__PURE__*/__webpack_require__.n(is_iterable);
// CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/iterableToArray.js
function _iterableToArray(iter) {
if (is_iterable_default()(Object(iter)) || Object.prototype.toString.call(iter) === "[object Arguments]") return from_default()(iter);
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/nonIterableSpread.js
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/toConsumableArray.js
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
// EXTERNAL MODULE: external {"commonjs":"sortablejs","commonjs2":"sortablejs","amd":"sortablejs","root":"Sortable"}
var external_commonjs_sortablejs_commonjs2_sortablejs_amd_sortablejs_root_Sortable_ = __webpack_require__("a352");
var external_commonjs_sortablejs_commonjs2_sortablejs_amd_sortablejs_root_Sortable_default = /*#__PURE__*/__webpack_require__.n(external_commonjs_sortablejs_commonjs2_sortablejs_amd_sortablejs_root_Sortable_);
// EXTERNAL MODULE: ./src/util/helper.js
var helper = __webpack_require__("c649");
// CONCATENATED MODULE: ./src/vuedraggable.js
function buildAttribute(object, propName, value) {
if (value === undefined) {
return object;
}
object = object || {};
object[propName] = value;
return object;
}
function computeVmIndex(vnodes, element) {
return vnodes.map(function (elt) {
return elt.elm;
}).indexOf(element);
}
function _computeIndexes(slots, children, isTransition, footerOffset) {
if (!slots) {
return [];
}
var elmFromNodes = slots.map(function (elt) {
return elt.elm;
});
var footerIndex = children.length - footerOffset;
var rawIndexes = _toConsumableArray(children).map(function (elt, idx) {
return idx >= footerIndex ? elmFromNodes.length : elmFromNodes.indexOf(elt);
});
return isTransition ? rawIndexes.filter(function (ind) {
return ind !== -1;
}) : rawIndexes;
}
function emit(evtName, evtData) {
var _this = this;
this.$nextTick(function () {
return _this.$emit(evtName.toLowerCase(), evtData);
});
}
function delegateAndEmit(evtName) {
var _this2 = this;
return function (evtData) {
if (_this2.realList !== null) {
_this2["onDrag" + evtName](evtData);
}
emit.call(_this2, evtName, evtData);
};
}
function isTransitionName(name) {
return ["transition-group", "TransitionGroup"].includes(name);
}
function vuedraggable_isTransition(slots) {
if (!slots || slots.length !== 1) {
return false;
}
var _slots = _slicedToArray(slots, 1),
componentOptions = _slots[0].componentOptions;
if (!componentOptions) {
return false;
}
return isTransitionName(componentOptions.tag);
}
function getSlot(slot, scopedSlot, key) {
return slot[key] || (scopedSlot[key] ? scopedSlot[key]() : undefined);
}
function computeChildrenAndOffsets(children, slot, scopedSlot) {
var headerOffset = 0;
var footerOffset = 0;
var header = getSlot(slot, scopedSlot, "header");
if (header) {
headerOffset = header.length;
children = children ? [].concat(_toConsumableArray(header), _toConsumableArray(children)) : _toConsumableArray(header);
}
var footer = getSlot(slot, scopedSlot, "footer");
if (footer) {
footerOffset = footer.length;
children = children ? [].concat(_toConsumableArray(children), _toConsumableArray(footer)) : _toConsumableArray(footer);
}
return {
children: children,
headerOffset: headerOffset,
footerOffset: footerOffset
};
}
function getComponentAttributes($attrs, componentData) {
var attributes = null;
var update = function update(name, value) {
attributes = buildAttribute(attributes, name, value);
};
var attrs = keys_default()($attrs).filter(function (key) {
return key === "id" || key.startsWith("data-");
}).reduce(function (res, key) {
res[key] = $attrs[key];
return res;
}, {});
update("attrs", attrs);
if (!componentData) {
return attributes;
}
var on = componentData.on,
props = componentData.props,
componentDataAttrs = componentData.attrs;
update("on", on);
update("props", props);
assign_default()(attributes.attrs, componentDataAttrs);
return attributes;
}
var eventsListened = ["Start", "Add", "Remove", "Update", "End"];
var eventsToEmit = ["Choose", "Unchoose", "Sort", "Filter", "Clone"];
var readonlyProperties = ["Move"].concat(eventsListened, eventsToEmit).map(function (evt) {
return "on" + evt;
});
var draggingElement = null;
var vuedraggable_props = {
options: Object,
list: {
type: Array,
required: false,
default: null
},
value: {
type: Array,
required: false,
default: null
},
noTransitionOnDrag: {
type: Boolean,
default: false
},
clone: {
type: Function,
default: function _default(original) {
return original;
}
},
element: {
type: String,
default: "div"
},
tag: {
type: String,
default: null
},
move: {
type: Function,
default: null
},
componentData: {
type: Object,
required: false,
default: null
}
};
var draggableComponent = {
name: "draggable",
inheritAttrs: false,
props: vuedraggable_props,
data: function data() {
return {
transitionMode: false,
noneFunctionalComponentMode: false
};
},
render: function render(h) {
var slots = this.$slots.default;
this.transitionMode = vuedraggable_isTransition(slots);
var _computeChildrenAndOf = computeChildrenAndOffsets(slots, this.$slots, this.$scopedSlots),
children = _computeChildrenAndOf.children,
headerOffset = _computeChildrenAndOf.headerOffset,
footerOffset = _computeChildrenAndOf.footerOffset;
this.headerOffset = headerOffset;
this.footerOffset = footerOffset;
var attributes = getComponentAttributes(this.$attrs, this.componentData);
return h(this.getTag(), attributes, children);
},
created: function created() {
if (this.list !== null && this.value !== null) {
helper["b" /* console */].error("Value and list props are mutually exclusive! Please set one or another.");
}
if (this.element !== "div") {
helper["b" /* console */].warn("Element props is deprecated please use tag props instead. See https://github.com/SortableJS/Vue.Draggable/blob/master/documentation/migrate.md#element-props");
}
if (this.options !== undefined) {
helper["b" /* console */].warn("Options props is deprecated, add sortable options directly as vue.draggable item, or use v-bind. See https://github.com/SortableJS/Vue.Draggable/blob/master/documentation/migrate.md#options-props");
}
},
mounted: function mounted() {
var _this3 = this;
this.noneFunctionalComponentMode = this.getTag().toLowerCase() !== this.$el.nodeName.toLowerCase() && !this.getIsFunctional();
if (this.noneFunctionalComponentMode && this.transitionMode) {
throw new Error("Transition-group inside component is not supported. Please alter tag value or remove transition-group. Current tag value: ".concat(this.getTag()));
}
var optionsAdded = {};
eventsListened.forEach(function (elt) {
optionsAdded["on" + elt] = delegateAndEmit.call(_this3, elt);
});
eventsToEmit.forEach(function (elt) {
optionsAdded["on" + elt] = emit.bind(_this3, elt);
});
var attributes = keys_default()(this.$attrs).reduce(function (res, key) {
res[Object(helper["a" /* camelize */])(key)] = _this3.$attrs[key];
return res;
}, {});
var options = assign_default()({}, this.options, attributes, optionsAdded, {
onMove: function onMove(evt, originalEvent) {
return _this3.onDragMove(evt, originalEvent);
}
});
!("draggable" in options) && (options.draggable = ">*");
this._sortable = new external_commonjs_sortablejs_commonjs2_sortablejs_amd_sortablejs_root_Sortable_default.a(this.rootContainer, options);
this.computeIndexes();
},
beforeDestroy: function beforeDestroy() {
if (this._sortable !== undefined) this._sortable.destroy();
},
computed: {
rootContainer: function rootContainer() {
return this.transitionMode ? this.$el.children[0] : this.$el;
},
realList: function realList() {
return this.list ? this.list : this.value;
}
},
watch: {
options: {
handler: function handler(newOptionValue) {
this.updateOptions(newOptionValue);
},
deep: true
},
$attrs: {
handler: function handler(newOptionValue) {
this.updateOptions(newOptionValue);
},
deep: true
},
realList: function realList() {
this.computeIndexes();
}
},
methods: {
getIsFunctional: function getIsFunctional() {
var fnOptions = this._vnode.fnOptions;
return fnOptions && fnOptions.functional;
},
getTag: function getTag() {
return this.tag || this.element;
},
updateOptions: function updateOptions(newOptionValue) {
for (var property in newOptionValue) {
var value = Object(helper["a" /* camelize */])(property);
if (readonlyProperties.indexOf(value) === -1) {
this._sortable.option(value, newOptionValue[property]);
}
}
},
getChildrenNodes: function getChildrenNodes() {
if (this.noneFunctionalComponentMode) {
return this.$children[0].$slots.default;
}
var rawNodes = this.$slots.default;
return this.transitionMode ? rawNodes[0].child.$slots.default : rawNodes;
},
computeIndexes: function computeIndexes() {
var _this4 = this;
this.$nextTick(function () {
_this4.visibleIndexes = _computeIndexes(_this4.getChildrenNodes(), _this4.rootContainer.children, _this4.transitionMode, _this4.footerOffset);
});
},
getUnderlyingVm: function getUnderlyingVm(htmlElt) {
var index = computeVmIndex(this.getChildrenNodes() || [], htmlElt);
if (index === -1) {
//Edge case during move callback: related element might be
//an element different from collection
return null;
}
var element = this.realList[index];
return {
index: index,
element: element
};
},
getUnderlyingPotencialDraggableComponent: function getUnderlyingPotencialDraggableComponent(_ref) {
var vue = _ref.__vue__;
if (!vue || !vue.$options || !isTransitionName(vue.$options._componentTag)) {
if (!("realList" in vue) && vue.$children.length === 1 && "realList" in vue.$children[0]) return vue.$children[0];
return vue;
}
return vue.$parent;
},
emitChanges: function emitChanges(evt) {
var _this5 = this;
this.$nextTick(function () {
_this5.$emit("change", evt);
});
},
alterList: function alterList(onList) {
if (this.list) {
onList(this.list);
return;
}
var newList = _toConsumableArray(this.value);
onList(newList);
this.$emit("input", newList);
},
spliceList: function spliceList() {
var _arguments = arguments;
var spliceList = function spliceList(list) {
return list.splice.apply(list, _toConsumableArray(_arguments));
};
this.alterList(spliceList);
},
updatePosition: function updatePosition(oldIndex, newIndex) {
var updatePosition = function updatePosition(list) {
return list.splice(newIndex, 0, list.splice(oldIndex, 1)[0]);
};
this.alterList(updatePosition);
},
getRelatedContextFromMoveEvent: function getRelatedContextFromMoveEvent(_ref2) {
var to = _ref2.to,
related = _ref2.related;
var component = this.getUnderlyingPotencialDraggableComponent(to);
if (!component) {
return {
component: component
};
}
var list = component.realList;
var context = {
list: list,
component: component
};
if (to !== related && list && component.getUnderlyingVm) {
var destination = component.getUnderlyingVm(related);
if (destination) {
return assign_default()(destination, context);
}
}
return context;
},
getVmIndex: function getVmIndex(domIndex) {
var indexes = this.visibleIndexes;
var numberIndexes = indexes.length;
return domIndex > numberIndexes - 1 ? numberIndexes : indexes[domIndex];
},
getComponent: function getComponent() {
return this.$slots.default[0].componentInstance;
},
resetTransitionData: function resetTransitionData(index) {
if (!this.noTransitionOnDrag || !this.transitionMode) {
return;
}
var nodes = this.getChildrenNodes();
nodes[index].data = null;
var transitionContainer = this.getComponent();
transitionContainer.children = [];
transitionContainer.kept = undefined;
},
onDragStart: function onDragStart(evt) {
this.context = this.getUnderlyingVm(evt.item);
evt.item._underlying_vm_ = this.clone(this.context.element);
draggingElement = evt.item;
},
onDragAdd: function onDragAdd(evt) {
var element = evt.item._underlying_vm_;
if (element === undefined) {
return;
}
Object(helper["d" /* removeNode */])(evt.item);
var newIndex = this.getVmIndex(evt.newIndex);
this.spliceList(newIndex, 0, element);
this.computeIndexes();
var added = {
element: element,
newIndex: newIndex
};
this.emitChanges({
added: added
});
},
onDragRemove: function onDragRemove(evt) {
Object(helper["c" /* insertNodeAt */])(this.rootContainer, evt.item, evt.oldIndex);
if (evt.pullMode === "clone") {
Object(helper["d" /* removeNode */])(evt.clone);
return;
}
var oldIndex = this.context.index;
this.spliceList(oldIndex, 1);
var removed = {
element: this.context.element,
oldIndex: oldIndex
};
this.resetTransitionData(oldIndex);
this.emitChanges({
removed: removed
});
},
onDragUpdate: function onDragUpdate(evt) {
Object(helper["d" /* removeNode */])(evt.item);
Object(helper["c" /* insertNodeAt */])(evt.from, evt.item, evt.oldIndex);
var oldIndex = this.context.index;
var newIndex = this.getVmIndex(evt.newIndex);
this.updatePosition(oldIndex, newIndex);
var moved = {
element: this.context.element,
oldIndex: oldIndex,
newIndex: newIndex
};
this.emitChanges({
moved: moved
});
},
updateProperty: function updateProperty(evt, propertyName) {
evt.hasOwnProperty(propertyName) && (evt[propertyName] += this.headerOffset);
},
computeFutureIndex: function computeFutureIndex(relatedContext, evt) {
if (!relatedContext.element) {
return 0;
}
var domChildren = _toConsumableArray(evt.to.children).filter(function (el) {
return el.style["display"] !== "none";
});
var currentDOMIndex = domChildren.indexOf(evt.related);
var currentIndex = relatedContext.component.getVmIndex(currentDOMIndex);
var draggedInList = domChildren.indexOf(draggingElement) !== -1;
return draggedInList || !evt.willInsertAfter ? currentIndex : currentIndex + 1;
},
onDragMove: function onDragMove(evt, originalEvent) {
var onMove = this.move;
if (!onMove || !this.realList) {
return true;
}
var relatedContext = this.getRelatedContextFromMoveEvent(evt);
var draggedContext = this.context;
var futureIndex = this.computeFutureIndex(relatedContext, evt);
assign_default()(draggedContext, {
futureIndex: futureIndex
});
var sendEvt = assign_default()({}, evt, {
relatedContext: relatedContext,
draggedContext: draggedContext
});
return onMove(sendEvt, originalEvent);
},
onDragEnd: function onDragEnd() {
this.computeIndexes();
draggingElement = null;
}
}
};
if (typeof window !== "undefined" && "Vue" in window) {
window.Vue.component("draggable", draggableComponent);
}
/* harmony default export */ var vuedraggable = (draggableComponent);
// CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/entry-lib.js
/* harmony default export */ var entry_lib = __webpack_exports__["default"] = (vuedraggable);
/***/ })
/******/ })["default"];
});
//# sourceMappingURL=vuedraggable.umd.js.map | {
"pile_set_name": "Github"
} |
/*
* cs42l73.c -- CS42L73 ALSA Soc Audio driver
*
* Copyright 2011 Cirrus Logic, Inc.
*
* Authors: Georgi Vlaev, Nucleus Systems Ltd, <[email protected]>
* Brian Austin, Cirrus Logic Inc, <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/regmap.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include "cs42l73.h"
struct sp_config {
u8 spc, mmcc, spfs;
u32 srate;
};
struct cs42l73_private {
struct sp_config config[3];
struct regmap *regmap;
u32 sysclk;
u8 mclksel;
u32 mclk;
};
static const struct reg_default cs42l73_reg_defaults[] = {
{ 1, 0x42 }, /* r01 - Device ID A&B */
{ 2, 0xA7 }, /* r02 - Device ID C&D */
{ 3, 0x30 }, /* r03 - Device ID E */
{ 6, 0xF1 }, /* r06 - Power Ctl 1 */
{ 7, 0xDF }, /* r07 - Power Ctl 2 */
{ 8, 0x3F }, /* r08 - Power Ctl 3 */
{ 9, 0x50 }, /* r09 - Charge Pump Freq */
{ 10, 0x53 }, /* r0A - Output Load MicBias Short Detect */
{ 11, 0x00 }, /* r0B - DMIC Master Clock Ctl */
{ 12, 0x00 }, /* r0C - Aux PCM Ctl */
{ 13, 0x15 }, /* r0D - Aux PCM Master Clock Ctl */
{ 14, 0x00 }, /* r0E - Audio PCM Ctl */
{ 15, 0x15 }, /* r0F - Audio PCM Master Clock Ctl */
{ 16, 0x00 }, /* r10 - Voice PCM Ctl */
{ 17, 0x15 }, /* r11 - Voice PCM Master Clock Ctl */
{ 18, 0x00 }, /* r12 - Voice/Aux Sample Rate */
{ 19, 0x06 }, /* r13 - Misc I/O Path Ctl */
{ 20, 0x00 }, /* r14 - ADC Input Path Ctl */
{ 21, 0x00 }, /* r15 - MICA Preamp, PGA Volume */
{ 22, 0x00 }, /* r16 - MICB Preamp, PGA Volume */
{ 23, 0x00 }, /* r17 - Input Path A Digital Volume */
{ 24, 0x00 }, /* r18 - Input Path B Digital Volume */
{ 25, 0x00 }, /* r19 - Playback Digital Ctl */
{ 26, 0x00 }, /* r1A - HP/LO Left Digital Volume */
{ 27, 0x00 }, /* r1B - HP/LO Right Digital Volume */
{ 28, 0x00 }, /* r1C - Speakerphone Digital Volume */
{ 29, 0x00 }, /* r1D - Ear/SPKLO Digital Volume */
{ 30, 0x00 }, /* r1E - HP Left Analog Volume */
{ 31, 0x00 }, /* r1F - HP Right Analog Volume */
{ 32, 0x00 }, /* r20 - LO Left Analog Volume */
{ 33, 0x00 }, /* r21 - LO Right Analog Volume */
{ 34, 0x00 }, /* r22 - Stereo Input Path Advisory Volume */
{ 35, 0x00 }, /* r23 - Aux PCM Input Advisory Volume */
{ 36, 0x00 }, /* r24 - Audio PCM Input Advisory Volume */
{ 37, 0x00 }, /* r25 - Voice PCM Input Advisory Volume */
{ 38, 0x00 }, /* r26 - Limiter Attack Rate HP/LO */
{ 39, 0x7F }, /* r27 - Limter Ctl, Release Rate HP/LO */
{ 40, 0x00 }, /* r28 - Limter Threshold HP/LO */
{ 41, 0x00 }, /* r29 - Limiter Attack Rate Speakerphone */
{ 42, 0x3F }, /* r2A - Limter Ctl, Release Rate Speakerphone */
{ 43, 0x00 }, /* r2B - Limter Threshold Speakerphone */
{ 44, 0x00 }, /* r2C - Limiter Attack Rate Ear/SPKLO */
{ 45, 0x3F }, /* r2D - Limter Ctl, Release Rate Ear/SPKLO */
{ 46, 0x00 }, /* r2E - Limter Threshold Ear/SPKLO */
{ 47, 0x00 }, /* r2F - ALC Enable, Attack Rate Left/Right */
{ 48, 0x3F }, /* r30 - ALC Release Rate Left/Right */
{ 49, 0x00 }, /* r31 - ALC Threshold Left/Right */
{ 50, 0x00 }, /* r32 - Noise Gate Ctl Left/Right */
{ 51, 0x00 }, /* r33 - ALC/NG Misc Ctl */
{ 52, 0x18 }, /* r34 - Mixer Ctl */
{ 53, 0x3F }, /* r35 - HP/LO Left Mixer Input Path Volume */
{ 54, 0x3F }, /* r36 - HP/LO Right Mixer Input Path Volume */
{ 55, 0x3F }, /* r37 - HP/LO Left Mixer Aux PCM Volume */
{ 56, 0x3F }, /* r38 - HP/LO Right Mixer Aux PCM Volume */
{ 57, 0x3F }, /* r39 - HP/LO Left Mixer Audio PCM Volume */
{ 58, 0x3F }, /* r3A - HP/LO Right Mixer Audio PCM Volume */
{ 59, 0x3F }, /* r3B - HP/LO Left Mixer Voice PCM Mono Volume */
{ 60, 0x3F }, /* r3C - HP/LO Right Mixer Voice PCM Mono Volume */
{ 61, 0x3F }, /* r3D - Aux PCM Left Mixer Input Path Volume */
{ 62, 0x3F }, /* r3E - Aux PCM Right Mixer Input Path Volume */
{ 63, 0x3F }, /* r3F - Aux PCM Left Mixer Volume */
{ 64, 0x3F }, /* r40 - Aux PCM Left Mixer Volume */
{ 65, 0x3F }, /* r41 - Aux PCM Left Mixer Audio PCM L Volume */
{ 66, 0x3F }, /* r42 - Aux PCM Right Mixer Audio PCM R Volume */
{ 67, 0x3F }, /* r43 - Aux PCM Left Mixer Voice PCM Volume */
{ 68, 0x3F }, /* r44 - Aux PCM Right Mixer Voice PCM Volume */
{ 69, 0x3F }, /* r45 - Audio PCM Left Input Path Volume */
{ 70, 0x3F }, /* r46 - Audio PCM Right Input Path Volume */
{ 71, 0x3F }, /* r47 - Audio PCM Left Mixer Aux PCM L Volume */
{ 72, 0x3F }, /* r48 - Audio PCM Right Mixer Aux PCM R Volume */
{ 73, 0x3F }, /* r49 - Audio PCM Left Mixer Volume */
{ 74, 0x3F }, /* r4A - Audio PCM Right Mixer Volume */
{ 75, 0x3F }, /* r4B - Audio PCM Left Mixer Voice PCM Volume */
{ 76, 0x3F }, /* r4C - Audio PCM Right Mixer Voice PCM Volume */
{ 77, 0x3F }, /* r4D - Voice PCM Left Input Path Volume */
{ 78, 0x3F }, /* r4E - Voice PCM Right Input Path Volume */
{ 79, 0x3F }, /* r4F - Voice PCM Left Mixer Aux PCM L Volume */
{ 80, 0x3F }, /* r50 - Voice PCM Right Mixer Aux PCM R Volume */
{ 81, 0x3F }, /* r51 - Voice PCM Left Mixer Audio PCM L Volume */
{ 82, 0x3F }, /* r52 - Voice PCM Right Mixer Audio PCM R Volume */
{ 83, 0x3F }, /* r53 - Voice PCM Left Mixer Voice PCM Volume */
{ 84, 0x3F }, /* r54 - Voice PCM Right Mixer Voice PCM Volume */
{ 85, 0xAA }, /* r55 - Mono Mixer Ctl */
{ 86, 0x3F }, /* r56 - SPK Mono Mixer Input Path Volume */
{ 87, 0x3F }, /* r57 - SPK Mono Mixer Aux PCM Mono/L/R Volume */
{ 88, 0x3F }, /* r58 - SPK Mono Mixer Audio PCM Mono/L/R Volume */
{ 89, 0x3F }, /* r59 - SPK Mono Mixer Voice PCM Mono Volume */
{ 90, 0x3F }, /* r5A - SPKLO Mono Mixer Input Path Mono Volume */
{ 91, 0x3F }, /* r5B - SPKLO Mono Mixer Aux Mono/L/R Volume */
{ 92, 0x3F }, /* r5C - SPKLO Mono Mixer Audio Mono/L/R Volume */
{ 93, 0x3F }, /* r5D - SPKLO Mono Mixer Voice Mono Volume */
{ 94, 0x00 }, /* r5E - Interrupt Mask 1 */
{ 95, 0x00 }, /* r5F - Interrupt Mask 2 */
};
static bool cs42l73_volatile_register(struct device *dev, unsigned int reg)
{
switch (reg) {
case CS42L73_IS1:
case CS42L73_IS2:
return true;
default:
return false;
}
}
static bool cs42l73_readable_register(struct device *dev, unsigned int reg)
{
switch (reg) {
case CS42L73_DEVID_AB:
case CS42L73_DEVID_CD:
case CS42L73_DEVID_E:
case CS42L73_REVID:
case CS42L73_PWRCTL1:
case CS42L73_PWRCTL2:
case CS42L73_PWRCTL3:
case CS42L73_CPFCHC:
case CS42L73_OLMBMSDC:
case CS42L73_DMMCC:
case CS42L73_XSPC:
case CS42L73_XSPMMCC:
case CS42L73_ASPC:
case CS42L73_ASPMMCC:
case CS42L73_VSPC:
case CS42L73_VSPMMCC:
case CS42L73_VXSPFS:
case CS42L73_MIOPC:
case CS42L73_ADCIPC:
case CS42L73_MICAPREPGAAVOL:
case CS42L73_MICBPREPGABVOL:
case CS42L73_IPADVOL:
case CS42L73_IPBDVOL:
case CS42L73_PBDC:
case CS42L73_HLADVOL:
case CS42L73_HLBDVOL:
case CS42L73_SPKDVOL:
case CS42L73_ESLDVOL:
case CS42L73_HPAAVOL:
case CS42L73_HPBAVOL:
case CS42L73_LOAAVOL:
case CS42L73_LOBAVOL:
case CS42L73_STRINV:
case CS42L73_XSPINV:
case CS42L73_ASPINV:
case CS42L73_VSPINV:
case CS42L73_LIMARATEHL:
case CS42L73_LIMRRATEHL:
case CS42L73_LMAXHL:
case CS42L73_LIMARATESPK:
case CS42L73_LIMRRATESPK:
case CS42L73_LMAXSPK:
case CS42L73_LIMARATEESL:
case CS42L73_LIMRRATEESL:
case CS42L73_LMAXESL:
case CS42L73_ALCARATE:
case CS42L73_ALCRRATE:
case CS42L73_ALCMINMAX:
case CS42L73_NGCAB:
case CS42L73_ALCNGMC:
case CS42L73_MIXERCTL:
case CS42L73_HLAIPAA:
case CS42L73_HLBIPBA:
case CS42L73_HLAXSPAA:
case CS42L73_HLBXSPBA:
case CS42L73_HLAASPAA:
case CS42L73_HLBASPBA:
case CS42L73_HLAVSPMA:
case CS42L73_HLBVSPMA:
case CS42L73_XSPAIPAA:
case CS42L73_XSPBIPBA:
case CS42L73_XSPAXSPAA:
case CS42L73_XSPBXSPBA:
case CS42L73_XSPAASPAA:
case CS42L73_XSPAASPBA:
case CS42L73_XSPAVSPMA:
case CS42L73_XSPBVSPMA:
case CS42L73_ASPAIPAA:
case CS42L73_ASPBIPBA:
case CS42L73_ASPAXSPAA:
case CS42L73_ASPBXSPBA:
case CS42L73_ASPAASPAA:
case CS42L73_ASPBASPBA:
case CS42L73_ASPAVSPMA:
case CS42L73_ASPBVSPMA:
case CS42L73_VSPAIPAA:
case CS42L73_VSPBIPBA:
case CS42L73_VSPAXSPAA:
case CS42L73_VSPBXSPBA:
case CS42L73_VSPAASPAA:
case CS42L73_VSPBASPBA:
case CS42L73_VSPAVSPMA:
case CS42L73_VSPBVSPMA:
case CS42L73_MMIXCTL:
case CS42L73_SPKMIPMA:
case CS42L73_SPKMXSPA:
case CS42L73_SPKMASPA:
case CS42L73_SPKMVSPMA:
case CS42L73_ESLMIPMA:
case CS42L73_ESLMXSPA:
case CS42L73_ESLMASPA:
case CS42L73_ESLMVSPMA:
case CS42L73_IM1:
case CS42L73_IM2:
return true;
default:
return false;
}
}
static const unsigned int hpaloa_tlv[] = {
TLV_DB_RANGE_HEAD(2),
0, 13, TLV_DB_SCALE_ITEM(-7600, 200, 0),
14, 75, TLV_DB_SCALE_ITEM(-4900, 100, 0),
};
static DECLARE_TLV_DB_SCALE(adc_boost_tlv, 0, 2500, 0);
static DECLARE_TLV_DB_SCALE(hl_tlv, -10200, 50, 0);
static DECLARE_TLV_DB_SCALE(ipd_tlv, -9600, 100, 0);
static DECLARE_TLV_DB_SCALE(micpga_tlv, -600, 50, 0);
static const unsigned int limiter_tlv[] = {
TLV_DB_RANGE_HEAD(2),
0, 2, TLV_DB_SCALE_ITEM(-3000, 600, 0),
3, 7, TLV_DB_SCALE_ITEM(-1200, 300, 0),
};
static const DECLARE_TLV_DB_SCALE(attn_tlv, -6300, 100, 1);
static const char * const cs42l73_pgaa_text[] = { "Line A", "Mic 1" };
static const char * const cs42l73_pgab_text[] = { "Line B", "Mic 2" };
static const struct soc_enum pgaa_enum =
SOC_ENUM_SINGLE(CS42L73_ADCIPC, 3,
ARRAY_SIZE(cs42l73_pgaa_text), cs42l73_pgaa_text);
static const struct soc_enum pgab_enum =
SOC_ENUM_SINGLE(CS42L73_ADCIPC, 7,
ARRAY_SIZE(cs42l73_pgab_text), cs42l73_pgab_text);
static const struct snd_kcontrol_new pgaa_mux =
SOC_DAPM_ENUM("Left Analog Input Capture Mux", pgaa_enum);
static const struct snd_kcontrol_new pgab_mux =
SOC_DAPM_ENUM("Right Analog Input Capture Mux", pgab_enum);
static const struct snd_kcontrol_new input_left_mixer[] = {
SOC_DAPM_SINGLE("ADC Left Input", CS42L73_PWRCTL1,
5, 1, 1),
SOC_DAPM_SINGLE("DMIC Left Input", CS42L73_PWRCTL1,
4, 1, 1),
};
static const struct snd_kcontrol_new input_right_mixer[] = {
SOC_DAPM_SINGLE("ADC Right Input", CS42L73_PWRCTL1,
7, 1, 1),
SOC_DAPM_SINGLE("DMIC Right Input", CS42L73_PWRCTL1,
6, 1, 1),
};
static const char * const cs42l73_ng_delay_text[] = {
"50ms", "100ms", "150ms", "200ms" };
static const struct soc_enum ng_delay_enum =
SOC_ENUM_SINGLE(CS42L73_NGCAB, 0,
ARRAY_SIZE(cs42l73_ng_delay_text), cs42l73_ng_delay_text);
static const char * const charge_pump_freq_text[] = {
"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9",
"10", "11", "12", "13", "14", "15" };
static const struct soc_enum charge_pump_enum =
SOC_ENUM_SINGLE(CS42L73_CPFCHC, 4,
ARRAY_SIZE(charge_pump_freq_text), charge_pump_freq_text);
static const char * const cs42l73_mono_mix_texts[] = {
"Left", "Right", "Mono Mix"};
static const unsigned int cs42l73_mono_mix_values[] = { 0, 1, 2 };
static const struct soc_enum spk_asp_enum =
SOC_VALUE_ENUM_SINGLE(CS42L73_MMIXCTL, 6, 3,
ARRAY_SIZE(cs42l73_mono_mix_texts),
cs42l73_mono_mix_texts,
cs42l73_mono_mix_values);
static const struct snd_kcontrol_new spk_asp_mixer =
SOC_DAPM_ENUM("Route", spk_asp_enum);
static const struct soc_enum spk_xsp_enum =
SOC_VALUE_ENUM_SINGLE(CS42L73_MMIXCTL, 4, 3,
ARRAY_SIZE(cs42l73_mono_mix_texts),
cs42l73_mono_mix_texts,
cs42l73_mono_mix_values);
static const struct snd_kcontrol_new spk_xsp_mixer =
SOC_DAPM_ENUM("Route", spk_xsp_enum);
static const struct soc_enum esl_asp_enum =
SOC_VALUE_ENUM_SINGLE(CS42L73_MMIXCTL, 2, 3,
ARRAY_SIZE(cs42l73_mono_mix_texts),
cs42l73_mono_mix_texts,
cs42l73_mono_mix_values);
static const struct snd_kcontrol_new esl_asp_mixer =
SOC_DAPM_ENUM("Route", esl_asp_enum);
static const struct soc_enum esl_xsp_enum =
SOC_VALUE_ENUM_SINGLE(CS42L73_MMIXCTL, 0, 3,
ARRAY_SIZE(cs42l73_mono_mix_texts),
cs42l73_mono_mix_texts,
cs42l73_mono_mix_values);
static const struct snd_kcontrol_new esl_xsp_mixer =
SOC_DAPM_ENUM("Route", esl_xsp_enum);
static const char * const cs42l73_ip_swap_text[] = {
"Stereo", "Mono A", "Mono B", "Swap A-B"};
static const struct soc_enum ip_swap_enum =
SOC_ENUM_SINGLE(CS42L73_MIOPC, 6,
ARRAY_SIZE(cs42l73_ip_swap_text), cs42l73_ip_swap_text);
static const char * const cs42l73_spo_mixer_text[] = {"Mono", "Stereo"};
static const struct soc_enum vsp_output_mux_enum =
SOC_ENUM_SINGLE(CS42L73_MIXERCTL, 5,
ARRAY_SIZE(cs42l73_spo_mixer_text), cs42l73_spo_mixer_text);
static const struct soc_enum xsp_output_mux_enum =
SOC_ENUM_SINGLE(CS42L73_MIXERCTL, 4,
ARRAY_SIZE(cs42l73_spo_mixer_text), cs42l73_spo_mixer_text);
static const struct snd_kcontrol_new vsp_output_mux =
SOC_DAPM_ENUM("Route", vsp_output_mux_enum);
static const struct snd_kcontrol_new xsp_output_mux =
SOC_DAPM_ENUM("Route", xsp_output_mux_enum);
static const struct snd_kcontrol_new hp_amp_ctl =
SOC_DAPM_SINGLE("Switch", CS42L73_PWRCTL3, 0, 1, 1);
static const struct snd_kcontrol_new lo_amp_ctl =
SOC_DAPM_SINGLE("Switch", CS42L73_PWRCTL3, 1, 1, 1);
static const struct snd_kcontrol_new spk_amp_ctl =
SOC_DAPM_SINGLE("Switch", CS42L73_PWRCTL3, 2, 1, 1);
static const struct snd_kcontrol_new spklo_amp_ctl =
SOC_DAPM_SINGLE("Switch", CS42L73_PWRCTL3, 4, 1, 1);
static const struct snd_kcontrol_new ear_amp_ctl =
SOC_DAPM_SINGLE("Switch", CS42L73_PWRCTL3, 3, 1, 1);
static const struct snd_kcontrol_new cs42l73_snd_controls[] = {
SOC_DOUBLE_R_SX_TLV("Headphone Analog Playback Volume",
CS42L73_HPAAVOL, CS42L73_HPBAVOL, 7,
0xffffffC1, 0x0C, hpaloa_tlv),
SOC_DOUBLE_R_SX_TLV("LineOut Analog Playback Volume", CS42L73_LOAAVOL,
CS42L73_LOBAVOL, 7, 0xffffffC1, 0x0C, hpaloa_tlv),
SOC_DOUBLE_R_SX_TLV("Input PGA Analog Volume", CS42L73_MICAPREPGAAVOL,
CS42L73_MICBPREPGABVOL, 5, 0xffffff35,
0x34, micpga_tlv),
SOC_DOUBLE_R("MIC Preamp Switch", CS42L73_MICAPREPGAAVOL,
CS42L73_MICBPREPGABVOL, 6, 1, 1),
SOC_DOUBLE_R_SX_TLV("Input Path Digital Volume", CS42L73_IPADVOL,
CS42L73_IPBDVOL, 7, 0xffffffA0, 0xA0, ipd_tlv),
SOC_DOUBLE_R_SX_TLV("HL Digital Playback Volume",
CS42L73_HLADVOL, CS42L73_HLBDVOL, 7, 0xffffffE5,
0xE4, hl_tlv),
SOC_SINGLE_TLV("ADC A Boost Volume",
CS42L73_ADCIPC, 2, 0x01, 1, adc_boost_tlv),
SOC_SINGLE_TLV("ADC B Boost Volume",
CS42L73_ADCIPC, 6, 0x01, 1, adc_boost_tlv),
SOC_SINGLE_TLV("Speakerphone Digital Playback Volume",
CS42L73_SPKDVOL, 0, 0xE4, 1, hl_tlv),
SOC_SINGLE_TLV("Ear Speaker Digital Playback Volume",
CS42L73_ESLDVOL, 0, 0xE4, 1, hl_tlv),
SOC_DOUBLE_R("Headphone Analog Playback Switch", CS42L73_HPAAVOL,
CS42L73_HPBAVOL, 7, 1, 1),
SOC_DOUBLE_R("LineOut Analog Playback Switch", CS42L73_LOAAVOL,
CS42L73_LOBAVOL, 7, 1, 1),
SOC_DOUBLE("Input Path Digital Switch", CS42L73_ADCIPC, 0, 4, 1, 1),
SOC_DOUBLE("HL Digital Playback Switch", CS42L73_PBDC, 0,
1, 1, 1),
SOC_SINGLE("Speakerphone Digital Playback Switch", CS42L73_PBDC, 2, 1,
1),
SOC_SINGLE("Ear Speaker Digital Playback Switch", CS42L73_PBDC, 3, 1,
1),
SOC_SINGLE("PGA Soft-Ramp Switch", CS42L73_MIOPC, 3, 1, 0),
SOC_SINGLE("Analog Zero Cross Switch", CS42L73_MIOPC, 2, 1, 0),
SOC_SINGLE("Digital Soft-Ramp Switch", CS42L73_MIOPC, 1, 1, 0),
SOC_SINGLE("Analog Output Soft-Ramp Switch", CS42L73_MIOPC, 0, 1, 0),
SOC_DOUBLE("ADC Signal Polarity Switch", CS42L73_ADCIPC, 1, 5, 1,
0),
SOC_SINGLE("HL Limiter Attack Rate", CS42L73_LIMARATEHL, 0, 0x3F,
0),
SOC_SINGLE("HL Limiter Release Rate", CS42L73_LIMRRATEHL, 0,
0x3F, 0),
SOC_SINGLE("HL Limiter Switch", CS42L73_LIMRRATEHL, 7, 1, 0),
SOC_SINGLE("HL Limiter All Channels Switch", CS42L73_LIMRRATEHL, 6, 1,
0),
SOC_SINGLE_TLV("HL Limiter Max Threshold Volume", CS42L73_LMAXHL, 5, 7,
1, limiter_tlv),
SOC_SINGLE_TLV("HL Limiter Cushion Volume", CS42L73_LMAXHL, 2, 7, 1,
limiter_tlv),
SOC_SINGLE("SPK Limiter Attack Rate Volume", CS42L73_LIMARATESPK, 0,
0x3F, 0),
SOC_SINGLE("SPK Limiter Release Rate Volume", CS42L73_LIMRRATESPK, 0,
0x3F, 0),
SOC_SINGLE("SPK Limiter Switch", CS42L73_LIMRRATESPK, 7, 1, 0),
SOC_SINGLE("SPK Limiter All Channels Switch", CS42L73_LIMRRATESPK,
6, 1, 0),
SOC_SINGLE_TLV("SPK Limiter Max Threshold Volume", CS42L73_LMAXSPK, 5,
7, 1, limiter_tlv),
SOC_SINGLE_TLV("SPK Limiter Cushion Volume", CS42L73_LMAXSPK, 2, 7, 1,
limiter_tlv),
SOC_SINGLE("ESL Limiter Attack Rate Volume", CS42L73_LIMARATEESL, 0,
0x3F, 0),
SOC_SINGLE("ESL Limiter Release Rate Volume", CS42L73_LIMRRATEESL, 0,
0x3F, 0),
SOC_SINGLE("ESL Limiter Switch", CS42L73_LIMRRATEESL, 7, 1, 0),
SOC_SINGLE_TLV("ESL Limiter Max Threshold Volume", CS42L73_LMAXESL, 5,
7, 1, limiter_tlv),
SOC_SINGLE_TLV("ESL Limiter Cushion Volume", CS42L73_LMAXESL, 2, 7, 1,
limiter_tlv),
SOC_SINGLE("ALC Attack Rate Volume", CS42L73_ALCARATE, 0, 0x3F, 0),
SOC_SINGLE("ALC Release Rate Volume", CS42L73_ALCRRATE, 0, 0x3F, 0),
SOC_DOUBLE("ALC Switch", CS42L73_ALCARATE, 6, 7, 1, 0),
SOC_SINGLE_TLV("ALC Max Threshold Volume", CS42L73_ALCMINMAX, 5, 7, 0,
limiter_tlv),
SOC_SINGLE_TLV("ALC Min Threshold Volume", CS42L73_ALCMINMAX, 2, 7, 0,
limiter_tlv),
SOC_DOUBLE("NG Enable Switch", CS42L73_NGCAB, 6, 7, 1, 0),
SOC_SINGLE("NG Boost Switch", CS42L73_NGCAB, 5, 1, 0),
/*
NG Threshold depends on NG_BOOTSAB, which selects
between two threshold scales in decibels.
Set linear values for now ..
*/
SOC_SINGLE("NG Threshold", CS42L73_NGCAB, 2, 7, 0),
SOC_ENUM("NG Delay", ng_delay_enum),
SOC_ENUM("Charge Pump Frequency", charge_pump_enum),
SOC_DOUBLE_R_TLV("XSP-IP Volume",
CS42L73_XSPAIPAA, CS42L73_XSPBIPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("XSP-XSP Volume",
CS42L73_XSPAXSPAA, CS42L73_XSPBXSPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("XSP-ASP Volume",
CS42L73_XSPAASPAA, CS42L73_XSPAASPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("XSP-VSP Volume",
CS42L73_XSPAVSPMA, CS42L73_XSPBVSPMA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("ASP-IP Volume",
CS42L73_ASPAIPAA, CS42L73_ASPBIPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("ASP-XSP Volume",
CS42L73_ASPAXSPAA, CS42L73_ASPBXSPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("ASP-ASP Volume",
CS42L73_ASPAASPAA, CS42L73_ASPBASPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("ASP-VSP Volume",
CS42L73_ASPAVSPMA, CS42L73_ASPBVSPMA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("VSP-IP Volume",
CS42L73_VSPAIPAA, CS42L73_VSPBIPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("VSP-XSP Volume",
CS42L73_VSPAXSPAA, CS42L73_VSPBXSPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("VSP-ASP Volume",
CS42L73_VSPAASPAA, CS42L73_VSPBASPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("VSP-VSP Volume",
CS42L73_VSPAVSPMA, CS42L73_VSPBVSPMA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("HL-IP Volume",
CS42L73_HLAIPAA, CS42L73_HLBIPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("HL-XSP Volume",
CS42L73_HLAXSPAA, CS42L73_HLBXSPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("HL-ASP Volume",
CS42L73_HLAASPAA, CS42L73_HLBASPBA, 0, 0x3F, 1,
attn_tlv),
SOC_DOUBLE_R_TLV("HL-VSP Volume",
CS42L73_HLAVSPMA, CS42L73_HLBVSPMA, 0, 0x3F, 1,
attn_tlv),
SOC_SINGLE_TLV("SPK-IP Mono Volume",
CS42L73_SPKMIPMA, 0, 0x3F, 1, attn_tlv),
SOC_SINGLE_TLV("SPK-XSP Mono Volume",
CS42L73_SPKMXSPA, 0, 0x3F, 1, attn_tlv),
SOC_SINGLE_TLV("SPK-ASP Mono Volume",
CS42L73_SPKMASPA, 0, 0x3F, 1, attn_tlv),
SOC_SINGLE_TLV("SPK-VSP Mono Volume",
CS42L73_SPKMVSPMA, 0, 0x3F, 1, attn_tlv),
SOC_SINGLE_TLV("ESL-IP Mono Volume",
CS42L73_ESLMIPMA, 0, 0x3F, 1, attn_tlv),
SOC_SINGLE_TLV("ESL-XSP Mono Volume",
CS42L73_ESLMXSPA, 0, 0x3F, 1, attn_tlv),
SOC_SINGLE_TLV("ESL-ASP Mono Volume",
CS42L73_ESLMASPA, 0, 0x3F, 1, attn_tlv),
SOC_SINGLE_TLV("ESL-VSP Mono Volume",
CS42L73_ESLMVSPMA, 0, 0x3F, 1, attn_tlv),
SOC_ENUM("IP Digital Swap/Mono Select", ip_swap_enum),
SOC_ENUM("VSPOUT Mono/Stereo Select", vsp_output_mux_enum),
SOC_ENUM("XSPOUT Mono/Stereo Select", xsp_output_mux_enum),
};
static const struct snd_soc_dapm_widget cs42l73_dapm_widgets[] = {
SND_SOC_DAPM_INPUT("LINEINA"),
SND_SOC_DAPM_INPUT("LINEINB"),
SND_SOC_DAPM_INPUT("MIC1"),
SND_SOC_DAPM_SUPPLY("MIC1 Bias", CS42L73_PWRCTL2, 6, 1, NULL, 0),
SND_SOC_DAPM_INPUT("MIC2"),
SND_SOC_DAPM_SUPPLY("MIC2 Bias", CS42L73_PWRCTL2, 7, 1, NULL, 0),
SND_SOC_DAPM_AIF_OUT("XSPOUTL", "XSP Capture", 0,
CS42L73_PWRCTL2, 1, 1),
SND_SOC_DAPM_AIF_OUT("XSPOUTR", "XSP Capture", 0,
CS42L73_PWRCTL2, 1, 1),
SND_SOC_DAPM_AIF_OUT("ASPOUTL", "ASP Capture", 0,
CS42L73_PWRCTL2, 3, 1),
SND_SOC_DAPM_AIF_OUT("ASPOUTR", "ASP Capture", 0,
CS42L73_PWRCTL2, 3, 1),
SND_SOC_DAPM_AIF_OUT("VSPOUTL", "VSP Capture", 0,
CS42L73_PWRCTL2, 4, 1),
SND_SOC_DAPM_AIF_OUT("VSPOUTR", "VSP Capture", 0,
CS42L73_PWRCTL2, 4, 1),
SND_SOC_DAPM_PGA("PGA Left", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_PGA("PGA Right", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MUX("PGA Left Mux", SND_SOC_NOPM, 0, 0, &pgaa_mux),
SND_SOC_DAPM_MUX("PGA Right Mux", SND_SOC_NOPM, 0, 0, &pgab_mux),
SND_SOC_DAPM_ADC("ADC Left", NULL, CS42L73_PWRCTL1, 7, 1),
SND_SOC_DAPM_ADC("ADC Right", NULL, CS42L73_PWRCTL1, 5, 1),
SND_SOC_DAPM_ADC("DMIC Left", NULL, CS42L73_PWRCTL1, 6, 1),
SND_SOC_DAPM_ADC("DMIC Right", NULL, CS42L73_PWRCTL1, 4, 1),
SND_SOC_DAPM_MIXER_NAMED_CTL("Input Left Capture", SND_SOC_NOPM,
0, 0, input_left_mixer,
ARRAY_SIZE(input_left_mixer)),
SND_SOC_DAPM_MIXER_NAMED_CTL("Input Right Capture", SND_SOC_NOPM,
0, 0, input_right_mixer,
ARRAY_SIZE(input_right_mixer)),
SND_SOC_DAPM_MIXER("ASPL Output Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("ASPR Output Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("XSPL Output Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("XSPR Output Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("VSPL Output Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("VSPR Output Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_AIF_IN("XSPINL", "XSP Playback", 0,
CS42L73_PWRCTL2, 0, 1),
SND_SOC_DAPM_AIF_IN("XSPINR", "XSP Playback", 0,
CS42L73_PWRCTL2, 0, 1),
SND_SOC_DAPM_AIF_IN("XSPINM", "XSP Playback", 0,
CS42L73_PWRCTL2, 0, 1),
SND_SOC_DAPM_AIF_IN("ASPINL", "ASP Playback", 0,
CS42L73_PWRCTL2, 2, 1),
SND_SOC_DAPM_AIF_IN("ASPINR", "ASP Playback", 0,
CS42L73_PWRCTL2, 2, 1),
SND_SOC_DAPM_AIF_IN("ASPINM", "ASP Playback", 0,
CS42L73_PWRCTL2, 2, 1),
SND_SOC_DAPM_AIF_IN("VSPIN", "VSP Playback", 0,
CS42L73_PWRCTL2, 4, 1),
SND_SOC_DAPM_MIXER("HL Left Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("HL Right Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SPK Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("ESL Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MUX("ESL-XSP Mux", SND_SOC_NOPM,
0, 0, &esl_xsp_mixer),
SND_SOC_DAPM_MUX("ESL-ASP Mux", SND_SOC_NOPM,
0, 0, &esl_asp_mixer),
SND_SOC_DAPM_MUX("SPK-ASP Mux", SND_SOC_NOPM,
0, 0, &spk_asp_mixer),
SND_SOC_DAPM_MUX("SPK-XSP Mux", SND_SOC_NOPM,
0, 0, &spk_xsp_mixer),
SND_SOC_DAPM_PGA("HL Left DAC", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_PGA("HL Right DAC", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_PGA("SPK DAC", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_PGA("ESL DAC", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_SWITCH("HP Amp", CS42L73_PWRCTL3, 0, 1,
&hp_amp_ctl),
SND_SOC_DAPM_SWITCH("LO Amp", CS42L73_PWRCTL3, 1, 1,
&lo_amp_ctl),
SND_SOC_DAPM_SWITCH("SPK Amp", CS42L73_PWRCTL3, 2, 1,
&spk_amp_ctl),
SND_SOC_DAPM_SWITCH("EAR Amp", CS42L73_PWRCTL3, 3, 1,
&ear_amp_ctl),
SND_SOC_DAPM_SWITCH("SPKLO Amp", CS42L73_PWRCTL3, 4, 1,
&spklo_amp_ctl),
SND_SOC_DAPM_OUTPUT("HPOUTA"),
SND_SOC_DAPM_OUTPUT("HPOUTB"),
SND_SOC_DAPM_OUTPUT("LINEOUTA"),
SND_SOC_DAPM_OUTPUT("LINEOUTB"),
SND_SOC_DAPM_OUTPUT("EAROUT"),
SND_SOC_DAPM_OUTPUT("SPKOUT"),
SND_SOC_DAPM_OUTPUT("SPKLINEOUT"),
};
static const struct snd_soc_dapm_route cs42l73_audio_map[] = {
/* SPKLO EARSPK Paths */
{"EAROUT", NULL, "EAR Amp"},
{"SPKLINEOUT", NULL, "SPKLO Amp"},
{"EAR Amp", "Switch", "ESL DAC"},
{"SPKLO Amp", "Switch", "ESL DAC"},
{"ESL DAC", "ESL-ASP Mono Volume", "ESL Mixer"},
{"ESL DAC", "ESL-XSP Mono Volume", "ESL Mixer"},
{"ESL DAC", "ESL-VSP Mono Volume", "VSPIN"},
/* Loopback */
{"ESL DAC", "ESL-IP Mono Volume", "Input Left Capture"},
{"ESL DAC", "ESL-IP Mono Volume", "Input Right Capture"},
{"ESL Mixer", NULL, "ESL-ASP Mux"},
{"ESL Mixer", NULL, "ESL-XSP Mux"},
{"ESL-ASP Mux", "Left", "ASPINL"},
{"ESL-ASP Mux", "Right", "ASPINR"},
{"ESL-ASP Mux", "Mono Mix", "ASPINM"},
{"ESL-XSP Mux", "Left", "XSPINL"},
{"ESL-XSP Mux", "Right", "XSPINR"},
{"ESL-XSP Mux", "Mono Mix", "XSPINM"},
/* Speakerphone Paths */
{"SPKOUT", NULL, "SPK Amp"},
{"SPK Amp", "Switch", "SPK DAC"},
{"SPK DAC", "SPK-ASP Mono Volume", "SPK Mixer"},
{"SPK DAC", "SPK-XSP Mono Volume", "SPK Mixer"},
{"SPK DAC", "SPK-VSP Mono Volume", "VSPIN"},
/* Loopback */
{"SPK DAC", "SPK-IP Mono Volume", "Input Left Capture"},
{"SPK DAC", "SPK-IP Mono Volume", "Input Right Capture"},
{"SPK Mixer", NULL, "SPK-ASP Mux"},
{"SPK Mixer", NULL, "SPK-XSP Mux"},
{"SPK-ASP Mux", "Left", "ASPINL"},
{"SPK-ASP Mux", "Mono Mix", "ASPINM"},
{"SPK-ASP Mux", "Right", "ASPINR"},
{"SPK-XSP Mux", "Left", "XSPINL"},
{"SPK-XSP Mux", "Mono Mix", "XSPINM"},
{"SPK-XSP Mux", "Right", "XSPINR"},
/* HP LineOUT Paths */
{"HPOUTA", NULL, "HP Amp"},
{"HPOUTB", NULL, "HP Amp"},
{"LINEOUTA", NULL, "LO Amp"},
{"LINEOUTB", NULL, "LO Amp"},
{"HP Amp", "Switch", "HL Left DAC"},
{"HP Amp", "Switch", "HL Right DAC"},
{"LO Amp", "Switch", "HL Left DAC"},
{"LO Amp", "Switch", "HL Right DAC"},
{"HL Left DAC", "HL-XSP Volume", "HL Left Mixer"},
{"HL Right DAC", "HL-XSP Volume", "HL Right Mixer"},
{"HL Left DAC", "HL-ASP Volume", "HL Left Mixer"},
{"HL Right DAC", "HL-ASP Volume", "HL Right Mixer"},
{"HL Left DAC", "HL-VSP Volume", "HL Left Mixer"},
{"HL Right DAC", "HL-VSP Volume", "HL Right Mixer"},
/* Loopback */
{"HL Left DAC", "HL-IP Volume", "HL Left Mixer"},
{"HL Right DAC", "HL-IP Volume", "HL Right Mixer"},
{"HL Left Mixer", NULL, "Input Left Capture"},
{"HL Right Mixer", NULL, "Input Right Capture"},
{"HL Left Mixer", NULL, "ASPINL"},
{"HL Right Mixer", NULL, "ASPINR"},
{"HL Left Mixer", NULL, "XSPINL"},
{"HL Right Mixer", NULL, "XSPINR"},
{"HL Left Mixer", NULL, "VSPIN"},
{"HL Right Mixer", NULL, "VSPIN"},
/* Capture Paths */
{"MIC1", NULL, "MIC1 Bias"},
{"PGA Left Mux", "Mic 1", "MIC1"},
{"MIC2", NULL, "MIC2 Bias"},
{"PGA Right Mux", "Mic 2", "MIC2"},
{"PGA Left Mux", "Line A", "LINEINA"},
{"PGA Right Mux", "Line B", "LINEINB"},
{"PGA Left", NULL, "PGA Left Mux"},
{"PGA Right", NULL, "PGA Right Mux"},
{"ADC Left", NULL, "PGA Left"},
{"ADC Right", NULL, "PGA Right"},
{"Input Left Capture", "ADC Left Input", "ADC Left"},
{"Input Right Capture", "ADC Right Input", "ADC Right"},
{"Input Left Capture", "DMIC Left Input", "DMIC Left"},
{"Input Right Capture", "DMIC Right Input", "DMIC Right"},
/* Audio Capture */
{"ASPL Output Mixer", NULL, "Input Left Capture"},
{"ASPR Output Mixer", NULL, "Input Right Capture"},
{"ASPOUTL", "ASP-IP Volume", "ASPL Output Mixer"},
{"ASPOUTR", "ASP-IP Volume", "ASPR Output Mixer"},
/* Auxillary Capture */
{"XSPL Output Mixer", NULL, "Input Left Capture"},
{"XSPR Output Mixer", NULL, "Input Right Capture"},
{"XSPOUTL", "XSP-IP Volume", "XSPL Output Mixer"},
{"XSPOUTR", "XSP-IP Volume", "XSPR Output Mixer"},
{"XSPOUTL", NULL, "XSPL Output Mixer"},
{"XSPOUTR", NULL, "XSPR Output Mixer"},
/* Voice Capture */
{"VSPL Output Mixer", NULL, "Input Left Capture"},
{"VSPR Output Mixer", NULL, "Input Left Capture"},
{"VSPOUTL", "VSP-IP Volume", "VSPL Output Mixer"},
{"VSPOUTR", "VSP-IP Volume", "VSPR Output Mixer"},
{"VSPOUTL", NULL, "VSPL Output Mixer"},
{"VSPOUTR", NULL, "VSPR Output Mixer"},
};
struct cs42l73_mclk_div {
u32 mclk;
u32 srate;
u8 mmcc;
};
static struct cs42l73_mclk_div cs42l73_mclk_coeffs[] = {
/* MCLK, Sample Rate, xMMCC[5:0] */
{5644800, 11025, 0x30},
{5644800, 22050, 0x20},
{5644800, 44100, 0x10},
{6000000, 8000, 0x39},
{6000000, 11025, 0x33},
{6000000, 12000, 0x31},
{6000000, 16000, 0x29},
{6000000, 22050, 0x23},
{6000000, 24000, 0x21},
{6000000, 32000, 0x19},
{6000000, 44100, 0x13},
{6000000, 48000, 0x11},
{6144000, 8000, 0x38},
{6144000, 12000, 0x30},
{6144000, 16000, 0x28},
{6144000, 24000, 0x20},
{6144000, 32000, 0x18},
{6144000, 48000, 0x10},
{6500000, 8000, 0x3C},
{6500000, 11025, 0x35},
{6500000, 12000, 0x34},
{6500000, 16000, 0x2C},
{6500000, 22050, 0x25},
{6500000, 24000, 0x24},
{6500000, 32000, 0x1C},
{6500000, 44100, 0x15},
{6500000, 48000, 0x14},
{6400000, 8000, 0x3E},
{6400000, 11025, 0x37},
{6400000, 12000, 0x36},
{6400000, 16000, 0x2E},
{6400000, 22050, 0x27},
{6400000, 24000, 0x26},
{6400000, 32000, 0x1E},
{6400000, 44100, 0x17},
{6400000, 48000, 0x16},
};
struct cs42l73_mclkx_div {
u32 mclkx;
u8 ratio;
u8 mclkdiv;
};
static struct cs42l73_mclkx_div cs42l73_mclkx_coeffs[] = {
{5644800, 1, 0}, /* 5644800 */
{6000000, 1, 0}, /* 6000000 */
{6144000, 1, 0}, /* 6144000 */
{11289600, 2, 2}, /* 5644800 */
{12288000, 2, 2}, /* 6144000 */
{12000000, 2, 2}, /* 6000000 */
{13000000, 2, 2}, /* 6500000 */
{19200000, 3, 3}, /* 6400000 */
{24000000, 4, 4}, /* 6000000 */
{26000000, 4, 4}, /* 6500000 */
{38400000, 6, 5} /* 6400000 */
};
static int cs42l73_get_mclkx_coeff(int mclkx)
{
int i;
for (i = 0; i < ARRAY_SIZE(cs42l73_mclkx_coeffs); i++) {
if (cs42l73_mclkx_coeffs[i].mclkx == mclkx)
return i;
}
return -EINVAL;
}
static int cs42l73_get_mclk_coeff(int mclk, int srate)
{
int i;
for (i = 0; i < ARRAY_SIZE(cs42l73_mclk_coeffs); i++) {
if (cs42l73_mclk_coeffs[i].mclk == mclk &&
cs42l73_mclk_coeffs[i].srate == srate)
return i;
}
return -EINVAL;
}
static int cs42l73_set_mclk(struct snd_soc_dai *dai, unsigned int freq)
{
struct snd_soc_codec *codec = dai->codec;
struct cs42l73_private *priv = snd_soc_codec_get_drvdata(codec);
int mclkx_coeff;
u32 mclk = 0;
u8 dmmcc = 0;
/* MCLKX -> MCLK */
mclkx_coeff = cs42l73_get_mclkx_coeff(freq);
if (mclkx_coeff < 0)
return mclkx_coeff;
mclk = cs42l73_mclkx_coeffs[mclkx_coeff].mclkx /
cs42l73_mclkx_coeffs[mclkx_coeff].ratio;
dev_dbg(codec->dev, "MCLK%u %u <-> internal MCLK %u\n",
priv->mclksel + 1, cs42l73_mclkx_coeffs[mclkx_coeff].mclkx,
mclk);
dmmcc = (priv->mclksel << 4) |
(cs42l73_mclkx_coeffs[mclkx_coeff].mclkdiv << 1);
snd_soc_write(codec, CS42L73_DMMCC, dmmcc);
priv->sysclk = mclkx_coeff;
priv->mclk = mclk;
return 0;
}
static int cs42l73_set_sysclk(struct snd_soc_dai *dai,
int clk_id, unsigned int freq, int dir)
{
struct snd_soc_codec *codec = dai->codec;
struct cs42l73_private *priv = snd_soc_codec_get_drvdata(codec);
switch (clk_id) {
case CS42L73_CLKID_MCLK1:
break;
case CS42L73_CLKID_MCLK2:
break;
default:
return -EINVAL;
}
if ((cs42l73_set_mclk(dai, freq)) < 0) {
dev_err(codec->dev, "Unable to set MCLK for dai %s\n",
dai->name);
return -EINVAL;
}
priv->mclksel = clk_id;
return 0;
}
static int cs42l73_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
struct cs42l73_private *priv = snd_soc_codec_get_drvdata(codec);
u8 id = codec_dai->id;
unsigned int inv, format;
u8 spc, mmcc;
spc = snd_soc_read(codec, CS42L73_SPC(id));
mmcc = snd_soc_read(codec, CS42L73_MMCC(id));
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
mmcc |= MS_MASTER;
break;
case SND_SOC_DAIFMT_CBS_CFS:
mmcc &= ~MS_MASTER;
break;
default:
return -EINVAL;
}
format = (fmt & SND_SOC_DAIFMT_FORMAT_MASK);
inv = (fmt & SND_SOC_DAIFMT_INV_MASK);
switch (format) {
case SND_SOC_DAIFMT_I2S:
spc &= ~SPDIF_PCM;
break;
case SND_SOC_DAIFMT_DSP_A:
case SND_SOC_DAIFMT_DSP_B:
if (mmcc & MS_MASTER) {
dev_err(codec->dev,
"PCM format in slave mode only\n");
return -EINVAL;
}
if (id == CS42L73_ASP) {
dev_err(codec->dev,
"PCM format is not supported on ASP port\n");
return -EINVAL;
}
spc |= SPDIF_PCM;
break;
default:
return -EINVAL;
}
if (spc & SPDIF_PCM) {
/* Clear PCM mode, clear PCM_BIT_ORDER bit for MSB->LSB */
spc &= ~(PCM_MODE_MASK | PCM_BIT_ORDER);
switch (format) {
case SND_SOC_DAIFMT_DSP_B:
if (inv == SND_SOC_DAIFMT_IB_IF)
spc |= PCM_MODE0;
if (inv == SND_SOC_DAIFMT_IB_NF)
spc |= PCM_MODE1;
break;
case SND_SOC_DAIFMT_DSP_A:
if (inv == SND_SOC_DAIFMT_IB_IF)
spc |= PCM_MODE1;
break;
default:
return -EINVAL;
}
}
priv->config[id].spc = spc;
priv->config[id].mmcc = mmcc;
return 0;
}
static u32 cs42l73_asrc_rates[] = {
8000, 11025, 12000, 16000, 22050,
24000, 32000, 44100, 48000
};
static unsigned int cs42l73_get_xspfs_coeff(u32 rate)
{
int i;
for (i = 0; i < ARRAY_SIZE(cs42l73_asrc_rates); i++) {
if (cs42l73_asrc_rates[i] == rate)
return i + 1;
}
return 0; /* 0 = Don't know */
}
static void cs42l73_update_asrc(struct snd_soc_codec *codec, int id, int srate)
{
u8 spfs = 0;
if (srate > 0)
spfs = cs42l73_get_xspfs_coeff(srate);
switch (id) {
case CS42L73_XSP:
snd_soc_update_bits(codec, CS42L73_VXSPFS, 0x0f, spfs);
break;
case CS42L73_ASP:
snd_soc_update_bits(codec, CS42L73_ASPC, 0x3c, spfs << 2);
break;
case CS42L73_VSP:
snd_soc_update_bits(codec, CS42L73_VXSPFS, 0xf0, spfs << 4);
break;
default:
break;
}
}
static int cs42l73_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
struct cs42l73_private *priv = snd_soc_codec_get_drvdata(codec);
int id = dai->id;
int mclk_coeff;
int srate = params_rate(params);
if (priv->config[id].mmcc & MS_MASTER) {
/* CS42L73 Master */
/* MCLK -> srate */
mclk_coeff =
cs42l73_get_mclk_coeff(priv->mclk, srate);
if (mclk_coeff < 0)
return -EINVAL;
dev_dbg(codec->dev,
"DAI[%d]: MCLK %u, srate %u, MMCC[5:0] = %x\n",
id, priv->mclk, srate,
cs42l73_mclk_coeffs[mclk_coeff].mmcc);
priv->config[id].mmcc &= 0xC0;
priv->config[id].mmcc |= cs42l73_mclk_coeffs[mclk_coeff].mmcc;
priv->config[id].spc &= 0xFC;
priv->config[id].spc |= MCK_SCLK_MCLK;
} else {
/* CS42L73 Slave */
priv->config[id].spc &= 0xFC;
priv->config[id].spc |= MCK_SCLK_64FS;
}
/* Update ASRCs */
priv->config[id].srate = srate;
snd_soc_write(codec, CS42L73_SPC(id), priv->config[id].spc);
snd_soc_write(codec, CS42L73_MMCC(id), priv->config[id].mmcc);
cs42l73_update_asrc(codec, id, srate);
return 0;
}
static int cs42l73_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
struct cs42l73_private *cs42l73 = snd_soc_codec_get_drvdata(codec);
switch (level) {
case SND_SOC_BIAS_ON:
snd_soc_update_bits(codec, CS42L73_DMMCC, MCLKDIS, 0);
snd_soc_update_bits(codec, CS42L73_PWRCTL1, PDN, 0);
break;
case SND_SOC_BIAS_PREPARE:
break;
case SND_SOC_BIAS_STANDBY:
if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) {
regcache_cache_only(cs42l73->regmap, false);
regcache_sync(cs42l73->regmap);
}
snd_soc_update_bits(codec, CS42L73_PWRCTL1, PDN, 1);
break;
case SND_SOC_BIAS_OFF:
snd_soc_update_bits(codec, CS42L73_PWRCTL1, PDN, 1);
snd_soc_update_bits(codec, CS42L73_DMMCC, MCLKDIS, 1);
break;
}
codec->dapm.bias_level = level;
return 0;
}
static int cs42l73_set_tristate(struct snd_soc_dai *dai, int tristate)
{
struct snd_soc_codec *codec = dai->codec;
int id = dai->id;
return snd_soc_update_bits(codec, CS42L73_SPC(id),
0x7F, tristate << 7);
}
static struct snd_pcm_hw_constraint_list constraints_12_24 = {
.count = ARRAY_SIZE(cs42l73_asrc_rates),
.list = cs42l73_asrc_rates,
};
static int cs42l73_pcm_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
snd_pcm_hw_constraint_list(substream->runtime, 0,
SNDRV_PCM_HW_PARAM_RATE,
&constraints_12_24);
return 0;
}
/* SNDRV_PCM_RATE_KNOT -> 12000, 24000 Hz, limit with constraint list */
#define CS42L73_RATES (SNDRV_PCM_RATE_8000_48000 | SNDRV_PCM_RATE_KNOT)
#define CS42L73_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\
SNDRV_PCM_FMTBIT_S24_LE)
static const struct snd_soc_dai_ops cs42l73_ops = {
.startup = cs42l73_pcm_startup,
.hw_params = cs42l73_pcm_hw_params,
.set_fmt = cs42l73_set_dai_fmt,
.set_sysclk = cs42l73_set_sysclk,
.set_tristate = cs42l73_set_tristate,
};
static struct snd_soc_dai_driver cs42l73_dai[] = {
{
.name = "cs42l73-xsp",
.id = CS42L73_XSP,
.playback = {
.stream_name = "XSP Playback",
.channels_min = 1,
.channels_max = 2,
.rates = CS42L73_RATES,
.formats = CS42L73_FORMATS,
},
.capture = {
.stream_name = "XSP Capture",
.channels_min = 1,
.channels_max = 2,
.rates = CS42L73_RATES,
.formats = CS42L73_FORMATS,
},
.ops = &cs42l73_ops,
.symmetric_rates = 1,
},
{
.name = "cs42l73-asp",
.id = CS42L73_ASP,
.playback = {
.stream_name = "ASP Playback",
.channels_min = 2,
.channels_max = 2,
.rates = CS42L73_RATES,
.formats = CS42L73_FORMATS,
},
.capture = {
.stream_name = "ASP Capture",
.channels_min = 2,
.channels_max = 2,
.rates = CS42L73_RATES,
.formats = CS42L73_FORMATS,
},
.ops = &cs42l73_ops,
.symmetric_rates = 1,
},
{
.name = "cs42l73-vsp",
.id = CS42L73_VSP,
.playback = {
.stream_name = "VSP Playback",
.channels_min = 1,
.channels_max = 2,
.rates = CS42L73_RATES,
.formats = CS42L73_FORMATS,
},
.capture = {
.stream_name = "VSP Capture",
.channels_min = 1,
.channels_max = 2,
.rates = CS42L73_RATES,
.formats = CS42L73_FORMATS,
},
.ops = &cs42l73_ops,
.symmetric_rates = 1,
}
};
static int cs42l73_suspend(struct snd_soc_codec *codec)
{
cs42l73_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int cs42l73_resume(struct snd_soc_codec *codec)
{
cs42l73_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static int cs42l73_probe(struct snd_soc_codec *codec)
{
int ret;
struct cs42l73_private *cs42l73 = snd_soc_codec_get_drvdata(codec);
codec->control_data = cs42l73->regmap;
ret = snd_soc_codec_set_cache_io(codec, 8, 8, SND_SOC_REGMAP);
if (ret < 0) {
dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret);
return ret;
}
regcache_cache_only(cs42l73->regmap, true);
cs42l73_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
cs42l73->mclksel = CS42L73_CLKID_MCLK1; /* MCLK1 as master clk */
cs42l73->mclk = 0;
return ret;
}
static int cs42l73_remove(struct snd_soc_codec *codec)
{
cs42l73_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_cs42l73 = {
.probe = cs42l73_probe,
.remove = cs42l73_remove,
.suspend = cs42l73_suspend,
.resume = cs42l73_resume,
.set_bias_level = cs42l73_set_bias_level,
.dapm_widgets = cs42l73_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(cs42l73_dapm_widgets),
.dapm_routes = cs42l73_audio_map,
.num_dapm_routes = ARRAY_SIZE(cs42l73_audio_map),
.controls = cs42l73_snd_controls,
.num_controls = ARRAY_SIZE(cs42l73_snd_controls),
};
static struct regmap_config cs42l73_regmap = {
.reg_bits = 8,
.val_bits = 8,
.max_register = CS42L73_MAX_REGISTER,
.reg_defaults = cs42l73_reg_defaults,
.num_reg_defaults = ARRAY_SIZE(cs42l73_reg_defaults),
.volatile_reg = cs42l73_volatile_register,
.readable_reg = cs42l73_readable_register,
.cache_type = REGCACHE_RBTREE,
};
static __devinit int cs42l73_i2c_probe(struct i2c_client *i2c_client,
const struct i2c_device_id *id)
{
struct cs42l73_private *cs42l73;
int ret;
unsigned int devid = 0;
unsigned int reg;
cs42l73 = devm_kzalloc(&i2c_client->dev, sizeof(struct cs42l73_private),
GFP_KERNEL);
if (!cs42l73) {
dev_err(&i2c_client->dev, "could not allocate codec\n");
return -ENOMEM;
}
i2c_set_clientdata(i2c_client, cs42l73);
cs42l73->regmap = regmap_init_i2c(i2c_client, &cs42l73_regmap);
if (IS_ERR(cs42l73->regmap)) {
ret = PTR_ERR(cs42l73->regmap);
dev_err(&i2c_client->dev, "regmap_init() failed: %d\n", ret);
goto err;
}
/* initialize codec */
ret = regmap_read(cs42l73->regmap, CS42L73_DEVID_AB, ®);
devid = (reg & 0xFF) << 12;
ret = regmap_read(cs42l73->regmap, CS42L73_DEVID_CD, ®);
devid |= (reg & 0xFF) << 4;
ret = regmap_read(cs42l73->regmap, CS42L73_DEVID_E, ®);
devid |= (reg & 0xF0) >> 4;
if (devid != CS42L73_DEVID) {
ret = -ENODEV;
dev_err(&i2c_client->dev,
"CS42L73 Device ID (%X). Expected %X\n",
devid, CS42L73_DEVID);
goto err_regmap;
}
ret = regmap_read(cs42l73->regmap, CS42L73_REVID, ®);
if (ret < 0) {
dev_err(&i2c_client->dev, "Get Revision ID failed\n");
goto err_regmap;
}
dev_info(&i2c_client->dev,
"Cirrus Logic CS42L73, Revision: %02X\n", reg & 0xFF);
regcache_cache_only(cs42l73->regmap, true);
ret = snd_soc_register_codec(&i2c_client->dev,
&soc_codec_dev_cs42l73, cs42l73_dai,
ARRAY_SIZE(cs42l73_dai));
if (ret < 0)
goto err_regmap;
return 0;
err_regmap:
regmap_exit(cs42l73->regmap);
err:
return ret;
}
static __devexit int cs42l73_i2c_remove(struct i2c_client *client)
{
struct cs42l73_private *cs42l73 = i2c_get_clientdata(client);
snd_soc_unregister_codec(&client->dev);
regmap_exit(cs42l73->regmap);
return 0;
}
static const struct i2c_device_id cs42l73_id[] = {
{"cs42l73", 0},
{}
};
MODULE_DEVICE_TABLE(i2c, cs42l73_id);
static struct i2c_driver cs42l73_i2c_driver = {
.driver = {
.name = "cs42l73",
.owner = THIS_MODULE,
},
.id_table = cs42l73_id,
.probe = cs42l73_i2c_probe,
.remove = __devexit_p(cs42l73_i2c_remove),
};
static int __init cs42l73_modinit(void)
{
int ret;
ret = i2c_add_driver(&cs42l73_i2c_driver);
if (ret != 0) {
pr_err("Failed to register CS42L73 I2C driver: %d\n", ret);
return ret;
}
return 0;
}
module_init(cs42l73_modinit);
static void __exit cs42l73_exit(void)
{
i2c_del_driver(&cs42l73_i2c_driver);
}
module_exit(cs42l73_exit);
MODULE_DESCRIPTION("ASoC CS42L73 driver");
MODULE_AUTHOR("Georgi Vlaev, Nucleus Systems Ltd, <[email protected]>");
MODULE_AUTHOR("Brian Austin, Cirrus Logic Inc, <[email protected]>");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
SyntaxError: Dimension node returned by a function is not valid here in {path}functions-7-dimension.less on line 2, column 1:
1 @plugin "../plugin/plugin-tree-nodes";
2 test-dimension();
| {
"pile_set_name": "Github"
} |
//
// DLUtility.h
// DLSlideViewDemo
//
// Created by Dongle Su on 15-2-12.
// Copyright (c) 2015年 dongle. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface DLUtility : NSObject
+ (UIColor *)getColorOfPercent:(CGFloat)percent between:(UIColor *)color1 and:(UIColor *)color2;
@end
| {
"pile_set_name": "Github"
} |
/*
Copyright 2018 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package metricsstore
import (
"io"
"sync"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/types"
)
// FamilyByteSlicer represents a metric family that can be converted to its string
// representation.
type FamilyByteSlicer interface {
ByteSlice() []byte
}
// MetricsStore implements the k8s.io/client-go/tools/cache.Store
// interface. Instead of storing entire Kubernetes objects, it stores metrics
// generated based on those objects.
type MetricsStore struct {
// Protects metrics
mutex sync.RWMutex
// metrics is a map indexed by Kubernetes object id, containing a slice of
// metric families, containing a slice of metrics. We need to keep metrics
// grouped by metric families in order to zip families with their help text in
// MetricsStore.WriteAll().
metrics map[types.UID][][]byte
// headers contains the header (TYPE and HELP) of each metric family. It is
// later on zipped with with their corresponding metric families in
// MetricStore.WriteAll().
headers []string
// generateMetricsFunc generates metrics based on a given Kubernetes object
// and returns them grouped by metric family.
generateMetricsFunc func(interface{}) []FamilyByteSlicer
}
// NewMetricsStore returns a new MetricsStore
func NewMetricsStore(headers []string, generateFunc func(interface{}) []FamilyByteSlicer) *MetricsStore {
return &MetricsStore{
generateMetricsFunc: generateFunc,
headers: headers,
metrics: map[types.UID][][]byte{},
}
}
// Implementing k8s.io/client-go/tools/cache.Store interface
// Add inserts adds to the MetricsStore by calling the metrics generator functions and
// adding the generated metrics to the metrics map that underlies the MetricStore.
func (s *MetricsStore) Add(obj interface{}) error {
o, err := meta.Accessor(obj)
if err != nil {
return err
}
s.mutex.Lock()
defer s.mutex.Unlock()
families := s.generateMetricsFunc(obj)
familyStrings := make([][]byte, len(families))
for i, f := range families {
familyStrings[i] = f.ByteSlice()
}
s.metrics[o.GetUID()] = familyStrings
return nil
}
// Update updates the existing entry in the MetricsStore.
func (s *MetricsStore) Update(obj interface{}) error {
// TODO: For now, just call Add, in the future one could check if the resource version changed?
return s.Add(obj)
}
// Delete deletes an existing entry in the MetricsStore.
func (s *MetricsStore) Delete(obj interface{}) error {
o, err := meta.Accessor(obj)
if err != nil {
return err
}
s.mutex.Lock()
defer s.mutex.Unlock()
delete(s.metrics, o.GetUID())
return nil
}
// List implements the List method of the store interface.
func (s *MetricsStore) List() []interface{} {
return nil
}
// ListKeys implements the ListKeys method of the store interface.
func (s *MetricsStore) ListKeys() []string {
return nil
}
// Get implements the Get method of the store interface.
func (s *MetricsStore) Get(obj interface{}) (item interface{}, exists bool, err error) {
return nil, false, nil
}
// GetByKey implements the GetByKey method of the store interface.
func (s *MetricsStore) GetByKey(key string) (item interface{}, exists bool, err error) {
return nil, false, nil
}
// Replace will delete the contents of the store, using instead the
// given list.
func (s *MetricsStore) Replace(list []interface{}, _ string) error {
s.mutex.Lock()
s.metrics = map[types.UID][][]byte{}
s.mutex.Unlock()
for _, o := range list {
err := s.Add(o)
if err != nil {
return err
}
}
return nil
}
// Resync implements the Resync method of the store interface.
func (s *MetricsStore) Resync() error {
return nil
}
// WriteAll writes all metrics of the store into the given writer, zipped with the
// help text of each metric family.
func (s *MetricsStore) WriteAll(w io.Writer) {
s.mutex.RLock()
defer s.mutex.RUnlock()
for i, help := range s.headers {
w.Write([]byte(help))
w.Write([]byte{'\n'})
for _, metricFamilies := range s.metrics {
w.Write([]byte(metricFamilies[i]))
}
}
}
| {
"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.
*/
package v1beta1
import (
"fmt"
"k8s.io/api/core/v1"
extensions "k8s.io/api/extensions/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
)
// ReplicaSetListerExpansion allows custom methods to be added to
// ReplicaSetLister.
type ReplicaSetListerExpansion interface {
GetPodReplicaSets(pod *v1.Pod) ([]*extensions.ReplicaSet, error)
}
// ReplicaSetNamespaceListerExpansion allows custom methods to be added to
// ReplicaSetNamespaceLister.
type ReplicaSetNamespaceListerExpansion interface{}
// GetPodReplicaSets returns a list of ReplicaSets that potentially match a pod.
// Only the one specified in the Pod's ControllerRef will actually manage it.
// Returns an error only if no matching ReplicaSets are found.
func (s *replicaSetLister) GetPodReplicaSets(pod *v1.Pod) ([]*extensions.ReplicaSet, error) {
if len(pod.Labels) == 0 {
return nil, fmt.Errorf("no ReplicaSets found for pod %v because it has no labels", pod.Name)
}
list, err := s.ReplicaSets(pod.Namespace).List(labels.Everything())
if err != nil {
return nil, err
}
var rss []*extensions.ReplicaSet
for _, rs := range list {
if rs.Namespace != pod.Namespace {
continue
}
selector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)
if err != nil {
return nil, fmt.Errorf("invalid selector: %v", err)
}
// If a ReplicaSet with a nil or empty selector creeps in, it should match nothing, not everything.
if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {
continue
}
rss = append(rss, rs)
}
if len(rss) == 0 {
return nil, fmt.Errorf("could not find ReplicaSet for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
}
return rss, nil
}
| {
"pile_set_name": "Github"
} |
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <errno.h>
#include "headers/includes.h"
#include "headers/server.h"
#include "headers/telnet_info.h"
#include "headers/binary.h"
#include "headers/util.h"
static void *stats_thread(void *);
static struct server *srv;
char *id_tag = "telnet";
int main(int argc, char **args)
{
pthread_t stats_thrd;
uint8_t addrs_len;
ipv4_t *addrs;
uint32_t total = 0;
struct telnet_info info;
#ifdef DEBUG
addrs_len = 1;
addrs = calloc(4, sizeof (ipv4_t));
addrs[0] = inet_addr("0.0.0.0");
#else
addrs_len = 2;
addrs = calloc(addrs_len, sizeof (ipv4_t));
addrs[0] = inet_addr("192.168.0.1"); // Address to bind to
addrs[1] = inet_addr("192.168.1.1"); // Address to bind to
#endif
if (argc == 2)
{
id_tag = args[1];
}
if (!binary_init())
{
printf("Failed to load bins/dlr.* as dropper\n");
return 1;
}
/* wget address tftp address */
if ((srv = server_create(sysconf(_SC_NPROCESSORS_ONLN), addrs_len, addrs, 1024 * 64, "100.200.100.100", 80, "100.200.100.100")) == NULL)
{
printf("Failed to initialize server. Aborting\n");
return 1;
}
pthread_create(&stats_thrd, NULL, stats_thread, NULL);
// Read from stdin
while (TRUE)
{
char strbuf[1024];
if (fgets(strbuf, sizeof (strbuf), stdin) == NULL)
break;
util_trim(strbuf);
if (strlen(strbuf) == 0)
{
usleep(10000);
continue;
}
memset(&info, 0, sizeof(struct telnet_info));
if (telnet_info_parse(strbuf, &info) == NULL)
printf("Failed to parse telnet info: \"%s\" Format -> ip:port user:pass arch\n", strbuf);
else
{
if (srv == NULL)
printf("srv == NULL 2\n");
server_queue_telnet(srv, &info);
if (total++ % 1000 == 0)
sleep(1);
}
ATOMIC_INC(&srv->total_input);
}
printf("Hit end of input.\n");
while(ATOMIC_GET(&srv->curr_open) > 0)
sleep(1);
return 0;
}
static void *stats_thread(void *arg)
{
uint32_t seconds = 0;
while (TRUE)
{
#ifndef DEBUG
printf("%ds\tProcessed: %d\tConns: %d\tLogins: %d\tRan: %d\tEchoes:%d Wgets: %d, TFTPs: %d\n",
seconds++, ATOMIC_GET(&srv->total_input), ATOMIC_GET(&srv->curr_open), ATOMIC_GET(&srv->total_logins), ATOMIC_GET(&srv->total_successes),
ATOMIC_GET(&srv->total_echoes), ATOMIC_GET(&srv->total_wgets), ATOMIC_GET(&srv->total_tftps));
#endif
fflush(stdout);
sleep(1);
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:include schemaLocation="AbstractShape.xsd" />
<!-- com.alee.painter.decoration.shape.EllipseShape -->
<xs:complexType name="EllipseShape">
<xs:complexContent>
<xs:extension base="AbstractShape" />
</xs:complexContent>
</xs:complexType>
</xs:schema> | {
"pile_set_name": "Github"
} |
// Mixins
// --------------------------
@mixin fa-icon() {
display: inline-block;
font: normal normal normal #{$fa-font-size-base}/1 FontAwesome; // shortening font declaration
font-size: inherit; // can't have font-size inherit on line above, so need to override
text-rendering: auto; // optimizelegibility throws things off #1094
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
transform: translate(0, 0); // ensures no half-pixel rendering in firefox
}
@mixin fa-icon-rotate($degrees, $rotation) {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=#{$rotation});
-webkit-transform: rotate($degrees);
-ms-transform: rotate($degrees);
transform: rotate($degrees);
}
@mixin fa-icon-flip($horiz, $vert, $rotation) {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=#{$rotation});
-webkit-transform: scale($horiz, $vert);
-ms-transform: scale($horiz, $vert);
transform: scale($horiz, $vert);
}
| {
"pile_set_name": "Github"
} |
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.bean.proxy;
import java.io.ObjectStreamException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;
import jakarta.enterprise.inject.spi.Bean;
import org.jboss.classfilewriter.AccessFlag;
import org.jboss.classfilewriter.ClassFile;
import org.jboss.classfilewriter.ClassMethod;
import org.jboss.classfilewriter.code.BranchEnd;
import org.jboss.classfilewriter.code.CodeAttribute;
import org.jboss.weld.Container;
import org.jboss.weld.bean.proxy.util.SerializableClientProxy;
import org.jboss.weld.exceptions.WeldException;
import org.jboss.weld.proxy.WeldClientProxy;
import org.jboss.weld.serialization.spi.BeanIdentifier;
import org.jboss.weld.serialization.spi.ContextualStore;
import org.jboss.weld.util.bytecode.BytecodeUtils;
import org.jboss.weld.util.bytecode.DeferredBytecode;
import org.jboss.weld.util.bytecode.MethodInformation;
/**
* Proxy factory that generates client proxies, it uses optimizations that
* are not valid for other proxy types.
*
* @author Stuart Douglas
* @author Marius Bogoevici
*/
public class ClientProxyFactory<T> extends ProxyFactory<T> {
private static final String CLIENT_PROXY_SUFFIX = "ClientProxy";
private static final String HASH_CODE_METHOD = "hashCode";
private static final String EMPTY_PARENTHESES = "()";
/**
* It is possible although very unlikely that two different beans will end up with the same proxy class
* (generally this will only happen in test situations where weld is being started/stopped multiple times
* in the same class loader, such as during unit tests)
* <p/>
* To avoid this causing serialization problems we explicitly set the bean id on creation, and store it in this
* field.
*/
private static final String BEAN_ID_FIELD = "BEAN_ID_FIELD";
private static final String CONTEXT_ID_FIELD = "CONTEXT_ID_FIELD";
private final BeanIdentifier beanId;
private volatile Field beanIdField;
private volatile Field contextIdField;
public ClientProxyFactory(String contextId, Class<?> proxiedBeanType, Set<? extends Type> typeClosure, Bean<?> bean) {
super(contextId, proxiedBeanType, typeClosure, bean);
beanId = Container.instance(contextId).services().get(ContextualStore.class).putIfAbsent(bean);
}
@Override
public T create(BeanInstance beanInstance) {
try {
final T instance = super.create(beanInstance);
if (beanIdField == null) {
final Field f = SecurityActions.getDeclaredField(instance.getClass(), BEAN_ID_FIELD);
SecurityActions.ensureAccessible(f);
beanIdField = f;
}
if (contextIdField == null) {
final Field f = SecurityActions.getDeclaredField(instance.getClass(), CONTEXT_ID_FIELD);
SecurityActions.ensureAccessible(f);
contextIdField = f;
}
beanIdField.set(instance, beanId);
contextIdField.set(instance, getContextId());
return instance;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e.getCause());
}
}
@Override
protected void addAdditionalInterfaces(Set<Class<?>> interfaces) {
// add marker interface for client proxy, this also requires adding interface methods implementations
interfaces.add(WeldClientProxy.class);
}
@Override
protected void addMethods(ClassFile proxyClassType, ClassMethod staticConstructor) {
// delegate to ProxyFactory#addMethods
super.addMethods(proxyClassType, staticConstructor);
// add method from WeldClientProxy
generateWeldClientProxyMethod(proxyClassType);
}
private void generateWeldClientProxyMethod(ClassFile proxyClassType) {
try {
Method getContextualMetadata = WeldClientProxy.class.getMethod("getMetadata");
generateBodyForWeldClientProxyMethod(proxyClassType.addMethod(getContextualMetadata));
} catch (Exception e) {
throw new WeldException(e);
}
}
private void generateBodyForWeldClientProxyMethod(ClassMethod method) throws Exception {
// ProxyMethodHandler implements ContextualMetadata, so let's just return reference to it
final CodeAttribute b = method.getCodeAttribute();
b.aload(0);
getMethodHandlerField(method.getClassFile(), b);
b.returnInstruction();
}
@Override
protected void addFields(final ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) {
super.addFields(proxyClassType, initialValueBytecode);
proxyClassType.addField(AccessFlag.VOLATILE | AccessFlag.PRIVATE, BEAN_ID_FIELD, BeanIdentifier.class);
proxyClassType.addField(AccessFlag.VOLATILE | AccessFlag.PRIVATE, CONTEXT_ID_FIELD, String.class);
}
@Override
protected Class<? extends MethodHandler> getMethodHandlerType() {
return ProxyMethodHandler.class;
}
@Override
protected void addSerializationSupport(ClassFile proxyClassType) {
final Class<Exception>[] exceptions = new Class[]{ObjectStreamException.class};
final ClassMethod writeReplace = proxyClassType.addMethod(AccessFlag.PRIVATE, "writeReplace", LJAVA_LANG_OBJECT);
writeReplace.addCheckedExceptions(exceptions);
CodeAttribute b = writeReplace.getCodeAttribute();
b.newInstruction(SerializableClientProxy.class.getName());
b.dup();
b.aload(0);
b.getfield(proxyClassType.getName(), BEAN_ID_FIELD, BeanIdentifier.class);
b.aload(0);
b.getfield(proxyClassType.getName(), CONTEXT_ID_FIELD, String.class);
b.invokespecial(SerializableClientProxy.class.getName(), INIT_METHOD_NAME, "(" + LBEAN_IDENTIFIER + LJAVA_LANG_STRING + ")" + BytecodeUtils.VOID_CLASS_DESCRIPTOR);
b.returnInstruction();
}
/**
* Calls methodHandler.invoke with a null method parameter in order to
* get the underlying instance. The invocation is then forwarded to
* this instance with generated bytecode.
*/
@Override
protected void createForwardingMethodBody(ClassMethod classMethod, final MethodInformation methodInfo, ClassMethod staticConstructor) {
final Method method = methodInfo.getMethod();
// we can only use bytecode based invocation for some methods
// at the moment we restrict it solely to public methods with public
// return and parameter types
boolean bytecodeInvocationAllowed = Modifier.isPublic(method.getModifiers()) && Modifier.isPublic(method.getReturnType().getModifiers());
for (Class<?> paramType : method.getParameterTypes()) {
if (!Modifier.isPublic(paramType.getModifiers())) {
bytecodeInvocationAllowed = false;
break;
}
}
if (!bytecodeInvocationAllowed) {
createInterceptorBody(classMethod, methodInfo, staticConstructor);
return;
}
// create a new interceptor invocation context whenever we invoke a method on a client proxy
// we use a try-catch block in order to make sure that endInterceptorContext() is invoked regardless whether
// the method has succeeded or not
new RunWithinInterceptionDecorationContextGenerator(classMethod, this) {
@Override
void doWork(CodeAttribute b, ClassMethod classMethod) {
loadBeanInstance(classMethod.getClassFile(), methodInfo, b);
//now we should have the target bean instance on top of the stack
// we need to dup it so we still have it to compare to the return value
b.dup();
//lets create the method invocation
String methodDescriptor = methodInfo.getDescriptor();
b.loadMethodParameters();
if (method.getDeclaringClass().isInterface()) {
b.invokeinterface(methodInfo.getDeclaringClass(), methodInfo.getName(), methodDescriptor);
} else {
b.invokevirtual(methodInfo.getDeclaringClass(), methodInfo.getName(), methodDescriptor);
}
}
@Override
void doReturn(CodeAttribute b, ClassMethod classMethod) {
// assumes doWork() result is on top of the stack
// if this method returns a primitive we just return
if (method.getReturnType().isPrimitive()) {
b.returnInstruction();
} else {
// otherwise we have to check that the proxy is not returning 'this;
// now we need to check if the proxy has return 'this' and if so return
// an
// instance of the proxy.
// currently we have result, beanInstance on the stack.
b.dupX1();
// now we have result, beanInstance, result
// we need to compare result and beanInstance
// first we need to build up the inner conditional that just returns
// the
// result
final BranchEnd returnInstruction = b.ifAcmpeq();
b.returnInstruction();
b.branchEnd(returnInstruction);
// now add the case where the proxy returns 'this';
b.aload(0);
b.checkcast(methodInfo.getMethod().getReturnType().getName());
b.returnInstruction();
}
}
}.runStartIfNotEmpty();
}
private void loadBeanInstance(ClassFile file, MethodInformation methodInfo, CodeAttribute b) {
b.aload(0);
getMethodHandlerField(file, b);
// lets invoke the method
b.invokevirtual(ProxyMethodHandler.class.getName(), "getInstance", EMPTY_PARENTHESES + LJAVA_LANG_OBJECT);
b.checkcast(methodInfo.getDeclaringClass());
}
/**
* Client proxies use the following hashCode:
* <code>MyProxyName.class.hashCode()</code>
*/
@Override
protected void generateHashCodeMethod(ClassFile proxyClassType) {
final ClassMethod method = proxyClassType.addMethod(AccessFlag.PUBLIC, HASH_CODE_METHOD, BytecodeUtils.INT_CLASS_DESCRIPTOR);
final CodeAttribute b = method.getCodeAttribute();
// MyProxyName.class.hashCode()
b.loadClass(proxyClassType.getName());
// now we have the class object on top of the stack
b.invokevirtual("java.lang.Object", HASH_CODE_METHOD, EMPTY_PARENTHESES + BytecodeUtils.INT_CLASS_DESCRIPTOR);
// now we have the hashCode
b.returnInstruction();
}
/**
* Client proxies are equal to other client proxies for the same bean.
* <p/>
* The corresponding java code: <code>
* return other instanceof MyProxyClassType.class
* </code>
*/
@Override
protected void generateEqualsMethod(ClassFile proxyClassType) {
ClassMethod method = proxyClassType.addMethod(AccessFlag.PUBLIC, "equals", BytecodeUtils.BOOLEAN_CLASS_DESCRIPTOR, LJAVA_LANG_OBJECT);
CodeAttribute b = method.getCodeAttribute();
b.aload(1);
b.instanceofInstruction(proxyClassType.getName());
b.returnInstruction();
}
@Override
protected String getProxyNameSuffix() {
return CLIENT_PROXY_SUFFIX;
}
@Override
protected boolean isMethodAccepted(Method method, Class<?> proxySuperclass) {
return super.isMethodAccepted(method, proxySuperclass) && CommonProxiedMethodFilters.NON_PRIVATE.accept(method, proxySuperclass);
}
}
| {
"pile_set_name": "Github"
} |
# Copyright 2016 Google 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.
import astroid
from astroid import MANAGER
def __init__(self):
pass
CONF_NODE = None # AST node representing the conf module.
CONF_LOCALS = {}
CURRENT_ROOT = None
def transform_declare(node):
"""Transform conf.declare calls by stashing the declared names."""
global CURRENT_ROOT
if not (isinstance(node.func, astroid.Attribute)
and isinstance(node.func.expr, astroid.Name)
and node.func.expr.name == 'conf'
and node.func.attrname == 'declare'):
return
conf_key_name = None
if node.args:
conf_key_name = node.args[0].value
else:
for keyword in node.keywords:
if keyword.arg == 'name':
# Assume the name is an astroid.Const(str), so it has a str value.
conf_key_name = keyword.value.value
break
assert conf_key_name != None, "Invalid conf.declare() syntax"
if CONF_NODE:
# Keep track of the current root, refreshing the locals if it changes.
if not CURRENT_ROOT or CURRENT_ROOT != node.root():
CURRENT_ROOT = node.root()
CONF_NODE.locals = CONF_LOCALS
CONF_NODE.locals[conf_key_name] = [None]
else:
CONF_LOCALS[conf_key_name] = [None]
def transform_conf_module(cls):
"""Transform usages of the conf module by updating locals."""
global CONF_NODE
if cls.name == 'openhtf.conf':
# Put all the attributes in Configuration into the openhtf.conf node.
cls._locals.update(cls.locals['Configuration'][0].locals)
# Store reference to this node for future use.
CONF_NODE = cls
CONF_LOCALS.update(cls.locals)
def register(linter):
"""Register all transforms with the linter."""
MANAGER.register_transform(astroid.Call, transform_declare)
MANAGER.register_transform(astroid.Module, transform_conf_module)
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.ecm.v20190719.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class ModifyModuleNameResponse extends AbstractModel{
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
@SerializedName("RequestId")
@Expose
private String RequestId;
/**
* Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public String getRequestId() {
return this.RequestId;
}
/**
* Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public void setRequestId(String RequestId) {
this.RequestId = RequestId;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
| {
"pile_set_name": "Github"
} |
using System;
using Xamarin.Forms;
namespace Plugin.Iconize
{
/// <summary>
/// Defines the <see cref="IconNavigationPage" /> page.
/// </summary>
/// <seealso cref="Xamarin.Forms.NavigationPage" />
public class IconNavigationPage : NavigationPage
{
/// <summary>
/// Initializes a new instance of the <see cref="IconNavigationPage" /> class.
/// </summary>
public IconNavigationPage()
{
InitListeners();
}
/// <summary>
/// Initializes a new instance of the <see cref="IconNavigationPage" /> class.
/// </summary>
/// <param name="root">The root page.</param>
public IconNavigationPage(Page root)
: base(root)
{
InitListeners();
}
/// <summary>
/// Initializes the event listeners.
/// </summary>
private void InitListeners()
{
Popped += OnNavigation;
PoppedToRoot += OnNavigation;
Pushed += OnNavigation;
}
/// <summary>
/// Called when [navigation].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="NavigationEventArgs"/> instance containing the event data.</param>
/// <exception cref="System.NotImplementedException"></exception>
private void OnNavigation(Object sender, NavigationEventArgs e)
{
MessagingCenter.Send(sender, IconToolbarItem.UpdateToolbarItemsMessage);
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- $Id$ -->
<testcase>
<info>
<p>
This test checks that the definition of a special page-master for the last page with a
different width that the previous "rest" page causes FOP to redo the line breaking layout.
</p>
</info>
<fo>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
<fo:layout-master-set>
<fo:simple-page-master master-name="Page-Portrait" page-width="8.5in" page-height="11in" margin-bottom="0in" margin-right="0in" margin-top="0in" margin-left="0in">
<fo:region-body margin-bottom="0.5in" margin-right="0.5in" margin-top="0.5in" margin-left="0.5in" region-name="letterPageBody"/>
</fo:simple-page-master>
<fo:simple-page-master master-name="Page_Landscape" page-width="11in" page-height="8.5in" margin-bottom="0in" margin-right="0in" margin-top="0in" margin-left="0in">
<fo:region-body margin-bottom="0.5in" margin-right="0.5in" margin-top="0.5in" margin-left="0.5in" region-name="letterPageBody"/>
</fo:simple-page-master>
<fo:page-sequence-master master-name="LetterPages">
<fo:repeatable-page-master-alternatives>
<fo:conditional-page-master-reference page-position="first" master-reference="Page-Portrait"/>
<fo:conditional-page-master-reference master-reference="Page_Landscape" page-position="rest"/>
<fo:conditional-page-master-reference master-reference="Page-Portrait" page-position="last"/>
</fo:repeatable-page-master-alternatives>
</fo:page-sequence-master>
</fo:layout-master-set>
<fo:page-sequence master-reference="LetterPages">
<fo:flow flow-name="letterPageBody">
<fo:block>This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. </fo:block>
<fo:block break-before="page"/>
<fo:block>This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. This is just some generic text to use for testing. </fo:block>
<fo:block break-after="page"/>
<fo:table>
<fo:table-body>
<fo:table-row>
<fo:table-cell>
<fo:block></fo:block>
</fo:table-cell>
</fo:table-row>
<fo:table-row>
<fo:table-cell>
<fo:block>A table with first row empty after change in IPD and forced break after page...</fo:block>
</fo:table-cell>
</fo:table-row>
</fo:table-body>
</fo:table>
</fo:flow>
</fo:page-sequence>
</fo:root>
</fo>
<checks>
<eval expected="A table with first row empty after change in IPD and forced break after page..." xpath="//pageViewport[3]//lineArea"/>
</checks>
</testcase>
| {
"pile_set_name": "Github"
} |
# ******************************************************************************
# Copyright 2018-2020 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ******************************************************************************
import numpy as np
import onnx
import pytest
from tests.test_onnx.utils import run_node
from tests import xfail_issue_35925
reduce_data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)
reduce_axis_parameters = [
None,
(0,),
(1,),
(2,),
(0, 1),
(0, 2),
(1, 2),
(0, 1, 2)
]
reduce_operation_parameters = [
("ReduceMax", np.max),
("ReduceMin", np.min),
("ReduceMean", np.mean),
("ReduceSum", np.sum),
("ReduceProd", np.prod)
]
def import_and_compute(op_type, input_data, **node_attrs):
data_inputs = [np.array(input_data)]
node = onnx.helper.make_node(op_type, inputs=["x"], outputs=["y"], **node_attrs)
return run_node(node, data_inputs).pop()
@pytest.mark.parametrize("operation, ref_operation", reduce_operation_parameters)
@pytest.mark.parametrize("axes", reduce_axis_parameters)
def test_reduce_operation_keepdims(operation, ref_operation, axes):
if axes:
assert np.array_equal(import_and_compute(operation, reduce_data, axes=axes, keepdims=True),
ref_operation(reduce_data, keepdims=True, axis=axes))
else:
assert np.array_equal(import_and_compute(operation, reduce_data, keepdims=True),
ref_operation(reduce_data, keepdims=True))
@pytest.mark.parametrize("axes", [
pytest.param(None, marks=xfail_issue_35925),
(0,),
(1,),
(2,),
(0, 1),
(0, 2),
(1, 2),
pytest.param((0, 1, 2), marks=xfail_issue_35925)])
@pytest.mark.parametrize("operation, ref_operation", reduce_operation_parameters)
def test_reduce_operation_no_keepdims(operation, ref_operation, axes):
if axes:
assert np.array_equal(import_and_compute(operation, reduce_data, axes=axes, keepdims=False),
ref_operation(reduce_data, keepdims=False, axis=axes))
else:
assert np.array_equal(import_and_compute(operation, reduce_data, keepdims=False),
ref_operation(reduce_data, keepdims=False))
@pytest.mark.parametrize("reduction_axes", [(0,), (0, 2), (0, 1, 2)])
def test_reduce_l1(reduction_axes):
shape = [2, 4, 3, 2]
np.random.seed(133391)
input_data = np.random.uniform(-100, 100, shape).astype(np.float32)
expected = np.sum(np.abs(input_data), keepdims=True, axis=reduction_axes)
node = onnx.helper.make_node("ReduceL1", inputs=["x"], outputs=["y"], axes=reduction_axes)
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
expected = np.sum(np.abs(input_data), keepdims=False, axis=reduction_axes)
node = onnx.helper.make_node("ReduceL1", inputs=["x"], outputs=["y"], keepdims=0, axes=reduction_axes)
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
def test_reduce_l1_default_axes():
shape = [2, 4, 3, 2]
np.random.seed(133391)
input_data = np.random.uniform(-100, 100, shape).astype(np.float32)
expected = np.sum(np.abs(input_data), keepdims=True)
node = onnx.helper.make_node("ReduceL1", inputs=["x"], outputs=["y"])
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
expected = np.array([np.sum(np.abs(input_data), keepdims=False)])
node = onnx.helper.make_node("ReduceL1", inputs=["x"], outputs=["y"], keepdims=0)
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
@pytest.mark.parametrize("reduction_axes", [(0,), (0, 2), (0, 1, 2)])
def test_reduce_l2(reduction_axes):
shape = [2, 4, 3, 2]
np.random.seed(133391)
input_data = np.random.uniform(-100, 100, shape).astype(np.float32)
expected = np.sqrt(np.sum(np.square(input_data), keepdims=True, axis=reduction_axes))
node = onnx.helper.make_node("ReduceL2", inputs=["x"], outputs=["y"], axes=reduction_axes)
raw_result = run_node(node, [input_data])
ng_result = np.array(raw_result.pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
expected = np.sqrt(np.sum(np.square(input_data), keepdims=False, axis=reduction_axes))
node = onnx.helper.make_node("ReduceL2", inputs=["x"], outputs=["y"], keepdims=0, axes=reduction_axes)
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
def test_reduce_l2_default_axes():
shape = [2, 4, 3, 2]
np.random.seed(133391)
input_data = np.random.uniform(-100, 100, shape).astype(np.float32)
expected = np.sqrt(np.sum(np.square(input_data), keepdims=True))
node = onnx.helper.make_node("ReduceL2", inputs=["x"], outputs=["y"])
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
expected = np.array([np.sqrt(np.sum(np.square(input_data), keepdims=False))])
node = onnx.helper.make_node("ReduceL2", inputs=["x"], outputs=["y"], keepdims=0)
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
@pytest.mark.parametrize("reduction_axes", [(0,), (0, 2), (0, 1, 2)])
def test_reduce_log_sum(reduction_axes):
shape = [2, 4, 3, 2]
np.random.seed(133391)
input_data = np.random.uniform(0, 1, shape).astype(np.float32)
expected = np.log(np.sum(input_data, keepdims=True, axis=reduction_axes))
node = onnx.helper.make_node("ReduceLogSum", inputs=["x"], outputs=["y"], axes=reduction_axes)
ng_result = run_node(node, [input_data]).pop()
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
expected = np.log(np.sum(input_data, keepdims=False, axis=reduction_axes))
node = onnx.helper.make_node("ReduceLogSum", inputs=["x"], outputs=["y"], keepdims=0, axes=reduction_axes)
ng_result = run_node(node, [input_data]).pop()
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
@xfail_issue_35925
def test_reduce_log_sum_default_axes():
shape = [2, 4, 3, 2]
np.random.seed(133391)
input_data = np.random.uniform(0, 1, shape).astype(np.float32)
expected = np.log(np.sum(input_data, keepdims=True))
node = onnx.helper.make_node("ReduceLogSum", inputs=["x"], outputs=["y"])
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
expected = np.log(np.sum(input_data, keepdims=False))
node = onnx.helper.make_node("ReduceLogSum", inputs=["x"], outputs=["y"], keepdims=0)
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
@xfail_issue_35925
def test_reduce_log_sum_exp():
def logsumexp(data, axis=None, keepdims=True):
return np.log(np.sum(np.exp(data), axis=axis, keepdims=keepdims))
data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)
assert np.array_equal(import_and_compute("ReduceLogSumExp", data), logsumexp(data, keepdims=True))
assert np.array_equal(
import_and_compute("ReduceLogSumExp", data, keepdims=0), logsumexp(data, keepdims=False)
)
assert np.array_equal(
import_and_compute("ReduceLogSumExp", data, axes=(1,)), logsumexp(data, keepdims=True, axis=(1,))
)
assert np.array_equal(
import_and_compute("ReduceLogSumExp", data, axes=(1,), keepdims=0),
logsumexp(data, keepdims=False, axis=(1,)),
)
assert np.array_equal(
import_and_compute("ReduceLogSumExp", data, axes=(0, 2)), logsumexp(data, keepdims=True, axis=(0, 2))
)
assert np.array_equal(
import_and_compute("ReduceLogSumExp", data, axes=(0, 2), keepdims=0),
logsumexp(data, keepdims=False, axis=(0, 2)),
)
assert np.array_equal(
import_and_compute("ReduceLogSumExp", data, axes=(0, 1, 2)),
logsumexp(data, keepdims=True, axis=(0, 1, 2)),
)
assert np.array_equal(
import_and_compute("ReduceLogSumExp", data, axes=(0, 1, 2), keepdims=0),
logsumexp(data, keepdims=False, axis=(0, 1, 2)),
)
@pytest.mark.parametrize("reduction_axes", [(0,), (0, 2), (0, 1, 2)])
def test_reduce_sum_square(reduction_axes):
shape = [2, 4, 3, 2]
np.random.seed(133391)
input_data = np.random.uniform(-100, 100, shape).astype(np.float32)
expected = np.sum(np.square(input_data), keepdims=True, axis=reduction_axes)
node = onnx.helper.make_node("ReduceSumSquare", inputs=["x"], outputs=["y"], axes=reduction_axes)
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
expected = np.sum(np.square(input_data), keepdims=False, axis=reduction_axes)
node = onnx.helper.make_node(
"ReduceSumSquare", inputs=["x"], outputs=["y"], keepdims=0, axes=reduction_axes
)
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
@xfail_issue_35925
def test_reduce_sum_square_default_axes():
shape = [2, 4, 3, 2]
np.random.seed(133391)
input_data = np.random.uniform(-100, 100, shape).astype(np.float32)
expected = np.sum(np.square(input_data), keepdims=True)
node = onnx.helper.make_node("ReduceSumSquare", inputs=["x"], outputs=["y"])
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
expected = np.sum(np.square(input_data), keepdims=False)
node = onnx.helper.make_node("ReduceSumSquare", inputs=["x"], outputs=["y"], keepdims=0)
ng_result = np.array(run_node(node, [input_data]).pop())
assert np.array_equal(expected.shape, ng_result.shape)
assert np.allclose(expected, ng_result)
def test_reduce_argmin():
def argmin(ndarray, axis, keepdims=False):
res = np.argmin(ndarray, axis=axis)
if keepdims:
res = np.expand_dims(res, axis=axis)
return res
data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)
assert np.array_equal(import_and_compute("ArgMin", data, axis=0), argmin(data, keepdims=True, axis=0))
assert np.array_equal(
import_and_compute("ArgMin", data, axis=0, keepdims=0), argmin(data, keepdims=False, axis=0)
)
assert np.array_equal(import_and_compute("ArgMin", data, axis=1), argmin(data, keepdims=True, axis=1))
assert np.array_equal(
import_and_compute("ArgMin", data, axis=1, keepdims=0), argmin(data, keepdims=False, axis=1)
)
assert np.array_equal(import_and_compute("ArgMin", data, axis=2), argmin(data, keepdims=True, axis=2))
assert np.array_equal(
import_and_compute("ArgMin", data, axis=2, keepdims=0), argmin(data, keepdims=False, axis=2)
)
def test_reduce_argmax():
def argmax(ndarray, axis, keepdims=False):
res = np.argmax(ndarray, axis=axis)
if keepdims:
res = np.expand_dims(res, axis=axis)
return res
data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)
assert np.array_equal(import_and_compute("ArgMax", data, axis=0), argmax(data, keepdims=True, axis=0))
assert np.array_equal(
import_and_compute("ArgMax", data, axis=0, keepdims=0), argmax(data, keepdims=False, axis=0)
)
assert np.array_equal(import_and_compute("ArgMax", data, axis=1), argmax(data, keepdims=True, axis=1))
assert np.array_equal(
import_and_compute("ArgMax", data, axis=1, keepdims=0), argmax(data, keepdims=False, axis=1)
)
assert np.array_equal(import_and_compute("ArgMax", data, axis=2), argmax(data, keepdims=True, axis=2))
assert np.array_equal(
import_and_compute("ArgMax", data, axis=2, keepdims=0), argmax(data, keepdims=False, axis=2)
)
| {
"pile_set_name": "Github"
} |
package copier
import (
"archive/tar"
"bufio"
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"sort"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/containers/storage/pkg/idtools"
"github.com/containers/storage/pkg/reexec"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMain(m *testing.M) {
if reexec.Init() {
return
}
flag.Parse()
if testing.Verbose() {
logrus.SetLevel(logrus.DebugLevel)
}
os.Exit(m.Run())
}
// makeFileContents creates contents for a file of a specified size
func makeContents(length int64) io.ReadCloser {
pipeReader, pipeWriter := io.Pipe()
buffered := bufio.NewWriter(pipeWriter)
go func() {
count := int64(0)
for count < length {
if _, err := buffered.Write([]byte{"0123456789abcdef"[count%16]}); err != nil {
buffered.Flush()
pipeWriter.CloseWithError(err) // nolint:errcheck
return
}
count++
}
buffered.Flush()
pipeWriter.Close()
}()
return pipeReader
}
// makeArchiveSlice creates an archive from the set of headers and returns a byte slice.
func makeArchiveSlice(headers []tar.Header) []byte {
rc := makeArchive(headers, nil)
defer rc.Close()
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, rc); err != nil {
panic("error creating in-memory archive")
}
return buf.Bytes()
}
// makeArchive creates an archive from the set of headers.
func makeArchive(headers []tar.Header, contents map[string][]byte) io.ReadCloser {
if contents == nil {
contents = make(map[string][]byte)
}
pipeReader, pipeWriter := io.Pipe()
go func() {
var err error
buffered := bufio.NewWriter(pipeWriter)
tw := tar.NewWriter(buffered)
for _, header := range headers {
var fileContent []byte
switch header.Typeflag {
case tar.TypeLink, tar.TypeSymlink:
header.Size = 0
case tar.TypeReg:
fileContent = contents[header.Name]
if len(fileContent) != 0 {
header.Size = int64(len(fileContent))
}
}
if err = tw.WriteHeader(&header); err != nil {
break
}
if header.Typeflag == tar.TypeReg && header.Size > 0 {
var fileContents io.Reader
if len(fileContent) > 0 {
fileContents = bytes.NewReader(fileContent)
} else {
rc := makeContents(header.Size)
defer rc.Close()
fileContents = rc
}
if _, err = io.Copy(tw, fileContents); err != nil {
break
}
}
}
tw.Close()
buffered.Flush()
if err != nil {
pipeWriter.CloseWithError(err) // nolint:errcheck
} else {
pipeWriter.Close()
}
}()
return pipeReader
}
// makeContextFromArchive creates a temporary directory, and a subdirectory
// inside of it, from an archive and returns its location. It can be removed
// once it's no longer needed.
func makeContextFromArchive(archive io.ReadCloser, subdir string) (string, error) {
tmp, err := ioutil.TempDir("", "copier-test-")
if err != nil {
return "", err
}
uidMap := []idtools.IDMap{{HostID: os.Getuid(), ContainerID: 0, Size: 1}}
gidMap := []idtools.IDMap{{HostID: os.Getgid(), ContainerID: 0, Size: 1}}
err = Put(tmp, path.Join(tmp, subdir), PutOptions{UIDMap: uidMap, GIDMap: gidMap}, archive)
archive.Close()
if err != nil {
os.RemoveAll(tmp)
return "", err
}
return tmp, err
}
// enumerateFiles walks a directory, returning the items it contains as a slice
// of names relative to that directory.
func enumerateFiles(directory string) ([]enumeratedFile, error) {
var results []enumeratedFile
err := filepath.Walk(directory, func(path string, info os.FileInfo, err error) error {
if info == nil || err != nil {
return err
}
rel, err := filepath.Rel(directory, path)
if err != nil {
return err
}
if rel != "" && rel != "." {
results = append(results, enumeratedFile{
name: rel,
mode: info.Mode() & os.ModePerm,
isSymlink: info.Mode()&os.ModeSymlink == os.ModeSymlink,
date: info.ModTime().UTC().String(),
})
}
return nil
})
if err != nil {
return nil, err
}
return results, nil
}
type expectedError struct {
inSubdir bool
name string
err error
}
type enumeratedFile struct {
name string
mode os.FileMode
isSymlink bool
date string
}
var (
testDate = time.Unix(1485449953, 0)
uid, gid = os.Getuid(), os.Getgid()
testArchiveSlice = makeArchiveSlice([]tar.Header{
{Name: "item-0", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 123, Mode: 0600, ModTime: testDate},
{Name: "item-1", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 456, Mode: 0600, ModTime: testDate},
{Name: "item-2", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 789, Mode: 0600, ModTime: testDate},
})
testArchives = []struct {
name string
rootOnly bool
headers []tar.Header
contents map[string][]byte
excludes []string
expectedGetErrors []expectedError
subdirContents map[string][]string
}{
{
name: "regular",
rootOnly: false,
headers: []tar.Header{
{Name: "file-0", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 123456789, Mode: 0600, ModTime: testDate},
{Name: "file-a", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 23, Mode: 0600, ModTime: testDate},
{Name: "file-b", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 23, Mode: 0600, ModTime: testDate},
{Name: "file-c", Uid: uid, Gid: gid, Typeflag: tar.TypeLink, Linkname: "file-a", Mode: 0600, ModTime: testDate},
{Name: "file-u", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 23, Mode: cISUID | 0755, ModTime: testDate},
{Name: "file-g", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 23, Mode: cISGID | 0755, ModTime: testDate},
{Name: "file-t", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 23, Mode: cISVTX | 0755, ModTime: testDate},
{Name: "link-0", Uid: uid, Gid: gid, Typeflag: tar.TypeSymlink, Linkname: "../file-0", Size: 123456789, Mode: 0777, ModTime: testDate},
{Name: "link-a", Uid: uid, Gid: gid, Typeflag: tar.TypeSymlink, Linkname: "file-a", Size: 23, Mode: 0777, ModTime: testDate},
{Name: "link-b", Uid: uid, Gid: gid, Typeflag: tar.TypeSymlink, Linkname: "../file-a", Size: 23, Mode: 0777, ModTime: testDate},
{Name: "hlink-0", Uid: uid, Gid: gid, Typeflag: tar.TypeLink, Linkname: "file-0", Size: 123456789, Mode: 0600, ModTime: testDate},
{Name: "hlink-a", Uid: uid, Gid: gid, Typeflag: tar.TypeLink, Linkname: "/file-a", Size: 23, Mode: 0600, ModTime: testDate},
{Name: "hlink-b", Uid: uid, Gid: gid, Typeflag: tar.TypeLink, Linkname: "../file-b", Size: 23, Mode: 0600, ModTime: testDate},
{Name: "subdir-a", Uid: uid, Gid: gid, Typeflag: tar.TypeDir, Mode: 0700, ModTime: testDate},
{Name: "subdir-a/file-n", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 108, Mode: 0660, ModTime: testDate},
{Name: "subdir-a/file-o", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 34, Mode: 0660, ModTime: testDate},
{Name: "subdir-a/file-a", Uid: uid, Gid: gid, Typeflag: tar.TypeSymlink, Linkname: "../file-a", Size: 23, Mode: 0777, ModTime: testDate},
{Name: "subdir-a/file-b", Uid: uid, Gid: gid, Typeflag: tar.TypeSymlink, Linkname: "../../file-b", Size: 23, Mode: 0777, ModTime: testDate},
{Name: "subdir-a/file-c", Uid: uid, Gid: gid, Typeflag: tar.TypeSymlink, Linkname: "/file-c", Size: 23, Mode: 0777, ModTime: testDate},
{Name: "subdir-b", Uid: uid, Gid: gid, Typeflag: tar.TypeDir, Mode: 0700, ModTime: testDate},
{Name: "subdir-b/file-n", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 216, Mode: 0660, ModTime: testDate},
{Name: "subdir-b/file-o", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 45, Mode: 0660, ModTime: testDate},
{Name: "subdir-c", Uid: uid, Gid: gid, Typeflag: tar.TypeDir, Mode: 0700, ModTime: testDate},
{Name: "subdir-c/file-n", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 432, Mode: 0666, ModTime: testDate},
{Name: "subdir-c/file-o", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 56, Mode: 0666, ModTime: testDate},
{Name: "subdir-d", Uid: uid, Gid: gid, Typeflag: tar.TypeDir, Mode: 0700, ModTime: testDate},
{Name: "subdir-d/hlink-0", Uid: uid, Gid: gid, Typeflag: tar.TypeLink, Linkname: "../file-0", Size: 123456789, Mode: 0600, ModTime: testDate},
{Name: "subdir-d/hlink-a", Uid: uid, Gid: gid, Typeflag: tar.TypeLink, Linkname: "/file-a", Size: 23, Mode: 0600, ModTime: testDate},
{Name: "subdir-d/hlink-b", Uid: uid, Gid: gid, Typeflag: tar.TypeLink, Linkname: "../../file-b", Size: 23, Mode: 0600, ModTime: testDate},
{Name: "archive-a", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 0, Mode: 0600, ModTime: testDate},
},
contents: map[string][]byte{
"archive-a": testArchiveSlice,
},
expectedGetErrors: []expectedError{
{inSubdir: false, name: "link-0", err: syscall.ENOENT},
{inSubdir: false, name: "link-b", err: syscall.ENOENT},
{inSubdir: false, name: "subdir-a/file-b", err: syscall.ENOENT},
{inSubdir: true, name: "link-0", err: syscall.ENOENT},
{inSubdir: true, name: "link-b", err: syscall.ENOENT},
{inSubdir: true, name: "subdir-a/file-b", err: syscall.ENOENT},
{inSubdir: true, name: "subdir-a/file-c", err: syscall.ENOENT},
},
},
{
name: "devices",
rootOnly: true,
headers: []tar.Header{
{Name: "char-dev", Uid: uid, Gid: gid, Typeflag: tar.TypeChar, Devmajor: 0, Devminor: 0, Mode: 0600, ModTime: testDate},
{Name: "blk-dev", Uid: uid, Gid: gid, Typeflag: tar.TypeBlock, Devmajor: 0, Devminor: 0, Mode: 0600, ModTime: testDate},
},
},
}
)
func TestPutNoChroot(t *testing.T) {
couldChroot := canChroot
canChroot = false
testPut(t)
canChroot = couldChroot
}
func TestPutChroot(t *testing.T) {
if uid != 0 {
t.Skipf("chroot() requires root privileges, skipping")
}
testPut(t)
}
func testPut(t *testing.T) {
for _, topdir := range []string{"", ".", "top"} {
for i := range testArchives {
t.Run(fmt.Sprintf("topdir=%s,archive=%s", topdir, testArchives[i].name), func(t *testing.T) {
if uid != 0 && testArchives[i].rootOnly {
t.Skipf("test archive %q can only be tested with root privileges, skipping", testArchives[i].name)
}
dir, err := makeContextFromArchive(makeArchive(testArchives[i].headers, testArchives[i].contents), topdir)
require.Nil(t, err, "error creating context from archive %q, topdir=%q", testArchives[i].name, topdir)
defer os.RemoveAll(dir)
// enumerate what we expect to have created
expected := make([]enumeratedFile, 0, len(testArchives[i].headers)+1)
if topdir != "" && topdir != "." {
info, err := os.Stat(filepath.Join(dir, topdir))
require.Nil(t, err, "error statting directory %q", filepath.Join(dir, topdir))
expected = append(expected, enumeratedFile{
name: filepath.FromSlash(topdir),
mode: info.Mode() & os.ModePerm,
isSymlink: info.Mode()&os.ModeSymlink == os.ModeSymlink,
date: info.ModTime().UTC().String(),
})
}
for _, hdr := range testArchives[i].headers {
expected = append(expected, enumeratedFile{
name: filepath.Join(filepath.FromSlash(topdir), filepath.FromSlash(hdr.Name)),
mode: os.FileMode(hdr.Mode) & os.ModePerm,
isSymlink: hdr.Typeflag == tar.TypeSymlink,
date: hdr.ModTime.UTC().String(),
})
}
sort.Slice(expected, func(i, j int) bool { return strings.Compare(expected[i].name, expected[j].name) < 0 })
// enumerate what we actually created
fileList, err := enumerateFiles(dir)
require.Nil(t, err, "error walking context directory for archive %q, topdir=%q", testArchives[i].name, topdir)
sort.Slice(fileList, func(i, j int) bool { return strings.Compare(fileList[i].name, fileList[j].name) < 0 })
// make sure they're the same
moddedEnumeratedFiles := func(enumerated []enumeratedFile) []enumeratedFile {
m := make([]enumeratedFile, 0, len(enumerated))
for i := range enumerated {
e := enumeratedFile{
name: enumerated[i].name,
mode: os.FileMode(int64(enumerated[i].mode) & testModeMask),
isSymlink: enumerated[i].isSymlink,
date: enumerated[i].date,
}
if testIgnoreSymlinkDates && e.isSymlink {
e.date = ""
}
m = append(m, e)
}
return m
}
if !reflect.DeepEqual(expected, fileList) && reflect.DeepEqual(moddedEnumeratedFiles(expected), moddedEnumeratedFiles(fileList)) {
logrus.Warn("chmod() lost some bits and possibly timestamps on symlinks, otherwise we match the source archive")
} else {
require.Equal(t, expected, fileList, "list of files in context directory for archive %q under topdir %q should match the archived used to populate it", testArchives[i].name, topdir)
}
})
}
}
}
func isExpectedError(err error, inSubdir bool, name string, expectedErrors []expectedError) bool {
// if we couldn't read that content, check if it's one of the expected failures
for _, expectedError := range expectedErrors {
if expectedError.inSubdir != inSubdir {
continue
}
if expectedError.name != name {
continue
}
if !strings.Contains(unwrapError(err).Error(), unwrapError(expectedError.err).Error()) {
// not expecting this specific error
continue
}
// it's an expected failure
return true
}
return false
}
func TestStatNoChroot(t *testing.T) {
couldChroot := canChroot
canChroot = false
testStat(t)
canChroot = couldChroot
}
func TestStatChroot(t *testing.T) {
if uid != 0 {
t.Skipf("chroot() requires root privileges, skipping")
}
testStat(t)
}
func testStat(t *testing.T) {
for _, absolute := range []bool{false, true} {
for _, topdir := range []string{"", ".", "top"} {
for _, testArchive := range testArchives {
if uid != 0 && testArchive.rootOnly {
t.Skipf("test archive %q can only be tested with root privileges, skipping", testArchive.name)
}
dir, err := makeContextFromArchive(makeArchive(testArchive.headers, testArchive.contents), topdir)
require.Nil(t, err, "error creating context from archive %q", testArchive.name)
defer os.RemoveAll(dir)
root := dir
for _, testItem := range testArchive.headers {
name := filepath.FromSlash(testItem.Name)
if absolute {
name = filepath.Join(root, topdir, name)
}
t.Run(fmt.Sprintf("absolute=%t,topdir=%s,archive=%s,item=%s", absolute, topdir, testArchive.name, name), func(t *testing.T) {
// read stats about this item
var excludes []string
for _, exclude := range testArchive.excludes {
excludes = append(excludes, filepath.FromSlash(exclude))
}
options := StatOptions{
CheckForArchives: false,
Excludes: excludes,
}
stats, err := Stat(root, topdir, options, []string{name})
require.Nil(t, err, "error statting %q: %v", name, err)
for _, st := range stats {
// should not have gotten an error
require.Emptyf(t, st.Error, "expected no error from stat %q", st.Glob)
// no matching characters -> should have matched one item
require.NotEmptyf(t, st.Globbed, "expected at least one match on glob %q", st.Glob)
matches := 0
for _, glob := range st.Globbed {
matches++
require.Equal(t, st.Glob, glob, "expected entry for %q", st.Glob)
require.NotNil(t, st.Results[glob], "%q globbed %q, but there are no results for it", st.Glob, glob)
toStat := glob
if !absolute {
toStat = filepath.Join(root, topdir, name)
}
_, err = os.Lstat(toStat)
require.Nil(t, err, "got error on lstat() of returned value %q(%q(%q)): %v", toStat, glob, name, err)
result := st.Results[glob]
switch testItem.Typeflag {
case tar.TypeReg, tar.TypeRegA:
if actualContent, ok := testArchive.contents[testItem.Name]; ok {
testItem.Size = int64(len(actualContent))
}
require.Equal(t, testItem.Size, result.Size, "unexpected size difference for %q", name)
require.True(t, result.IsRegular, "expected %q.IsRegular to be true", glob)
require.False(t, result.IsDir, "expected %q.IsDir to be false", glob)
require.False(t, result.IsSymlink, "expected %q.IsSymlink to be false", glob)
case tar.TypeDir:
require.False(t, result.IsRegular, "expected %q.IsRegular to be false", glob)
require.True(t, result.IsDir, "expected %q.IsDir to be true", glob)
require.False(t, result.IsSymlink, "expected %q.IsSymlink to be false", glob)
case tar.TypeSymlink:
require.True(t, result.IsSymlink, "%q is supposed to be a symbolic link, but is not", name)
require.Equal(t, filepath.FromSlash(testItem.Linkname), result.ImmediateTarget, "%q is supposed to point to %q, but points to %q", glob, testItem.Linkname, result.ImmediateTarget)
case tar.TypeBlock, tar.TypeChar:
require.False(t, result.IsRegular, "%q is a regular file, but is not supposed to be", name)
require.False(t, result.IsDir, "%q is a directory, but is not supposed to be", name)
require.False(t, result.IsSymlink, "%q is not supposed to be a symbolic link, but appears to be one", name)
}
}
require.Equal(t, 1, matches, "non-glob %q matched %d items, not exactly one", name, matches)
}
})
}
}
}
}
}
func TestGetSingleNoChroot(t *testing.T) {
couldChroot := canChroot
canChroot = false
testGetSingle(t)
canChroot = couldChroot
}
func TestGetSingleChroot(t *testing.T) {
if uid != 0 {
t.Skipf("chroot() requires root privileges, skipping")
}
testGetSingle(t)
}
func testGetSingle(t *testing.T) {
for _, absolute := range []bool{false, true} {
for _, topdir := range []string{"", ".", "top"} {
for _, testArchive := range testArchives {
var excludes []string
for _, exclude := range testArchive.excludes {
excludes = append(excludes, filepath.FromSlash(exclude))
}
getOptions := GetOptions{
Excludes: excludes,
ExpandArchives: false,
}
if uid != 0 && testArchive.rootOnly {
t.Skipf("test archive %q can only be tested with root privileges, skipping", testArchive.name)
}
dir, err := makeContextFromArchive(makeArchive(testArchive.headers, testArchive.contents), topdir)
require.Nil(t, err, "error creating context from archive %q", testArchive.name)
defer os.RemoveAll(dir)
root := dir
for _, testItem := range testArchive.headers {
name := filepath.FromSlash(testItem.Name)
if absolute {
name = filepath.Join(root, topdir, name)
}
t.Run(fmt.Sprintf("absolute=%t,topdir=%s,archive=%s,item=%s", absolute, topdir, testArchive.name, name), func(t *testing.T) {
// check if we can get this one item
err := Get(root, topdir, getOptions, []string{name}, ioutil.Discard)
// if we couldn't read that content, check if it's one of the expected failures
if err != nil && isExpectedError(err, topdir != "" && topdir != ".", testItem.Name, testArchive.expectedGetErrors) {
return
}
require.Nil(t, err, "error getting %q under %q", name, filepath.Join(root, topdir))
// we'll check subdirectories later
if testItem.Typeflag == tar.TypeDir {
return
}
// check what we get when we get this one item
pipeReader, pipeWriter := io.Pipe()
var getErr error
var wg sync.WaitGroup
wg.Add(1)
go func() {
getErr = Get(root, topdir, getOptions, []string{name}, pipeWriter)
pipeWriter.Close()
wg.Done()
}()
tr := tar.NewReader(pipeReader)
hdr, err := tr.Next()
for err == nil {
assert.Equal(t, filepath.Base(name), filepath.FromSlash(hdr.Name), "expected item named %q, got %q", filepath.Base(name), filepath.FromSlash(hdr.Name))
hdr, err = tr.Next()
}
assert.Equal(t, io.EOF.Error(), err.Error(), "expected EOF at end of archive, got %q", err.Error())
if !t.Failed() && testItem.Typeflag == tar.TypeReg && testItem.Mode&(cISUID|cISGID|cISVTX) != 0 {
for _, stripSetuidBit := range []bool{false, true} {
for _, stripSetgidBit := range []bool{false, true} {
for _, stripStickyBit := range []bool{false, true} {
t.Run(fmt.Sprintf("absolute=%t,topdir=%s,archive=%s,item=%s,strip_setuid=%t,strip_setgid=%t,strip_sticky=%t", absolute, topdir, testArchive.name, name, stripSetuidBit, stripSetgidBit, stripStickyBit), func(t *testing.T) {
var getErr error
var wg sync.WaitGroup
getOptions := getOptions
getOptions.StripSetuidBit = stripSetuidBit
getOptions.StripSetgidBit = stripSetgidBit
getOptions.StripStickyBit = stripStickyBit
pipeReader, pipeWriter := io.Pipe()
wg.Add(1)
go func() {
getErr = Get(root, topdir, getOptions, []string{name}, pipeWriter)
pipeWriter.Close()
wg.Done()
}()
tr := tar.NewReader(pipeReader)
hdr, err := tr.Next()
for err == nil {
expectedMode := testItem.Mode
modifier := ""
if stripSetuidBit {
expectedMode &^= cISUID
modifier += "(with setuid bit stripped) "
}
if stripSetgidBit {
expectedMode &^= cISGID
modifier += "(with setgid bit stripped) "
}
if stripStickyBit {
expectedMode &^= cISVTX
modifier += "(with sticky bit stripped) "
}
if expectedMode != hdr.Mode && expectedMode&testModeMask == hdr.Mode&testModeMask {
logrus.Warnf("chmod() lost some bits: expected 0%o, got 0%o", expectedMode, hdr.Mode)
} else {
assert.Equal(t, expectedMode, hdr.Mode, "expected item named %q %sto have mode 0%o, got 0%o", hdr.Name, modifier, expectedMode, hdr.Mode)
}
hdr, err = tr.Next()
}
assert.Equal(t, io.EOF.Error(), err.Error(), "expected EOF at end of archive, got %q", err.Error())
wg.Wait()
assert.Nil(t, getErr, "unexpected error from Get(%q): %v", name, getErr)
pipeReader.Close()
})
}
}
}
}
wg.Wait()
assert.Nil(t, getErr, "unexpected error from Get(%q): %v", name, getErr)
pipeReader.Close()
})
}
}
}
}
}
func TestGetMultipleNoChroot(t *testing.T) {
couldChroot := canChroot
canChroot = false
testGetMultiple(t)
canChroot = couldChroot
}
func TestGetMultipleChroot(t *testing.T) {
if uid != 0 {
t.Skipf("chroot() requires root privileges, skipping")
}
testGetMultiple(t)
}
func testGetMultiple(t *testing.T) {
type getTestArchiveCase struct {
name string
pattern string
exclude []string
items []string
expandArchives bool
stripSetuidBit bool
stripSetgidBit bool
stripStickyBit bool
stripXattrs bool
keepDirectoryNames bool
}
var getTestArchives = []struct {
name string
headers []tar.Header
contents map[string][]byte
cases []getTestArchiveCase
expectedGetErrors []expectedError
}{
{
name: "regular",
headers: []tar.Header{
{Name: "file-0", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 123456789, Mode: 0600},
{Name: "file-a", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 23, Mode: 0600},
{Name: "file-b", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 23, Mode: 0600},
{Name: "link-a", Uid: uid, Gid: gid, Typeflag: tar.TypeSymlink, Linkname: "file-a", Size: 23, Mode: 0600},
{Name: "archive-a", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 0, Mode: 0600},
{Name: "non-archive-a", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 1199, Mode: 0600},
{Name: "hlink-0", Uid: uid, Gid: gid, Typeflag: tar.TypeLink, Linkname: "file-0", Size: 123456789, Mode: 0600},
{Name: "something-a", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 34, Mode: 0600},
{Name: "subdir-a", Uid: uid, Gid: gid, Typeflag: tar.TypeDir, Mode: 0700},
{Name: "subdir-a/file-n", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 108, Mode: 0660},
{Name: "subdir-a/file-o", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 45, Mode: 0660},
{Name: "subdir-a/file-a", Uid: uid, Gid: gid, Typeflag: tar.TypeSymlink, Linkname: "../file-a", Size: 23, Mode: 0600},
{Name: "subdir-a/file-b", Uid: uid, Gid: gid, Typeflag: tar.TypeSymlink, Linkname: "../../file-b", Size: 23, Mode: 0600},
{Name: "subdir-a/file-c", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 56, Mode: 0600},
{Name: "subdir-b", Uid: uid, Gid: gid, Typeflag: tar.TypeDir, Mode: 0700},
{Name: "subdir-b/file-n", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 216, Mode: 0660},
{Name: "subdir-b/file-o", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 67, Mode: 0660},
{Name: "subdir-c", Uid: uid, Gid: gid, Typeflag: tar.TypeDir, Mode: 0700},
{Name: "subdir-c/file-p", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 432, Mode: 0666},
{Name: "subdir-c/file-q", Uid: uid, Gid: gid, Typeflag: tar.TypeReg, Size: 78, Mode: 0666},
{Name: "subdir-d", Uid: uid, Gid: gid, Typeflag: tar.TypeDir, Mode: 0700},
{Name: "subdir-d/hlink-0", Uid: uid, Gid: gid, Typeflag: tar.TypeLink, Linkname: "../file-0", Size: 123456789, Mode: 0600},
{Name: "subdir-e", Uid: uid, Gid: gid, Typeflag: tar.TypeDir, Mode: 0700},
{Name: "subdir-e/subdir-f", Uid: uid, Gid: gid, Typeflag: tar.TypeDir, Mode: 0700},
{Name: "subdir-e/subdir-f/hlink-b", Uid: uid, Gid: gid, Typeflag: tar.TypeLink, Linkname: "../../file-b", Size: 23, Mode: 0600},
},
contents: map[string][]byte{
"archive-a": testArchiveSlice,
},
expectedGetErrors: []expectedError{
{inSubdir: true, name: ".", err: syscall.ENOENT},
{inSubdir: true, name: "/subdir-b/*", err: syscall.ENOENT},
{inSubdir: true, name: "../../subdir-b/*", err: syscall.ENOENT},
},
cases: []getTestArchiveCase{
{
name: "everything",
pattern: ".",
items: []string{
"file-0",
"file-a",
"file-b",
"link-a",
"hlink-0",
"something-a",
"archive-a",
"non-archive-a",
"subdir-a",
"subdir-a/file-n",
"subdir-a/file-o",
"subdir-a/file-a",
"subdir-a/file-b",
"subdir-a/file-c",
"subdir-b",
"subdir-b/file-n",
"subdir-b/file-o",
"subdir-c",
"subdir-c/file-p",
"subdir-c/file-q",
"subdir-d",
"subdir-d/hlink-0",
"subdir-e",
"subdir-e/subdir-f",
"subdir-e/subdir-f/hlink-b",
},
},
{
name: "wildcard",
pattern: "*",
items: []string{
"file-0",
"file-a",
"file-b",
"link-a",
"hlink-0",
"something-a",
"archive-a",
"non-archive-a",
"file-n", // from subdir-a
"file-o", // from subdir-a
"file-a", // from subdir-a
"file-b", // from subdir-a
"file-c", // from subdir-a
"file-n", // from subdir-b
"file-o", // from subdir-b
"file-p", // from subdir-c
"file-q", // from subdir-c
"hlink-0", // from subdir-d
"subdir-f", // from subdir-e
"subdir-f/hlink-b", // from subdir-e
},
},
{
name: "dot-with-wildcard-includes-and-excludes",
pattern: ".",
exclude: []string{"**/*-a", "!**/*-c"},
items: []string{
"file-0",
"file-b",
"hlink-0",
"subdir-a/file-c",
"subdir-b",
"subdir-b/file-n",
"subdir-b/file-o",
"subdir-c",
"subdir-c/file-p",
"subdir-c/file-q",
"subdir-d",
"subdir-d/hlink-0",
"subdir-e",
"subdir-e/subdir-f",
"subdir-e/subdir-f/hlink-b",
},
},
{
name: "everything-with-wildcard-includes-and-excludes",
pattern: "*",
exclude: []string{"**/*-a", "!**/*-c"},
items: []string{
"file-0",
"file-b",
"file-n",
"file-o",
"file-p",
"file-q",
"hlink-0",
"hlink-0",
"subdir-f",
"subdir-f/hlink-b",
},
},
{
name: "dot-with-dot-exclude",
pattern: ".",
exclude: []string{".", "!**/*-c"},
items: []string{
"file-0",
"file-a",
"file-b",
"link-a",
"hlink-0",
"something-a",
"archive-a",
"non-archive-a",
"subdir-a",
"subdir-a/file-a",
"subdir-a/file-b",
"subdir-a/file-c",
"subdir-a/file-n",
"subdir-a/file-o",
"subdir-b",
"subdir-b/file-n",
"subdir-b/file-o",
"subdir-c",
"subdir-c/file-p",
"subdir-c/file-q",
"subdir-d",
"subdir-d/hlink-0",
"subdir-e",
"subdir-e/subdir-f",
"subdir-e/subdir-f/hlink-b",
},
},
{
name: "everything-with-dot-exclude",
pattern: "*",
exclude: []string{".", "!**/*-c"},
items: []string{
"file-0",
"file-a",
"file-a",
"file-b",
"file-b",
"file-c",
"file-n",
"file-n",
"file-o",
"file-o",
"file-p",
"file-q",
"hlink-0",
"hlink-0",
"link-a",
"something-a",
"archive-a",
"non-archive-a",
"subdir-f",
"subdir-f/hlink-b",
},
},
{
name: "all-with-all-exclude",
pattern: "*",
exclude: []string{"*", "!**/*-c"},
items: []string{
"file-p",
"file-q",
},
},
{
name: "everything-with-all-exclude",
pattern: ".",
exclude: []string{"*", "!**/*-c"},
items: []string{
"subdir-a/file-c",
"subdir-c",
"subdir-c/file-p",
"subdir-c/file-q",
},
},
{
name: "file-wildcard",
pattern: "file-*",
items: []string{
"file-0",
"file-a",
"file-b",
},
},
{
name: "file-and-dir-wildcard",
pattern: "*-a",
items: []string{
"file-a",
"link-a",
"something-a",
"archive-a",
"non-archive-a",
"file-n", // from subdir-a
"file-o", // from subdir-a
"file-a", // from subdir-a
"file-b", // from subdir-a
"file-c", // from subdir-a
},
},
{
name: "file-and-dir-wildcard-with-exclude",
pattern: "*-a",
exclude: []string{"subdir-a", "top/subdir-a"},
items: []string{
"file-a",
"link-a",
"something-a",
"archive-a",
"non-archive-a",
},
},
{
name: "file-and-dir-wildcard-with-wildcard-exclude",
pattern: "*-a",
exclude: []string{"subdir*", "top/subdir*"},
items: []string{
"file-a",
"link-a",
"something-a",
"archive-a",
"non-archive-a",
},
},
{
name: "file-and-dir-wildcard-with-deep-exclude",
pattern: "*-a",
exclude: []string{"**/subdir-a"},
items: []string{
"file-a",
"link-a",
"something-a",
"archive-a",
"non-archive-a",
},
},
{
name: "file-and-dir-wildcard-with-wildcard-deep-exclude",
pattern: "*-a",
exclude: []string{"**/subdir*"},
items: []string{
"file-a",
"link-a",
"something-a",
"archive-a",
"non-archive-a",
},
},
{
name: "file-and-dir-wildcard-with-deep-include",
pattern: "*-a",
exclude: []string{"**/subdir-a", "!**/file-c"},
items: []string{
"file-a",
"link-a",
"something-a",
"archive-a",
"non-archive-a",
// no "file-c" from subdir-a
},
},
{
name: "file-and-dir-wildcard-with-wildcard-deep-include",
pattern: "*-a",
exclude: []string{"**/subdir*", "!**/file-c"},
items: []string{
"file-a",
"link-a",
"something-a",
"archive-a",
"non-archive-a",
// no "file-c" from subdir-a
},
},
{
name: "subdirectory",
pattern: "subdir-e",
items: []string{
"subdir-f",
"subdir-f/hlink-b",
},
},
{
name: "subdirectory-wildcard",
pattern: "*/subdir-*",
items: []string{
"hlink-b", // from subdir-e/subdir-f
},
},
{
name: "not-expanded-archive",
pattern: "*archive-a",
items: []string{
"archive-a",
"non-archive-a",
},
},
{
name: "expanded-archive",
pattern: "*archive-a",
expandArchives: true,
items: []string{
"non-archive-a",
"item-0",
"item-1",
"item-2",
},
},
{
name: "subdir-without-name",
pattern: "subdir-e",
items: []string{
"subdir-f",
"subdir-f/hlink-b",
},
},
{
name: "subdir-with-name",
pattern: "subdir-e",
keepDirectoryNames: true,
items: []string{
"subdir-e",
"subdir-e/subdir-f",
"subdir-e/subdir-f/hlink-b",
},
},
{
name: "root-wildcard",
pattern: "/subdir-b/*",
keepDirectoryNames: false,
items: []string{
"file-n",
"file-o",
},
},
{
name: "dotdot-wildcard",
pattern: "../../subdir-b/*",
keepDirectoryNames: false,
items: []string{
"file-n",
"file-o",
},
},
},
},
}
for _, topdir := range []string{"", ".", "top"} {
for _, testArchive := range getTestArchives {
dir, err := makeContextFromArchive(makeArchive(testArchive.headers, testArchive.contents), topdir)
require.Nil(t, err, "error creating context from archive %q", testArchive.name)
defer os.RemoveAll(dir)
root := dir
cases := make(map[string]struct{})
for _, testCase := range testArchive.cases {
if _, ok := cases[testCase.name]; ok {
t.Fatalf("duplicate case %q", testCase.name)
}
cases[testCase.name] = struct{}{}
}
for _, testCase := range testArchive.cases {
var excludes []string
for _, exclude := range testCase.exclude {
excludes = append(excludes, filepath.FromSlash(exclude))
}
getOptions := GetOptions{
Excludes: excludes,
ExpandArchives: testCase.expandArchives,
StripSetuidBit: testCase.stripSetuidBit,
StripSetgidBit: testCase.stripSetgidBit,
StripStickyBit: testCase.stripStickyBit,
StripXattrs: testCase.stripXattrs,
KeepDirectoryNames: testCase.keepDirectoryNames,
}
t.Run(fmt.Sprintf("topdir=%s,archive=%s,case=%s,pattern=%s", topdir, testArchive.name, testCase.name, testCase.pattern), func(t *testing.T) {
// ensure that we can get stuff using this spec
err := Get(root, topdir, getOptions, []string{testCase.pattern}, ioutil.Discard)
if err != nil && isExpectedError(err, topdir != "" && topdir != ".", testCase.pattern, testArchive.expectedGetErrors) {
return
}
require.Nil(t, err, "error getting %q under %q", testCase.pattern, filepath.Join(root, topdir))
// see what we get when we get this pattern
pipeReader, pipeWriter := io.Pipe()
var getErr error
var wg sync.WaitGroup
wg.Add(1)
go func() {
getErr = Get(root, topdir, getOptions, []string{testCase.pattern}, pipeWriter)
pipeWriter.Close()
wg.Done()
}()
tr := tar.NewReader(pipeReader)
hdr, err := tr.Next()
actualContents := []string{}
for err == nil {
actualContents = append(actualContents, filepath.FromSlash(hdr.Name))
hdr, err = tr.Next()
}
pipeReader.Close()
sort.Strings(actualContents)
// compare it to what we were supposed to get
expectedContents := make([]string, 0, len(testCase.items))
for _, item := range testCase.items {
expectedContents = append(expectedContents, filepath.FromSlash(item))
}
sort.Strings(expectedContents)
assert.Equal(t, io.EOF.Error(), err.Error(), "expected EOF at end of archive, got %q", err.Error())
wg.Wait()
assert.Nil(t, getErr, "unexpected error from Get(%q)", testCase.pattern)
assert.Equal(t, expectedContents, actualContents, "Get(%q,excludes=%v) didn't produce the right set of items", testCase.pattern, excludes)
})
}
}
}
}
func TestMkdirNoChroot(t *testing.T) {
couldChroot := canChroot
canChroot = false
testMkdir(t)
canChroot = couldChroot
}
func TestMkdirChroot(t *testing.T) {
if uid != 0 {
t.Skipf("chroot() requires root privileges, skipping")
}
testMkdir(t)
}
func testMkdir(t *testing.T) {
type testCase struct {
name string
create string
expect []string
}
testArchives := []struct {
name string
headers []tar.Header
testCases []testCase
}{
{
name: "regular",
headers: []tar.Header{
{Name: "subdir-a", Typeflag: tar.TypeDir, Mode: 0755, ModTime: testDate},
{Name: "subdir-a/subdir-b", Typeflag: tar.TypeDir, Mode: 0755, ModTime: testDate},
{Name: "subdir-a/subdir-b/subdir-c", Typeflag: tar.TypeDir, Mode: 0755, ModTime: testDate},
{Name: "subdir-a/subdir-b/dangle1", Typeflag: tar.TypeSymlink, Linkname: "dangle1-target", ModTime: testDate},
{Name: "subdir-a/subdir-b/dangle2", Typeflag: tar.TypeSymlink, Linkname: "../dangle2-target", ModTime: testDate},
{Name: "subdir-a/subdir-b/dangle3", Typeflag: tar.TypeSymlink, Linkname: "../../dangle3-target", ModTime: testDate},
{Name: "subdir-a/subdir-b/dangle4", Typeflag: tar.TypeSymlink, Linkname: "../../../dangle4-target", ModTime: testDate},
{Name: "subdir-a/subdir-b/dangle5", Typeflag: tar.TypeSymlink, Linkname: "../../../../dangle5-target", ModTime: testDate},
{Name: "subdir-a/subdir-b/dangle6", Typeflag: tar.TypeSymlink, Linkname: "/dangle6-target", ModTime: testDate},
{Name: "subdir-a/subdir-b/dangle7", Typeflag: tar.TypeSymlink, Linkname: "/../dangle7-target", ModTime: testDate},
},
testCases: []testCase{
{
name: "basic",
create: "subdir-d",
expect: []string{"subdir-d"},
},
{
name: "subdir",
create: "subdir-d/subdir-e/subdir-f",
expect: []string{"subdir-d", "subdir-d/subdir-e", "subdir-d/subdir-e/subdir-f"},
},
{
name: "dangling-link-itself",
create: "subdir-a/subdir-b/dangle1",
expect: []string{"subdir-a/subdir-b/dangle1-target"},
},
{
name: "dangling-link-as-intermediate-parent",
create: "subdir-a/subdir-b/dangle2/final",
expect: []string{"subdir-a/dangle2-target", "subdir-a/dangle2-target/final"},
},
{
name: "dangling-link-as-intermediate-grandparent",
create: "subdir-a/subdir-b/dangle3/final",
expect: []string{"dangle3-target", "dangle3-target/final"},
},
{
name: "dangling-link-as-intermediate-attempted-relative-breakout",
create: "subdir-a/subdir-b/dangle4/final",
expect: []string{"dangle4-target", "dangle4-target/final"},
},
{
name: "dangling-link-as-intermediate-attempted-relative-breakout-again",
create: "subdir-a/subdir-b/dangle5/final",
expect: []string{"dangle5-target", "dangle5-target/final"},
},
{
name: "dangling-link-itself-absolute",
create: "subdir-a/subdir-b/dangle6",
expect: []string{"dangle6-target"},
},
{
name: "dangling-link-as-intermediate-absolute",
create: "subdir-a/subdir-b/dangle6/final",
expect: []string{"dangle6-target", "dangle6-target/final"},
},
{
name: "dangling-link-as-intermediate-absolute-relative-breakout",
create: "subdir-a/subdir-b/dangle7/final",
expect: []string{"dangle7-target", "dangle7-target/final"},
},
{
name: "parent-parent-final",
create: "../../final",
expect: []string{"final"},
},
{
name: "root-parent-final",
create: "/../final",
expect: []string{"final"},
},
{
name: "root-parent-intermediate-parent-final",
create: "/../intermediate/../final",
expect: []string{"final"},
},
},
},
}
for i := range testArchives {
t.Run(testArchives[i].name, func(t *testing.T) {
for _, testCase := range testArchives[i].testCases {
t.Run(testCase.name, func(t *testing.T) {
dir, err := makeContextFromArchive(makeArchive(testArchives[i].headers, nil), "")
require.Nil(t, err, "error creating context from archive %q, topdir=%q", testArchives[i].name, "")
defer os.RemoveAll(dir)
root := dir
options := MkdirOptions{ChownNew: &idtools.IDPair{UID: os.Getuid(), GID: os.Getgid()}}
var beforeNames, afterNames []string
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info == nil || err != nil {
return err
}
rel, err := filepath.Rel(dir, path)
if err != nil {
return err
}
beforeNames = append(beforeNames, rel)
return nil
})
require.Nil(t, err, "error walking directory to catalog pre-Mkdir contents: %v", err)
err = Mkdir(root, testCase.create, options)
require.Nil(t, err, "error creating directory %q under %q with Mkdir: %v", testCase.create, root, err)
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info == nil || err != nil {
return err
}
rel, err := filepath.Rel(dir, path)
if err != nil {
return err
}
afterNames = append(afterNames, rel)
return nil
})
require.Nil(t, err, "error walking directory to catalog post-Mkdir contents: %v", err)
expected := append([]string{}, beforeNames...)
for _, expect := range testCase.expect {
expected = append(expected, filepath.FromSlash(expect))
}
sort.Strings(expected)
sort.Strings(afterNames)
assert.Equal(t, expected, afterNames, "expected different paths")
})
}
})
}
}
func TestCleanerSubdirectory(t *testing.T) {
testCases := [][2]string{
{".", "."},
{"..", "."},
{"/", "."},
{"directory/subdirectory/..", "directory"},
{"directory/../..", "."},
{"../../directory", "directory"},
{"../directory/subdirectory", "directory/subdirectory"},
{"/directory/../..", "."},
{"/directory/../../directory", "directory"},
}
for _, testCase := range testCases {
t.Run(testCase[0], func(t *testing.T) {
cleaner := cleanerReldirectory(filepath.FromSlash(testCase[0]))
assert.Equal(t, testCase[1], filepath.ToSlash(cleaner), "expected to get %q, got %q", testCase[1], cleaner)
})
}
}
| {
"pile_set_name": "Github"
} |
tar-ignore = Tor2web/.git
tar-ignore = .gitignore
| {
"pile_set_name": "Github"
} |
# Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rails secret` to generate a secure secret key.
# Make sure the secrets in this file are kept private
# if you're sharing your code publicly.
development:
secret_key_base: dd5a7441b31591192f98a55c1b4ba7aae8a92b99c66b3843182d0fd5d01b4313ed357140a8d19195874011148b55fe26d7a75a0d84999f0582c2d431664fcc30
test:
secret_key_base: c9e1758789fddaa607f39973bd942a5e61929c4fe6827a35c347bcf455abbed1431462dc696707f703c10a2df5aa2b91cfbd8de859482eb24b84cbde7a1bccfc
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details
from odoo import models
class IrModelFields(models.Model):
_inherit = 'ir.model.fields'
def unlink(self):
# Nasty hack to prevent the deletion of shared field reveal_id
self = self.filtered(
lambda rec: not (
rec.model == 'crm.lead'
and rec.name == 'reveal_id'
)
)
return super(IrModelFields, self).unlink()
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<razerdp.demo.widget.TitleBarView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:mode="mode_both"
app:right_icon="@drawable/ic_setting_white"
app:title_text="朋友圈模拟" />
<razerdp.demo.widget.DPRecyclerView
android:id="@+id/rv_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white" />
</LinearLayout> | {
"pile_set_name": "Github"
} |
#define FXAA_PC 1
//#define FXAA_HLSL_4 1
#define FXAA_HLSL_5 1
#define FXAA_QUALITY__PRESET 15
#define FXAA_GREEN_AS_LUMA 0
//----------------------------------------------------------------------------------
// File: FXAA\media/FXAA.hlsl
// SDK Version: v1.2
// Email: [email protected]
// Site: http://developer.nvidia.com/
//
// Copyright (c) 2014, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------------
/*============================================================================
NVIDIA FXAA 3.11 by TIMOTHY LOTTES
------------------------------------------------------------------------------
INTEGRATION CHECKLIST
------------------------------------------------------------------------------
(1.)
In the shader source, setup defines for the desired configuration.
When providing multiple shaders (for different presets),
simply setup the defines differently in multiple files.
Example,
#define FXAA_PC 1
#define FXAA_HLSL_5 1
#define FXAA_QUALITY__PRESET 12
Or,
#define FXAA_360 1
Or,
#define FXAA_PS3 1
Etc.
(2.)
Then include this file,
#include "Fxaa3_11.h"
(3.)
Then call the FXAA pixel shader from within your desired shader.
Look at the FXAA Quality FxaaPixelShader() for docs on inputs.
As for FXAA 3.11 all inputs for all shaders are the same
to enable easy porting between platforms.
return FxaaPixelShader(...);
(4.)
Insure pass prior to FXAA outputs RGBL (see next section).
Or use,
#define FXAA_GREEN_AS_LUMA 1
(5.)
Setup engine to provide the following constants
which are used in the FxaaPixelShader() inputs,
FxaaFloat2 fxaaQualityRcpFrame,
FxaaFloat4 fxaaConsoleRcpFrameOpt,
FxaaFloat4 fxaaConsoleRcpFrameOpt2,
FxaaFloat4 fxaaConsole360RcpFrameOpt2,
FxaaFloat fxaaQualitySubpix,
FxaaFloat fxaaQualityEdgeThreshold,
FxaaFloat fxaaQualityEdgeThresholdMin,
FxaaFloat fxaaConsoleEdgeSharpness,
FxaaFloat fxaaConsoleEdgeThreshold,
FxaaFloat fxaaConsoleEdgeThresholdMin,
FxaaFloat4 fxaaConsole360ConstDir
Look at the FXAA Quality FxaaPixelShader() for docs on inputs.
(6.)
Have FXAA vertex shader run as a full screen triangle,
and output "pos" and "fxaaConsolePosPos"
such that inputs in the pixel shader provide,
// {xy} = center of pixel
FxaaFloat2 pos,
// {xy__} = upper left of pixel
// {__zw} = lower right of pixel
FxaaFloat4 fxaaConsolePosPos,
(7.)
Insure the texture sampler(s) used by FXAA are set to bilinear filtering.
------------------------------------------------------------------------------
INTEGRATION - RGBL AND COLORSPACE
------------------------------------------------------------------------------
FXAA3 requires RGBL as input unless the following is set,
#define FXAA_GREEN_AS_LUMA 1
In which case the engine uses green in place of luma,
and requires RGB input is in a non-linear colorspace.
RGB should be LDR (low dynamic range).
Specifically do FXAA after tonemapping.
RGB data as returned by a texture fetch can be non-linear,
or linear when FXAA_GREEN_AS_LUMA is not set.
Note an "sRGB format" texture counts as linear,
because the result of a texture fetch is linear data.
Regular "RGBA8" textures in the sRGB colorspace are non-linear.
If FXAA_GREEN_AS_LUMA is not set,
luma must be stored in the alpha channel prior to running FXAA.
This luma should be in a perceptual space (could be gamma 2.0).
Example pass before FXAA where output is gamma 2.0 encoded,
color.rgb = ToneMap(color.rgb); // linear color output
color.rgb = sqrt(color.rgb); // gamma 2.0 color output
return color;
To use FXAA,
color.rgb = ToneMap(color.rgb); // linear color output
color.rgb = sqrt(color.rgb); // gamma 2.0 color output
color.a = dot(color.rgb, FxaaFloat3(0.299, 0.587, 0.114)); // compute luma
return color;
Another example where output is linear encoded,
say for instance writing to an sRGB formated render target,
where the render target does the conversion back to sRGB after blending,
color.rgb = ToneMap(color.rgb); // linear color output
return color;
To use FXAA,
color.rgb = ToneMap(color.rgb); // linear color output
color.a = sqrt(dot(color.rgb, FxaaFloat3(0.299, 0.587, 0.114))); // compute luma
return color;
Getting luma correct is required for the algorithm to work correctly.
------------------------------------------------------------------------------
BEING LINEARLY CORRECT?
------------------------------------------------------------------------------
Applying FXAA to a framebuffer with linear RGB color will look worse.
This is very counter intuitive, but happends to be true in this case.
The reason is because dithering artifacts will be more visiable
in a linear colorspace.
------------------------------------------------------------------------------
COMPLEX INTEGRATION
------------------------------------------------------------------------------
Q. What if the engine is blending into RGB before wanting to run FXAA?
A. In the last opaque pass prior to FXAA,
have the pass write out luma into alpha.
Then blend into RGB only.
FXAA should be able to run ok
assuming the blending pass did not any add aliasing.
This should be the common case for particles and common blending passes.
A. Or use FXAA_GREEN_AS_LUMA.
============================================================================*/
/*============================================================================
INTEGRATION KNOBS
============================================================================*/
//
// FXAA_PS3 and FXAA_360 choose the console algorithm (FXAA3 CONSOLE).
// FXAA_360_OPT is a prototype for the new optimized 360 version.
//
// 1 = Use API.
// 0 = Don't use API.
//
/*--------------------------------------------------------------------------*/
#ifndef FXAA_PS3
#define FXAA_PS3 0
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_360
#define FXAA_360 0
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_360_OPT
#define FXAA_360_OPT 0
#endif
/*==========================================================================*/
#ifndef FXAA_PC
//
// FXAA Quality
// The high quality PC algorithm.
//
#define FXAA_PC 1
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_PC_CONSOLE
//
// The console algorithm for PC is included
// for developers targeting really low spec machines.
// Likely better to just run FXAA_PC, and use a really low preset.
//
#define FXAA_PC_CONSOLE 0
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_GLSL_120
#define FXAA_GLSL_120 0
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_GLSL_130
#define FXAA_GLSL_130 0
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_HLSL_3
#define FXAA_HLSL_3 0
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_HLSL_4
#define FXAA_HLSL_4 0
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_HLSL_5
#define FXAA_HLSL_5 1
#endif
/*==========================================================================*/
#ifndef FXAA_GREEN_AS_LUMA
//
// For those using non-linear color,
// and either not able to get luma in alpha, or not wanting to,
// this enables FXAA to run using green as a proxy for luma.
// So with this enabled, no need to pack luma in alpha.
//
// This will turn off AA on anything which lacks some amount of green.
// Pure red and blue or combination of only R and B, will get no AA.
//
// Might want to lower the settings for both,
// fxaaConsoleEdgeThresholdMin
// fxaaQualityEdgeThresholdMin
// In order to insure AA does not get turned off on colors
// which contain a minor amount of green.
//
// 1 = On.
// 0 = Off.
//
#define FXAA_GREEN_AS_LUMA 1
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_EARLY_EXIT
//
// Controls algorithm's early exit path.
// On PS3 turning this ON adds 2 cycles to the shader.
// On 360 turning this OFF adds 10ths of a millisecond to the shader.
// Turning this off on console will result in a more blurry image.
// So this defaults to on.
//
// 1 = On.
// 0 = Off.
//
#define FXAA_EARLY_EXIT 1
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_DISCARD
//
// Only valid for PC OpenGL currently.
// Probably will not work when FXAA_GREEN_AS_LUMA = 1.
//
// 1 = Use discard on pixels which don't need AA.
// For APIs which enable concurrent TEX+ROP from same surface.
// 0 = Return unchanged color on pixels which don't need AA.
//
#define FXAA_DISCARD 0
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_FAST_PIXEL_OFFSET
//
// Used for GLSL 120 only.
//
// 1 = GL API supports fast pixel offsets
// 0 = do not use fast pixel offsets
//
#ifdef GL_EXT_gpu_shader4
#define FXAA_FAST_PIXEL_OFFSET 1
#endif
#ifdef GL_NV_gpu_shader5
#define FXAA_FAST_PIXEL_OFFSET 1
#endif
#ifdef GL_ARB_gpu_shader5
#define FXAA_FAST_PIXEL_OFFSET 1
#endif
#ifndef FXAA_FAST_PIXEL_OFFSET
#define FXAA_FAST_PIXEL_OFFSET 0
#endif
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_GATHER4_ALPHA
//
// 1 = API supports gather4 on alpha channel.
// 0 = API does not support gather4 on alpha channel.
//
#if (FXAA_HLSL_5 == 1)
#define FXAA_GATHER4_ALPHA 1
#endif
#ifdef GL_ARB_gpu_shader5
#define FXAA_GATHER4_ALPHA 1
#endif
#ifdef GL_NV_gpu_shader5
#define FXAA_GATHER4_ALPHA 1
#endif
#ifndef FXAA_GATHER4_ALPHA
#define FXAA_GATHER4_ALPHA 0
#endif
#endif
/*============================================================================
FXAA CONSOLE PS3 - TUNING KNOBS
============================================================================*/
#ifndef FXAA_CONSOLE__PS3_EDGE_SHARPNESS
//
// Consoles the sharpness of edges on PS3 only.
// Non-PS3 tuning is done with shader input.
//
// Due to the PS3 being ALU bound,
// there are only two safe values here: 4 and 8.
// These options use the shaders ability to a free *|/ by 2|4|8.
//
// 8.0 is sharper
// 4.0 is softer
// 2.0 is really soft (good for vector graphics inputs)
//
#if 1
#define FXAA_CONSOLE__PS3_EDGE_SHARPNESS 8.0
#endif
#if 0
#define FXAA_CONSOLE__PS3_EDGE_SHARPNESS 4.0
#endif
#if 0
#define FXAA_CONSOLE__PS3_EDGE_SHARPNESS 2.0
#endif
#endif
/*--------------------------------------------------------------------------*/
#ifndef FXAA_CONSOLE__PS3_EDGE_THRESHOLD
//
// Only effects PS3.
// Non-PS3 tuning is done with shader input.
//
// The minimum amount of local contrast required to apply algorithm.
// The console setting has a different mapping than the quality setting.
//
// This only applies when FXAA_EARLY_EXIT is 1.
//
// Due to the PS3 being ALU bound,
// there are only two safe values here: 0.25 and 0.125.
// These options use the shaders ability to a free *|/ by 2|4|8.
//
// 0.125 leaves less aliasing, but is softer
// 0.25 leaves more aliasing, and is sharper
//
#if 1
#define FXAA_CONSOLE__PS3_EDGE_THRESHOLD 0.125
#else
#define FXAA_CONSOLE__PS3_EDGE_THRESHOLD 0.25
#endif
#endif
/*============================================================================
FXAA QUALITY - TUNING KNOBS
------------------------------------------------------------------------------
NOTE the other tuning knobs are now in the shader function inputs!
============================================================================*/
#ifndef FXAA_QUALITY__PRESET
//
// Choose the quality preset.
// This needs to be compiled into the shader as it effects code.
// Best option to include multiple presets is to
// in each shader define the preset, then include this file.
//
// OPTIONS
// -----------------------------------------------------------------------
// 10 to 15 - default medium dither (10=fastest, 15=highest quality)
// 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality)
// 39 - no dither, very expensive
//
// NOTES
// -----------------------------------------------------------------------
// 12 = slightly faster then FXAA 3.9 and higher edge quality (default)
// 13 = about same speed as FXAA 3.9 and better than 12
// 23 = closest to FXAA 3.9 visually and performance wise
// _ = the lowest digit is directly related to performance
// _ = the highest digit is directly related to style
//
#define FXAA_QUALITY__PRESET 12
#endif
/*============================================================================
FXAA QUALITY - PRESETS
============================================================================*/
/*============================================================================
FXAA QUALITY - MEDIUM DITHER PRESETS
============================================================================*/
#if (FXAA_QUALITY__PRESET == 10)
#define FXAA_QUALITY__PS 3
#define FXAA_QUALITY__P0 1.5
#define FXAA_QUALITY__P1 3.0
#define FXAA_QUALITY__P2 12.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 11)
#define FXAA_QUALITY__PS 4
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 3.0
#define FXAA_QUALITY__P3 12.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 12)
#define FXAA_QUALITY__PS 5
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 4.0
#define FXAA_QUALITY__P4 12.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 13)
#define FXAA_QUALITY__PS 6
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 4.0
#define FXAA_QUALITY__P5 12.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 14)
#define FXAA_QUALITY__PS 7
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 2.0
#define FXAA_QUALITY__P5 4.0
#define FXAA_QUALITY__P6 12.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 15)
#define FXAA_QUALITY__PS 8
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 2.0
#define FXAA_QUALITY__P5 2.0
#define FXAA_QUALITY__P6 4.0
#define FXAA_QUALITY__P7 12.0
#endif
/*============================================================================
FXAA QUALITY - LOW DITHER PRESETS
============================================================================*/
#if (FXAA_QUALITY__PRESET == 20)
#define FXAA_QUALITY__PS 3
#define FXAA_QUALITY__P0 1.5
#define FXAA_QUALITY__P1 2.0
#define FXAA_QUALITY__P2 8.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 21)
#define FXAA_QUALITY__PS 4
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 8.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 22)
#define FXAA_QUALITY__PS 5
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 8.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 23)
#define FXAA_QUALITY__PS 6
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 2.0
#define FXAA_QUALITY__P5 8.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 24)
#define FXAA_QUALITY__PS 7
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 2.0
#define FXAA_QUALITY__P5 3.0
#define FXAA_QUALITY__P6 8.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 25)
#define FXAA_QUALITY__PS 8
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 2.0
#define FXAA_QUALITY__P5 2.0
#define FXAA_QUALITY__P6 4.0
#define FXAA_QUALITY__P7 8.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 26)
#define FXAA_QUALITY__PS 9
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 2.0
#define FXAA_QUALITY__P5 2.0
#define FXAA_QUALITY__P6 2.0
#define FXAA_QUALITY__P7 4.0
#define FXAA_QUALITY__P8 8.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 27)
#define FXAA_QUALITY__PS 10
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 2.0
#define FXAA_QUALITY__P5 2.0
#define FXAA_QUALITY__P6 2.0
#define FXAA_QUALITY__P7 2.0
#define FXAA_QUALITY__P8 4.0
#define FXAA_QUALITY__P9 8.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 28)
#define FXAA_QUALITY__PS 11
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 2.0
#define FXAA_QUALITY__P5 2.0
#define FXAA_QUALITY__P6 2.0
#define FXAA_QUALITY__P7 2.0
#define FXAA_QUALITY__P8 2.0
#define FXAA_QUALITY__P9 4.0
#define FXAA_QUALITY__P10 8.0
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PRESET == 29)
#define FXAA_QUALITY__PS 12
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.5
#define FXAA_QUALITY__P2 2.0
#define FXAA_QUALITY__P3 2.0
#define FXAA_QUALITY__P4 2.0
#define FXAA_QUALITY__P5 2.0
#define FXAA_QUALITY__P6 2.0
#define FXAA_QUALITY__P7 2.0
#define FXAA_QUALITY__P8 2.0
#define FXAA_QUALITY__P9 2.0
#define FXAA_QUALITY__P10 4.0
#define FXAA_QUALITY__P11 8.0
#endif
/*============================================================================
FXAA QUALITY - EXTREME QUALITY
============================================================================*/
#if (FXAA_QUALITY__PRESET == 39)
#define FXAA_QUALITY__PS 12
#define FXAA_QUALITY__P0 1.0
#define FXAA_QUALITY__P1 1.0
#define FXAA_QUALITY__P2 1.0
#define FXAA_QUALITY__P3 1.0
#define FXAA_QUALITY__P4 1.0
#define FXAA_QUALITY__P5 1.5
#define FXAA_QUALITY__P6 2.0
#define FXAA_QUALITY__P7 2.0
#define FXAA_QUALITY__P8 2.0
#define FXAA_QUALITY__P9 2.0
#define FXAA_QUALITY__P10 4.0
#define FXAA_QUALITY__P11 8.0
#endif
/*============================================================================
API PORTING
============================================================================*/
#if (FXAA_GLSL_120 == 1) || (FXAA_GLSL_130 == 1)
#define FxaaBool bool
#define FxaaDiscard discard
#define FxaaFloat float
#define FxaaFloat2 vec2
#define FxaaFloat3 vec3
#define FxaaFloat4 vec4
#define FxaaHalf float
#define FxaaHalf2 vec2
#define FxaaHalf3 vec3
#define FxaaHalf4 vec4
#define FxaaInt2 ivec2
#define FxaaSat(x) clamp(x, 0.0, 1.0)
#define FxaaTex sampler2D
#else
#define FxaaBool bool
#define FxaaDiscard clip(-1)
#define FxaaFloat float
#define FxaaFloat2 float2
#define FxaaFloat3 float3
#define FxaaFloat4 float4
#define FxaaHalf half
#define FxaaHalf2 half2
#define FxaaHalf3 half3
#define FxaaHalf4 half4
#define FxaaSat(x) saturate(x)
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_GLSL_120 == 1)
// Requires,
// #version 120
// And at least,
// #extension GL_EXT_gpu_shader4 : enable
// (or set FXAA_FAST_PIXEL_OFFSET 1 to work like DX9)
#define FxaaTexTop(t, p) texture2DLod(t, p, 0.0)
#if (FXAA_FAST_PIXEL_OFFSET == 1)
#define FxaaTexOff(t, p, o, r) texture2DLodOffset(t, p, 0.0, o)
#else
#define FxaaTexOff(t, p, o, r) texture2DLod(t, p + (o * r), 0.0)
#endif
#if (FXAA_GATHER4_ALPHA == 1)
// use #extension GL_ARB_gpu_shader5 : enable
#define FxaaTexAlpha4(t, p) textureGather(t, p, 3)
#define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3)
#define FxaaTexGreen4(t, p) textureGather(t, p, 1)
#define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1)
#endif
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_GLSL_130 == 1)
// Requires "#version 130" or better
#define FxaaTexTop(t, p) textureLod(t, p, 0.0)
#define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o)
#if (FXAA_GATHER4_ALPHA == 1)
// use #extension GL_ARB_gpu_shader5 : enable
#define FxaaTexAlpha4(t, p) textureGather(t, p, 3)
#define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3)
#define FxaaTexGreen4(t, p) textureGather(t, p, 1)
#define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1)
#endif
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_HLSL_3 == 1) || (FXAA_360 == 1) || (FXAA_PS3 == 1)
#define FxaaInt2 float2
#define FxaaTex sampler2D
#define FxaaTexTop(t, p) tex2Dlod(t, float4(p, 0.0, 0.0))
#define FxaaTexOff(t, p, o, r) tex2Dlod(t, float4(p + (o * r), 0, 0))
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_HLSL_4 == 1)
#define FxaaInt2 int2
struct FxaaTex { SamplerState smpl; Texture2D tex; };
#define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0)
#define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o)
#endif
/*--------------------------------------------------------------------------*/
#if (FXAA_HLSL_5 == 1)
#define FxaaInt2 int2
struct FxaaTex { SamplerState smpl; Texture2D tex; };
#define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0)
#define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o)
#define FxaaTexAlpha4(t, p) t.tex.GatherAlpha(t.smpl, p)
#define FxaaTexOffAlpha4(t, p, o) t.tex.GatherAlpha(t.smpl, p, o)
#define FxaaTexGreen4(t, p) t.tex.GatherGreen(t.smpl, p)
#define FxaaTexOffGreen4(t, p, o) t.tex.GatherGreen(t.smpl, p, o)
#endif
/*============================================================================
GREEN AS LUMA OPTION SUPPORT FUNCTION
============================================================================*/
#if (FXAA_GREEN_AS_LUMA == 0)
FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.w; }
#else
FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.y; }
#endif
/*============================================================================
FXAA3 QUALITY - PC
============================================================================*/
#if (FXAA_PC == 1)
/*--------------------------------------------------------------------------*/
FxaaFloat4 FxaaPixelShader(
//
// Use noperspective interpolation here (turn off perspective interpolation).
// {xy} = center of pixel
FxaaFloat2 pos,
//
// Used only for FXAA Console, and not used on the 360 version.
// Use noperspective interpolation here (turn off perspective interpolation).
// {xy__} = upper left of pixel
// {__zw} = lower right of pixel
FxaaFloat4 fxaaConsolePosPos,
//
// Input color texture.
// {rgb_} = color in linear or perceptual color space
// if (FXAA_GREEN_AS_LUMA == 0)
// {___a} = luma in perceptual color space (not linear)
FxaaTex tex,
//
// Only used on the optimized 360 version of FXAA Console.
// For everything but 360, just use the same input here as for "tex".
// For 360, same texture, just alias with a 2nd sampler.
// This sampler needs to have an exponent bias of -1.
FxaaTex fxaaConsole360TexExpBiasNegOne,
//
// Only used on the optimized 360 version of FXAA Console.
// For everything but 360, just use the same input here as for "tex".
// For 360, same texture, just alias with a 3nd sampler.
// This sampler needs to have an exponent bias of -2.
FxaaTex fxaaConsole360TexExpBiasNegTwo,
//
// Only used on FXAA Quality.
// This must be from a constant/uniform.
// {x_} = 1.0/screenWidthInPixels
// {_y} = 1.0/screenHeightInPixels
FxaaFloat2 fxaaQualityRcpFrame,
//
// Only used on FXAA Console.
// This must be from a constant/uniform.
// This effects sub-pixel AA quality and inversely sharpness.
// Where N ranges between,
// N = 0.50 (default)
// N = 0.33 (sharper)
// {x___} = -N/screenWidthInPixels
// {_y__} = -N/screenHeightInPixels
// {__z_} = N/screenWidthInPixels
// {___w} = N/screenHeightInPixels
FxaaFloat4 fxaaConsoleRcpFrameOpt,
//
// Only used on FXAA Console.
// Not used on 360, but used on PS3 and PC.
// This must be from a constant/uniform.
// {x___} = -2.0/screenWidthInPixels
// {_y__} = -2.0/screenHeightInPixels
// {__z_} = 2.0/screenWidthInPixels
// {___w} = 2.0/screenHeightInPixels
FxaaFloat4 fxaaConsoleRcpFrameOpt2,
//
// Only used on FXAA Console.
// Only used on 360 in place of fxaaConsoleRcpFrameOpt2.
// This must be from a constant/uniform.
// {x___} = 8.0/screenWidthInPixels
// {_y__} = 8.0/screenHeightInPixels
// {__z_} = -4.0/screenWidthInPixels
// {___w} = -4.0/screenHeightInPixels
FxaaFloat4 fxaaConsole360RcpFrameOpt2,
//
// Only used on FXAA Quality.
// This used to be the FXAA_QUALITY__SUBPIX define.
// It is here now to allow easier tuning.
// Choose the amount of sub-pixel aliasing removal.
// This can effect sharpness.
// 1.00 - upper limit (softer)
// 0.75 - default amount of filtering
// 0.50 - lower limit (sharper, less sub-pixel aliasing removal)
// 0.25 - almost off
// 0.00 - completely off
FxaaFloat fxaaQualitySubpix,
//
// Only used on FXAA Quality.
// This used to be the FXAA_QUALITY__EDGE_THRESHOLD define.
// It is here now to allow easier tuning.
// The minimum amount of local contrast required to apply algorithm.
// 0.333 - too little (faster)
// 0.250 - low quality
// 0.166 - default
// 0.125 - high quality
// 0.063 - overkill (slower)
FxaaFloat fxaaQualityEdgeThreshold,
//
// Only used on FXAA Quality.
// This used to be the FXAA_QUALITY__EDGE_THRESHOLD_MIN define.
// It is here now to allow easier tuning.
// Trims the algorithm from processing darks.
// 0.0833 - upper limit (default, the start of visible unfiltered edges)
// 0.0625 - high quality (faster)
// 0.0312 - visible limit (slower)
// Special notes when using FXAA_GREEN_AS_LUMA,
// Likely want to set this to zero.
// As colors that are mostly not-green
// will appear very dark in the green channel!
// Tune by looking at mostly non-green content,
// then start at zero and increase until aliasing is a problem.
FxaaFloat fxaaQualityEdgeThresholdMin,
//
// Only used on FXAA Console.
// This used to be the FXAA_CONSOLE__EDGE_SHARPNESS define.
// It is here now to allow easier tuning.
// This does not effect PS3, as this needs to be compiled in.
// Use FXAA_CONSOLE__PS3_EDGE_SHARPNESS for PS3.
// Due to the PS3 being ALU bound,
// there are only three safe values here: 2 and 4 and 8.
// These options use the shaders ability to a free *|/ by 2|4|8.
// For all other platforms can be a non-power of two.
// 8.0 is sharper (default!!!)
// 4.0 is softer
// 2.0 is really soft (good only for vector graphics inputs)
FxaaFloat fxaaConsoleEdgeSharpness,
//
// Only used on FXAA Console.
// This used to be the FXAA_CONSOLE__EDGE_THRESHOLD define.
// It is here now to allow easier tuning.
// This does not effect PS3, as this needs to be compiled in.
// Use FXAA_CONSOLE__PS3_EDGE_THRESHOLD for PS3.
// Due to the PS3 being ALU bound,
// there are only two safe values here: 1/4 and 1/8.
// These options use the shaders ability to a free *|/ by 2|4|8.
// The console setting has a different mapping than the quality setting.
// Other platforms can use other values.
// 0.125 leaves less aliasing, but is softer (default!!!)
// 0.25 leaves more aliasing, and is sharper
FxaaFloat fxaaConsoleEdgeThreshold,
//
// Only used on FXAA Console.
// This used to be the FXAA_CONSOLE__EDGE_THRESHOLD_MIN define.
// It is here now to allow easier tuning.
// Trims the algorithm from processing darks.
// The console setting has a different mapping than the quality setting.
// This only applies when FXAA_EARLY_EXIT is 1.
// This does not apply to PS3,
// PS3 was simplified to avoid more shader instructions.
// 0.06 - faster but more aliasing in darks
// 0.05 - default
// 0.04 - slower and less aliasing in darks
// Special notes when using FXAA_GREEN_AS_LUMA,
// Likely want to set this to zero.
// As colors that are mostly not-green
// will appear very dark in the green channel!
// Tune by looking at mostly non-green content,
// then start at zero and increase until aliasing is a problem.
FxaaFloat fxaaConsoleEdgeThresholdMin,
//
// Extra constants for 360 FXAA Console only.
// Use zeros or anything else for other platforms.
// These must be in physical constant registers and NOT immedates.
// Immedates will result in compiler un-optimizing.
// {xyzw} = float4(1.0, -1.0, 0.25, -0.25)
FxaaFloat4 fxaaConsole360ConstDir
) {
/*--------------------------------------------------------------------------*/
FxaaFloat2 posM;
posM.x = pos.x;
posM.y = pos.y;
#if (FXAA_GATHER4_ALPHA == 1)
#if (FXAA_DISCARD == 0)
FxaaFloat4 rgbyM = FxaaTexTop(tex, posM);
#if (FXAA_GREEN_AS_LUMA == 0)
#define lumaM rgbyM.w
#else
#define lumaM rgbyM.y
#endif
#endif
#if (FXAA_GREEN_AS_LUMA == 0)
FxaaFloat4 luma4A = FxaaTexAlpha4(tex, posM);
FxaaFloat4 luma4B = FxaaTexOffAlpha4(tex, posM, FxaaInt2(-1, -1));
#else
FxaaFloat4 luma4A = FxaaTexGreen4(tex, posM);
FxaaFloat4 luma4B = FxaaTexOffGreen4(tex, posM, FxaaInt2(-1, -1));
#endif
#if (FXAA_DISCARD == 1)
#define lumaM luma4A.w
#endif
#define lumaE luma4A.z
#define lumaS luma4A.x
#define lumaSE luma4A.y
#define lumaNW luma4B.w
#define lumaN luma4B.z
#define lumaW luma4B.x
#else
FxaaFloat4 rgbyM = FxaaTexTop(tex, posM);
#if (FXAA_GREEN_AS_LUMA == 0)
#define lumaM rgbyM.w
#else
#define lumaM rgbyM.y
#endif
FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy));
FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy));
#endif
/*--------------------------------------------------------------------------*/
FxaaFloat maxSM = max(lumaS, lumaM);
FxaaFloat minSM = min(lumaS, lumaM);
FxaaFloat maxESM = max(lumaE, maxSM);
FxaaFloat minESM = min(lumaE, minSM);
FxaaFloat maxWN = max(lumaN, lumaW);
FxaaFloat minWN = min(lumaN, lumaW);
FxaaFloat rangeMax = max(maxWN, maxESM);
FxaaFloat rangeMin = min(minWN, minESM);
FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold;
FxaaFloat range = rangeMax - rangeMin;
FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled);
FxaaBool earlyExit = range < rangeMaxClamped;
/*--------------------------------------------------------------------------*/
if (earlyExit)
{
#if (FXAA_DISCARD == 1)
FxaaDiscard;
#else
return rgbyM;
#endif
}
else
{
/*--------------------------------------------------------------------------*/
#if (FXAA_GATHER4_ALPHA == 0)
FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));
#else
FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, -1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));
#endif
/*--------------------------------------------------------------------------*/
FxaaFloat lumaNS = lumaN + lumaS;
FxaaFloat lumaWE = lumaW + lumaE;
FxaaFloat subpixRcpRange = 1.0 / range;
FxaaFloat subpixNSWE = lumaNS + lumaWE;
FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS;
FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE;
/*--------------------------------------------------------------------------*/
FxaaFloat lumaNESE = lumaNE + lumaSE;
FxaaFloat lumaNWNE = lumaNW + lumaNE;
FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE;
FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE;
/*--------------------------------------------------------------------------*/
FxaaFloat lumaNWSW = lumaNW + lumaSW;
FxaaFloat lumaSWSE = lumaSW + lumaSE;
FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2);
FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2);
FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW;
FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE;
FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4;
FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4;
/*--------------------------------------------------------------------------*/
FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE;
FxaaFloat lengthSign = fxaaQualityRcpFrame.x;
FxaaBool horzSpan = edgeHorz >= edgeVert;
FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE;
/*--------------------------------------------------------------------------*/
if (!horzSpan) lumaN = lumaW;
if (!horzSpan) lumaS = lumaE;
if (horzSpan)
lengthSign = fxaaQualityRcpFrame.y;
FxaaFloat subpixB = (subpixA * (1.0 / 12.0)) - lumaM;
/*--------------------------------------------------------------------------*/
FxaaFloat gradientN = lumaN - lumaM;
FxaaFloat gradientS = lumaS - lumaM;
FxaaFloat lumaNN = lumaN + lumaM;
FxaaFloat lumaSS = lumaS + lumaM;
FxaaBool pairN = abs(gradientN) >= abs(gradientS);
FxaaFloat gradient = max(abs(gradientN), abs(gradientS));
if (pairN)
lengthSign = -lengthSign;
FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange);
/*--------------------------------------------------------------------------*/
FxaaFloat2 posB;
posB.x = posM.x;
posB.y = posM.y;
FxaaFloat2 offNP;
offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;
offNP.y = (horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;
if (!horzSpan)
posB.x += lengthSign * 0.5;
if (horzSpan)
posB.y += lengthSign * 0.5;
/*--------------------------------------------------------------------------*/
FxaaFloat2 posN;
posN.x = posB.x - offNP.x * FXAA_QUALITY__P0;
posN.y = posB.y - offNP.y * FXAA_QUALITY__P0;
FxaaFloat2 posP;
posP.x = posB.x + offNP.x * FXAA_QUALITY__P0;
posP.y = posB.y + offNP.y * FXAA_QUALITY__P0;
FxaaFloat subpixD = ((-2.0) * subpixC) + 3.0;
FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN));
FxaaFloat subpixE = subpixC * subpixC;
FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP));
/*--------------------------------------------------------------------------*/
if (!pairN)
lumaNN = lumaSS;
FxaaFloat gradientScaled = gradient * 1.0 / 4.0;
FxaaFloat lumaMM = lumaM - lumaNN * 0.5;
FxaaFloat subpixF = subpixD * subpixE;
FxaaBool lumaMLTZero = lumaMM < 0.0;
/*--------------------------------------------------------------------------*/
lumaEndN -= lumaNN * 0.5;
lumaEndP -= lumaNN * 0.5;
FxaaBool doneN = abs(lumaEndN) >= gradientScaled;
FxaaBool doneP = abs(lumaEndP) >= gradientScaled;
if (!doneN)
posN.x -= offNP.x * FXAA_QUALITY__P1;
if (!doneN)
posN.y -= offNP.y * FXAA_QUALITY__P1;
FxaaBool doneNP = (!doneN) || (!doneP);
if (!doneP)
posP.x += offNP.x * FXAA_QUALITY__P1;
if (!doneP)
posP.y += offNP.y * FXAA_QUALITY__P1;
/*--------------------------------------------------------------------------*/
if (doneNP)
{
if (!doneN)
lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if (!doneP)
lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if (!doneN)
lumaEndN = lumaEndN - lumaNN * 0.5;
if (!doneP)
lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if (!doneN)
posN.x -= offNP.x * FXAA_QUALITY__P2;
if (!doneN)
posN.y -= offNP.y * FXAA_QUALITY__P2;
doneNP = (!doneN) || (!doneP);
if (!doneP)
posP.x += offNP.x * FXAA_QUALITY__P2;
if (!doneP)
posP.y += offNP.y * FXAA_QUALITY__P2;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PS > 3)
if (doneNP)
{
if (!doneN)
lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if (!doneP)
lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if (!doneN)
lumaEndN = lumaEndN - lumaNN * 0.5;
if (!doneP)
lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if (!doneN)
posN.x -= offNP.x * FXAA_QUALITY__P3;
if (!doneN)
posN.y -= offNP.y * FXAA_QUALITY__P3;
doneNP = (!doneN) || (!doneP);
if (!doneP)
posP.x += offNP.x * FXAA_QUALITY__P3;
if (!doneP)
posP.y += offNP.y * FXAA_QUALITY__P3;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PS > 4)
if (doneNP)
{
if (!doneN)
lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if (!doneP)
lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if (!doneN)
lumaEndN = lumaEndN - lumaNN * 0.5;
if (!doneP)
lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if (!doneN)
posN.x -= offNP.x * FXAA_QUALITY__P4;
if (!doneN)
posN.y -= offNP.y * FXAA_QUALITY__P4;
doneNP = (!doneN) || (!doneP);
if (!doneP)
posP.x += offNP.x * FXAA_QUALITY__P4;
if (!doneP)
posP.y += offNP.y * FXAA_QUALITY__P4;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PS > 5)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P5;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P5;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P5;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P5;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PS > 6)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P6;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P6;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P6;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P6;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PS > 7)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P7;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P7;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P7;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P7;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PS > 8)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P8;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P8;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P8;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P8;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PS > 9)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P9;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P9;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P9;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P9;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PS > 10)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P10;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P10;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P10;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P10;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PS > 11)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P11;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P11;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P11;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P11;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY__PS > 12)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P12;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P12;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P12;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P12;
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
/*--------------------------------------------------------------------------*/
FxaaFloat dstN = posM.x - posN.x;
FxaaFloat dstP = posP.x - posM.x;
if(!horzSpan) dstN = posM.y - posN.y;
if(!horzSpan) dstP = posP.y - posM.y;
/*--------------------------------------------------------------------------*/
FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero;
FxaaFloat spanLength = (dstP + dstN);
FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero;
FxaaFloat spanLengthRcp = 1.0/spanLength;
/*--------------------------------------------------------------------------*/
FxaaBool directionN = dstN < dstP;
FxaaFloat dst = min(dstN, dstP);
FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP;
FxaaFloat subpixG = subpixF * subpixF;
FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5;
FxaaFloat subpixH = subpixG * fxaaQualitySubpix;
/*--------------------------------------------------------------------------*/
FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0;
FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH);
if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign;
if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign;
#if (FXAA_DISCARD == 1)
return FxaaTexTop(tex, posM);
#else
return FxaaFloat4(FxaaTexTop(tex, posM).xyz, lumaM);
#endif
}
}
/*==========================================================================*/
#endif
/*============================================================================
FXAA3 CONSOLE - PC VERSION
------------------------------------------------------------------------------
Instead of using this on PC, I'd suggest just using FXAA Quality with
#define FXAA_QUALITY__PRESET 10
Or
#define FXAA_QUALITY__PRESET 20
Either are higher qualilty and almost as fast as this on modern PC GPUs.
============================================================================*/
#if (FXAA_PC_CONSOLE == 1)
/*--------------------------------------------------------------------------*/
FxaaFloat4 FxaaPixelShader(
// See FXAA Quality FxaaPixelShader() source for docs on Inputs!
FxaaFloat2 pos,
FxaaFloat4 fxaaConsolePosPos,
FxaaTex tex,
FxaaTex fxaaConsole360TexExpBiasNegOne,
FxaaTex fxaaConsole360TexExpBiasNegTwo,
FxaaFloat2 fxaaQualityRcpFrame,
FxaaFloat4 fxaaConsoleRcpFrameOpt,
FxaaFloat4 fxaaConsoleRcpFrameOpt2,
FxaaFloat4 fxaaConsole360RcpFrameOpt2,
FxaaFloat fxaaQualitySubpix,
FxaaFloat fxaaQualityEdgeThreshold,
FxaaFloat fxaaQualityEdgeThresholdMin,
FxaaFloat fxaaConsoleEdgeSharpness,
FxaaFloat fxaaConsoleEdgeThreshold,
FxaaFloat fxaaConsoleEdgeThresholdMin,
FxaaFloat4 fxaaConsole360ConstDir
) {
/*--------------------------------------------------------------------------*/
FxaaFloat lumaNw = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.xy));
FxaaFloat lumaSw = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.xw));
FxaaFloat lumaNe = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.zy));
FxaaFloat lumaSe = FxaaLuma(FxaaTexTop(tex, fxaaConsolePosPos.zw));
/*--------------------------------------------------------------------------*/
FxaaFloat4 rgbyM = FxaaTexTop(tex, pos.xy);
#if (FXAA_GREEN_AS_LUMA == 0)
FxaaFloat lumaM = rgbyM.w;
#else
FxaaFloat lumaM = rgbyM.y;
#endif
/*--------------------------------------------------------------------------*/
FxaaFloat lumaMaxNwSw = max(lumaNw, lumaSw);
lumaNe += 1.0/384.0;
FxaaFloat lumaMinNwSw = min(lumaNw, lumaSw);
/*--------------------------------------------------------------------------*/
FxaaFloat lumaMaxNeSe = max(lumaNe, lumaSe);
FxaaFloat lumaMinNeSe = min(lumaNe, lumaSe);
/*--------------------------------------------------------------------------*/
FxaaFloat lumaMax = max(lumaMaxNeSe, lumaMaxNwSw);
FxaaFloat lumaMin = min(lumaMinNeSe, lumaMinNwSw);
/*--------------------------------------------------------------------------*/
FxaaFloat lumaMaxScaled = lumaMax * fxaaConsoleEdgeThreshold;
/*--------------------------------------------------------------------------*/
FxaaFloat lumaMinM = min(lumaMin, lumaM);
FxaaFloat lumaMaxScaledClamped = max(fxaaConsoleEdgeThresholdMin, lumaMaxScaled);
FxaaFloat lumaMaxM = max(lumaMax, lumaM);
FxaaFloat dirSwMinusNe = lumaSw - lumaNe;
FxaaFloat lumaMaxSubMinM = lumaMaxM - lumaMinM;
FxaaFloat dirSeMinusNw = lumaSe - lumaNw;
if(lumaMaxSubMinM < lumaMaxScaledClamped) return rgbyM;
/*--------------------------------------------------------------------------*/
FxaaFloat2 dir;
dir.x = dirSwMinusNe + dirSeMinusNw;
dir.y = dirSwMinusNe - dirSeMinusNw;
/*--------------------------------------------------------------------------*/
FxaaFloat2 dir1 = normalize(dir.xy);
FxaaFloat4 rgbyN1 = FxaaTexTop(tex, pos.xy - dir1 * fxaaConsoleRcpFrameOpt.zw);
FxaaFloat4 rgbyP1 = FxaaTexTop(tex, pos.xy + dir1 * fxaaConsoleRcpFrameOpt.zw);
/*--------------------------------------------------------------------------*/
FxaaFloat dirAbsMinTimesC = min(abs(dir1.x), abs(dir1.y)) * fxaaConsoleEdgeSharpness;
FxaaFloat2 dir2 = clamp(dir1.xy / dirAbsMinTimesC, -2.0, 2.0);
/*--------------------------------------------------------------------------*/
FxaaFloat4 rgbyN2 = FxaaTexTop(tex, pos.xy - dir2 * fxaaConsoleRcpFrameOpt2.zw);
FxaaFloat4 rgbyP2 = FxaaTexTop(tex, pos.xy + dir2 * fxaaConsoleRcpFrameOpt2.zw);
/*--------------------------------------------------------------------------*/
FxaaFloat4 rgbyA = rgbyN1 + rgbyP1;
FxaaFloat4 rgbyB = ((rgbyN2 + rgbyP2) * 0.25) + (rgbyA * 0.25);
/*--------------------------------------------------------------------------*/
#if (FXAA_GREEN_AS_LUMA == 0)
FxaaBool twoTap = (rgbyB.w < lumaMin) || (rgbyB.w > lumaMax);
#else
FxaaBool twoTap = (rgbyB.y < lumaMin) || (rgbyB.y > lumaMax);
#endif
if(twoTap) rgbyB.xyz = rgbyA.xyz * 0.5;
return rgbyB; }
/*==========================================================================*/
#endif
/*============================================================================
FXAA3 CONSOLE - 360 PIXEL SHADER
------------------------------------------------------------------------------
This optimized version thanks to suggestions from Andy Luedke.
Should be fully tex bound in all cases.
As of the FXAA 3.11 release, I have still not tested this code,
however I fixed a bug which was in both FXAA 3.9 and FXAA 3.10.
And note this is replacing the old unoptimized version.
If it does not work, please let me know so I can fix it.
============================================================================*/
#if (FXAA_360 == 1)
/*--------------------------------------------------------------------------*/
[reduceTempRegUsage(4)]
float4 FxaaPixelShader(
// See FXAA Quality FxaaPixelShader() source for docs on Inputs!
FxaaFloat2 pos,
FxaaFloat4 fxaaConsolePosPos,
FxaaTex tex,
FxaaTex fxaaConsole360TexExpBiasNegOne,
FxaaTex fxaaConsole360TexExpBiasNegTwo,
FxaaFloat2 fxaaQualityRcpFrame,
FxaaFloat4 fxaaConsoleRcpFrameOpt,
FxaaFloat4 fxaaConsoleRcpFrameOpt2,
FxaaFloat4 fxaaConsole360RcpFrameOpt2,
FxaaFloat fxaaQualitySubpix,
FxaaFloat fxaaQualityEdgeThreshold,
FxaaFloat fxaaQualityEdgeThresholdMin,
FxaaFloat fxaaConsoleEdgeSharpness,
FxaaFloat fxaaConsoleEdgeThreshold,
FxaaFloat fxaaConsoleEdgeThresholdMin,
FxaaFloat4 fxaaConsole360ConstDir
) {
/*--------------------------------------------------------------------------*/
float4 lumaNwNeSwSe;
#if (FXAA_GREEN_AS_LUMA == 0)
asm {
tfetch2D lumaNwNeSwSe.w___, tex, pos.xy, OffsetX = -0.5, OffsetY = -0.5, UseComputedLOD=false
tfetch2D lumaNwNeSwSe._w__, tex, pos.xy, OffsetX = 0.5, OffsetY = -0.5, UseComputedLOD=false
tfetch2D lumaNwNeSwSe.__w_, tex, pos.xy, OffsetX = -0.5, OffsetY = 0.5, UseComputedLOD=false
tfetch2D lumaNwNeSwSe.___w, tex, pos.xy, OffsetX = 0.5, OffsetY = 0.5, UseComputedLOD=false
};
#else
asm {
tfetch2D lumaNwNeSwSe.y___, tex, pos.xy, OffsetX = -0.5, OffsetY = -0.5, UseComputedLOD=false
tfetch2D lumaNwNeSwSe._y__, tex, pos.xy, OffsetX = 0.5, OffsetY = -0.5, UseComputedLOD=false
tfetch2D lumaNwNeSwSe.__y_, tex, pos.xy, OffsetX = -0.5, OffsetY = 0.5, UseComputedLOD=false
tfetch2D lumaNwNeSwSe.___y, tex, pos.xy, OffsetX = 0.5, OffsetY = 0.5, UseComputedLOD=false
};
#endif
/*--------------------------------------------------------------------------*/
lumaNwNeSwSe.y += 1.0/384.0;
float2 lumaMinTemp = min(lumaNwNeSwSe.xy, lumaNwNeSwSe.zw);
float2 lumaMaxTemp = max(lumaNwNeSwSe.xy, lumaNwNeSwSe.zw);
float lumaMin = min(lumaMinTemp.x, lumaMinTemp.y);
float lumaMax = max(lumaMaxTemp.x, lumaMaxTemp.y);
/*--------------------------------------------------------------------------*/
float4 rgbyM = tex2Dlod(tex, float4(pos.xy, 0.0, 0.0));
#if (FXAA_GREEN_AS_LUMA == 0)
float lumaMinM = min(lumaMin, rgbyM.w);
float lumaMaxM = max(lumaMax, rgbyM.w);
#else
float lumaMinM = min(lumaMin, rgbyM.y);
float lumaMaxM = max(lumaMax, rgbyM.y);
#endif
if((lumaMaxM - lumaMinM) < max(fxaaConsoleEdgeThresholdMin, lumaMax * fxaaConsoleEdgeThreshold)) return rgbyM;
/*--------------------------------------------------------------------------*/
float2 dir;
dir.x = dot(lumaNwNeSwSe, fxaaConsole360ConstDir.yyxx);
dir.y = dot(lumaNwNeSwSe, fxaaConsole360ConstDir.xyxy);
dir = normalize(dir);
/*--------------------------------------------------------------------------*/
float4 dir1 = dir.xyxy * fxaaConsoleRcpFrameOpt.xyzw;
/*--------------------------------------------------------------------------*/
float4 dir2;
float dirAbsMinTimesC = min(abs(dir.x), abs(dir.y)) * fxaaConsoleEdgeSharpness;
dir2 = saturate(fxaaConsole360ConstDir.zzww * dir.xyxy / dirAbsMinTimesC + 0.5);
dir2 = dir2 * fxaaConsole360RcpFrameOpt2.xyxy + fxaaConsole360RcpFrameOpt2.zwzw;
/*--------------------------------------------------------------------------*/
float4 rgbyN1 = tex2Dlod(fxaaConsole360TexExpBiasNegOne, float4(pos.xy + dir1.xy, 0.0, 0.0));
float4 rgbyP1 = tex2Dlod(fxaaConsole360TexExpBiasNegOne, float4(pos.xy + dir1.zw, 0.0, 0.0));
float4 rgbyN2 = tex2Dlod(fxaaConsole360TexExpBiasNegTwo, float4(pos.xy + dir2.xy, 0.0, 0.0));
float4 rgbyP2 = tex2Dlod(fxaaConsole360TexExpBiasNegTwo, float4(pos.xy + dir2.zw, 0.0, 0.0));
/*--------------------------------------------------------------------------*/
float4 rgbyA = rgbyN1 + rgbyP1;
float4 rgbyB = rgbyN2 + rgbyP2 + rgbyA * 0.5;
/*--------------------------------------------------------------------------*/
float4 rgbyR = ((FxaaLuma(rgbyB) - lumaMax) > 0.0) ? rgbyA : rgbyB;
rgbyR = ((FxaaLuma(rgbyB) - lumaMin) > 0.0) ? rgbyR : rgbyA;
return rgbyR; }
/*==========================================================================*/
#endif
/*============================================================================
FXAA3 CONSOLE - OPTIMIZED PS3 PIXEL SHADER (NO EARLY EXIT)
==============================================================================
The code below does not exactly match the assembly.
I have a feeling that 12 cycles is possible, but was not able to get there.
Might have to increase register count to get full performance.
Note this shader does not use perspective interpolation.
Use the following cgc options,
--fenable-bx2 --fastmath --fastprecision --nofloatbindings
------------------------------------------------------------------------------
NVSHADERPERF OUTPUT
------------------------------------------------------------------------------
For reference and to aid in debug, output of NVShaderPerf should match this,
Shader to schedule:
0: texpkb h0.w(TRUE), v5.zyxx, #0
2: addh h2.z(TRUE), h0.w, constant(0.001953, 0.000000, 0.000000, 0.000000).x
4: texpkb h0.w(TRUE), v5.xwxx, #0
6: addh h0.z(TRUE), -h2, h0.w
7: texpkb h1.w(TRUE), v5, #0
9: addh h0.x(TRUE), h0.z, -h1.w
10: addh h3.w(TRUE), h0.z, h1
11: texpkb h2.w(TRUE), v5.zwzz, #0
13: addh h0.z(TRUE), h3.w, -h2.w
14: addh h0.x(TRUE), h2.w, h0
15: nrmh h1.xz(TRUE), h0_n
16: minh_m8 h0.x(TRUE), |h1|, |h1.z|
17: maxh h4.w(TRUE), h0, h1
18: divx h2.xy(TRUE), h1_n.xzzw, h0_n
19: movr r1.zw(TRUE), v4.xxxy
20: madr r2.xz(TRUE), -h1, constant(cConst5.x, cConst5.y, cConst5.z, cConst5.w).zzww, r1.zzww
22: minh h5.w(TRUE), h0, h1
23: texpkb h0(TRUE), r2.xzxx, #0
25: madr r0.zw(TRUE), h1.xzxz, constant(cConst5.x, cConst5.y, cConst5.z, cConst5.w), r1
27: maxh h4.x(TRUE), h2.z, h2.w
28: texpkb h1(TRUE), r0.zwzz, #0
30: addh_d2 h1(TRUE), h0, h1
31: madr r0.xy(TRUE), -h2, constant(cConst5.x, cConst5.y, cConst5.z, cConst5.w).xyxx, r1.zwzz
33: texpkb h0(TRUE), r0, #0
35: minh h4.z(TRUE), h2, h2.w
36: fenct TRUE
37: madr r1.xy(TRUE), h2, constant(cConst5.x, cConst5.y, cConst5.z, cConst5.w).xyxx, r1.zwzz
39: texpkb h2(TRUE), r1, #0
41: addh_d2 h0(TRUE), h0, h2
42: maxh h2.w(TRUE), h4, h4.x
43: minh h2.x(TRUE), h5.w, h4.z
44: addh_d2 h0(TRUE), h0, h1
45: slth h2.x(TRUE), h0.w, h2
46: sgth h2.w(TRUE), h0, h2
47: movh h0(TRUE), h0
48: addx.c0 rc(TRUE), h2, h2.w
49: movh h0(c0.NE.x), h1
IPU0 ------ Simplified schedule: --------
Pass | Unit | uOp | PC: Op
-----+--------+------+-------------------------
1 | SCT0/1 | mov | 0: TXLr h0.w, g[TEX1].zyxx, const.xxxx, TEX0;
| TEX | txl | 0: TXLr h0.w, g[TEX1].zyxx, const.xxxx, TEX0;
| SCB1 | add | 2: ADDh h2.z, h0.--w-, const.--x-;
| | |
2 | SCT0/1 | mov | 4: TXLr h0.w, g[TEX1].xwxx, const.xxxx, TEX0;
| TEX | txl | 4: TXLr h0.w, g[TEX1].xwxx, const.xxxx, TEX0;
| SCB1 | add | 6: ADDh h0.z,-h2, h0.--w-;
| | |
3 | SCT0/1 | mov | 7: TXLr h1.w, g[TEX1], const.xxxx, TEX0;
| TEX | txl | 7: TXLr h1.w, g[TEX1], const.xxxx, TEX0;
| SCB0 | add | 9: ADDh h0.x, h0.z---,-h1.w---;
| SCB1 | add | 10: ADDh h3.w, h0.---z, h1;
| | |
4 | SCT0/1 | mov | 11: TXLr h2.w, g[TEX1].zwzz, const.xxxx, TEX0;
| TEX | txl | 11: TXLr h2.w, g[TEX1].zwzz, const.xxxx, TEX0;
| SCB0 | add | 14: ADDh h0.x, h2.w---, h0;
| SCB1 | add | 13: ADDh h0.z, h3.--w-,-h2.--w-;
| | |
5 | SCT1 | mov | 15: NRMh h1.xz, h0;
| SRB | nrm | 15: NRMh h1.xz, h0;
| SCB0 | min | 16: MINh*8 h0.x, |h1|, |h1.z---|;
| SCB1 | max | 17: MAXh h4.w, h0, h1;
| | |
6 | SCT0 | div | 18: DIVx h2.xy, h1.xz--, h0;
| SCT1 | mov | 19: MOVr r1.zw, g[TEX0].--xy;
| SCB0 | mad | 20: MADr r2.xz,-h1, const.z-w-, r1.z-w-;
| SCB1 | min | 22: MINh h5.w, h0, h1;
| | |
7 | SCT0/1 | mov | 23: TXLr h0, r2.xzxx, const.xxxx, TEX0;
| TEX | txl | 23: TXLr h0, r2.xzxx, const.xxxx, TEX0;
| SCB0 | max | 27: MAXh h4.x, h2.z---, h2.w---;
| SCB1 | mad | 25: MADr r0.zw, h1.--xz, const, r1;
| | |
8 | SCT0/1 | mov | 28: TXLr h1, r0.zwzz, const.xxxx, TEX0;
| TEX | txl | 28: TXLr h1, r0.zwzz, const.xxxx, TEX0;
| SCB0/1 | add | 30: ADDh/2 h1, h0, h1;
| | |
9 | SCT0 | mad | 31: MADr r0.xy,-h2, const.xy--, r1.zw--;
| SCT1 | mov | 33: TXLr h0, r0, const.zzzz, TEX0;
| TEX | txl | 33: TXLr h0, r0, const.zzzz, TEX0;
| SCB1 | min | 35: MINh h4.z, h2, h2.--w-;
| | |
10 | SCT0 | mad | 37: MADr r1.xy, h2, const.xy--, r1.zw--;
| SCT1 | mov | 39: TXLr h2, r1, const.zzzz, TEX0;
| TEX | txl | 39: TXLr h2, r1, const.zzzz, TEX0;
| SCB0/1 | add | 41: ADDh/2 h0, h0, h2;
| | |
11 | SCT0 | min | 43: MINh h2.x, h5.w---, h4.z---;
| SCT1 | max | 42: MAXh h2.w, h4, h4.---x;
| SCB0/1 | add | 44: ADDh/2 h0, h0, h1;
| | |
12 | SCT0 | set | 45: SLTh h2.x, h0.w---, h2;
| SCT1 | set | 46: SGTh h2.w, h0, h2;
| SCB0/1 | mul | 47: MOVh h0, h0;
| | |
13 | SCT0 | mad | 48: ADDxc0_s rc, h2, h2.w---;
| SCB0/1 | mul | 49: MOVh h0(NE0.xxxx), h1;
Pass SCT TEX SCB
1: 0% 100% 25%
2: 0% 100% 25%
3: 0% 100% 50%
4: 0% 100% 50%
5: 0% 0% 50%
6: 100% 0% 75%
7: 0% 100% 75%
8: 0% 100% 100%
9: 0% 100% 25%
10: 0% 100% 100%
11: 50% 0% 100%
12: 50% 0% 100%
13: 25% 0% 100%
MEAN: 17% 61% 67%
Pass SCT0 SCT1 TEX SCB0 SCB1
1: 0% 0% 100% 0% 100%
2: 0% 0% 100% 0% 100%
3: 0% 0% 100% 100% 100%
4: 0% 0% 100% 100% 100%
5: 0% 0% 0% 100% 100%
6: 100% 100% 0% 100% 100%
7: 0% 0% 100% 100% 100%
8: 0% 0% 100% 100% 100%
9: 0% 0% 100% 0% 100%
10: 0% 0% 100% 100% 100%
11: 100% 100% 0% 100% 100%
12: 100% 100% 0% 100% 100%
13: 100% 0% 0% 100% 100%
MEAN: 30% 23% 61% 76% 100%
Fragment Performance Setup: Driver RSX Compiler, GPU RSX, Flags 0x5
Results 13 cycles, 3 r regs, 923,076,923 pixels/s
============================================================================*/
#if (FXAA_PS3 == 1) && (FXAA_EARLY_EXIT == 0)
/*--------------------------------------------------------------------------*/
#pragma regcount 7
#pragma disablepc all
#pragma option O3
#pragma option OutColorPrec=fp16
#pragma texformat default RGBA8
/*==========================================================================*/
half4 FxaaPixelShader(
// See FXAA Quality FxaaPixelShader() source for docs on Inputs!
FxaaFloat2 pos,
FxaaFloat4 fxaaConsolePosPos,
FxaaTex tex,
FxaaTex fxaaConsole360TexExpBiasNegOne,
FxaaTex fxaaConsole360TexExpBiasNegTwo,
FxaaFloat2 fxaaQualityRcpFrame,
FxaaFloat4 fxaaConsoleRcpFrameOpt,
FxaaFloat4 fxaaConsoleRcpFrameOpt2,
FxaaFloat4 fxaaConsole360RcpFrameOpt2,
FxaaFloat fxaaQualitySubpix,
FxaaFloat fxaaQualityEdgeThreshold,
FxaaFloat fxaaQualityEdgeThresholdMin,
FxaaFloat fxaaConsoleEdgeSharpness,
FxaaFloat fxaaConsoleEdgeThreshold,
FxaaFloat fxaaConsoleEdgeThresholdMin,
FxaaFloat4 fxaaConsole360ConstDir
) {
/*--------------------------------------------------------------------------*/
// (1)
half4 dir;
half4 lumaNe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zy, 0, 0));
#if (FXAA_GREEN_AS_LUMA == 0)
lumaNe.w += half(1.0/512.0);
dir.x = -lumaNe.w;
dir.z = -lumaNe.w;
#else
lumaNe.y += half(1.0/512.0);
dir.x = -lumaNe.y;
dir.z = -lumaNe.y;
#endif
/*--------------------------------------------------------------------------*/
// (2)
half4 lumaSw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xw, 0, 0));
#if (FXAA_GREEN_AS_LUMA == 0)
dir.x += lumaSw.w;
dir.z += lumaSw.w;
#else
dir.x += lumaSw.y;
dir.z += lumaSw.y;
#endif
/*--------------------------------------------------------------------------*/
// (3)
half4 lumaNw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xy, 0, 0));
#if (FXAA_GREEN_AS_LUMA == 0)
dir.x -= lumaNw.w;
dir.z += lumaNw.w;
#else
dir.x -= lumaNw.y;
dir.z += lumaNw.y;
#endif
/*--------------------------------------------------------------------------*/
// (4)
half4 lumaSe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zw, 0, 0));
#if (FXAA_GREEN_AS_LUMA == 0)
dir.x += lumaSe.w;
dir.z -= lumaSe.w;
#else
dir.x += lumaSe.y;
dir.z -= lumaSe.y;
#endif
/*--------------------------------------------------------------------------*/
// (5)
half4 dir1_pos;
dir1_pos.xy = normalize(dir.xyz).xz;
half dirAbsMinTimesC = min(abs(dir1_pos.x), abs(dir1_pos.y)) * half(FXAA_CONSOLE__PS3_EDGE_SHARPNESS);
/*--------------------------------------------------------------------------*/
// (6)
half4 dir2_pos;
dir2_pos.xy = clamp(dir1_pos.xy / dirAbsMinTimesC, half(-2.0), half(2.0));
dir1_pos.zw = pos.xy;
dir2_pos.zw = pos.xy;
half4 temp1N;
temp1N.xy = dir1_pos.zw - dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw;
/*--------------------------------------------------------------------------*/
// (7)
temp1N = h4tex2Dlod(tex, half4(temp1N.xy, 0.0, 0.0));
half4 rgby1;
rgby1.xy = dir1_pos.zw + dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw;
/*--------------------------------------------------------------------------*/
// (8)
rgby1 = h4tex2Dlod(tex, half4(rgby1.xy, 0.0, 0.0));
rgby1 = (temp1N + rgby1) * 0.5;
/*--------------------------------------------------------------------------*/
// (9)
half4 temp2N;
temp2N.xy = dir2_pos.zw - dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw;
temp2N = h4tex2Dlod(tex, half4(temp2N.xy, 0.0, 0.0));
/*--------------------------------------------------------------------------*/
// (10)
half4 rgby2;
rgby2.xy = dir2_pos.zw + dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw;
rgby2 = h4tex2Dlod(tex, half4(rgby2.xy, 0.0, 0.0));
rgby2 = (temp2N + rgby2) * 0.5;
/*--------------------------------------------------------------------------*/
// (11)
// compilier moves these scalar ops up to other cycles
#if (FXAA_GREEN_AS_LUMA == 0)
half lumaMin = min(min(lumaNw.w, lumaSw.w), min(lumaNe.w, lumaSe.w));
half lumaMax = max(max(lumaNw.w, lumaSw.w), max(lumaNe.w, lumaSe.w));
#else
half lumaMin = min(min(lumaNw.y, lumaSw.y), min(lumaNe.y, lumaSe.y));
half lumaMax = max(max(lumaNw.y, lumaSw.y), max(lumaNe.y, lumaSe.y));
#endif
rgby2 = (rgby2 + rgby1) * 0.5;
/*--------------------------------------------------------------------------*/
// (12)
#if (FXAA_GREEN_AS_LUMA == 0)
bool twoTapLt = rgby2.w < lumaMin;
bool twoTapGt = rgby2.w > lumaMax;
#else
bool twoTapLt = rgby2.y < lumaMin;
bool twoTapGt = rgby2.y > lumaMax;
#endif
/*--------------------------------------------------------------------------*/
// (13)
if(twoTapLt || twoTapGt) rgby2 = rgby1;
/*--------------------------------------------------------------------------*/
return rgby2; }
/*==========================================================================*/
#endif
/*============================================================================
FXAA3 CONSOLE - OPTIMIZED PS3 PIXEL SHADER (WITH EARLY EXIT)
==============================================================================
The code mostly matches the assembly.
I have a feeling that 14 cycles is possible, but was not able to get there.
Might have to increase register count to get full performance.
Note this shader does not use perspective interpolation.
Use the following cgc options,
--fenable-bx2 --fastmath --fastprecision --nofloatbindings
Use of FXAA_GREEN_AS_LUMA currently adds a cycle (16 clks).
Will look at fixing this for FXAA 3.12.
------------------------------------------------------------------------------
NVSHADERPERF OUTPUT
------------------------------------------------------------------------------
For reference and to aid in debug, output of NVShaderPerf should match this,
Shader to schedule:
0: texpkb h0.w(TRUE), v5.zyxx, #0
2: addh h2.y(TRUE), h0.w, constant(0.001953, 0.000000, 0.000000, 0.000000).x
4: texpkb h1.w(TRUE), v5.xwxx, #0
6: addh h0.x(TRUE), h1.w, -h2.y
7: texpkb h2.w(TRUE), v5.zwzz, #0
9: minh h4.w(TRUE), h2.y, h2
10: maxh h5.x(TRUE), h2.y, h2.w
11: texpkb h0.w(TRUE), v5, #0
13: addh h3.w(TRUE), -h0, h0.x
14: addh h0.x(TRUE), h0.w, h0
15: addh h0.z(TRUE), -h2.w, h0.x
16: addh h0.x(TRUE), h2.w, h3.w
17: minh h5.y(TRUE), h0.w, h1.w
18: nrmh h2.xz(TRUE), h0_n
19: minh_m8 h2.w(TRUE), |h2.x|, |h2.z|
20: divx h4.xy(TRUE), h2_n.xzzw, h2_n.w
21: movr r1.zw(TRUE), v4.xxxy
22: maxh h2.w(TRUE), h0, h1
23: fenct TRUE
24: madr r0.xy(TRUE), -h2.xzzw, constant(cConst5.x, cConst5.y, cConst5.z, cConst5.w).zwzz, r1.zwzz
26: texpkb h0(TRUE), r0, #0
28: maxh h5.x(TRUE), h2.w, h5
29: minh h5.w(TRUE), h5.y, h4
30: madr r1.xy(TRUE), h2.xzzw, constant(cConst5.x, cConst5.y, cConst5.z, cConst5.w).zwzz, r1.zwzz
32: texpkb h2(TRUE), r1, #0
34: addh_d2 h2(TRUE), h0, h2
35: texpkb h1(TRUE), v4, #0
37: maxh h5.y(TRUE), h5.x, h1.w
38: minh h4.w(TRUE), h1, h5
39: madr r0.xy(TRUE), -h4, constant(cConst5.x, cConst5.y, cConst5.z, cConst5.w).xyxx, r1.zwzz
41: texpkb h0(TRUE), r0, #0
43: addh_m8 h5.z(TRUE), h5.y, -h4.w
44: madr r2.xy(TRUE), h4, constant(cConst5.x, cConst5.y, cConst5.z, cConst5.w).xyxx, r1.zwzz
46: texpkb h3(TRUE), r2, #0
48: addh_d2 h0(TRUE), h0, h3
49: addh_d2 h3(TRUE), h0, h2
50: movh h0(TRUE), h3
51: slth h3.x(TRUE), h3.w, h5.w
52: sgth h3.w(TRUE), h3, h5.x
53: addx.c0 rc(TRUE), h3.x, h3
54: slth.c0 rc(TRUE), h5.z, h5
55: movh h0(c0.NE.w), h2
56: movh h0(c0.NE.x), h1
IPU0 ------ Simplified schedule: --------
Pass | Unit | uOp | PC: Op
-----+--------+------+-------------------------
1 | SCT0/1 | mov | 0: TXLr h0.w, g[TEX1].zyxx, const.xxxx, TEX0;
| TEX | txl | 0: TXLr h0.w, g[TEX1].zyxx, const.xxxx, TEX0;
| SCB0 | add | 2: ADDh h2.y, h0.-w--, const.-x--;
| | |
2 | SCT0/1 | mov | 4: TXLr h1.w, g[TEX1].xwxx, const.xxxx, TEX0;
| TEX | txl | 4: TXLr h1.w, g[TEX1].xwxx, const.xxxx, TEX0;
| SCB0 | add | 6: ADDh h0.x, h1.w---,-h2.y---;
| | |
3 | SCT0/1 | mov | 7: TXLr h2.w, g[TEX1].zwzz, const.xxxx, TEX0;
| TEX | txl | 7: TXLr h2.w, g[TEX1].zwzz, const.xxxx, TEX0;
| SCB0 | max | 10: MAXh h5.x, h2.y---, h2.w---;
| SCB1 | min | 9: MINh h4.w, h2.---y, h2;
| | |
4 | SCT0/1 | mov | 11: TXLr h0.w, g[TEX1], const.xxxx, TEX0;
| TEX | txl | 11: TXLr h0.w, g[TEX1], const.xxxx, TEX0;
| SCB0 | add | 14: ADDh h0.x, h0.w---, h0;
| SCB1 | add | 13: ADDh h3.w,-h0, h0.---x;
| | |
5 | SCT0 | mad | 16: ADDh h0.x, h2.w---, h3.w---;
| SCT1 | mad | 15: ADDh h0.z,-h2.--w-, h0.--x-;
| SCB0 | min | 17: MINh h5.y, h0.-w--, h1.-w--;
| | |
6 | SCT1 | mov | 18: NRMh h2.xz, h0;
| SRB | nrm | 18: NRMh h2.xz, h0;
| SCB1 | min | 19: MINh*8 h2.w, |h2.---x|, |h2.---z|;
| | |
7 | SCT0 | div | 20: DIVx h4.xy, h2.xz--, h2.ww--;
| SCT1 | mov | 21: MOVr r1.zw, g[TEX0].--xy;
| SCB1 | max | 22: MAXh h2.w, h0, h1;
| | |
8 | SCT0 | mad | 24: MADr r0.xy,-h2.xz--, const.zw--, r1.zw--;
| SCT1 | mov | 26: TXLr h0, r0, const.xxxx, TEX0;
| TEX | txl | 26: TXLr h0, r0, const.xxxx, TEX0;
| SCB0 | max | 28: MAXh h5.x, h2.w---, h5;
| SCB1 | min | 29: MINh h5.w, h5.---y, h4;
| | |
9 | SCT0 | mad | 30: MADr r1.xy, h2.xz--, const.zw--, r1.zw--;
| SCT1 | mov | 32: TXLr h2, r1, const.xxxx, TEX0;
| TEX | txl | 32: TXLr h2, r1, const.xxxx, TEX0;
| SCB0/1 | add | 34: ADDh/2 h2, h0, h2;
| | |
10 | SCT0/1 | mov | 35: TXLr h1, g[TEX0], const.xxxx, TEX0;
| TEX | txl | 35: TXLr h1, g[TEX0], const.xxxx, TEX0;
| SCB0 | max | 37: MAXh h5.y, h5.-x--, h1.-w--;
| SCB1 | min | 38: MINh h4.w, h1, h5;
| | |
11 | SCT0 | mad | 39: MADr r0.xy,-h4, const.xy--, r1.zw--;
| SCT1 | mov | 41: TXLr h0, r0, const.zzzz, TEX0;
| TEX | txl | 41: TXLr h0, r0, const.zzzz, TEX0;
| SCB0 | mad | 44: MADr r2.xy, h4, const.xy--, r1.zw--;
| SCB1 | add | 43: ADDh*8 h5.z, h5.--y-,-h4.--w-;
| | |
12 | SCT0/1 | mov | 46: TXLr h3, r2, const.xxxx, TEX0;
| TEX | txl | 46: TXLr h3, r2, const.xxxx, TEX0;
| SCB0/1 | add | 48: ADDh/2 h0, h0, h3;
| | |
13 | SCT0/1 | mad | 49: ADDh/2 h3, h0, h2;
| SCB0/1 | mul | 50: MOVh h0, h3;
| | |
14 | SCT0 | set | 51: SLTh h3.x, h3.w---, h5.w---;
| SCT1 | set | 52: SGTh h3.w, h3, h5.---x;
| SCB0 | set | 54: SLThc0 rc, h5.z---, h5;
| SCB1 | add | 53: ADDxc0_s rc, h3.---x, h3;
| | |
15 | SCT0/1 | mul | 55: MOVh h0(NE0.wwww), h2;
| SCB0/1 | mul | 56: MOVh h0(NE0.xxxx), h1;
Pass SCT TEX SCB
1: 0% 100% 25%
2: 0% 100% 25%
3: 0% 100% 50%
4: 0% 100% 50%
5: 50% 0% 25%
6: 0% 0% 25%
7: 100% 0% 25%
8: 0% 100% 50%
9: 0% 100% 100%
10: 0% 100% 50%
11: 0% 100% 75%
12: 0% 100% 100%
13: 100% 0% 100%
14: 50% 0% 50%
15: 100% 0% 100%
MEAN: 26% 60% 56%
Pass SCT0 SCT1 TEX SCB0 SCB1
1: 0% 0% 100% 100% 0%
2: 0% 0% 100% 100% 0%
3: 0% 0% 100% 100% 100%
4: 0% 0% 100% 100% 100%
5: 100% 100% 0% 100% 0%
6: 0% 0% 0% 0% 100%
7: 100% 100% 0% 0% 100%
8: 0% 0% 100% 100% 100%
9: 0% 0% 100% 100% 100%
10: 0% 0% 100% 100% 100%
11: 0% 0% 100% 100% 100%
12: 0% 0% 100% 100% 100%
13: 100% 100% 0% 100% 100%
14: 100% 100% 0% 100% 100%
15: 100% 100% 0% 100% 100%
MEAN: 33% 33% 60% 86% 80%
Fragment Performance Setup: Driver RSX Compiler, GPU RSX, Flags 0x5
Results 15 cycles, 3 r regs, 800,000,000 pixels/s
============================================================================*/
#if (FXAA_PS3 == 1) && (FXAA_EARLY_EXIT == 1)
/*--------------------------------------------------------------------------*/
#pragma regcount 7
#pragma disablepc all
#pragma option O2
#pragma option OutColorPrec=fp16
#pragma texformat default RGBA8
/*==========================================================================*/
half4 FxaaPixelShader(
// See FXAA Quality FxaaPixelShader() source for docs on Inputs!
FxaaFloat2 pos,
FxaaFloat4 fxaaConsolePosPos,
FxaaTex tex,
FxaaTex fxaaConsole360TexExpBiasNegOne,
FxaaTex fxaaConsole360TexExpBiasNegTwo,
FxaaFloat2 fxaaQualityRcpFrame,
FxaaFloat4 fxaaConsoleRcpFrameOpt,
FxaaFloat4 fxaaConsoleRcpFrameOpt2,
FxaaFloat4 fxaaConsole360RcpFrameOpt2,
FxaaFloat fxaaQualitySubpix,
FxaaFloat fxaaQualityEdgeThreshold,
FxaaFloat fxaaQualityEdgeThresholdMin,
FxaaFloat fxaaConsoleEdgeSharpness,
FxaaFloat fxaaConsoleEdgeThreshold,
FxaaFloat fxaaConsoleEdgeThresholdMin,
FxaaFloat4 fxaaConsole360ConstDir
) {
/*--------------------------------------------------------------------------*/
// (1)
half4 rgbyNe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zy, 0, 0));
#if (FXAA_GREEN_AS_LUMA == 0)
half lumaNe = rgbyNe.w + half(1.0/512.0);
#else
half lumaNe = rgbyNe.y + half(1.0/512.0);
#endif
/*--------------------------------------------------------------------------*/
// (2)
half4 lumaSw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xw, 0, 0));
#if (FXAA_GREEN_AS_LUMA == 0)
half lumaSwNegNe = lumaSw.w - lumaNe;
#else
half lumaSwNegNe = lumaSw.y - lumaNe;
#endif
/*--------------------------------------------------------------------------*/
// (3)
half4 lumaNw = h4tex2Dlod(tex, half4(fxaaConsolePosPos.xy, 0, 0));
#if (FXAA_GREEN_AS_LUMA == 0)
half lumaMaxNwSw = max(lumaNw.w, lumaSw.w);
half lumaMinNwSw = min(lumaNw.w, lumaSw.w);
#else
half lumaMaxNwSw = max(lumaNw.y, lumaSw.y);
half lumaMinNwSw = min(lumaNw.y, lumaSw.y);
#endif
/*--------------------------------------------------------------------------*/
// (4)
half4 lumaSe = h4tex2Dlod(tex, half4(fxaaConsolePosPos.zw, 0, 0));
#if (FXAA_GREEN_AS_LUMA == 0)
half dirZ = lumaNw.w + lumaSwNegNe;
half dirX = -lumaNw.w + lumaSwNegNe;
#else
half dirZ = lumaNw.y + lumaSwNegNe;
half dirX = -lumaNw.y + lumaSwNegNe;
#endif
/*--------------------------------------------------------------------------*/
// (5)
half3 dir;
dir.y = 0.0;
#if (FXAA_GREEN_AS_LUMA == 0)
dir.x = lumaSe.w + dirX;
dir.z = -lumaSe.w + dirZ;
half lumaMinNeSe = min(lumaNe, lumaSe.w);
#else
dir.x = lumaSe.y + dirX;
dir.z = -lumaSe.y + dirZ;
half lumaMinNeSe = min(lumaNe, lumaSe.y);
#endif
/*--------------------------------------------------------------------------*/
// (6)
half4 dir1_pos;
dir1_pos.xy = normalize(dir).xz;
half dirAbsMinTimes8 = min(abs(dir1_pos.x), abs(dir1_pos.y)) * half(FXAA_CONSOLE__PS3_EDGE_SHARPNESS);
/*--------------------------------------------------------------------------*/
// (7)
half4 dir2_pos;
dir2_pos.xy = clamp(dir1_pos.xy / dirAbsMinTimes8, half(-2.0), half(2.0));
dir1_pos.zw = pos.xy;
dir2_pos.zw = pos.xy;
#if (FXAA_GREEN_AS_LUMA == 0)
half lumaMaxNeSe = max(lumaNe, lumaSe.w);
#else
half lumaMaxNeSe = max(lumaNe, lumaSe.y);
#endif
/*--------------------------------------------------------------------------*/
// (8)
half4 temp1N;
temp1N.xy = dir1_pos.zw - dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw;
temp1N = h4tex2Dlod(tex, half4(temp1N.xy, 0.0, 0.0));
half lumaMax = max(lumaMaxNwSw, lumaMaxNeSe);
half lumaMin = min(lumaMinNwSw, lumaMinNeSe);
/*--------------------------------------------------------------------------*/
// (9)
half4 rgby1;
rgby1.xy = dir1_pos.zw + dir1_pos.xy * fxaaConsoleRcpFrameOpt.zw;
rgby1 = h4tex2Dlod(tex, half4(rgby1.xy, 0.0, 0.0));
rgby1 = (temp1N + rgby1) * 0.5;
/*--------------------------------------------------------------------------*/
// (10)
half4 rgbyM = h4tex2Dlod(tex, half4(pos.xy, 0.0, 0.0));
#if (FXAA_GREEN_AS_LUMA == 0)
half lumaMaxM = max(lumaMax, rgbyM.w);
half lumaMinM = min(lumaMin, rgbyM.w);
#else
half lumaMaxM = max(lumaMax, rgbyM.y);
half lumaMinM = min(lumaMin, rgbyM.y);
#endif
/*--------------------------------------------------------------------------*/
// (11)
half4 temp2N;
temp2N.xy = dir2_pos.zw - dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw;
temp2N = h4tex2Dlod(tex, half4(temp2N.xy, 0.0, 0.0));
half4 rgby2;
rgby2.xy = dir2_pos.zw + dir2_pos.xy * fxaaConsoleRcpFrameOpt2.zw;
half lumaRangeM = (lumaMaxM - lumaMinM) / FXAA_CONSOLE__PS3_EDGE_THRESHOLD;
/*--------------------------------------------------------------------------*/
// (12)
rgby2 = h4tex2Dlod(tex, half4(rgby2.xy, 0.0, 0.0));
rgby2 = (temp2N + rgby2) * 0.5;
/*--------------------------------------------------------------------------*/
// (13)
rgby2 = (rgby2 + rgby1) * 0.5;
/*--------------------------------------------------------------------------*/
// (14)
#if (FXAA_GREEN_AS_LUMA == 0)
bool twoTapLt = rgby2.w < lumaMin;
bool twoTapGt = rgby2.w > lumaMax;
#else
bool twoTapLt = rgby2.y < lumaMin;
bool twoTapGt = rgby2.y > lumaMax;
#endif
bool earlyExit = lumaRangeM < lumaMax;
bool twoTap = twoTapLt || twoTapGt;
/*--------------------------------------------------------------------------*/
// (15)
if(twoTap) rgby2 = rgby1;
if(earlyExit) rgby2 = rgbyM;
/*--------------------------------------------------------------------------*/
return rgby2; }
/*==========================================================================*/
#endif
#define BORDEREFFECTS
#include"..\Common\DataStructs.hlsl"
#include"..\Common\CommonBuffers.hlsl"
/*
cbuffer cbFxaa : register(b1) {
float4 RCPFrame : packoffset(c0);
};
struct FxaaVS_Output {
float4 Pos : SV_POSITION;
float2 Tex : TEXCOORD0;
};
FxaaVS_Output FxaaVS(uint id : SV_VertexID) {
FxaaVS_Output Output;
Output.Tex = float2((id << 1) & 2, id & 2);
Output.Pos = float4(Output.Tex * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);
return Output;
}
SamplerState InputSampler : register(s3);
Texture2D InputTexture : register(t0);
*/
float4 main(MeshOutlinePS_INPUT Input) : SV_Target
{
//return texDiffuseMap.Sample(samplerSurface, Input.Tex.xy);
FxaaTex InputFXAATex = { samplerSurface, texDiffuseMap };
float4 c = FxaaPixelShader(
Input.Tex.xy, // FxaaFloat2 pos,
FxaaFloat4(0.0f, 0.0f, 0.0f, 0.0f), // FxaaFloat4 fxaaConsolePosPos,
InputFXAATex, // FxaaTex tex,
InputFXAATex, // FxaaTex fxaaConsole360TexExpBiasNegOne,
InputFXAATex, // FxaaTex fxaaConsole360TexExpBiasNegTwo,
Color.xy, // FxaaFloat2 fxaaQualityRcpFrame,
FxaaFloat4(0.0f, 0.0f, 0.0f, 0.0f), // FxaaFloat4 fxaaConsoleRcpFrameOpt,
FxaaFloat4(0.0f, 0.0f, 0.0f, 0.0f), // FxaaFloat4 fxaaConsoleRcpFrameOpt2,
FxaaFloat4(0.0f, 0.0f, 0.0f, 0.0f), // FxaaFloat4 fxaaConsole360RcpFrameOpt2,
Param._m00, // FxaaFloat fxaaQualitySubpix,
Param._m01, // FxaaFloat fxaaQualityEdgeThreshold,
Param._m02, // FxaaFloat fxaaQualityEdgeThresholdMin,
0.0f, // FxaaFloat fxaaConsoleEdgeSharpness,
0.0f, // FxaaFloat fxaaConsoleEdgeThreshold,
0.0f, // FxaaFloat fxaaConsoleEdgeThresholdMin,
FxaaFloat4(0.0f, 0.0f, 0.0f, 0.0f) // FxaaFloat fxaaConsole360ConstDir,
);
c.a = 1;
return c;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Javadoc API documentation for Fresco." />
<link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" />
<title>
Sets - Fresco API
| Fresco
</title>
<link href="../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" />
<script src="../../../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../../../assets/doclava-developer-docs.js" type="text/javascript"></script>
<script src="../../../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
setToRoot("../../../../", "../../../../../assets/");
</script>
<script src="../../../../../assets/doclava-developer-reference.js" type="text/javascript"></script>
<script src="../../../../../assets/navtree_data.js" type="text/javascript"></script>
<script src="../../../../../assets/customizations.js" type="text/javascript"></script>
<noscript>
<style type="text/css">
html,body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
</head>
<body class="">
<div id="header">
<div id="headerLeft">
<span id="masthead-title"><a href="../../../../packages.html">Fresco</a></span>
</div>
<div id="headerRight">
<div id="search" >
<div id="searchForm">
<form accept-charset="utf-8" class="gsc-search-box"
onsubmit="return submit_search()">
<table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
<tr>
<td class="gsc-input">
<input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
title="search developer docs" name="q"
value="search developer docs"
onFocus="search_focus_changed(this, true)"
onBlur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../')"
onkeyup="return search_changed(event, false, '../../../../')" />
<div id="search_filtered_div" class="no-display">
<table id="search_filtered" cellspacing=0>
</table>
</div>
</td>
<!-- <td class="gsc-search-button">
<input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
</td>
<td class="gsc-clear-button">
<div title="clear results" class="gsc-clear-button"> </div>
</td> -->
</tr></tbody>
</table>
</form>
</div><!-- searchForm -->
</div><!-- search -->
</div>
</div><!-- header -->
<div class="g-section g-tpl-240" id="body-content">
<div class="g-unit g-first side-nav-resizable" id="side-nav">
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav">
<div id="index-links">
<a href="../../../../packages.html" >Packages</a> |
<a href="../../../../classes.html" >Classes</a>
</div>
<ul>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/giflite/package-summary.html">com.facebook.animated.giflite</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/giflite/decoder/package-summary.html">com.facebook.animated.giflite.decoder</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/giflite/draw/package-summary.html">com.facebook.animated.giflite.draw</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/giflite/drawable/package-summary.html">com.facebook.animated.giflite.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/webpdrawable/package-summary.html">com.facebook.animated.webpdrawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/callercontext/package-summary.html">com.facebook.callercontext</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li>
<li class="selected api apilevel-">
<a href="../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/backends/pipeline/debug/package-summary.html">com.facebook.drawee.backends.pipeline.debug</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/backends/pipeline/info/package-summary.html">com.facebook.drawee.backends.pipeline.info</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/backends/pipeline/info/internal/package-summary.html">com.facebook.drawee.backends.pipeline.info.internal</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/debug/listener/package-summary.html">com.facebook.drawee.debug.listener</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/preparation/package-summary.html">com.facebook.fresco.animation.bitmap.preparation</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/middleware/package-summary.html">com.facebook.fresco.middleware</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/ui/common/package-summary.html">com.facebook.fresco.ui.common</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/debug/package-summary.html">com.facebook.imagepipeline.debug</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/drawable/package-summary.html">com.facebook.imagepipeline.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/filter/package-summary.html">com.facebook.imagepipeline.filter</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/instrumentation/package-summary.html">com.facebook.imagepipeline.instrumentation</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/multiuri/package-summary.html">com.facebook.imagepipeline.multiuri</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/systrace/package-summary.html">com.facebook.imagepipeline.systrace</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/transcoder/package-summary.html">com.facebook.imagepipeline.transcoder</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/transformation/package-summary.html">com.facebook.imagepipeline.transformation</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li>
</ul><br/>
</div> <!-- end packages -->
</div> <!-- end resize-packages -->
<div id="classes-nav">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Fn.html">Fn</a><A, R></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Predicate.html">Predicate</a><T></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Supplier.html">Supplier</a><T></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/AndroidPredicates.html">AndroidPredicates</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/ByteStreams.html">ByteStreams</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Closeables.html">Closeables</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/CountingOutputStream.html">CountingOutputStream</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Files.html">Files</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/ImmutableList.html">ImmutableList</a><E></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/ImmutableMap.html">ImmutableMap</a><K, V></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/ImmutableSet.html">ImmutableSet</a><E></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Ints.html">Ints</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Objects.html">Objects</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Objects.ToStringHelper.html">Objects.ToStringHelper</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Preconditions.html">Preconditions</a></li>
<li class="selected api apilevel-"><a href="../../../../com/facebook/common/internal/Sets.html">Sets</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Suppliers.html">Suppliers</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/Throwables.html">Throwables</a></li>
</ul>
</li>
<li><h2>Annotations</h2>
<ul>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/DoNotStrip.html">DoNotStrip</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/internal/VisibleForTesting.html">VisibleForTesting</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none">
<div id="index-links">
<a href="../../../../packages.html" >Packages</a> |
<a href="../../../../classes.html" >Classes</a>
</div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
</div> <!-- end side-nav -->
<script>
if (!isMobile) {
//$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav");
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../");
} else {
addLoadEvent(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
}
//$("#swapper").css({borderBottom:"2px solid #aaa"});
} else {
swapNav(); // tree view should be used on mobile
}
</script>
<div class="g-unit" id="doc-content">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#pubmethods">Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
final
class
<h1>Sets</h1>
extends Object<br/>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell">java.lang.Object</td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.facebook.common.internal.Sets</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p>Static utility methods pertaining to Set instances. </p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
static
<E>
CopyOnWriteArraySet<E>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/internal/Sets.html#newCopyOnWriteArraySet()">newCopyOnWriteArraySet</a></span>()
<div class="jd-descrdiv">Creates an empty <code>CopyOnWriteArraySet</code> instance.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
static
<E>
HashSet<E>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/internal/Sets.html#newHashSet(java.util.Iterator<? extends E>)">newHashSet</a></span>(Iterator<? extends E> elements)
<div class="jd-descrdiv">Creates a <i>mutable</i> <code>HashSet</code> instance containing the given elements in unspecified
order.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
static
<E>
HashSet<E>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/internal/Sets.html#newHashSet(E...)">newHashSet</a></span>(E... elements)
<div class="jd-descrdiv">Creates a <i>mutable</i> <code>HashSet</code> instance containing the given elements in unspecified
order.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
static
<E>
HashSet<E>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/internal/Sets.html#newHashSet()">newHashSet</a></span>()
<div class="jd-descrdiv">Creates a <i>mutable</i>, empty <code>HashSet</code> instance.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
static
<E>
HashSet<E>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/internal/Sets.html#newHashSet(java.lang.Iterable<? extends E>)">newHashSet</a></span>(Iterable<? extends E> elements)
<div class="jd-descrdiv">Creates a <i>mutable</i> <code>HashSet</code> instance containing the given elements in unspecified
order.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
static
<E>
HashSet<E>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/internal/Sets.html#newHashSetWithCapacity(int)">newHashSetWithCapacity</a></span>(int capacity)
<div class="jd-descrdiv">Creates a <code>HashSet</code> instance, with a high enough "initial capacity" that it <i>should</i>
hold <code>expectedSize</code> elements without growth.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
static
<E>
Set<E>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/internal/Sets.html#newIdentityHashSet()">newIdentityHashSet</a></span>()
<div class="jd-descrdiv">Creates an empty <code>Set</code> that uses identity to determine equality.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
static
<E>
LinkedHashSet<E>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/internal/Sets.html#newLinkedHashSet()">newLinkedHashSet</a></span>()
<div class="jd-descrdiv">Creates a <i>mutable</i>, empty <code>LinkedHashSet</code> instance.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
static
<E>
Set<E>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/internal/Sets.html#newSetFromMap(java.util.Map<E, java.lang.Boolean>)">newSetFromMap</a></span>(Map<E, Boolean> map)
<div class="jd-descrdiv">Returns a set backed by the specified map.</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
java.lang.Object
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Object
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">clone</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">equals</span>(Object arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">finalize</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
Class<?>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getClass</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">hashCode</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">notify</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">notifyAll</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
String
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">toString</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>(long arg0, int arg1)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>(long arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>()
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<a id="newCopyOnWriteArraySet()"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
CopyOnWriteArraySet<E>
</span>
<span class="sympad">newCopyOnWriteArraySet</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates an empty <code>CopyOnWriteArraySet</code> instance.
<p><b>Note:</b> if you need an immutable empty Set, use <code><a href="null#emptySet()">emptySet()</a></code>
instead.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>a new, empty <code>CopyOnWriteArraySet</code></li></ul>
</div>
</div>
</div>
<a id="newHashSet(java.util.Iterator<? extends E>)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
HashSet<E>
</span>
<span class="sympad">newHashSet</span>
<span class="normal">(Iterator<? extends E> elements)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates a <i>mutable</i> <code>HashSet</code> instance containing the given elements in unspecified
order.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>elements</th>
<td>the elements that the set should contain</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>a new <code>HashSet</code> containing those elements (minus duplicates)
</li></ul>
</div>
</div>
</div>
<a id="newHashSet(E...)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
HashSet<E>
</span>
<span class="sympad">newHashSet</span>
<span class="normal">(E... elements)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates a <i>mutable</i> <code>HashSet</code> instance containing the given elements in unspecified
order.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>elements</th>
<td>the elements that the set should contain</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>a new <code>HashSet</code> containing those elements (minus duplicates)
</li></ul>
</div>
</div>
</div>
<a id="newHashSet()"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
HashSet<E>
</span>
<span class="sympad">newHashSet</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates a <i>mutable</i>, empty <code>HashSet</code> instance.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>a new, empty <code>HashSet</code>
</li></ul>
</div>
</div>
</div>
<a id="newHashSet(java.lang.Iterable<? extends E>)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
HashSet<E>
</span>
<span class="sympad">newHashSet</span>
<span class="normal">(Iterable<? extends E> elements)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates a <i>mutable</i> <code>HashSet</code> instance containing the given elements in unspecified
order.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>elements</th>
<td>the elements that the set should contain</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>a new <code>HashSet</code> containing those elements (minus duplicates)
</li></ul>
</div>
</div>
</div>
<a id="newHashSetWithCapacity(int)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
HashSet<E>
</span>
<span class="sympad">newHashSetWithCapacity</span>
<span class="normal">(int capacity)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates a <code>HashSet</code> instance, with a high enough "initial capacity" that it <i>should</i>
hold <code>expectedSize</code> elements without growth. This behavior cannot be broadly guaranteed,
but it is observed to be true for OpenJDK 1.6. It also can't be guaranteed that the method
isn't inadvertently <i>oversizing</i> the returned set.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>capacity</th>
<td>the number of elements you expect to add to the returned set</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>a new, empty <code>HashSet</code> with enough capacity to hold <code>expectedSize</code> elements
without resizing</li></ul>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Throws</h5>
<table class="jd-tagtable">
<tr>
<th>IllegalArgumentException</td>
<td>if <code>expectedSize</code> is negative
</td>
</tr>
</table>
</div>
</div>
</div>
<a id="newIdentityHashSet()"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
Set<E>
</span>
<span class="sympad">newIdentityHashSet</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates an empty <code>Set</code> that uses identity to determine equality. It compares object
references, instead of calling <code>equals</code>, to determine whether a provided object matches
an element in the set. For example, <code>contains</code> returns <code>false</code> when passed an
object that equals a set member, but isn't the same instance. This behavior is similar to the
way <code>IdentityHashMap</code> handles key lookups.
</p></div>
</div>
</div>
<a id="newLinkedHashSet()"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
LinkedHashSet<E>
</span>
<span class="sympad">newLinkedHashSet</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates a <i>mutable</i>, empty <code>LinkedHashSet</code> instance.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>a new, empty <code>LinkedHashSet</code>
</li></ul>
</div>
</div>
</div>
<a id="newSetFromMap(java.util.Map<E, java.lang.Boolean>)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
Set<E>
</span>
<span class="sympad">newSetFromMap</span>
<span class="normal">(Map<E, Boolean> map)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns a set backed by the specified map. The resulting set displays the same ordering,
concurrency, and performance characteristics as the backing map. In essence, this factory
method provides a Set implementation corresponding to any Map implementation.
There is no need to use this method on a Map implementation that already has a
corresponding Set implementation (such as java.util.HashMap or java.util.TreeMap).
<p>Each method invocation on the set returned by this method results in exactly one method
invocation on the backing map or its <code>keySet</code> view, with one exception. The <code>addAll</code> method is implemented as a sequence of <code>put</code> invocations on the backing map.
<p>The specified map must be empty at the time this method is invoked, and should not be
accessed directly after this method returns. These conditions are ensured if the map is created
empty, passed directly to this method, and no reference to the map is retained, as illustrated
in the following code fragment:
<pre><code>Set<Object> identityHashSet = Sets.newSetFromMap(
new IdentityHashMap<Object, Boolean>());
</code></pre>
<p>This method has the same behavior as the JDK 6 method <code>Collections.newSetFromMap()</code>.
The returned set is serializable if the backing map is.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>map</th>
<td>the backing map</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>the set backed by the map</li></ul>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Throws</h5>
<table class="jd-tagtable">
<tr>
<th>IllegalArgumentException</td>
<td>if <code>map</code> is not empty
</td>
</tr>
</table>
</div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<a id="navbar_top"></a>
<div id="footer">
+Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>.
+</div> <!-- end footer - @generated -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script type="text/javascript">
init(); /* initialize doclava-developer-docs.js */
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
@file:Suppress("ObjectPropertyName", "FunctionName")
package ch.tutteli.atrium.logic
import ch.tutteli.atrium.assertions.Assertion
import ch.tutteli.atrium.creating.AssertionContainer
import ch.tutteli.atrium.creating.Expect
/**
* Appends the [Assertion] the given [factory] creates based on this [Expect].
*
* Use [_logic] for more sophisticated scenarios, like feature extraction.
*/
inline fun <T> Expect<T>._logicAppend(factory: AssertionContainer<T>.() -> Assertion): Expect<T> =
addAssertion(_logic.factory())
/**
* Entry point to the logic level of Atrium -- which is one level deeper than the API --
* on which assertion functions do not return [Expect]s but [Assertion]s and the like.
*
* Use [_logicAppend] in case you want to create and append an [Assertion] to this [Expect].
*/
inline val <T> Expect<T>._logic: AssertionContainer<T>
get() = this.toAssertionContainer()
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2020 Team Gateship-One
* (Hendrik Borghorst & Frederik Luetkes)
*
* The AUTHORS.md file contains a detailed contributors list:
* <https://github.com/gateship-one/odyssey/blob/master/AUTHORS.md>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.gateshipone.odyssey.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.RemoteException;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.gateshipone.odyssey.R;
import org.gateshipone.odyssey.activities.GenericActivity;
import org.gateshipone.odyssey.adapter.AlbumsRecyclerViewAdapter;
import org.gateshipone.odyssey.artwork.ArtworkManager;
import org.gateshipone.odyssey.listener.OnAlbumSelectedListener;
import org.gateshipone.odyssey.listener.ToolbarAndFABCallback;
import org.gateshipone.odyssey.models.AlbumModel;
import org.gateshipone.odyssey.models.ArtistModel;
import org.gateshipone.odyssey.utils.CoverBitmapLoader;
import org.gateshipone.odyssey.utils.RecyclerScrollSpeedListener;
import org.gateshipone.odyssey.utils.ThemeUtils;
import org.gateshipone.odyssey.viewitems.GenericImageViewItem;
import org.gateshipone.odyssey.viewitems.GenericViewItemHolder;
import org.gateshipone.odyssey.viewmodels.AlbumViewModel;
import org.gateshipone.odyssey.viewmodels.GenericViewModel;
import org.gateshipone.odyssey.views.OdysseyRecyclerView;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.preference.PreferenceManager;
public class ArtistAlbumsFragment extends OdysseyRecyclerFragment<AlbumModel, GenericViewItemHolder> implements CoverBitmapLoader.CoverBitmapReceiver, ArtworkManager.onNewArtistImageListener, OdysseyRecyclerView.OnItemClickListener {
private static final String TAG = ArtistAlbumsFragment.class.getSimpleName();
/**
* {@link ArtistModel} to show albums for
*/
private ArtistModel mArtist;
/**
* key values for arguments of the fragment
*/
private final static String ARG_ARTISTMODEL = "artistmodel";
private final static String ARG_BITMAP = "bitmap";
private CoverBitmapLoader mBitmapLoader;
private Bitmap mBitmap;
private boolean mHideArtwork;
/**
* Listener to open an album
*/
protected OnAlbumSelectedListener mAlbumSelectedCallback;
/**
* Save the last scroll position to resume there
*/
protected int mLastPosition = -1;
public static ArtistAlbumsFragment newInstance(@NonNull final ArtistModel artistModel, @Nullable final Bitmap bitmap) {
final Bundle args = new Bundle();
args.putParcelable(ARG_ARTISTMODEL, artistModel);
if (bitmap != null) {
args.putParcelable(ARG_BITMAP, bitmap);
}
final ArtistAlbumsFragment fragment = new ArtistAlbumsFragment();
fragment.setArguments(args);
return fragment;
}
/**
* Called to create instantiate the UI of the fragment.
*/
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.recycler_list_refresh, container, false);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String viewAppearance = sharedPref.getString(getString(R.string.pref_view_library_key), getString(R.string.pref_library_view_default));
// get swipe layout
mSwipeRefreshLayout = rootView.findViewById(R.id.refresh_layout);
// set swipe colors
mSwipeRefreshLayout.setColorSchemeColors(ThemeUtils.getThemeColor(getContext(), R.attr.colorAccent),
ThemeUtils.getThemeColor(getContext(), R.attr.colorPrimary));
// set swipe refresh listener
mSwipeRefreshLayout.setOnRefreshListener(this::refreshContent);
mRecyclerView = rootView.findViewById(R.id.recycler_view);
final boolean useList = viewAppearance.equals(getString(R.string.pref_library_view_list_key));
mRecyclerAdapter = new AlbumsRecyclerViewAdapter(getContext(), useList);
if (useList) {
mRecyclerView.setAdapter(mRecyclerAdapter);
setLinearLayoutManagerAndDecoration();
} else {
mRecyclerView.setAdapter(mRecyclerAdapter);
setGridLayoutManagerAndDecoration();
}
mRecyclerView.addOnScrollListener(new RecyclerScrollSpeedListener(mRecyclerAdapter));
mRecyclerView.addOnItemClicklistener(this);
registerForContextMenu(mRecyclerView);
// get empty view
mEmptyView = rootView.findViewById(R.id.empty_view);
// set empty view message
((TextView) rootView.findViewById(R.id.empty_view_message)).setText(R.string.empty_albums_message);
// read arguments
Bundle args = getArguments();
mArtist = args.getParcelable(ARG_ARTISTMODEL);
mBitmap = args.getParcelable(ARG_BITMAP);
setHasOptionsMenu(true);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
mHideArtwork = sharedPreferences.getBoolean(getContext().getString(R.string.pref_hide_artwork_key), getContext().getResources().getBoolean(R.bool.pref_hide_artwork_default));
mBitmapLoader = new CoverBitmapLoader(getContext(), this);
// setup observer for the live data
getViewModel().getData().observe(getViewLifecycleOwner(), this::onDataReady);
return rootView;
}
@Override
GenericViewModel<AlbumModel> getViewModel() {
return new ViewModelProvider(this, new AlbumViewModel.AlbumViewModelFactory(getActivity().getApplication(), mArtist.getArtistID())).get(AlbumViewModel.class);
}
@Override
public void onResume() {
super.onResume();
ArtworkManager.getInstance(getContext()).registerOnNewAlbumImageListener((AlbumsRecyclerViewAdapter) mRecyclerAdapter);
if (mToolbarAndFABCallback != null) {
// set up play button
mToolbarAndFABCallback.setupFAB(v -> playArtist());
}
// set toolbar behaviour and title
if (!mHideArtwork && mBitmap == null) {
mToolbarAndFABCallback.setupToolbar(mArtist.getArtistName(), false, false, false);
final View rootView = getView();
if (rootView != null) {
getView().post(() -> {
int width = rootView.getWidth();
mBitmapLoader.getArtistImage(mArtist, width, width);
});
}
} else if (!mHideArtwork) {
mToolbarAndFABCallback.setupToolbar(mArtist.getArtistName(), false, false, true);
mToolbarAndFABCallback.setupToolbarImage(mBitmap);
final View rootView = getView();
if (rootView != null) {
getView().post(() -> {
int width = rootView.getWidth();
// Image too small
if (mBitmap.getWidth() < width) {
mBitmapLoader.getArtistImage(mArtist, width, width);
}
});
}
} else {
mToolbarAndFABCallback.setupToolbar(mArtist.getArtistName(), false, false, false);
}
ArtworkManager.getInstance(getContext()).registerOnNewArtistImageListener(this);
}
@Override
public void onPause() {
super.onPause();
ArtworkManager.getInstance(getContext()).unregisterOnNewAlbumImageListener((AlbumsRecyclerViewAdapter) mRecyclerAdapter);
ArtworkManager.getInstance(getContext()).unregisterOnNewArtistImageListener(this);
}
/**
* Called when the fragment is first attached to its context.
*/
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mAlbumSelectedCallback = (OnAlbumSelectedListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnAlbumSelectedListener");
}
try {
mToolbarAndFABCallback = (ToolbarAndFABCallback) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement ToolbarAndFABCallback");
}
}
/**
* Called when the observed {@link androidx.lifecycle.LiveData} is changed.
* <p>
* This method will update the related adapter and the {@link androidx.swiperefreshlayout.widget.SwipeRefreshLayout} if present.
*
* @param model The data observed by the {@link androidx.lifecycle.LiveData}.
*/
@Override
protected void onDataReady(List<AlbumModel> model) {
super.onDataReady(model);
// Reset old scroll position
if (mLastPosition >= 0) {
mRecyclerView.getLayoutManager().scrollToPosition(mLastPosition);
mLastPosition = -1;
}
}
/**
* Callback when an item in the GridView was clicked.
*/
@Override
public void onItemClick(int position) {
// save last scroll position
mLastPosition = position;
// identify current album
AlbumModel currentAlbum = mRecyclerAdapter.getItem(position);
Bitmap bitmap = null;
final View view = mRecyclerView.getChildAt(position);
// Check if correct view type, to be safe
if (view instanceof GenericImageViewItem) {
bitmap = ((GenericImageViewItem) view).getBitmap();
}
// send the event to the host activity
mAlbumSelectedCallback.onAlbumSelected(currentAlbum, bitmap);
}
/**
* Call the PBS to enqueue the selected album.
*
* @param position the position of the selected album in the adapter
*/
protected void enqueueAlbum(int position) {
// identify current album
AlbumModel clickedAlbum = mRecyclerAdapter.getItem(position);
String albumKey = clickedAlbum.getAlbumKey();
// enqueue album
try {
((GenericActivity) getActivity()).getPlaybackService().enqueueAlbum(albumKey);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Call the PBS to play the selected album.
* A previous playlist will be cleared.
*
* @param position the position of the selected album in the adapter
*/
protected void playAlbum(int position) {
// identify current album
AlbumModel clickedAlbum = mRecyclerAdapter.getItem(position);
String albumKey = clickedAlbum.getAlbumKey();
// play album
try {
((GenericActivity) getActivity()).getPlaybackService().playAlbum(albumKey, 0);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Create the context menu.
*/
@Override
public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.context_menu_artist_albums_fragment, menu);
}
/**
* Hook called when an menu item in the context menu is selected.
*
* @param item The menu item that was selected.
* @return True if the hook was consumed here.
*/
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
OdysseyRecyclerView.RecyclerViewContextMenuInfo info =
(OdysseyRecyclerView.RecyclerViewContextMenuInfo) item.getMenuInfo();
if (info == null) {
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case R.id.fragment_artist_albums_action_enqueue:
enqueueAlbum(info.position);
return true;
case R.id.fragment_artist_albums_action_play:
playAlbum(info.position);
return true;
default:
return super.onContextItemSelected(item);
}
}
/**
* Initialize the options menu.
* Be sure to call {@link #setHasOptionsMenu} before.
*
* @param menu The container for the custom options menu.
* @param menuInflater The inflater to instantiate the layout.
*/
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.options_menu_artist_albums_fragment, menu);
// get tint color
int tintColor = ThemeUtils.getThemeColor(getContext(), R.attr.odyssey_color_text_accent);
Drawable drawable = menu.findItem(R.id.action_add_artist_albums).getIcon();
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, tintColor);
menu.findItem(R.id.action_add_artist_albums).setIcon(drawable);
super.onCreateOptionsMenu(menu, menuInflater);
}
/**
* Hook called when an menu item in the options menu is selected.
*
* @param item The menu item that was selected.
* @return True if the hook was consumed here.
*/
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_reset_artwork:
mToolbarAndFABCallback.setupToolbar(mArtist.getArtistName(), false, false, false);
ArtworkManager.getInstance(getContext()).resetImage(mArtist);
return true;
case R.id.action_add_artist_albums:
enqueueArtist();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
getArguments().remove(ARG_BITMAP);
super.onSaveInstanceState(savedInstanceState);
}
/**
* Call the PBS to enqueue artist.
*/
private void enqueueArtist() {
// Read order preference
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String orderKey = sharedPref.getString(getString(R.string.pref_album_sort_order_key), getString(R.string.pref_artist_albums_sort_default));
// enqueue artist
try {
((GenericActivity) getActivity()).getPlaybackService().enqueueArtist(mArtist.getArtistID(), orderKey);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Call the PBS to play artist.
* A previous playlist will be cleared.
*/
private void playArtist() {
// Read order preference
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String orderKey = sharedPref.getString(getString(R.string.pref_album_sort_order_key), getString(R.string.pref_artist_albums_sort_default));
// play artist
try {
((GenericActivity) getActivity()).getPlaybackService().playArtist(mArtist.getArtistID(), orderKey);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void receiveArtistBitmap(final Bitmap bm) {
if (bm != null && mToolbarAndFABCallback != null) {
getActivity().runOnUiThread(() -> {
// set toolbar behaviour and title
mToolbarAndFABCallback.setupToolbar(mArtist.getArtistName(), false, false, true);
// set toolbar image
mToolbarAndFABCallback.setupToolbarImage(bm);
getArguments().putParcelable(ARG_BITMAP, bm);
});
}
}
@Override
public void receiveAlbumBitmap(final Bitmap bm) {
}
@Override
public void newArtistImage(ArtistModel artist) {
if (artist.equals(mArtist)) {
if (!mHideArtwork) {
int width = getView().getWidth();
mBitmapLoader.getArtistImage(mArtist, width, width);
}
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.corba.se.impl.ior;
import java.util.HashMap;
import java.util.Map;
import com.sun.corba.se.spi.ior.Identifiable ;
import com.sun.corba.se.spi.ior.IdentifiableFactory ;
import com.sun.corba.se.spi.ior.IdentifiableFactoryFinder ;
import com.sun.corba.se.spi.ior.TaggedComponent ;
import com.sun.corba.se.spi.ior.TaggedComponentFactoryFinder ;
import com.sun.corba.se.impl.ior.GenericTaggedComponent ;
import com.sun.corba.se.impl.ior.IdentifiableFactoryFinderBase ;
import com.sun.corba.se.impl.encoding.EncapsOutputStream ;
import com.sun.corba.se.spi.orb.ORB ;
import org.omg.CORBA_2_3.portable.InputStream ;
/**
* @author Ken Cavanaugh
*/
public class TaggedComponentFactoryFinderImpl extends
IdentifiableFactoryFinderBase implements TaggedComponentFactoryFinder
{
public TaggedComponentFactoryFinderImpl( ORB orb )
{
super( orb ) ;
}
public Identifiable handleMissingFactory( int id, InputStream is ) {
return new GenericTaggedComponent( id, is ) ;
}
public TaggedComponent create( org.omg.CORBA.ORB orb,
org.omg.IOP.TaggedComponent comp )
{
EncapsOutputStream os =
sun.corba.OutputStreamFactory.newEncapsOutputStream((ORB)orb);
org.omg.IOP.TaggedComponentHelper.write( os, comp ) ;
InputStream is = (InputStream)(os.create_input_stream() ) ;
// Skip the component ID: we just wrote it out above
is.read_ulong() ;
return (TaggedComponent)create( comp.tag, is ) ;
}
}
| {
"pile_set_name": "Github"
} |
#ifndef EMPTY_SYSTEM_SIGNATURE_H
#define EMPTY_SYSTEM_SIGNATURE_H
/* This generated file contains includes for project dependencies */
#include "empty_system_signature/bake_config.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
using System;
using Metrics.Core;
using Metrics.MetricData;
using Metrics.Sampling;
namespace Metrics
{
public interface AdvancedMetricsContext : Utils.IHideObjectMembers
{
/// <summary>
/// Attach a context that has already been created (ex: by a library exposing internal metrics)
/// </summary>
/// <param name="contextName">name of the context to attach</param>
/// <param name="context">Existing context instance.</param>
/// <returns>true if the context was attached, false otherwise.</returns>
bool AttachContext(string contextName, MetricsContext context);
/// <summary>
/// All metrics operations will be NO-OP.
/// This is useful for measuring the impact of the metrics library on the application.
/// If you think the Metrics library is causing issues, this will disable all Metrics operations.
/// </summary>
void CompletelyDisableMetrics();
/// <summary>
/// Clear all collected data for all the metrics in this context
/// </summary>
void ResetMetricsValues();
/// <summary>
/// Event fired when the context is disposed or shutdown or the CompletelyDisableMetrics is called.
/// </summary>
event EventHandler ContextShuttingDown;
/// <summary>
/// Event fired when the context CompletelyDisableMetrics is called.
/// </summary>
event EventHandler ContextDisabled;
/// <summary>
/// Register a custom Gauge instance.
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all counters in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="valueProvider">Function used to build a custom instance.</param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
void Gauge(string name, Func<MetricValueProvider<double>> valueProvider, Unit unit, MetricTags tags = default(MetricTags));
/// <summary>
/// Register a custom Counter instance
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all counters in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="builder">Function used to build a custom instance.</param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Counter Counter<T>(string name, Unit unit, Func<T> builder, MetricTags tags = default(MetricTags))
where T : CounterImplementation;
/// <summary>
/// Register a custom Meter instance.
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all meters in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="builder">Function used to build a custom instance.</param>
/// <param name="rateUnit">Time unit for rates reporting. Defaults to Second ( occurrences / second ).</param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Meter Meter<T>(string name, Unit unit, Func<T> builder, TimeUnit rateUnit = TimeUnit.Seconds, MetricTags tags = default(MetricTags))
where T : MeterImplementation;
/// <summary>
/// Register a custom Histogram instance
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all histograms in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="builder">Function used to build a custom instance.</param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Histogram Histogram<T>(string name, Unit unit, Func<T> builder, MetricTags tags = default(MetricTags))
where T : HistogramImplementation;
/// <summary>
/// Register a Histogram metric with a custom Reservoir instance
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all histograms in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="builder">Function used to build a custom reservoir instance.</param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Histogram Histogram(string name, Unit unit, Func<Reservoir> builder, MetricTags tags = default(MetricTags));
/// <summary>
/// Register a custom Timer implementation.
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all timers in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="builder">Function used to build a custom instance.</param>
/// <param name="rateUnit">Time unit for rates reporting. Defaults to Second ( occurrences / second ).</param>
/// <param name="durationUnit">Time unit for reporting durations. Defaults to Milliseconds. </param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Timer Timer<T>(string name, Unit unit, Func<T> builder, TimeUnit rateUnit = TimeUnit.Seconds, TimeUnit durationUnit = TimeUnit.Milliseconds, MetricTags tags = default(MetricTags))
where T : TimerImplementation;
/// <summary>
/// Register a Timer metric with a custom Histogram implementation.
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all timers in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="builder">Function used to build a custom histogram instance.</param>
/// <param name="rateUnit">Time unit for rates reporting. Defaults to Second ( occurrences / second ).</param>
/// <param name="durationUnit">Time unit for reporting durations. Defaults to Milliseconds. </param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Timer Timer(string name, Unit unit, Func<HistogramImplementation> builder, TimeUnit rateUnit = TimeUnit.Seconds, TimeUnit durationUnit = TimeUnit.Milliseconds, MetricTags tags = default(MetricTags));
/// <summary>
/// Register a Timer metric with a custom Reservoir implementation for the histogram.
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all timers in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="builder">Function used to build a custom reservoir instance.</param>
/// <param name="rateUnit">Time unit for rates reporting. Defaults to Second ( occurrences / second ).</param>
/// <param name="durationUnit">Time unit for reporting durations. Defaults to Milliseconds. </param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Timer Timer(string name, Unit unit, Func<Reservoir> builder, TimeUnit rateUnit = TimeUnit.Seconds, TimeUnit durationUnit = TimeUnit.Milliseconds, MetricTags tags = default(MetricTags));
/// <summary>
/// Replace the DefaultMetricsBuilder used in this context.
/// </summary>
/// <param name="metricsBuilder">The custom metrics builder.</param>
void WithCustomMetricsBuilder(MetricsBuilder metricsBuilder);
}
}
| {
"pile_set_name": "Github"
} |
1 array 8 1
2 var 8
4 zero 1
5 one 1
6 ones 8
7 one 8
8 write 8 1 1 4 6
9 write 8 1 8 5 7
10 eq 1 8 9
11 read 8 9 10
12 eq 1 2 11
13 root 1 12
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//
#import "IPropertyValueController.h"
@interface TSpotlightMetaDataController : IPropertyValueController
{
struct TKeyValueBinder _spotlightMetaDataBinder;
}
- (id).cxx_construct;
- (void).cxx_destruct;
- (void)handleNodeMDAttributesChanged:(const struct TFENode *)arg1 attributes:(id)arg2 isDisplayAttributes:(_Bool)arg3;
- (_Bool)adjustSize:(_Bool)arg1;
- (void)setView:(id)arg1;
- (void)flush;
- (id)spotlightMetaDataView;
- (void)aboutToTearDown;
@end
| {
"pile_set_name": "Github"
} |
class AddShippedAtToOrders < ActiveRecord::Migration[4.2]
def change
add_column :orders, :shipped_at, :datetime
end
end
| {
"pile_set_name": "Github"
} |
/* v3_akey.c */
/*
* Written by Dr Stephen N Henson ([email protected]) for the OpenSSL project
* 1999.
*/
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* ([email protected]). This product includes software written by Tim
* Hudson ([email protected]).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
AUTHORITY_KEYID *akeyid,
STACK_OF(CONF_VALUE)
*extlist);
static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *values);
const X509V3_EXT_METHOD v3_akey_id = {
NID_authority_key_identifier,
X509V3_EXT_MULTILINE, ASN1_ITEM_ref(AUTHORITY_KEYID),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_AUTHORITY_KEYID,
(X509V3_EXT_V2I)v2i_AUTHORITY_KEYID,
0, 0,
NULL
};
static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
AUTHORITY_KEYID *akeyid,
STACK_OF(CONF_VALUE)
*extlist)
{
char *tmp;
if (akeyid->keyid) {
tmp = hex_to_string(akeyid->keyid->data, akeyid->keyid->length);
X509V3_add_value("keyid", tmp, &extlist);
OPENSSL_free(tmp);
}
if (akeyid->issuer)
extlist = i2v_GENERAL_NAMES(NULL, akeyid->issuer, extlist);
if (akeyid->serial) {
tmp = hex_to_string(akeyid->serial->data, akeyid->serial->length);
X509V3_add_value("serial", tmp, &extlist);
OPENSSL_free(tmp);
}
return extlist;
}
/*-
* Currently two options:
* keyid: use the issuers subject keyid, the value 'always' means its is
* an error if the issuer certificate doesn't have a key id.
* issuer: use the issuers cert issuer and serial number. The default is
* to only use this if keyid is not present. With the option 'always'
* this is always included.
*/
static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *values)
{
char keyid = 0, issuer = 0;
int i;
CONF_VALUE *cnf;
ASN1_OCTET_STRING *ikeyid = NULL;
X509_NAME *isname = NULL;
GENERAL_NAMES *gens = NULL;
GENERAL_NAME *gen = NULL;
ASN1_INTEGER *serial = NULL;
X509_EXTENSION *ext;
X509 *cert;
AUTHORITY_KEYID *akeyid;
for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
cnf = sk_CONF_VALUE_value(values, i);
if (!strcmp(cnf->name, "keyid")) {
keyid = 1;
if (cnf->value && !strcmp(cnf->value, "always"))
keyid = 2;
} else if (!strcmp(cnf->name, "issuer")) {
issuer = 1;
if (cnf->value && !strcmp(cnf->value, "always"))
issuer = 2;
} else {
X509V3err(X509V3_F_V2I_AUTHORITY_KEYID, X509V3_R_UNKNOWN_OPTION);
ERR_add_error_data(2, "name=", cnf->name);
return NULL;
}
}
if (!ctx || !ctx->issuer_cert) {
if (ctx && (ctx->flags == CTX_TEST))
return AUTHORITY_KEYID_new();
X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,
X509V3_R_NO_ISSUER_CERTIFICATE);
return NULL;
}
cert = ctx->issuer_cert;
if (keyid) {
i = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1);
if ((i >= 0) && (ext = X509_get_ext(cert, i)))
ikeyid = X509V3_EXT_d2i(ext);
if (keyid == 2 && !ikeyid) {
X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,
X509V3_R_UNABLE_TO_GET_ISSUER_KEYID);
return NULL;
}
}
if ((issuer && !ikeyid) || (issuer == 2)) {
isname = X509_NAME_dup(X509_get_issuer_name(cert));
serial = M_ASN1_INTEGER_dup(X509_get_serialNumber(cert));
if (!isname || !serial) {
X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,
X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS);
goto err;
}
}
if (!(akeyid = AUTHORITY_KEYID_new()))
goto err;
if (isname) {
if (!(gens = sk_GENERAL_NAME_new_null())
|| !(gen = GENERAL_NAME_new())
|| !sk_GENERAL_NAME_push(gens, gen)) {
X509V3err(X509V3_F_V2I_AUTHORITY_KEYID, ERR_R_MALLOC_FAILURE);
goto err;
}
gen->type = GEN_DIRNAME;
gen->d.dirn = isname;
}
akeyid->issuer = gens;
akeyid->serial = serial;
akeyid->keyid = ikeyid;
return akeyid;
err:
X509_NAME_free(isname);
M_ASN1_INTEGER_free(serial);
M_ASN1_OCTET_STRING_free(ikeyid);
return NULL;
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Linq;
namespace Windows.UI.Xaml.Media
{
internal enum ImageDataKind
{
/// <summary>
/// The source is empty and the target visual element should be cleared
/// </summary>
Empty,
Url,
/// <summary>
/// A base64 encoded image
/// </summary>
Base64,
/// <summary>
/// The image failed to load (cf. The Error property)
/// </summary>
Error = 256
}
}
| {
"pile_set_name": "Github"
} |
contrib/python/cjdns-dynamic.conf /etc/
contrib/python/dynamicEndpoints.py /usr/lib/cjdns/
| {
"pile_set_name": "Github"
} |
// cgo -godefs types_freebsd.go | go run mkpost.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build arm64,freebsd
package unix
const (
SizeofPtr = 0x8
SizeofShort = 0x2
SizeofInt = 0x4
SizeofLong = 0x8
SizeofLongLong = 0x8
)
type (
_C_short int16
_C_int int32
_C_long int64
_C_long_long int64
)
type Timespec struct {
Sec int64
Nsec int64
}
type Timeval struct {
Sec int64
Usec int64
}
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int64
Ixrss int64
Idrss int64
Isrss int64
Minflt int64
Majflt int64
Nswap int64
Inblock int64
Oublock int64
Msgsnd int64
Msgrcv int64
Nsignals int64
Nvcsw int64
Nivcsw int64
}
type Rlimit struct {
Cur int64
Max int64
}
type _Gid_t uint32
const (
_statfsVersion = 0x20140518
_dirblksiz = 0x400
)
type Stat_t struct {
Dev uint64
Ino uint64
Nlink uint64
Mode uint16
_0 int16
Uid uint32
Gid uint32
_1 int32
Rdev uint64
Atim Timespec
Mtim Timespec
Ctim Timespec
Birthtim Timespec
Size int64
Blocks int64
Blksize int32
Flags uint32
Gen uint64
Spare [10]uint64
}
type stat_freebsd11_t struct {
Dev uint32
Ino uint32
Mode uint16
Nlink uint16
Uid uint32
Gid uint32
Rdev uint32
Atim Timespec
Mtim Timespec
Ctim Timespec
Size int64
Blocks int64
Blksize int32
Flags uint32
Gen uint32
Lspare int32
Birthtim Timespec
}
type Statfs_t struct {
Version uint32
Type uint32
Flags uint64
Bsize uint64
Iosize uint64
Blocks uint64
Bfree uint64
Bavail int64
Files uint64
Ffree int64
Syncwrites uint64
Asyncwrites uint64
Syncreads uint64
Asyncreads uint64
Spare [10]uint64
Namemax uint32
Owner uint32
Fsid Fsid
Charspare [80]int8
Fstypename [16]int8
Mntfromname [1024]int8
Mntonname [1024]int8
}
type statfs_freebsd11_t struct {
Version uint32
Type uint32
Flags uint64
Bsize uint64
Iosize uint64
Blocks uint64
Bfree uint64
Bavail int64
Files uint64
Ffree int64
Syncwrites uint64
Asyncwrites uint64
Syncreads uint64
Asyncreads uint64
Spare [10]uint64
Namemax uint32
Owner uint32
Fsid Fsid
Charspare [80]int8
Fstypename [16]int8
Mntfromname [88]int8
Mntonname [88]int8
}
type Flock_t struct {
Start int64
Len int64
Pid int32
Type int16
Whence int16
Sysid int32
_ [4]byte
}
type Dirent struct {
Fileno uint64
Off int64
Reclen uint16
Type uint8
Pad0 uint8
Namlen uint16
Pad1 uint16
Name [256]int8
}
type dirent_freebsd11 struct {
Fileno uint32
Reclen uint16
Type uint8
Namlen uint8
Name [256]int8
}
type Fsid struct {
Val [2]int32
}
const (
PathMax = 0x400
)
const (
FADV_NORMAL = 0x0
FADV_RANDOM = 0x1
FADV_SEQUENTIAL = 0x2
FADV_WILLNEED = 0x3
FADV_DONTNEED = 0x4
FADV_NOREUSE = 0x5
)
type RawSockaddrInet4 struct {
Len uint8
Family uint8
Port uint16
Addr [4]byte /* in_addr */
Zero [8]int8
}
type RawSockaddrInet6 struct {
Len uint8
Family uint8
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Len uint8
Family uint8
Path [104]int8
}
type RawSockaddrDatalink struct {
Len uint8
Family uint8
Index uint16
Type uint8
Nlen uint8
Alen uint8
Slen uint8
Data [46]int8
}
type RawSockaddr struct {
Len uint8
Family uint8
Data [14]int8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [92]int8
}
type _Socklen uint32
type Linger struct {
Onoff int32
Linger int32
}
type Iovec struct {
Base *byte
Len uint64
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPMreqn struct {
Multiaddr [4]byte /* in_addr */
Address [4]byte /* in_addr */
Ifindex int32
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type Msghdr struct {
Name *byte
Namelen uint32
_ [4]byte
Iov *Iovec
Iovlen int32
_ [4]byte
Control *byte
Controllen uint32
Flags int32
}
type Cmsghdr struct {
Len uint32
Level int32
Type int32
}
type Inet6Pktinfo struct {
Addr [16]byte /* in6_addr */
Ifindex uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type ICMPv6Filter struct {
Filt [8]uint32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x6c
SizeofSockaddrUnix = 0x6a
SizeofSockaddrDatalink = 0x36
SizeofLinger = 0x8
SizeofIPMreq = 0x8
SizeofIPMreqn = 0xc
SizeofIPv6Mreq = 0x14
SizeofMsghdr = 0x30
SizeofCmsghdr = 0xc
SizeofInet6Pktinfo = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofICMPv6Filter = 0x20
)
const (
PTRACE_TRACEME = 0x0
PTRACE_CONT = 0x7
PTRACE_KILL = 0x8
)
type Kevent_t struct {
Ident uint64
Filter int16
Flags uint16
Fflags uint32
Data int64
Udata *byte
}
type FdSet struct {
Bits [16]uint64
}
const (
sizeofIfMsghdr = 0xa8
SizeofIfMsghdr = 0xa8
sizeofIfData = 0x98
SizeofIfData = 0x98
SizeofIfaMsghdr = 0x14
SizeofIfmaMsghdr = 0x10
SizeofIfAnnounceMsghdr = 0x18
SizeofRtMsghdr = 0x98
SizeofRtMetrics = 0x70
)
type ifMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
_ [2]byte
Data ifData
}
type IfMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
_ [2]byte
Data IfData
}
type ifData struct {
Type uint8
Physical uint8
Addrlen uint8
Hdrlen uint8
Link_state uint8
Vhid uint8
Datalen uint16
Mtu uint32
Metric uint32
Baudrate uint64
Ipackets uint64
Ierrors uint64
Opackets uint64
Oerrors uint64
Collisions uint64
Ibytes uint64
Obytes uint64
Imcasts uint64
Omcasts uint64
Iqdrops uint64
Oqdrops uint64
Noproto uint64
Hwassist uint64
_ [8]byte
_ [16]byte
}
type IfData struct {
Type uint8
Physical uint8
Addrlen uint8
Hdrlen uint8
Link_state uint8
Spare_char1 uint8
Spare_char2 uint8
Datalen uint8
Mtu uint64
Metric uint64
Baudrate uint64
Ipackets uint64
Ierrors uint64
Opackets uint64
Oerrors uint64
Collisions uint64
Ibytes uint64
Obytes uint64
Imcasts uint64
Omcasts uint64
Iqdrops uint64
Noproto uint64
Hwassist uint64
Epoch int64
Lastchange Timeval
}
type IfaMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
_ [2]byte
Metric int32
}
type IfmaMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
_ [2]byte
}
type IfAnnounceMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Index uint16
Name [16]int8
What uint16
}
type RtMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Index uint16
_ [2]byte
Flags int32
Addrs int32
Pid int32
Seq int32
Errno int32
Fmask int32
Inits uint64
Rmx RtMetrics
}
type RtMetrics struct {
Locks uint64
Mtu uint64
Hopcount uint64
Expire uint64
Recvpipe uint64
Sendpipe uint64
Ssthresh uint64
Rtt uint64
Rttvar uint64
Pksent uint64
Weight uint64
Filler [3]uint64
}
const (
SizeofBpfVersion = 0x4
SizeofBpfStat = 0x8
SizeofBpfZbuf = 0x18
SizeofBpfProgram = 0x10
SizeofBpfInsn = 0x8
SizeofBpfHdr = 0x20
SizeofBpfZbufHeader = 0x20
)
type BpfVersion struct {
Major uint16
Minor uint16
}
type BpfStat struct {
Recv uint32
Drop uint32
}
type BpfZbuf struct {
Bufa *byte
Bufb *byte
Buflen uint64
}
type BpfProgram struct {
Len uint32
_ [4]byte
Insns *BpfInsn
}
type BpfInsn struct {
Code uint16
Jt uint8
Jf uint8
K uint32
}
type BpfHdr struct {
Tstamp Timeval
Caplen uint32
Datalen uint32
Hdrlen uint16
_ [6]byte
}
type BpfZbufHeader struct {
Kernel_gen uint32
Kernel_len uint32
User_gen uint32
_ [5]uint32
}
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Cc [20]uint8
Ispeed uint32
Ospeed uint32
}
type Winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
const (
AT_FDCWD = -0x64
AT_REMOVEDIR = 0x800
AT_SYMLINK_FOLLOW = 0x400
AT_SYMLINK_NOFOLLOW = 0x200
)
type PollFd struct {
Fd int32
Events int16
Revents int16
}
const (
POLLERR = 0x8
POLLHUP = 0x10
POLLIN = 0x1
POLLINIGNEOF = 0x2000
POLLNVAL = 0x20
POLLOUT = 0x4
POLLPRI = 0x2
POLLRDBAND = 0x80
POLLRDNORM = 0x40
POLLWRBAND = 0x100
POLLWRNORM = 0x4
)
type CapRights struct {
Rights [2]uint64
}
type Utsname struct {
Sysname [256]byte
Nodename [256]byte
Release [256]byte
Version [256]byte
Machine [256]byte
}
| {
"pile_set_name": "Github"
} |
<!--
Copyright 2014 Google 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.
-->
<resources>
<declare-styleable name="ScrimInsetsView">
<attr name="obaInsetForeground" format="reference|color"/>
</declare-styleable>
<declare-styleable name="RealtimeIndicatorView">
<!-- Duration of animation, in milliseconds -->
<attr name="duration" format="reference|integer"/>
<!-- Color of circle -->
<attr name="fillColor" format="reference|color"/>
<!-- Color of circle -->
<attr name="lineColor" format="reference|color"/>
</declare-styleable>
</resources>
| {
"pile_set_name": "Github"
} |
{
"_from": "source-map@~0.6.1",
"_id": "[email protected]",
"_inBundle": false,
"_integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"_location": "/uglify-js/source-map",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "source-map@~0.6.1",
"name": "source-map",
"escapedName": "source-map",
"rawSpec": "~0.6.1",
"saveSpec": null,
"fetchSpec": "~0.6.1"
},
"_requiredBy": [
"/uglify-js"
],
"_resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"_shasum": "74722af32e9614e9c287a8d0bbde48b5e2f1a263",
"_spec": "source-map@~0.6.1",
"_where": "F:\\git\\node.js\\4-1Express\\Express的CRUD\\node_modules\\uglify-js",
"author": {
"name": "Nick Fitzgerald",
"email": "[email protected]"
},
"bugs": {
"url": "https://github.com/mozilla/source-map/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Tobias Koppers",
"email": "[email protected]"
},
{
"name": "Duncan Beevers",
"email": "[email protected]"
},
{
"name": "Stephen Crane",
"email": "[email protected]"
},
{
"name": "Ryan Seddon",
"email": "[email protected]"
},
{
"name": "Miles Elam",
"email": "[email protected]"
},
{
"name": "Mihai Bazon",
"email": "[email protected]"
},
{
"name": "Michael Ficarra",
"email": "[email protected]"
},
{
"name": "Todd Wolfson",
"email": "[email protected]"
},
{
"name": "Alexander Solovyov",
"email": "[email protected]"
},
{
"name": "Felix Gnass",
"email": "[email protected]"
},
{
"name": "Conrad Irwin",
"email": "[email protected]"
},
{
"name": "usrbincc",
"email": "[email protected]"
},
{
"name": "David Glasser",
"email": "[email protected]"
},
{
"name": "Chase Douglas",
"email": "[email protected]"
},
{
"name": "Evan Wallace",
"email": "[email protected]"
},
{
"name": "Heather Arthur",
"email": "[email protected]"
},
{
"name": "Hugh Kennedy",
"email": "[email protected]"
},
{
"name": "David Glasser",
"email": "[email protected]"
},
{
"name": "Simon Lydell",
"email": "[email protected]"
},
{
"name": "Jmeas Smith",
"email": "[email protected]"
},
{
"name": "Michael Z Goddard",
"email": "[email protected]"
},
{
"name": "azu",
"email": "[email protected]"
},
{
"name": "John Gozde",
"email": "[email protected]"
},
{
"name": "Adam Kirkton",
"email": "[email protected]"
},
{
"name": "Chris Montgomery",
"email": "[email protected]"
},
{
"name": "J. Ryan Stinnett",
"email": "[email protected]"
},
{
"name": "Jack Herrington",
"email": "[email protected]"
},
{
"name": "Chris Truter",
"email": "[email protected]"
},
{
"name": "Daniel Espeset",
"email": "[email protected]"
},
{
"name": "Jamie Wong",
"email": "[email protected]"
},
{
"name": "Eddy Bruël",
"email": "[email protected]"
},
{
"name": "Hawken Rives",
"email": "[email protected]"
},
{
"name": "Gilad Peleg",
"email": "[email protected]"
},
{
"name": "djchie",
"email": "[email protected]"
},
{
"name": "Gary Ye",
"email": "[email protected]"
},
{
"name": "Nicolas Lalevée",
"email": "[email protected]"
}
],
"deprecated": false,
"description": "Generates and consumes source maps",
"devDependencies": {
"doctoc": "^0.15.0",
"webpack": "^1.12.0"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"source-map.js",
"source-map.d.ts",
"lib/",
"dist/source-map.debug.js",
"dist/source-map.js",
"dist/source-map.min.js",
"dist/source-map.min.js.map"
],
"homepage": "https://github.com/mozilla/source-map",
"license": "BSD-3-Clause",
"main": "./source-map.js",
"name": "source-map",
"repository": {
"type": "git",
"url": "git+ssh://[email protected]/mozilla/source-map.git"
},
"scripts": {
"build": "webpack --color",
"test": "npm run build && node test/run-tests.js",
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
},
"typings": "source-map",
"version": "0.6.1"
}
| {
"pile_set_name": "Github"
} |
{
"include": [
"src/**/*.ts"
],
"exclude": [],
"rules": {
"array-type": [true, "array-simple"],
"arrow-return-shorthand": true,
"ban": [true,
{"name": "parseInt", "message": "See http://goto.google.com/tsstyle#type-coercion"},
{"name": "parseFloat", "message": "See http://goto.google.com/tsstyle#type-coercion"},
{"name": "Array", "message": "See http://goto.google.com/tsstyle#array-constructor"},
{"name": ["*", "innerText"], "message": "Use .textContent instead. http://goto.google.com/typescript/patterns#browser-oddities"}
],
"ban-types": [true,
["Object", "Use {} or 'object' instead. See http://goto.google.com/ts-style#redundant-types"],
["String", "Use 'string' instead."],
["Number", "Use 'number' instead."],
["Boolean", "Use 'boolean' instead."]
],
"class-name": true,
"curly": [true, "ignore-same-line"],
"forin": true,
"interface-name": [true, "never-prefix"],
"interface-over-type-literal": true,
"jsdoc-format": true,
"label-position": true,
"member-access": [true, "no-public"],
"new-parens": true,
"no-angle-bracket-type-assertion": true,
"no-any": true,
"no-construct": true,
"no-debugger": true,
"no-default-export": true,
"no-duplicate-switch-case": true,
"no-inferrable-types": true,
"no-namespace": [true, "allow-declarations"],
"no-reference": true,
"no-require-imports": true,
"no-string-throw": true,
"no-return-await": true,
"no-unsafe-finally": true,
"no-unused-expression": [true, "allow-new"], // E.g. new ModifyGlobalState(); without assignment.
"no-var-keyword": true,
"object-literal-shorthand": true,
"only-arrow-functions": [true, "allow-declarations", "allow-named-functions"],
"prefer-const": true,
"radix": true,
"semicolon": [true, "always", "ignore-bound-class-methods"],
"switch-default": true,
"triple-equals": [true, "allow-null-check"],
"variable-name": [
true,
"check-format",
"ban-keywords",
"allow-leading-underscore",
"allow-trailing-underscore",
"allow-pascal-case"
],
"deprecation": true,
"no-for-in-array": true,
"no-unnecessary-type-assertion": true,
"restrict-plus-operands": true,
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator"
]
},
"jsRules": {
"no-empty": true
}
}
| {
"pile_set_name": "Github"
} |
import { batchActions } from 'redux-batched-actions';
import createAjaxRequest from 'Utilities/createAjaxRequest';
import { set, update, updateItem } from '../baseActions';
export default function createFetchHandler(section, url) {
return function(getState, payload, dispatch) {
dispatch(set({ section, isFetching: true }));
const {
id,
...otherPayload
} = payload;
const { request, abortRequest } = createAjaxRequest({
url: id == null ? url : `${url}/${id}`,
data: otherPayload,
traditional: true
});
request.done((data) => {
dispatch(batchActions([
id == null ? update({ section, data }) : updateItem({ section, ...data }),
set({
section,
isFetching: false,
isPopulated: true,
error: null
})
]));
});
request.fail((xhr) => {
dispatch(set({
section,
isFetching: false,
isPopulated: false,
error: xhr.aborted ? null : xhr
}));
});
return abortRequest;
};
}
| {
"pile_set_name": "Github"
} |
mfsrestoremaster(8)
===================
== NAME
mfsrestoremaster - scripts automating starting master server on a metalogger machine.
== SYNOPSIS
[verse]
*mfsrestoremaster* '<net-interface>' '[<etc-lfs-dir>]'
*<net-interface>*::
Network interface to reconfigure.
*<etc-lfs-dir>*::
LizardFS configuration directory to use (default: `/etc/lizardfs`).
== DESCRIPTION
This scripts performs the following steps:
* verify basic sanity of configuration files,
* update metadata image with data from metalogger changelogs,
* set master's IP address on given network interface,
* start the master server.
== NOTES
`mfsrestoremaster` makes use of `mfsmetarestore`.
== COPYRIGHT
Copyright 2008-2009 Gemius SA, 2013-2019 Skytechnology sp. z o.o.
LizardFS 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, version 3.
LizardFS 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 LizardFS. If not, see
<http://www.gnu.org/licenses/>.
== SEE ALSO
mfsmetarestore(8), mfstools(1)
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `remove_file` fn in crate `std`.">
<meta name="keywords" content="rust, rustlang, rust-lang, remove_file">
<title>std::fs::remove_file - Rust</title>
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
<link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../../std/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a>
<p class='location'><a href='../index.html'>std</a>::<wbr><a href='index.html'>fs</a></p><script>window.sidebarCurrent = {name: 'remove_file', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'>Function <a href='../index.html'>std</a>::<wbr><a href='index.html'>fs</a>::<wbr><a class='fn' href=''>remove_file</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-3760' class='srclink' href='../../src/std/fs.rs.html#778-780' title='goto source code'>[src]</a></span></h1>
<pre class='rust fn'>pub fn remove_file<P: <a class='trait' href='../../std/convert/trait.AsRef.html' title='std::convert::AsRef'>AsRef</a><<a class='struct' href='../../std/path/struct.Path.html' title='std::path::Path'>Path</a>>>(path: P) -> <a class='type' href='../../std/io/type.Result.html' title='std::io::Result'>Result</a><<a class='primitive' href='../primitive.tuple.html'>()</a>></pre><div class='docblock'><p>Removes a file from the filesystem.</p>
<p>Note that there is no
guarantee that the file is immediately deleted (e.g. depending on
platform, other open file descriptors may prevent immediate removal).</p>
<h1 id='errors' class='section-header'><a href='#errors'>Errors</a></h1>
<p>This function will return an error if <code>path</code> points to a directory, if the
user lacks permissions to remove the file, or if some other filesystem-level
error occurs.</p>
<h1 id='examples' class='section-header'><a href='#examples'>Examples</a></h1><span class='rusttest'>fn main() {
use std::fs;
fn foo() -> std::io::Result<()> {
try!(fs::remove_file("a.txt"));
Ok(())
}
}</span><pre class='rust rust-example-rendered'>
<span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>fs</span>;
<span class='macro'>try</span><span class='macro'>!</span>(<span class='ident'>fs</span>::<span class='ident'>remove_file</span>(<span class='string'>"a.txt"</span>));</pre>
</div></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "std";
window.playgroundUrl = "https://play.rust-lang.org/";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script src="../../playpen.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html> | {
"pile_set_name": "Github"
} |
/* krb5_asn.h */
/*
* Written by Vern Staats <[email protected]> for the OpenSSL project, **
* using ocsp/{*.h,*asn*.c} as a starting point
*/
/* ====================================================================
* Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* ([email protected]). This product includes software written by Tim
* Hudson ([email protected]).
*
*/
#ifndef HEADER_KRB5_ASN_H
# define HEADER_KRB5_ASN_H
/*
* #include <krb5.h>
*/
# include <openssl/safestack.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* ASN.1 from Kerberos RFC 1510
*/
/*- EncryptedData ::= SEQUENCE {
* etype[0] INTEGER, -- EncryptionType
* kvno[1] INTEGER OPTIONAL,
* cipher[2] OCTET STRING -- ciphertext
* }
*/
typedef struct krb5_encdata_st {
ASN1_INTEGER *etype;
ASN1_INTEGER *kvno;
ASN1_OCTET_STRING *cipher;
} KRB5_ENCDATA;
DECLARE_STACK_OF(KRB5_ENCDATA)
/*- PrincipalName ::= SEQUENCE {
* name-type[0] INTEGER,
* name-string[1] SEQUENCE OF GeneralString
* }
*/
typedef struct krb5_princname_st {
ASN1_INTEGER *nametype;
STACK_OF(ASN1_GENERALSTRING) *namestring;
} KRB5_PRINCNAME;
DECLARE_STACK_OF(KRB5_PRINCNAME)
/*- Ticket ::= [APPLICATION 1] SEQUENCE {
* tkt-vno[0] INTEGER,
* realm[1] Realm,
* sname[2] PrincipalName,
* enc-part[3] EncryptedData
* }
*/
typedef struct krb5_tktbody_st {
ASN1_INTEGER *tktvno;
ASN1_GENERALSTRING *realm;
KRB5_PRINCNAME *sname;
KRB5_ENCDATA *encdata;
} KRB5_TKTBODY;
typedef STACK_OF(KRB5_TKTBODY) KRB5_TICKET;
DECLARE_STACK_OF(KRB5_TKTBODY)
/*- AP-REQ ::= [APPLICATION 14] SEQUENCE {
* pvno[0] INTEGER,
* msg-type[1] INTEGER,
* ap-options[2] APOptions,
* ticket[3] Ticket,
* authenticator[4] EncryptedData
* }
*
* APOptions ::= BIT STRING {
* reserved(0), use-session-key(1), mutual-required(2) }
*/
typedef struct krb5_ap_req_st {
ASN1_INTEGER *pvno;
ASN1_INTEGER *msgtype;
ASN1_BIT_STRING *apoptions;
KRB5_TICKET *ticket;
KRB5_ENCDATA *authenticator;
} KRB5_APREQBODY;
typedef STACK_OF(KRB5_APREQBODY) KRB5_APREQ;
DECLARE_STACK_OF(KRB5_APREQBODY)
/* Authenticator Stuff */
/*- Checksum ::= SEQUENCE {
* cksumtype[0] INTEGER,
* checksum[1] OCTET STRING
* }
*/
typedef struct krb5_checksum_st {
ASN1_INTEGER *ctype;
ASN1_OCTET_STRING *checksum;
} KRB5_CHECKSUM;
DECLARE_STACK_OF(KRB5_CHECKSUM)
/*- EncryptionKey ::= SEQUENCE {
* keytype[0] INTEGER,
* keyvalue[1] OCTET STRING
* }
*/
typedef struct krb5_encryptionkey_st {
ASN1_INTEGER *ktype;
ASN1_OCTET_STRING *keyvalue;
} KRB5_ENCKEY;
DECLARE_STACK_OF(KRB5_ENCKEY)
/*- AuthorizationData ::= SEQUENCE OF SEQUENCE {
* ad-type[0] INTEGER,
* ad-data[1] OCTET STRING
* }
*/
typedef struct krb5_authorization_st {
ASN1_INTEGER *adtype;
ASN1_OCTET_STRING *addata;
} KRB5_AUTHDATA;
DECLARE_STACK_OF(KRB5_AUTHDATA)
/*- -- Unencrypted authenticator
* Authenticator ::= [APPLICATION 2] SEQUENCE {
* authenticator-vno[0] INTEGER,
* crealm[1] Realm,
* cname[2] PrincipalName,
* cksum[3] Checksum OPTIONAL,
* cusec[4] INTEGER,
* ctime[5] KerberosTime,
* subkey[6] EncryptionKey OPTIONAL,
* seq-number[7] INTEGER OPTIONAL,
* authorization-data[8] AuthorizationData OPTIONAL
* }
*/
typedef struct krb5_authenticator_st {
ASN1_INTEGER *avno;
ASN1_GENERALSTRING *crealm;
KRB5_PRINCNAME *cname;
KRB5_CHECKSUM *cksum;
ASN1_INTEGER *cusec;
ASN1_GENERALIZEDTIME *ctime;
KRB5_ENCKEY *subkey;
ASN1_INTEGER *seqnum;
KRB5_AUTHDATA *authorization;
} KRB5_AUTHENTBODY;
typedef STACK_OF(KRB5_AUTHENTBODY) KRB5_AUTHENT;
DECLARE_STACK_OF(KRB5_AUTHENTBODY)
/*- DECLARE_ASN1_FUNCTIONS(type) = DECLARE_ASN1_FUNCTIONS_name(type, type) =
* type *name##_new(void);
* void name##_free(type *a);
* DECLARE_ASN1_ENCODE_FUNCTIONS(type, name, name) =
* DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name) =
* type *d2i_##name(type **a, const unsigned char **in, long len);
* int i2d_##name(type *a, unsigned char **out);
* DECLARE_ASN1_ITEM(itname) = OPENSSL_EXTERN const ASN1_ITEM itname##_it
*/
DECLARE_ASN1_FUNCTIONS(KRB5_ENCDATA)
DECLARE_ASN1_FUNCTIONS(KRB5_PRINCNAME)
DECLARE_ASN1_FUNCTIONS(KRB5_TKTBODY)
DECLARE_ASN1_FUNCTIONS(KRB5_APREQBODY)
DECLARE_ASN1_FUNCTIONS(KRB5_TICKET)
DECLARE_ASN1_FUNCTIONS(KRB5_APREQ)
DECLARE_ASN1_FUNCTIONS(KRB5_CHECKSUM)
DECLARE_ASN1_FUNCTIONS(KRB5_ENCKEY)
DECLARE_ASN1_FUNCTIONS(KRB5_AUTHDATA)
DECLARE_ASN1_FUNCTIONS(KRB5_AUTHENTBODY)
DECLARE_ASN1_FUNCTIONS(KRB5_AUTHENT)
/* BEGIN ERROR CODES */
/*
* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
!--------------------------------------------------------------------------------------------------!
! CP2K: A general program to perform molecular dynamics simulations !
! Copyright 2000-2020 CP2K developers group <https://cp2k.org> !
! !
! SPDX-License-Identifier: GPL-2.0-or-later !
!--------------------------------------------------------------------------------------------------!
! **************************************************************************************************
!> \brief Util force_env module
!> \author Teodoro Laino [tlaino] - 02.2011
! **************************************************************************************************
MODULE force_env_utils
USE atomic_kind_list_types, ONLY: atomic_kind_list_type
USE cell_types, ONLY: cell_type
USE constraint, ONLY: rattle_control,&
shake_control
USE constraint_util, ONLY: getold
USE cp_subsys_types, ONLY: cp_subsys_get,&
cp_subsys_type
USE distribution_1d_types, ONLY: distribution_1d_type
USE force_env_types, ONLY: force_env_get,&
force_env_type
USE input_section_types, ONLY: section_vals_get,&
section_vals_get_subs_vals,&
section_vals_type,&
section_vals_val_get
USE kinds, ONLY: dp
USE mathlib, ONLY: det_3x3,&
jacobi
USE molecule_kind_list_types, ONLY: molecule_kind_list_type
USE molecule_list_types, ONLY: molecule_list_type
USE molecule_types, ONLY: global_constraint_type
USE particle_list_types, ONLY: particle_list_type
USE particle_types, ONLY: update_particle_set
USE physcon, ONLY: pascal
#include "./base/base_uses.f90"
IMPLICIT NONE
PRIVATE
CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'force_env_utils'
PUBLIC :: force_env_shake, &
force_env_rattle, &
rescale_forces, &
write_stress_tensor, &
write_forces
CONTAINS
! **************************************************************************************************
!> \brief perform shake (enforcing of constraints)
!> \param force_env the force env to shake
!> \param dt the dt for shake (if you are not interested in the velocities
!> it can be any positive number)
!> \param shake_tol the tolerance for shake
!> \param log_unit if >0 then some information on the shake is printed,
!> defaults to -1
!> \param lagrange_mult ...
!> \param dump_lm ...
!> \param pos ...
!> \param vel ...
!> \param compold ...
!> \param reset ...
!> \author fawzi
! **************************************************************************************************
SUBROUTINE force_env_shake(force_env, dt, shake_tol, log_unit, lagrange_mult, dump_lm, &
pos, vel, compold, reset)
TYPE(force_env_type), POINTER :: force_env
REAL(kind=dp), INTENT(IN), OPTIONAL :: dt
REAL(kind=dp), INTENT(IN) :: shake_tol
INTEGER, INTENT(in), OPTIONAL :: log_unit, lagrange_mult
LOGICAL, INTENT(IN), OPTIONAL :: dump_lm
REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT), &
OPTIONAL, TARGET :: pos, vel
LOGICAL, INTENT(IN), OPTIONAL :: compold, reset
CHARACTER(len=*), PARAMETER :: routineN = 'force_env_shake'
INTEGER :: handle, i, iparticle, iparticle_kind, iparticle_local, j, my_lagrange_mult, &
my_log_unit, nparticle_kind, nparticle_local
LOGICAL :: has_pos, has_vel, my_dump_lm
REAL(KIND=dp) :: mydt
REAL(KIND=dp), DIMENSION(:, :), POINTER :: my_pos, my_vel
TYPE(atomic_kind_list_type), POINTER :: atomic_kinds
TYPE(cell_type), POINTER :: cell
TYPE(cp_subsys_type), POINTER :: subsys
TYPE(distribution_1d_type), POINTER :: local_molecules, local_particles
TYPE(global_constraint_type), POINTER :: gci
TYPE(molecule_kind_list_type), POINTER :: molecule_kinds
TYPE(molecule_list_type), POINTER :: molecules
TYPE(particle_list_type), POINTER :: particles
CALL timeset(routineN, handle)
CPASSERT(ASSOCIATED(force_env))
CPASSERT(force_env%ref_count > 0)
my_log_unit = -1
IF (PRESENT(log_unit)) my_log_unit = log_unit
my_lagrange_mult = -1
IF (PRESENT(lagrange_mult)) my_lagrange_mult = lagrange_mult
my_dump_lm = .FALSE.
IF (PRESENT(dump_lm)) my_dump_lm = dump_lm
NULLIFY (subsys, cell, molecules, molecule_kinds, local_molecules, particles, &
my_pos, my_vel, gci)
IF (PRESENT(pos)) my_pos => pos
IF (PRESENT(vel)) my_vel => vel
mydt = 0.1_dp
IF (PRESENT(dt)) mydt = dt
CALL force_env_get(force_env, subsys=subsys, cell=cell)
CALL cp_subsys_get(subsys, &
atomic_kinds=atomic_kinds, &
local_molecules=local_molecules, &
local_particles=local_particles, &
molecules=molecules, &
molecule_kinds=molecule_kinds, &
particles=particles, &
gci=gci)
nparticle_kind = atomic_kinds%n_els
IF (PRESENT(compold)) THEN
IF (compold) THEN
CALL getold(gci, local_molecules, molecules%els, molecule_kinds%els, &
particles%els, cell)
END IF
END IF
has_pos = .FALSE.
IF (.NOT. ASSOCIATED(my_pos)) THEN
has_pos = .TRUE.
ALLOCATE (my_pos(3, particles%n_els))
my_pos = 0.0_dp
DO iparticle_kind = 1, nparticle_kind
nparticle_local = local_particles%n_el(iparticle_kind)
DO iparticle_local = 1, nparticle_local
iparticle = local_particles%list(iparticle_kind)%array(iparticle_local)
my_pos(:, iparticle) = particles%els(iparticle)%r(:)
END DO
END DO
END IF
has_vel = .FALSE.
IF (.NOT. ASSOCIATED(my_vel)) THEN
has_vel = .TRUE.
ALLOCATE (my_vel(3, particles%n_els))
my_vel = 0.0_dp
DO iparticle_kind = 1, nparticle_kind
nparticle_local = local_particles%n_el(iparticle_kind)
DO iparticle_local = 1, nparticle_local
iparticle = local_particles%list(iparticle_kind)%array(iparticle_local)
my_vel(:, iparticle) = particles%els(iparticle)%v(:)
END DO
END DO
END IF
CALL shake_control(gci=gci, local_molecules=local_molecules, &
molecule_set=molecules%els, molecule_kind_set=molecule_kinds%els, &
particle_set=particles%els, pos=my_pos, vel=my_vel, dt=mydt, &
shake_tol=shake_tol, log_unit=my_log_unit, lagrange_mult=my_lagrange_mult, &
dump_lm=my_dump_lm, cell=cell, group=force_env%para_env%group, &
local_particles=local_particles)
! Possibly reset the lagrange multipliers
IF (PRESENT(reset)) THEN
IF (reset) THEN
! Reset Intramolecular constraints
DO i = 1, SIZE(molecules%els)
IF (ASSOCIATED(molecules%els(i)%lci%lcolv)) THEN
DO j = 1, SIZE(molecules%els(i)%lci%lcolv)
! Reset langrange multiplier
molecules%els(i)%lci%lcolv(j)%lambda = 0.0_dp
END DO
END IF
IF (ASSOCIATED(molecules%els(i)%lci%lg3x3)) THEN
DO j = 1, SIZE(molecules%els(i)%lci%lg3x3)
! Reset langrange multiplier
molecules%els(i)%lci%lg3x3(j)%lambda = 0.0_dp
END DO
END IF
IF (ASSOCIATED(molecules%els(i)%lci%lg4x6)) THEN
DO j = 1, SIZE(molecules%els(i)%lci%lg4x6)
! Reset langrange multiplier
molecules%els(i)%lci%lg4x6(j)%lambda = 0.0_dp
END DO
END IF
END DO
! Reset Intermolecular constraints
IF (ASSOCIATED(gci)) THEN
IF (ASSOCIATED(gci%lcolv)) THEN
DO j = 1, SIZE(gci%lcolv)
! Reset langrange multiplier
gci%lcolv(j)%lambda = 0.0_dp
END DO
END IF
IF (ASSOCIATED(gci%lg3x3)) THEN
DO j = 1, SIZE(gci%lg3x3)
! Reset langrange multiplier
gci%lg3x3(j)%lambda = 0.0_dp
END DO
END IF
IF (ASSOCIATED(gci%lg4x6)) THEN
DO j = 1, SIZE(gci%lg4x6)
! Reset langrange multiplier
gci%lg4x6(j)%lambda = 0.0_dp
END DO
END IF
END IF
END IF
END IF
IF (has_pos) THEN
CALL update_particle_set(particles%els, force_env%para_env%group, pos=my_pos)
DEALLOCATE (my_pos)
END IF
IF (has_vel) THEN
CALL update_particle_set(particles%els, force_env%para_env%group, vel=my_vel)
DEALLOCATE (my_vel)
END IF
CALL timestop(handle)
END SUBROUTINE force_env_shake
! **************************************************************************************************
!> \brief perform rattle (enforcing of constraints on velocities)
!> This routine can be easily adapted to performe rattle on whatever
!> other vector different from forces..
!> \param force_env the force env to shake
!> \param dt the dt for shake (if you are not interested in the velocities
!> it can be any positive number)
!> \param shake_tol the tolerance for shake
!> \param log_unit if >0 then some information on the shake is printed,
!> defaults to -1
!> \param lagrange_mult ...
!> \param dump_lm ...
!> \param vel ...
!> \param reset ...
!> \author tlaino
! **************************************************************************************************
SUBROUTINE force_env_rattle(force_env, dt, shake_tol, log_unit, lagrange_mult, dump_lm, &
vel, reset)
TYPE(force_env_type), POINTER :: force_env
REAL(kind=dp), INTENT(in), OPTIONAL :: dt
REAL(kind=dp), INTENT(in) :: shake_tol
INTEGER, INTENT(in), OPTIONAL :: log_unit, lagrange_mult
LOGICAL, INTENT(IN), OPTIONAL :: dump_lm
REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT), &
OPTIONAL, TARGET :: vel
LOGICAL, INTENT(IN), OPTIONAL :: reset
CHARACTER(len=*), PARAMETER :: routineN = 'force_env_rattle'
INTEGER :: handle, i, iparticle, iparticle_kind, iparticle_local, j, my_lagrange_mult, &
my_log_unit, nparticle_kind, nparticle_local
LOGICAL :: has_vel, my_dump_lm
REAL(KIND=dp) :: mydt
REAL(KIND=dp), DIMENSION(:, :), POINTER :: my_vel
TYPE(atomic_kind_list_type), POINTER :: atomic_kinds
TYPE(cell_type), POINTER :: cell
TYPE(cp_subsys_type), POINTER :: subsys
TYPE(distribution_1d_type), POINTER :: local_molecules, local_particles
TYPE(global_constraint_type), POINTER :: gci
TYPE(molecule_kind_list_type), POINTER :: molecule_kinds
TYPE(molecule_list_type), POINTER :: molecules
TYPE(particle_list_type), POINTER :: particles
CALL timeset(routineN, handle)
CPASSERT(ASSOCIATED(force_env))
CPASSERT(force_env%ref_count > 0)
my_log_unit = -1
IF (PRESENT(log_unit)) my_log_unit = log_unit
my_lagrange_mult = -1
IF (PRESENT(lagrange_mult)) my_lagrange_mult = lagrange_mult
my_dump_lm = .FALSE.
IF (PRESENT(dump_lm)) my_dump_lm = dump_lm
NULLIFY (subsys, cell, molecules, molecule_kinds, local_molecules, particles, &
my_vel)
IF (PRESENT(vel)) my_vel => vel
mydt = 0.1_dp
IF (PRESENT(dt)) mydt = dt
CALL force_env_get(force_env, subsys=subsys, cell=cell)
CALL cp_subsys_get(subsys, &
atomic_kinds=atomic_kinds, &
local_molecules=local_molecules, &
local_particles=local_particles, &
molecules=molecules, &
molecule_kinds=molecule_kinds, &
particles=particles, &
gci=gci)
nparticle_kind = atomic_kinds%n_els
has_vel = .FALSE.
IF (.NOT. ASSOCIATED(my_vel)) THEN
has_vel = .TRUE.
ALLOCATE (my_vel(3, particles%n_els))
my_vel = 0.0_dp
DO iparticle_kind = 1, nparticle_kind
nparticle_local = local_particles%n_el(iparticle_kind)
DO iparticle_local = 1, nparticle_local
iparticle = local_particles%list(iparticle_kind)%array(iparticle_local)
my_vel(:, iparticle) = particles%els(iparticle)%v(:)
END DO
END DO
END IF
CALL rattle_control(gci=gci, local_molecules=local_molecules, &
molecule_set=molecules%els, molecule_kind_set=molecule_kinds%els, &
particle_set=particles%els, vel=my_vel, dt=mydt, &
rattle_tol=shake_tol, log_unit=my_log_unit, lagrange_mult=my_lagrange_mult, &
dump_lm=my_dump_lm, cell=cell, group=force_env%para_env%group, &
local_particles=local_particles)
! Possibly reset the lagrange multipliers
IF (PRESENT(reset)) THEN
IF (reset) THEN
! Reset Intramolecular constraints
DO i = 1, SIZE(molecules%els)
IF (ASSOCIATED(molecules%els(i)%lci%lcolv)) THEN
DO j = 1, SIZE(molecules%els(i)%lci%lcolv)
! Reset langrange multiplier
molecules%els(i)%lci%lcolv(j)%lambda = 0.0_dp
END DO
END IF
IF (ASSOCIATED(molecules%els(i)%lci%lg3x3)) THEN
DO j = 1, SIZE(molecules%els(i)%lci%lg3x3)
! Reset langrange multiplier
molecules%els(i)%lci%lg3x3(j)%lambda = 0.0_dp
END DO
END IF
IF (ASSOCIATED(molecules%els(i)%lci%lg4x6)) THEN
DO j = 1, SIZE(molecules%els(i)%lci%lg4x6)
! Reset langrange multiplier
molecules%els(i)%lci%lg4x6(j)%lambda = 0.0_dp
END DO
END IF
END DO
! Reset Intermolecular constraints
IF (ASSOCIATED(gci)) THEN
IF (ASSOCIATED(gci%lcolv)) THEN
DO j = 1, SIZE(gci%lcolv)
! Reset langrange multiplier
gci%lcolv(j)%lambda = 0.0_dp
END DO
END IF
IF (ASSOCIATED(gci%lg3x3)) THEN
DO j = 1, SIZE(gci%lg3x3)
! Reset langrange multiplier
gci%lg3x3(j)%lambda = 0.0_dp
END DO
END IF
IF (ASSOCIATED(gci%lg4x6)) THEN
DO j = 1, SIZE(gci%lg4x6)
! Reset langrange multiplier
gci%lg4x6(j)%lambda = 0.0_dp
END DO
END IF
END IF
END IF
END IF
IF (has_vel) THEN
CALL update_particle_set(particles%els, force_env%para_env%group, vel=my_vel)
END IF
DEALLOCATE (my_vel)
CALL timestop(handle)
END SUBROUTINE force_env_rattle
! **************************************************************************************************
!> \brief Rescale forces if requested
!> \param force_env the force env to shake
!> \author tlaino
! **************************************************************************************************
SUBROUTINE rescale_forces(force_env)
TYPE(force_env_type), POINTER :: force_env
CHARACTER(len=*), PARAMETER :: routineN = 'rescale_forces'
INTEGER :: handle, iparticle
LOGICAL :: explicit
REAL(KIND=dp) :: force(3), max_value, mod_force
TYPE(cp_subsys_type), POINTER :: subsys
TYPE(particle_list_type), POINTER :: particles
TYPE(section_vals_type), POINTER :: rescale_force_section
CALL timeset(routineN, handle)
CPASSERT(ASSOCIATED(force_env))
CPASSERT(force_env%ref_count > 0)
rescale_force_section => section_vals_get_subs_vals(force_env%force_env_section, "RESCALE_FORCES")
CALL section_vals_get(rescale_force_section, explicit=explicit)
IF (explicit) THEN
CALL section_vals_val_get(rescale_force_section, "MAX_FORCE", r_val=max_value)
CALL force_env_get(force_env, subsys=subsys)
CALL cp_subsys_get(subsys, particles=particles)
DO iparticle = 1, SIZE(particles%els)
force = particles%els(iparticle)%f(:)
mod_force = SQRT(DOT_PRODUCT(force, force))
IF ((mod_force > max_value) .AND. (mod_force /= 0.0_dp)) THEN
force = force/mod_force*max_value
particles%els(iparticle)%f(:) = force
END IF
END DO
END IF
CALL timestop(handle)
END SUBROUTINE rescale_forces
! **************************************************************************************************
!> \brief Variable precision output of the stress tensor
!>
!> \param pv_virial ...
!> \param output_unit ...
!> \param cell ...
!> \param ndigits ...
!> \param numerical ...
!> \author MK (26.08.2010)
! **************************************************************************************************
SUBROUTINE write_stress_tensor(pv_virial, output_unit, cell, ndigits, numerical)
REAL(KIND=dp), DIMENSION(3, 3), INTENT(IN) :: pv_virial
INTEGER, INTENT(IN) :: output_unit
TYPE(cell_type), POINTER :: cell
INTEGER, INTENT(IN) :: ndigits
LOGICAL, INTENT(IN) :: numerical
CHARACTER(LEN=15) :: fmtstr3
CHARACTER(LEN=16) :: fmtstr4
CHARACTER(LEN=22) :: fmtstr2
CHARACTER(LEN=27) :: fmtstr5
CHARACTER(LEN=31) :: fmtstr1
INTEGER :: n
REAL(KIND=dp), DIMENSION(3) :: eigval
REAL(KIND=dp), DIMENSION(3, 3) :: eigvec, stress_tensor
IF (output_unit > 0) THEN
CPASSERT(ASSOCIATED(cell))
stress_tensor(:, :) = pv_virial(:, :)/cell%deth*pascal*1.0E-9_dp
n = MIN(MAX(1, ndigits), 20)
fmtstr1 = "(/,T2,A,/,/,T13,A1,2( X,A1))"
WRITE (UNIT=fmtstr1(22:23), FMT="(I2)") n + 7
fmtstr2 = "(T3,A,T5,3(1X,F . ))"
WRITE (UNIT=fmtstr2(16:17), FMT="(I2)") n + 7
WRITE (UNIT=fmtstr2(19:20), FMT="(I2)") n
fmtstr3 = "(/,T3,A,F . )"
WRITE (UNIT=fmtstr3(10:11), FMT="(I2)") n + 8
WRITE (UNIT=fmtstr3(13:14), FMT="(I2)") n
IF (numerical) THEN
WRITE (UNIT=output_unit, FMT=fmtstr1) &
"NUMERICAL STRESS TENSOR [GPa]", "X", "Y", "Z"
ELSE
WRITE (UNIT=output_unit, FMT=fmtstr1) &
"STRESS TENSOR [GPa]", "X", "Y", "Z"
END IF
WRITE (UNIT=output_unit, FMT=fmtstr2) "X", stress_tensor(1, 1:3)
WRITE (UNIT=output_unit, FMT=fmtstr2) "Y", stress_tensor(2, 1:3)
WRITE (UNIT=output_unit, FMT=fmtstr2) "Z", stress_tensor(3, 1:3)
fmtstr4 = "(/,T3,A,ES . )"
WRITE (UNIT=fmtstr4(11:12), FMT="(I2)") n + 8
WRITE (UNIT=fmtstr4(14:15), FMT="(I2)") n
WRITE (UNIT=output_unit, FMT=fmtstr4) &
"1/3 Trace(stress tensor): ", (stress_tensor(1, 1) + &
stress_tensor(2, 2) + &
stress_tensor(3, 3))/3.0_dp, &
"Det(stress tensor) : ", det_3x3(stress_tensor(:, 1), &
stress_tensor(:, 2), &
stress_tensor(:, 3))
eigval(:) = 0.0_dp
eigvec(:, :) = 0.0_dp
CALL jacobi(stress_tensor, eigval, eigvec)
fmtstr5 = "(/,/,T2,A,/,/,T5,3F . ,/)"
WRITE (UNIT=fmtstr5(20:21), FMT="(I2)") n + 8
WRITE (UNIT=fmtstr5(23:24), FMT="(I2)") n
WRITE (UNIT=output_unit, FMT=fmtstr5) &
"EIGENVECTORS AND EIGENVALUES OF THE STRESS TENSOR", &
eigval(1:3)
WRITE (UNIT=output_unit, FMT=fmtstr2) " ", eigvec(1, 1:3)
WRITE (UNIT=output_unit, FMT=fmtstr2) " ", eigvec(2, 1:3)
WRITE (UNIT=output_unit, FMT=fmtstr2) " ", eigvec(3, 1:3)
END IF
END SUBROUTINE write_stress_tensor
! **************************************************************************************************
!> \brief Write forces
!>
!> \param particles ...
!> \param output_unit ...
!> \param label ...
!> \param ndigits ...
!> \param total_force ...
!> \param grand_total_force ...
!> \param zero_force_core_shell_atom ...
!> \author MK (06.09.2010)
! **************************************************************************************************
SUBROUTINE write_forces(particles, output_unit, label, ndigits, total_force, &
grand_total_force, zero_force_core_shell_atom)
TYPE(particle_list_type), POINTER :: particles
INTEGER, INTENT(IN) :: output_unit
CHARACTER(LEN=*), INTENT(IN) :: label
INTEGER, INTENT(IN) :: ndigits
REAL(KIND=dp), DIMENSION(3), INTENT(OUT) :: total_force
REAL(KIND=dp), DIMENSION(3), INTENT(INOUT), &
OPTIONAL :: grand_total_force
LOGICAL, INTENT(IN), OPTIONAL :: zero_force_core_shell_atom
CHARACTER(LEN=23) :: fmtstr3
CHARACTER(LEN=36) :: fmtstr2
CHARACTER(LEN=46) :: fmtstr1
INTEGER :: i, ikind, iparticle, n
LOGICAL :: zero_force
REAL(KIND=dp), DIMENSION(3) :: f
IF (output_unit > 0) THEN
CPASSERT(ASSOCIATED(particles))
n = MIN(MAX(1, ndigits), 20)
fmtstr1 = "(/,T2,A,/,/,T2,A,T11,A,T18,A,T35,A1,2( X,A1))"
WRITE (UNIT=fmtstr1(39:40), FMT="(I2)") n + 6
fmtstr2 = "(T2,I6,1X,I6,T21,A,T28,3(1X,F . ))"
WRITE (UNIT=fmtstr2(33:34), FMT="(I2)") n
WRITE (UNIT=fmtstr2(30:31), FMT="(I2)") n + 6
fmtstr3 = "(T2,A,T28,4(1X,F . ))"
WRITE (UNIT=fmtstr3(20:21), FMT="(I2)") n
WRITE (UNIT=fmtstr3(17:18), FMT="(I2)") n + 6
IF (PRESENT(zero_force_core_shell_atom)) THEN
zero_force = zero_force_core_shell_atom
ELSE
zero_force = .FALSE.
END IF
WRITE (UNIT=output_unit, FMT=fmtstr1) &
label//" FORCES in [a.u.]", "# Atom", "Kind", "Element", "X", "Y", "Z"
total_force(1:3) = 0.0_dp
DO iparticle = 1, particles%n_els
ikind = particles%els(iparticle)%atomic_kind%kind_number
IF (particles%els(iparticle)%atom_index /= 0) THEN
i = particles%els(iparticle)%atom_index
ELSE
i = iparticle
END IF
IF (zero_force .AND. (particles%els(iparticle)%shell_index /= 0)) THEN
f(1:3) = 0.0_dp
ELSE
f(1:3) = particles%els(iparticle)%f(1:3)
END IF
WRITE (UNIT=output_unit, FMT=fmtstr2) &
i, ikind, particles%els(iparticle)%atomic_kind%element_symbol, f(1:3)
total_force(1:3) = total_force(1:3) + f(1:3)
END DO
WRITE (UNIT=output_unit, FMT=fmtstr3) &
"SUM OF "//label//" FORCES", total_force(1:3), SQRT(SUM(total_force(:)**2))
END IF
IF (PRESENT(grand_total_force)) THEN
grand_total_force(1:3) = grand_total_force(1:3) + total_force(1:3)
WRITE (UNIT=output_unit, FMT="(A)") ""
WRITE (UNIT=output_unit, FMT=fmtstr3) &
"GRAND TOTAL FORCE", grand_total_force(1:3), SQRT(SUM(grand_total_force(:)**2))
END IF
END SUBROUTINE write_forces
END MODULE force_env_utils
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IBClasses</key>
<array>
<dict>
<key>CLASS</key>
<string>SUWindowController</string>
<key>LANGUAGE</key>
<string>ObjC</string>
<key>SUPERCLASS</key>
<string>NSWindowController</string>
</dict>
<dict>
<key>ACTIONS</key>
<dict>
<key>finishPrompt</key>
<string>id</string>
<key>toggleMoreInfo</key>
<string>id</string>
</dict>
<key>CLASS</key>
<string>SUUpdatePermissionPrompt</string>
<key>LANGUAGE</key>
<string>ObjC</string>
<key>OUTLETS</key>
<dict>
<key>delegate</key>
<string>id</string>
<key>descriptionTextField</key>
<string>NSTextField</string>
<key>moreInfoButton</key>
<string>NSButton</string>
<key>moreInfoView</key>
<string>NSView</string>
</dict>
<key>SUPERCLASS</key>
<string>SUWindowController</string>
</dict>
<dict>
<key>CLASS</key>
<string>FirstResponder</string>
<key>LANGUAGE</key>
<string>ObjC</string>
<key>SUPERCLASS</key>
<string>NSObject</string>
</dict>
<dict>
<key>CLASS</key>
<string>NSObject</string>
<key>LANGUAGE</key>
<string>ObjC</string>
</dict>
</array>
<key>IBVersion</key>
<string>1</string>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2017, 2020, Oracle and/or its affiliates.
* Copyright (c) 2013, Regents of the University of California
*
* 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER 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.
*/
package com.oracle.graal.python.nodes.statement;
import static com.oracle.graal.python.runtime.exception.PythonErrorType.AssertionError;
import java.io.PrintStream;
import com.oracle.graal.python.PythonLanguage;
import com.oracle.graal.python.nodes.PRaiseNode;
import com.oracle.graal.python.nodes.SpecialMethodNames;
import com.oracle.graal.python.nodes.call.special.LookupAndCallUnaryNode;
import com.oracle.graal.python.nodes.expression.CoerceToBooleanNode;
import com.oracle.graal.python.nodes.expression.ExpressionNode;
import com.oracle.graal.python.runtime.PythonContext;
import com.oracle.graal.python.runtime.PythonOptions;
import com.oracle.graal.python.runtime.exception.PException;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.TruffleLanguage.ContextReference;
import com.oracle.truffle.api.TruffleLanguage.LanguageReference;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.profiles.ConditionProfile;
public class AssertNode extends StatementNode {
@Child private PRaiseNode raise;
@Child private CoerceToBooleanNode condition;
@Child private ExpressionNode message;
@Child private LookupAndCallUnaryNode callNode;
@CompilationFinal private Boolean assertionsEnabled = null;
@CompilationFinal private LanguageReference<PythonLanguage> languageRef;
@CompilationFinal private ContextReference<PythonContext> contextRef;
private final ConditionProfile profile = ConditionProfile.createBinaryProfile();
public AssertNode(CoerceToBooleanNode condition, ExpressionNode message) {
this.condition = condition;
this.message = message;
}
@Override
public void executeVoid(VirtualFrame frame) {
if (assertionsEnabled == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
assertionsEnabled = !getContext().getOption(PythonOptions.PythonOptimizeFlag);
}
if (assertionsEnabled) {
try {
if (profile.profile(!condition.executeBoolean(frame))) {
throw assertionFailed(frame);
}
} catch (PException e) {
// Python exceptions just fall through
throw e;
} catch (Exception e) {
if (getPythonLanguage().getEngineOption(PythonOptions.CatchAllExceptions)) {
// catch any other exception and convert to Python exception
throw assertionFailed(frame);
} else {
throw e;
}
}
}
}
private PException assertionFailed(VirtualFrame frame) {
String assertionMessage = null;
if (message != null) {
try {
Object messageObj = message.execute(frame);
if (callNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
callNode = insert(LookupAndCallUnaryNode.create(SpecialMethodNames.__STR__));
}
assertionMessage = (String) callNode.executeObject(frame, messageObj);
} catch (PException e) {
// again, Python exceptions just fall through
throw e;
} catch (Exception e) {
assertionMessage = "internal exception occurred";
if (PythonOptions.isWithJavaStacktrace(getPythonLanguage())) {
printStackTrace(getContext(), e);
}
}
}
if (raise == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
raise = insert(PRaiseNode.create());
}
if (assertionMessage == null) {
return raise.raise(AssertionError);
}
return raise.raise(AssertionError, assertionMessage);
}
public CoerceToBooleanNode getCondition() {
return condition;
}
public ExpressionNode getMessage() {
return message;
}
@TruffleBoundary
private static void printStackTrace(PythonContext context, Exception e) {
e.printStackTrace(new PrintStream(context.getStandardErr()));
}
private PythonLanguage getPythonLanguage() {
if (languageRef == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
languageRef = lookupLanguageReference(PythonLanguage.class);
}
return languageRef.get();
}
private PythonContext getContext() {
if (contextRef == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
contextRef = lookupContextReference(PythonLanguage.class);
}
return contextRef.get();
}
}
| {
"pile_set_name": "Github"
} |
---
--- CREATE_DOMAIN
---
CREATE DOMAIN domainvarchar VARCHAR(5);
NOTICE: DDL test: type simple, tag CREATE DOMAIN
CREATE DOMAIN japanese_postal_code AS TEXT
CHECK(
VALUE ~ '^\d{3}$'
OR VALUE ~ '^\d{3}-\d{4}$'
);
NOTICE: DDL test: type simple, tag CREATE DOMAIN
| {
"pile_set_name": "Github"
} |
syntax = "proto3";
package msgpb;
import "google/protobuf/timestamp.proto";
import "google/protobuf/wrappers.proto";
import "google/protobuf/any.proto";
enum DataSourceType {
UNKNOWN_DATA_SOURCE = 0;
MYSQL = 1;
MONGODB = 2;
TIDB = 3;
REDIS = 4;
CODIS = 5;
}
message Msg {
// Version is the Msg definition version
string version = 1;
// Database is the database/schema name for MySQL
// is the database for Mongo
string database = 2;
// Table is the table name for MySQL
// is the collection name for Mongo
string table = 3;
// MsgType is the message type
string msgType = 4;
// Timestamp is the binlog event header timestamp for MySQL
google.protobuf.Timestamp timestamp = 5;
DMLMsg dmlMsg = 6;
DDLMsg ddlMsg = 7;
}
// DDLMsg is not available for Mongo?
message DDLMsg {
// The DDL SQL
string SQL = 2;
}
message DMLMsg {
string Op = 1;
// Data is the changed data
map<string, google.protobuf.Any> data = 2;
// Old is the original data (if it is not empty)
map<string, google.protobuf.Any> old = 3;
// Pks is the pkColumnName -> pkColumnValue mapping,
map<string, google.protobuf.Any> pks = 4;
}
message ConfigureRequest {
map<string, google.protobuf.Any> data = 1;
}
message ConfigureResponse {
google.protobuf.StringValue error = 1;
}
message FilterRequest {
Msg msg = 1;
}
message FilterResponse {
Msg msg = 1;
bool continueNext = 2;
google.protobuf.StringValue error = 3;
}
service FilterPlugin {
rpc Configure(ConfigureRequest) returns (ConfigureResponse);
rpc Filter(FilterRequest) returns (FilterResponse);
} | {
"pile_set_name": "Github"
} |
#ifndef CondFormats_HcalObjects_HcalLinearCompositionFunctor_h
#define CondFormats_HcalObjects_HcalLinearCompositionFunctor_h
#include "FWCore/Utilities/interface/Exception.h"
#include "CondFormats/HcalObjects/interface/AbsHcalFunctor.h"
#include "boost/serialization/access.hpp"
#include "boost/serialization/version.hpp"
#include "boost/serialization/shared_ptr.hpp"
//
// A functor returning a linearly transformed value
// of another functor: f(x) = a*p(x) + b. Useful for
// implementing cuts symmetric about 0, etc.
//
class HcalLinearCompositionFunctor : public AbsHcalFunctor {
public:
// Dummy constructor, to be used for deserialization only
inline HcalLinearCompositionFunctor() : a_(0.0), b_(0.0) {}
// Normal constructor
HcalLinearCompositionFunctor(std::shared_ptr<AbsHcalFunctor> p, double a, double b);
inline ~HcalLinearCompositionFunctor() override {}
double operator()(double x) const override;
inline double xmin() const override { return other_->xmin(); }
inline double xmax() const override { return other_->xmax(); }
inline double a() const { return a_; }
inline double b() const { return b_; }
protected:
inline bool isEqual(const AbsHcalFunctor& other) const override {
const HcalLinearCompositionFunctor& r = static_cast<const HcalLinearCompositionFunctor&>(other);
return *other_ == *r.other_ && a_ == r.a_ && b_ == r.b_;
}
private:
std::shared_ptr<AbsHcalFunctor> other_;
double a_;
double b_;
friend class boost::serialization::access;
template <class Archive>
inline void serialize(Archive& ar, unsigned /* version */) {
boost::serialization::base_object<AbsHcalFunctor>(*this);
// Direct polymorphic serialization of shared_ptr is broken
// in boost for versions 1.56, 1.57, 1.58. For detail, see
// https://svn.boost.org/trac/boost/ticket/10727
#if BOOST_VERSION < 105600 || BOOST_VERSION > 105800
ar& other_& a_& b_;
#else
throw cms::Exception(
"HcalLinearCompositionFunctor can not be"
" serialized with this version of boost");
#endif
}
};
BOOST_CLASS_VERSION(HcalLinearCompositionFunctor, 1)
BOOST_CLASS_EXPORT_KEY(HcalLinearCompositionFunctor)
#endif // CondFormats_HcalObjects_HcalLinearCompositionFunctor_h
| {
"pile_set_name": "Github"
} |
{
"name": "OpticStudio",
"description": "Optical design software.",
"url": "https://www.zemax.com/products/opticstudio"
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.