text
stringlengths 1
22.8M
|
|---|
Mokgweetsi Eric Keabetswe Masisi (born 21 July 1961) is the fifth and current President of Botswana, serving since 2018. He served as the 8th Vice President of Botswana from 12 November 2014 to 1 April 2018. He was a Member of Parliament in the National Assembly for the Moshupa-Manyana constituency from 2009 to 2018.
Initially having a good relationship with former President Ian Khama, who appointed Masisi as Vice President, the two later clashed over a ban on elephant hunting, and Khama has since accused Masisi of having "stifled dissent". Coming to power in the 2019 elections, the opposition claimed irregularities and electoral fraud, however an observation mission from the African Union reported that the elections were conducted transparently and met international standards.
His government oversaw response to the COVID-19 pandemic. Amidst the pandemic, Masisi ruled by decree from March 2020 to September 2021, despite protests from the public and the opposition party.
Early life and education
Mokgweetsi Masisi is the son of Edison Masisi (1921–2003), the long-time MP for Moshupa and many-time cabinet member. The younger Masisi grew up in Gaborone, attending Thornhill Primary School and Maru A Pula School. One of his three brothers, Tshelang, was the MP for Francistown West for many years, while another is a retired army general. He also has a sister, Phadi.
In school, Masisi competed in soccer and tennis, but ultimately found acting to be his calling. In 1984, he won acclaim for his portrayal of the lead role in a Gaborone production of Cry the Beloved Country. He has taken part in several South African films.
In the 1980s, Masisi became a high school social studies teacher after graduating from the University of Botswana in 1984 in English and History. He taught at Mmanaana Secondary School in 1984 in Moshupa village before moving on to the University of Botswana in 1987 as a curriculum development specialist.
In 1989, he went to Florida State University to obtain a Master's degree in social sciences education, after Masisi met some FSU faculty members working in Botswana for the Junior Secondary Education Improvement Project. Following graduation, he was employed by UNICEF in Botswana.
Career
Masisi unsuccessfully sought the nomination of the ruling Botswana Democratic Party (BDP) to stand in Moshupa constituency in the 2004 general election. However, he obtained the BDP nomination for the same seat prior to the 2009 general election and won the seat. He was promptly appointed as Assistant Minister for Presidential Affairs and Public Administration in October 2009. After a little more than a year as an assistant minister, he was appointed as Minister for Presidential Affairs and Public Administration in January 2011. Masisi became Minister of Education and Skills Development in an acting capacity in April 2014. He was re-elected to his seat in Parliament in October 2014, and was appointed as Minister of Education and Skills Development on 28 October 2014. Masisi was appointed as Vice President of Botswana by President Ian Khama on 12 November 2014 while remaining in his post as Minister of Education.
President Khama appointed Masisi as the Chancellor of the University of Botswana on July 5, 2017. The appointment, which was in consonance with Section 7 of the University of Botswana Act of 2008, was for a period of five years. It followed the death of former President Quett Masire, who served as the Chancellor until he died on June 22, 2017.
On April 1, 2018, he was sworn in as the 5th President of Botswana. After he ascended to the presidency, his predecessor Ian Khama left the ruling Botswana Democratic Party (BDP) to found the Botswana Patriotic Front (BPF). Khama criticized Masisi for lifting the ban on elephant hunting and called his decision to appoint Masisi as his successor a "mistake".
On October 13, 2018, Masisi received an honorary doctorate from the University of Botswana. Some commentators have criticized this decision, and claimed that the correct process was not followed.
2019 elections
In October 2019, Masisi was re-elected president after the BDP faced the biggest threat to its unity in more than five decades, following Khama's move to the opposition, accusing Masisi of authoritarianism. In the 2019 Botswana general election, Masisi received a 52.65% majority of the vote and received a majority of seats in the National Assembly. The 2019 Botswana elections were hotly contested, and the main opposition, the Umbrella for Democratic Change lodged a litany of court challenges alleging irregularities and electoral fraud. The High Court ruled against the allegations and the elections were deemed credible by international observers. While the African Union Election Observation Mission (AUEOM) concluded that the elections were transparent and conducted peacefully. The election conformed to international and regional best practices and standards.
Amongst his election pledges, he proposed lifting the ban on elephant hunting and decriminalising homosexuality. When Botswana's Attorney General appealed a court decision decriminalising homosexuality later that year, Masisi (then president) spoke out in favour of the court order.
Response to the COVID-19 pandemic (2020-22)
In early 2020, COVID-19 pandemic in Botswana has occurred during Masisi's time in office. The President responded to the pandemic by declaring a state of emergency on March 31, 2020. After the declaration, emergency powers allowed Masisi to rule by decree for a period of 18 months to September 2021, despite protests from some opposition parties. In December, Botswana found evidence of a new strain, leading to a curfew being enforced from December 24, 2020 to January 3, 2021. After nearly two years of the State of Public Emergency, and threats of protests from the public and opposition parties, Masisi announced he would not renew the State of Public Emergency, which saw him rule by decree for this period, also bringing an end to the curfews that had been in place by the end of September 2021.
On 3 January 2022, it was announced that Masisi was in mandatory self-isolation after testing positive for COVID-19 during routine testing. Vice-President Slumber Tsogwane would assume the president's responsibilities while Masisi was in isolation.
Political opinions
Masisi has been accused by some of having authoritarian views, and contributing to undermining democracy in Botswana. Former President Ian Khama, who has fallen out with Masisi since his election, alleged that Masisi "stifled dissent" in an interview with the Financial Times, and added that Botswana's reputation was being undermined locally and internationally, and that democracy was in decline.
Masisi is in support of elephant hunting in Botswana, and believes that allowing some ivory trading would allow more funding for conservation. In 2019, he presented stools made from elephant feet to the national leaders of Namibia, Zambia and Zimbabwe, a move that received some criticism from international media outlets. Masisi reversed the ban on elephant hunting put in place by his predecessor, and removed Botswana's "Shoot to Kill" anti-poaching policy.
Personal life
In 2002 Masisi married Neo Maswabi, an accountant who later worked for the United Nations in New York and in Addis Ababa. They have a daughter.
Masisi is a noted fan of the Rutgers Scarlet Knights football program. While visiting the United Nations on 22 September 2018, he and his family attended the Rutgers vs. Buffalo game at SHI Stadium in Piscataway, New Jersey.
Masisi is colloquially referred to as "Sisiboy" among the population, a play of words on his family name.
References
External links
1961 births
Botswana Democratic Party politicians
Botswana educators
Florida State University alumni
Living people
Members of the National Assembly (Botswana)
Presidents of Botswana
University of Botswana alumni
Vice-presidents of Botswana
People from Moshupa
People from Gaborone
|
The Baltimore and Hanover Railroad (B&H) was a railroad that operated in Maryland in the 19th century. The 20 mile (32 km) main line ran from Emory Grove, Maryland north to the Pennsylvania state line near Black Rock Junction, where it connected with the Bachman Valley Railroad.
The B&H was chartered by the Maryland General Assembly in 1877 and began operation in 1879. The railroad was operated by the Hanover Junction, Hanover and Gettysburg Railroad.
In 1886 the B&H merged with the Bachman Valley and the Hanover Junction, Hanover and Gettysburg to form the Baltimore and Harrisburg Railway. The Baltimore and Harrisburg was controlled by the Western Maryland Railway, and the WM bought the company in 1917.
See also
List of defunct Maryland railroads
References
Defunct Maryland railroads
Predecessors of the Western Maryland Railway
Railway companies established in 1877
Railway companies disestablished in 1886
Defunct Pennsylvania railroads
1877 establishments in Pennsylvania
American companies disestablished in 1886
American companies established in 1877
|
```c
/*
* All rights reserved.
*
* This source code is licensed under both the BSD-style license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
/*-************************************
* Tuning parameters
**************************************/
#ifndef ZSTDCLI_CLEVEL_DEFAULT
# define ZSTDCLI_CLEVEL_DEFAULT 3
#endif
#ifndef ZSTDCLI_CLEVEL_MAX
# define ZSTDCLI_CLEVEL_MAX 19 /* without using --ultra */
#endif
#ifndef ZSTDCLI_NBTHREADS_DEFAULT
# define ZSTDCLI_NBTHREADS_DEFAULT 1
#endif
/*-************************************
* Dependencies
**************************************/
#include "platform.h" /* PLATFORM_POSIX_VERSION */
#include "util.h" /* UTIL_HAS_CREATEFILELIST, UTIL_createFileList, UTIL_isConsole */
#include <stdlib.h> /* getenv */
#include <string.h> /* strcmp, strlen */
#include <stdio.h> /* fprintf(), stdin, stdout, stderr */
#include <errno.h> /* errno */
#include <assert.h> /* assert */
#include "fileio.h" /* stdinmark, stdoutmark, ZSTD_EXTENSION */
#ifndef ZSTD_NOBENCH
# include "benchzstd.h" /* BMK_benchFilesAdvanced */
#endif
#ifndef ZSTD_NODICT
# include "dibio.h" /* ZDICT_cover_params_t, DiB_trainFromFiles() */
#endif
#ifndef ZSTD_NOTRACE
# include "zstdcli_trace.h"
#endif
#include "../lib/zstd.h" /* ZSTD_VERSION_STRING, ZSTD_minCLevel, ZSTD_maxCLevel */
#include "fileio_asyncio.h"
/*-************************************
* Constants
**************************************/
#define COMPRESSOR_NAME "Zstandard CLI"
#ifndef ZSTD_VERSION
# define ZSTD_VERSION "v" ZSTD_VERSION_STRING
#endif
#define AUTHOR "Yann Collet"
#define WELCOME_MESSAGE "*** %s (%i-bit) %s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(size_t)*8), ZSTD_VERSION, AUTHOR
#define ZSTD_ZSTDMT "zstdmt"
#define ZSTD_UNZSTD "unzstd"
#define ZSTD_CAT "zstdcat"
#define ZSTD_ZCAT "zcat"
#define ZSTD_GZ "gzip"
#define ZSTD_GUNZIP "gunzip"
#define ZSTD_GZCAT "gzcat"
#define ZSTD_LZMA "lzma"
#define ZSTD_UNLZMA "unlzma"
#define ZSTD_XZ "xz"
#define ZSTD_UNXZ "unxz"
#define ZSTD_LZ4 "lz4"
#define ZSTD_UNLZ4 "unlz4"
#define KB *(1 <<10)
#define MB *(1 <<20)
#define GB *(1U<<30)
#define DISPLAY_LEVEL_DEFAULT 2
static const char* g_defaultDictName = "dictionary";
static const unsigned g_defaultMaxDictSize = 110 KB;
static const int g_defaultDictCLevel = 3;
static const unsigned g_defaultSelectivityLevel = 9;
static const unsigned g_defaultMaxWindowLog = 27;
#define OVERLAP_LOG_DEFAULT 9999
#define LDM_PARAM_DEFAULT 9999 /* Default for parameters where 0 is valid */
static U32 g_overlapLog = OVERLAP_LOG_DEFAULT;
static U32 g_ldmHashLog = 0;
static U32 g_ldmMinMatch = 0;
static U32 g_ldmHashRateLog = LDM_PARAM_DEFAULT;
static U32 g_ldmBucketSizeLog = LDM_PARAM_DEFAULT;
#define DEFAULT_ACCEL 1
typedef enum { cover, fastCover, legacy } dictType;
/*-************************************
* Display Macros
**************************************/
#define DISPLAY_F(f, ...) fprintf((f), __VA_ARGS__)
#define DISPLAYOUT(...) DISPLAY_F(stdout, __VA_ARGS__)
#define DISPLAY(...) DISPLAY_F(stderr, __VA_ARGS__)
#define DISPLAYLEVEL(l, ...) { if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } }
static int g_displayLevel = DISPLAY_LEVEL_DEFAULT; /* 0 : no display, 1: errors, 2 : + result + interaction + warnings, 3 : + progression, 4 : + information */
/*-************************************
* Check Version (when CLI linked to dynamic library)
**************************************/
/* Due to usage of experimental symbols and capabilities by the CLI,
* the CLI must be linked against a dynamic library of same version */
static void checkLibVersion(void)
{
if (strcmp(ZSTD_VERSION_STRING, ZSTD_versionString())) {
DISPLAYLEVEL(1, "Error : incorrect library version (expecting : %s ; actual : %s ) \n",
ZSTD_VERSION_STRING, ZSTD_versionString());
DISPLAYLEVEL(1, "Please update library to version %s, or use stand-alone zstd binary \n",
ZSTD_VERSION_STRING);
exit(1);
}
}
/*! exeNameMatch() :
@return : a non-zero value if exeName matches test, excluding the extension
*/
static int exeNameMatch(const char* exeName, const char* test)
{
return !strncmp(exeName, test, strlen(test)) &&
(exeName[strlen(test)] == '\0' || exeName[strlen(test)] == '.');
}
/*-************************************
* Command Line
**************************************/
/* print help either in `stderr` or `stdout` depending on originating request
* error (badusage) => stderr
* help (usage_advanced) => stdout
*/
static void usage(FILE* f, const char* programName)
{
DISPLAY_F(f, "Compress or decompress the INPUT file(s); reads from STDIN if INPUT is `-` or not provided.\n\n");
DISPLAY_F(f, "Usage: %s [OPTIONS...] [INPUT... | -] [-o OUTPUT]\n\n", programName);
DISPLAY_F(f, "Options:\n");
DISPLAY_F(f, " -o OUTPUT Write output to a single file, OUTPUT.\n");
DISPLAY_F(f, " -k, --keep Preserve INPUT file(s). [Default] \n");
DISPLAY_F(f, " --rm Remove INPUT file(s) after successful (de)compression.\n");
#ifdef ZSTD_GZCOMPRESS
if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
DISPLAY_F(f, " -n, --no-name Do not store original filename when compressing.\n\n");
}
#endif
DISPLAY_F(f, "\n");
#ifndef ZSTD_NOCOMPRESS
DISPLAY_F(f, " -# Desired compression level, where `#` is a number between 1 and %d;\n", ZSTDCLI_CLEVEL_MAX);
DISPLAY_F(f, " lower numbers provide faster compression, higher numbers yield\n");
DISPLAY_F(f, " better compression ratios. [Default: %d]\n\n", ZSTDCLI_CLEVEL_DEFAULT);
#endif
#ifndef ZSTD_NODECOMPRESS
DISPLAY_F(f, " -d, --decompress Perform decompression.\n");
#endif
DISPLAY_F(f, " -D DICT Use DICT as the dictionary for compression or decompression.\n\n");
DISPLAY_F(f, " -f, --force Disable input and output checks. Allows overwriting existing files,\n");
DISPLAY_F(f, " receiving input from the console, printing output to STDOUT, and\n");
DISPLAY_F(f, " operating on links, block devices, etc. Unrecognized formats will be\n");
DISPLAY_F(f, " passed-through through as-is.\n\n");
DISPLAY_F(f, " -h Display short usage and exit.\n");
DISPLAY_F(f, " -H, --help Display full help and exit.\n");
DISPLAY_F(f, " -V, --version Display the program version and exit.\n");
DISPLAY_F(f, "\n");
}
static void usage_advanced(const char* programName)
{
DISPLAYOUT(WELCOME_MESSAGE);
DISPLAYOUT("\n");
usage(stdout, programName);
DISPLAYOUT("Advanced options:\n");
DISPLAYOUT(" -c, --stdout Write to STDOUT (even if it is a console) and keep the INPUT file(s).\n\n");
DISPLAYOUT(" -v, --verbose Enable verbose output; pass multiple times to increase verbosity.\n");
DISPLAYOUT(" -q, --quiet Suppress warnings; pass twice to suppress errors.\n");
#ifndef ZSTD_NOTRACE
DISPLAYOUT(" --trace LOG Log tracing information to LOG.\n");
#endif
DISPLAYOUT("\n");
DISPLAYOUT(" --[no-]progress Forcibly show/hide the progress counter. NOTE: Any (de)compressed\n");
DISPLAYOUT(" output to terminal will mix with progress counter text.\n\n");
#ifdef UTIL_HAS_CREATEFILELIST
DISPLAYOUT(" -r Operate recursively on directories.\n");
DISPLAYOUT(" --filelist LIST Read a list of files to operate on from LIST.\n");
DISPLAYOUT(" --output-dir-flat DIR Store processed files in DIR.\n");
#endif
#ifdef UTIL_HAS_MIRRORFILELIST
DISPLAYOUT(" --output-dir-mirror DIR Store processed files in DIR, respecting original directory structure.\n");
#endif
if (AIO_supported())
DISPLAYOUT(" --[no-]asyncio Use asynchronous IO. [Default: Enabled]\n");
DISPLAYOUT("\n");
#ifndef ZSTD_NOCOMPRESS
DISPLAYOUT(" --[no-]check Add XXH64 integrity checksums during compression. [Default: Add, Validate]\n");
#ifndef ZSTD_NODECOMPRESS
DISPLAYOUT(" If `-d` is present, ignore/validate checksums during decompression.\n");
#endif
#else
#ifdef ZSTD_NOCOMPRESS
DISPLAYOUT(" --[no-]check Ignore/validate checksums during decompression. [Default: Validate]");
#endif
#endif /* ZSTD_NOCOMPRESS */
DISPLAYOUT("\n");
DISPLAYOUT(" -- Treat remaining arguments after `--` as files.\n");
#ifndef ZSTD_NOCOMPRESS
DISPLAYOUT("\n");
DISPLAYOUT("Advanced compression options:\n");
DISPLAYOUT(" --ultra Enable levels beyond %i, up to %i; requires more memory.\n", ZSTDCLI_CLEVEL_MAX, ZSTD_maxCLevel());
DISPLAYOUT(" --fast[=#] Use to very fast compression levels. [Default: %u]\n", 1);
#ifdef ZSTD_GZCOMPRESS
if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
DISPLAYOUT(" --best Compatibility alias for `-9`.\n");
}
#endif
DISPLAYOUT(" --adapt Dynamically adapt compression level to I/O conditions.\n");
DISPLAYOUT(" --long[=#] Enable long distance matching with window log #. [Default: %u]\n", g_defaultMaxWindowLog);
DISPLAYOUT(" --patch-from=REF Use REF as the reference point for Zstandard's diff engine. \n\n");
# ifdef ZSTD_MULTITHREAD
DISPLAYOUT(" -T# Spawn # compression threads. [Default: 1; pass 0 for core count.]\n");
DISPLAYOUT(" --single-thread Share a single thread for I/O and compression (slightly different than `-T1`).\n");
DISPLAYOUT(" --auto-threads={physical|logical}\n");
DISPLAYOUT(" Use physical/logical cores when using `-T0`. [Default: Physical]\n\n");
DISPLAYOUT(" -B# Set job size to #. [Default: 0 (automatic)]\n");
DISPLAYOUT(" --rsyncable Compress using a rsync-friendly method (`-B` sets block size). \n");
DISPLAYOUT("\n");
# endif
DISPLAYOUT(" --exclude-compressed Only compress files that are not already compressed.\n\n");
DISPLAYOUT(" --stream-size=# Specify size of streaming input from STDIN.\n");
DISPLAYOUT(" --size-hint=# Optimize compression parameters for streaming input of approximately size #.\n");
DISPLAYOUT(" --target-compressed-block-size=#\n");
DISPLAYOUT(" Generate compressed blocks of approximately # size.\n\n");
DISPLAYOUT(" --no-dictID Don't write `dictID` into the header (dictionary compression only).\n");
DISPLAYOUT(" --[no-]compress-literals Force (un)compressed literals.\n");
DISPLAYOUT(" --[no-]row-match-finder Explicitly enable/disable the fast, row-based matchfinder for\n");
DISPLAYOUT(" the 'greedy', 'lazy', and 'lazy2' strategies.\n");
DISPLAYOUT("\n");
DISPLAYOUT(" --format=zstd Compress files to the `.zst` format. [Default]\n");
DISPLAYOUT(" --mmap-dict Memory-map dictionary file rather than mallocing and loading all at once");
#ifdef ZSTD_GZCOMPRESS
DISPLAYOUT(" --format=gzip Compress files to the `.gz` format.\n");
#endif
#ifdef ZSTD_LZMACOMPRESS
DISPLAYOUT(" --format=xz Compress files to the `.xz` format.\n");
DISPLAYOUT(" --format=lzma Compress files to the `.lzma` format.\n");
#endif
#ifdef ZSTD_LZ4COMPRESS
DISPLAYOUT( " --format=lz4 Compress files to the `.lz4` format.\n");
#endif
#endif /* !ZSTD_NOCOMPRESS */
#ifndef ZSTD_NODECOMPRESS
DISPLAYOUT("\n");
DISPLAYOUT("Advanced decompression options:\n");
DISPLAYOUT(" -l Print information about Zstandard-compressed files.\n");
DISPLAYOUT(" --test Test compressed file integrity.\n");
DISPLAYOUT(" -M# Set the memory usage limit to # megabytes.\n");
# if ZSTD_SPARSE_DEFAULT
DISPLAYOUT(" --[no-]sparse Enable sparse mode. [Default: Enabled for files, disabled for STDOUT.]\n");
# else
DISPLAYOUT(" --[no-]sparse Enable sparse mode. [Default: Disabled]\n");
# endif
{
char const* passThroughDefault = "Disabled";
if (exeNameMatch(programName, ZSTD_CAT) ||
exeNameMatch(programName, ZSTD_ZCAT) ||
exeNameMatch(programName, ZSTD_GZCAT)) {
passThroughDefault = "Enabled";
}
DISPLAYOUT(" --[no-]pass-through Pass through uncompressed files as-is. [Default: %s]\n", passThroughDefault);
}
#endif /* ZSTD_NODECOMPRESS */
#ifndef ZSTD_NODICT
DISPLAYOUT("\n");
DISPLAYOUT("Dictionary builder:\n");
DISPLAYOUT(" --train Create a dictionary from a training set of files.\n\n");
DISPLAYOUT(" --train-cover[=k=#,d=#,steps=#,split=#,shrink[=#]]\n");
DISPLAYOUT(" Use the cover algorithm (with optional arguments).\n");
DISPLAYOUT(" --train-fastcover[=k=#,d=#,f=#,steps=#,split=#,accel=#,shrink[=#]]\n");
DISPLAYOUT(" Use the fast cover algorithm (with optional arguments).\n\n");
DISPLAYOUT(" --train-legacy[=s=#] Use the legacy algorithm with selectivity #. [Default: %u]\n", g_defaultSelectivityLevel);
DISPLAYOUT(" -o NAME Use NAME as dictionary name. [Default: %s]\n", g_defaultDictName);
DISPLAYOUT(" --maxdict=# Limit dictionary to specified size #. [Default: %u]\n", g_defaultMaxDictSize);
DISPLAYOUT(" --dictID=# Force dictionary ID to #. [Default: Random]\n");
#endif
#ifndef ZSTD_NOBENCH
DISPLAYOUT("\n");
DISPLAYOUT("Benchmark options:\n");
DISPLAYOUT(" -b# Perform benchmarking with compression level #. [Default: %d]\n", ZSTDCLI_CLEVEL_DEFAULT);
DISPLAYOUT(" -e# Test all compression levels up to #; starting level is `-b#`. [Default: 1]\n");
DISPLAYOUT(" -i# Set the minimum evaluation to time # seconds. [Default: 3]\n");
DISPLAYOUT(" -B# Cut file into independent chunks of size #. [Default: No chunking]\n");
DISPLAYOUT(" -S Output one benchmark result per input file. [Default: Consolidated result]\n");
DISPLAYOUT(" --priority=rt Set process priority to real-time.\n");
#endif
}
static void badusage(const char* programName)
{
DISPLAYLEVEL(1, "Incorrect parameters \n");
if (g_displayLevel >= 2) usage(stderr, programName);
}
static void waitEnter(void)
{
int unused;
DISPLAY("Press enter to continue... \n");
unused = getchar();
(void)unused;
}
static const char* lastNameFromPath(const char* path)
{
const char* name = path;
if (strrchr(name, '/')) name = strrchr(name, '/') + 1;
if (strrchr(name, '\\')) name = strrchr(name, '\\') + 1; /* windows */
return name;
}
static void errorOut(const char* msg)
{
DISPLAYLEVEL(1, "%s \n", msg); exit(1);
}
/*! readU32FromCharChecked() :
* @return 0 if success, and store the result in *value.
* allows and interprets K, KB, KiB, M, MB and MiB suffix.
* Will also modify `*stringPtr`, advancing it to position where it stopped reading.
* @return 1 if an overflow error occurs */
static int readU32FromCharChecked(const char** stringPtr, unsigned* value)
{
unsigned result = 0;
while ((**stringPtr >='0') && (**stringPtr <='9')) {
unsigned const max = ((unsigned)(-1)) / 10;
unsigned last = result;
if (result > max) return 1; /* overflow error */
result *= 10;
result += (unsigned)(**stringPtr - '0');
if (result < last) return 1; /* overflow error */
(*stringPtr)++ ;
}
if ((**stringPtr=='K') || (**stringPtr=='M')) {
unsigned const maxK = ((unsigned)(-1)) >> 10;
if (result > maxK) return 1; /* overflow error */
result <<= 10;
if (**stringPtr=='M') {
if (result > maxK) return 1; /* overflow error */
result <<= 10;
}
(*stringPtr)++; /* skip `K` or `M` */
if (**stringPtr=='i') (*stringPtr)++;
if (**stringPtr=='B') (*stringPtr)++;
}
*value = result;
return 0;
}
/*! readU32FromChar() :
* @return : unsigned integer value read from input in `char` format.
* allows and interprets K, KB, KiB, M, MB and MiB suffix.
* Will also modify `*stringPtr`, advancing it to position where it stopped reading.
* Note : function will exit() program if digit sequence overflows */
static unsigned readU32FromChar(const char** stringPtr) {
static const char errorMsg[] = "error: numeric value overflows 32-bit unsigned int";
unsigned result;
if (readU32FromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
return result;
}
/*! readIntFromChar() :
* @return : signed integer value read from input in `char` format.
* allows and interprets K, KB, KiB, M, MB and MiB suffix.
* Will also modify `*stringPtr`, advancing it to position where it stopped reading.
* Note : function will exit() program if digit sequence overflows */
static int readIntFromChar(const char** stringPtr) {
static const char errorMsg[] = "error: numeric value overflows 32-bit int";
int sign = 1;
unsigned result;
if (**stringPtr=='-') {
(*stringPtr)++;
sign = -1;
}
if (readU32FromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
return (int) result * sign;
}
/*! readSizeTFromCharChecked() :
* @return 0 if success, and store the result in *value.
* allows and interprets K, KB, KiB, M, MB and MiB suffix.
* Will also modify `*stringPtr`, advancing it to position where it stopped reading.
* @return 1 if an overflow error occurs */
static int readSizeTFromCharChecked(const char** stringPtr, size_t* value)
{
size_t result = 0;
while ((**stringPtr >='0') && (**stringPtr <='9')) {
size_t const max = ((size_t)(-1)) / 10;
size_t last = result;
if (result > max) return 1; /* overflow error */
result *= 10;
result += (size_t)(**stringPtr - '0');
if (result < last) return 1; /* overflow error */
(*stringPtr)++ ;
}
if ((**stringPtr=='K') || (**stringPtr=='M')) {
size_t const maxK = ((size_t)(-1)) >> 10;
if (result > maxK) return 1; /* overflow error */
result <<= 10;
if (**stringPtr=='M') {
if (result > maxK) return 1; /* overflow error */
result <<= 10;
}
(*stringPtr)++; /* skip `K` or `M` */
if (**stringPtr=='i') (*stringPtr)++;
if (**stringPtr=='B') (*stringPtr)++;
}
*value = result;
return 0;
}
/*! readSizeTFromChar() :
* @return : size_t value read from input in `char` format.
* allows and interprets K, KB, KiB, M, MB and MiB suffix.
* Will also modify `*stringPtr`, advancing it to position where it stopped reading.
* Note : function will exit() program if digit sequence overflows */
static size_t readSizeTFromChar(const char** stringPtr) {
static const char errorMsg[] = "error: numeric value overflows size_t";
size_t result;
if (readSizeTFromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
return result;
}
/** longCommandWArg() :
* check if *stringPtr is the same as longCommand.
* If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
* @return 0 and doesn't modify *stringPtr otherwise.
*/
static int longCommandWArg(const char** stringPtr, const char* longCommand)
{
size_t const comSize = strlen(longCommand);
int const result = !strncmp(*stringPtr, longCommand, comSize);
if (result) *stringPtr += comSize;
return result;
}
#ifndef ZSTD_NODICT
static const unsigned kDefaultRegression = 1;
/**
* parseCoverParameters() :
* reads cover parameters from *stringPtr (e.g. "--train-cover=k=48,d=8,steps=32") into *params
* @return 1 means that cover parameters were correct
* @return 0 in case of malformed parameters
*/
static unsigned parseCoverParameters(const char* stringPtr, ZDICT_cover_params_t* params)
{
memset(params, 0, sizeof(*params));
for (; ;) {
if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "split=")) {
unsigned splitPercentage = readU32FromChar(&stringPtr);
params->splitPoint = (double)splitPercentage / 100.0;
if (stringPtr[0]==',') { stringPtr++; continue; } else break;
}
if (longCommandWArg(&stringPtr, "shrink")) {
params->shrinkDictMaxRegression = kDefaultRegression;
params->shrinkDict = 1;
if (stringPtr[0]=='=') {
stringPtr++;
params->shrinkDictMaxRegression = readU32FromChar(&stringPtr);
}
if (stringPtr[0]==',') {
stringPtr++;
continue;
}
else break;
}
return 0;
}
if (stringPtr[0] != 0) return 0;
DISPLAYLEVEL(4, "cover: k=%u\nd=%u\nsteps=%u\nsplit=%u\nshrink%u\n", params->k, params->d, params->steps, (unsigned)(params->splitPoint * 100), params->shrinkDictMaxRegression);
return 1;
}
/**
* parseFastCoverParameters() :
* reads fastcover parameters from *stringPtr (e.g. "--train-fastcover=k=48,d=8,f=20,steps=32,accel=2") into *params
* @return 1 means that fastcover parameters were correct
* @return 0 in case of malformed parameters
*/
static unsigned parseFastCoverParameters(const char* stringPtr, ZDICT_fastCover_params_t* params)
{
memset(params, 0, sizeof(*params));
for (; ;) {
if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "f=")) { params->f = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "accel=")) { params->accel = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "split=")) {
unsigned splitPercentage = readU32FromChar(&stringPtr);
params->splitPoint = (double)splitPercentage / 100.0;
if (stringPtr[0]==',') { stringPtr++; continue; } else break;
}
if (longCommandWArg(&stringPtr, "shrink")) {
params->shrinkDictMaxRegression = kDefaultRegression;
params->shrinkDict = 1;
if (stringPtr[0]=='=') {
stringPtr++;
params->shrinkDictMaxRegression = readU32FromChar(&stringPtr);
}
if (stringPtr[0]==',') {
stringPtr++;
continue;
}
else break;
}
return 0;
}
if (stringPtr[0] != 0) return 0;
DISPLAYLEVEL(4, "cover: k=%u\nd=%u\nf=%u\nsteps=%u\nsplit=%u\naccel=%u\nshrink=%u\n", params->k, params->d, params->f, params->steps, (unsigned)(params->splitPoint * 100), params->accel, params->shrinkDictMaxRegression);
return 1;
}
/**
* parseLegacyParameters() :
* reads legacy dictionary builder parameters from *stringPtr (e.g. "--train-legacy=selectivity=8") into *selectivity
* @return 1 means that legacy dictionary builder parameters were correct
* @return 0 in case of malformed parameters
*/
static unsigned parseLegacyParameters(const char* stringPtr, unsigned* selectivity)
{
if (!longCommandWArg(&stringPtr, "s=") && !longCommandWArg(&stringPtr, "selectivity=")) { return 0; }
*selectivity = readU32FromChar(&stringPtr);
if (stringPtr[0] != 0) return 0;
DISPLAYLEVEL(4, "legacy: selectivity=%u\n", *selectivity);
return 1;
}
static ZDICT_cover_params_t defaultCoverParams(void)
{
ZDICT_cover_params_t params;
memset(¶ms, 0, sizeof(params));
params.d = 8;
params.steps = 4;
params.splitPoint = 1.0;
params.shrinkDict = 0;
params.shrinkDictMaxRegression = kDefaultRegression;
return params;
}
static ZDICT_fastCover_params_t defaultFastCoverParams(void)
{
ZDICT_fastCover_params_t params;
memset(¶ms, 0, sizeof(params));
params.d = 8;
params.f = 20;
params.steps = 4;
params.splitPoint = 0.75; /* different from default splitPoint of cover */
params.accel = DEFAULT_ACCEL;
params.shrinkDict = 0;
params.shrinkDictMaxRegression = kDefaultRegression;
return params;
}
#endif
/** parseAdaptParameters() :
* reads adapt parameters from *stringPtr (e.g. "--zstd=min=1,max=19) and store them into adaptMinPtr and adaptMaxPtr.
* Both adaptMinPtr and adaptMaxPtr must be already allocated and correctly initialized.
* There is no guarantee that any of these values will be updated.
* @return 1 means that parsing was successful,
* @return 0 in case of malformed parameters
*/
static unsigned parseAdaptParameters(const char* stringPtr, int* adaptMinPtr, int* adaptMaxPtr)
{
for ( ; ;) {
if (longCommandWArg(&stringPtr, "min=")) { *adaptMinPtr = readIntFromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "max=")) { *adaptMaxPtr = readIntFromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
DISPLAYLEVEL(4, "invalid compression parameter \n");
return 0;
}
if (stringPtr[0] != 0) return 0; /* check the end of string */
if (*adaptMinPtr > *adaptMaxPtr) {
DISPLAYLEVEL(4, "incoherent adaptation limits \n");
return 0;
}
return 1;
}
/** parseCompressionParameters() :
* reads compression parameters from *stringPtr (e.g. "--zstd=wlog=23,clog=23,hlog=22,slog=6,mml=3,tlen=48,strat=6") into *params
* @return 1 means that compression parameters were correct
* @return 0 in case of malformed parameters
*/
static unsigned parseCompressionParameters(const char* stringPtr, ZSTD_compressionParameters* params)
{
for ( ; ;) {
if (longCommandWArg(&stringPtr, "windowLog=") || longCommandWArg(&stringPtr, "wlog=")) { params->windowLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "chainLog=") || longCommandWArg(&stringPtr, "clog=")) { params->chainLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "hashLog=") || longCommandWArg(&stringPtr, "hlog=")) { params->hashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "searchLog=") || longCommandWArg(&stringPtr, "slog=")) { params->searchLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "minMatch=") || longCommandWArg(&stringPtr, "mml=")) { params->minMatch = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "targetLength=") || longCommandWArg(&stringPtr, "tlen=")) { params->targetLength = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "strategy=") || longCommandWArg(&stringPtr, "strat=")) { params->strategy = (ZSTD_strategy)(readU32FromChar(&stringPtr)); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "overlapLog=") || longCommandWArg(&stringPtr, "ovlog=")) { g_overlapLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "ldmHashLog=") || longCommandWArg(&stringPtr, "lhlog=")) { g_ldmHashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "ldmMinMatch=") || longCommandWArg(&stringPtr, "lmml=")) { g_ldmMinMatch = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "ldmBucketSizeLog=") || longCommandWArg(&stringPtr, "lblog=")) { g_ldmBucketSizeLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
if (longCommandWArg(&stringPtr, "ldmHashRateLog=") || longCommandWArg(&stringPtr, "lhrlog=")) { g_ldmHashRateLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
DISPLAYLEVEL(4, "invalid compression parameter \n");
return 0;
}
DISPLAYLEVEL(4, "windowLog=%d, chainLog=%d, hashLog=%d, searchLog=%d \n", params->windowLog, params->chainLog, params->hashLog, params->searchLog);
DISPLAYLEVEL(4, "minMatch=%d, targetLength=%d, strategy=%d \n", params->minMatch, params->targetLength, params->strategy);
if (stringPtr[0] != 0) return 0; /* check the end of string */
return 1;
}
static void printVersion(void)
{
if (g_displayLevel < DISPLAY_LEVEL_DEFAULT) {
DISPLAYOUT("%s\n", ZSTD_VERSION_STRING);
return;
}
DISPLAYOUT(WELCOME_MESSAGE);
if (g_displayLevel >= 3) {
/* format support */
DISPLAYOUT("*** supports: zstd");
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>0) && (ZSTD_LEGACY_SUPPORT<8)
DISPLAYOUT(", zstd legacy v0.%d+", ZSTD_LEGACY_SUPPORT);
#endif
#ifdef ZSTD_GZCOMPRESS
DISPLAYOUT(", gzip");
#endif
#ifdef ZSTD_LZ4COMPRESS
DISPLAYOUT(", lz4");
#endif
#ifdef ZSTD_LZMACOMPRESS
DISPLAYOUT(", lzma, xz ");
#endif
DISPLAYOUT("\n");
if (g_displayLevel >= 4) {
/* library versions */
DISPLAYOUT("zlib version %s\n", FIO_zlibVersion());
DISPLAYOUT("lz4 version %s\n", FIO_lz4Version());
DISPLAYOUT("lzma version %s\n", FIO_lzmaVersion());
/* posix support */
#ifdef _POSIX_C_SOURCE
DISPLAYOUT("_POSIX_C_SOURCE defined: %ldL\n", (long) _POSIX_C_SOURCE);
#endif
#ifdef _POSIX_VERSION
DISPLAYOUT("_POSIX_VERSION defined: %ldL \n", (long) _POSIX_VERSION);
#endif
#ifdef PLATFORM_POSIX_VERSION
DISPLAYOUT("PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION);
#endif
} }
}
#define ZSTD_NB_STRATEGIES 9
static const char* ZSTD_strategyMap[ZSTD_NB_STRATEGIES + 1] = { "", "ZSTD_fast",
"ZSTD_dfast", "ZSTD_greedy", "ZSTD_lazy", "ZSTD_lazy2", "ZSTD_btlazy2",
"ZSTD_btopt", "ZSTD_btultra", "ZSTD_btultra2"};
#ifndef ZSTD_NOCOMPRESS
static void printDefaultCParams(const char* filename, const char* dictFileName, int cLevel) {
unsigned long long fileSize = UTIL_getFileSize(filename);
const size_t dictSize = dictFileName != NULL ? (size_t)UTIL_getFileSize(dictFileName) : 0;
const ZSTD_compressionParameters cParams = ZSTD_getCParams(cLevel, fileSize, dictSize);
if (fileSize != UTIL_FILESIZE_UNKNOWN) DISPLAY("%s (%u bytes)\n", filename, (unsigned)fileSize);
else DISPLAY("%s (src size unknown)\n", filename);
DISPLAY(" - windowLog : %u\n", cParams.windowLog);
DISPLAY(" - chainLog : %u\n", cParams.chainLog);
DISPLAY(" - hashLog : %u\n", cParams.hashLog);
DISPLAY(" - searchLog : %u\n", cParams.searchLog);
DISPLAY(" - minMatch : %u\n", cParams.minMatch);
DISPLAY(" - targetLength : %u\n", cParams.targetLength);
assert(cParams.strategy < ZSTD_NB_STRATEGIES + 1);
DISPLAY(" - strategy : %s (%u)\n", ZSTD_strategyMap[(int)cParams.strategy], (unsigned)cParams.strategy);
}
static void printActualCParams(const char* filename, const char* dictFileName, int cLevel, const ZSTD_compressionParameters* cParams) {
unsigned long long fileSize = UTIL_getFileSize(filename);
const size_t dictSize = dictFileName != NULL ? (size_t)UTIL_getFileSize(dictFileName) : 0;
ZSTD_compressionParameters actualCParams = ZSTD_getCParams(cLevel, fileSize, dictSize);
assert(g_displayLevel >= 4);
actualCParams.windowLog = cParams->windowLog == 0 ? actualCParams.windowLog : cParams->windowLog;
actualCParams.chainLog = cParams->chainLog == 0 ? actualCParams.chainLog : cParams->chainLog;
actualCParams.hashLog = cParams->hashLog == 0 ? actualCParams.hashLog : cParams->hashLog;
actualCParams.searchLog = cParams->searchLog == 0 ? actualCParams.searchLog : cParams->searchLog;
actualCParams.minMatch = cParams->minMatch == 0 ? actualCParams.minMatch : cParams->minMatch;
actualCParams.targetLength = cParams->targetLength == 0 ? actualCParams.targetLength : cParams->targetLength;
actualCParams.strategy = cParams->strategy == 0 ? actualCParams.strategy : cParams->strategy;
DISPLAY("--zstd=wlog=%d,clog=%d,hlog=%d,slog=%d,mml=%d,tlen=%d,strat=%d\n",
actualCParams.windowLog, actualCParams.chainLog, actualCParams.hashLog, actualCParams.searchLog,
actualCParams.minMatch, actualCParams.targetLength, actualCParams.strategy);
}
#endif
/* Environment variables for parameter setting */
#define ENV_CLEVEL "ZSTD_CLEVEL"
#define ENV_NBTHREADS "ZSTD_NBTHREADS" /* takes lower precedence than directly specifying -T# in the CLI */
/* pick up environment variable */
static int init_cLevel(void) {
const char* const env = getenv(ENV_CLEVEL);
if (env != NULL) {
const char* ptr = env;
int sign = 1;
if (*ptr == '-') {
sign = -1;
ptr++;
} else if (*ptr == '+') {
ptr++;
}
if ((*ptr>='0') && (*ptr<='9')) {
unsigned absLevel;
if (readU32FromCharChecked(&ptr, &absLevel)) {
DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_CLEVEL, env);
return ZSTDCLI_CLEVEL_DEFAULT;
} else if (*ptr == 0) {
return sign * (int)absLevel;
} }
DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid integer value \n", ENV_CLEVEL, env);
}
return ZSTDCLI_CLEVEL_DEFAULT;
}
#ifdef ZSTD_MULTITHREAD
static unsigned init_nbThreads(void) {
const char* const env = getenv(ENV_NBTHREADS);
if (env != NULL) {
const char* ptr = env;
if ((*ptr>='0') && (*ptr<='9')) {
unsigned nbThreads;
if (readU32FromCharChecked(&ptr, &nbThreads)) {
DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_NBTHREADS, env);
return ZSTDCLI_NBTHREADS_DEFAULT;
} else if (*ptr == 0) {
return nbThreads;
}
}
DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBTHREADS, env);
}
return ZSTDCLI_NBTHREADS_DEFAULT;
}
#endif
#define NEXT_FIELD(ptr) { \
if (*argument == '=') { \
ptr = ++argument; \
argument += strlen(ptr); \
} else { \
argNb++; \
if (argNb >= argCount) { \
DISPLAYLEVEL(1, "error: missing command argument \n"); \
CLEAN_RETURN(1); \
} \
ptr = argv[argNb]; \
assert(ptr != NULL); \
if (ptr[0]=='-') { \
DISPLAYLEVEL(1, "error: command cannot be separated from its argument by another command \n"); \
CLEAN_RETURN(1); \
} } }
#define NEXT_UINT32(val32) { \
const char* __nb; \
NEXT_FIELD(__nb); \
val32 = readU32FromChar(&__nb); \
if(*__nb != 0) { \
errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \
} \
}
#define NEXT_TSIZE(valTsize) { \
const char* __nb; \
NEXT_FIELD(__nb); \
valTsize = readSizeTFromChar(&__nb); \
if(*__nb != 0) { \
errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \
} \
}
typedef enum { zom_compress, zom_decompress, zom_test, zom_bench, zom_train, zom_list } zstd_operation_mode;
#define CLEAN_RETURN(i) { operationResult = (i); goto _end; }
#ifdef ZSTD_NOCOMPRESS
/* symbols from compression library are not defined and should not be invoked */
# define MINCLEVEL -99
# define MAXCLEVEL 22
#else
# define MINCLEVEL ZSTD_minCLevel()
# define MAXCLEVEL ZSTD_maxCLevel()
#endif
int main(int argCount, const char* argv[])
{
int argNb,
followLinks = 0,
allowBlockDevices = 0,
forceStdin = 0,
forceStdout = 0,
hasStdout = 0,
ldmFlag = 0,
main_pause = 0,
adapt = 0,
adaptMin = MINCLEVEL,
adaptMax = MAXCLEVEL,
rsyncable = 0,
nextArgumentsAreFiles = 0,
operationResult = 0,
separateFiles = 0,
setRealTimePrio = 0,
singleThread = 0,
defaultLogicalCores = 0,
showDefaultCParams = 0,
ultra=0,
contentSize=1,
removeSrcFile=0;
ZSTD_paramSwitch_e mmapDict=ZSTD_ps_auto;
ZSTD_paramSwitch_e useRowMatchFinder = ZSTD_ps_auto;
FIO_compressionType_t cType = FIO_zstdCompression;
unsigned nbWorkers = 0;
double compressibility = 0.5;
unsigned bench_nbSeconds = 3; /* would be better if this value was synchronized from bench */
size_t blockSize = 0;
FIO_prefs_t* const prefs = FIO_createPreferences();
FIO_ctx_t* const fCtx = FIO_createContext();
FIO_progressSetting_e progress = FIO_ps_auto;
zstd_operation_mode operation = zom_compress;
ZSTD_compressionParameters compressionParams;
int cLevel = init_cLevel();
int cLevelLast = MINCLEVEL - 1; /* lower than minimum */
unsigned recursive = 0;
unsigned memLimit = 0;
FileNamesTable* filenames = UTIL_allocateFileNamesTable((size_t)argCount); /* argCount >= 1 */
FileNamesTable* file_of_names = UTIL_allocateFileNamesTable((size_t)argCount); /* argCount >= 1 */
const char* programName = argv[0];
const char* outFileName = NULL;
const char* outDirName = NULL;
const char* outMirroredDirName = NULL;
const char* dictFileName = NULL;
const char* patchFromDictFileName = NULL;
const char* suffix = ZSTD_EXTENSION;
unsigned maxDictSize = g_defaultMaxDictSize;
unsigned dictID = 0;
size_t streamSrcSize = 0;
size_t targetCBlockSize = 0;
size_t srcSizeHint = 0;
size_t nbInputFileNames = 0;
int dictCLevel = g_defaultDictCLevel;
unsigned dictSelect = g_defaultSelectivityLevel;
#ifndef ZSTD_NODICT
ZDICT_cover_params_t coverParams = defaultCoverParams();
ZDICT_fastCover_params_t fastCoverParams = defaultFastCoverParams();
dictType dict = fastCover;
#endif
#ifndef ZSTD_NOBENCH
BMK_advancedParams_t benchParams = BMK_initAdvancedParams();
#endif
ZSTD_paramSwitch_e literalCompressionMode = ZSTD_ps_auto;
/* init */
checkLibVersion();
(void)recursive; (void)cLevelLast; /* not used when ZSTD_NOBENCH set */
(void)memLimit;
assert(argCount >= 1);
if ((filenames==NULL) || (file_of_names==NULL)) { DISPLAYLEVEL(1, "zstd: allocation error \n"); exit(1); }
programName = lastNameFromPath(programName);
#ifdef ZSTD_MULTITHREAD
nbWorkers = init_nbThreads();
#endif
/* preset behaviors */
if (exeNameMatch(programName, ZSTD_ZSTDMT)) nbWorkers=0, singleThread=0;
if (exeNameMatch(programName, ZSTD_UNZSTD)) operation=zom_decompress;
if (exeNameMatch(programName, ZSTD_CAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* supports multiple formats */
if (exeNameMatch(programName, ZSTD_ZCAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* behave like zcat, also supports multiple formats */
if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
suffix = GZ_EXTENSION; cType = FIO_gzipCompression; removeSrcFile=1;
dictCLevel = cLevel = 6; /* gzip default is -6 */
}
if (exeNameMatch(programName, ZSTD_GUNZIP)) { operation=zom_decompress; removeSrcFile=1; } /* behave like gunzip, also supports multiple formats */
if (exeNameMatch(programName, ZSTD_GZCAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* behave like gzcat, also supports multiple formats */
if (exeNameMatch(programName, ZSTD_LZMA)) { suffix = LZMA_EXTENSION; cType = FIO_lzmaCompression; removeSrcFile=1; } /* behave like lzma */
if (exeNameMatch(programName, ZSTD_UNLZMA)) { operation=zom_decompress; cType = FIO_lzmaCompression; removeSrcFile=1; } /* behave like unlzma, also supports multiple formats */
if (exeNameMatch(programName, ZSTD_XZ)) { suffix = XZ_EXTENSION; cType = FIO_xzCompression; removeSrcFile=1; } /* behave like xz */
if (exeNameMatch(programName, ZSTD_UNXZ)) { operation=zom_decompress; cType = FIO_xzCompression; removeSrcFile=1; } /* behave like unxz, also supports multiple formats */
if (exeNameMatch(programName, ZSTD_LZ4)) { suffix = LZ4_EXTENSION; cType = FIO_lz4Compression; } /* behave like lz4 */
if (exeNameMatch(programName, ZSTD_UNLZ4)) { operation=zom_decompress; cType = FIO_lz4Compression; } /* behave like unlz4, also supports multiple formats */
memset(&compressionParams, 0, sizeof(compressionParams));
/* init crash handler */
FIO_addAbortHandler();
/* command switches */
for (argNb=1; argNb<argCount; argNb++) {
const char* argument = argv[argNb];
if (!argument) continue; /* Protection if argument empty */
if (nextArgumentsAreFiles) {
UTIL_refFilename(filenames, argument);
continue;
}
/* "-" means stdin/stdout */
if (!strcmp(argument, "-")){
UTIL_refFilename(filenames, stdinmark);
continue;
}
/* Decode commands (note : aggregated commands are allowed) */
if (argument[0]=='-') {
if (argument[1]=='-') {
/* long commands (--long-word) */
if (!strcmp(argument, "--")) { nextArgumentsAreFiles=1; continue; } /* only file names allowed from now on */
if (!strcmp(argument, "--list")) { operation=zom_list; continue; }
if (!strcmp(argument, "--compress")) { operation=zom_compress; continue; }
if (!strcmp(argument, "--decompress")) { operation=zom_decompress; continue; }
if (!strcmp(argument, "--uncompress")) { operation=zom_decompress; continue; }
if (!strcmp(argument, "--force")) { FIO_overwriteMode(prefs); forceStdin=1; forceStdout=1; followLinks=1; allowBlockDevices=1; continue; }
if (!strcmp(argument, "--version")) { printVersion(); CLEAN_RETURN(0); }
if (!strcmp(argument, "--help")) { usage_advanced(programName); CLEAN_RETURN(0); }
if (!strcmp(argument, "--verbose")) { g_displayLevel++; continue; }
if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; }
if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; removeSrcFile=0; continue; }
if (!strcmp(argument, "--ultra")) { ultra=1; continue; }
if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(prefs, 2); continue; }
if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(prefs, 0); continue; }
if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(prefs, 2); continue; }
if (!strcmp(argument, "--no-sparse")) { FIO_setSparseWrite(prefs, 0); continue; }
if (!strcmp(argument, "--pass-through")) { FIO_setPassThroughFlag(prefs, 1); continue; }
if (!strcmp(argument, "--no-pass-through")) { FIO_setPassThroughFlag(prefs, 0); continue; }
if (!strcmp(argument, "--test")) { operation=zom_test; continue; }
if (!strcmp(argument, "--asyncio")) { FIO_setAsyncIOFlag(prefs, 1); continue;}
if (!strcmp(argument, "--no-asyncio")) { FIO_setAsyncIOFlag(prefs, 0); continue;}
if (!strcmp(argument, "--train")) { operation=zom_train; if (outFileName==NULL) outFileName=g_defaultDictName; continue; }
if (!strcmp(argument, "--no-dictID")) { FIO_setDictIDFlag(prefs, 0); continue; }
if (!strcmp(argument, "--keep")) { removeSrcFile=0; continue; }
if (!strcmp(argument, "--rm")) { removeSrcFile=1; continue; }
if (!strcmp(argument, "--priority=rt")) { setRealTimePrio = 1; continue; }
if (!strcmp(argument, "--show-default-cparams")) { showDefaultCParams = 1; continue; }
if (!strcmp(argument, "--content-size")) { contentSize = 1; continue; }
if (!strcmp(argument, "--no-content-size")) { contentSize = 0; continue; }
if (!strcmp(argument, "--adapt")) { adapt = 1; continue; }
if (!strcmp(argument, "--no-row-match-finder")) { useRowMatchFinder = ZSTD_ps_disable; continue; }
if (!strcmp(argument, "--row-match-finder")) { useRowMatchFinder = ZSTD_ps_enable; continue; }
if (longCommandWArg(&argument, "--adapt=")) { adapt = 1; if (!parseAdaptParameters(argument, &adaptMin, &adaptMax)) { badusage(programName); CLEAN_RETURN(1); } continue; }
if (!strcmp(argument, "--single-thread")) { nbWorkers = 0; singleThread = 1; continue; }
if (!strcmp(argument, "--format=zstd")) { suffix = ZSTD_EXTENSION; cType = FIO_zstdCompression; continue; }
if (!strcmp(argument, "--mmap-dict")) { mmapDict = ZSTD_ps_enable; continue; }
if (!strcmp(argument, "--no-mmap-dict")) { mmapDict = ZSTD_ps_disable; continue; }
#ifdef ZSTD_GZCOMPRESS
if (!strcmp(argument, "--format=gzip")) { suffix = GZ_EXTENSION; cType = FIO_gzipCompression; continue; }
if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
if (!strcmp(argument, "--best")) { dictCLevel = cLevel = 9; continue; }
if (!strcmp(argument, "--no-name")) { /* ignore for now */; continue; }
}
#endif
#ifdef ZSTD_LZMACOMPRESS
if (!strcmp(argument, "--format=lzma")) { suffix = LZMA_EXTENSION; cType = FIO_lzmaCompression; continue; }
if (!strcmp(argument, "--format=xz")) { suffix = XZ_EXTENSION; cType = FIO_xzCompression; continue; }
#endif
#ifdef ZSTD_LZ4COMPRESS
if (!strcmp(argument, "--format=lz4")) { suffix = LZ4_EXTENSION; cType = FIO_lz4Compression; continue; }
#endif
if (!strcmp(argument, "--rsyncable")) { rsyncable = 1; continue; }
if (!strcmp(argument, "--compress-literals")) { literalCompressionMode = ZSTD_ps_enable; continue; }
if (!strcmp(argument, "--no-compress-literals")) { literalCompressionMode = ZSTD_ps_disable; continue; }
if (!strcmp(argument, "--no-progress")) { progress = FIO_ps_never; continue; }
if (!strcmp(argument, "--progress")) { progress = FIO_ps_always; continue; }
if (!strcmp(argument, "--exclude-compressed")) { FIO_setExcludeCompressedFile(prefs, 1); continue; }
if (!strcmp(argument, "--fake-stdin-is-console")) { UTIL_fakeStdinIsConsole(); continue; }
if (!strcmp(argument, "--fake-stdout-is-console")) { UTIL_fakeStdoutIsConsole(); continue; }
if (!strcmp(argument, "--fake-stderr-is-console")) { UTIL_fakeStderrIsConsole(); continue; }
if (!strcmp(argument, "--trace-file-stat")) { UTIL_traceFileStat(); continue; }
/* long commands with arguments */
#ifndef ZSTD_NODICT
if (longCommandWArg(&argument, "--train-cover")) {
operation = zom_train;
if (outFileName == NULL)
outFileName = g_defaultDictName;
dict = cover;
/* Allow optional arguments following an = */
if (*argument == 0) { memset(&coverParams, 0, sizeof(coverParams)); }
else if (*argument++ != '=') { badusage(programName); CLEAN_RETURN(1); }
else if (!parseCoverParameters(argument, &coverParams)) { badusage(programName); CLEAN_RETURN(1); }
continue;
}
if (longCommandWArg(&argument, "--train-fastcover")) {
operation = zom_train;
if (outFileName == NULL)
outFileName = g_defaultDictName;
dict = fastCover;
/* Allow optional arguments following an = */
if (*argument == 0) { memset(&fastCoverParams, 0, sizeof(fastCoverParams)); }
else if (*argument++ != '=') { badusage(programName); CLEAN_RETURN(1); }
else if (!parseFastCoverParameters(argument, &fastCoverParams)) { badusage(programName); CLEAN_RETURN(1); }
continue;
}
if (longCommandWArg(&argument, "--train-legacy")) {
operation = zom_train;
if (outFileName == NULL)
outFileName = g_defaultDictName;
dict = legacy;
/* Allow optional arguments following an = */
if (*argument == 0) { continue; }
else if (*argument++ != '=') { badusage(programName); CLEAN_RETURN(1); }
else if (!parseLegacyParameters(argument, &dictSelect)) { badusage(programName); CLEAN_RETURN(1); }
continue;
}
#endif
if (longCommandWArg(&argument, "--threads")) { NEXT_UINT32(nbWorkers); continue; }
if (longCommandWArg(&argument, "--memlimit")) { NEXT_UINT32(memLimit); continue; }
if (longCommandWArg(&argument, "--memory")) { NEXT_UINT32(memLimit); continue; }
if (longCommandWArg(&argument, "--memlimit-decompress")) { NEXT_UINT32(memLimit); continue; }
if (longCommandWArg(&argument, "--block-size")) { NEXT_TSIZE(blockSize); continue; }
if (longCommandWArg(&argument, "--maxdict")) { NEXT_UINT32(maxDictSize); continue; }
if (longCommandWArg(&argument, "--dictID")) { NEXT_UINT32(dictID); continue; }
if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) { badusage(programName); CLEAN_RETURN(1); } ; cType = FIO_zstdCompression; continue; }
if (longCommandWArg(&argument, "--stream-size")) { NEXT_TSIZE(streamSrcSize); continue; }
if (longCommandWArg(&argument, "--target-compressed-block-size")) { NEXT_TSIZE(targetCBlockSize); continue; }
if (longCommandWArg(&argument, "--size-hint")) { NEXT_TSIZE(srcSizeHint); continue; }
if (longCommandWArg(&argument, "--output-dir-flat")) {
NEXT_FIELD(outDirName);
if (strlen(outDirName) == 0) {
DISPLAYLEVEL(1, "error: output dir cannot be empty string (did you mean to pass '.' instead?)\n");
CLEAN_RETURN(1);
}
continue;
}
if (longCommandWArg(&argument, "--auto-threads")) {
const char* threadDefault = NULL;
NEXT_FIELD(threadDefault);
if (strcmp(threadDefault, "logical") == 0)
defaultLogicalCores = 1;
continue;
}
#ifdef UTIL_HAS_MIRRORFILELIST
if (longCommandWArg(&argument, "--output-dir-mirror")) {
NEXT_FIELD(outMirroredDirName);
if (strlen(outMirroredDirName) == 0) {
DISPLAYLEVEL(1, "error: output dir cannot be empty string (did you mean to pass '.' instead?)\n");
CLEAN_RETURN(1);
}
continue;
}
#endif
#ifndef ZSTD_NOTRACE
if (longCommandWArg(&argument, "--trace")) { char const* traceFile; NEXT_FIELD(traceFile); TRACE_enable(traceFile); continue; }
#endif
if (longCommandWArg(&argument, "--patch-from")) { NEXT_FIELD(patchFromDictFileName); continue; }
if (longCommandWArg(&argument, "--long")) {
unsigned ldmWindowLog = 0;
ldmFlag = 1;
/* Parse optional window log */
if (*argument == '=') {
++argument;
ldmWindowLog = readU32FromChar(&argument);
} else if (*argument != 0) {
/* Invalid character following --long */
badusage(programName);
CLEAN_RETURN(1);
} else {
ldmWindowLog = g_defaultMaxWindowLog;
}
/* Only set windowLog if not already set by --zstd */
if (compressionParams.windowLog == 0)
compressionParams.windowLog = ldmWindowLog;
continue;
}
#ifndef ZSTD_NOCOMPRESS /* linking ZSTD_minCLevel() requires compression support */
if (longCommandWArg(&argument, "--fast")) {
/* Parse optional acceleration factor */
if (*argument == '=') {
U32 const maxFast = (U32)-ZSTD_minCLevel();
U32 fastLevel;
++argument;
fastLevel = readU32FromChar(&argument);
if (fastLevel > maxFast) fastLevel = maxFast;
if (fastLevel) {
dictCLevel = cLevel = -(int)fastLevel;
} else {
badusage(programName);
CLEAN_RETURN(1);
}
} else if (*argument != 0) {
/* Invalid character following --fast */
badusage(programName);
CLEAN_RETURN(1);
} else {
cLevel = -1; /* default for --fast */
}
continue;
}
#endif
if (longCommandWArg(&argument, "--filelist")) {
const char* listName;
NEXT_FIELD(listName);
UTIL_refFilename(file_of_names, listName);
continue;
}
/* fall-through, will trigger bad_usage() later on */
}
argument++;
while (argument[0]!=0) {
#ifndef ZSTD_NOCOMPRESS
/* compression Level */
if ((*argument>='0') && (*argument<='9')) {
dictCLevel = cLevel = (int)readU32FromChar(&argument);
continue;
}
#endif
switch(argument[0])
{
/* Display help */
case 'V': printVersion(); CLEAN_RETURN(0); /* Version Only */
case 'H': usage_advanced(programName); CLEAN_RETURN(0);
case 'h': usage(stdout, programName); CLEAN_RETURN(0);
/* Compress */
case 'z': operation=zom_compress; argument++; break;
/* Decoding */
case 'd':
#ifndef ZSTD_NOBENCH
benchParams.mode = BMK_decodeOnly;
if (operation==zom_bench) { argument++; break; } /* benchmark decode (hidden option) */
#endif
operation=zom_decompress; argument++; break;
/* Force stdout, even if stdout==console */
case 'c': forceStdout=1; outFileName=stdoutmark; removeSrcFile=0; argument++; break;
/* do not store filename - gzip compatibility - nothing to do */
case 'n': argument++; break;
/* Use file content as dictionary */
case 'D': argument++; NEXT_FIELD(dictFileName); break;
/* Overwrite */
case 'f': FIO_overwriteMode(prefs); forceStdin=1; forceStdout=1; followLinks=1; allowBlockDevices=1; argument++; break;
/* Verbose mode */
case 'v': g_displayLevel++; argument++; break;
/* Quiet mode */
case 'q': g_displayLevel--; argument++; break;
/* keep source file (default) */
case 'k': removeSrcFile=0; argument++; break;
/* Checksum */
case 'C': FIO_setChecksumFlag(prefs, 2); argument++; break;
/* test compressed file */
case 't': operation=zom_test; argument++; break;
/* destination file name */
case 'o': argument++; NEXT_FIELD(outFileName); break;
/* limit memory */
case 'M':
argument++;
memLimit = readU32FromChar(&argument);
break;
case 'l': operation=zom_list; argument++; break;
#ifdef UTIL_HAS_CREATEFILELIST
/* recursive */
case 'r': recursive=1; argument++; break;
#endif
#ifndef ZSTD_NOBENCH
/* Benchmark */
case 'b':
operation=zom_bench;
argument++;
break;
/* range bench (benchmark only) */
case 'e':
/* compression Level */
argument++;
cLevelLast = (int)readU32FromChar(&argument);
break;
/* Modify Nb Iterations (benchmark only) */
case 'i':
argument++;
bench_nbSeconds = readU32FromChar(&argument);
break;
/* cut input into blocks (benchmark only) */
case 'B':
argument++;
blockSize = readU32FromChar(&argument);
break;
/* benchmark files separately (hidden option) */
case 'S':
argument++;
separateFiles = 1;
break;
#endif /* ZSTD_NOBENCH */
/* nb of threads (hidden option) */
case 'T':
argument++;
nbWorkers = readU32FromChar(&argument);
break;
/* Dictionary Selection level */
case 's':
argument++;
dictSelect = readU32FromChar(&argument);
break;
/* Pause at the end (-p) or set an additional param (-p#) (hidden option) */
case 'p': argument++;
#ifndef ZSTD_NOBENCH
if ((*argument>='0') && (*argument<='9')) {
benchParams.additionalParam = (int)readU32FromChar(&argument);
} else
#endif
main_pause=1;
break;
/* Select compressibility of synthetic sample */
case 'P':
argument++;
compressibility = (double)readU32FromChar(&argument) / 100;
break;
/* unknown command */
default : badusage(programName); CLEAN_RETURN(1);
}
}
continue;
} /* if (argument[0]=='-') */
/* none of the above : add filename to list */
UTIL_refFilename(filenames, argument);
}
/* Welcome message (if verbose) */
DISPLAYLEVEL(3, WELCOME_MESSAGE);
#ifdef ZSTD_MULTITHREAD
if ((operation==zom_decompress) && (!singleThread) && (nbWorkers > 1)) {
DISPLAYLEVEL(2, "Warning : decompression does not support multi-threading\n");
}
if ((nbWorkers==0) && (!singleThread)) {
/* automatically set # workers based on # of reported cpus */
if (defaultLogicalCores) {
nbWorkers = (unsigned)UTIL_countLogicalCores();
DISPLAYLEVEL(3, "Note: %d logical core(s) detected \n", nbWorkers);
} else {
nbWorkers = (unsigned)UTIL_countPhysicalCores();
DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbWorkers);
}
}
#else
(void)singleThread; (void)nbWorkers; (void)defaultLogicalCores;
#endif
g_utilDisplayLevel = g_displayLevel;
#ifdef UTIL_HAS_CREATEFILELIST
if (!followLinks) {
unsigned u, fileNamesNb;
unsigned const nbFilenames = (unsigned)filenames->tableSize;
for (u=0, fileNamesNb=0; u<nbFilenames; u++) {
if ( UTIL_isLink(filenames->fileNames[u])
&& !UTIL_isFIFO(filenames->fileNames[u])
) {
DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring \n", filenames->fileNames[u]);
} else {
filenames->fileNames[fileNamesNb++] = filenames->fileNames[u];
} }
if (fileNamesNb == 0 && nbFilenames > 0) /* all names are eliminated */
CLEAN_RETURN(1);
filenames->tableSize = fileNamesNb;
} /* if (!followLinks) */
/* read names from a file */
if (file_of_names->tableSize) {
size_t const nbFileLists = file_of_names->tableSize;
size_t flNb;
for (flNb=0; flNb < nbFileLists; flNb++) {
FileNamesTable* const fnt = UTIL_createFileNamesTable_fromFileName(file_of_names->fileNames[flNb]);
if (fnt==NULL) {
DISPLAYLEVEL(1, "zstd: error reading %s \n", file_of_names->fileNames[flNb]);
CLEAN_RETURN(1);
}
filenames = UTIL_mergeFileNamesTable(filenames, fnt);
}
}
nbInputFileNames = filenames->tableSize; /* saving number of input files */
if (recursive) { /* at this stage, filenameTable is a list of paths, which can contain both files and directories */
UTIL_expandFNT(&filenames, followLinks);
}
#else
(void)followLinks;
#endif
if (operation == zom_list) {
#ifndef ZSTD_NODECOMPRESS
int const ret = FIO_listMultipleFiles((unsigned)filenames->tableSize, filenames->fileNames, g_displayLevel);
CLEAN_RETURN(ret);
#else
DISPLAYLEVEL(1, "file information is not supported \n");
CLEAN_RETURN(1);
#endif
}
/* Check if benchmark is selected */
if (operation==zom_bench) {
#ifndef ZSTD_NOBENCH
if (cType != FIO_zstdCompression) {
DISPLAYLEVEL(1, "benchmark mode is only compatible with zstd format \n");
CLEAN_RETURN(1);
}
benchParams.blockSize = blockSize;
benchParams.nbWorkers = (int)nbWorkers;
benchParams.realTime = (unsigned)setRealTimePrio;
benchParams.nbSeconds = bench_nbSeconds;
benchParams.ldmFlag = ldmFlag;
benchParams.ldmMinMatch = (int)g_ldmMinMatch;
benchParams.ldmHashLog = (int)g_ldmHashLog;
benchParams.useRowMatchFinder = (int)useRowMatchFinder;
if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) {
benchParams.ldmBucketSizeLog = (int)g_ldmBucketSizeLog;
}
if (g_ldmHashRateLog != LDM_PARAM_DEFAULT) {
benchParams.ldmHashRateLog = (int)g_ldmHashRateLog;
}
benchParams.literalCompressionMode = literalCompressionMode;
if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel();
if (cLevelLast > ZSTD_maxCLevel()) cLevelLast = ZSTD_maxCLevel();
if (cLevelLast < cLevel) cLevelLast = cLevel;
if (cLevelLast > cLevel)
DISPLAYLEVEL(3, "Benchmarking levels from %d to %d\n", cLevel, cLevelLast);
if (filenames->tableSize > 0) {
if(separateFiles) {
unsigned i;
for(i = 0; i < filenames->tableSize; i++) {
int c;
DISPLAYLEVEL(3, "Benchmarking %s \n", filenames->fileNames[i]);
for(c = cLevel; c <= cLevelLast; c++) {
operationResult = BMK_benchFilesAdvanced(&filenames->fileNames[i], 1, dictFileName, c, &compressionParams, g_displayLevel, &benchParams);
} }
} else {
for(; cLevel <= cLevelLast; cLevel++) {
operationResult = BMK_benchFilesAdvanced(filenames->fileNames, (unsigned)filenames->tableSize, dictFileName, cLevel, &compressionParams, g_displayLevel, &benchParams);
} }
} else {
for(; cLevel <= cLevelLast; cLevel++) {
operationResult = BMK_syntheticTest(cLevel, compressibility, &compressionParams, g_displayLevel, &benchParams);
} }
#else
(void)bench_nbSeconds; (void)blockSize; (void)setRealTimePrio; (void)separateFiles; (void)compressibility;
#endif
goto _end;
}
/* Check if dictionary builder is selected */
if (operation==zom_train) {
#ifndef ZSTD_NODICT
ZDICT_params_t zParams;
zParams.compressionLevel = dictCLevel;
zParams.notificationLevel = (unsigned)g_displayLevel;
zParams.dictID = dictID;
if (dict == cover) {
int const optimize = !coverParams.k || !coverParams.d;
coverParams.nbThreads = (unsigned)nbWorkers;
coverParams.zParams = zParams;
operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, NULL, &coverParams, NULL, optimize, memLimit);
} else if (dict == fastCover) {
int const optimize = !fastCoverParams.k || !fastCoverParams.d;
fastCoverParams.nbThreads = (unsigned)nbWorkers;
fastCoverParams.zParams = zParams;
operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, NULL, NULL, &fastCoverParams, optimize, memLimit);
} else {
ZDICT_legacy_params_t dictParams;
memset(&dictParams, 0, sizeof(dictParams));
dictParams.selectivityLevel = dictSelect;
dictParams.zParams = zParams;
operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, &dictParams, NULL, NULL, 0, memLimit);
}
#else
(void)dictCLevel; (void)dictSelect; (void)dictID; (void)maxDictSize; /* not used when ZSTD_NODICT set */
DISPLAYLEVEL(1, "training mode not available \n");
operationResult = 1;
#endif
goto _end;
}
#ifndef ZSTD_NODECOMPRESS
if (operation==zom_test) { FIO_setTestMode(prefs, 1); outFileName=nulmark; removeSrcFile=0; } /* test mode */
#endif
/* No input filename ==> use stdin and stdout */
if (filenames->tableSize == 0) {
/* It is possible that the input
was a number of empty directories. In this case
stdin and stdout should not be used */
if (nbInputFileNames > 0 ){
DISPLAYLEVEL(1, "please provide correct input file(s) or non-empty directories -- ignored \n");
CLEAN_RETURN(0);
}
UTIL_refFilename(filenames, stdinmark);
}
if (filenames->tableSize == 1 && !strcmp(filenames->fileNames[0], stdinmark) && !outFileName)
outFileName = stdoutmark; /* when input is stdin, default output is stdout */
/* Check if input/output defined as console; trigger an error in this case */
if (!forceStdin
&& (UTIL_searchFileNamesTable(filenames, stdinmark) != -1)
&& UTIL_isConsole(stdin) ) {
DISPLAYLEVEL(1, "stdin is a console, aborting\n");
CLEAN_RETURN(1);
}
if ( (!outFileName || !strcmp(outFileName, stdoutmark))
&& UTIL_isConsole(stdout)
&& (UTIL_searchFileNamesTable(filenames, stdinmark) != -1)
&& !forceStdout
&& operation!=zom_decompress ) {
DISPLAYLEVEL(1, "stdout is a console, aborting\n");
CLEAN_RETURN(1);
}
#ifndef ZSTD_NOCOMPRESS
/* check compression level limits */
{ int const maxCLevel = ultra ? ZSTD_maxCLevel() : ZSTDCLI_CLEVEL_MAX;
if (cLevel > maxCLevel) {
DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i \n", maxCLevel);
cLevel = maxCLevel;
} }
#endif
if (showDefaultCParams) {
if (operation == zom_decompress) {
DISPLAYLEVEL(1, "error : can't use --show-default-cparams in decompression mode \n");
CLEAN_RETURN(1);
}
}
if (dictFileName != NULL && patchFromDictFileName != NULL) {
DISPLAYLEVEL(1, "error : can't use -D and --patch-from=# at the same time \n");
CLEAN_RETURN(1);
}
if (patchFromDictFileName != NULL && filenames->tableSize > 1) {
DISPLAYLEVEL(1, "error : can't use --patch-from=# on multiple files \n");
CLEAN_RETURN(1);
}
/* No status message by default when output is stdout */
hasStdout = outFileName && !strcmp(outFileName,stdoutmark);
if (hasStdout && (g_displayLevel==2)) g_displayLevel=1;
/* when stderr is not the console, do not pollute it with progress updates (unless requested) */
if (!UTIL_isConsole(stderr) && (progress!=FIO_ps_always)) progress=FIO_ps_never;
FIO_setProgressSetting(progress);
/* don't remove source files when output is stdout */;
if (hasStdout && removeSrcFile) {
DISPLAYLEVEL(3, "Note: src files are not removed when output is stdout \n");
removeSrcFile = 0;
}
FIO_setRemoveSrcFile(prefs, removeSrcFile);
/* IO Stream/File */
FIO_setHasStdoutOutput(fCtx, hasStdout);
FIO_setNbFilesTotal(fCtx, (int)filenames->tableSize);
FIO_determineHasStdinInput(fCtx, filenames);
FIO_setNotificationLevel(g_displayLevel);
FIO_setAllowBlockDevices(prefs, allowBlockDevices);
FIO_setPatchFromMode(prefs, patchFromDictFileName != NULL);
FIO_setMMapDict(prefs, mmapDict);
if (memLimit == 0) {
if (compressionParams.windowLog == 0) {
memLimit = (U32)1 << g_defaultMaxWindowLog;
} else {
memLimit = (U32)1 << (compressionParams.windowLog & 31);
} }
if (patchFromDictFileName != NULL)
dictFileName = patchFromDictFileName;
FIO_setMemLimit(prefs, memLimit);
if (operation==zom_compress) {
#ifndef ZSTD_NOCOMPRESS
FIO_setCompressionType(prefs, cType);
FIO_setContentSize(prefs, contentSize);
FIO_setNbWorkers(prefs, (int)nbWorkers);
FIO_setBlockSize(prefs, (int)blockSize);
if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(prefs, (int)g_overlapLog);
FIO_setLdmFlag(prefs, (unsigned)ldmFlag);
FIO_setLdmHashLog(prefs, (int)g_ldmHashLog);
FIO_setLdmMinMatch(prefs, (int)g_ldmMinMatch);
if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) FIO_setLdmBucketSizeLog(prefs, (int)g_ldmBucketSizeLog);
if (g_ldmHashRateLog != LDM_PARAM_DEFAULT) FIO_setLdmHashRateLog(prefs, (int)g_ldmHashRateLog);
FIO_setAdaptiveMode(prefs, adapt);
FIO_setUseRowMatchFinder(prefs, (int)useRowMatchFinder);
FIO_setAdaptMin(prefs, adaptMin);
FIO_setAdaptMax(prefs, adaptMax);
FIO_setRsyncable(prefs, rsyncable);
FIO_setStreamSrcSize(prefs, streamSrcSize);
FIO_setTargetCBlockSize(prefs, targetCBlockSize);
FIO_setSrcSizeHint(prefs, srcSizeHint);
FIO_setLiteralCompressionMode(prefs, literalCompressionMode);
FIO_setSparseWrite(prefs, 0);
if (adaptMin > cLevel) cLevel = adaptMin;
if (adaptMax < cLevel) cLevel = adaptMax;
/* Compare strategies constant with the ground truth */
{ ZSTD_bounds strategyBounds = ZSTD_cParam_getBounds(ZSTD_c_strategy);
assert(ZSTD_NB_STRATEGIES == strategyBounds.upperBound);
(void)strategyBounds; }
if (showDefaultCParams || g_displayLevel >= 4) {
size_t fileNb;
for (fileNb = 0; fileNb < (size_t)filenames->tableSize; fileNb++) {
if (showDefaultCParams)
printDefaultCParams(filenames->fileNames[fileNb], dictFileName, cLevel);
if (g_displayLevel >= 4)
printActualCParams(filenames->fileNames[fileNb], dictFileName, cLevel, &compressionParams);
}
}
if (g_displayLevel >= 4)
FIO_displayCompressionParameters(prefs);
if ((filenames->tableSize==1) && outFileName)
operationResult = FIO_compressFilename(fCtx, prefs, outFileName, filenames->fileNames[0], dictFileName, cLevel, compressionParams);
else
operationResult = FIO_compressMultipleFilenames(fCtx, prefs, filenames->fileNames, outMirroredDirName, outDirName, outFileName, suffix, dictFileName, cLevel, compressionParams);
#else
/* these variables are only used when compression mode is enabled */
(void)contentSize; (void)suffix; (void)adapt; (void)rsyncable;
(void)ultra; (void)cLevel; (void)ldmFlag; (void)literalCompressionMode;
(void)targetCBlockSize; (void)streamSrcSize; (void)srcSizeHint;
(void)ZSTD_strategyMap; (void)useRowMatchFinder; (void)cType;
DISPLAYLEVEL(1, "Compression not supported \n");
#endif
} else { /* decompression or test */
#ifndef ZSTD_NODECOMPRESS
if (filenames->tableSize == 1 && outFileName) {
operationResult = FIO_decompressFilename(fCtx, prefs, outFileName, filenames->fileNames[0], dictFileName);
} else {
operationResult = FIO_decompressMultipleFilenames(fCtx, prefs, filenames->fileNames, outMirroredDirName, outDirName, outFileName, dictFileName);
}
#else
DISPLAYLEVEL(1, "Decompression not supported \n");
#endif
}
_end:
FIO_freePreferences(prefs);
FIO_freeContext(fCtx);
if (main_pause) waitEnter();
UTIL_freeFileNamesTable(filenames);
UTIL_freeFileNamesTable(file_of_names);
#ifndef ZSTD_NOTRACE
TRACE_finish();
#endif
return operationResult;
}
```
|
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "path_to_url">
<html xmlns="path_to_url">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="x-ua-compatible" content="ie=7"/>
<title> CMS500 | WooYun-2015-102271 | WooYun.org </title>
<meta name="author" content="80sec"/>
<meta name="copyright" content="path_to_url"/>
<meta name="keywords" content=",,,wooyun,,web,,,,,"/>
<meta name="description" content="
rank|WooYun,,,"/>
<link rel="icon" href="path_to_url" sizes="32x32" />
<link href="../css/style.css?v=201501291909" rel="stylesheet" type="text/css"/>
<script src="path_to_url" type="text/javascript"></script>
</head>
<body id="bugDetail">
<style>
#myBugListTab { position:relative; display:inline; border:none }
#myBugList { position:absolute; display:none; margin-left:309px; * margin-left:-60px; * margin-top:18px ; border:#c0c0c0 1px solid; padding:2px 7px; background:#FFF }
#myBugList li { text-align:left }
</style>
<script type="text/javascript">
$(document).ready(function(){
if ( $("#__cz_push_d_object_box__") ) {
$("script[src^='path_to_url").attr("src"," ").remove();
$("#__cz_push_d_object_box__").empty().remove();
$("a[id^='__czUnion_a']").attr("href","#").remove();
}
if ( $("#ooDiv") ) {
$("#ooDiv").empty().parent("div").remove();
}
$("#myBugListTab").toggle(
function(){
$("#myBugList").css("display","block");
},
function(){
$("#myBugList").css("display","none");
}
);
if ( $(window).scrollTop() > 120 ) {
$("#back-to-top").fadeIn(300);
} else {
$("#back-to-top").fadeOut(300);
}
$(window).scroll(function(){
if ( $(window).scrollTop() > 120 ) {
$("#back-to-top").fadeIn(300);
} else {
$("#back-to-top").fadeOut(300);
}
});
$("#back-to-top a").click(function() {
$('body,html').animate({scrollTop:0},300);
return false;
});
$("#go-to-comment a").click(function() {
var t = $("#replys").offset().top - 52;
$('body,html').animate({scrollTop:t},300);
return false;
});
});
function gofeedback(){
var bugid=$("#fbid").val();
if(bugid){
var url="/feedback.php?bugid="+bugid;
}else{
var url="/feedback.php"
}
window.open(url);
}
</script>
<div class="go-to-wrapper">
<ul class="go-to">
<li id="go-to-comment" title=""><a href="wooyun-2015-0102271#"></a></li>
<li id="go-to-feedback" title=""><a href="javascript:void(0)" onclick="gofeedback()"></a></li>
<li id="back-to-top" title=""><a href="wooyun-2015-0102271#"></a></li>
</ul>
</div>
<div class="banner">
<div class="logo">
<h1>WooYun.org</h1>
<div class="weibo"><iframe width="136" height="24" frameborder="0" allowtransparency="true" marginwidth="0" marginheight="0" scrolling="no" border="0" src="path_to_url"></iframe>
</div>
<div class="wxewm">
<a class="ewmthumb" href="javascript:void(0)"><span><img src="path_to_url"width="220" border="0"></span><img src="path_to_url"width="22" border="0"></a>
</div>
</div>
<div class="login">
<a href="path_to_url"></a> | <a href="path_to_url" class="reg"></a>
</div>
</div>
<div class="nav" id="nav_sc">
<ul>
<li><a href="path_to_url"></a></li>
<li><a href="path_to_url"></a></li>
<li><a href="path_to_url"></a></li>
<li><a href="path_to_url"></a></li>
<li><a href="path_to_url"></a></li>
<li><a href="path_to_url"></a></li>
<li class="new"><a href="path_to_url"></a></li>
<!--li><a href="/corp_actions"></a></li-->
<!--<li><a target='_blank' href="path_to_url"></a></li>-->
<li><a href="path_to_url" target="_blank" style="color:rgb(246,172,110);font-size:14px;font-weight:blod"></a></li>
<!--li><a href="/job/"></a></li-->
<li><a href="path_to_url" target="_blank"></a></li>
<li><a href="path_to_url" target="_blank"></a></li>
<li><a href="path_to_url"></a></li>
</ul>
<form action="path_to_url" method="post" id="searchbox">
<input type="text" name="q" id="search_input" />
<input type="submit" value="" id="search_button" />
</form>
</div>
<div class="bread" style="padding-top: 4px;">
<div style="float:left"><a href="path_to_url">WooYun</a> >> <a href="wooyun-2015-0102271#"></a></div>
</div>
<script language="javascript">
var _LANGJS = {"COMMENT_LIKE_SELF":"\u4e0d\u80fd\u81ea\u5df1\u8d5e\u81ea\u5df1\u7684\u8bc4\u8bba","COMMENT_LIKED":"\u5df2\u8d5e\u6b64\u8bc4\u8bba","COMMENT_NOT":"\u6b64\u8bc4\u8bba\u4e0d\u5b58\u5728","COMMENT_FILL":"\u8bf7\u8f93\u5165\u8bc4\u8bba\u5185\u5bb9","COMMENT_STAT":"\u8bc4\u8bba\u4e0d\u80fd\u4e3a\u7a7a","COMMENT_LOGIN":"\u767b\u9646\u540e\u624d\u80fd\u8bc4\u8bba","COMMENT_GOOD_DONE":"\u5df2\u8d5e\u8fc7\u6b64\u6761\u8bc4\u8bba","COMMENT_SELF":"\u4e0d\u80fd\u8bc4\u4ef7\u81ea\u5df1\u53d1\u5e03\u7684\u8bc4\u8bba","COMMENT_CLICK_FILL":"\u70b9\u51fb\u8f93\u5165\u8bc4\u8bba\u5185\u5bb9","FAIL":"\u64cd\u4f5c\u5931\u8d25","FAIL_MANAGE":"\u64cd\u4f5c\u5931\u8d25\uff0c\u8bf7\u4e0e\u7ba1\u7406\u5458\u8054\u7cfb","FAIL_NO_WHITEHATS":"\u64cd\u4f5c\u5931\u8d25\uff0c\u6ca1\u6709\u6b64\u767d\u5e3d\u5b50","FAIL_NO_CORPS":"\u64cd\u4f5c\u5931\u8d25\uff0c\u6ca1\u6709\u6b64\u5382\u5546","BUGS_CORPS_SELECT":"\u9009\u62e9\u5382\u5546(\u53ef\u8f93\u5165\u5173\u952e\u5b57\u641c\u7d22)","BUGS_CORPS_OTHER":"Other\/\u5176\u5b83\u5382\u5546","BUGS_CORPS_TYPE_STAT":"\u8be5\u6f0f\u6d1e\u5bf9\u5e94\u5382\u5546\u7684\u7c7b\u578b","BUGS_CORPS_NAME_STAT":"\u8be5\u6f0f\u6d1e\u5bf9\u5e94\u5382\u5546\u7684\u540d\u79f0","BUGS_TYPE_STAT":"\u8be5\u6f0f\u6d1e\u7684\u7c7b\u578b\uff0c\u4e71\u9009\u6263\u5206","BUGS_TITLE_STAT":"\u8be5\u6f0f\u6d1e\u7684\u6807\u9898","BUGS_HARMLEVEL_STAT":"\u8be5\u6f0f\u6d1e\u7684\u5371\u5bb3\u7b49\u7ea7","BUGS_DESCRIPTION_STAT":"\u5bf9\u6f0f\u6d1e\u7684\u7b80\u8981\u63cf\u8ff0\uff0c\u53ef\u4ee5\u7b80\u5355\u63cf\u8ff0\u6f0f\u6d1e\u7684\u5371\u5bb3\u548c\u6210\u56e0\uff0c\u4e0d\u8981\u900f\u6f0f\u6f0f\u6d1e\u7684\u7ec6\u8282","BUGS_CONTENT_STAT":"\u5bf9\u6f0f\u6d1e\u7684\u8be6\u7ec6\u63cf\u8ff0\uff0c\u8bf7\u5c3d\u91cf\u591a\u7684\u6df1\u5165\u7ec6\u8282\u4ee5\u65b9\u4fbf\u5bf9\u6f0f\u6d1e\u7684\u7406\u89e3\uff0c\u652f\u6301<code><\/code>\u6807\u7b7e","BUGS_POC_STAT":"\u7ed9\u51fa\u95ee\u9898\u7684\u6982\u5ff5\u6027\u8bc1\u660e\uff0c\u652f\u6301<code><\/code>\u6807\u7b7e","BUGS_PATCH_STAT":"\u5efa\u8bae\u7684\u6f0f\u6d1e\u4fee\u590d\u65b9\u6848\uff0c\u652f\u6301<code><\/code>\u6807\u7b7e","BUGS_TEST_STAT":"\u7ed9\u51fa\u95ee\u9898\u7684\u6807\u51c6\u6d4b\u8bd5\u4ee3\u7801\u4ee5\u66f4\u4e3a\u65b9\u4fbf\u7684\u5bf9\u6f0f\u6d1e\u8fdb\u884c\u6d4b\u8bd5\u548c\u9a8c\u8bc1\uff0c\u6d4b\u8bd5\u4ee3\u7801\u5bf9\u5916\u9ed8\u8ba4\u4e0d\u663e\u793a\uff0c<br\/>\u5176\u4ed6\u767d\u5e3d\u5b50\u652f\u4ed8\u4e4c\u4e91\u5e01\u67e5\u770b\u540e\u4f60\u5c06\u83b7\u5f97\u989d\u5916\u4e4c\u4e91\u5e01\uff0c<br\/>\u540c\u65f6\u4e5f\u5c06\u5728\u4f60\u7684\u4e2a\u4eba\u9875\u9762\u4f53\u73b0\u4f60\u7684\u6d4b\u8bd5\u4ee3\u7801\u7f16\u5199\u80fd\u529b\u3002","BUGS_QUESTION_SELECT":"\u8bf7\u9009\u62e9\u95ee\u9898\u5382\u5546","BUGS_TITLE_NOTICE":"\u6f0f\u6d1e\u6807\u9898\u4e0d\u80fd\u4e3a\u7a7a","BUGS_RANK_NOTICE1":"\u8bf7\u586b\u5199\u81ea\u8bc4Rank","BUGS_RANK_NOTICE2":"\u81ea\u8bc4Rank\u4e3a\u5927\u4e8e0\u7684\u6570\u5b57","BUGS_TYPE_SELECT":"\u8bf7\u9009\u62e9\u6f0f\u6d1e\u7c7b\u578b","BUGS_TYPE_NOTICE":"\u8bf7\u586b\u5199\u6f0f\u6d1e\u7c7b\u578b","BUGS_HARMLEVEL_SELECT":"\u9009\u62e9\u6f0f\u6d1e\u7b49\u7ea7","BUGS_HARMLEVEL_NOTICE":"\u8bf7\u9009\u62e9\u6f0f\u6d1e\u7b49\u7ea7","BUGS_HARMLEVEL_LOWER":"\u6f0f\u6d1e\u7b49\u7ea7\u4e3a \u4f4e \u65f6\uff0c\u81ea\u8bc4Rank\u4e3a1-5","BUGS_HARMLEVEL_MIDDLE":"\u6f0f\u6d1e\u7b49\u7ea7\u4e3a \u4e2d \u65f6\uff0c\u81ea\u8bc4Rank\u4e3a5-10","BUGS_HARMLEVEL_HIGH":"\u6f0f\u6d1e\u7b49\u7ea7\u4e3a \u9ad8 \u65f6\uff0c\u81ea\u8bc4Rank\u4e3a10-20","BUGS_AREA_SELECT":"\u8bf7\u9009\u62e9\u5730\u533a\uff01","BUGS_DOMAILS":"\u6f0f\u6d1e\u6240\u5728\u57df\u540d(\u5982qq.com)","BUGS_DOMAIN_FILL":"\u8bf7\u586b\u5199\u57df\u540d\uff01","BUGS_DETAIL_MORE":"\u67e5\u770b\u8be6\u60c5","BUGS_IGNORE_DAYS":"\u8ddd\u6f0f\u6d1e\u5ffd\u7565\u8fd8\u6709","BUGS_CONFIRM_QUICK":"\u8bf7\u5382\u5546\u5c3d\u5feb","BUGS":"\u6f0f\u6d1e","BUGS_PUBLIC_DAYS":"\u8ddd\u6f0f\u6d1e\u5411\u516c\u4f17\u516c\u5f00\u8fd8\u6709","BUGS_IGNORE_PUBLIC_DAYS":"\u8ddd\u6f0f\u6d1e\u672a\u786e\u8ba4\u65e0\u5f71\u54cd\u5ffd\u7565\u8fd8\u6709","BUGS_REPAIR_QUICK":"\u8bf7\u5382\u5546\u5c3d\u5feb\u4fee\u590d\u6f0f\u6d1e","BUGS_HARMLEVEL_REMIND":"\u8bf7\u9009\u62e9\u5371\u5bb3\u7b49\u7ea7","BUGS_RANK_STAT":"rank\u4e3a1-20\u7684\u6b63\u6574\u6570","BUGS_RANK_STAT1":"rank\u4e3a1-5\u7684\u6b63\u6574\u6570","BUGS_RANK_STAT2":"rank\u4e3a5-10\u7684\u6b63\u6574\u6570","BUGS_RANK_STAT3":"rank\u4e3a10-20\u7684\u6b63\u6574\u6570","BUGS_COMPLEMENT_REASON":"\u6dfb\u52a0\u5bf9\u6f0f\u6d1e\u7684\u8865\u5145\u8bf4\u660e\u4ee5\u53ca\u505a\u51fa\u8bc4\u4ef7\u7684\u7406\u7531","BUGS_REPLY_FILL":"\u8bf7\u586b\u5199\u6f0f\u6d1e\u56de\u590d","BUGS_IGNORE_CONFIRM":"\u786e\u5b9a\u5ffd\u7565\u6b64\u6f0f\u6d1e\u5417","BUGS_STATUS_NEW_UPDATE":"\u66f4\u6539\u6f0f\u6d1e\u7684\u6700\u65b0\u72b6\u6001","BUGS_STATUS_FILL":"\u8bf7\u586b\u5199\u6f0f\u6d1e\u72b6\u6001","BUGS_PUBLIC_ADVANCE":"\u786e\u5b9a\u63d0\u524d\u516c\u5f00\u6b64\u6f0f\u6d1e\u5417","BUGS_COUNT":"\u6f0f\u6d1e\u6570","BUGS_REPLY_HAT":"\u56de\u590d\u6b64\u4eba","BUGS_DELAY_CONFIRM":"\u786e\u5b9a\u8981\u5ef6\u671f\u4e48?","BUGS_DELAY":"\u7533\u8bf7\u5ef6\u671f","BUGS_DELAY_DONE":"\u5df2\u7ecf\u5ef6\u671f","BUGS_RISK_CONFIM":"\u786e\u5b9a\u6b64\u6f0f\u6d1e\u4e3a\u9ad8\u5371\u5417?","BUGS_NULL_EDITE":"\u7559\u7a7a\u8868\u793a\u4e0d\u4fee\u6539","BUGS_DONE_CONFIRM":"\u8be5\u64cd\u4f5c\u6682\u65f6\u4e0d\u53ef\u9006\uff0c\u786e\u5b9a\uff1f","BUGS_UPUBLIC":"\u4f60\u4ece\u53d1\u5e03\u7684\u6f0f\u6d1e","BUGS_UPUBLIC1":"\u91cc\u53c8\u83b7\u5f97\u4e86","BUGS_PRECHECK":"\u6709\u4eba\u63d0\u524d\u67e5\u770b\u4e86\u4f60\u53d1\u5e03\u7684\u6f0f\u6d1e","BUGS_PRECHECK_UNPUBLIC":"\u63d0\u524d\u67e5\u770b\u672a\u516c\u5f00\u6f0f\u6d1e","BUGS_NUM":"\u6f0f\u6d1e\u6570\u91cf","RANKAVG":"\u4eba\u5747\u8d21\u732e Rank","CAPTCHA_GET":"\u83b7\u53d6\u9a8c\u8bc1\u7801","CAPTCHA_FILL":"\u8bf7\u8f93\u5165\u56fe\u7247\u4e2d\u7684\u9a8c\u8bc1\u7801","CAPTCHA_NULL":"\u9a8c\u8bc1\u7801\u4e0d\u80fd\u4e3a\u7a7a","CAPTCHA_ERROR":"\u9a8c\u8bc1\u7801\u8f93\u5165\u9519\u8bef","CAPTCHA_PHONE_ERROR":"\u624b\u673a\u9a8c\u8bc1\u7801\u4e0d\u6b63\u786e","CAPTCHA_PHONE_SEND":"\u9a8c\u8bc1\u7801\u5df2\u53d1\u9001\u5230\u4f60\u7684\u624b\u673a\u4e0a\u8bf7\u6ce8\u610f\u67e5\u6536","CAPTCHA_SEND_AGAIN":"\u540e\u53ef\u91cd\u53d1","CAPTCHA_SEND_OVER":"\u77ed\u4fe1\u5df2\u53d1\u9001\u6210\u529f,\u9a8c\u8bc1\u7801\u533a\u5206\u5927\u5c0f\u5199","CAPTCHA_PHONE_NO":"\u4e0d\u9700\u8981\u77ed\u4fe1\u9a8c\u8bc1\u7801","CAPTCHA_PHONE_NULL":"\u77ed\u4fe1\u5bc6\u7801\u4e0d\u80fd\u4e3a\u7a7a","PHONE_TYPE_ERROR":"\u7535\u8bdd\u683c\u5f0f\u4e0d\u5bf9","PHONE_NOTING":"\u7535\u8bdd\u4e0d\u80fd\u4e3a\u7a7a","PHONE_FILL":"\u8bf7\u586b\u5199\u624b\u673a\u53f7","PHONE_CAPTCHA_NOTING":"\u624b\u673a\u9a8c\u8bc1\u7801\u4e0d\u80fd\u4e3a\u7a7a","PASSWORD_NOTING":"\u5bc6\u7801\u4e0d\u80fd\u4e3a\u7a7a","PASSWORD_CONFIRM_NOTING":"\u5bc6\u7801\u786e\u8ba4\u4e0d\u80fd\u4e3a\u7a7a","PASSWORD_PAY_LESS":"\u652f\u4ed8\u5bc6\u7801\u4e0d\u80fd\u5c11\u4e8e6\u4f4d","PASSWORD_FILL_DIFFERENT":"\u8f93\u5165\u7684\u4e24\u6b21\u5bc6\u7801\u4e0d\u4e00\u6837","PASSWORD_PAY_LOGIN_SAME":"\u652f\u4ed8\u5bc6\u7801\u4e0d\u80fd\u540c\u767b\u9646\u5bc6\u7801\u4e00\u6837","PASSWORD_PAY_FILL":"\u8bf7\u586b\u5199\u652f\u4ed8\u5bc6\u7801","PASSWORD_LENGH_LESS":"\u5bc6\u7801\u957f\u5ea6\u4e0d\u80fd\u5c0f\u4e8e6\u4f4d","PASSWORD_SEND_OK":"\u53d1\u9001\u5bc6\u7801\u90ae\u4ef6\u6210\u529f","PASSWORD_OFER_WRROR":"\u60a8\u63d0\u4f9b\u7684\u627e\u56de\u5bc6\u7801\u4fe1\u606f\u4e0d\u6b63\u786e","PASSWORD_OLD_ERROR":"\u539f\u5bc6\u7801\u9519\u8bef","PASSWORD_UPDATE_OK":"\u5bc6\u7801\u4fee\u6539\u6210\u529f","EMAILL_USED":"\u90ae\u7bb1\u5df2\u88ab\u5360\u7528","EMAILL_NULL":"\u90ae\u7bb1\u4e0d\u80fd\u4e3a\u7a7a\uff01","NOTING":"\u65e0","LEAVEWORDS_NULL":"\u7559\u8a00\u5185\u5bb9\u4e0d\u80fd\u4e3a\u7a7a","LOGIN_FIRST":"\u8bf7\u5148\u767b\u5f55","CONFIRM":"\u786e\u8ba4","YEAR":"\u5e74","DAYS":"\u5929","HOURS":"\u65f6","HOUR":"\u5c0f\u65f6","MINUTE":"\u5206","SECOND":"\u79d2","IS":"\u4e3a","ONE":"\u4e00","TWE":"\u4e8c","TIMES":"\u6b21","COUNTENT_UPDATE_FILL":"\u8bf7\u586b\u5199\u4fee\u6539\u5185\u5bb9","CANCLE":"\u53d6\u6d88","OPERATE_CONFIRM":"\u786e\u5b9a\u6b64\u64cd\u4f5c\u5417\uff1f","USERNAME":"\u59d3\u540d","SUCCESS":"\u64cd\u4f5c\u6210\u529f","FAIL_REPLY":"\u64cd\u4f5c\u5931\u8d25\uff0c\u8bf7\u586b\u5199\u56de\u590d\u4fe1\u606f","SEND_OK":"\u53d1\u9001\u6210\u529f","PHONE_BIND_DONE":"\u5df2\u7ed1\u5b9a","TAGS_USE":"\u4f7f\u7528\u6b64\u6807\u7b7e","WHITEHATS":"\u767d\u5e3d\u5b50","WHITEHATS_VERTIFY":"\u8ba4\u8bc1\u767d\u5e3d\u5b50","WHITEHATES_NAME":"\u8bf7\u8f93\u5165\u767d\u5e3d\u5b50\u7528\u6237\u540d","USER_ZONE_EDIT":"\u7f16\u8f91\u9886\u57df","WB_TRANSFER":"\u6211\u8981\u8f6c\u8d26","WB_TRANSFER_CANCEL":"\u53d6\u6d88\u8f6c\u8d26","WB_NUM":"\u8bf7\u8f93\u5165\u4e4c\u4e91\u5e01\u6570\u91cf","WB_NUMBER":"\u4e4c\u4e91\u5e01\u6570\u91cf\u4e3a\u6b63\u6574\u6570","WB_NEED_LESS":"\u81f3\u5c11\u9700\u8981","WB_NEED_SUM":"\u4e2a\u4e4c\u4e91\u5e01","WB_TRANSFER_OK":"\u8f6c\u8d26\u6210\u529f","WB_MY":"\u6211\u7684\u4e4c\u4e91\u5e01","WB_CAN_USE":"\u53ef\u7528\u7684\u4e4c\u4e91\u5e01","WB_FROZEN":"\u51bb\u7ed3\u7684\u4e4c\u4e91\u5e01","WB_LACK":"\u4e4c\u4e91\u5e01\u4e0d\u8db3","WB_SET_SCOPE":"\u51fa\u4ef7\u8303\u56f4\u4e3a","WB_BIND_CANCEL_STAT":"(\u70b9\u51fb\u201c\u53d6\u6d88\u7ed1\u5b9a\u201d\u83b7\u53d6\u9a8c\u8bc1\u7801\uff0c\u5411\u4e4c\u4e91\u516c\u4f17\u8d26\u53f7\u53d1\u9001\u9a8c\u8bc1\u7801\u53d6\u6d88\u5fae\u4fe1\u7ed1\u5b9a\uff0c\u7136\u540e\u5237\u65b0\u672c\u9875\u9762)","EMAIL_LOGIN_MEXT":"\u90ae\u4ef6\u53d1\u9001\u6210\u529f,\u8bf7\u767b\u9646\u60a8\u7684\u90ae\u7bb1\u8fdb\u884c\u4e0b\u4e00\u6b65\u64cd\u4f5c","EMAIL_UPDATE_LOGIN_MEXT":"\u66f4\u6539\u8bf7\u6c42\u5df2\u53d1\u9001\u5230\u90ae\u7bb1,\u8bf7\u767b\u9646\u60a8\u7684\u90ae\u7bb1\u8fdb\u884c\u4e0b\u4e00\u6b65\u64cd\u4f5c","EMAIL_SEND_OK":"\u90ae\u4ef6\u53d1\u9001\u6210\u529f\uff01","CORPS":"\u5382\u5546","TEAM_NAME_NULL":"\u56e2\u961f\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a","TEAM_HOMEPAGE_NULL":"\u56e2\u961f\u4e3b\u9875\u4e0d\u80fd\u4e3a\u7a7a","TEAM_QQ_NULL":"\u56e2\u961fqq\u4e0d\u80fd\u4e3a\u7a7a","TEAM_BRIEF_NULL":"\u56e2\u961f\u7b80\u4ecb\u4e0d\u80fd\u4e3a\u7a7a","TEAM_EXIST":"\u56e2\u961f\u5df2\u5b58\u5728","TEAM_DISMISS_CONFIRM":"\u786e\u5b9a\u89e3\u6563\u672c\u56e2\u961f\u5417?","TEAM_NAME":"\u56e2\u961f\u540d\u79f0","TEAM_CREATER":"\u521b\u5efa\u4eba","TEAM_DONATER":"\u56e2\u961f\u4e3b\u529b","TEAM_MUMBER":"\u4eba\u6570","TEAM":"\u56e2\u961f","REGISTER_BRIEF":"*\u8bf7\u8f93\u5165\u4e2a\u4eba\u7684\u7b80\u8981\u4ecb\u7ecd","REGISTER_TYPE":"*\u9009\u62e9\u6ce8\u518c\u7c7b\u578b","REGISTER_CORPS_BRIEF":"*\u8f93\u5165\u5382\u5546\u7684\u7b80\u8981\u4ecb\u7ecd","REGISTER_EMAIL":"*\u5382\u5546\u90ae\u4ef6\u5fc5\u987b\u4e3a\u4f01\u4e1a\u4f7f\u7528\u7684\u6b63\u5f0f\u90ae\u4ef6","REGISTER_NAME_NULL":"\u7528\u6237\u540d\u4e0d\u80fd\u4e3a\u7a7a","REGISTER_HOMEPAGE_NULL":"\u4e2a\u4eba\u4e3b\u9875\u4e0d\u80fd\u4e3a\u7a7a","REGISTER_BREIF_NULL":"\u7b80\u8981\u4ecb\u7ecd\u4e0d\u80fd\u4e3a\u7a7a","REGISTER_CORPNAME_NULL":"\u5382\u5546\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a","REGISTER_CORPHOMEPAGE_NULL":"\u5b98\u65b9\u4e3b\u9875\u4e0d\u80fd\u4e3a\u7a7a","REGISTER_LAW_AGREE":"\u540c\u610f\u300a\u4fe1\u606f\u5b89\u5168\u76f8\u5173\u4fdd\u62a4\u548c\u58f0\u660e\u300b\u624d\u80fd\u6ce8\u518c","ATTENTION":"\u5173\u6ce8","ATTENTION_SUM":"\u5173\u6ce8\u6570","ATTENTION_DONE":"\u5df2\u5173\u6ce8","ATTENTION_CANCEL":"\u53d6\u6d88\u5173\u6ce8","ATTENTION_BUG_DONE":"\u5df2\u5173\u6ce8\u6b64\u6f0f\u6d1e","ATTENTION_BUG_CONFIRM":"\u786e\u5b9a\u53d6\u6d88\u5bf9\u6b64\u6f0f\u6d1e\u7684\u5173\u6ce8","ATTENTION_BUG":"\u5173\u6ce8\u6b64\u6f0f\u6d1e","ATTENTION_BUG_UNDO":"\u6ca1\u6709\u5173\u6ce8\u6b64\u6f0f\u6d1e","ATTENTION_HAT_DONE":"\u5df2\u5173\u6ce8\u6b64\u767d\u5e3d\u5b50","ATTENTION_HAT_CONFIRM":"\u786e\u5b9a\u53d6\u6d88\u5bf9\u6b64\u767d\u5e3d\u5b50\u7684\u5173\u6ce8?","COLLECTION":"\u6536\u85cf","COLLECTION_DONE":"\u5df2\u6536\u85cf","COLLECTION_BUG_DONE":"\u5df2\u6536\u85cf\u6b64\u6f0f\u6d1e","COLLECTION_BUG_UNDO":"\u6ca1\u6709\u6536\u85cf\u6b64\u6f0f\u6d1e","COLLECTION_BUG_CONFIRM":"\u786e\u5b9a\u53d6\u6d88\u5bf9\u6b64\u6f0f\u6d1e\u7684\u6536\u85cf","SMS_SEND_NAME":"* \u7528\u6237\u6635\u79f0\/\u5382\u5546\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a<br \/>","SMS_SEND_TITLE":"* \u6807\u9898\u4e0d\u80fd\u4e3a\u7a7a<br \/>","SMS_SEND_CONTENT":"* \u5185\u5bb9\u4e0d\u80fd\u4e3a\u7a7a<br \/>","SMS_SEND_CAPTCHA":"* \u9a8c\u8bc1\u7801\u4e0d\u80fd\u4e3a\u7a7a<br \/>","NUMBER":"\u7684\u6b63\u6574\u6570","RATING_SUCCESS":"\u8bc4\u5206\u6210\u529f","RATING_BUGS_DONE":"\u5df2\u5bf9\u6b64\u6f0f\u6d1e\u8fdb\u884c\u8fc7\u8bc4\u5206","RATING_BUGS_SELF":"\u4e0d\u80fd\u5bf9\u81ea\u5df1\u53d1\u5e03\u7684\u6f0f\u6d1e\u8fdb\u884c\u8bc4\u5206","RATING_SUBMIT_CANCLE":"\u53d6\u6d88\u63d0\u4ea4\u8bc4\u5206","RATING_SUBMIT":"\u63d0\u4ea4\u6211\u7684\u8bc4\u5206","RATING_SUBMIT_CHECK":"\u8bf7\u786e\u5b9a\u6bcf\u4e00\u9879\u90fd\u9009\u62e9\u4e86\u8bc4\u5206","RATING_CONFIRM":"\u786e\u5b9a\u63d0\u4ea4\u5bf9\u6b64\u5382\u5546\u7684\u8bc4\u5206\u5417\uff1f","RATING_LOGIN":"\u53ea\u6709\u767b\u5f55\u7684\u767d\u5e3d\u5b50\u624d\u80fd\u8bc4\u5206","RATING_DONE":"\u5df2\u7ecf\u8bc4\u8fc7\u5206\u4e86","WOOYUN_CORPS":"\u4e4c\u4e91\u5382\u5546","MARST_IMAGE":"\u5bf9\u56fe\u7247\u6253\u7801","FEEDBACK_LINK_NULL":"\u94fe\u63a5\u4e0d\u80fd\u4e3a\u7a7a\uff01","FEEDBACK_LINK_ERROR":"\u8bf7\u4e66\u5199\u6b63\u786e\u7684\u94fe\u63a5\u5730\u5740\uff01","FEEDBACK_CONTENT_NULL":"\u95ee\u9898\u5185\u5bb9\u4e0d\u80fd\u4e3a\u7a7a\uff01","FEEDBACK_ALLOW_LIMIT":"\u534a\u5c0f\u65f6\u53ea\u5141\u8bb8\u53cd\u9988\u4e00\u6b21","TOP_RANK":"\u6392\u540d","TOP_BUG_TITLE":"\u6f0f\u6d1e\u6807\u9898","TOP_RANK_NONE":"\u6682\u65e0\u6392\u540d","TOP_BUGS_GOOD":"\u4f18\u8d28\u6f0f\u6d1e\u6570","NICKNAME":"\u6635\u79f0","LEVEL":"\u7b49\u7ea7","VALUE":"\u503c","EDITOR_INSERT_PIC":"\u63d2\u5165\u56fe\u7247","EDITOR_PIC_ADDR":"\u5730\u5740\uff1a","EDITOR_CONFIRM":"\u786e\u5b9a","EDITOR_PIC_NULL":"\u8bf7\u4e0a\u4f20\u56fe\u7247\u6216\u586b\u5199\u56fe\u7247\u5730\u5740","EDITOR_INSERT_VIDIO":"\u63d2\u5165\u89c6\u9891","EDITOR_VIDIO_ADDR":"\u89c6\u9891\u5730\u5740\uff1a","EDITOR_VIDIO_NULL":"\u8bf7\u586b\u5199\u89c6\u9891\u5730\u5740(.swf)","EDITOR_VIDIO_TYPE":"\u76ee\u524d\u4ec5\u652f\u6301.swf\u683c\u5f0f","PIC_SELECT":"\u8bf7\u9009\u62e9\u5f85\u4e0a\u4f20\u7684\u56fe\u7247","PIC_TYPE_IS":"\u56fe\u7247\u7c7b\u578b\u4e3a","UPLOAD":"\u4e0a\u4f20","RANK_AVG":"\u6f0f\u6d1e\u5e73\u5747"};
$(function(){
function getParamsOfShareWindow(width, height) {
return ['toolbar=0,status=0,resizable=1,width=' + width + ',height=' + height + ',left=',(screen.width-width)/2,',top=',(screen.height-height)/2].join('');
}
});
function errimg(img){
tmp=img.src;
nimg=tmp.replace("path_to_url","path_to_url");
img.src=nimg;
$(img).parent().attr('href',nimg);
img.onerror=null;
}
function AttendBug(id){
$.get('/ajaxdo.php',{module:'attendbug',id:id,rid:Math.random(),token:$("#token").val()},function(re){
if(re==1){
$("#attention_num").html(parseInt($("#attention_num").html())+1);
$("#attend_action").html(''+_LANGJS.ATTENTION_DONE+' <a class="btn" href="javascript:void(0)" onclick="AttendCancel('+id+')">'+_LANGJS.ATTENTION_CANCEL+'</a></span>');
}else if(re==2){
alert(_LANGJS.LOGIN_FIRST);
}else if(re==3){
alert(_LANGJS.ATTENTION_BUG_DONE);
}else{
alert(_LANGJS.FAIL_MANAGE);
}
});
}
function AttendCancel(id){
if(confirm(_LANGJS.ATTENTION_BUG_CONFIRM+"?")){
$.get('/ajaxdo.php',{module:'attendcancel',id:id,rid:Math.random(),token:$("#token").val()},function(re){
if(re==1){
$("#attention_num").html(parseInt($("#attention_num").html())-1);
$("#attend_action").html('<a class="btn" href="javascript:void(0)" onclick="AttendBug('+id+')">'+_LANGJS.ATTENTION_BUG+'</a></span>');
}else{
alert(_LANGJS.FAIL_MANAGE);
}
});
}
}
function CollectBug(id,token){
$.get('/ajaxdo.php',{'module':'collect','id':id,'token':token,'rid':Math.random()},function(re){
if(re==1){
$("#collection_num").html(parseInt($("#collection_num").html())+1);
$(".btn-fav").removeClass("fav-add");
$(".btn-fav").addClass("fav-cancel");
$(".btn-fav").unbind();
$(".btn-fav").click(function(){
CollectCancel(id,token);
});
}else if(re==2){
alert(_LANGJS.LOGIN_FIRST);
}else if(re==3){
alert(_LANGJS.COLLECTION_BUG_DONE);
}else{
alert(_LANGJS.FAIL_MANAGE);
}
});
}
function CollectCancel(id,token){
if(confirm(_LANGJS.COLLECTION_BUG_CONFIRM+"?")){
$.get('/ajaxdo.php',{'module':'collectcancel','id':id,'token':token,'rid':Math.random()},function(re){
if(re==1){
$("#collection_num").html(parseInt($("#collection_num").html())-1);
$(".btn-fav").removeClass("fav-cancel");
$(".btn-fav").addClass("fav-add");
$(".btn-fav").unbind();
$(".btn-fav").click(function(){
CollectBug(id,token);
});
}else{
alert(_LANGJS.FAIL_MANAGE);
}
});
}
}
</script>
<div class="content">
<input type="hidden" id="token" style="display:none" value="" />
<h2>
<span style="margin:0 0 0 580px; float:right; position:absolute; font-size:14px; font-weight:normal">(<span id="attention_num">20</span>)
<span id="attend_action">
<a class="btn" href="javascript:void(0)" onclick="AttendBug(102271)"></a></span>
</span></h2>
<h3> <a href="wooyun-2015-0102271">WooYun-2015-102271</a>
<input id="fbid" type="hidden" value="102271">
</h3>
<h3 class='wybug_title'> CMS500 <img src="path_to_url" alt="" class="credit">
</h3>
<h3 class='wybug_corp'> <a href="path_to_url">
</a>
</h3>
<h3 class='wybug_author'> <a href="path_to_url"></a></h3>
<h3 class='wybug_date'> 2015-03-21 11:09</h3>
<h3 class='wybug_open_date'> 2015-06-22 08:32</h3>
<h3 class='wybug_type'> </h3>
<h3 class='wybug_level'> </h3>
<h3>Rank 20</h3>
<h3 class='wybug_status'>
(cncert)
</h3>
<h3> <a href="path_to_url">path_to_url help@wooyun.org</h3>
<h3>Tags
</h3>
<h3>
<!-- Baidu Button BEGIN -->
<div id="share">
<div style="float:right; margin-right:100px;font-size:12px">
<span class="fav-num"><a id="collection_num">0</a></span>
<a style="text-decoration:none; font-size:12px" href="javascript:void(0)" class="fav-add btn-fav"></a>
<script type="text/javascript">
var token="";
var id="102271";
$(".btn-fav").click(function(){ CollectBug(id,token); });
</script>
</div>
<span style="float:left;"></span>
<div id="bdshare" class="bdshare_b" style="line-height: 12px;"><img src="path_to_url" />
<a class="shareCount"></a>
</div>
</div>
<!-- Baidu Button END -->
</h3>
<hr align="center"/>
<h2></h2>
<h3 class="detailTitle"></h3>
<p class="detail" style="padding-bottom:0">
</p>
<p class="detail wybug_open_status">
2015-03-21 <br/>
2015-03-24 <br/>
2015-03-27 <a href="path_to_url" target="_blank"></a><a href="path_to_url" target="_blank"></a><a href="path_to_url" target="_blank"></a><br/>
2015-05-18 <br/>
2015-05-28 <br/>
2015-06-07 <br/>
2015-06-22 <br/>
</p>
<h3 class="detailTitle"></h3>
<p class="detail wybug_description"><br />
rank</p>
<h3 class="detailTitle"></h3>
<div class='wybug_detail'>
<p class="detail"><br />
<br />
</p><fieldset class='fieldset fieldset-code'><legend>code </legend><pre><code>path_to_url class='detail'><br />
<br />
<br />
<br />
/esbclient/layout/make.php<br />
<br />
<br />
<br />
</p><fieldset class='fieldset fieldset-code'><legend>code </legend><pre><code><?php <br />
$_POST ['code'] = html_entity_decode ( stripslashes ( ($_POST ['code']) ) ); //\html<br />
file_put_contents('content.php',$_POST['code']);<br />
?></code></pre></fieldset><p class='detail'><br />
<br />
file_put_contents...<br />
<br />
<br />
<br />
<br />
<br />
path_to_url />
<br />
POSTcode=<?php $wexiaoma;?><br />
<br />
content.php<br />
<br />
</p>
</div>
<h3 class="detailTitle"></h3>
<div class='wybug_poc'>
<p class="detail"></p><p class="detail usemasaic"><a href="../upload/201503/191059200f32d4ff38ee020ba153292a68dab1fb.png" target="_blank"><img src="../upload/201503/191059200f32d4ff38ee020ba153292a68dab1fb.png" alt="1.png" width="600" onerror="javascript:errimg(this);"/></a></p><p class="detail"> </p>
</div>
<h3 class="detailTitle"></h3>
<div class='wybug_patch'>
<p class="detail"> </p>
</div>
<h3 class="detailTitle"> <a style="font-weight:normal" href="path_to_url" title=""></a>@<a style="font-weight:normal" href="path_to_url" title="CMS500"></a></h3>
<hr align="center"/>
<h2 id="bugreply"></h2>
<div class='bug_result'>
<h3 class="detailTitle"></h3>
<p class="detail"></p>
<p class="detail">Rank11 </p>
<p class="detail">2015-03-24 08:30</p>
<h3 class="detailTitle"></h3>
<p class="detail">CNVD,CNVD,.</p>
<h3 class="detailTitle"></h3>
<p class="detail"></p>
</div>
<hr align="center" />
<script type="text/javascript">
var bugid="102271";
var bugRating="-3";
var myRating="";
var ratingCount="0";
function ShowBugRating(k){
var ratingItems=$(".myrating span");
$.each(ratingItems,function(i,n){
var nk=parseInt($(n).attr("rel"));
if(nk<=k){
$(n).addClass("on");
}else{
$(n).removeClass("on");
}
});
$(".myrating span").hover(
function(){
$("#ratingShow").html($(this).attr("data-title"));
},
function(){
$("#ratingShow").html("");
}
);
}
$(document).ready(function(){
if(myRating==""){
var ratingItems=$(".myrating span");
$(".myrating span").hover(
function(){
$(this).addClass("hover");
var k=parseInt($(this).attr("rel"));
$.each(ratingItems,function(i,n){
var nk=parseInt($(n).attr("rel"));
if(nk<k) $(n).addClass("on");
if(nk>k) $(n).removeClass("on");
});
$("#ratingShow").html($(this).attr("data-title"));
},
function(){
$(this).removeClass("hover");
if($("#myRating").val()==""){
$.each(ratingItems,function(i,n){
$(n).removeClass("on");
});
}
$("#ratingShow").html("");
}
);
$(".myrating span").click(function(){
var rating=$(this).attr("rel");
var k=parseInt($(this).attr("rel"));
$.post("/ajaxdo.php?module=bugrating",{"id":bugid,"rating":rating,"token":$("#token").val()},function(re){
//
$(".myrating span").unbind();
re=parseInt(re);
switch(re){
case 1:
$("#ratingShow").html(_LANGJS.RATING_SUCCESS);
$("#ratingSpan").html(parseInt($("#ratingSpan").html())+1);
$.each(ratingItems,function(i,n){
var nk=parseInt($(n).attr("rel"));
if(nk<=k){
$(n).addClass("on");
}else{
$(n).removeClass("on");
}
});
ShowBugRating(rating);
break;
case 2:
$("#ratingShow").html(_LANGJS.LOGIN_FIRST);
break;
case 4:
$("#ratingShow").html(_LANGJS.RATING_BUGS_DONE);
break;
case 6:
$("#ratingShow").html(_LANGJS.RATING_BUGS_SELF);
break;
default:break;
}
});
});
}else{
if(ratingCount>2){
ShowBugRating(bugRating);
}else{
ShowBugRating(-3);
}
}
});
</script>
<h3 class="detailTitle"></h3>
<p class="detail"></p>
<h5 class="rating">
<div class="ratingText"><span>(<span id="ratingSpan">0</span>)</span>:</div>
<div class="myrating">
<span rel="-2" data-title=""></span>
<span rel="-1" data-title=""></span>
<span rel="0" data-title=""></span>
<span rel="1" data-title=""></span>
<span rel="2" data-title=""></span>
<div id="ratingShow">
</div>
</div>
</h5>
<input type="hidden" id="myRating" value="" />
<hr align="center" />
<h2></h2>
<div id="replys" class="replys">
<ol class="replylist">
<li class="reply clearfix">
<div class="reply-content">
<div class="reply-info">
<span class="addtime">2015-03-19 11:11</span> |
<a target='_blank' href="path_to_url"></a> <!-- @zm 2013-12-13 Begin -->
( | <!-- @zm 2013-12-13 End -->
Rank:121 :44 | ~~~~ ......)
<div class="likebox">
<span class="likepre" title="" rel="137076"></span>
<span class="liketext liketext_min"><span id="likenum_137076">0</span></span>
<span class="likesuf"></span>
</div>
</div><!-- reply-info End -->
<div class="description">
<p> </p>
</div>
<div class="replylist-act">
<span class="floor">1#</span>
<a title=" " href="javascript:void(0)" class="replyBtn" onclick="Reply('')"></a>
</div>
</div><!-- reply-content End -->
</li>
<li class="reply clearfix">
<div class="reply-content">
<div class="reply-info">
<span class="addtime">2015-03-19 11:36</span> |
<a target='_blank' href="path_to_url">zhxs</a> <!-- @zm 2013-12-13 Begin -->
( | <!-- @zm 2013-12-13 End -->
Rank:69 :26 | ...)
<div class="likebox">
<span class="likepre" title="" rel="137081"></span>
<span class="liketext liketext_min"><span id="likenum_137081">0</span></span>
<span class="likesuf"></span>
</div>
</div><!-- reply-info End -->
<div class="description">
<p> </p>
</div>
<div class="replylist-act">
<span class="floor">2#</span>
<a title=" zhxs" href="javascript:void(0)" class="replyBtn" onclick="Reply('zhxs')"></a>
</div>
</div><!-- reply-content End -->
</li>
<li class="reply clearfix">
<div class="reply-content">
<div class="reply-info">
<span class="addtime">2015-03-19 11:37</span> |
<a target='_blank' href="path_to_url"></a> <!-- @zm 2013-12-13 Begin -->
( | <!-- @zm 2013-12-13 End -->
Rank:273 :34 | ~)
<div class="likebox">
<span class="likepre" title="" rel="137082"></span>
<span class="liketext liketext_min"><span id="likenum_137082">0</span></span>
<span class="likesuf"></span>
</div>
</div><!-- reply-info End -->
<div class="description">
<p> </p>
</div>
<div class="replylist-act">
<span class="floor">3#</span>
<a title=" " href="javascript:void(0)" class="replyBtn" onclick="Reply('')"></a>
</div>
</div><!-- reply-content End -->
</li>
<li class="reply clearfix">
<div class="reply-content">
<div class="reply-info">
<span class="addtime">2015-03-19 12:22</span> |
<a target='_blank' href="path_to_url"></a> <img height="12" width="12" style="vertical-align:-2px;" src="path_to_url" alt="" /> <!-- @zm 2013-12-13 Begin -->
( | <!-- @zm 2013-12-13 End -->
Rank:44 :2 | )
<div class="likebox">
<span class="likepre" title="" rel="137091"></span>
<span class="liketext liketext_min"><span id="likenum_137091">0</span></span>
<span class="likesuf"></span>
</div>
</div><!-- reply-info End -->
<div class="description">
<p> </p>
</div>
<div class="replylist-act">
<span class="floor">4#</span>
<a title=" " href="javascript:void(0)" class="replyBtn" onclick="Reply('')"></a>
</div>
</div><!-- reply-content End -->
</li>
<li class="reply clearfix">
<div class="reply-content">
<div class="reply-info">
<span class="addtime">2015-03-19 13:58</span> |
<a target='_blank' href="path_to_url">an0nym0us</a> <!-- @zm 2013-12-13 Begin -->
( | <!-- @zm 2013-12-13 End -->
Rank:18 :3 | no)
<div class="likebox">
<span class="likepre" title="" rel="137105"></span>
<span class="liketext liketext_min"><span id="likenum_137105">0</span></span>
<span class="likesuf"></span>
</div>
</div><!-- reply-info End -->
<div class="description">
<p>omg! </p>
</div>
<div class="replylist-act">
<span class="floor">5#</span>
<a title=" an0nym0us" href="javascript:void(0)" class="replyBtn" onclick="Reply('an0nym0us')"></a>
</div>
</div><!-- reply-content End -->
</li>
<li class="reply clearfix">
<div class="reply-content">
<div class="reply-info">
<span class="addtime">2015-03-19 14:08</span> |
<a target='_blank' href="path_to_url"></a> <!-- @zm 2013-12-13 Begin -->
( | <!-- @zm 2013-12-13 End -->
Rank:255 :83 | ...)
<div class="likebox">
<span class="likepre" title="" rel="137106"></span>
<span class="liketext liketext_min"><span id="likenum_137106">0</span></span>
<span class="likesuf"></span>
</div>
</div><!-- reply-info End -->
<div class="description">
<p> </p>
</div>
<div class="replylist-act">
<span class="floor">6#</span>
<a title=" " href="javascript:void(0)" class="replyBtn" onclick="Reply('')"></a>
</div>
</div><!-- reply-content End -->
</li>
<li class="reply clearfix">
<div class="reply-content">
<div class="reply-info">
<span class="addtime">2015-03-24 08:50</span> |
<a target='_blank' href="path_to_url"></a> <!-- @zm 2013-12-13 Begin -->
( | <!-- @zm 2013-12-13 End -->
Rank:63 :10 | ...)
<div class="likebox">
<span class="likepre" title="" rel="137730"></span>
<span class="liketext liketext_min"><span id="likenum_137730">0</span></span>
<span class="likesuf"></span>
</div>
</div><!-- reply-info End -->
<div class="description">
<p> </p>
</div>
<div class="replylist-act">
<span class="floor">7#</span>
<a title=" " href="javascript:void(0)" class="replyBtn" onclick="Reply('')"></a>
</div>
</div><!-- reply-content End -->
</li>
<li class="reply clearfix">
<div class="reply-content">
<div class="reply-info">
<span class="addtime">2015-03-26 13:20</span> |
<a target='_blank' href="path_to_url">me1ody</a> <!-- @zm 2013-12-13 Begin -->
( | <!-- @zm 2013-12-13 End -->
Rank:121 :35 | )
<div class="likebox">
<span class="likepre" title="" rel="138134"></span>
<span class="liketext liketext_min"><span id="likenum_138134">0</span></span>
<span class="likesuf"></span>
</div>
</div><!-- reply-info End -->
<div class="description">
<p> </p>
</div>
<div class="replylist-act">
<span class="floor">8#</span>
<a title=" me1ody" href="javascript:void(0)" class="replyBtn" onclick="Reply('me1ody')"></a>
</div>
</div><!-- reply-content End -->
</li>
</ol><!-- replylist End -->
</div><!-- replys End -->
<div id="reply" class="reply">
<a name="comment"></a>
<p class="detail">
<a href="path_to_url"><u></u></a>
</p>
<script type="text/javascript">
var masaic = '0';
function CommentLike(id){
$.post("/ajaxdo.php?module=commentrating",{"id":id,"token":$("#token").val()},function(re){
re=parseInt(re);
switch(re){
case 1:
$("#likenum_"+id).html(parseInt($("#likenum_"+id).html())+1);
break;
case 4:
alert(_LANGJS.COMMENT_GOOD_DONE);
break;
case 6:
alert(_LANGJS.COMMENT_SELF);
break;
default:break;
}
});
}
$(document).ready(function(){
$(".likebox .likepre").click(function(){
CommentLike($(this).attr("rel"));
});
});
</script>
<div>
</div>
<div id="footer">
<span class="copyright fleft">
<a href="path_to_url">ICP15041338-1</a>
<!--a href="path_to_url" target="_blank"><img src="/images/sae_bottom_logo.png" title="Powered by Sina App Engine"></a-->
</span>
<span class="other fright">
<a href="path_to_url"></a>
<a href="path_to_url"></a>
<a href="path_to_url"></a>
<a href="path_to_url"></a>
<a href="path_to_url"></a>
</span>
</div>
<script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fc12f88b5c1cd041a732dea597a5ec94c' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript" id="bdshare_js" data="type=button" ></script>
<script type="text/javascript" id="bdshell_js"></script>
<script type="text/javascript">
document.getElementById("bdshell_js").src = "path_to_url" + new Date().getHours();
if (top.location !== self.location) top.location=self.location;
</script>
</body>
</html>
```
|
```yaml
version: "2.0"
intents:
- greet
- goodbye
responses:
utter_greet:
- text: "Hey! How are you?"
utter_chatter:
- text: "Lovely weather today, isn't it?"
```
|
Lorenzo Ghiberti (, , ; 1378 – 1 December 1455), born Lorenzo di Bartolo, was an Italian Renaissance sculptor from Florence, a key figure in the Early Renaissance, best known as the creator of two sets of bronze doors of the Florence Baptistery, the later one called by Michelangelo the Gates of Paradise. Trained as a goldsmith and sculptor, he established an important workshop for sculpture in metal. His book of Commentarii contains important writing on art, as well as what may be the earliest surviving autobiography by any artist.
Ghiberti's career was dominated by his two successive commissions for pairs of bronze doors to the Florence Baptistery (Battistero di San Giovanni). They are recognized as a major masterpiece of the Early Renaissance, and were famous and influential from their unveiling.
Early life
Ghiberti was born in 1378 in Pelago, a comune 20 km from Florence. It is said that Lorenzo was the son of Cione di Ser Buonaccorso Ghiberti and Fiore Ghiberti. However, there is some doubt about whether Cione was Ghiberti's actual father. At some point in their marriage, Fiore went to Florence and lived with a goldsmith by the name of Bartolo di Michele. Fiore and Bartolo maintained a common law marriage, so it is unknown who Ghiberti's biological father was. There is no documentation of Cione's death, but it is known that after his passing Fiore and Bartolo married in 1406. Regardless, Bartolo was the only father Lorenzo knew and they had a close and loving relationship. Bartolo was a clever and popular goldsmith in Florence, and trained Lorenzo in his trade. It was from this apprenticeship that Lorenzo learned the first principles of design.
Lorenzo was interested in many forms of art and did not confine himself to gold-working. He delighted in modeling copies of antique medals and also in painting. Lorenzo received formal training as a painter from Gherardo Starnina He then went to work in the workshop of his stepfather. When the bubonic plague struck Florence in 1400, Ghiberti moved to Rimini.
In Rimini he was fortunate enough to receive employment by Carlo I Malatesta, where he assisted in the completion of frescoes on the walls of the castle. It is believed that this is where he gained his love for the art of painting. However, shortly after his arrival he received word from his friends back in his home town of Florence that the governors of the Baptistery were holding a competition and sending for masters who were skilled in bronze working. Despite his great appreciation for painting, Ghiberti asked Malatesta for leave. In 1401 he headed back to Florence to participate in a competition that was being held for the commission to make the second pair of bronze doors for the Baptistery of the Cathedral of Florence.
Florence Baptistery doors
Ghiberti first became famous when as a 21-year-old he won the 1401 competition for the first set of bronze doors, with Brunelleschi as the runner up. The original plan was for the doors to depict scenes from the Old Testament, but the plan was changed to depict scenes from the New Testament instead. However, the trial piece, which survives, depicts the sacrifice of Isaac.
To carry out this commission, he set up a large workshop in which many artists trained, including Donatello, Masolino, Paolo Uccello, and Antonio del Pollaiuolo. When his first set of twenty-eight panels was complete, Ghiberti was commissioned to produce a second set for another doorway in the church, this time with scenes from the Old Testament, as originally intended for his first set. Instead of twenty-eight scenes, he produced ten rectangular scenes in a completely different style. These were more naturalistic, with perspective and a greater idealization of the subject. Dubbed "The Gates of Paradise" by Michelangelo, this second set remains a major monument of the age of Renaissance humanism.
The Gates of Paradise had ten panels with several episodes from a particular story from the Old Testament portrayed on each of them.
The list below shows where each story is placed on the Gates of Paradise.
Gates of Paradise multiple descriptive panels
The Story of Adam and Eve (Panel)
In the beginning of Genesis, God created the Universe (shown on the top of the image).
When he created the universe, he created “The Garden of Eden”. This is where he created the first humans Adam and Eve. Adam and Eve are eating an apple from the forbidden tree. Eve was tricked by Lucifer, God's fallen angel, the serpent from being told she would be like God if she ate the forbidden fruit (shown on left middle side).
Lucifer, his most beautiful angel, became a fallen angel and the devil (shown on the bottom left).
The Story of Cain and Abel (Panel)
Cain and Abel were the sons of Adam, the first man. Abel was younger than Cain. Out of jealousy, Cain was enraged with God preferring Abel's sacrifice over his (shown at the top of the photograph). Abel was known to be peaceful and is sitting peacefully with the herd (shown on the middle left side). Cain tricks Abel to follow him and murders him (shown on the bottom).
The Story of Noah (Panel)
God did not like how the world was full of violence. He told Noah he was going to destroy the earth with a flood and that he needed to build an Ark (shown by the waves in the photograph). He was told to bring two of each kind of animal and his family (shown on the left, right, and on the middle area). There is a Moses laying next to a barrel signifying the drunks (shown on the bottom left).
There is Moses offering a sacrifice (shown on the bottom right).
The Story of Abraham (Panel)
Three men came to Abraham. He clothed them, fed them, and gave them drinks. The three men were angels and they revealed themselves as messengers of God (shown at the bottom left). They told him his wife Sarah, who was 80 years old, would bear a child. Once they had the child God order Abraham to sacrifice Isaac, but was ordered to stop by an angel (shown at the top).
The Story of Isaac (Panel)
Isaac is the son of Abraham. He was going to be sacrificed before an angel stopped Abraham. Jacob is receiving Issac's blessing (shown on the right). Rebecca is listening to God tell her of her two sons who will have conflicts (shown on the rooftop).
The Story of Joseph (Panel)
Joseph's father's name was Jacob and they lived in Canaan. Joseph was the second youngest of 11 brothers and his father spent more time with him because of it. Jacob had given Joseph a special robe, which his brothers became envious of. Joseph had two dreams he told his brothers about one where they were all killing him and the other was where they were bowing to him. They were enraged and were planning on killing him, but sold him to slavery and being owned by Egypt (shown at the bottom right). Joseph was imprisoned and told people their meaning of their dreams. The Pharaoh sought Joseph to explain his dream. The Pharaoh told Joseph of his dreams of his city becoming low in food resources. Joseph suggest putting food aside each year for the upcoming low harvest (shown with people having plentiful food).
The Story of Moses (Panel)
Moses was hidden by his birth mother in a basket in the Nile River. The Pharaoh's daughter spotted Moses and took him from the basket (shown on the left with the river and people). Moses became a child of the Pharaoh of Egypt. He was born an Israelite and his people were enslaved by people of Egypt. The ten plagues hit Egypt and people are shown to be frightened (shown by the people on the right). Moses lead the Israelites out of Egypt to cross the Red Sea (shown on the right, people rejoicing) Moses receives the ten commandments from God on Mount Sinai (shown at the top).
The Story of Joshua (Panel)
Moses died. Joshua was now the leader of the Israelites and had to lead them to the Promised Land (shown at the bottom). God's people, to cross the Jordan River (seen in the middle of a river stream). Joshua carries the ten commandments around the city of Jericho seven times then the wall collapsed. Joshua and his army then took over the city (shown at the top). They were victorious in taking the city (shown at the top).
The Story of David (Panel)
Saul was the king of Israel. God said Saul was not the chosen king to lead God's people.
Samuel, a prophet, who was sent by God to search for a new king. David was brought back to Saul like David and had become his armor bearer and had him carry his shield. A war was between Israel and Egypt (shown throughout the photograph). Goliath promised his armies work quit if someone could kill him. David was skilled at killing beast from protecting his sheep, as a herdsman, and hit Goliath with a rock and killed him with his own sword (shown at the bottom of the photograph).
The Story of King Solomon (Panel)
King Solomon made an alliance with the Pharaoh king of Egypt and married his daughter (shown in the middle).
God Solomon any wish. Solomon asked God to become a better leader and God rewarded him with wisdom. People acknowledged Solomon as a good and wise king (shown with the rejoiceful crowd). Two prostitutes came to the king. They both had a baby. One of the babies died. The mother of the dead baby claimed that the live baby was hers. Both women swore the live baby was theirs. King Solomon ordered the baby to be cut in half so they could share the baby. Its mother cried out for mercy on her baby, while the other shamelessly submitted. Solomon rewarded the one who cried out, since he believed she was truly the mother (shown on the middle left side, behind his wife).
Earlier doors by Andrea Pisano
As recommended by Giotto, Andrea Pisano was awarded the commission to design the first set of doors at the Florence Baptistery in 1329. The south doors were originally installed on the east side facing the Duomo, and were transferred to their present location in 1452. These proto-Renaissance doors consist of 28 quatrefoil panels, with the twenty top panels depicting scenes from the life of St. John the Baptist. The eight lower panels depict eight virtues: hope, faith, charity, humility, fortitude, temperance, justice, and prudence. Pisano took six years to complete them, finishing in 1336. In 1453, Ghiberti and his son Vittorio were commissioned to add a door case to Pisano's existing panels. Ghiberti died in 1455, eight years before the frame was finished leaving a majority of the work to Vittorio and other members of his workshop. There is a Latin inscription on top of the door: "Andreas Ugolini Nini de Pisis me fecit A.D. MCCCXXX" (Andrea Pisano made me in 1330). The South Doors were undergoing restoration during September, 2016.
1401 competition
In 1401, the Arte di Calimala (Cloth Importers Guild) announced a competition to design doors that eventually would be placed on the north side of the baptistry. The original location for these doors was the east side of the baptistry, but the doors were moved to the north side of the baptistry after Ghiberti completed his second commission, known as the "Gates of Paradise".
These new doors would serve as a votive offering to celebrate Florence being spared from relatively recent scourges such as the Black Death in 1348. Each participant was given four tables of brass, and was required to make a relief of the “Sacrifice of Isaac” on a piece of metal that was the size and shape of the door panels. Each artist was given a year to prepare their panel, and the artist who was judged the best was to be given the commission. While many artists competed for this commission the jury selected only seven semifinalists which included Ghiberti, Filippo Brunelleschi, Simone da Colle, Francesco di Val d’Ombrino, Niccolo d’ Arezzo, Jacopo della Quercia da Siena, and Niccolo Lamberti. In 1402 at the time of judging, only Ghiberti and Brunelleschi were finalists, and when the judges could not decide, they were assigned to work together on them. Brunelleschi's pride got in the way, and he went to Rome to study architecture, thereby leaving the then 21-year-old Ghiberti to work on the doors himself. Ghiberti's autobiography, however, claimed that he had won, "without a single dissenting voice." The original designs of The Sacrifice of Isaac by Ghiberti and Brunelleschi are on display in the museum of the Bargello in Florence. Differences between the Sacrifice of Isaac created by Brunelleschi and Ghiberti include the way that the panel was constructed and the overall efficiency of the panel. Brunelleschi's panel consisted of individual pieces of the figures of the artwork being placed onto the bronze framework. In contrast to Brunelleschi's method of creating the artwork on his panel, Ghiberti's casting of the art had all of the figures, with the exception of Isaac, created as one piece. The pieces of the figures themselves were all hollowed out on the inside. Due to the methods of how Ghiberti made the panel, it ended up being stronger, used less bronze, and had less weight than Brunelleschi's panel. By using less bronze, the panels were also more cost efficient. Including the aspect of the art itself, these differences were included on how the council of the competition decided on the victor.
After the competition
After the competition, Ghiberti's father Bartolo assisted him greatly in perfecting the design of his door before it was cast. This commission brought immediate and lasting recognition to the young artist. In 1403 the formal contract was signed with Bartolo di Michele's workshop, the same workshop he had previously been trained in, and overnight it became the most prestigious in Florence. Four years later in 1407, Lorenzo legally took over the commission and was prohibited from accepting additional commissions. He devoted much of his time to creating the gates, and was paid two-hundred florins a year for his work. To cast the doors, Lorenzo worked in a studio named the Aja or Threshing floor. The studio was located near the Hospital of Saint. Maria Nuova, the oldest hospital that is still active in Florence today. At the Aja, Ghiberti built a large furnace to melt his metal in an attempt to cast the doors, however his first model was a failure. After this trial, he attempted once more to make a mold. On his second try he was successful and ended up using 34,000 pounds of bronze, costing a total of 22,000 ducats. This was a large sum in this time period.
It took Ghiberti 21 years to complete the doors. These gilded bronze doors consist of twenty-eight panels, with twenty panels depicting the life of Christ from the New Testament, and on April 19, 1424 they were placed on the side of the Baptistery. Twenty panels showing the life of Christ from the New Testament are depicted: the Annunciation, Nativity, Adoration of the Magi, Dispute with the Doctors, Baptism of Christ, Temptation of Christ, Chasing the Merchants Away, Christ Walking on Water, Transfiguration, Resurrection of Lazarus, Christ’s Arrival in Jerusalem, Last Supper, Agony in the Garden, Christ Being Captured, Flagellation, Christ on Trial with Pilate, Trip to Calvary, Crucifixion, Resurrection, and Pentecost. The eight lower panels show the four evangelists and the Church Fathers: Saint Ambrose, Saint Jerome, Saint Gregory and Saint Augustine. The panels are surrounded by a framework of foliage in the door case and gilded busts of prophets and sibyls at the intersections of the panels. Originally installed on the east side in place of Pisano's doors, they were later moved to the north side. They are described by the art historian Antonio Paolucci as "the most important event in the history of Florentine art in the first quarter of the fifteenth century".
The bronze statues over the northern gate depict John the Baptist preaching to a Pharisee and Sadducee and were sculpted by Francesco Rustici. Rustici may have been aided in his design by Leonardo da Vinci, who assisted him in the choice of his tools.
After completion of the doors
After the completion of these doors, Ghiberti was widely recognized as a celebrity and the top artist in this field. He was given many commissions, including some from the pope. In 1425 he got a second commission for the Florence Baptistery, this time for the east doors, on which he and his workshop (including Michelozzo and Benozzo Gozzoli) toiled for 27 years, excelling themselves. The subjects of the designs for the doors were chosen by Leonardo Bruni d'Arezzo, then chancellor of the Republic of Florence. They have ten panels depicting scenes from the Old Testament, and were in turn installed on the east side. The panels are large rectangles and were no longer embedded in the traditional Gothic quatrefoil, as in the previous doors. Ghiberti employed the recently discovered principles of perspective to give depth to his compositions. Each panel depicts more than one episode. "The Story of Joseph" portrays the narrative scheme of Joseph Cast by His Brethren into the Well, Joseph Sold to the Merchants, The merchants delivering Joseph to the pharaoh, Joseph Interpreting the Pharaoh's dream, The Pharaoh Paying him Honour, Jacob Sends His Sons to Egypt and Joseph Recognizes His Brothers and Returns Home. According to Vasari's Lives, this panel was the most difficult and also the most beautiful. The figures are distributed in very low relief in a perspective space (a technique invented by Donatello and called rilievo schiacciato, which literally means "flattened relief"). Ghiberti uses different sculptural techniques, from incised lines to almost free-standing figure sculpture within the panels, further accentuating the sense of space.
The panels are included in a richly decorated gilt framework of foliage and fruit, with many statuettes of prophets and 24 busts. The two central busts are portraits of the artist and of his father, Bartolomeo Ghiberti.
The Annunciation panel portrays the scene with an angel dressed in robe, wings, and a trumpet appearing to Mary, which was shown in an expression of shock leaving a doorway. The Nativity panel depicts the birth of Christ with an ox, a donkey, Joseph and Mary, an angel, and the shepherds. All the characters in the panel are all depicted near a cave while all but Mary are showing reverence towards her. The Adoration of the Magi panel shows the three magi giving praise to Christ and Mary, with Joseph and angels in the background. In the Christ Among the Doctors panel, Christ is depicted as a child sitting upon a throne-like chair surrounded by the doctors in discussion with him. The narrative of the doctors being shocked of how intelligently Christ spoke is demonstrated by how all the doctors are speaking to each other in intense discussion around Christ. The Baptism of Christ panel, Christ is shown surrounded by spectators, a dove, and his cousin, John the Baptist, being baptized in a river. The background includes intensely detailed trees with leaves, rocks, and a flowing river. The Temptation of Christ panel is shown with Christ surrounded by angels while facing the fallen angel, Satan, standing upon rocks. Satan is depicted as a human with bat-like wings and robes. The Chasing the Merchants Away panel depicts the scene with by Christ pushing away a group of merchants with his fists raised inside the temple. The temple in the background is depicted by columns and arches with complex designs, the merchants are also shown holding goods while being pushed away. The Christ Walking on Water panel displays Jesus standing on water and the disciples at sea while Peter is drowning. The panel shows a ship detailed with sails shown to have the individual ropes from the mast as well as the ship itself having artistic designs. The ocean is also detailed with the waves flowing and where Jesus stands on the water, it bends down to show him standing on it. The Transfiguration panel shows Jesus standing with the prophets Moses and Elijah over his disciples Peter, James, and John. The awe of the three disciples are expressed by them being on the ground and looking away from Christ and the prophets. The Raising of Lazarus panel shows Lazarus leaving his tomb being surrounded by Christ, his sisters, and disciples. The awe of the sisters of Lazarus are shown by one of them on the ground and the other grabbing Lazarus while kneeling. The Entry into Jerusalem panel shows Christ riding upon a donkey being greeted by a large crowd with the gates of Jerusalem in the background. Each individual of the crowd has a distinct face with different hairstyles and clothes. The Last Supper panel shows the well known scene in the New Testament of Christ eating with the twelve disciples. The background is decorated grapes on the columns and drapes in the background while Christ is at the head of the table and the disciples sitting in unison. The Agony in the Garden panel shows Christ praying towards an angle and disciples sleeping behind him. The imagery of the garden is detailed with highly detailed bushes, rocks, and trees. The Christ Being Captured panel shows Christ being marked by Judas to be arrested by the Roman soldiers while disciples are struggling against the soldier. The soldiers each have individualized armor and weapons like a spear, axe, and a sword. The Flagellation panel depicts Jesus being flogged by the Roman soldiers holding rods in a swinging motion. The Crucifixion panel of the North Doors depicts the scene with Mary and John at the foot of the cross mourning with angels next to Christ hanging. Mary is shown to be in mourning with her looking down away from the cross. Although the overall quality of the casting is considered exquisite, there are some known mistakes. For example, in panel 15 of the North Doors (Flagellation) the casting of the second column in the front row has been overlaid over an arm, so that one of the flagellators appears trapped in stone, with his hand sticking out of it.
Michelangelo referred to these doors as fit to be the "Gates of Paradise" (It. Porte del Paradiso), and they are still invariably referred to by this name. Giorgio Vasari described them a century later as "undeniably perfect in every way and must rank as the finest masterpiece ever created". Ghiberti himself said they were "the most singular work that I have ever made".
The bronze statues for Orsanmichele
St. John the Baptist
The St. John The Baptist statue sits in a niche of the Orsanmichele in Florence was built from 1412–-1416. This statue based on the St. John the Baptist.
Ghiberti's masterpiece was commissioned by the Arte di Calimala guild, which was the wool merchants guild. They were one of the wealthiest in Florence.
This statue was a technological advance for its time. Ghiberti had incredible casting skill to be able to bond this 8’ 4” statue made of bronze.
Ghiberti's statue was influenced by the gothic style in Italy, shown by the elegant curves from the sword and drapery.
St. Matthew
This statue was commissioned by the Arte del Cambio, the bankers guild and executed by Ghiberti between 1419–-1423.
The Saint Matthew statue reaches a height of 8’ 10” of bronze. It is also located in a niche in the Orsanmichele in Florence.
The guild specified they wanted their statue as tall or taller than the St. John the Baptist statue.
St. Stephen
St. Stephen for the Arte della Lana (Wool Manufacturers' Guild)
Later life, family, and death
By 1417 Lorenzo Ghiberti was married to Marsila, the 16- year-old daughter of Bartolommeo di Lucca, a worthy comb-maker. Together they had two sons. In 1417 they had Tommaso Ghiberti, and a year later they had Vittorio Ghiberti. Ghiberti was wealthier than most of his contemporary artists, with his success bringing him great financial rewards. A surviving tax return of 1427 shows and he owned a considerable amount of land in, and outside of Florence. He also had a substantial amount of money invested in government bonds to his credit. Over the years, his real estate and monetary holdings continued to grow. Lorenzo Ghiberti lived to be seventy-five years old, and succumbed to a fever and died in Florence. He was buried on December 1, 1455, in Santa Croce. Vittorio followed in his father's footsteps as a goldsmith and bronze-caster, but never rose to great fame. Tommaso did join his father's business, helping as a collaborator with Lorenzo's assistants. After his father's death it is unknown if he continued in the business, as he is not mentioned in any of the documents after 1447. Later, Vittorio had a son in which he named Buonaccorso who followed the paternal art. However, Buonaccorso had a different spin on his grandfather's work, with his metal castings taking the form of artillery and cannonballs. His manufacture of these weapons made him famous, mainly for supplying the wars of Sarzana and Pisa.
Other works
He was also a collector of classical artifacts and a historian. He was actively involved in the spreading of humanist ideas. His unfinished Commentarii are a valuable source of information about Renaissance art and contains what is considered the first autobiography of an artist. This work was a major source for Vasari's Vite.
Ghiberti's "Commentario" includes the earliest known surviving autobiography of an artist. He discusses the development of art from the time of Cimabue through to his own work. In describing his second bronze portal for the Florence Baptistry, he states: "In this work I sought to imitate nature as closely as possible, both in proportions and in perspective... the buildings appear as seen by the eye of one who gazes on them from a distance." The language Ghiberti used to describe his art has proved invaluable to art historians in understanding the aims Renaissance artists were striving for in their artworks.
Paolo Uccello, who was commonly regarded as the first great master of perspective, worked in Ghiberti's workshop for several years, making it difficult to determine the extent to which Uccello's innovations in perspective were due to Ghiberti's instruction. Donatello, known for one of the first examples of central-point perspective in sculpture, also worked briefly in Ghiberti's workshop. It was also about this time that Paolo began his lifelong friendship with Donatello. In about 1413 one of Ghiberti's contemporaries, Filippo Brunelleschi, demonstrated the geometrical method of perspective used today by artists, by painting the outlines of various Florentine buildings onto a mirror. When the building's outline was continued, he noticed that all of the lines converged on the horizon line.
Recent scholarship indicates that in his work on perspective, Ghiberti was influenced by the Arab polymath Alhazen who had written about the optical basis of perspective in the early eleventh century. His Book of Optics was translated into Italian in the fourteenth century as Deli Aspecti, and was quoted at length in Ghiberti's "Commentario terzo." Author A. Mark Smith suggests that, through Ghiberti, Alhazen's Book of Optics "may well have been central to the development of artificial perspective in early Renaissance Italian painting."
Gallery
References
Sullivan, Mary Ann. “Gates of Paradise, Florence Baptistry.” Images of the Gates of Paradise by Ghiberti, Florence Baptistry, Florence, Italy. Digital Imaging Project: Art Historical Images of European and North American Architecture and Sculpture from Classical Greek to Post-Modern. Scanned from Slides Taken on Site by Mary Ann Sullivan, Bluffton College.
External links
Catholic Encyclopedia article
Golden Oldies With a New Sparkle, Review by Roberta Smith in the New York Times
Images of the Gates of Paradise by Ghiberti, Bluffton University.
Italian Renaissance sculptors
Italian Roman Catholics
Sculptors from Florence
Italian goldsmiths
1378 births
1455 deaths
Artist authors
Italian male sculptors
15th-century people from the Republic of Florence
Burials at Basilica of Santa Croce, Florence
15th-century Italian sculptors
Catholic sculptors
|
```c++
//////////////////////////////////////////////////////////////////////////////
//
// (See accompanying file LICENSE_1_0.txt or copy at
// path_to_url
//
// See path_to_url for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <cstdlib> //std::srand
#include <iostream> //std::cout
#include <boost/config.hpp>
#include <boost/move/unique_ptr.hpp>
#include <boost/container/vector.hpp>
#include "order_type.hpp"
#include "random_shuffle.hpp"
#include <boost/move/algo/adaptive_sort.hpp>
#include <boost/move/core.hpp>
template<class T>
bool test_random_shuffled(std::size_t const element_count, std::size_t const num_keys, std::size_t const num_iter)
{
boost::movelib::unique_ptr<T[]> elements(new T[element_count]);
boost::movelib::unique_ptr<std::size_t[]> key_reps(new std::size_t[num_keys ? num_keys : element_count]);
std::cout << "- - N: " << element_count << ", Keys: " << num_keys << ", It: " << num_iter << " \n";
//Initialize keys
for(std::size_t i=0; i < element_count; ++i){
std::size_t key = num_keys ? (i % num_keys) : i;
elements[i].key=key;
}
std::srand(0);
for (std::size_t i = 0; i != num_iter; ++i)
{
::random_shuffle(elements.get(), elements.get() + element_count);
for(std::size_t i = 0; i < (num_keys ? num_keys : element_count); ++i){
key_reps[i]=0;
}
for(std::size_t i = 0; i < element_count; ++i){
elements[i].val = key_reps[elements[i].key]++;
}
boost::movelib::adaptive_sort(elements.get(), elements.get()+element_count, order_type_less());
if (!is_order_type_ordered(elements.get(), element_count))
{
std::cout << "\n ERROR\n";
throw int(0);
}
}
return true;
}
int main()
{
const std::size_t NIter = 100;
test_random_shuffled<order_move_type>(10001, 3, NIter);
test_random_shuffled<order_move_type>(10001, 65, NIter);
test_random_shuffled<order_move_type>(10001, 101, NIter);
test_random_shuffled<order_move_type>(10001, 1023, NIter);
test_random_shuffled<order_move_type>(10001, 4095, NIter);
test_random_shuffled<order_move_type>(10001, 0, NIter);
return 0;
}
```
|
```sqlpl
posts: select * from Post where p_cid=?;
public_posts: select * from Post WHERE Post.p_private=0 and p_cid=?;
private_posts: select * from Post WHERE Post.p_private=1 and p_cid=?;
tas: select * from Role WHERE r_role = 1 and r_cid=?;
ta_posts: select * from Post WHERE Post.p_author in (select r_uid from Role WHERE Role.r_role=1) and p_cid=?;
enrolled_in: select r_cid from Role where r_uid=?;
enrolled_students: select r_uid from Role where r_cid=?;
-- vote_count: select postId, COUNT(userId) AS votes FROM Vote GROUP BY postId;
```
|
```c
/*
* Parse a string block size specification. This is approximately a
* subset of the block size specs supported by GNU fileutils:
* "nk" = n kilobytes
* "nM" = n megabytes
* "nG" = n gigabytes
* All numbers are decimal, and suffixes refer to powers of two.
* Case-insensitive.
*/
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include "defs.h"
#include "misc.h"
unsigned long parse_blocksize(const char *bs)
{
char *suf;
unsigned long r = strtoul(bs, &suf, 10);
if (*suf != '\0') {
while (*suf && isspace((unsigned char)*suf)) suf++;
switch (*suf) {
case 'k': case 'K':
r *= 1024ul;
break;
case 'm': case 'M':
r *= 1024ul * 1024ul;
break;
case 'g': case 'G':
r *= 1024ul * 1024ul * 1024ul;
break;
case '\0':
default:
break;
}
}
return r;
}
```
|
```forth
*> \brief \b SSYR
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* path_to_url
*
* Definition:
* ===========
*
* SUBROUTINE SSYR(UPLO,N,ALPHA,X,INCX,A,LDA)
*
* .. Scalar Arguments ..
* REAL ALPHA
* INTEGER INCX,LDA,N
* CHARACTER UPLO
* ..
* .. Array Arguments ..
* REAL A(LDA,*),X(*)
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> SSYR performs the symmetric rank 1 operation
*>
*> A := alpha*x*x**T + A,
*>
*> where alpha is a real scalar, x is an n element vector and A is an
*> n by n symmetric matrix.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] UPLO
*> \verbatim
*> UPLO is CHARACTER*1
*> On entry, UPLO specifies whether the upper or lower
*> triangular part of the array A is to be referenced as
*> follows:
*>
*> UPLO = 'U' or 'u' Only the upper triangular part of A
*> is to be referenced.
*>
*> UPLO = 'L' or 'l' Only the lower triangular part of A
*> is to be referenced.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> On entry, N specifies the order of the matrix A.
*> N must be at least zero.
*> \endverbatim
*>
*> \param[in] ALPHA
*> \verbatim
*> ALPHA is REAL
*> On entry, ALPHA specifies the scalar alpha.
*> \endverbatim
*>
*> \param[in] X
*> \verbatim
*> X is REAL array, dimension at least
*> ( 1 + ( n - 1 )*abs( INCX ) ).
*> Before entry, the incremented array X must contain the n
*> element vector x.
*> \endverbatim
*>
*> \param[in] INCX
*> \verbatim
*> INCX is INTEGER
*> On entry, INCX specifies the increment for the elements of
*> X. INCX must not be zero.
*> \endverbatim
*>
*> \param[in,out] A
*> \verbatim
*> A is REAL array, dimension ( LDA, N )
*> Before entry with UPLO = 'U' or 'u', the leading n by n
*> upper triangular part of the array A must contain the upper
*> triangular part of the symmetric matrix and the strictly
*> lower triangular part of A is not referenced. On exit, the
*> upper triangular part of the array A is overwritten by the
*> upper triangular part of the updated matrix.
*> Before entry with UPLO = 'L' or 'l', the leading n by n
*> lower triangular part of the array A must contain the lower
*> triangular part of the symmetric matrix and the strictly
*> upper triangular part of A is not referenced. On exit, the
*> lower triangular part of the array A is overwritten by the
*> lower triangular part of the updated matrix.
*> \endverbatim
*>
*> \param[in] LDA
*> \verbatim
*> LDA is INTEGER
*> On entry, LDA specifies the first dimension of A as declared
*> in the calling (sub) program. LDA must be at least
*> max( 1, n ).
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \ingroup her
*
*> \par Further Details:
* =====================
*>
*> \verbatim
*>
*> Level 2 Blas routine.
*>
*> -- Written on 22-October-1986.
*> Jack Dongarra, Argonne National Lab.
*> Jeremy Du Croz, Nag Central Office.
*> Sven Hammarling, Nag Central Office.
*> Richard Hanson, Sandia National Labs.
*> \endverbatim
*>
* =====================================================================
SUBROUTINE SSYR(UPLO,N,ALPHA,X,INCX,A,LDA)
*
* -- Reference BLAS level2 routine --
* -- Reference BLAS is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
*
* .. Scalar Arguments ..
REAL ALPHA
INTEGER INCX,LDA,N
CHARACTER UPLO
* ..
* .. Array Arguments ..
REAL A(LDA,*),X(*)
* ..
*
* =====================================================================
*
* .. Parameters ..
REAL ZERO
PARAMETER (ZERO=0.0E+0)
* ..
* .. Local Scalars ..
REAL TEMP
INTEGER I,INFO,IX,J,JX,KX
* ..
* .. External Functions ..
LOGICAL LSAME
EXTERNAL LSAME
* ..
* .. External Subroutines ..
EXTERNAL XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC MAX
* ..
*
* Test the input parameters.
*
INFO = 0
IF (.NOT.LSAME(UPLO,'U') .AND. .NOT.LSAME(UPLO,'L')) THEN
INFO = 1
ELSE IF (N.LT.0) THEN
INFO = 2
ELSE IF (INCX.EQ.0) THEN
INFO = 5
ELSE IF (LDA.LT.MAX(1,N)) THEN
INFO = 7
END IF
IF (INFO.NE.0) THEN
CALL XERBLA('SSYR ',INFO)
RETURN
END IF
*
* Quick return if possible.
*
IF ((N.EQ.0) .OR. (ALPHA.EQ.ZERO)) RETURN
*
* Set the start point in X if the increment is not unity.
*
IF (INCX.LE.0) THEN
KX = 1 - (N-1)*INCX
ELSE IF (INCX.NE.1) THEN
KX = 1
END IF
*
* Start the operations. In this version the elements of A are
* accessed sequentially with one pass through the triangular part
* of A.
*
IF (LSAME(UPLO,'U')) THEN
*
* Form A when A is stored in upper triangle.
*
IF (INCX.EQ.1) THEN
DO 20 J = 1,N
IF (X(J).NE.ZERO) THEN
TEMP = ALPHA*X(J)
DO 10 I = 1,J
A(I,J) = A(I,J) + X(I)*TEMP
10 CONTINUE
END IF
20 CONTINUE
ELSE
JX = KX
DO 40 J = 1,N
IF (X(JX).NE.ZERO) THEN
TEMP = ALPHA*X(JX)
IX = KX
DO 30 I = 1,J
A(I,J) = A(I,J) + X(IX)*TEMP
IX = IX + INCX
30 CONTINUE
END IF
JX = JX + INCX
40 CONTINUE
END IF
ELSE
*
* Form A when A is stored in lower triangle.
*
IF (INCX.EQ.1) THEN
DO 60 J = 1,N
IF (X(J).NE.ZERO) THEN
TEMP = ALPHA*X(J)
DO 50 I = J,N
A(I,J) = A(I,J) + X(I)*TEMP
50 CONTINUE
END IF
60 CONTINUE
ELSE
JX = KX
DO 80 J = 1,N
IF (X(JX).NE.ZERO) THEN
TEMP = ALPHA*X(JX)
IX = JX
DO 70 I = J,N
A(I,J) = A(I,J) + X(IX)*TEMP
IX = IX + INCX
70 CONTINUE
END IF
JX = JX + INCX
80 CONTINUE
END IF
END IF
*
RETURN
*
* End of SSYR
*
END
```
|
Shergarh is a village in Shivgarh block of Rae Bareli district, Uttar Pradesh, India. As of 2011, its population is 548, in 111 households. It has no schools and no healthcare facilities. It is located 11 km from Maharajganj, the tehsil headquarters. The main staple foods are wheat and rice.
The 1961 census recorded Shergarh as comprising 3 hamlets, with a total population of 294 people (161 male and 133 female), in 58 households and 53 physical houses. The area of the village was given as 203 acres.
The 1981 census recorded Shergarh as having a population of 333 people, in 74 households, and having an area of 82.15 hectares.
References
Villages in Raebareli district
|
```java
@ExportPackage
@PublicApi
package com.yahoo.search.query.context;
import com.yahoo.api.annotations.PublicApi;
import com.yahoo.osgi.annotation.ExportPackage;
```
|
James Bird (c. 1773 – 18 October 1856) was a Hudson's Bay Company fur trader. He was born in England and came to Canada in 1788.
Bird made steady progress within the company serving his apprenticeship in York Factory and then moving on to more westerly posts which he first visited with the HBC inland master, William Tomison. They included Cumberland House, Saskatchewan and Buckingham House in Alberta.
Bird was named chief factor of the Lower Red River district in 1821. He had a period previously as the acting HBC governor of Rupert’s Land.
At the end of his career, he was an important figure with the company in the Red River Colony. It was there he married his last wife, having had one or more previous wives according to the custom of the country. He retired there and had a large property at what is now Birds Hill which was named after him.
His last son, Curtis James Bird, inherited this property and became a prominent part of the larger community. His third son, James Bird (Jimmy Jock) had a long career as a free trader and sometimes company employee.
References
James Curtis Bird - Manitoba Historical Society
1773 births
1856 deaths
Canadian fur traders
Hudson's Bay Company people
|
The 1946 Oklahoma gubernatorial election was held on November 5, 1946, and was a race for Governor of Oklahoma. Democrat Roy J. Turner defeated Republican Olney F. Flynn and three Independents, Mickey Harrell, R. M. Funk, and Bruno Miller. Dixie Gilmer unsuccessfully sought the Democratic nomination.
Results
References
1946
Gubernatorial
Okla
|
```c
/*
*
*/
#include <zephyr/arch/arm64/arm-smccc.h>
#include <zephyr/drivers/tee.h>
#include <zephyr/logging/log.h>
#include <zephyr/sys/bitarray.h>
#include <zephyr/sys/dlist.h>
#include "optee_msg.h"
#include "optee_rpc_cmd.h"
#include "optee_smc.h"
LOG_MODULE_REGISTER(optee);
#define DT_DRV_COMPAT linaro_optee_tz
/* amount of physical addresses that can be stored in one page */
#define OPTEE_NUMBER_OF_ADDR_PER_PAGE (OPTEE_MSG_NONCONTIG_PAGE_SIZE / sizeof(uint64_t))
/*
* TEE Implementation ID
*/
#define TEE_IMPL_ID_OPTEE 1
/*
* OP-TEE specific capabilities
*/
#define TEE_OPTEE_CAP_TZ BIT(0)
struct optee_rpc_param {
uint32_t a0;
uint32_t a1;
uint32_t a2;
uint32_t a3;
uint32_t a4;
uint32_t a5;
uint32_t a6;
uint32_t a7;
};
typedef void (*smc_call_t)(unsigned long a0, unsigned long a1, unsigned long a2, unsigned long a3,
unsigned long a4, unsigned long a5, unsigned long a6, unsigned long a7,
struct arm_smccc_res *res);
struct optee_driver_config {
const char *method;
};
struct optee_notify {
sys_dnode_t node;
uint32_t key;
struct k_sem wait;
};
struct optee_supp_req {
sys_dnode_t link;
bool in_queue;
uint32_t func;
uint32_t ret;
size_t num_params;
struct tee_param *param;
struct k_sem complete;
};
struct optee_supp {
/* Serializes access to this struct */
struct k_mutex mutex;
int req_id;
sys_dlist_t reqs;
struct optee_supp_req *current;
struct k_sem reqs_c;
};
struct optee_driver_data {
smc_call_t smc_call;
sys_bitarray_t *notif_bitmap;
sys_dlist_t notif;
struct k_spinlock notif_lock;
struct optee_supp supp;
unsigned long sec_caps;
struct k_sem call_sem;
};
/* Wrapping functions so function pointer can be used */
static void optee_smccc_smc(unsigned long a0, unsigned long a1, unsigned long a2, unsigned long a3,
unsigned long a4, unsigned long a5, unsigned long a6, unsigned long a7,
struct arm_smccc_res *res)
{
arm_smccc_smc(a0, a1, a2, a3, a4, a5, a6, a7, res);
}
static void optee_smccc_hvc(unsigned long a0, unsigned long a1, unsigned long a2, unsigned long a3,
unsigned long a4, unsigned long a5, unsigned long a6, unsigned long a7,
struct arm_smccc_res *res)
{
arm_smccc_hvc(a0, a1, a2, a3, a4, a5, a6, a7, res);
}
static int param_to_msg_param(const struct tee_param *param, unsigned int num_param,
struct optee_msg_param *msg_param)
{
int i;
const struct tee_param *tp = param;
struct optee_msg_param *mtp = msg_param;
if (!param || !msg_param) {
return -EINVAL;
}
for (i = 0; i < num_param; i++, tp++, mtp++) {
if (!tp || !mtp) {
LOG_ERR("Wrong param on %d iteration", i);
return -EINVAL;
}
switch (tp->attr) {
case TEE_PARAM_ATTR_TYPE_NONE:
mtp->attr = OPTEE_MSG_ATTR_TYPE_NONE;
memset(&mtp->u, 0, sizeof(mtp->u));
break;
case TEE_PARAM_ATTR_TYPE_VALUE_INPUT:
case TEE_PARAM_ATTR_TYPE_VALUE_OUTPUT:
case TEE_PARAM_ATTR_TYPE_VALUE_INOUT:
mtp->attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT + tp->attr -
TEE_PARAM_ATTR_TYPE_VALUE_INPUT;
mtp->u.value.a = tp->a;
mtp->u.value.b = tp->b;
mtp->u.value.c = tp->c;
break;
case TEE_PARAM_ATTR_TYPE_MEMREF_INPUT:
case TEE_PARAM_ATTR_TYPE_MEMREF_OUTPUT:
case TEE_PARAM_ATTR_TYPE_MEMREF_INOUT:
mtp->attr = OPTEE_MSG_ATTR_TYPE_RMEM_INPUT + tp->attr -
TEE_PARAM_ATTR_TYPE_MEMREF_INPUT;
mtp->u.rmem.shm_ref = tp->c;
mtp->u.rmem.size = tp->b;
mtp->u.rmem.offs = tp->a;
break;
default:
return -EINVAL;
}
}
return 0;
}
static void msg_param_to_tmp_mem(struct tee_param *p, uint32_t attr,
const struct optee_msg_param *mp)
{
struct tee_shm *shm = (struct tee_shm *)mp->u.tmem.shm_ref;
p->attr = TEE_PARAM_ATTR_TYPE_MEMREF_INPUT + attr - OPTEE_MSG_ATTR_TYPE_TMEM_INPUT;
p->b = mp->u.tmem.size;
if (!shm) {
p->a = 0;
p->c = 0;
return;
}
p->a = mp->u.tmem.buf_ptr - k_mem_phys_addr(shm->addr);
p->c = mp->u.tmem.shm_ref;
}
static int msg_param_to_param(struct tee_param *param, unsigned int num_param,
const struct optee_msg_param *msg_param)
{
int i;
struct tee_param *tp = param;
const struct optee_msg_param *mtp = msg_param;
if (!param || !msg_param) {
return -EINVAL;
}
for (i = 0; i < num_param; i++, tp++, mtp++) {
uint32_t attr = mtp->attr & OPTEE_MSG_ATTR_TYPE_MASK;
if (!tp || !mtp) {
LOG_ERR("Wrong param on %d iteration", i);
return -EINVAL;
}
switch (attr) {
case OPTEE_MSG_ATTR_TYPE_NONE:
memset(tp, 0, sizeof(*tp));
tp->attr = TEE_PARAM_ATTR_TYPE_NONE;
break;
case OPTEE_MSG_ATTR_TYPE_VALUE_INPUT:
case OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT:
case OPTEE_MSG_ATTR_TYPE_VALUE_INOUT:
tp->attr = TEE_PARAM_ATTR_TYPE_VALUE_INPUT + attr -
OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
tp->a = mtp->u.value.a;
tp->b = mtp->u.value.b;
tp->c = mtp->u.value.c;
break;
case OPTEE_MSG_ATTR_TYPE_RMEM_INPUT:
case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:
case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:
tp->attr = TEE_PARAM_ATTR_TYPE_MEMREF_INPUT + attr -
OPTEE_MSG_ATTR_TYPE_RMEM_INPUT;
tp->b = mtp->u.rmem.size;
if (!mtp->u.rmem.shm_ref) {
tp->a = 0;
tp->c = 0;
} else {
tp->a = mtp->u.rmem.offs;
tp->c = mtp->u.rmem.shm_ref;
}
break;
case OPTEE_MSG_ATTR_TYPE_TMEM_INPUT:
case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:
case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:
msg_param_to_tmp_mem(tp, attr, mtp);
break;
default:
return -EINVAL;
}
}
return 0;
}
static uint64_t regs_to_u64(uint32_t reg0, uint32_t reg1)
{
return (uint64_t)(((uint64_t)reg0 << 32) | reg1);
}
static void u64_to_regs(uint64_t val, uint32_t *reg0, uint32_t *reg1)
{
*reg0 = val >> 32;
*reg1 = val;
}
static inline bool check_param_input(struct optee_msg_arg *arg)
{
return arg->num_params == 1 &&
arg->params[0].attr == OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
}
static void *optee_construct_page_list(void *buf, uint32_t len, uint64_t *phys_buf);
static uint32_t optee_call_supp(const struct device *dev, uint32_t func, size_t num_params,
struct tee_param *param)
{
struct optee_driver_data *data = (struct optee_driver_data *)dev->data;
struct optee_supp *supp = &data->supp;
struct optee_supp_req *req;
uint32_t ret;
req = k_malloc(sizeof(*req));
if (!req) {
return TEEC_ERROR_OUT_OF_MEMORY;
}
k_sem_init(&req->complete, 0, 1);
req->func = func;
req->num_params = num_params;
req->param = param;
/* Insert the request in the request list */
k_mutex_lock(&supp->mutex, K_FOREVER);
sys_dlist_append(&supp->reqs, &req->link);
k_mutex_unlock(&supp->mutex);
/* Tell an event listener there's a new request */
k_sem_give(&supp->reqs_c);
/*
* Wait for supplicant to process and return result, once we've
* returned from k_sem_take(&req->c) successfully we have
* exclusive access again.
*/
k_sem_take(&req->complete, K_FOREVER);
ret = req->ret;
k_free(req);
return ret;
}
static int cmd_alloc_suppl(const struct device *dev, size_t sz, struct tee_shm **shm)
{
uint32_t ret;
struct tee_param param;
param.attr = TEE_PARAM_ATTR_TYPE_VALUE_INOUT;
param.a = OPTEE_RPC_SHM_TYPE_APPL;
param.b = sz;
param.c = 0;
ret = optee_call_supp(dev, OPTEE_RPC_CMD_SHM_ALLOC, 1, ¶m);
if (ret) {
return ret;
}
ret = tee_add_shm(dev, (void *)param.c, 0, param.b, 0, shm);
return ret;
}
static void cmd_free_suppl(const struct device *dev, struct tee_shm *shm)
{
struct tee_param param;
param.attr = TEE_PARAM_ATTR_TYPE_VALUE_INOUT;
param.a = OPTEE_RPC_SHM_TYPE_APPL;
param.b = (uint64_t)shm;
param.c = 0;
optee_call_supp(dev, OPTEE_RPC_CMD_SHM_FREE, 1, ¶m);
tee_rm_shm(dev, shm);
}
static void handle_cmd_alloc(const struct device *dev, struct optee_msg_arg *arg,
void **pages)
{
int rc;
struct tee_shm *shm = NULL;
void *pl;
uint64_t pl_phys_and_offset;
arg->ret_origin = TEEC_ORIGIN_COMMS;
if (!check_param_input(arg)) {
arg->ret = TEEC_ERROR_BAD_PARAMETERS;
return;
}
switch (arg->params[0].u.value.a) {
case OPTEE_RPC_SHM_TYPE_KERNEL:
/* TODO handle situation when shm was allocated statically so buffer can be reused*/
rc = tee_add_shm(dev, NULL, 0, arg->params[0].u.value.b, TEE_SHM_ALLOC, &shm);
break;
case OPTEE_RPC_SHM_TYPE_APPL:
rc = cmd_alloc_suppl(dev, arg->params[0].u.value.b, &shm);
break;
default:
arg->ret = TEEC_ERROR_BAD_PARAMETERS;
return;
}
if (rc) {
if (rc == -ENOMEM) {
arg->ret = TEEC_ERROR_OUT_OF_MEMORY;
} else {
arg->ret = TEEC_ERROR_GENERIC;
}
return;
}
pl = optee_construct_page_list(shm->addr, shm->size, &pl_phys_and_offset);
if (!pl) {
arg->ret = TEEC_ERROR_OUT_OF_MEMORY;
goto out;
}
*pages = pl;
arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT | OPTEE_MSG_ATTR_NONCONTIG;
arg->params[0].u.tmem.buf_ptr = pl_phys_and_offset;
arg->params[0].u.tmem.size = shm->size;
arg->params[0].u.tmem.shm_ref = (uint64_t)shm;
arg->ret = TEEC_SUCCESS;
return;
out:
tee_shm_free(dev, shm);
}
static void handle_cmd_free(const struct device *dev, struct optee_msg_arg *arg)
{
int rc = 0;
if (!check_param_input(arg)) {
arg->ret = TEEC_ERROR_BAD_PARAMETERS;
return;
}
switch (arg->params[0].u.value.a) {
case OPTEE_RPC_SHM_TYPE_KERNEL:
rc = tee_rm_shm(dev, (struct tee_shm *)arg->params[0].u.value.b);
break;
case OPTEE_RPC_SHM_TYPE_APPL:
cmd_free_suppl(dev, (struct tee_shm *)arg->params[0].u.value.b);
break;
default:
arg->ret = TEEC_ERROR_BAD_PARAMETERS;
return;
}
if (rc) {
arg->ret = TEEC_ERROR_OUT_OF_MEMORY;
return;
}
arg->ret = TEEC_SUCCESS;
}
static void handle_cmd_get_time(const struct device *dev, struct optee_msg_arg *arg)
{
int64_t ticks;
int64_t up_secs;
int64_t up_nsecs;
if (arg->num_params != 1 ||
(arg->params[0].attr & OPTEE_MSG_ATTR_TYPE_MASK)
!= OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT) {
arg->ret = TEEC_ERROR_BAD_PARAMETERS;
return;
}
ticks = k_uptime_ticks();
up_secs = ticks / CONFIG_SYS_CLOCK_TICKS_PER_SEC;
up_nsecs = k_ticks_to_ns_floor64(ticks - up_secs * CONFIG_SYS_CLOCK_TICKS_PER_SEC);
arg->params[0].u.value.a = up_secs;
arg->params[0].u.value.b = up_nsecs;
arg->ret = TEEC_SUCCESS;
}
/* This should be called under notif_lock */
static inline bool key_is_pending(struct optee_driver_data *data, uint32_t key)
{
struct optee_notify *iter;
SYS_DLIST_FOR_EACH_CONTAINER(&data->notif, iter, node) {
if (iter->key == key) {
k_sem_give(&iter->wait);
return true;
}
}
return false;
}
static int optee_notif_send(const struct device *dev, uint32_t key)
{
struct optee_driver_data *data = dev->data;
k_spinlock_key_t sp_key;
if (key > CONFIG_OPTEE_MAX_NOTIF) {
return -EINVAL;
}
sp_key = k_spin_lock(&data->notif_lock);
if (!key_is_pending(data, key)) {
/* If nobody is waiting for key - set bit in the bitmap */
sys_bitarray_set_bit(data->notif_bitmap, key);
}
k_spin_unlock(&data->notif_lock, sp_key);
return 0;
}
static int optee_notif_wait(const struct device *dev, uint32_t key)
{
int rc = 0;
struct optee_driver_data *data = dev->data;
struct optee_notify *entry;
k_spinlock_key_t sp_key;
int prev_val;
if (key > CONFIG_OPTEE_MAX_NOTIF)
return -EINVAL;
entry = k_malloc(sizeof(*entry));
if (!entry) {
return -ENOMEM;
}
k_sem_init(&entry->wait, 0, 1);
entry->key = key;
sp_key = k_spin_lock(&data->notif_lock);
/*
* If notif bit was set then SEND command was already received.
* Skipping wait.
*/
rc = sys_bitarray_test_and_clear_bit(data->notif_bitmap, key, &prev_val);
if (rc || prev_val) {
goto out;
}
/*
* If key is already registred, then skip.
*/
if (key_is_pending(data, key)) {
rc = -EBUSY;
goto out;
}
sys_dlist_append(&data->notif, &entry->node);
k_spin_unlock(&data->notif_lock, sp_key);
k_sem_take(&entry->wait, K_FOREVER);
sp_key = k_spin_lock(&data->notif_lock);
sys_dlist_remove(&entry->node);
out:
k_spin_unlock(&data->notif_lock, sp_key);
k_free(entry);
return rc;
}
static void handle_cmd_notify(const struct device *dev, struct optee_msg_arg *arg)
{
if (!check_param_input(arg)) {
arg->ret = TEEC_ERROR_BAD_PARAMETERS;
return;
}
switch (arg->params[0].u.value.a) {
case OPTEE_RPC_NOTIFICATION_SEND:
if (optee_notif_send(dev, arg->params[0].u.value.b)) {
goto err;
}
break;
case OPTEE_RPC_NOTIFICATION_WAIT:
if (optee_notif_wait(dev, arg->params[0].u.value.b)) {
goto err;
}
break;
default:
goto err;
}
arg->ret = TEEC_SUCCESS;
return;
err:
arg->ret = TEEC_ERROR_BAD_PARAMETERS;
}
static void handle_cmd_wait(const struct device *dev, struct optee_msg_arg *arg)
{
if (!check_param_input(arg)) {
arg->ret = TEEC_ERROR_BAD_PARAMETERS;
return;
}
k_sleep(K_MSEC(arg->params[0].u.value.a));
arg->ret = TEEC_SUCCESS;
}
static void free_shm_pages(void **pages)
{
/*
* Clean allocated pages if needed. Some function calls requires pages
* allocation which should be freed after processing new request.
* It is safe to free this list when another SHM op (e,g. another alloc
* or free) was received.
*/
if (*pages) {
k_free(*pages);
*pages = NULL;
}
}
static void handle_rpc_supp_cmd(const struct device *dev, struct optee_msg_arg *arg)
{
struct tee_param *params;
int ret;
arg->ret_origin = TEEC_ORIGIN_COMMS;
params = k_malloc(sizeof(*params) * arg->num_params);
if (!params) {
arg->ret = TEEC_ERROR_OUT_OF_MEMORY;
return;
}
ret = msg_param_to_param(params, arg->num_params, arg->params);
if (ret) {
arg->ret = TEEC_ERROR_BAD_PARAMETERS;
arg->ret_origin = TEEC_ORIGIN_COMMS;
goto out;
}
arg->ret = optee_call_supp(dev, arg->cmd, arg->num_params, params);
ret = param_to_msg_param(params, arg->num_params, arg->params);
if (ret) {
arg->ret = TEEC_ERROR_GENERIC;
arg->ret_origin = TEEC_ORIGIN_COMMS;
}
out:
k_free(params);
}
static uint32_t handle_func_rpc_call(const struct device *dev, struct tee_shm *shm,
void **pages)
{
struct optee_msg_arg *arg = shm->addr;
switch (arg->cmd) {
case OPTEE_RPC_CMD_SHM_ALLOC:
free_shm_pages(pages);
handle_cmd_alloc(dev, arg, pages);
break;
case OPTEE_RPC_CMD_SHM_FREE:
handle_cmd_free(dev, arg);
break;
case OPTEE_RPC_CMD_GET_TIME:
handle_cmd_get_time(dev, arg);
break;
case OPTEE_RPC_CMD_NOTIFICATION:
handle_cmd_notify(dev, arg);
break;
case OPTEE_RPC_CMD_SUSPEND:
handle_cmd_wait(dev, arg);
break;
case OPTEE_RPC_CMD_I2C_TRANSFER:
/* TODO: i2c transfer case is not implemented right now */
return TEEC_ERROR_NOT_IMPLEMENTED;
default:
handle_rpc_supp_cmd(dev, arg);
break;
}
return OPTEE_SMC_CALL_RETURN_FROM_RPC;
}
static void handle_rpc_call(const struct device *dev, struct optee_rpc_param *param,
void **pages)
{
struct tee_shm *shm = NULL;
uint32_t res = OPTEE_SMC_CALL_RETURN_FROM_RPC;
switch (OPTEE_SMC_RETURN_GET_RPC_FUNC(param->a0)) {
case OPTEE_SMC_RPC_FUNC_ALLOC:
if (!tee_add_shm(dev, NULL, OPTEE_MSG_NONCONTIG_PAGE_SIZE,
param->a1,
TEE_SHM_ALLOC, &shm)) {
u64_to_regs((uint64_t)k_mem_phys_addr(shm->addr), ¶m->a1, ¶m->a2);
u64_to_regs((uint64_t)shm, ¶m->a4, ¶m->a5);
} else {
param->a1 = 0;
param->a2 = 0;
param->a4 = 0;
param->a5 = 0;
}
break;
case OPTEE_SMC_RPC_FUNC_FREE:
shm = (struct tee_shm *)regs_to_u64(param->a1, param->a2);
tee_rm_shm(dev, shm);
break;
case OPTEE_SMC_RPC_FUNC_FOREIGN_INTR:
/* Foreign interrupt was raised */
break;
case OPTEE_SMC_RPC_FUNC_CMD:
shm = (struct tee_shm *)regs_to_u64(param->a1, param->a2);
res = handle_func_rpc_call(dev, shm, pages);
break;
default:
break;
}
param->a0 = res;
}
static int optee_call(const struct device *dev, struct optee_msg_arg *arg)
{
struct optee_driver_data *data = (struct optee_driver_data *)dev->data;
struct optee_rpc_param param = {
.a0 = OPTEE_SMC_CALL_WITH_ARG
};
void *pages = NULL;
u64_to_regs((uint64_t)k_mem_phys_addr(arg), ¶m.a1, ¶m.a2);
k_sem_take(&data->call_sem, K_FOREVER);
while (true) {
struct arm_smccc_res res;
data->smc_call(param.a0, param.a1, param.a2, param.a3,
param.a4, param.a5, param.a6, param.a7, &res);
if (OPTEE_SMC_RETURN_IS_RPC(res.a0)) {
param.a0 = res.a0;
param.a1 = res.a1;
param.a2 = res.a2;
param.a3 = res.a3;
handle_rpc_call(dev, ¶m, &pages);
} else {
free_shm_pages(&pages);
k_sem_give(&data->call_sem);
return res.a0 == OPTEE_SMC_RETURN_OK ? TEEC_SUCCESS :
TEEC_ERROR_BAD_PARAMETERS;
}
}
}
static int optee_get_version(const struct device *dev, struct tee_version_info *info)
{
if (!info) {
return -EINVAL;
}
/*
* TODO Version and capabilities should be requested from
* OP-TEE OS.
*/
info->impl_id = TEE_IMPL_ID_OPTEE;
info->impl_caps = TEE_OPTEE_CAP_TZ;
info->gen_caps = TEE_GEN_CAP_GP | TEE_GEN_CAP_REG_MEM;
return 0;
}
static int optee_close_session(const struct device *dev, uint32_t session_id)
{
int rc;
struct tee_shm *shm;
struct optee_msg_arg *marg;
rc = tee_add_shm(dev, NULL, OPTEE_MSG_NONCONTIG_PAGE_SIZE,
OPTEE_MSG_GET_ARG_SIZE(0),
TEE_SHM_ALLOC, &shm);
if (rc) {
LOG_ERR("Unable to get shared memory, rc = %d", rc);
return rc;
}
marg = shm->addr;
marg->num_params = 0;
marg->cmd = OPTEE_MSG_CMD_CLOSE_SESSION;
marg->session = session_id;
rc = optee_call(dev, marg);
if (tee_rm_shm(dev, shm)) {
LOG_ERR("Unable to free shared memory");
}
return rc;
}
static int optee_open_session(const struct device *dev, struct tee_open_session_arg *arg,
unsigned int num_param, struct tee_param *param,
uint32_t *session_id)
{
int rc, ret;
struct tee_shm *shm;
struct optee_msg_arg *marg;
if (!arg || !session_id) {
return -EINVAL;
}
rc = tee_add_shm(dev, NULL, OPTEE_MSG_NONCONTIG_PAGE_SIZE,
OPTEE_MSG_GET_ARG_SIZE(num_param + 2),
TEE_SHM_ALLOC, &shm);
if (rc) {
LOG_ERR("Unable to get shared memory, rc = %d", rc);
return rc;
}
marg = shm->addr;
memset(marg, 0, OPTEE_MSG_GET_ARG_SIZE(num_param + 2));
marg->num_params = num_param + 2;
marg->cmd = OPTEE_MSG_CMD_OPEN_SESSION;
marg->params[0].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT | OPTEE_MSG_ATTR_META;
marg->params[1].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT | OPTEE_MSG_ATTR_META;
memcpy(&marg->params[0].u.value, arg->uuid, sizeof(arg->uuid));
memcpy(&marg->params[1].u.value, arg->uuid, sizeof(arg->clnt_uuid));
marg->params[1].u.value.c = arg->clnt_login;
rc = param_to_msg_param(param, num_param, marg->params + 2);
if (rc) {
goto out;
}
arg->ret = optee_call(dev, marg);
if (arg->ret) {
arg->ret_origin = TEEC_ORIGIN_COMMS;
goto out;
}
rc = msg_param_to_param(param, num_param, marg->params);
if (rc) {
arg->ret = TEEC_ERROR_COMMUNICATION;
arg->ret_origin = TEEC_ORIGIN_COMMS;
/*
* Ret is needed here only to print an error. Param conversion error
* should be returned from the function.
*/
ret = optee_close_session(dev, marg->session);
if (ret) {
LOG_ERR("Unable to close session: %d", ret);
}
goto out;
}
*session_id = marg->session;
arg->ret = marg->ret;
arg->ret_origin = marg->ret_origin;
out:
ret = tee_rm_shm(dev, shm);
if (ret) {
LOG_ERR("Unable to free shared memory");
}
return (rc) ? rc : ret;
}
static int optee_cancel(const struct device *dev, uint32_t session_id, uint32_t cancel_id)
{
int rc;
struct tee_shm *shm;
struct optee_msg_arg *marg;
rc = tee_add_shm(dev, NULL, OPTEE_MSG_NONCONTIG_PAGE_SIZE,
OPTEE_MSG_GET_ARG_SIZE(0),
TEE_SHM_ALLOC, &shm);
if (rc) {
LOG_ERR("Unable to get shared memory, rc = %d", rc);
return rc;
}
marg = shm->addr;
marg->num_params = 0;
marg->cmd = OPTEE_MSG_CMD_CANCEL;
marg->cancel_id = cancel_id;
marg->session = session_id;
rc = optee_call(dev, marg);
if (tee_rm_shm(dev, shm)) {
LOG_ERR("Unable to free shared memory");
}
return rc;
}
static int optee_invoke_func(const struct device *dev, struct tee_invoke_func_arg *arg,
unsigned int num_param, struct tee_param *param)
{
int rc, ret;
struct tee_shm *shm;
struct optee_msg_arg *marg;
if (!arg) {
return -EINVAL;
}
rc = tee_add_shm(dev, NULL, OPTEE_MSG_NONCONTIG_PAGE_SIZE,
OPTEE_MSG_GET_ARG_SIZE(num_param),
TEE_SHM_ALLOC, &shm);
if (rc) {
LOG_ERR("Unable to get shared memory, rc = %d", rc);
return rc;
}
marg = shm->addr;
memset(marg, 0, OPTEE_MSG_GET_ARG_SIZE(num_param));
marg->num_params = num_param;
marg->cmd = OPTEE_MSG_CMD_INVOKE_COMMAND;
marg->func = arg->func;
marg->session = arg->session;
rc = param_to_msg_param(param, num_param, marg->params);
if (rc) {
goto out;
}
arg->ret = optee_call(dev, marg);
if (arg->ret) {
arg->ret_origin = TEEC_ORIGIN_COMMS;
goto out;
}
rc = msg_param_to_param(param, num_param, marg->params);
if (rc) {
arg->ret = TEEC_ERROR_COMMUNICATION;
arg->ret_origin = TEEC_ORIGIN_COMMS;
goto out;
}
arg->ret = marg->ret;
arg->ret_origin = marg->ret_origin;
out:
ret = tee_rm_shm(dev, shm);
if (ret) {
LOG_ERR("Unable to free shared memory");
}
return (rc) ? rc : ret;
}
static void *optee_construct_page_list(void *buf, uint32_t len, uint64_t *phys_buf)
{
const size_t page_size = OPTEE_MSG_NONCONTIG_PAGE_SIZE;
const size_t num_pages_in_pl = OPTEE_NUMBER_OF_ADDR_PER_PAGE - 1;
uint32_t page_offset = (uintptr_t)buf & (page_size - 1);
uint8_t *buf_page;
uint32_t num_pages;
uint32_t list_size;
/* see description of OPTEE_MSG_ATTR_NONCONTIG */
struct {
uint64_t pages[OPTEE_NUMBER_OF_ADDR_PER_PAGE - 1];
uint64_t next_page;
} *pl;
BUILD_ASSERT(sizeof(*pl) == OPTEE_MSG_NONCONTIG_PAGE_SIZE);
num_pages = ROUND_UP(page_offset + len, page_size) / page_size;
list_size = DIV_ROUND_UP(num_pages, num_pages_in_pl) * page_size;
pl = k_aligned_alloc(page_size, list_size);
if (!pl) {
return NULL;
}
memset(pl, 0, list_size);
buf_page = (uint8_t *)ROUND_DOWN((uintptr_t)buf, page_size);
for (uint32_t pl_idx = 0; pl_idx < list_size / page_size; pl_idx++) {
for (uint32_t page_idx = 0; num_pages && page_idx < num_pages_in_pl; page_idx++) {
pl[pl_idx].pages[page_idx] = k_mem_phys_addr(buf_page);
buf_page += page_size;
num_pages--;
}
if (!num_pages) {
break;
}
pl[pl_idx].next_page = k_mem_phys_addr(pl + 1);
}
/* 12 least significant bits of optee_msg_param.u.tmem.buf_ptr should hold page offset
* of user buffer
*/
*phys_buf = k_mem_phys_addr(pl) | page_offset;
return pl;
}
static int optee_shm_register(const struct device *dev, struct tee_shm *shm)
{
struct tee_shm *shm_arg;
struct optee_msg_arg *msg_arg;
void *pl;
uint64_t pl_phys_and_offset;
int rc;
rc = tee_add_shm(dev, NULL, OPTEE_MSG_NONCONTIG_PAGE_SIZE, OPTEE_MSG_GET_ARG_SIZE(1),
TEE_SHM_ALLOC, &shm_arg);
if (rc) {
return rc;
}
msg_arg = shm_arg->addr;
memset(msg_arg, 0, OPTEE_MSG_GET_ARG_SIZE(1));
pl = optee_construct_page_list(shm->addr, shm->size, &pl_phys_and_offset);
if (!pl) {
rc = -ENOMEM;
goto out;
}
/* for this command op-tee os should support CFG_CORE_DYN_SHM */
msg_arg->cmd = OPTEE_MSG_CMD_REGISTER_SHM;
/* op-tee OS ingnore this cmd in case when TYPE_TMEM_OUTPUT and NONCONTIG aren't set */
msg_arg->params->attr = OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT | OPTEE_MSG_ATTR_NONCONTIG;
msg_arg->num_params = 1;
msg_arg->params->u.tmem.buf_ptr = pl_phys_and_offset;
msg_arg->params->u.tmem.shm_ref = (uint64_t)shm;
msg_arg->params->u.tmem.size = shm->size;
if (optee_call(dev, msg_arg)) {
rc = -EINVAL;
}
k_free(pl);
out:
tee_rm_shm(dev, shm_arg);
return rc;
}
static int optee_shm_unregister(const struct device *dev, struct tee_shm *shm)
{
struct tee_shm *shm_arg;
struct optee_msg_arg *msg_arg;
int rc;
rc = tee_add_shm(dev, NULL, OPTEE_MSG_NONCONTIG_PAGE_SIZE, OPTEE_MSG_GET_ARG_SIZE(1),
TEE_SHM_ALLOC, &shm_arg);
if (rc) {
return rc;
}
msg_arg = shm_arg->addr;
memset(msg_arg, 0, OPTEE_MSG_GET_ARG_SIZE(1));
msg_arg->cmd = OPTEE_MSG_CMD_UNREGISTER_SHM;
msg_arg->num_params = 1;
msg_arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_RMEM_INPUT;
msg_arg->params[0].u.rmem.shm_ref = (uint64_t)shm;
if (optee_call(dev, msg_arg)) {
rc = -EINVAL;
}
tee_rm_shm(dev, shm_arg);
return rc;
}
static int optee_suppl_recv(const struct device *dev, uint32_t *func, unsigned int *num_params,
struct tee_param *param)
{
struct optee_driver_data *data = (struct optee_driver_data *)dev->data;
struct optee_supp *supp = &data->supp;
struct optee_supp_req *req = NULL;
while (true) {
k_mutex_lock(&supp->mutex, K_FOREVER);
req = (struct optee_supp_req *)sys_dlist_peek_head(&supp->reqs);
if (req) {
if (supp->current) {
LOG_ERR("Concurrent supp_recv calls are not supported");
k_mutex_unlock(&supp->mutex);
return -EBUSY;
}
if (*num_params < req->num_params) {
LOG_ERR("Not enough space for params, need at least %lu",
req->num_params);
k_mutex_unlock(&supp->mutex);
return -EINVAL;
}
supp->current = req;
sys_dlist_remove(&req->link);
}
k_mutex_unlock(&supp->mutex);
if (req) {
break;
}
k_sem_take(&supp->reqs_c, K_FOREVER);
}
*func = req->func;
*num_params = req->num_params;
memcpy(param, req->param, sizeof(struct tee_param) * req->num_params);
return 0;
}
static int optee_suppl_send(const struct device *dev, unsigned int ret, unsigned int num_params,
struct tee_param *param)
{
struct optee_driver_data *data = (struct optee_driver_data *)dev->data;
struct optee_supp *supp = &data->supp;
struct optee_supp_req *req = NULL;
size_t n;
k_mutex_lock(&supp->mutex, K_FOREVER);
if (supp->current && num_params >= supp->current->num_params) {
req = supp->current;
supp->current = NULL;
} else {
LOG_ERR("Invalid number of parameters, expected %lu got %u", req->num_params,
num_params);
}
k_mutex_unlock(&supp->mutex);
if (!req) {
return -EINVAL;
}
/* Update out and in/out parameters */
for (n = 0; n < req->num_params; n++) {
struct tee_param *p = req->param + n;
switch (p->attr & TEE_PARAM_ATTR_TYPE_MASK) {
case TEE_PARAM_ATTR_TYPE_VALUE_OUTPUT:
case TEE_PARAM_ATTR_TYPE_VALUE_INOUT:
p->a = param[n].a;
p->b = param[n].b;
p->c = param[n].c;
break;
case TEE_PARAM_ATTR_TYPE_MEMREF_OUTPUT:
case TEE_PARAM_ATTR_TYPE_MEMREF_INOUT:
LOG_WRN("Memref params are not fully tested");
p->a = param[n].a;
p->b = param[n].b;
p->c = param[n].c;
break;
default:
break;
}
}
req->ret = ret;
/* Let the requesting thread continue */
k_mutex_lock(&supp->mutex, K_FOREVER);
supp->current = NULL;
k_mutex_unlock(&supp->mutex);
k_sem_give(&req->complete);
return 0;
}
static int set_optee_method(const struct device *dev)
{
const struct optee_driver_config *conf = dev->config;
struct optee_driver_data *data = dev->data;
if (!strcmp("hvc", conf->method)) {
data->smc_call = optee_smccc_hvc;
} else if (!strcmp("smc", conf->method)) {
data->smc_call = optee_smccc_smc;
} else {
LOG_ERR("Invalid smc_call method");
return -EINVAL;
}
return 0;
}
static bool optee_check_uid(const struct device *dev)
{
struct arm_smccc_res res;
struct optee_driver_data *data = (struct optee_driver_data *)dev->data;
data->smc_call(OPTEE_SMC_CALLS_UID, 0, 0, 0, 0, 0, 0, 0, &res);
if (res.a0 == OPTEE_MSG_UID_0 && res.a1 == OPTEE_MSG_UID_1 &&
res.a2 == OPTEE_MSG_UID_2 && res.a3 == OPTEE_MSG_UID_3) {
return true;
}
return false;
}
static void optee_get_revision(const struct device *dev)
{
struct optee_driver_data *data = (struct optee_driver_data *)dev->data;
struct arm_smccc_res res = { 0 };
data->smc_call(OPTEE_SMC_CALL_GET_OS_REVISION, 0, 0, 0, 0, 0, 0, 0, &res);
if (res.a2) {
LOG_INF("OPTEE revision %lu.%lu (%08lx)", res.a0,
res.a1, res.a2);
} else {
LOG_INF("OPTEE revision %lu.%lu", res.a0, res.a1);
}
}
static bool optee_exchange_caps(const struct device *dev, unsigned long *sec_caps)
{
struct optee_driver_data *data = (struct optee_driver_data *)dev->data;
struct arm_smccc_res res = { 0 };
unsigned long a1 = 0;
if (!IS_ENABLED(CONFIG_SMP) || arch_num_cpus() == 1) {
a1 |= OPTEE_SMC_NSEC_CAP_UNIPROCESSOR;
}
data->smc_call(OPTEE_SMC_EXCHANGE_CAPABILITIES, a1, 0, 0, 0, 0, 0, 0, &res);
if (res.a0 != OPTEE_SMC_RETURN_OK) {
return false;
}
*sec_caps = res.a1;
return true;
}
static unsigned long optee_get_thread_count(const struct device *dev, unsigned long *thread_count)
{
struct optee_driver_data *data = (struct optee_driver_data *)dev->data;
struct arm_smccc_res res = { 0 };
unsigned long a1 = 0;
data->smc_call(OPTEE_SMC_GET_THREAD_COUNT, a1, 0, 0, 0, 0, 0, 0, &res);
if (res.a0 != OPTEE_SMC_RETURN_OK) {
return false;
}
*thread_count = res.a1;
return true;
}
static int optee_init(const struct device *dev)
{
struct optee_driver_data *data = dev->data;
unsigned long thread_count;
if (set_optee_method(dev)) {
return -ENOTSUP;
}
sys_dlist_init(&data->notif);
k_mutex_init(&data->supp.mutex);
k_sem_init(&data->supp.reqs_c, 0, 1);
sys_dlist_init(&data->supp.reqs);
if (!optee_check_uid(dev)) {
LOG_ERR("OPTEE API UID mismatch");
return -EINVAL;
}
optee_get_revision(dev);
if (!optee_exchange_caps(dev, &data->sec_caps)) {
LOG_ERR("OPTEE capabilities exchange failed\n");
return -EINVAL;
}
if (!(data->sec_caps & OPTEE_SMC_SEC_CAP_DYNAMIC_SHM)) {
LOG_ERR("OPTEE does not support dynamic shared memory");
return -ENOTSUP;
}
if (!optee_get_thread_count(dev, &thread_count)) {
LOG_ERR("OPTEE unable to get maximum thread count");
return -ENOTSUP;
}
k_sem_init(&data->call_sem, thread_count, thread_count);
return 0;
}
static const struct tee_driver_api optee_driver_api = {
.get_version = optee_get_version,
.open_session = optee_open_session,
.close_session = optee_close_session,
.cancel = optee_cancel,
.invoke_func = optee_invoke_func,
.shm_register = optee_shm_register,
.shm_unregister = optee_shm_unregister,
.suppl_recv = optee_suppl_recv,
.suppl_send = optee_suppl_send,
};
/*
* Bitmap of the ongoing notificatons, received from OP-TEE. Maximum number is
* CONFIG_OPTEE_MAX_NOTIF. This bitmap is needed to handle case when SEND command
* was received before WAIT command from OP-TEE. In this case WAIT will not create
* locks.
*/
#define OPTEE_DT_DEVICE_INIT(inst) \
SYS_BITARRAY_DEFINE_STATIC(notif_bitmap_##inst, CONFIG_OPTEE_MAX_NOTIF); \
\
static struct optee_driver_config optee_config_##inst = { \
.method = DT_INST_PROP(inst, method) \
}; \
\
static struct optee_driver_data optee_data_##inst = { \
.notif_bitmap = ¬if_bitmap_##inst \
}; \
\
DEVICE_DT_INST_DEFINE(inst, optee_init, NULL, &optee_data_##inst, \
&optee_config_##inst, POST_KERNEL, \
CONFIG_KERNEL_INIT_PRIORITY_DEVICE, \
&optee_driver_api); \
DT_INST_FOREACH_STATUS_OKAY(OPTEE_DT_DEVICE_INIT)
```
|
```smalltalk
// snippet-start:[BedrockRuntime.dotnetv3.InvokeModel_Ai21LabsJurassic2]
// Use the native inference API to send a text message to AI21 Labs Jurassic-2.
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;
// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);
// Set the model ID, e.g., Jurassic-2 Mid.
var modelId = "ai21.j2-mid-v1";
// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";
//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
prompt = userMessage,
maxTokens = 512,
temperature = 0.5
});
// Create a request with the model ID and the model's native request payload.
var request = new InvokeModelRequest()
{
ModelId = modelId,
Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
ContentType = "application/json"
};
try
{
// Send the request to the Bedrock Runtime and wait for the response.
var response = await client.InvokeModelAsync(request);
// Decode the response body.
var modelResponse = await JsonNode.ParseAsync(response.Body);
// Extract and print the response text.
var responseText = modelResponse["completions"]?[0]?["data"]?["text"] ?? "";
Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
throw;
}
// snippet-end:[BedrockRuntime.dotnetv3.InvokeModel_Ai21LabsJurassic2]
// Create a partial class to make the top-level script testable.
namespace Ai21LabsJurassic2 { public partial class InvokeModel { } }
```
|
Simon Murray, CBE (born 25 March 1940) is a British Hong Kong-based businessman, adventurer and author.
Murray is the oldest man to reach the South Pole unsupported, at the age of 63.
Early life
Murray was born at Leicester, England into an aristocratic family with some tradition of military service. His father belonged to a wealthy family. Murray's grandfather on his father's side retained a permanent suite at the Connaught Hotel, while his grandmother retained a similar suite at Claridges Hotel. Murray's father abandoned the family early on and Murray claims to have had no recollection of him at that time. An uncle paid for Murray to attend Bedford School, an independent school in Bedford, Bedfordshire. In 1960, he joined the French Foreign Legion, and served for five years in the 2nd Foreign Parachute Regiment (2e REP). During his service, he fought in the Algerian War against the Front de Libération National (FLN). After rising to the rank of Chief Corporal, he turned down an offer to attend Officers' School in France, and left the Legion in 1965 after completing his service. He wrote of his experiences in the Legion in the book Legionnaire, published in 1978. And later, based on his book he produced the autobiographical movie "Deserter" which released as a DVD.
Business career
On leaving the Foreign Legion in 1965, he got married and moved to Hong Kong where he worked for Jardine Matheson for fourteen years. After that, he left to start his own company, Davenham Investments, a project advisory company. N.M.Rothschild took a 50% stake in Davenham. Amongst many high-profile deals, Davenham went on to represent Mitsui in the Singapore Mass Transit Railway project.
In 1984, Davenham was sold to Li Ka-Shing for US$20 million as a precursor to Murray becoming group managing director of Hutchison Whampoa. He stayed for ten years, initiating Hutchison's acquisition of Hong Kong Electric, and negotiating their entry into the oil business through their acquisition of Husky Oil. Whilst CEO of Hutchison, he founded a mobile phone company and, after turning it into the global brand "Orange", it was sold in 1999 for US$36 billion to Mannesmann.
From 1994 to 1998, Simon was the Executive Chairman of the Deutsche Bank Group in Asia. He then established his own company, General Enterprise Management Services Ltd (GEMS), a mid-sized investment group operating across Asia. In addition to this Simon was a founder of Distacom which made a number of mobile telecoms investments including Madacom in Madagascar, Spice Telecom in India and Sunday Communications in Hong Kong. He has also invested in other mobile operations in New Zealand, San Marino, Papua New Guinea and elsewhere.
Murray was the chairman of Glencore from 2011 to 2013. He later became chairman of Gulf Keystone Petroleum from 2013 to 2015. He has served on boards and held advisory positions with a number of other large companies, including Vodafone, Tommy Hilfiger Corporation, Vivendi Universal, Usinor SA, Hermes, General Electric (USA), China National Offshore Oil Corporation (CNOOC), Macquarie Bank, N.M. Rothschild, and Bain (the consultancy company). He continues to serve on the advisory board of Lightbridge Corporation (USA), and was on the Development Advisory Board of Imperial College, London.
Murray is currently the Executive Chairman of GEMS, and a board director of Cheung Kong Holdings Ltd, Orient Overseas (International) Ltd, Wing Tai Properties Ltd, Arnhold Holdings Ltd, Richemont SA, Essar Energy plc, Omnicorp Ltd and IRC Ltd.
Adventurer
Following a suggestion by his wife, Murray joined Pen Hadow for a trek to the Geographic South Pole. The 1,200 km trek started in early December 2004 at Hercules Inlet on the Zumberge Coast, Antarctica and was completed when they reached the South Pole about two months later. They climbed up to 2,835 m above mean sea level on the way. Murray became the oldest man to reach the South Pole unsupported.
Honours
Appointed CBE in 2013, Murray is also a Commandeur of the Order of Merit of the French Republic and a Chevalier de La Legion d’Honneur. He holds an honorary degree in Law, from the University of Bath and attended the (SEP) Stanford Executive Program in the US.
Television
Murray presented 'The Legion is My Country', a BBC Radio 4 documentary (produced by Alec Reid) celebrating the 150th anniversary of the founding of the French Foreign Legion. It was broadcast on 26 May 1981. Also in the 80s, Murray presented a documentary on the French Foreign Legion, where he explained the traditions and folklore that surround this elite force. He also appeared and contributed on the documentary series Escape to the Legion and Weaponology.
Personal life
A kinsman of the Dukes of Atholl, Murray married in 1965 his long-time girlfriend, pilot Jennifer (née Mather), with whom he has three children and six grandchildren. She was the first woman to fly around the world in a helicopter.
References
External links
Tetley South Polar Mission
BBC Article on the South Polar Mission
1940 births
Living people
People educated at Bedford School
Hong Kong people of Scottish descent
Businesspeople from Leicester
Writers from Leicester
People with acquired permanent residency of Hong Kong
Soldiers of the French Foreign Legion
French military personnel of the Algerian War
Commanders of the Order of the British Empire
Commanders of the Ordre national du Mérite
Knights of the Legion of Honour
|
```ruby
# coding: US-ASCII
# frozen_string_literal: false
require 'logger'
class TestLoggerSeverity < Test::Unit::TestCase
def test_enum
logger_levels = Logger.constants
levels = ["WARN", "UNKNOWN", "INFO", "FATAL", "DEBUG", "ERROR"]
Logger::Severity.constants.each do |level|
assert(levels.include?(level.to_s))
assert(logger_levels.include?(level))
end
assert_equal(levels.size, Logger::Severity.constants.size)
end
def test_level_assignment
logger = Logger.new(nil)
Logger::Severity.constants.each do |level|
next if level == :UNKNOWN
logger.send("#{level.downcase}!")
assert(logger.level) == Logger::Severity.const_get(level)
end
end
end
```
|
```scss
// Import your custom theme
@import '../../theme.scss';
.footer-list {
padding: 0 2em;
margin-bottom: 2em;
&__title {
color: mat-color($monocular-app-primary);
font-weight: bold;
vertical-align: top;
margin-bottom: 1em;
}
&__list {
ul {
list-style: none;
padding: 0;
margin: 0;
li {
padding: 0;
margin-bottom: .5em;
}
}
}
@include mappy-bp(small) {
&, &__title, &__list {
display: inline-block;
}
&__list {
ul {
padding-left: 2em;
}
}
}
}
```
|
```groovy
package com.dexvis.dex.task.vis.dexjs
import org.simpleframework.xml.Root
import com.dexvis.dex.task.base.WebTask
@Root
class RadialTree extends WebTask {
public RadialTree() {
super("Visualization: Dex JS", "Radial Tree",
"visualization/dexjs/RadialTree.html",
"web/dexjs/d3/RadialTree.gtmpl")
setSaveDynamic(true)
}
}
```
|
```python
#
#
#
# path_to_url
#
# Unless required by applicable law or agreed to in writing, software
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
import torch
import time
import argparse
from ipex_llm.transformers import AutoModelForCausalLM
from transformers import LlamaTokenizer
# you could tune the prompt based on your own model,
# here the prompt tuning refers to path_to_url#prompt-style
DEFAULT_SYSTEM_PROMPT = """\
"""
def get_prompt(message: str, chat_history: list[tuple[str, str]],
system_prompt: str) -> str:
texts = [f'<s>[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n']
# The first user input is _not_ stripped
do_strip = False
for user_input, response in chat_history:
user_input = user_input.strip() if do_strip else user_input
do_strip = True
texts.append(f'{user_input} [/INST] {response.strip()} </s><s>[INST] ')
message = message.strip() if do_strip else message
texts.append(f'{message} [/INST]')
return ''.join(texts)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for Llama2 model')
parser.add_argument('--repo-id-or-model-path', type=str, default="LinkSoul/Chinese-Llama-2-7b",
help='The huggingface repo id for the Chinese Llama2 (e.g. `LinkSoul/Chinese-Llama-2-7b`) to be downloaded'
', or the path to the huggingface checkpoint folder')
parser.add_argument('--prompt', type=str, default="AI",
help='Prompt to infer')
parser.add_argument('--n-predict', type=int, default=32,
help='Max tokens to predict')
args = parser.parse_args()
model_path = args.repo_id_or_model_path
# Load model in 4 bit,
# which convert the relevant layers in the model into INT4 format
# if your selected model is capable of utilizing previous key/value attentions
# to enhance decoding speed, but has `"use_cache": false` in its model config,
# it is important to set `use_cache=True` explicitly to obtain optimal
# performance with IPEX-LLM INT4 optimizations
# When running LLMs on Intel iGPUs for Windows users, we recommend setting `cpu_embedding=True` in the from_pretrained function.
# This will allow the memory-intensive embedding layer to utilize the CPU instead of iGPU.
model = AutoModelForCausalLM.from_pretrained(model_path,
load_in_4bit=True,
optimize_model=True,
trust_remote_code=True,
use_cache=True)
model = model.to('xpu')
# Load tokenizer
tokenizer = LlamaTokenizer.from_pretrained(model_path, trust_remote_code=True)
# Generate predicted tokens
with torch.inference_mode():
prompt = get_prompt(args.prompt, [], system_prompt=DEFAULT_SYSTEM_PROMPT)
input_ids = tokenizer.encode(prompt, return_tensors="pt").to('xpu')
# ipex_llm model needs a warmup, then inference time can be accurate
output = model.generate(input_ids,
max_new_tokens=args.n_predict)
# start inference
st = time.time()
output = model.generate(input_ids,
max_new_tokens=args.n_predict)
torch.xpu.synchronize()
end = time.time()
output = output.cpu()
output_str = tokenizer.decode(output[0], skip_special_tokens=True)
print(f'Inference time: {end-st} s')
print('-'*20, 'Prompt', '-'*20)
print(prompt)
print('-'*20, 'Output', '-'*20)
print(output_str)
```
|
KXIO is a radio station airing a country music format licensed to Clarksville, Arkansas, broadcasting on 106.9 MHz FM. The station is owned by EAB of Clarksville, LLC.
On March 3, 2017, KXIO changed their format from classic rock to country, branded as "KIC 106.9". (info taken from stationintel.com)
Previous logo
References
External links
Country radio stations in the United States
XIO
Radio stations established in 1992
1992 establishments in Arkansas
|
```python
""" IMPORTS """
from ast import literal_eval
from CommonServerPython import *
# disable insecure warnings
import urllib3
urllib3.disable_warnings()
""""" MAPPERS """
CATEGORY_MAPPER: Dict[str, List[int]] = {
'Network Access': [1, 2, 3, 4, 19, 20, 21, 22],
'Network Inspection': [7, 10, 11, 12, 18],
'Endpoint': [8, 9, 13, 14, 17],
'Email': [15, 24],
'Web': [5, 6],
'Data Leak': [16]
}
SAFEBREACH_TO_DEMISTO_MAPPER = {
'SHA256': 'SHA256',
'Port': 'Port',
'Protocol': 'Protocol',
'FQDN/IP': 'Data',
'Command': 'Command',
'URI': 'URI'
}
INDICATOR_TYPE_MAPPER: Any = {
'FQDN/IP': FeedIndicatorType.Domain,
'SHA256': FeedIndicatorType.File,
'Domain': FeedIndicatorType.Domain,
'Port': 'SafeBreach Port',
'Protocol': 'SafeBreach Protocol',
'Process': 'SafeBreach Process',
'Registry': 'SafeBreach Registry',
'Command': 'SafeBreach Command',
'URI': FeedIndicatorType.URL,
'IP': FeedIndicatorType.IP,
}
# mapper from SB data type to demisto data type that given when the integration was configured.
INDICATOR_TYPE_SB_TO_DEMISTO_MAPPER = {
'SHA256': 'Hash',
'Port': 'Port',
'FQDN/IP': 'Domain',
'Command': 'Command',
'Protocol': 'Protocol',
'URI': 'URI'
}
INSIGHT_DATA_TYPE_MAPPER = {
1: 'Port',
2: 'Protocol',
3: 'Port',
4: 'Port',
5: 'Domain',
6: 'URI',
7: 'Hash',
9: 'Hash',
10: 'Protocol',
14: 'Command',
15: 'Hash',
17: 'CVE', # Not Supported Yet.
18: 'CVE', # Not Supported Yet.
19: 'Port',
20: 'Protocol',
21: 'Port',
22: 'Port',
24: 'Hash',
}
SAFEBREACH_TYPES = [
'Protocol', 'FQDN/IP', 'Port',
'URI', 'SHA256', 'Attack', 'Proxies',
'Impersonated User', 'Commands', 'Drop Path', 'Registry Path',
'Outbound', 'Inbound', 'Server Header', 'Client Header'
]
DEMISTO_INDICATOR_REPUTATION = {
'None': 0,
'Good': 1,
'Suspicious': 2,
'Bad': 3
}
IP_REGEX = r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"
class Client:
def __init__(self, base_url, account_id, api_key, proxies, verify, tags: Optional[list] = None,
tlp_color: Optional[str] = None):
self.base_url = base_url
self.account_id = account_id
self.api_key = api_key
self.verify = verify
self.tags = [] if tags is None else tags
self.tlp_color = tlp_color
self.proxies = proxies
def http_request(self, method, endpoint_url, url_suffix, body=None):
full_url = urljoin(self.base_url, f'{endpoint_url}/v1/accounts/' + f'{self.account_id}{url_suffix}')
return requests.request(
method,
full_url,
json=body,
headers={'Accept': 'application/json', 'x-apitoken': self.api_key},
verify=self.verify,
proxies=self.proxies
)
def rerun_at_safebreach(self, rerun_data):
return self.http_request('POST', endpoint_url='/api/orch', url_suffix='/queue', body=rerun_data)
def get_remediation_data(self, insight_id):
return self.http_request('GET', endpoint_url='/api/data',
url_suffix=f'/insights/{insight_id}/remediation')
def get_insights(self):
return self.http_request(method='GET', endpoint_url='/api/data', url_suffix='/insights?type=actionBased')
def get_nodes(self):
return self.http_request('GET', endpoint_url='api/config',
url_suffix='/nodes?details=true&deleted=true&assets=true')
def get_simulation(self, simulation_id):
return self.http_request(method='GET', endpoint_url='api/data', url_suffix=f'/executions/{simulation_id}')
def get_test_status(self, test_id):
return self.http_request('GET', endpoint_url='/api/data', url_suffix=f'/testsummaries/{test_id}')
def test_connection(self):
return self.http_request('GET', endpoint_url='/api/siem', url_suffix='/config/')
''' Helper functions '''
def is_ip(value):
if isinstance(value, int):
value = str(value)
return re.match(IP_REGEX, value)
def fix_url(url):
if url and url.endswith('/'):
return url[0:-1]
return url
def contains(list_a, list_b):
return list(set(list_a) & set(list_b))
def unescape_string(string):
try:
return string.encode('utf-8').decode('unicode_escape')
except Exception as e:
demisto.debug(f"Failed to unescape_string: ' {e}")
return string
def generate_readable_output(data):
output = []
types = list(set(map(lambda i: i['type'], data)))
for type in types:
same_type = list({x['value'] for x in data if x['type'] == type})
output.append({f'{type} ({len(same_type)})': ', '.join(map(str, same_type))})
return output
def extract_data(data) -> List[Dict[str, Any]]:
output: list = []
list_of_seen_items = []
parent_key = list(data.keys())[0]
first_level_data = list(data[parent_key].keys())
list_of_seen_items.extend(first_level_data)
if parent_key != 'Attack':
output.extend(list(map(lambda o: {'type': parent_key, "value": o}, first_level_data)))
for indicator in data[parent_key]:
if contains(SAFEBREACH_TYPES, list(data[parent_key][indicator].keys())):
for inner_type in data[parent_key][indicator]:
formated_inner_type = inner_type.replace(' ', '')
for item in data[parent_key][indicator][inner_type]:
if item == 'N/A':
continue
if isinstance(item, str):
item = unescape_string(item)
if item not in list_of_seen_items:
list_of_seen_items.append(item)
output.append({'type': formated_inner_type, "value": item})
return output
def get_dbot_type(data_type, value):
if data_type.lower() in ['sha1', 'md5', 'sha256']:
return 'file'
if data_type in ['Domain', 'FQDN/IP', 'URI']:
if is_ip(value):
return 'ip'
return 'url'
return data_type
def get_demisto_context_path(data_type):
mapper = {
'SHA256s': 'File(val.SHA256 == obj.SHA256)',
'SHA256': 'File(val.SHA256 == obj.SHA256)',
'FQDNs/IPs': 'URL(val.Data == obj.Data)',
'FQDN/IP': 'URL(val.Data == obj.Data)',
'IP': 'URL(val.Data == obj.Data)',
'Domain': 'URL(val.Data == obj.Data)',
'Commands': 'Process(val.CommandLine == obj.CommandLine)',
'URIs': 'URL(val.URI == obj.URI)',
'URI': 'URL(val.URI == obj.URI)'
}
return mapper.get(data_type)
def get_insights_ids_by_category(insight_category: List[str]) -> Union[List[int], None]:
output: Any = []
for category in insight_category:
if CATEGORY_MAPPER.get(category):
output.append(CATEGORY_MAPPER.get(category))
return list(set([y for x in output for y in x]))
def refactor_rerun_data(rerun_data, simulation):
rerun_name = f'Rerun (Demisto) - #({rerun_data.get("matrix").get("moveIds")[0]}) {simulation.get("moveName")}'
return {
"force": True,
"matrix": {
"name": rerun_name,
"moveIds": rerun_data['matrix']['moveIds'],
"nodeIds": list(set(rerun_data['matrix']['nodeIds'])),
"simulationId": simulation.get('id')
}
}
def fetch_simulation_result(simulation):
if simulation['status'] == 'SUCCESS':
return 'Not-Blocked'
if simulation['status'] == 'FAIL':
return 'Blocked'
return 'Failure'
def get_node_details(node_role, simulation):
id = simulation.get('attackerNodeId') if node_role == 'Attacker' else simulation.get('targetNodeId')
for item in simulation.get('dataObj').get('data')[0]:
if id == item['id']:
return item['details']
return ""
def get_mitre_details(simulation):
return [list(map(lambda tech: tech['value'], simulation.get('MITRE_Technique') or [])),
list(map(lambda group: group['value'], simulation.get('Threat_Actor') or [])),
list(map(lambda soft: soft['value'], simulation.get('MITRE_Software') or []))]
def get_node_display_name(node_role, simulation):
node_name = simulation.get(f'{node_role}NodeName')
internal_ip = simulation.get(f'{node_role}InternalIp')
external_ip = simulation.get(f'{node_role}ExternalIp')
return f"{node_name} ({internal_ip},{external_ip})"
def get_category_and_data_type_filters(args, predefine_insight_category, predefine_insight_data_type):
insight_category = args.get('insightCategory') or predefine_insight_category
insight_data_type = args.get('insightDataType') or predefine_insight_data_type
# The User can provide the arguments as the following: insightCategory=`Web,Network Inspection`
if isinstance(insight_category, str):
insight_category = insight_category.split(',')
if isinstance(insight_data_type, str):
insight_data_type = insight_data_type.split(',')
# if the user provide invalid category or data type raise an ValueError.
if not contains(insight_category,
['Network Access', 'Network Inspection', 'Endpoint', 'Email', 'Web', 'Data Leak']):
raise ValueError(f'Category {insight_category} is not a valid category')
if not contains(insight_data_type, ['Hash', 'Domain', 'URI', 'Command', 'Port', 'Protocol']):
raise ValueError(f'Data type {insight_data_type} is not a valid data type')
return insight_category, insight_data_type
def get_node_ids_from_insight(insight):
node_ids = []
for target in insight.get('targets'):
node_ids.append(target.get('targetNodeId'))
for attacker in target['attackers']:
node_ids.append(attacker.get('attackerNodeId'))
return list(set(node_ids))
def extract_affected_targets(client, insight):
all_nodes = {item['id']: item for item in client.get_nodes().json()['data']}
return list(map(lambda t: {'name': all_nodes[t['targetNodeId']]['name'],
'ip': all_nodes[t['targetNodeId']]['externalIp'],
'count': t['breakdown']['count']}, insight['targets']))
def get_splunk_remedation_query(response):
try:
query = [vendor['searchQuery'] for vendor in response.json()['mitigationVendors'] if
vendor['id'] == 'splunk']
return "".join(query)
except Exception as e:
demisto.error(e)
return ""
def extract_safebreach_error(response):
errors = response.json().get('error') and response.json().get('error').get('errors')
if not errors:
return f'Failed to extract error!\n{response.json().get("error")}'
return ','.join(list(map(lambda e: e.get('data').get('message'), errors)))
''' Commands '''
def get_indicators_command(client: Client, insight_category: list, insight_data_type: list, tlp_color: Optional[str],
args: dict) -> List[Dict]:
"""Create indicators.
Arguments:
client {Client} -- Client derives from BaseClient.
insight_category {List[String]} -- List of SafeBreach insight category - using as filter.
insight_data_type {List[String]} -- List of data types - using as filter.
tlp_color {str}: Traffic Light Protocol color.
Keyword Arguments:
Returns:
List[Dict] -- List of insights from SafeBreach
"""
limit: int = int(args.get('limit') or demisto.params().get('indicatorLimit', 1000))
indicators: List[Dict] = []
count: int = 0
# These variable be filled directly from the integration configuration or as arguments.
insight_category, insight_data_type = get_category_and_data_type_filters(args, insight_category,
insight_data_type)
# Convert category into insight id
insights_ids: Any = get_insights_ids_by_category(insight_category)
raw_insights: Any = client.get_insights().json()
# Filter insight by category
insights: Any = [item for item in raw_insights if int(item.get('ruleId')) in insights_ids]
for insight in insights:
# Fetch remediation data for each insight
processed_data: List[Dict[str, Any]] = get_remediation_data_command(client,
{'insightId': insight.get('ruleId')}, False)
for item in processed_data:
# if the data type is not in the filter data types continue,
if INDICATOR_TYPE_SB_TO_DEMISTO_MAPPER.get(item['type']) not in insight_data_type:
continue
if not INDICATOR_TYPE_MAPPER.get(str(item['type'])) or item["value"] == 'N/A':
continue
if isinstance(item['type'], int):
demisto.info('Data type is int', item['type'], insight['ruleId'])
is_behaveioral = item['type'] not in ['Domain', 'FQDN/IP', 'SHA256', 'URI', 'Hash']
score_behavioral_reputation = DEMISTO_INDICATOR_REPUTATION.get(demisto.params().get('behavioralReputation'))
score_non_behavioral_reputation = DEMISTO_INDICATOR_REPUTATION.get(
demisto.params().get('nonBehavioralReputation'))
raw_json = {
'value': str(item["value"]),
'dataType': item['type'],
'insightId': insight.get('ruleId'),
'insightTime': insight.get('maxExecutionTime'),
}
mapping = {
'description': 'SafeBreach Insight - {0}'.format(insight['actionBasedTitle']),
item['type'].lower(): item["value"],
"safebreachinsightids": str(insight.get('ruleId')),
"safebreachseverity": insight.get('severity'),
"safebreachseverityscore": str(insight.get('severityScore')),
"safebreachisbehavioral": is_behaveioral,
"safebreachattackids": list(map(str, insight.get('attacks'))),
'tags': [
f"SafeBreachInsightId: {insight.get('ruleId')}",
]
}
if tlp_color:
mapping['trafficlightprotocol'] = tlp_color
mapping['tags'] = list((set(mapping['tags'])).union(set(client.tags)))
indicator = {
'value': str(item["value"]),
'type': INDICATOR_TYPE_MAPPER.get(str(item['type'])),
'rawJSON': raw_json,
'fields': mapping,
'score': score_behavioral_reputation if is_behaveioral else score_non_behavioral_reputation
}
if is_ip(item["value"]):
indicator['type'] = FeedIndicatorType.IP
count += 1
if count > limit:
return indicators
indicators.append(indicator)
return indicators
def get_remediation_data_command(client: Client, args: dict, no_output_mode: bool) -> List[Dict[str, Any]]:
"""Get SafeBreach remediation data.
Arguments:
client {Client} -- Client derives from BaseClient
args {dict} -- function arguments
no_output_mode {bool} -- if true, this function will insert data to the context,
otherwise, it will just returns the data.
Keyword Arguments:
Returns:
Dict -- Each key is a unique SafeBreach data type.
Each value is a list of the data.
"""
insight_id: Optional[int] = args.get('insightId')
response = client.get_remediation_data(insight_id)
insight: Any = get_insights_command(client, {'insightIds': [insight_id]}, False)
if insight:
insight = insight[0]
if response.status_code < 200 or response.status_code >= 300:
error = extract_safebreach_error(response)
raise DemistoException(
f'Failed to fetch remediation data for insight id {insight_id}\nSafeBreach error:{error}')
sb_remediation_data = response.json().get('remediationData')
processed_data = extract_data(sb_remediation_data)
readable_output_list = generate_readable_output(processed_data)
vendor_remediation_data = list(filter(lambda o: o['value'],
[{'type': "Splunk", "value": get_splunk_remedation_query(response)}]))
# Demisto Context:
dbot_score_list = []
standard_context_dict = {}
standard_context_list: Any = []
secondary_standard_context_dict: Any = {}
secondary_standard_context_list = []
secondary_path: Any = None
# SafeBreach Context:
safebreach_context_list = []
safebreach_context = {
"Id": insight_id,
'RawRemediationData': processed_data,
'VendorRemediationData': vendor_remediation_data
}
safebreach_context_list.append(safebreach_context)
for item in processed_data:
if item.get('type', '').startswith('Attack') or len(processed_data) == 0:
continue
demisto_standard_path = get_demisto_context_path(item['type']) # e.g URL(val.Data == obj.Data)
demisto_data_type = SAFEBREACH_TO_DEMISTO_MAPPER.get(item['type']) # SHA256,Port,Protocol,Data,Command,URI
if item['type'] in ['DropPaths', 'URIs', 'URI', 'Command']:
try:
item["value"] = item["value"].encode('utf-8').decode('unicode_escape').encode('latin1').decode('utf-8')
except Exception as e:
demisto.debug(f"Failed to decode/encode: ' {e}")
item["value"] = item["value"]
if demisto_data_type:
is_behaveioral = item['type'] not in ['Domain', 'FQDN/IP', 'SHA256', 'URI', 'Hash']
score_behavioral_reputation = DEMISTO_INDICATOR_REPUTATION.get(demisto.params().get('behavioralReputation'))
score_non_behavioral_reputation = DEMISTO_INDICATOR_REPUTATION.get(
demisto.params().get('nonBehavioralReputation'))
dbot_score = {
"Indicator": item["value"],
'type': get_dbot_type(item['type'], item["value"]), # TODO: maybe change it to SB_Indicator?
"Vendor": "SafeBreach",
"Score": score_behavioral_reputation if is_behaveioral else score_non_behavioral_reputation
}
primary_standard_context = {
demisto_data_type: item["value"], # e.g Data : <URL>, SHA256:<SHA256>
"Malicious": {
"Description": f"SafeBreach Insights - ({insight_id}){insight.get('actionBasedTitle')}",
"Vendor": "SafeBreach"
}
}
if item['type'] in ['FQDNs/IPs', 'FQDN/IP']:
if re.match(IP_REGEX, item["value"]):
secondary_path = 'IP(val.Address == obj.Address)'
secondary_standard_context_dict = {
'IP': item["value"],
"Malicious": {
"Description": f"SafeBreach Insights - ({insight_id}){insight.get('actionBasedTitle')}",
"Vendor": "SafeBreach"
}
}
else:
secondary_path = 'Domain(val.Name == obj.Name)'
secondary_standard_context_dict = {
'Name': item["value"],
"Malicious": {
"Description": f"SafeBreach Insights - ({insight_id}){insight.get('actionBasedTitle')}",
"Vendor": "SafeBreach"
}
}
if demisto_standard_path:
standard_context_list.append(primary_standard_context)
secondary_standard_context_list.append(secondary_standard_context_dict)
dbot_score_list.append(dbot_score)
if len(standard_context_list) > 0 and demisto_standard_path:
standard_context_dict[demisto_standard_path] = standard_context_list
if secondary_path:
standard_context_dict[secondary_path] = secondary_standard_context_list
output_context = {
"DBotScore(val.Indicator == obj.Indicator)": dbot_score_list,
"SafeBreach.Insight(val.Id == obj.Id)": safebreach_context_list
}
merged_context = {**output_context, **standard_context_dict}
readable_output = tableToMarkdown(name="Remediation Data", t=readable_output_list, removeNull=True)
if no_output_mode:
return_outputs(readable_output=readable_output, outputs=merged_context)
return processed_data
def insight_rerun_command(client: Client, args: dict):
"""Rerun SafeBreach insight.
Arguments:
client {Client} -- Client derives from BaseClient
args {dict} -- function arguments
Keyword Arguments:
insight_id {list<int>} -- The insight id to rerun
Returns:
outputs
"""
raw_insights: Any = client.get_insights().json()
insight_ids: Any = args.get('insightIds')
if not insight_ids:
raise Exception('insightIds was not provided to the command')
human_readable_list = []
safebreach_insight_context_list = []
safebreach_test_context_list = []
if isinstance(insight_ids, str):
insight_ids = literal_eval(insight_ids)
if isinstance(insight_ids, int):
insight_ids = [insight_ids]
insight_ids = [int(id) for id in insight_ids]
# Filter all insight according to given.
active_insight_ids = list(map(lambda i: i['ruleId'], raw_insights))
invalid_insight_ids = list(filter(lambda i: i not in active_insight_ids, insight_ids))
insights = list(filter(lambda insight: insight['ruleId'] in insight_ids, raw_insights))
# if given id is not in the active id:
if len(invalid_insight_ids):
# TODO: check if it can be demisto.log()
demisto.info(f'Insight ids:{invalid_insight_ids} are invalid.')
for insight in insights:
try:
insight_id = insight.get('ruleId')
if not insight_ids:
raise ValueError('Insight IDs are invalid')
nodes_ids = get_node_ids_from_insight(insight)
rerun_data = {
"matrix": {
"name": "Insight (XSOAR) - {0}".format(insight['actionBasedTitle']),
"moveIds": insight['attacks'],
"nodeIds": nodes_ids
},
"force": True
}
response = client.rerun_at_safebreach(rerun_data)
if response.status_code < 200 or response.status_code >= 300:
error = extract_safebreach_error(response)
raise DemistoException(
f'Failed to rerun simulation for insight id {insight_id}\nSafeBreach error:{error}')
try:
response = response.json()['data']
except ValueError:
raise ValueError('Response body does not contain valid json')
t = {
'Insight Id': insight_id,
'Test Id': response.get('runId'),
'Name': "Insight (XSOAR) - {0}".format(insight.get('actionBasedTitle')),
'# Attacks': len(insight.get('attacks'))
}
context_object = {
'Id': insight_id,
'Rerun': [{'Name': "Insight (XSOAR) - {0}".format(insight.get('actionBasedTitle')),
'Id': response.get('runId'),
'AttacksCount': len(insight.get('attacks')),
'ScheduledTime': datetime.now().isoformat()}]
}
test_context_dict = {
'Id': response.get('runId'),
'Name': "Insight (XSOAR) - {0}".format(insight.get('actionBasedTitle')),
'Status': 'Pending',
'AttacksCount': len(insight.get('attacks')),
'ScheduledTime': datetime.now().isoformat()
}
human_readable_list.append(t)
safebreach_insight_context_list.append(context_object)
safebreach_test_context_list.append(test_context_dict)
except Exception as e:
traceback.print_exc()
return_error('Failed to rerun insight', e)
safebreach_context = {
'SafeBreach.Insight(val.Id == obj.Id)': safebreach_insight_context_list,
'SafeBreach.Test(val.Id == obj.Id)': safebreach_test_context_list,
}
readable_output = tableToMarkdown(name='Rerun SafeBreach Insight', t=human_readable_list, removeNull=True)
return_outputs(readable_output=readable_output, outputs=safebreach_context)
def get_insights_command(client: Client, args: Dict, no_output_mode: bool) -> List:
"""Get SafeBreach insights.
Arguments:
client {Client} -- Client derives from BaseClient
args {dict} -- function arguments
Keyword Arguments:
Returns:
List[Dict] -- List of insights from SafeBreach
"""
insight_ids = args.get('insightIds')
insights: Any
if isinstance(insight_ids, str):
insight_ids = literal_eval(insight_ids)
if isinstance(insight_ids, int):
insight_ids = [insight_ids]
response: Any = client.get_insights()
if response.status_code < 200 or response.status_code >= 300:
raise ValueError('Failed to fetch SafeBreach insights', response)
try:
insights = sorted(response.json(), key=lambda i: i.get('ruleId'))
except TypeError:
demisto.info('Failed to sort SafeBreach insights, skip')
if insight_ids and len(insight_ids) > 0:
# Verify that insight_ids holds List[int]
if isinstance(insight_ids, list):
insight_ids = list(map(int, insight_ids))
insights = [item for item in insights if int(item.get('ruleId')) in insight_ids]
insight_output = []
insight_readable = []
headers = []
for insight in insights:
affected_targets = extract_affected_targets(client, insight)
context_insight = {
'Name': insight['actionBasedTitle'],
'Id': insight['ruleId'],
'DataType': INSIGHT_DATA_TYPE_MAPPER.get(insight['ruleId']) or 'Other',
'Category': insight.get('category'),
'LatestSimulation': insight.get('maxExecutionTime'),
'EarliestSimulation': insight.get('minExecutionTime'),
'SimulationsCount': insight.get('context').get('simulationsCount'),
'RiskImpact': float("{0:.2f}".format(insight.get('impact'))),
'AffectedTargetsCount': len(insight.get('targets')),
'SeverityScore': insight.get('severityScore'),
'Severity': insight.get('severity'),
'RemediationDataCount': insight.get("mitigationPoints").get('value'),
'RemediationDataType': insight.get("mitigationPoints").get('key'),
'ThreatGroups': insight.get('threatActors'),
'NetworkDirection': insight.get('direction'),
'AttacksCount': len(insight.get('attacks')),
'AttackIds': insight.get('attacks'),
'AffectedTargets': affected_targets,
'RemediationAction': insight.get('action'),
'ResultLink': f"{fix_url(demisto.params().get('url'))}/#/executions?query={insight.get('criteria')}"
}
t = {
'Id': context_insight['Id'],
'Name': context_insight['Name'],
'Category': context_insight['Category'],
'Risk Impact': context_insight['RiskImpact'],
'Severity': context_insight['Severity'],
'Affected Targets': context_insight['AffectedTargetsCount'],
'Data Type': context_insight['DataType'],
}
headers = list(t.keys())
insight_output.append(context_insight)
insight_readable.append(t)
readable_output = tableToMarkdown(name='SafeBreach Insights', t=insight_readable, headers=headers,
removeNull=True)
outputs = {
'SafeBreach.Insight(val.Id == obj.Id)': insight_output
}
if no_output_mode:
return_outputs(
readable_output,
outputs,
insight_output
)
return insights
def get_test_status_command(client: Client, args: Dict):
"""Get status of a SafeBreach test for tracking progress of a run.
Arguments:
client {Client} -- Client derives from BaseClient
args {dict} -- function's arguments
Keyword Arguments:
testId : float
Returns:
None
"""
test_ids = argToList(args.get('testId'))
for test_id in test_ids:
tries = 0
response: Any
while tries < 3:
response = client.get_test_status(test_id)
if response.status_code == 200:
break
tries += 1
if response.status_code < 200 or response.status_code >= 300:
raise ValueError(f'Failed to get status of test: {test_id}')
try:
response = response.json()
except ValueError:
raise ValueError('Response body does not contain valid json')
t = {
'Test Id': response.get('id'),
'Name': response.get('matrixName'),
'Status': response.get('status'),
'Start Time': response.get('startTime'),
'End Time': response.get('endTime'),
'Total Simulation Number': response.get('blocked', 0) + response.get('notBlocked', 0)
}
readable_output = tableToMarkdown(name='Test Status', t=t, headers=list(t.keys()), removeNull=True)
safebreach_context = {
"SafeBreach.Test(val.Id == obj.Id)": {
'Id': response.get('id'),
'Name': response.get('matrixName'),
'Status': response.get('status'),
'StartTime': response.get('startTime'),
'EndTime': response.get('endTime'),
'TotalSimulationNumber': response.get('blocked', 0) + response.get('notBlocked', 0)
}
}
return_outputs(readable_output=readable_output, outputs=safebreach_context)
def get_safebreach_simulation_command(client: Client, args: Dict):
"""Get SafeBreach simulation.
Arguments:
client {Client} -- Client derives from BaseClient
args {dict} -- function arguments
Keyword Arguments:
simulationId {str} -- simulation id.
Returns:
None
"""
simulation_id = args.get('simulationId')
if not simulation_id:
raise ValueError('No simulation ID')
response = client.get_simulation(simulation_id)
if response.status_code < 200 or response.status_code >= 300:
raise ValueError('Failed to fetch SafeBreach simulation')
try:
simulation = response.json()
except ValueError:
raise ValueError('Response body does not contain valid json')
mitre_techniques, mitre_groups, mitre_software = get_mitre_details(simulation)
final_status = simulation.get('finalStatus')
if final_status is not None:
final_status = final_status.capitalize()
detected_action = simulation.get('siemDetectionStatus')
if detected_action is not None:
detected_action = detected_action.capitalize()
try:
simulation_context = {
'Id': simulation.get('id'),
'FinalStatus': final_status,
'Result': fetch_simulation_result(simulation),
'DetectedAction': detected_action,
'SimulationRunId': simulation.get('jobId'),
'Time': simulation.get('executionTime'),
'LastChangeTime': simulation.get('lastStatusChangeDate'),
'Labels': simulation.get('labels'),
"Parameters": simulation.get('parameters'),
'Attack': {
'Id': simulation.get('moveId'),
'Name': simulation.get('moveName'),
'Description': simulation.get('moveDesc'),
'Phase': simulation.get('packageName'),
'Type': list(map(lambda attack_type: attack_type['value'], simulation.get('Attack_Type'))),
'SecurityControl': list(map(lambda item: item['value'], simulation.get('Security_Controls'))),
'IndicatorBased': 'True' if simulation.get('IoC_Based')[0]['value'] == 1 else 'False'
},
'Attacker': {
'Name': simulation.get('attackerNodeName'),
'OS': simulation.get('attackerOSType'),
'InternalIp': simulation.get('attackerInternalIp'),
'ExternalIp': simulation.get('attackerExternalIp'),
'SimulationDetails': get_node_details('Attacker', simulation),
},
'Target': {
'Name': simulation.get('targetNodeName'),
'OS': simulation.get('targetOSType'),
'InternalIp': simulation.get('targetInternalIp'),
'ExternalIp': simulation.get('targetExternalIp'),
'SimulationDetails': get_node_details('Target', simulation),
},
'Network': {
'Direction': simulation.get('direction'),
'SourceIp': simulation.get('sourceIp'),
'DestinationIp': simulation.get('destinationIp'),
'SourcePort': simulation.get('sourcePort'),
'DestinationPort': simulation.get('serverPort'),
'Protocol': simulation.get('attackProtocol'),
'Proxy': simulation.get('parameters').get('PROXY') and simulation['parameters']['PROXY'][0][
'displayName'],
},
'Classifications': {
'MITRETechniques': mitre_techniques,
'MITREGroups': mitre_groups,
'MITRESoftware': mitre_software
}
}
t = {
'Id': simulation_id,
'Name': f'(#{simulation.get("moveId")}) {simulation.get("moveName")}',
'Status': simulation.get('status').capitalize(),
'Result': simulation.get('status').capitalize(),
'Detected Action': simulation.get('status').capitalize(),
'Attacker': get_node_display_name('attacker', simulation),
'Target': get_node_display_name('target', simulation),
}
human_readable = tableToMarkdown(name='SafeBreach Simulation', t=t, headers=list(t.keys()), removeNull=True)
outputs = {
'SafeBreach.Simulation(val.Id == obj.Id)': simulation_context
}
return_outputs(readable_output=human_readable, outputs=outputs)
except Exception:
traceback.print_exc()
def rerun_simulation_command(client: Client, args: dict):
"""Rerun a specific SafeBreach simulation in your environment.
Arguments:
client {Client} -- Client derives from BaseClient
args {dict} -- function arguments
Keyword Arguments:
simulationId {str} -- The id of the simulation to rerun.
Returns:
None
"""
rerun_data = {}
simulation_id = args.get('simulationId')
if not simulation_id:
raise ValueError("No simulation ID has been provided")
try:
response = client.get_simulation(simulation_id)
if response.status_code < 200 or response.status_code >= 300:
raise ValueError(f'Cant Find Simualtion id :{simulation_id}')
simulation = response.json()
rerun_data = simulation.get('rerun')
if not rerun_data:
raise ValueError(f'Cant Find Rerun Data for simulation is:{simulation_id}')
rerun_data = refactor_rerun_data(rerun_data, simulation)
response = client.rerun_at_safebreach(rerun_data).json()['data']
t = {
'Simulation Id': simulation_id,
'Test Id': response['runId'],
'Name': rerun_data['matrix']['name'],
}
safebreach_context = {
"Id": simulation_id,
"Rerun": {
'Id': response['runId'],
'Name': rerun_data['matrix']['name'],
'ScheduledTime': datetime.now().isoformat()
}
}
test_context_dict = {
'Id': response['runId'],
'Name': rerun_data['matrix']['name'],
'Status': 'PENDING',
'AttacksCount': len(rerun_data['matrix']['moveIds'])
}
human_readable = tableToMarkdown(name='SafeBreach Rerun Simualtion', t=t, headers=list(t.keys()),
removeNull=True)
safebreach_context = {
'SafeBreach.Simulation(val.Id == obj.Id)': safebreach_context,
'SafeBreach.Test(val.Id == obj.Id)': test_context_dict,
}
return_outputs(readable_output=human_readable, outputs=safebreach_context)
except Exception as e:
traceback.print_exc()
return_error('Error in rerun_simulation', e)
def safebreach_test_module(client: Client) -> str:
"""A simple test module
Arguments:
url {String} -- SafeBreach Management URL.
Returns:
str -- "ok" if succeeded, else raises a error.
"""
response = client.test_connection()
if response.status_code == 200:
return 'ok'
else:
massage = response.reason.lower()
if response.status_code == 401:
massage = 'API Key is invalid, try again'
elif response.status_code == 404:
massage = 'URL is invalid, try again'
elif response.status_code < 200 or response.status_code >= 300:
massage = 'Test connection failed'
raise Exception(f'{massage}')
def main():
command = demisto.command()
params = demisto.params()
account_id = params.get('accountId')
api_key = params.get('apiKey')
url = fix_url(params.get('url'))
insight_category_filter = params.get('insightCategory')
insight_data_type_filter = params.get('insightDataType')
tags = argToList(params.get('feedTags'))
tlp_color = params.get('tlp_color')
verify_certificate = not params.get('insecure', False)
proxies = handle_proxy()
try:
client = Client(base_url=url, account_id=account_id, api_key=api_key, proxies=proxies,
verify=verify_certificate, tags=tags)
if command == 'safebreach-get-insights':
get_insights_command(client, demisto.args(), True)
elif command == 'safebreach-rerun-insight':
insight_rerun_command(client, demisto.args())
elif command == 'safebreach-get-remediation-data':
get_remediation_data_command(client, demisto.args(), True)
elif command == 'safebreach-get-test-status':
get_test_status_command(client, demisto.args())
elif command == 'safebreach-get-simulation':
get_safebreach_simulation_command(client, demisto.args())
elif command == 'safebreach-rerun-simulation':
rerun_simulation_command(client, demisto.args())
elif command == 'fetch-indicators':
indicators = get_indicators_command(client, insight_category_filter, insight_data_type_filter,
tlp_color, demisto.args())
for b in batch(indicators, batch_size=2000):
demisto.createIndicators(b) # type: ignore
demisto.results('ok')
elif command == 'safebreach-get-indicators':
indicators = get_indicators_command(client, insight_category_filter, insight_data_type_filter,
tlp_color, demisto.args())
entry_result = camelize(indicators)
hr = tableToMarkdown('Indicators:', entry_result)
return_outputs(hr, {}, entry_result)
elif command == 'test-module':
results = safebreach_test_module(client)
return_outputs(results)
else:
return_error(f'Command: {command} is not supported.')
except Exception as e:
return_error(str(e))
# python2 uses __builtin__ python3 uses builtins
if __name__ in ['__main__', "__builtin__", "builtins"]:
main()
```
|
An industry day is an event held by a military to present requirements to industry representatives for weapons or vehicles. Common presentation methods include outlines by PowerPoint. Industry days are usually held in succession with each event holding fewer people as contractors drop their bids.
Military equipment
|
```javascript
/**
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
'use strict';
// EXPORTS //
module.exports = 'debug-stream-sink';
```
|
Benedikte is a first name. It can refer to:
Benedikte Naubert (1756–1819), German writer
Princess Benedikte of Denmark (born 1944), a member of the Danish royal family
Benedikte Hansen (born 1958), Danish actress
Benedikte Kiær (born 1969), Danish politician
See also
Benedict (disambiguation)
|
The 2020–21 WPBL season was the 30th season of the Russian Women's Basketball Premier League. UMMC Ekaterinburg are the defending champions.
Regular season
Playoffs
Russian clubs in European competitions
References
External links
Official Website (in Russian)
202021
WPBL
Russia
|
```javascript
/**
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var pkg = require( './../package.json' ).name;
var iterNone = require( './../lib' );
// FUNCTIONS //
function createIterator( arr ) {
var len;
var it;
var i;
len = arr.length;
i = -1;
it = {};
it.next = next;
it.reset = reset;
return it;
function next() {
i += 1;
if ( i < len ) {
return {
'value': arr[ i ],
'done': false
};
}
i = -1; // reset index
return {
'done': true
};
}
function reset() {
i = -1;
}
}
// MAIN //
bench( pkg, function benchmark( b ) {
var bool;
var arr;
var i;
arr = createIterator( [ 0, 0, 0, 0, 0, 1 ] );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
bool = iterNone( arr );
if ( typeof bool !== 'boolean' ) {
b.fail( 'should return a boolean' );
}
arr.reset();
}
b.toc();
if ( !isBoolean( bool ) ) {
b.fail( 'should return a boolean' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::loop', function benchmark( b ) {
var values;
var bool;
var arr;
var i;
var j;
values = [ 0, 0, 0, 0, 0, 1 ];
arr = createIterator( values );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
bool = true;
for ( j = 0; j < values.length; j++ ) {
if ( arr.next().value ) {
bool = false;
break;
}
}
if ( typeof bool !== 'boolean' ) {
b.fail( 'should be a boolean' );
}
arr.reset();
}
b.toc();
if ( !isBoolean( bool ) ) {
b.fail( 'should be a boolean' );
}
b.pass( 'benchmark finished' );
b.end();
});
```
|
```smalltalk
Class {
#name : 'MetacelloPackageSpecTestCase',
#superclass : 'MetacelloSpecTestCase',
#category : 'Metacello-TestsMCCore',
#package : 'Metacello-TestsMCCore'
}
{ #category : 'tests' }
MetacelloPackageSpecTestCase >> testPackageMergeSpec [
| packageA packageB package repository |
packageA := self packageSpec
name: 'Package';
name: 'Package';
requires: 'AnotherPackage';
includes: 'IncludedPackage';
answers: #(#('preload' 'preload answer') #('postload' 'postload answer'));
file: 'Package-dkh.1';
preLoadDoIt: #preLoadDoIt;
postLoadDoIt: #postLoadDoIt;
repository: 'path_to_url username: 'dkh' password: 'password';
repository: '/opt/gemstone/repository';
yourself.
packageB := self packageSpec
name: 'Package';
requires: 'AndAnotherPackage';
includes: 'AndIncludedPackage';
answers: #(#('xpostload' 'xpostload answer'));
file: 'Package-dkh.2';
repository: 'path_to_url username: 'DaleHenrichs' password: 'secret';
repository: '/opt/gemstone/repo';
yourself.
package := packageA mergeSpec: packageB.
self assert: package name equals: 'Package'.
self assert: package requires equals: #('AnotherPackage' 'AndAnotherPackage').
self assert: package includes equals: #('IncludedPackage' 'AndIncludedPackage').
self assert: package answers equals: #(#('preload' 'preload answer') #('postload' 'postload answer') #('xpostload' 'xpostload answer')).
self assert: package file equals: 'Package-dkh.2'.
self assert: package preLoadDoIt value identicalTo: #preLoadDoIt.
self assert: package postLoadDoIt value identicalTo: #postLoadDoIt.
repository := package repositories map at: '/opt/gemstone/repository' ifAbsent: [ self assert: false ].
self assert: repository type equals: 'directory'.
repository := package repositories map at: '/opt/gemstone/repo' ifAbsent: [ self assert: false ].
self assert: repository type equals: 'directory'.
repository := package repositories map at: 'path_to_url ifAbsent: [ self assert: false ].
self assert: repository type equals: 'http'.
self assert: repository username equals: 'DaleHenrichs'.
self assert: repository password equals: 'secret'
]
{ #category : 'tests' }
MetacelloPackageSpecTestCase >> testPackageSpec [
| package repository |
package := self packageSpec
name: 'Package';
requires: 'AnotherPackage';
includes: 'IncludedPackage';
answers: #(#('preload' 'preload answer') #('postload' 'postload answer'));
file: 'Package-dkh.1';
preLoadDoIt: #preLoadDoIt;
postLoadDoIt: #postLoadDoIt;
repository: 'path_to_url username: 'dkh' password: 'password';
repository: '/opt/gemstone/repository';
yourself.
self assert: package name equals: 'Package'.
self assert: package requires equals: #('AnotherPackage').
self assert: package includes equals: #('IncludedPackage').
self assert: package answers equals: #(#('preload' 'preload answer') #('postload' 'postload answer')).
self assert: package file equals: 'Package-dkh.1'.
self assert: package preLoadDoIt value identicalTo: #preLoadDoIt.
self assert: package postLoadDoIt value identicalTo: #postLoadDoIt.
repository := package repositories map at: '/opt/gemstone/repository' ifAbsent: [ self assert: false ].
self assert: repository type equals: 'directory'.
repository := package repositories map at: 'path_to_url ifAbsent: [ self assert: false ].
self assert: repository type equals: 'http'.
self assert: repository username equals: 'dkh'.
self assert: repository password equals: 'password'
]
```
|
The Pavillon de l'Arsenal is the Paris Center for architecture and urbanism, a center for urban planning and museum located in the 4th arrondissement at 21, boulevard Morland, Paris, France. It is open daily except Mondays; admission is free.
The museum building was built in 1878―1879 for Laurent-Louis Borniche, wood merchant and amateur painter, near the former site of a Celestine monastic community turned arsenal. In 1988, it became a center for documentation and exhibitions related to urban planning and the architecture of Paris.
Today the museum's activities include operating its exhibitions, publishing reference books on issues related to the daily life of Parisians, and providing a forum for individuals and authorities involved in the city's urban planning. Its permanent exhibit (800 m²) displays Parisian architecture and shows how the city has evolved. Three additional spaces are used for temporary exhibits on topics including housing in Paris, the Paris of Baron Haussmann and of private homes, projects for Paris 2012, and other aspects of French and international architecture.
See also
List of museums in Paris
References
Paris.org description
Barry Bergdoll, "Paris: Pavillon de l'Arsenal La Ville et ses Projets/A City in the Making", The Journal of the Society of Architectural Historians, Vol. 53, No. 3 (September 1994), pp. 350–352.
External links
Pavillon de l'Arsenal
Museums in Paris
Architecture museums
History museums in France
Art museums established in 1988
1988 establishments in France
Urban planning museums
Buildings and structures in the 4th arrondissement of Paris
|
```c
/* $OpenBSD: imaxdiv.c,v 1.1 2006/01/13 17:58:09 millert Exp $ */
/*
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <inttypes.h> /* imaxdiv_t */
imaxdiv_t
imaxdiv(intmax_t num, intmax_t denom)
{
imaxdiv_t r;
/* see div.c for comments */
r.quot = num / denom;
r.rem = num % denom;
if (num >= 0 && r.rem < 0) {
r.quot++;
r.rem -= denom;
}
return (r);
}
```
|
```go
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
//go:build go1.16 && integration
// +build go1.16,integration
package kinesis_test
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/awstesting/integration"
"github.com/aws/aws-sdk-go/service/kinesis"
)
var _ aws.Config
var _ awserr.Error
var _ request.Request
func TestInteg_00_ListStreams(t *testing.T) {
ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelFn()
sess := integration.SessionWithDefaultRegion("us-west-2")
svc := kinesis.New(sess)
params := &kinesis.ListStreamsInput{}
_, err := svc.ListStreamsWithContext(ctx, params, func(r *request.Request) {
r.Handlers.Validate.RemoveByName("core.ValidateParametersHandler")
})
if err != nil {
t.Errorf("expect no error, got %v", err)
}
}
func TestInteg_01_DescribeStream(t *testing.T) {
ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelFn()
sess := integration.SessionWithDefaultRegion("us-west-2")
svc := kinesis.New(sess)
params := &kinesis.DescribeStreamInput{
StreamName: aws.String("bogus-stream-name"),
}
_, err := svc.DescribeStreamWithContext(ctx, params, func(r *request.Request) {
r.Handlers.Validate.RemoveByName("core.ValidateParametersHandler")
})
if err == nil {
t.Fatalf("expect request to fail")
}
aerr, ok := err.(awserr.RequestFailure)
if !ok {
t.Fatalf("expect awserr, was %T", err)
}
if len(aerr.Code()) == 0 {
t.Errorf("expect non-empty error code")
}
if len(aerr.Message()) == 0 {
t.Errorf("expect non-empty error message")
}
if v := aerr.Code(); v == request.ErrCodeSerialization {
t.Errorf("expect API error code got serialization failure")
}
}
```
|
Amphisbaena bilabialata is a species of worm lizards found in Brazil.
References
bilabialata
Reptiles described in 1972
Taxa named by Andrew F. Stimson
Endemic fauna of Brazil
Reptiles of Brazil
|
```julia
using Test, Random
using Flux: activations
@testset "basic" begin
@testset "helpers" begin
@testset "activations" begin
dummy_model = Chain(x->x.^2, x->x .- 3, x -> tan.(x))
x = randn(10)
@test activations(dummy_model, x)[1] == x.^2
@test activations(dummy_model, x)[2] == (x.^2 .- 3)
@test activations(dummy_model, x)[3] == tan.(x.^2 .- 3)
@test activations(Chain(), x) == ()
@test activations(Chain(identity, x->:foo), x)[2] == :foo # results include `Any` type
end
end
@testset "Chain" begin
@test_nowarn Chain(Dense(10, 5, ), Dense(5, 2))(randn32(10))
@test_throws DimensionMismatch Chain(Dense(10, 5, ),Dense(2, 1))(randn32(10))
# numeric test should be put into testset of corresponding layer
@test_nowarn Chain(first = Dense(10, 5, ), second = Dense(5, 2))(randn32(10))
m = Chain(first = Dense(10, 5, ), second = Dense(5, 2))
@test m[:first] == m[1]
@test m[1:2] == m
@test m == m
@test m == fmap(identity, m) # does not forget names
@test_throws ArgumentError Chain(layers = Dense(10, 10), two = identity) # reserved name
@test_nowarn Chain([Dense(10, 5, ), Dense(5, 2)])(randn(Float32, 10)) # vector of layers
c = Chain(Dense(10, 5, ), Dense(5, 2), Dense(2, 1, relu))
@test c[1] == c[begin]
@test c[3] == c[end]
end
@testset "Activations" begin
c = Chain(Dense(3,5,relu), Dense(5,1,relu))
X = Float32.([1.0; 1.0; 1.0])
@test_nowarn gradient(()->Flux.activations(c, X)[2][1], Flux.params(c))
c2 = Chain(enc = c[1], dec = c[2])
@test Flux.activations(c, X) == Flux.activations(c2, X)
@test_nowarn gradient(()->Flux.activations(c2, X)[2][1], Flux.params(c2))
end
@testset "Dense" begin
@testset "constructors" begin
@test size(Dense(10, 100).weight) == (100, 10)
@test size(Dense(10, 100).bias) == (100,)
@test Dense(rand(100,10), rand(100)). == identity
@test Dense(rand(100,10)). == identity
@test Dense(rand(100,10), false). == identity
@test Dense(rand(100,10), false, tanh). == tanh
@test Dense(rand(100,10), rand(100)). == identity
@test Dense(rand(Float16, 100,10), true).bias isa Vector{Float16} # creates matching type
@test Dense(rand(Float16, 100,10), rand(100)).bias isa Vector{Float16} # converts to match
@test Dense(3,4; init=Base.randn, bias=true).bias isa Vector{Float64}
@test Dense(3,4; init=Base.randn, bias=[1,2,3,4]).bias isa Vector{Float64}
@test_throws MethodError Dense(10, 10.5)
@test_throws MethodError Dense(10, 10.5, tanh)
@test_throws DimensionMismatch Dense(3,4; bias=rand(5))
@test_throws DimensionMismatch Dense(rand(4,3), rand(5))
@test_throws MethodError Dense(rand(5))
@test_throws MethodError Dense(rand(5), rand(5))
@test_throws MethodError Dense(rand(5), rand(5), tanh)
end
@testset "dimensions" begin
@test length(Dense(10 => 5)(randn32(10))) == 5
@test_throws DimensionMismatch Dense(10 => 5)(randn32(1))
@test_throws MethodError Dense(10 => 5)(1) # avoid broadcasting
@test_throws MethodError Dense(10 => 5).(randn32(10)) # avoid broadcasting
@test size(Dense(10, 5)(randn(10))) == (5,)
@test size(Dense(10, 5)(randn(10,2))) == (5,2)
@test size(Dense(10, 5)(randn(10,2,3))) == (5,2,3)
@test size(Dense(10, 5)(randn(10,2,3,4))) == (5,2,3,4)
@test_throws DimensionMismatch Dense(10, 5)(randn(11,2,3))
end
@testset "zeros" begin
@test Dense(10, 1, identity, init = ones)(ones(10,1)) == 10*ones(1, 1)
@test Dense(10, 1, identity, init = ones)(ones(10,2)) == 10*ones(1, 2)
@test Dense(10, 2, identity, init = ones)(ones(10,1)) == 10*ones(2, 1)
@test Dense(10, 2, identity, init = ones)([ones(10,1) 2*ones(10,1)]) == [10 20; 10 20]
@test Dense(10, 2, identity, init = ones, bias = false)([ones(10,1) 2*ones(10,1)]) == [10 20; 10 20]
end
@testset "type matching" begin
d1 = Dense(2 => 3)
d2 = Dense(d1.weight, false)
x1 = randn(Float32, 2, 4)
@test d1(x1) d2(x1) d1.weight * x1
x2 = Float64.(x1)
@test d1(x2) d2(x2) d1.weight * x2
@test d1(x2) isa Array{Float32} # tests _match_eltype, will print a warning
@test d2(x2) isa Array{Float32}
x3 = rand(-5:5, 2, 4)
@test d1(x3) d2(x3) d1.weight * x3
x4 = rand(Bool, 2, 4)
@test d1(x4) d2(x4) d1.weight * x4
x5 = Flux.onehotbatch(rand(Bool, 5), (true, false))
@test d1(x5) d2(x5) d1.weight * x5
end
end
@testset "Scale" begin
@test length(Flux.Scale(10)(randn(10))) == 10
@test length(Flux.Scale(10)(randn(1))) == 10
@test length(Flux.Scale(10; bias = false)(randn(10))) == 10
@test length(Flux.Scale(10, tanh)(randn(10))) == 10
@test_throws DimensionMismatch Flux.Scale(10)(randn(2))
@test Flux.Scale(2)([1 2]) == [1 2; 1 2]
@test Flux.Scale(2)([1, 2]) == [1, 2]
@test Flux.Scale(2; init = randn)([1, 2]) != [1, 2]
@test Flux.Scale(2; bias = false)([1 2; 3 4]) == [1 2; 3 4]
@test Flux.Scale(2, abs2; bias = false, init = ones)([1 2; 3 4]) == [1 4; 9 16]
@test Flux.Scale(2)(rand(2, 3, 4)) |> size == (2, 3, 4)
@test Flux.Scale(2, 3;)(rand(2, 3, 4)) |> size == (2, 3, 4)
@test Flux.Scale(2, 3, 4; bias = false)(rand(2, 3, 4)) |> size == (2, 3, 4)
@test Flux.Scale(2, 3; bias = false)(rand(2, 1, 4)) |> size == (2, 3, 4)
@test Flux.Scale(2, 3, tanh; bias = false, init = zeros)(rand(2, 1, 4)) == zeros(2, 3, 4)
@test_throws MethodError Flux.Scale(1.)
@test_throws MethodError Flux.Scale(1., 2.)
@test_throws Exception Flux.Scale()
@test_throws MethodError Flux.Scale(sin)
end
@testset "Maxout" begin
# Note that the normal common usage of Maxout is as per the docstring
# These are abnormal constructors used for testing purposes
@testset "Constructor" begin
mo = Maxout(() -> identity, 4)
input = rand(40)
@test mo(input) == input
end
@testset "simple alternatives" begin
mo = Maxout(x -> x, x -> 2x, x -> 0.5x)
input = rand(40)
@test mo(input) == 2*input
end
@testset "complex alternatives" begin
mo = Maxout(x -> [0.5; 0.1]*x, x -> [0.2; 0.7]*x)
input = [3.0 2.0]
target = [0.5, 0.7].*input
@test mo(input) == target
end
@testset "params" begin
mo = Maxout(()->Dense(32, 64), 4)
ps = Flux.params(mo)
@test length(ps) == 8 #4 alts, each with weight and bias
end
end
@testset "SkipConnection" begin
@testset "zero sum" begin
input = randn(10, 10, 10, 10)
@test SkipConnection(x -> zeros(size(x)), (a,b) -> a + b)(input) == input
end
@testset "concat size" begin
input = randn(10, 2)
@test size(SkipConnection(Dense(10,10), (a,b) -> cat(a, b, dims = 2))(input)) == (10,4)
end
end
@testset "Bilinear" begin
@testset "SkipConnection recombinator" begin
d = Dense(10, 10)
b = Flux.Bilinear(10, 10, 5)
x = randn(Float32,10,9)
sc = SkipConnection(d, b)
@test size(sc(x)) == (5,9)
end
@testset "Two-streams zero sum" begin
x = zeros(Float32,10,9)
y = zeros(Float32,2,9)
b = Flux.Bilinear(10, 2, 3)
@test size(b(x,y)) == (3,9)
@test sum(abs2, b(x,y)) == 0f0
end
@testset "Inner interactions" begin
x = randn(Float32,11,7)
b = Flux.Bilinear(11, 11, 3)
@test size(b(x)) == (3,7)
@test_nowarn gs = gradient(() -> sum(abs2.(b(x))), params(b))
end
@testset "constructors" begin
b1 = Flux.Bilinear(randn(3,4,5))
@test b1.bias isa Vector{Float64}
@test b1. == identity
b2 = Flux.Bilinear(randn(3,4,5), false)
@test b2.bias === false
b3 = Flux.Bilinear(randn(Float16, 3,4,5), true, tanh)
@test b3. == tanh
@test b3.bias isa Vector{Float16}
@test size(b3(rand(4), rand(5))) == (3,)
b4 = Flux.Bilinear(3,3,7; bias=1:7, init=Flux.zeros32)
@test_skip b4.bias isa Vector{Float32}
@test_throws ArgumentError Flux.Bilinear(rand(3)) # expects a 3-array
@test_throws ArgumentError Flux.Bilinear(rand(3,4), false, tanh)
@test_throws DimensionMismatch Flux.Bilinear(rand(3,4,5), rand(6), tanh) # wrong length bias
end
end
@testset "Parallel" begin
@testset "zero sum" begin
input = randn(10, 10, 10, 10)
@test Parallel(+, x -> zeros(size(x)), identity)(input) == input
end
@testset "concat size" begin
input = randn(10, 2)
@test size(Parallel((a, b) -> cat(a, b; dims=2), Dense(10, 10), identity)(input)) == (10, 4)
@test size(Parallel(hcat, one = Dense(10, 10), two = identity)(input)) == (10, 4)
end
@testset "vararg input" begin
inputs = randn(10), randn(5), randn(4)
@test size(Parallel(+, Dense(10, 2), Dense(5, 2), Dense(4, 2))(inputs)) == (2,)
@test size(Parallel(+; a = Dense(10, 2), b = Dense(5, 2), c = Dense(4, 2))(inputs)) == (2,)
@test_throws ArgumentError Parallel(+, sin, cos)(1,2,3) # wrong number of inputs
@test Parallel(+, sin, cos)(pi/2) 1
end
@testset "named access" begin
m = Parallel(hcat, one = Dense(10, 10), two = identity)
@test m[1] == m[:one]
@test m[1:2] == m
@test_throws ArgumentError Parallel(hcat, layers = Dense(10, 10), two = identity) # reserved names
@test_throws ArgumentError Parallel(hcat, connection = Dense(10, 10), two = identity)
@test m == fmap(identity, m) # does not forget names
@test Parallel(vcat, x = log)(1) == [0]
@test Parallel(vcat, log)(1) == [0]
end
@testset "trivial cases" begin
@test Parallel(hcat) isa Parallel{typeof(hcat), Tuple{}} # not a NamedTuple
@test Parallel(hcat)(1) == hcat()
@test Parallel(hcat, inv)(2) == hcat(1/2) # still calls connection once.
end
@testset "connection is called once" begin
CNT = Ref(0)
f_cnt = (x...) -> (CNT[]+=1; +(x...))
Parallel(f_cnt, sin, cos, tan)(1)
@test CNT[] == 1
Parallel(f_cnt, sin, cos, tan)(1,2,3)
@test CNT[] == 2
Parallel(f_cnt, sin)(1)
@test CNT[] == 3
end
# Ref path_to_url
@testset "Input domain" begin
struct Input
x
end
struct L1
x
end
(l::L1)(x) = l.x * x
Flux.@functor L1
Base.:*(a::AbstractArray, b::Input) = a * b.x
par = Parallel(+, L1(rand(Float32, 3,3)), L1(rand(Float32, 3,3)))
ip = Input(rand(Float32, 3,3))
ip2 = Input(rand(Float32, 3,3))
@test par(ip) par.layers[1](ip.x) + par.layers[2](ip.x)
@test par(ip, ip2) par.layers[1](ip.x) + par.layers[2](ip2.x)
gs = gradient((par, x...) -> sum(par(x...)), par, ip, ip2)
gs_reg = gradient(par, ip, ip2) do par, x, y
sum(par.layers[1](x.x) + par.layers[2](y.x))
end
for (a,b) in zip(gs[1].layers, gs_reg[1].layers)
@test a.x b.x
end
@test gs[2].x gs_reg[2].x
@test gs[3].x gs_reg[3].x
end
end
@testset "Embedding" begin
vocab_size, embed_size = 10, 4
m = Embedding(vocab_size, embed_size)
@test size(m.weight) == (embed_size, vocab_size)
# one index
@test m(1) isa Vector{Float32}
@test m(2) m.weight[:,2]
@test m(OneHotVector(3, vocab_size)) m.weight[:,3]
@test_throws DimensionMismatch m(OneHotVector(3, 1000))
@test m(4) m((1:vocab_size) .== 4)
# a batch of indices
x = rand(1:vocab_size, 3)
y = m(x)
@test y isa Matrix{Float32}
@test y m.weight[:,x]
x2 = OneHotMatrix(x, vocab_size)
y2 = m(x2)
@test y2 isa Matrix{Float32}
@test y2 y
@test_throws DimensionMismatch m(OneHotMatrix(x, 1000))
@test y m(x' .== (1:vocab_size))
# more dimensions via reshape
x = rand(1:vocab_size, 3, 4)
y = m(x)
@test y isa Array{Float32, 3}
@test size(y) == (embed_size, 3, 4)
x3 = Flux.onehotbatch(x, 1:1:vocab_size)
@test size(x3) == (vocab_size, 3, 4)
y3 = m(x3)
@test size(y3) == (embed_size, 3, 4)
end
@testset "EmbeddingBag" begin
# test _splitat
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
offsets_good = [1, 3, 6]
offsets_each = [1,2,3,4,5,6,7,8,9]
offsets_just_one = [1]
offsets_all_but_last = [1, 9]
@test Flux._splitat(data, offsets_good) == [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
@test Flux._splitat(data, offsets_each) == [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
@test Flux._splitat(data, offsets_just_one) == [[1,2,3,4,5,6,7,8,9]]
@test Flux._splitat(data, offsets_all_but_last) == [[1,2,3,4,5,6,7,8], [9]]
offsets_non_monotonic = [1, 2, 2, 5]
offsets_non_sorted = [1, 5, 2]
offsets_non_one = [2, 3, 5]
offsets_too_large = [1, 5, 11]
@test_throws ArgumentError Flux._splitat(data, offsets_non_monotonic)
@test_throws ArgumentError Flux._splitat(data, offsets_non_sorted)
@test_throws ArgumentError Flux._splitat(data, offsets_non_one)
@test_throws ArgumentError Flux._splitat(data, offsets_too_large)
@testset for reduction in [sum, Statistics.mean, maximum]
vocab_size, embed_size = 10, 4
emb_bag = Flux.EmbeddingBag(vocab_size => embed_size, reduction)
emb = Flux.Embedding(emb_bag.weight)
@test size(emb_bag.weight) == (embed_size, vocab_size)
@test_throws ErrorException emb_bag(2)
# single bag (input as a vector)
x = rand(1:vocab_size, 3)
y = emb_bag(x)
z = vec(reduction(emb(x), dims=2))
@test y isa Vector{Float32}
@test y z
# PyTorch style `input`/`offset` bagging
@test emb_bag([1,3,2,4,5,7], [1,3,5]) emb_bag([[1,3], [2,4], [5,7]])
@test emb_bag([1,3,2,4,5,7], [1,3,5]) emb_bag([1 2 5; 3 4 7])
@test_throws ArgumentError emb_bag([1,2,3,4,5,6], [2, 4])
@test_throws ArgumentError emb_bag([1,2,3,4,5,6], [1, 12])
# docstring example
@test emb_bag([1,2,3,4,5,6,7,8,9,10], [1,5,6,8]) emb_bag([[1,2,3,4], [5], [6,7], [8,9,10]])
# multiple bags (input as a vector of vectors)
x = [rand(1:vocab_size, 3) for _ in 1:4]
y = emb_bag(x)
z = reduce(hcat, reduction.(emb.(x), dims=2))
@test y isa Matrix{Float32}
@test y z
# multiple bags (input as a matrix)
x = rand(1:vocab_size, (3, 5))
xvec = collect(eachcol(x))
y = emb_bag(x)
z = reduce(hcat, reduction.(emb.(xvec), dims=2))
@test y emb_bag(xvec)
@test y z
# a one-hot matrix is a bag, but a one-hot vector is not.
@test_throws ErrorException emb_bag(Flux.OneHotVector(3, vocab_size))
i2 = rand(1:vocab_size, 3)
x2 = Flux.OneHotMatrix(i2, vocab_size)
y2 = emb_bag(x2)
z2 = emb(i2)
@test y2 isa Vector{Float32}
@test y2 vec(reduction(z2, dims=2))
@test_throws DimensionMismatch emb_bag(Flux.OneHotMatrix(1:5, 1000))
end
end
end
@testset "second derivatives" begin
m1 = Chain(Dense(3,4,tanh; bias=false), Dense(4,2))
@test Zygote.hessian_dual(summ1, [1,2,3]) Zygote.hessian_reverse(summ1, [1,2,3])
m1v = Chain([m1[1], m1[2]]) # vector of layers
@test Zygote.hessian_dual(summ1v, [1,2,3]) Zygote.hessian_dual(summ1, [1,2,3])
@test Zygote.hessian_dual(summ1v, [1,2,3]) Zygote.hessian_reverse(summ1v, [1,2,3])
# NNlib's softmax gradient writes in-place
m2 = Chain(Dense(3,4,tanh), Dense(4,2), softmax)
@test_broken Zygote.hessian_dual(summ2, [1,2,3]) Zygote.hessian_reverse(summ2, [1,2,3])
# path_to_url
m3 = Chain(Conv((3,), 2 => 3, relu), Dense(2,2))
x3 = cat(Float32[1 2; 3 4; 5 6; 7 8]; dims=3)
@test Zygote.hessian_dual(summ3, x3) Zygote.hessian_reverse(summ3, x3)
end
@testset "gradients of Chain{Vector}" begin
m1 = Chain(Dense(3,4,tanh; bias=false), Dense(4,2))
m1v = Chain([m1[1], m1[2]])
@test sum(length, params(m1)) == sum(length, params(m1v))
x1 = randn(Float32,3,5)
@test m1(x1) m1v(x1)
y1 = rand(Bool,2,5)
g1 = gradient(() -> Flux.Losses.logitcrossentropy(m1(x1), y1), params(m1))
g1v = gradient(() -> Flux.Losses.logitcrossentropy(m1v(x1), y1), params(m1v))
@test g1[m1[1].weight] g1v[m1v[1].weight]
@test g1[m1[2].bias] g1v[m1v[2].bias]
@test Flux.destructure(m1)[1] Flux.destructure(m1v)[1]
z1 = rand(22);
@test Flux.destructure(m1)[2](z1)[1].weight Flux.destructure(m1v)[2](z1)[1].weight
# Note that Flux.destructure(m1v)[2](z) has a Chain{Tuple}, as does m1v[1:2]
end
@testset "PairwiseFusion" begin
x = (rand(1, 10), rand(30, 10))
layer = PairwiseFusion(+, Dense(1, 30), Dense(30, 10))
y = layer(x)
@test length(y) == 2
@test size(y[1]) == (30, 10)
@test size(y[2]) == (10, 10)
x = rand(1, 10)
layer = PairwiseFusion(.+, Dense(1, 10), Dense(10, 1))
y = layer(x)
@test length(y) == 2
@test size(y[1]) == (10, 10)
@test size(y[2]) == (1, 10)
@test PairwiseFusion(vcat, x->x.+1, x->x.+2, x->x.^3)(2, 10, 20) == (3, [5, 12], [125, 1728, 8000])
@test PairwiseFusion(vcat, x->x.+1, x->x.+2, x->x.^3)(7) == (8, [10, 9], [1000, 729, 343])
end
```
|
```javascript
const fields = ['id', 'name', 'username'];
const id = '1';
module.exports = /* GraphQL */ `
query getUser {
user(id: ${id}) {
${fields.join('\n')}
}
}
`;
```
|
```python
from routersploit.modules.creds.cameras.dlink.ftp_default_creds import Exploit
def test_check_success(generic_target):
""" Test scenario - testing against FTP server """
exploit = Exploit()
assert exploit.target == ""
assert exploit.port == 21
assert exploit.threads == 1
assert exploit.defaults == ["admin:admin"]
assert exploit.stop_on_success is True
assert exploit.verbosity is True
exploit.target = generic_target.host
exploit.port = generic_target.port
assert exploit.check() is False
assert exploit.check_default() is None
assert exploit.run() is None
```
|
Ariel Beltramo (born August 20, 1969) is an Argentine former professional footballer who played as a forward for clubs in Argentina, Chile, Peru, Italy, Israel, Colombia and Guatemala.
References
1969 births
Living people
Argentine men's footballers
Men's association football forwards
Talleres de Córdoba footballers
Club Atlético River Plate footballers
Club de Gimnasia y Esgrima La Plata footballers
Club Atlético Lanús footballers
Club Universidad de Chile footballers
Club Universitario de Deportes footballers
Club Deportivo Palestino footballers
Deportes Tolima footballers
Maccabi Akhi Nazareth F.C. players
SS Chieti Calcio players
ASD Francavilla players
Argentine Primera División players
Categoría Primera A players
Chilean Primera División players
Liga Leumit players
Argentine expatriate men's footballers
Expatriate men's footballers in Chile
Expatriate men's footballers in Peru
Expatriate men's footballers in Guatemala
Expatriate men's footballers in Colombia
Expatriate men's footballers in Israel
Expatriate men's footballers in Italy
Argentine expatriate sportspeople in Chile
Argentine expatriate sportspeople in Peru
Argentine expatriate sportspeople in Guatemala
Argentine expatriate sportspeople in Colombia
Argentine expatriate sportspeople in Israel
Argentine expatriate sportspeople in Italy
|
The Criminal Investigation Department (known as CID) of the Sri Lanka Police Service is responsible for carrying out investigations throughout the island into serious crimes, including murders, rape and organized crime cases of a very serious nature that require special skills and complex detection. At times, the CID carries out investigations pertaining to national security.
It is the primer investigation arm of the Sri Lanka Police Department and was established in 1870.
It is headed by a director, who was of a Senior Superintendent of Police (SSP) Grade. However, since the late 1970s, the position of Deputy Inspector General of Police - CID (DIG/CID) was established.
The CID was modeled after the British Police Criminal Investigation Department and hence constitute the plain clothes detectives of the Sri Lanka police. The CID has the power to arrest any person from anywhere in Sri Lanka without getting approval from any Range DIG.
Notable Directors and D.I.G/C.I.D/ASP Officers
S.A. Dissanayake
John Attygalle
Frank de Silva
W.K.S Weranga Srilal
Bennet Perera
Tyrrell Goonatilleke
Punya de Silva
Lionel Gunathilaka
J. M Saparamadu
O. K. Hemachandra
Keerthi Gajanayaka
Sisira Mendis
Lal Wickrematunge
A Bandula Wickramasinghe
Rayan Steve Hardy.(ASP)
References
External links
Official Police Website
Sri Lanka Police units
Criminology organizations
Secret police
|
Varroa underwoodi is an external parasitic mite that feeds on honey bees. It parasitizes the western honey bee, Asian honey bee, Apis nigrocincta, and Apis nuluensis V. underwoodi has been found on multiple bee species in Southern Asia, though has only been found on the Asian honey bee in China. The smallest sized V. underwoodi was collected from Papua New Guinea from western honey bee hives.
References
Mesostigmata
Arachnids of Asia
Beekeeping
Parasites of bees
Animals described in 1987
|
J34 may refer to:
Hawker J 34 Hunter, a British fighter jet in service with the Swedish Air Force
LNER Class J34, a British steam locomotive class
Malaysia Federal Route J34
Pentagonal orthobirotunda (J34), a Johnson solid
Westinghouse J34, an American turbojet engine
|
Santa Barbara City College (SBCC) is a public community college in Santa Barbara, California. It opened in 1909 and is located on a campus.
History
Santa Barbara City College was established by the Santa Barbara High School District in 1909, making it one of the oldest community colleges in California. The college was discontinued shortly after World War I, and its work largely taken over by the Santa Barbara State Normal School, which became the Santa Barbara State College, and later, the University of California, Santa Barbara.
SBCC was reorganized by the high school district in the fall of 1946. Called Santa Barbara Junior College from its inception, the Santa Barbara Board of Education formally changed the name to Santa Barbara City College in July 1959. Also in the summer of 1959, the institution moved to its present and permanent location on the Santa Barbara Mesa, former site of the University of California, Santa Barbara. Situated on a 74-acre bluff, the campus overlooks the harbor and Pacific Ocean. Passage of a 1969 construction bond issue and a 1973 land acquisition bond issue ensured that the college would have a single, consolidated Mesa campus.
In 2013, Santa Barbara City College was awarded the Aspen Prize for Community College Excellence.
Academics
The School of Media Arts (SOMA) was established in 2001 to focus on applied communication, visual literacy and digital media. The school covers many areas of interest, including film studies, film production, photography, and computer and multimedia arts.
The music department at features several performance groups, including three jazz ensembles, large and small vocal ensembles, a concert band, and a full symphony orchestra.
The automotive program has been certified by the National Institute for Automotive Service Excellence (ASE) as a master training institution, having met industry standards in all eight of the automotive specialty areas: engine repair, engine performance, heating and air conditioning, electrical systems, automatic transmissions, manual transmission and axle, and brakes and front end.
Santa Barbara City College's Marine Diving Technologies Program is the only community college degree program in the nation which is accredited by the Association of Commercial Diving Educators (ACDE), the International Diving Schools Association (IDSA), and the National Association of Underwater Instructors (NAUI). The program trains and certifies for all levels of SCUBA diving.
The Cancer Information Management Program at Santa Barbara City College offers two types of degrees: An Associate in Science in Cancer Information Management and the Certificate of Completion in Cancer Information Management. It is one of the few Cancer Information Management programs in the nation to currently offer an associate degree which is required to sit for the National Exam to become a Certified Tumor Registrar with the National Cancer Registrars Association starting in 2009.
The student newspaper is named The Channels.
Athletics
The college's athletic teams are known as the Vaqueros. Santa Barbara competes as a member of the California Community College Athletic Association (CCCAA) in the Western State Conference (WSC) for all sports except football, which competes in Southern California Football Association (SCFA). City College offers intercollegiate athletic competition with nine men sports and eleven women's sports.
Santa Barbara City College has won 11 CCCAA State Championship with the women's water polo team being the most recent winner in 2017. Under the leadership of Athletic Director Rocco Constantino in 2017–2018, the Vaqueros finished tenth in the state of California in the NATYCAA Cup Standings, which measures the overall success of the athletic program on the state level. They were the highest ranking Western State Conference school in these standings. This represented the best showing for SBCC in the Cup's history. In 2017–2018, the Vaqueros won a WSC-leading six conference championships. The SBCC Vaqueros soccer and football teams play at the 10,000-capacity La Playa Stadium in Santa Barbara.
A number of SBCC alumni have gone on to play professional sports in America. This group is highlighted by Jesse Orosco, Tyler Gilbert, Dylan Axelrod, Delwyn Young, Gary Woods, Lemmie Miller and Scott Randall (Major League Baseball), Larry Moriarty, Mitch Wishnowsky and Booker Brown (National Football League) and Don Ford (National Basketball Association). Orosco is a member of the CCCAA Hall of Fame, along with former SBCC coaches and administrators Pat Moorhouse and Bob Dinaberg. In 2019, the Santa Barbara City College established the SBCC Vaqueros Hall of Fame to recognize athletes, coaches, contributors and teams from their past. The inaugural Hall of Fame Class of 2019 includes former head coaches/administrators Bob Dinaberg, Pat Moorhouse and Bud Revis, student-athletes Booker Brown, Gary Woods, Marina Gomez and Debbie Ekola and the 1977 State Champion Women's Track & Field team.
Notable people
Notable alumni
Jaime Ambriz, retired professional soccer player
Ron Anderson, NBA
Dylan Axelrod, Major League baseball player
Eion Bailey, American actor
David Crosby, American folk rock musician
Tyler Gilbert, Major League Baseball player
Phillip Gonyea, drummer for Los Angeles heavy metal band Before The Mourning and former percussionist for alternative rock band Against All Will
Ben Howland, American basketball coach of the UCLA Bruins
James Kiffe, professional soccer player
Ozzy Lusth of Survivor: Cook Islands and Survivor: Micronesia
Mansour bin Zayed Al Nahyan, deputy prime minister of the United Arab Emirates and minister of presidential affairs
Randolph Mantooth, American actor, writer, and producer
Airin Older, bassist of Sugarcult
Jesse Orosco, major league baseball record-holder for career pitching appearances
Katy Perry, American singer/songwriter
Chris Plante, television reporter, host of eponymous radio show
Elliot Rodger, perpetrator of the 2014 Isla Vista killings
Mark Andrew Smith, graphic novelist
Matthew Landy Steen, American political activist, co-founder Weather Underground
Grace Tame, 2021 Australian of the Year
Das Williams, California State Assembly member
Mitch Wishnowsky, football player for the San Francisco 49ers
David Woodard, conductor
Delwyn Young, baseball player for the Los Angeles Dodgers
Notable faculty
Kathryn Ish, acting teacher
References
External links
Official website
City College
California Community Colleges
Universities and colleges established in 1909
Schools accredited by the Western Association of Schools and Colleges
Universities and colleges in Santa Barbara County, California
1909 establishments in California
|
Nineteenth-century theatre describes a wide range of movements in the theatrical culture of Europe and the United States in the 19th century. In the West, they include Romanticism, melodrama, the well-made plays of Scribe and Sardou, the farces of Feydeau, the problem plays of Naturalism and Realism, Wagner's operatic Gesamtkunstwerk, Gilbert and Sullivan's plays and operas, Wilde's drawing-room comedies, Symbolism, and proto-Expressionism in the late works of August Strindberg and Henrik Ibsen.
Melodrama
Beginning in France after the theatre monopolies were abolished during the French Revolution, melodrama became the most popular theatrical form of the century. Melodrama itself can be traced back to classical Greece, but the term mélodrame did not appear until 1766 and only entered popular usage sometime after 1800. The plays of August von Kotzebue and René Charles Guilbert de Pixérécourt established melodrama as the dominant dramatic form of the early 19th century. Kotzebue in particular was the most popular playwright of his time, writing more than 215 plays that were produced all around the world. His play The Stranger (1789) is often considered the classic melodramatic play. Although monopolies and subsidies were reinstated under Napoleon, theatrical melodrama continued to be more popular and brought in larger audiences than the state-sponsored drama and operas.
Melodrama involved a plethora of scenic effects, an intensely emotional but codified acting style, and a developing stage technology that advanced the arts of theatre towards grandly spectacular staging. It was also a highly reactive form of theatre which was constantly changing and adapting to new social contexts, new audiences and new cultural influences. This, in part, helps to explains its popularity throughout the 19th century. David Grimsted, in his book Melodrama Unveiled (1968), argues that:Its conventions were false, its language stilted and commonplace, its characters stereotypes, and its morality and theology gross simplifications. Yet its appeal was great and understandable. It took the lives of common people seriously and paid much respect to their superior purity and wisdom. [...] And its moral parable struggled to reconcile social fears and life's awesomeness with the period's confidence in absolute moral standards, man's upward progress, and a benevolent providence that insured the triumph of the pure.
In Paris, the 19th century saw a flourishing of melodrama in the many theatres that were located on the popular Boulevard du Crime, especially in the Gaîté. All this was to come to an end, however, when most of these theatres were demolished during the rebuilding of Paris by Baron Haussmann in 1862.
By the end of the 19th century, the term melodrama had nearly exclusively narrowed down to a specific genre of salon entertainment: more or less rhythmically spoken words (often poetry)—not sung, sometimes more or less enacted, at least with some dramatic structure or plot—synchronized to an accompaniment of music (usually piano). It was looked down on as a genre for authors and composers of lesser stature (probably also the reason why virtually no realisations of the genre are still remembered).
Romanticism in Germany and France
In Germany, there was a trend toward historical accuracy in costumes and settings, a revolution in theatre architecture, and the introduction of the theatrical form of German Romanticism. Influenced by trends in 20th -century philosophy and the visual arts, German writers were increasingly fascinated with their Teutonic past and had a growing sense of romantic nationalism. The plays of Gotthold Ephraim Lessing, Johann Wolfgang von Goethe, Friedrich Schiller, and other Sturm und Drang playwrights, inspired a growing faith in feeling and instinct as guides to moral behavior. Romantics borrowed from the philosophy of Immanuel Kant to formulate the theoretical basis of "Romantic" art. According to Romantics, art is of enormous significance because it gives eternal truths a concrete, material form that the limited human sensory apparatus may apprehend. Among those who called themselves Romantics during this period, August Wilhelm Schlegel and Ludwig Tieck were the most deeply concerned with theatre. After a time, Romanticism was adopted in France with the plays of Victor Hugo, Alexandre Dumas, Alfred de Musset, and George Sand.
Through the 1830s in France, the theatre struggled against the Comédie Française, which maintained a strong neo-classical hold over the repertory and encouraged traditional modes of tragic writing in new playwrights. This clash culminated in the premiere of Hernani by Victor Hugo in 1830. The large crowd that attended the premiere was full of conservatives and censors who booed the show for disobeying the classical norms and who wanted to stop the performance from going forward. But Hugo organized a Romantic Army of bohemian and radical writers to ensure that the opening would have to go ahead. The resulting riot represented the rejection in France of the classical traditions and the triumph of Romanticism.
By the 1840s, however, enthusiasm for Romantic drama had faded in France and a new "Theatre of Common Sense" replaced it.
Well-made play
In France, the "well-made play" of Eugene Scribe (1791–1861) became popular with playwrights and audiences. First developed by Scribe in 1825, the form has a strong Neoclassical flavour, involving a tight plot and a climax that takes place close to the end of the play. The story depends upon a key piece of information kept from some characters, but known to others (and to the audience). A recurrent device that the well-made play employs is the use of letters or papers falling into unintended hands, to bring about plot twists and climaxes. The suspense and pace builds towards a climactic scene, in which the hero triumphs in an unforeseen reversal of fortune.
Scribe himself wrote over 400 plays of this type, using what essentially amounted to a literary factory with writers who supplied the story, another the dialogue, a third the jokes and so on. Although he was highly prolific and popular, he was not without detractors: Théophile Gautier questioned how it could be that, "an author without poetry, lyricism, style, philosophy, truth or naturalism could be the most successful writer of his epoch, despite the opposition of literature and the critics?"
Its structure was employed by realist playwrights Alexandre Dumas, fils, Emile Augier, and Victorien Sardou. Sardou in particular was one of the world's most popular playwrights between 1860 and 1900. He adapted the well-made play to every dramatic type, from comedies to historical spectacles. In Britain, playwrights like Wilkie Collins, Henry Arthur Jones and Arthur Pinero took up the genre, with Collins describing the well-made play as: “Make ’em laugh; make ’em weep; make ’em wait.” George Bernard Shaw thought that Sardou's plays epitomized the decadence and mindlessness into which the late 19th-century theatre had descended, a state that he labeled "Sardoodledom".
Theatre in Britain
In the early years of the 19th century, the Licensing Act allowed plays to be shown at only two theatres in London during the winter: Drury Lane and Covent Garden. These two huge theatres contained two royal boxes, huge galleries, and a pit with benches where people could come and go during performances. Perhaps the most telling episode of the popularity of theatre in the early 19th century is the theatrical Old Price riots of 1809. After Covent Garden burned down, John Philip Kemble, the theatre's manager, decided to raise prices in the pit, the boxes and the third tier. Audience members hated the new pricing which they thought denied them access to a national meeting place and led to three months of rioting until finally Kemble was forced to publicly apologize and lower prices again. To escape the restrictions, non-patent theatres along the Strand, like the Sans Pareil, interspersed dramatic scenes with musical interludes and comic skits after the Lord Chamberlain's Office allowed them to stage Burlettas—leading to the formation of the modern West End. Outside of the metropolitan area of London, theatres like Astley's Amphitheatre and the Coburg were also able to operate outside of the rules. The exploding popularity of these forms began to make the patent system unworkable and the boundaries between the two began to blur through the 1830s until finally the Licensing Act was dropped in 1843 with the Theatres Act. Parliament hoped that this would civilize the audiences and lead to more literate playwrighting—instead, it created an explosion of Music halls, comedies and sensationalist melodramas.
Percy Bysshe Shelley and Lord Byron were the most important literary dramatists of their time (although Shelley's plays were not performed until later in the century). Shakespeare was enormously popular, and began to be performed with texts closer to the original, as the drastic rewriting of 17th and 18th century performing versions for the theatre were gradually removed over the first half of the century. Kotzebue's plays were translated into English and Thomas Holcroft's A Tale of Mystery was the first of many English melodramas. Pierce Egan, Douglas William Jerrold, Edward Fitzball, James Roland MacLaren and John Baldwin Buckstone initiated a trend towards more contemporary and rural stories in preference to the usual historical or fantastical melodramas. James Sheridan Knowles and Edward Bulwer-Lytton established a "gentlemanly" drama that began to re-establish the former prestige of the theatre with the aristocracy.
Theatres throughout the century were dominated by actor-managers who managed the establishments and often acted in the lead roles. Henry Irving, Charles Kean and Herbert Beerbohm Tree are all examples of managers who created productions in which they were the star performer. Irving especially dominated the Lyceum Theatre for almost 30 years from 1871 to 1899 and was hero-worshipped by his audiences. When he died in 1905, King Edward VII and Theodore Roosevelt send their condolences. Among these actor-managers, Shakespeare was often the most popular writer as his plays afforded them great dramatic opportunity and name recognition. The stage spectacle of these productions was often more important than the play and texts were often cut to give maximum exposure to the leading roles. However, they also introduced significant reforms into the theatrical process. For example, William Charles Macready was the first to introduce proper rehearsals to the process. Before this lead actors would rarely rehearse their parts with the rest of the cast: Edmund Kean's most famous direction to his fellow actors being, "stand upstage of me and do your worst."
Melodramas, light comedies, operas, Shakespeare and classic English drama, pantomimes, translations of French farces and, from the 1860s, French operettas, continued to be popular, together with Victorian burlesque. The most successful dramatists were James Planché and Dion Boucicault, whose penchant for making the latest scientific inventions important elements in his plots exerted considerable influence on theatrical production. His first big success, London Assurance (1841) was a comedy in the style of Sheridan, but he wrote in various styles, including melodrama. T. W. Robertson wrote popular domestic comedies and introduced a more naturalistic style of acting and stagecraft to the British stage in the 1860s.
In 1871, the producer John Hollingshead brought together the librettist W.S. Gilbert and the composer Arthur Sullivan to create a Christmas entertainment, unwittingly spawning one of the great duos of theatrical history. So successful were the 14 comic operas of Gilbert and Sullivan, such as H.M.S. Pinafore (1878) and The Mikado (1885), that they had a huge influence over the development of musical theatre in the 20th century. This, together with much improved street lighting and transportation in London and New York led to a late Victorian and Edwardian theatre building boom in the West End and on Broadway. At the end of the century, Edwardian musical comedy came to dominate the musical stage.
In the 1890s, the comedies of Oscar Wilde and George Bernard Shaw offered sophisticated social comment and were very popular.
Theatre in the United States
In the United States, Philadelphia was the dominant theatrical centre until the 1820s. There, Thomas Wignell established the Chestnut Street Theatre and gathered a group of actors and playwrights that included William Warren, Susanna Rowson, and Thomas Abthorpe Cooper, who later was considered the leading actor in North America. In its infancy after the American Revolution, many Americans lamented the lack of a 'native drama', even while playwrights such as Royall Tyler, William Dunlap, James Nelson Barker, John Howard Payne, and Samuel Woodworth laid the foundations for an American drama separate from Britain. Part of the reason for the dearth of original plays in this period may be that playwrights were rarely paid for their work and it was much cheaper for managers to adapt or translate foreign work. Tradition held that remuneration was mainly in the form of a benefit performance for the writer on the third night of a run, but many managers would skirt this custom by simply closing the show before the third performance.
Known as the "Father of the American Drama", Dunlap grew up watching plays given by British officers and was heavily immersed in theatrical culture while living in London just after the Revolution. As the manager of the John Street Theatre and Park Theatre in New York City, he brought back to his country the plays and theatrical values that he had seen. Like many playwright-managers of his day, Dunlap adapted or translated melodramatic works by French of German playwrights, but he also wrote some 29 original works including The Father (1789), André (1798), and The Italian Father (1799).
From 1820 to 1830, improvements in the material conditions of American life and the growing demand of a rising middle class for entertainment led to the construction of new theatres in New York, Philadelphia, Boston and Washington, including Catham Garden, Federal Street , the Tremont, Niblo's Garden and the Bowery. During the early part of this period, Philadelphia continued to be the major theatrical centre: plays would often open in Baltimore in September or October before transferring to larger theatres in Philadelphia until April or May, followed by a summer season in Washington or Alexandria. However, rivalries and larger economic forces led to a string of bankruptcies for five major theatre companies in just eight months between 1 October 1828 and 27 May 1829. Due to this and the import of star system performers like Clara Fisher, New York took over as the dominant city in American theatre.
In the 1830s, Romanticism flourished in Europe and America with writers like Robert Montgomery Bird rising to the forefront. Since Romanticism emphasized eternal truths and nationalistic themes, it fit perfectly with the emerging national identity of the United States. Bird's The Gladiator was well-received when it premiered in 1831 and was performed at Drury Lane in London in 1836 with Edwin Forrest as Spartacus, with The Courier proclaiming that "America has at length vindicated her capability of producing a dramatist of the highest order." Dealing with slave insurgency in Ancient Rome, The Gladiator implicitly attacks the institution of Slavery in the United States by "transforming the Antebellum into neoclassical rebels". Forrest would continue to play the role for over one thousand performances around the world until 1872. Following the success of their early collaboration, Bird and Forrest would work together on further premieres of Oralloosa, Son of the Incas and The Broker of Bogota. But the success of The Gladiator led to contract disagreements, with Bird arguing that Forrest, who had made tens of thousands from Bird's plays, owed him more than the $2,000 he had been paid.
Minstrel shows emerged as brief burlesques and comic Entr'actes in the early 1830s. They were developed into full-fledged form in the next decade. By 1848, blackface minstrel shows were the national art form, translating formal art such as opera into popular terms for a general audience. Each show consisted of comic skits, variety acts, dancing, and music performances that mocked people specifically of African descent. The shows were performed by Caucasians in make-up or blackface for the purpose of playing the role of black people. Minstrel songs and sketches featured several Stock characters, most popularly the slave and the dandy. These were further divided into sub-archetypes such as the mammy, her counterpart the old darky, the provocative mulatto wench, and the black soldier. Minstrels claimed that their songs and dances were authentically black, although the extent of the black influence remains debated.
Star actors amassed an immensely loyal following, comparable to modern celebrities or sports stars. At the same time, audiences had always treated theaters as places to make their feelings known, not just towards the actors, but towards their fellow theatergoers of different classes or political persuasions, and theatre Riots were a regular occurrence in New York. An example of the power of these stars is the Astor Place riot in 1849, which was caused by a conflict between the American star Edwin Forrest and the English actor William Charles Macready. The riot pitted immigrants and nativists against each other, leaving at least 25 dead and more than 120 injured.
In the pre-Civil War era, there were also many types of more political drama staged across the United States. As America pushed west in the 1830s and 40s, theatres began to stage plays that romanticized and masked treatment of Native Americans like Pocahontas, The Pawnee Chief, De Soto and Metamora or the Last of the Wampanoags. Some fifty of these plays were produced between 1825 and 1860, including burlesque performances of the "noble savage" by John Brougham. Reacting off of current events, many playwrights wrote short comedies that dealt with the major issues of the day. For example, Removing the Deposits was a farce produced in 1835 at the Bowery in reaction to Andrew Jackson's battle with the banks and Whigs and Democrats, or Love of No Politics was a play that dealt with the struggle between America's two political parties.
In 1852, Harriet Beecher Stowe published the anti-slavery novel Uncle Tom's Cabin and, without any strong copyright laws, was immediately dramatized on stages across the country. At the National Theatre in New York, it was a huge success and ran for over two hundred performances up to twelve times per week until 1854. The adaptation by George Aiken was a six-act production that stood on its own, without any other entertainments or afterpiece. Minstrelsy's reaction to Uncle Tom's Cabin is indicative of plantation content at the time. Tom acts largely came to replace other plantation narratives, particularly in the third act. These sketches sometimes supported Stowe's novel, but just as often they turned it on its head or attacked the author. Whatever the intended message, it was usually lost in the joyous, slapstick atmosphere of the piece. Characters such as Simon Legree sometimes disappeared, and the title was frequently changed to something more cheerful like "Happy Uncle Tom" or "Uncle Dad's Cabin". Uncle Tom himself was frequently portrayed as a harmless bootlicker to be ridiculed. Troupes known as Tommercompanies specialized in such burlesques, and theatrical Tom shows integrated elements of the minstrel show and competed with it for a time.
After the Civil War, the American stage was dominated by melodramas, minstrel shows, comedies, farces, circuses, vaudevilles, burlesques, operas, operettas, musicals, musical revues, medicine shows, amusement arcades, and Wild West shows. Many American playwrights and theatre workers lamented the "failure of the American playwright", including Augustin Daly, Edward Harrigan, Dion Boucicault, and Bronson Howard. However, as cities and urban areas boomed from immigration in the late nineteenth century, the social upheaval and innovation in technology, communication and transportation had a profound effect on the American theatre.
In Boston, although ostracized from Gilded Age society, Irish American performers began to find success, including Lawrence Barrett, James O'Neill, Dan Emmett, Tony Hart, Annie Yeamans, John McCullough, George M. Cohan, and Laurette Taylor, and Irish playwrights came to dominate the stage, including Daly, Harrigan, and James Herne.
In 1883, the Kiralfy brothers met with Thomas Edison at Menlo Park to see if the electric light bulb could be incorporated into a musical ballet called Excelsior that they were to present at Niblo's Gardens in New York City. A showman himself, Edison realized the potential of this venture to create demand for his invention, and together they designed a finale to the production that would be illuminated by more than five hundred light bulbs attached to the costumes of the dancers and to the scenery. When the show opened on 21 August, it was an immediate hit, and would subsequently be staged in Buffalo, Chicago, Denver and San Francisco. Thus, electric lighting in the theatre was born and would radically change not just stage lighting, but the principles of scenic design.
The Gilded Age was also the golden age of touring in American theatre: while New York City was the mecca of the ambitious, the talented and the lucky, throughout the rest of the country, a network of theatres large and small supported a huge industry of famous stars, small troupes, minstrel shows, vaudevillians, and circuses. For example, in 1895, the Burt Theatre in Toledo, Ohio offered popular melodramas for up to thirty cents a seat and saw an average audience of 45,000 people per month at 488 performances of 64 different plays. On average 250–300 shows, many originating in New York, crisscrossed the country each year between 1880 and 1910. Meanwhile, owners of successful theatres began to expand their reach, like the theatrical empire of B.F. Keith and Edward F. Albee that spanned over seven hundred theatres, including the Palace in New York. This culminated in the founding of the Theatre Syndicate in 1896.
New York City's importance as a theatrical center grew in the 1870s around Union Square until it became the primary theatre center, and the Theater District slowly moved north from lower Manhattan until it finally arrived in midtown at the end of the century.
On the musical stage, Harrigan and Hart innovated with comic musical plays from the 1870s, but London imports came to dominate, beginning with Victorian burlesque, then Gilbert and Sullivan from 1880, and finally (in competition with George M. Cohan and musicals by the Gershwins) Edwardian musical comedies at the turn of the century and into the 1920s.
Meiningen Ensemble and Richard Wagner
In Germany, drama entered a state of decline from which it did not recover until the 1890s. The major playwrights of the period were Otto Ludwig and Gustav Freytag. The lack of new dramatists was not keenly felt because the plays of Shakespeare, Lessing, Goethe, and Schiller were prominent in the repertory. The most important theatrical force in later 19th-century Germany was that of Georg II, Duke of Saxe-Meiningen and his Meiningen Ensemble, under the direction of Ludwig Chronegk. The Ensemble's productions are often considered the most historically accurate of the 19th century, although his primary goal was to serve the interests of the playwright. The Ensemble's productions used detailed, historically accurate costumes and furniture, something that was unprecedented in Europe at the time. The Meiningen Ensemble stands at the beginning of the new movement toward unified production (or what Richard Wagner would call the Gesamtkunstwerk) and the rise of the director (at the expense of the actor) as the dominant artist in theatre-making.
The Meiningen Ensemble traveled throughout Europe from 1874 to 1890 and met with unparalleled success wherever they went. Audiences had grown tired with regular, shallow entertainment theatre and were beginning to demand a more creatively and intellectually stimulating form of expression that the Ensemble was able to provide. Therefore, the Meiningen Ensemble can be seen as the forerunners of the art-theatre movement which appeared in Europe at the end of the 1880s.
Richard Wagner (1813–1883) rejected the contemporary trend toward realism and argued that the dramatist should be a myth maker who portrays an ideal world through the expression of inner impulses and aspirations of a people. Wagner used music to defeat performers' personal whims. The melody and tempo of music allowed him to have greater personal control over performance than he would with spoken drama. As with the Meininger Ensemble, Wagner believed that the author-composer should supervise every aspect of production to unify all the elements into a "master art work." Wagner also introduced a new type of auditorium that abolished the side boxes, pits, and galleries that were a prominent feature of most European theatres and replaced them with a 1,745 seat fan-shaped auditorium that was wide at the proscenium and at the rear. This allowed every seat in the auditorium to enjoy a full view of the stage and meant that there were no "good" seats.
Rise of realism in Russia
In Russia, Aleksandr Griboyedov, Alexander Pushkin, and Nikolai Polevoy were the most accomplished playwrights. As elsewhere, Russia was dominated by melodrama and musical theatre. More realistic drama began to emerge with the plays of Nikolai Gogol and the acting of Mikhail Shchepkin. Under close government supervision, the Russian theatre expanded considerably. Prince Alexander Shakhovskoy opened state theatres and training schools, attempted to raise the level of Russian production after a trip to Paris, and put in place regulations for governing troupes that remained in effect until 1917.
Realism began earlier in the 19th century in Russia than elsewhere in Europe and took a more uncompromising form. Beginning with the plays of Ivan Turgenev (who used "domestic detail to reveal inner turmoil"), Aleksandr Ostrovsky (who was Russia's first professional playwright), Aleksey Pisemsky (whose A Bitter Fate (1859) anticipated Naturalism), and Leo Tolstoy (whose The Power of Darkness (1886) is "one of the most effective of naturalistic plays"), a tradition of psychological realism in Russia culminated with the establishment of the Moscow Art Theatre by Konstantin Stanislavski and Vladimir Nemirovich-Danchenko.
Ostrovsky is often credited with creating a peculiarly Russian drama. His plays Enough Stupidity in Every Wise Man (1868) and The Storm (1859) draw on the life that he knew best, that of the middle class. Other important Russian playwrights of the 19th century include Alexander Sukhovo-Kobylin (whose Tarelkin's Death (1869) anticipated the Theatre of the Absurd) and Mikhail Saltykov-Shchedrin.
Naturalism and Realism
Naturalism, a theatrical movement born out of Charles Darwin's The Origin of Species (1859) and contemporary political and economic conditions, found its main proponent in Émile Zola. His essay "Naturalism in the Theatre" (1881) argued that poetry is everywhere instead of in the past or abstraction: "There is more poetry in the little apartment of a bourgeois than in all the empty worm-eaten palaces of history."
The realisation of Zola's ideas was hindered by a lack of capable dramatists writing naturalist drama. André Antoine emerged in the 1880s with his Théâtre Libre that was only open to members and therefore was exempt from censorship. He quickly won the approval of Zola and began to stage Naturalistic works and other foreign realistic pieces. Antoine was unique in his set design as he built sets with the "fourth wall" intact, only deciding which wall to remove later. The most important French playwrights of this period were given first hearing by Antoine including Georges Porto-Riche, François de Curel, and Eugène Brieux.
The work of Henry Arthur Jones and Arthur Wing Pinero initiated a new direction on the English stage. While their work paved the way, the development of more significant drama owes itself most to the playwright Henrik Ibsen.
Ibsen was born in Norway in 1828. He wrote 25 plays, the most famous of which are A Doll's House (1879), Ghosts (1881), The Wild Duck (1884), and Hedda Gabler (1890). A Doll's House and Ghosts shocked conservatives: Nora's departure in A Doll's House was viewed as an attack on family and home, while the allusions to venereal disease and sexual misconduct in Ghosts were considered deeply offensive to standards of public decency. Ibsen refined Scribe's well-made play formula to make it more fitting to the realistic style. He provided a model for writers of the realistic school. In addition, his works Rosmersholm (1886) and When We Dead Awaken (1899) evoke a sense of mysterious forces at work in human destiny, which was to be a major theme of symbolism and the so-called "Theatre of the Absurd".
After Ibsen, British theatre experienced revitalization with the work of George Bernard Shaw, Oscar Wilde, and (in fact from 1900) John Galsworthy. Unlike most of the gloomy and intensely serious work of their contemporaries, Shaw and Wilde wrote primarily in the comic form.
Technological Changes
Stage lighting
The eighteenth century theatre had been lit by candles and oil-lamps which were mainly provided for illumination so that the audience could see the performance, with no further purpose. This changed in the early 19th century with the introduction of gas lighting which was slowly adopted by the major theatres throughout the 1810s and 1820s to provide illumination for the house and the stage. The introduction of gas lighting revolutionized stage lighting. It provided a somewhat more natural and adequate light for the playing and the scenic space upstage of the proscenium arch. While there was no way to control the gas lights, this was soon to change as well. In Britain, theatres in London developed limelight for the stage in the late 1830s. In Paris, the electric carbon arc lamp first came into use in the 1840s. Both of these types of lighting were able to be hand-operated and could be focused by means of an attached lens, thus giving the theatre an ability to focus light on particular performers for the first time.
From the 1880s onwards, theatres began to be gradually electrified with the Savoy Theatre becoming the first theatre in the world to introduce a fully electrified theatrical lighting system in 1881. Richard D'Oyly Carte, who built the Savoy, explained why he had introduced electric light: "The greatest drawbacks to the enjoyment of the theatrical performances are, undoubtedly, the foul air and heat which pervade all theatres. As everyone knows, each gas-burner consumes as much oxygen as many people, and causes great heat beside. The incandescent lamps consume no oxygen, and cause no perceptible heat." Notably, the introduction of electric light coincided with the rise of realism: the new forms of lighting encouraged more realistic scenic detail and a subtler, more realistic acting style.
Scenic design
One of the most important scenic transition into the century was from the often-used two-dimensional scenic backdrop to three-dimensional sets. Previously, as a two-dimensional environment, scenery did not provide an embracing, physical environment for the dramatic action happening on stage. This changed when three-dimensional sets were introduced in the first half of the century. This, coupled with change in audience and stage dynamic as well as advancement in theatre architecture that allowed for hidden scene changes, the theatre became more representational instead of presentational, and invited audience to be transported to a conceived 'other' world. The early 19th century also saw the innovation of the moving panorama: a setting painted on a long cloth, which could be unrolled across the stage by turning spools, created an illusion of movement and changing locales.
See also
History of theatre
Nineteenth-century theatrical scenery
Twentieth-century theatre
References
Sources
19th-century theatre. Victoria and Albert Museum, 2015. Web. 1 November 2015.
Baily, Leslie (1956). The Gilbert and Sullivan Book (fourth ed.). London: Cassell. OCLC 21934871.
Banham, Martin, ed. 1998. The Cambridge Guide to Theatre. Cambridge: Cambridge UP. .
Baugh, Christopher (2005). Theatre, Performance and Technology. London: Palgrave Macmillan.
Benedetti, Jean. 1999. Stanislavski: His Life and Art. Revised edition. Original edition published in 1988. London: Methuen. .
---. 2005. The Art of the Actor: The Essential History of Acting, From Classical Times to the Present Day. London: Methuen. .
Booth, Michael R. 1995. 'Nineteenth-Century Theatre'. In John Russell Brown. 1995. The Oxford Illustrated History of Theatre. Oxford: Oxford University Press. .
Brockett, Oscar G. and Franklin J. Hildy. 2003. History of the Theatre. Ninth edition, International edition. Boston: Allyn and Bacon. .
Cardwell, Douglas (May 1983). "The Well-Made Play of Eugène Scribe". American Association of Teachers of French 56 (6): 878–879. Retrieved 12 May 2012.
Fischer-Lichte, Erika. 2001. History of European Drama and Theatre. New York: Taylor & Francis. .
Grimsted, David. 1968. Melodrama Unveiled: American Theatre and Culture, 1800–50. Chicago: U of Chicago P. .
"well-made play". Encyclopædia Britannica Online. Encyclopædia Britannica, 2015. Web. 1 November 2015.
Stephenson, Laura, et al. (2013). Forgotten Comedies of the 19th Century Theater. Clarion Publishing, Staunton, Va.. .
|
```java
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.activiti.examples.mgmt;
import java.util.Arrays;
import java.util.Map;
import org.activiti.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.common.engine.api.management.TableMetaData;
import org.flowable.engine.ManagementService;
/**
* Test case for the various operations of the {@link ManagementService}
*
* @author Tom Baeyens
* @author Joram Barrez
*/
public class ManagementServiceTest extends PluggableFlowableTestCase {
public void testTableCount() {
Map<String, Long> tableCount = managementService.getTableCount();
String tablePrefix = processEngineConfiguration.getDatabaseTablePrefix();
assertEquals(Long.valueOf(13), tableCount.get(tablePrefix + "ACT_GE_PROPERTY"));
assertEquals(Long.valueOf(0), tableCount.get(tablePrefix + "ACT_GE_BYTEARRAY"));
assertEquals(Long.valueOf(0), tableCount.get(tablePrefix + "ACT_RE_DEPLOYMENT"));
assertEquals(Long.valueOf(0), tableCount.get(tablePrefix + "ACT_RU_EXECUTION"));
assertEquals(Long.valueOf(0), tableCount.get(tablePrefix + "ACT_ID_GROUP"));
assertEquals(Long.valueOf(0), tableCount.get(tablePrefix + "ACT_ID_MEMBERSHIP"));
assertEquals(Long.valueOf(0), tableCount.get(tablePrefix + "ACT_ID_USER"));
assertEquals(Long.valueOf(0), tableCount.get(tablePrefix + "ACT_RE_PROCDEF"));
assertEquals(Long.valueOf(0), tableCount.get(tablePrefix + "ACT_RU_TASK"));
assertEquals(Long.valueOf(0), tableCount.get(tablePrefix + "ACT_RU_IDENTITYLINK"));
}
public void testGetTableMetaData() {
String tablePrefix = processEngineConfiguration.getDatabaseTablePrefix();
TableMetaData tableMetaData = managementService.getTableMetaData(tablePrefix + "ACT_RU_TASK");
assertEquals(tableMetaData.getColumnNames().size(), tableMetaData.getColumnTypes().size());
assertEquals(37, tableMetaData.getColumnNames().size());
int assigneeIndex = tableMetaData.getColumnNames().indexOf("ASSIGNEE_");
int createTimeIndex = tableMetaData.getColumnNames().indexOf("CREATE_TIME_");
assertTrue(assigneeIndex >= 0);
assertTrue(createTimeIndex >= 0);
assertOneOf(new String[] { "VARCHAR", "NVARCHAR2", "nvarchar", "NVARCHAR", "CHARACTER VARYING" }, tableMetaData.getColumnTypes().get(assigneeIndex));
assertOneOf(new String[] { "TIMESTAMP", "TIMESTAMP(6)", "datetime", "DATETIME" }, tableMetaData.getColumnTypes().get(createTimeIndex));
}
private void assertOneOf(String[] possibleValues, String currentValue) {
for (String value : possibleValues) {
if (currentValue.equals(value)) {
return;
}
}
fail("Value '" + currentValue + "' should be one of: " + Arrays.deepToString(possibleValues));
}
}
```
|
Altagonum tenuellum is a species in the beetle family Carabidae. It is found in New Guinea.
References
Altagonum
|
The Tromaville Café is a television program broadcast by the BBC in the United Kingdom from 1997 to 2000 that ran Troma films.
The show featured Lloyd Kaufman as himself, different actors portraying Toxie, Paul Kyrmse as Sgt. Kabukiman N.Y.P.D., Stephen Blackehart as Felix the French Trickster and scantily clad Tromettes (Debbie Rochon, Stephanie Stokes, Tiffany Shepis, etc.) playing waitress/action news reporters. Another regular on the show was Joe Fleishaker, who portrayed Troma VP and co-founder Michael Herz.
References
External links
BBC Television shows
Troma Entertainment films
Works by James Gunn
|
The First Somali Bank (FSB) is a bank headquartered in Mogadishu, Somalia.
Overview
FSB was established in May 2012 by Liban Abdi Egal. It is the first commercial bank to open in southern Somalia since 1991.
An Islamic financial institution, the bank offers personal banking, commercial banking, agency banking, mobile banking and internet banking. It also provides money transfer services to clients.
In mid-2012, the First Somali Bank organized its first ever Technology, Entertainment, Design (TEDx) conference. The event was launched to showcase improvements in local business, development and security to potential Somali and international investors.
Albert Falck was the first CEO of the bank from January 2012 to end of June 2012. He managed the product portfolio creation and launch of the bank.
See also
Central Bank of Somalia
Notes
External links
First Somali Bank
First Somali Bank Prospectus 2012
Banks of Somalia
Companies based in Mogadishu
2012 establishments in Somalia
Banks established in 2012
|
Battle Point () is a rocky and conspicuous coastal headland lying just below and southeast of Mount Dater on the east coast of Graham Land, Antarctica. This coastal area was photographed by several American expeditions: United States Antarctic Service, 1939–41; Ronne Antarctic Research Expedition, 1947–48; U.S. Navy photos, 1968. It was mapped by the British Antarctic Survey, 1963–64, and named by the UK Antarctic Place-Names Committee for Walter R.B. Battle (1919–53), British glaciologist who worked on problems of cirque erosion.
References
Headlands of Graham Land
Foyn Coast
|
The 1984 United States Senate election in Wyoming took place on November 6, 1984. Incumbent Republican U.S. Senator Alan Simpson was re-elected to a second term in office, defeating Democrat Victor Ryan in a landslide.
Republican primary
Candidates
Alan Simpson, incumbent Senator
Stephen Tarver
Results
Democratic primary
Candidates
Michael J. Dee, Republican candidate for U.S. Representative in 1982
Al Hamburg, perennial candidate
Victor Ryan, chemistry professor
Results
General election
Results
See also
1984 United States Senate elections
References
1984
Wyoming
United States Senate
|
Kwanza (The First) is an album by drummer Albert Heath featuring performances recorded in 1973 and originally released on the Muse label.
Reception
Andrew Gilbert of KQED says, "Kwanza captures a mid-career master with a long-established reputation as one of the most eloquent and adaptable drummers in jazz ... Heath wasn’t content to organize an all-star jam session. He’d been collaborating and studying composition with multi-instrumental explorer Yusef Lateef, and he used Kwanza to investigate some of the chamber music concepts he’d been working on". Jazz Views' Eddie Myer observed, "This album come replete with all kinds of modish innovations, from Swahili titles to 4/4 straight-8 rock rhythms, to guitar and rhodes from the youngest members".
Track listing
All compositions by Albert Heath, except Oops! by Percy Heath.
"Tafadhali" – 6:56
"A Notion" – 5:29
"Dr. JEH" – 6:22
"Dunia" – 4:01
"Oops!" – 6:33
"Sub-Set" – 10:11
Personnel
Albert Heath – drums, chimes, timpani
Curtis Fuller – trombone
Jimmy Heath – tenor saxophone, soprano saxophone, flute
Kenny Barron – piano, electric piano
Ted Dunbar – guitar
Percy Heath – bass
References
Muse Records albums
Albert Heath albums
1973 albums
Albums produced by Don Schlitten
|
```java
/*
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.apache.rocketmq.common.help;
public class FAQUrl {
public static final String APPLY_TOPIC_URL =
"path_to_url";
public static final String NAME_SERVER_ADDR_NOT_EXIST_URL =
"path_to_url";
public static final String GROUP_NAME_DUPLICATE_URL =
"path_to_url";
public static final String CLIENT_PARAMETER_CHECK_URL =
"path_to_url";
public static final String SUBSCRIPTION_GROUP_NOT_EXIST =
"path_to_url";
public static final String CLIENT_SERVICE_NOT_OK =
"path_to_url";
// FAQ: No route info of this topic, TopicABC
public static final String NO_TOPIC_ROUTE_INFO =
"path_to_url";
public static final String LOAD_JSON_EXCEPTION =
"path_to_url";
public static final String SAME_GROUP_DIFFERENT_TOPIC =
"path_to_url";
public static final String MQLIST_NOT_EXIST =
"path_to_url";
public static final String UNEXPECTED_EXCEPTION_URL =
"path_to_url";
public static final String SEND_MSG_FAILED =
"path_to_url";
public static final String UNKNOWN_HOST_EXCEPTION =
"path_to_url";
private static final String TIP_STRING_BEGIN = "\nSee ";
private static final String TIP_STRING_END = " for further details.";
public static String suggestTodo(final String url) {
StringBuilder sb = new StringBuilder();
sb.append(TIP_STRING_BEGIN);
sb.append(url);
sb.append(TIP_STRING_END);
return sb.toString();
}
public static String attachDefaultURL(final String errorMessage) {
if (errorMessage != null) {
int index = errorMessage.indexOf(TIP_STRING_BEGIN);
if (-1 == index) {
StringBuilder sb = new StringBuilder();
sb.append(errorMessage);
sb.append("\n");
sb.append("For more information, please visit the url, ");
sb.append(UNEXPECTED_EXCEPTION_URL);
return sb.toString();
}
}
return errorMessage;
}
}
```
|
```html
<!--
(See accompanying file LICENSE.md or copy at path_to_url
-->
<!-- boost-no-inspect -->
<!-- HTML header for doxygen 1.8.9.1-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "path_to_url">
<html xmlns="path_to_url">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Boost.Hana: boost/hana/filter.hpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
// (See accompanying file LICENSE.md or copy at path_to_url
MathJax.Hub.Config({
"HTML-CSS": {
linebreaks: {
automatic: true,
width: "75% container"
}
}
});
</script><script type="text/javascript" src="path_to_url"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<!-- Additional javascript for drawing charts. -->
<script type="text/javascript" src="highcharts.js"></script>
<script type="text/javascript" src="highcharts-data.js"></script>
<script type="text/javascript" src="highcharts-exporting.js"></script>
<script type="text/javascript" src="chart.js"></script>
<script type="text/javascript" src="hana.js"></script>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="Boost.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">Boost.Hana
 <span id="projectnumber">1.3.0</span>
</div>
<div id="projectbrief">Your standard library for metaprogramming</div>
</td>
<td> <div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('filter_8hpp.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#namespaces">Namespaces</a> </div>
<div class="headertitle">
<div class="title">filter.hpp File Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Defines <code><a class="el" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a" title="Filter a monadic structure using a custom predicate.Given a monadic structure and a predicate...">boost::hana::filter</a></code>.
<a href="#details">More...</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a>
Namespaces</h2></td></tr>
<tr class="memitem:namespaceboost_1_1hana"><td class="memItemLeft" align="right" valign="top">  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceboost_1_1hana.html">boost::hana</a></td></tr>
<tr class="memdesc:namespaceboost_1_1hana"><td class="mdescLeft"> </td><td class="mdescRight">Namespace containing everything in the library. <br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Defines <code><a class="el" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a" title="Filter a monadic structure using a custom predicate.Given a monadic structure and a predicate...">boost::hana::filter</a></code>. </p>
</div></div><!-- contents -->
</div><!-- doc-content -->
<!--
(See accompanying file LICENSE.md or copy at path_to_url
-->
<!-- boost-no-inspect -->
<!-- HTML footer for doxygen 1.8.9.1-->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_1878a3f4746a95c6aad317458cc7ef80.html">boost</a></li><li class="navelem"><a class="el" href="dir_daf74c896eae580804ddb7810f485dad.html">hana</a></li><li class="navelem"><a class="el" href="filter_8hpp.html">filter.hpp</a></li>
</ul>
</div>
</body>
</html>
```
|
```java
/*
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
/** Utilities for a Beam runner to interact with the pipeline proto representation. */
package org.apache.beam.runners.fnexecution.graph;
```
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="tab_titles">
<item></item>
<item></item>
</string-array>
<string-array name="playlist_category">
<item></item>
</string-array>
<string-array name="player_titles">
<item></item>
<item></item>
<item></item>
</string-array>
<string-array name="song_list">
<item></item>
<item></item>
</string-array>
<string-array name="love_list">
<item></item>
<item></item>
</string-array>
<string-array name="song_download">
<item></item>
<item></item>
</string-array>
<string-array name="info_music_mode">
<item></item>
<item></item>
<item></item>
</string-array>
<string-array name="info_music_mode_values">
<item>0</item>
<item>1</item>
<item>2</item>
</string-array>
<string-array name="info_secret_setting">
<item></item>
<item></item>
</string-array>
<array name="material_colors">
<item>#F44336</item>
<item>#9C27B0</item>
<item>#3F51B5</item>
<item>#03A9F4</item>
<item>#009688</item>
<item>#8BC34A</item>
<item>#FFEB3B</item>
<item>#FF9800</item>
<item>#795548</item>
<item>#607D8B</item>
</array>
<string-array name="pref_quality_select">
<item></item>
<item></item>
<item></item>
<item></item>
</string-array>
<string-array name="pref_quality_select_values">
<item>128</item>
<item>192</item>
<item>320</item>
<item>999</item>
</string-array>
<string-array name="pref_search_filter_select">
<item>@string/search_filter_qq</item>
<item>@string/search_filter_xiami</item>
<item>@string/search_filter_netease</item>
<item>@string/search_filter_baidu</item>
<item>@string/search_filter_repeat</item>
<item>@string/search_filter_cp</item>
</string-array>
<string-array name="pref_search_filter_values">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
</string-array>
</resources>
```
|
```java
package chapter3.section2;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 03/06/17.
*/
public class Exercise28_SoftwareCaching {
private class BinarySearchTree<Key extends Comparable<Key>, Value>{
private class Node {
private Key key;
private Value value;
private Node left;
private Node right;
private int size; //# of nodes in subtree rooted here
public Node(Key key, Value value, int size) {
this.key = key;
this.value = value;
this.size = size;
}
}
private Node root;
private Node cacheItem;
public int size() {
return size(root);
}
private int size(Node node) {
if (node == null) {
return 0;
}
return node.size;
}
public Value get(Key key) {
if (cacheItem != null && cacheItem.key == key) {
StdOut.println("Cache hit");
return cacheItem.value;
}
StdOut.println("Cache miss");
return get(root, key);
}
private Value get(Node node, Key key) {
if (node == null) {
return null;
}
int compare = key.compareTo(node.key);
if (compare < 0) {
return get(node.left, key);
} else if (compare > 0) {
return get(node.right, key);
} else {
cacheItem = node;
return node.value;
}
}
public void put(Key key, Value value) {
if (cacheItem != null && cacheItem.key == key) {
cacheItem.value = value;
StdOut.println("Cache hit");
return;
}
StdOut.println("Cache miss");
root = put(root, key, value);
}
private Node put(Node node, Key key, Value value) {
if (node == null) {
Node newNode = new Node(key, value, 1);
cacheItem = newNode;
return newNode;
}
int compare = key.compareTo(node.key);
if (compare < 0) {
node.left = put(node.left, key, value);
} else if (compare > 0) {
node.right = put(node.right, key, value);
} else {
node.value = value;
cacheItem = node;
}
node.size = size(node.left) + 1 + size(node.right);
return node;
}
public Key min() {
if (root == null) {
throw new NoSuchElementException("Empty binary search tree");
}
return min(root).key;
}
private Node min(Node node) {
if (node.left == null) {
cacheItem = node;
return node;
}
return min(node.left);
}
public Key max() {
if (root == null) {
throw new NoSuchElementException("Empty binary search tree");
}
return max(root).key;
}
private Node max(Node node) {
if (node.right == null) {
cacheItem = node;
return node;
}
return max(node.right);
}
public Key floor(Key key) {
Node node = floor(root, key);
if (node == null) {
return null;
}
cacheItem = node;
return node.key;
}
private Node floor(Node node, Key key) {
if (node == null) {
return null;
}
int compare = key.compareTo(node.key);
if (compare == 0) {
return node;
} else if (compare < 0) {
return floor(node.left, key);
} else {
Node rightNode = floor(node.right, key);
if (rightNode != null) {
return rightNode;
} else {
return node;
}
}
}
public Key ceiling(Key key) {
Node node = ceiling(root, key);
if (node == null) {
return null;
}
cacheItem = node;
return node.key;
}
private Node ceiling(Node node, Key key) {
if (node == null) {
return null;
}
int compare = key.compareTo(node.key);
if (compare == 0) {
return node;
} else if (compare > 0) {
return ceiling(node.right, key);
} else {
Node leftNode = ceiling(node.left, key);
if (leftNode != null) {
return leftNode;
} else {
return node;
}
}
}
public Key select(int index) {
if (index >= size()) {
throw new IllegalArgumentException("Index is higher than tree size");
}
return select(root, index).key;
}
private Node select(Node node, int index) {
int leftSubtreeSize = size(node.left);
if (leftSubtreeSize == index) {
cacheItem = node;
return node;
} else if (leftSubtreeSize > index) {
return select(node.left, index);
} else {
return select(node.right, index - leftSubtreeSize - 1);
}
}
public int rank(Key key) {
return rank(root, key);
}
private int rank(Node node, Key key) {
if (node == null) {
return 0;
}
//Returns the number of keys less than node.key in the subtree rooted at node
int compare = key.compareTo(node.key);
if (compare < 0) {
return rank(node.left, key);
} else if (compare > 0) {
return size(node.left) + 1 + rank(node.right, key);
} else {
cacheItem = node;
return size(node.left);
}
}
public void deleteMin() {
root = deleteMin(root);
}
private Node deleteMin(Node node) {
if (node == null) {
return null;
}
if (node.left == null) {
if (cacheItem != null && cacheItem == node) {
invalidateCache();
}
return node.right;
}
node.left = deleteMin(node.left);
node.size = size(node.left) + 1 + size(node.right);
return node;
}
public void deleteMax() {
root = deleteMax(root);
}
private Node deleteMax(Node node) {
if (node == null) {
return null;
}
if (node.right == null) {
if (cacheItem != null && cacheItem == node) {
invalidateCache();
}
return node.left;
}
node.right = deleteMax(node.right);
node.size = size(node.left) + 1 + size(node.right);
return node;
}
public void delete(Key key) {
if (cacheItem != null && cacheItem.key == key) {
invalidateCache();
}
root = delete(root, key);
}
private Node delete(Node node, Key key) {
if (node == null) {
return null;
}
int compare = key.compareTo(node.key);
if (compare < 0) {
node.left = delete(node.left, key);
} else if (compare > 0) {
node.right = delete(node.right, key);
} else {
if (node.left == null) {
return node.right;
} else if (node.right == null) {
return node.left;
} else {
Node aux = node;
node = min(aux.right);
node.right = deleteMin(aux.right);
node.left = aux.left;
}
}
node.size = size(node.left) + 1 + size(node.right);
return node;
}
public Iterable<Key> keys() {
return keys(min(), max());
}
public Iterable<Key> keys(Key low, Key high) {
Queue<Key> queue = new Queue<>();
keys(root, queue, low, high);
return queue;
}
private void keys(Node node, Queue<Key> queue, Key low, Key high) {
if (node == null) {
return;
}
int compareLow = low.compareTo(node.key);
int compareHigh = high.compareTo(node.key);
if (compareLow < 0) {
keys(node.left, queue, low, high);
}
if (compareLow <= 0 && compareHigh >= 0) {
queue.enqueue(node.key);
}
if (compareHigh > 0) {
keys(node.right, queue, low, high);
}
}
private void invalidateCache() {
cacheItem = null;
}
}
public static void main(String[] args) {
Exercise28_SoftwareCaching softwareCaching = new Exercise28_SoftwareCaching();
BinarySearchTree<Integer, String> binarySearchTree = softwareCaching.new BinarySearchTree<>();
for (int i = 0; i < 10; i++) {
binarySearchTree.put(i, "Value " + i);
}
//Cache on get operation
StdOut.println("\nGet key 2:");
binarySearchTree.get(2);
StdOut.println("Expected: cache miss");
StdOut.println("\nGet key 2:");
binarySearchTree.get(2);
StdOut.println("Expected: cache hit");
StdOut.println("\nDelete key 4:");
binarySearchTree.delete(4);
StdOut.println("\nGet key 7:");
binarySearchTree.get(7);
StdOut.println("Expected: cache miss");
StdOut.println("\nGet key 7:");
binarySearchTree.get(7);
StdOut.println("Expected: cache hit");
StdOut.println("\nDelete key 7:");
binarySearchTree.delete(7);
binarySearchTree.min();
StdOut.println("\nGet key 0:");
binarySearchTree.get(0);
StdOut.println("Expected: cache hit");
StdOut.println("\nGet key 9:");
binarySearchTree.get(9);
StdOut.println("Expected: cache miss");
binarySearchTree.select(3);
StdOut.println("\nGet key 3:");
binarySearchTree.get(3);
StdOut.println("Expected: cache hit");
binarySearchTree.max();
StdOut.println("\nGet key 9:");
binarySearchTree.get(9);
StdOut.println("Expected: cache hit");
}
}
```
|
```java
//
//
// path_to_url
//
// Unless required by applicable law or agreed to in writing, software
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.beust.jcommander.ParameterException;
import org.joda.money.Money;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link MoneyParameter}. */
class MoneyParameterTest {
private final MoneyParameter instance = new MoneyParameter();
@Test
void testConvert_withCurrency() {
assertThat(instance.convert("USD 777.99")).isEqualTo(Money.parse("USD 777.99"));
}
@Test
void testConvert_negative() {
assertThat(instance.convert("USD -777.99")).isEqualTo(Money.parse("USD -777.99"));
}
@Test
void testConvert_missingSpace_isForgiving() {
assertThat(instance.convert("USD777.99")).isEqualTo(Money.parse("USD 777.99"));
}
@Test
void testConvert_lowercase_isForgiving() {
assertThat(instance.convert("usd777.99")).isEqualTo(Money.parse("USD 777.99"));
}
@Test
void testConvert_badCurrency_throws() {
assertThrows(IllegalArgumentException.class, () -> instance.convert("FOO 1337"));
}
@Test
void testConvert_null_throws() {
assertThrows(NullPointerException.class, () -> instance.convert(null));
}
@Test
void testConvert_empty_throws() {
assertThrows(IllegalArgumentException.class, () -> instance.convert(""));
}
@Test
void testConvert_sillyString_throws() {
assertThrows(IllegalArgumentException.class, () -> instance.convert("foo"));
}
@Test
void testValidate_sillyString_throws() {
ParameterException thrown =
assertThrows(ParameterException.class, () -> instance.validate("--money", "foo"));
assertThat(thrown).hasMessageThat().contains("--money=foo not valid");
}
@Test
void testValidate_correctInput() {
instance.validate("--money", "USD 777");
}
}
```
|
```sqlpl
DROP TABLE IF EXISTS t_index_lazy_load;
CREATE TABLE t_index_lazy_load (a UInt64, b UInt64)
ENGINE = MergeTree ORDER BY (a, b)
SETTINGS index_granularity = 4, your_sha256_hash = 0.5;
INSERT INTO t_index_lazy_load SELECT number, number FROM numbers(10);
SELECT mark_number, a, b FROM mergeTreeIndex(currentDatabase(), t_index_lazy_load) ORDER BY mark_number;
DETACH TABLE t_index_lazy_load;
ATTACH TABLE t_index_lazy_load;
SELECT mark_number, a, b FROM mergeTreeIndex(currentDatabase(), t_index_lazy_load) ORDER BY mark_number;
DROP TABLE t_index_lazy_load;
```
|
Knut Hald (10 June 1902 – 12 January 1972) was a Norwegian businessperson, best known as chief executive of the Federation of Norwegian Industries from 1945 to 1965.
Career
He was born in Kristiania as a son of Ulrik Hald (1866–1939) and Kitty Wang. In 1932 he married Inger Marie Thorkildsen, a daughter of banker Sverre O. Thorkildsen.
After finishing his secondary education in 1920 and Kristiania Commerce School in 1921, he was employed in the Federation of Norwegian Industries. He was promoted to secretary in 1928, then subeditor of their magazine Norges Industri in 1935 and editor in 1939. In 1942 he became acting chief executive of the federation. In 1943 the federation was replaced by the Nazi authorities with Norges Næringssamband. After the Second World War, the Federation of Norwegian Industries resumed its activities, and Hald became chief executive. He retired in 1965.
Hald was vice chairman of the Norwegian Student Choral Society from 1937 to 1940 and 1942 to 1944, board member of Norwegian
Publications, Norges Varemesse and Nationaltheatret (from 1970), supervisory council member of Forsikringsselskapet Norden/Nordengruppen and Kreditkassen and working committee member in Norges Eksportråd. In politics, he was a member of the financial committee in Oslo Conservative Party.
He was decorated as a Knight, First Class of the Order of St. Olav in 1961. He died in January 1972.
References
1902 births
1972 deaths
Businesspeople from Oslo
20th-century Norwegian businesspeople
Norwegian magazine editors
20th-century Norwegian writers
|
```c
/*
* C Extension module to test Python interpreter C APIs.
*
* The 'test_*' functions exported by this module are run as part of the
* standard Python regression test, via Lib/test/test_capi.py.
*/
#include "Python.h"
#include <float.h>
#include "structmember.h"
#include "datetime.h"
#include "marshal.h"
#ifdef WITH_THREAD
#include "pythread.h"
#endif /* WITH_THREAD */
static PyObject *TestError; /* set to exception object in init */
/* Raise TestError with test_name + ": " + msg, and return NULL. */
static PyObject *
raiseTestError(const char* test_name, const char* msg)
{
char buf[2048];
if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50)
PyErr_SetString(TestError, "internal error msg too large");
else {
PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg);
PyErr_SetString(TestError, buf);
}
return NULL;
}
/* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
The ones derived from autoconf on the UNIX-like OSes can be relied
upon (in the absence of sloppy cross-compiling), but the Windows
platforms have these hardcoded. Better safe than sorry.
*/
static PyObject*
sizeof_error(const char* fatname, const char* typname,
int expected, int got)
{
char buf[1024];
PyOS_snprintf(buf, sizeof(buf),
"%.200s #define == %d but sizeof(%.200s) == %d",
fatname, expected, typname, got);
PyErr_SetString(TestError, buf);
return (PyObject*)NULL;
}
static PyObject*
test_config(PyObject *self)
{
#define CHECK_SIZEOF(FATNAME, TYPE) \
if (FATNAME != sizeof(TYPE)) \
return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE))
CHECK_SIZEOF(SIZEOF_SHORT, short);
CHECK_SIZEOF(SIZEOF_INT, int);
CHECK_SIZEOF(SIZEOF_LONG, long);
CHECK_SIZEOF(SIZEOF_VOID_P, void*);
CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
#ifdef HAVE_LONG_LONG
CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG);
#endif
#undef CHECK_SIZEOF
Py_INCREF(Py_None);
return Py_None;
}
static PyObject*
test_list_api(PyObject *self)
{
PyObject* list;
int i;
/* SF bug 132008: PyList_Reverse segfaults */
#define NLIST 30
list = PyList_New(NLIST);
if (list == (PyObject*)NULL)
return (PyObject*)NULL;
/* list = range(NLIST) */
for (i = 0; i < NLIST; ++i) {
PyObject* anint = PyInt_FromLong(i);
if (anint == (PyObject*)NULL) {
Py_DECREF(list);
return (PyObject*)NULL;
}
PyList_SET_ITEM(list, i, anint);
}
/* list.reverse(), via PyList_Reverse() */
i = PyList_Reverse(list); /* should not blow up! */
if (i != 0) {
Py_DECREF(list);
return (PyObject*)NULL;
}
/* Check that list == range(29, -1, -1) now */
for (i = 0; i < NLIST; ++i) {
PyObject* anint = PyList_GET_ITEM(list, i);
if (PyInt_AS_LONG(anint) != NLIST-1-i) {
PyErr_SetString(TestError,
"test_list_api: reverse screwed up");
Py_DECREF(list);
return (PyObject*)NULL;
}
}
Py_DECREF(list);
#undef NLIST
Py_INCREF(Py_None);
return Py_None;
}
static int
test_dict_inner(int count)
{
Py_ssize_t pos = 0, iterations = 0;
int i;
PyObject *dict = PyDict_New();
PyObject *v, *k;
if (dict == NULL)
return -1;
for (i = 0; i < count; i++) {
v = PyInt_FromLong(i);
PyDict_SetItem(dict, v, v);
Py_DECREF(v);
}
while (PyDict_Next(dict, &pos, &k, &v)) {
PyObject *o;
iterations++;
i = PyInt_AS_LONG(v) + 1;
o = PyInt_FromLong(i);
if (o == NULL)
return -1;
if (PyDict_SetItem(dict, k, o) < 0) {
Py_DECREF(o);
return -1;
}
Py_DECREF(o);
}
Py_DECREF(dict);
if (iterations != count) {
PyErr_SetString(
TestError,
"test_dict_iteration: dict iteration went wrong ");
return -1;
} else {
return 0;
}
}
static PyObject*
test_dict_iteration(PyObject* self)
{
int i;
for (i = 0; i < 200; i++) {
if (test_dict_inner(i) < 0) {
return NULL;
}
}
Py_INCREF(Py_None);
return Py_None;
}
/* Issue #4701: Check that PyObject_Hash implicitly calls
* PyType_Ready if it hasn't already been called
*/
static PyTypeObject _HashInheritanceTester_Type = {
PyObject_HEAD_INIT(NULL)
0, /* Number of items for varobject */
"hashinheritancetester", /* Name of this type */
sizeof(PyObject), /* Basic object size */
0, /* Item size for varobject */
(destructor)PyObject_Del, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
static PyObject*
test_lazy_hash_inheritance(PyObject* self)
{
PyTypeObject *type;
PyObject *obj;
long hash;
type = &_HashInheritanceTester_Type;
if (type->tp_dict != NULL)
/* The type has already been initialized. This probably means
-R is being used. */
Py_RETURN_NONE;
obj = PyObject_New(PyObject, type);
if (obj == NULL) {
PyErr_Clear();
PyErr_SetString(
TestError,
"test_lazy_hash_inheritance: failed to create object");
return NULL;
}
if (type->tp_dict != NULL) {
PyErr_SetString(
TestError,
"test_lazy_hash_inheritance: type initialised too soon");
Py_DECREF(obj);
return NULL;
}
hash = PyObject_Hash(obj);
if ((hash == -1) && PyErr_Occurred()) {
PyErr_Clear();
PyErr_SetString(
TestError,
"test_lazy_hash_inheritance: could not hash object");
Py_DECREF(obj);
return NULL;
}
if (type->tp_dict == NULL) {
PyErr_SetString(
TestError,
"test_lazy_hash_inheritance: type not initialised by hash()");
Py_DECREF(obj);
return NULL;
}
if (type->tp_hash != PyType_Type.tp_hash) {
PyErr_SetString(
TestError,
"test_lazy_hash_inheritance: unexpected hash function");
Py_DECREF(obj);
return NULL;
}
Py_DECREF(obj);
Py_RETURN_NONE;
}
/* Issue #7385: Check that memoryview() does not crash
* when bf_getbuffer returns an error
*/
static int
broken_buffer_getbuffer(PyObject *self, Py_buffer *view, int flags)
{
PyErr_SetString(
TestError,
"test_broken_memoryview: expected error in bf_getbuffer");
return -1;
}
static PyBufferProcs memoryviewtester_as_buffer = {
0, /* bf_getreadbuffer */
0, /* bf_getwritebuffer */
0, /* bf_getsegcount */
0, /* bf_getcharbuffer */
(getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */
0, /* bf_releasebuffer */
};
static PyTypeObject _MemoryViewTester_Type = {
PyObject_HEAD_INIT(NULL)
0, /* Number of items for varobject */
"memoryviewtester", /* Name of this type */
sizeof(PyObject), /* Basic object size */
0, /* Item size for varobject */
(destructor)PyObject_Del, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
&memoryviewtester_as_buffer, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
static PyObject*
test_broken_memoryview(PyObject* self)
{
PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type);
PyObject *res;
if (obj == NULL) {
PyErr_Clear();
PyErr_SetString(
TestError,
"test_broken_memoryview: failed to create object");
return NULL;
}
res = PyMemoryView_FromObject(obj);
if (res || !PyErr_Occurred()){
PyErr_SetString(
TestError,
"test_broken_memoryview: memoryview() didn't raise an Exception");
Py_XDECREF(res);
Py_DECREF(obj);
return NULL;
}
PyErr_Clear();
Py_DECREF(obj);
Py_RETURN_NONE;
}
static PyObject *
test_to_contiguous(PyObject* self, PyObject *noargs)
{
int data[9] = {0, -1, 1, -1, 2, -1, 3, -1, 4};
int result[5];
Py_ssize_t itemsize = sizeof(int);
Py_ssize_t shape = 5;
Py_ssize_t strides = 2 * itemsize;
Py_buffer view = {
data,
NULL,
5 * itemsize,
itemsize,
1,
1,
NULL,
&shape,
&strides,
NULL,
{0, 0},
NULL
};
int i;
PyBuffer_ToContiguous(result, &view, view.len, 'C');
for (i = 0; i < 5; i++) {
if (result[i] != i) {
PyErr_SetString(TestError,
"test_to_contiguous: incorrect result");
return NULL;
}
}
view.buf = &data[8];
view.strides[0] = -2 * itemsize;
PyBuffer_ToContiguous(result, &view, view.len, 'C');
for (i = 0; i < 5; i++) {
if (result[i] != 4-i) {
PyErr_SetString(TestError,
"test_to_contiguous: incorrect result");
return NULL;
}
}
Py_RETURN_NONE;
}
static PyObject *
test_from_contiguous(PyObject* self, PyObject *noargs)
{
int data[9] = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
int init[5] = {0, 1, 2, 3, 4};
Py_ssize_t itemsize = sizeof(int);
Py_ssize_t shape = 5;
Py_ssize_t strides = 2 * itemsize;
Py_buffer view = {
data,
NULL,
5 * itemsize,
itemsize,
1,
1,
NULL,
&shape,
&strides,
NULL,
{0, 0},
NULL
};
int *ptr;
int i;
PyBuffer_FromContiguous(&view, init, view.len, 'C');
ptr = view.buf;
for (i = 0; i < 5; i++) {
if (ptr[2*i] != i) {
PyErr_SetString(TestError,
"test_from_contiguous: incorrect result");
return NULL;
}
}
view.buf = &data[8];
view.strides[0] = -2 * itemsize;
PyBuffer_FromContiguous(&view, init, view.len, 'C');
ptr = view.buf;
for (i = 0; i < 5; i++) {
if (*(ptr-2*i) != i) {
PyErr_SetString(TestError,
"test_from_contiguous: incorrect result");
return NULL;
}
}
Py_RETURN_NONE;
}
/* Tests of PyLong_{As, From}{Unsigned,}Long(), and (#ifdef HAVE_LONG_LONG)
PyLong_{As, From}{Unsigned,}LongLong().
Note that the meat of the test is contained in testcapi_long.h.
This is revolting, but delicate code duplication is worse: "almost
exactly the same" code is needed to test PY_LONG_LONG, but the ubiquitous
dependence on type names makes it impossible to use a parameterized
function. A giant macro would be even worse than this. A C++ template
would be perfect.
The "report an error" functions are deliberately not part of the #include
file: if the test fails, you can set a breakpoint in the appropriate
error function directly, and crawl back from there in the debugger.
*/
#define UNBIND(X) Py_DECREF(X); (X) = NULL
static PyObject *
raise_test_long_error(const char* msg)
{
return raiseTestError("test_long_api", msg);
}
#define TESTNAME test_long_api_inner
#define TYPENAME long
#define F_S_TO_PY PyLong_FromLong
#define F_PY_TO_S PyLong_AsLong
#define F_U_TO_PY PyLong_FromUnsignedLong
#define F_PY_TO_U PyLong_AsUnsignedLong
#include "testcapi_long.h"
static PyObject *
test_long_api(PyObject* self)
{
return TESTNAME(raise_test_long_error);
}
#undef TESTNAME
#undef TYPENAME
#undef F_S_TO_PY
#undef F_PY_TO_S
#undef F_U_TO_PY
#undef F_PY_TO_U
#ifdef HAVE_LONG_LONG
static PyObject *
raise_test_longlong_error(const char* msg)
{
return raiseTestError("test_longlong_api", msg);
}
#define TESTNAME test_longlong_api_inner
#define TYPENAME PY_LONG_LONG
#define F_S_TO_PY PyLong_FromLongLong
#define F_PY_TO_S PyLong_AsLongLong
#define F_U_TO_PY PyLong_FromUnsignedLongLong
#define F_PY_TO_U PyLong_AsUnsignedLongLong
#include "testcapi_long.h"
static PyObject *
test_longlong_api(PyObject* self, PyObject *args)
{
return TESTNAME(raise_test_longlong_error);
}
#undef TESTNAME
#undef TYPENAME
#undef F_S_TO_PY
#undef F_PY_TO_S
#undef F_U_TO_PY
#undef F_PY_TO_U
/* Test the PyLong_AsLongAndOverflow API. General conversion to PY_LONG
is tested by test_long_api_inner. This test will concentrate on proper
handling of overflow.
*/
static PyObject *
test_long_and_overflow(PyObject *self)
{
PyObject *num, *one, *temp;
long value;
int overflow;
/* Test that overflow is set properly for a large value. */
/* num is a number larger than LONG_MAX even on 64-bit platforms */
num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
if (num == NULL)
return NULL;
overflow = 1234;
value = PyLong_AsLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != -1)
return raiseTestError("test_long_and_overflow",
"return value was not set to -1");
if (overflow != 1)
return raiseTestError("test_long_and_overflow",
"overflow was not set to 1");
/* Same again, with num = LONG_MAX + 1 */
num = PyLong_FromLong(LONG_MAX);
if (num == NULL)
return NULL;
one = PyLong_FromLong(1L);
if (one == NULL) {
Py_DECREF(num);
return NULL;
}
temp = PyNumber_Add(num, one);
Py_DECREF(one);
Py_DECREF(num);
num = temp;
if (num == NULL)
return NULL;
overflow = 0;
value = PyLong_AsLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != -1)
return raiseTestError("test_long_and_overflow",
"return value was not set to -1");
if (overflow != 1)
return raiseTestError("test_long_and_overflow",
"overflow was not set to 1");
/* Test that overflow is set properly for a large negative value. */
/* num is a number smaller than LONG_MIN even on 64-bit platforms */
num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
if (num == NULL)
return NULL;
overflow = 1234;
value = PyLong_AsLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != -1)
return raiseTestError("test_long_and_overflow",
"return value was not set to -1");
if (overflow != -1)
return raiseTestError("test_long_and_overflow",
"overflow was not set to -1");
/* Same again, with num = LONG_MIN - 1 */
num = PyLong_FromLong(LONG_MIN);
if (num == NULL)
return NULL;
one = PyLong_FromLong(1L);
if (one == NULL) {
Py_DECREF(num);
return NULL;
}
temp = PyNumber_Subtract(num, one);
Py_DECREF(one);
Py_DECREF(num);
num = temp;
if (num == NULL)
return NULL;
overflow = 0;
value = PyLong_AsLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != -1)
return raiseTestError("test_long_and_overflow",
"return value was not set to -1");
if (overflow != -1)
return raiseTestError("test_long_and_overflow",
"overflow was not set to -1");
/* Test that overflow is cleared properly for small values. */
num = PyLong_FromString("FF", NULL, 16);
if (num == NULL)
return NULL;
overflow = 1234;
value = PyLong_AsLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != 0xFF)
return raiseTestError("test_long_and_overflow",
"expected return value 0xFF");
if (overflow != 0)
return raiseTestError("test_long_and_overflow",
"overflow was not cleared");
num = PyLong_FromString("-FF", NULL, 16);
if (num == NULL)
return NULL;
overflow = 0;
value = PyLong_AsLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != -0xFF)
return raiseTestError("test_long_and_overflow",
"expected return value 0xFF");
if (overflow != 0)
return raiseTestError("test_long_and_overflow",
"overflow was set incorrectly");
num = PyLong_FromLong(LONG_MAX);
if (num == NULL)
return NULL;
overflow = 1234;
value = PyLong_AsLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != LONG_MAX)
return raiseTestError("test_long_and_overflow",
"expected return value LONG_MAX");
if (overflow != 0)
return raiseTestError("test_long_and_overflow",
"overflow was not cleared");
num = PyLong_FromLong(LONG_MIN);
if (num == NULL)
return NULL;
overflow = 0;
value = PyLong_AsLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != LONG_MIN)
return raiseTestError("test_long_and_overflow",
"expected return value LONG_MIN");
if (overflow != 0)
return raiseTestError("test_long_and_overflow",
"overflow was not cleared");
Py_INCREF(Py_None);
return Py_None;
}
/* Test the PyLong_AsLongLongAndOverflow API. General conversion to
PY_LONG_LONG is tested by test_long_api_inner. This test will
concentrate on proper handling of overflow.
*/
static PyObject *
test_long_long_and_overflow(PyObject *self)
{
PyObject *num, *one, *temp;
PY_LONG_LONG value;
int overflow;
/* Test that overflow is set properly for a large value. */
/* num is a number larger than PY_LLONG_MAX on a typical machine. */
num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
if (num == NULL)
return NULL;
overflow = 1234;
value = PyLong_AsLongLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != -1)
return raiseTestError("test_long_long_and_overflow",
"return value was not set to -1");
if (overflow != 1)
return raiseTestError("test_long_long_and_overflow",
"overflow was not set to 1");
/* Same again, with num = PY_LLONG_MAX + 1 */
num = PyLong_FromLongLong(PY_LLONG_MAX);
if (num == NULL)
return NULL;
one = PyLong_FromLong(1L);
if (one == NULL) {
Py_DECREF(num);
return NULL;
}
temp = PyNumber_Add(num, one);
Py_DECREF(one);
Py_DECREF(num);
num = temp;
if (num == NULL)
return NULL;
overflow = 0;
value = PyLong_AsLongLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != -1)
return raiseTestError("test_long_long_and_overflow",
"return value was not set to -1");
if (overflow != 1)
return raiseTestError("test_long_long_and_overflow",
"overflow was not set to 1");
/* Test that overflow is set properly for a large negative value. */
/* num is a number smaller than PY_LLONG_MIN on a typical platform */
num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
if (num == NULL)
return NULL;
overflow = 1234;
value = PyLong_AsLongLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != -1)
return raiseTestError("test_long_long_and_overflow",
"return value was not set to -1");
if (overflow != -1)
return raiseTestError("test_long_long_and_overflow",
"overflow was not set to -1");
/* Same again, with num = PY_LLONG_MIN - 1 */
num = PyLong_FromLongLong(PY_LLONG_MIN);
if (num == NULL)
return NULL;
one = PyLong_FromLong(1L);
if (one == NULL) {
Py_DECREF(num);
return NULL;
}
temp = PyNumber_Subtract(num, one);
Py_DECREF(one);
Py_DECREF(num);
num = temp;
if (num == NULL)
return NULL;
overflow = 0;
value = PyLong_AsLongLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != -1)
return raiseTestError("test_long_long_and_overflow",
"return value was not set to -1");
if (overflow != -1)
return raiseTestError("test_long_long_and_overflow",
"overflow was not set to -1");
/* Test that overflow is cleared properly for small values. */
num = PyLong_FromString("FF", NULL, 16);
if (num == NULL)
return NULL;
overflow = 1234;
value = PyLong_AsLongLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != 0xFF)
return raiseTestError("test_long_long_and_overflow",
"expected return value 0xFF");
if (overflow != 0)
return raiseTestError("test_long_long_and_overflow",
"overflow was not cleared");
num = PyLong_FromString("-FF", NULL, 16);
if (num == NULL)
return NULL;
overflow = 0;
value = PyLong_AsLongLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != -0xFF)
return raiseTestError("test_long_long_and_overflow",
"expected return value 0xFF");
if (overflow != 0)
return raiseTestError("test_long_long_and_overflow",
"overflow was set incorrectly");
num = PyLong_FromLongLong(PY_LLONG_MAX);
if (num == NULL)
return NULL;
overflow = 1234;
value = PyLong_AsLongLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != PY_LLONG_MAX)
return raiseTestError("test_long_long_and_overflow",
"expected return value PY_LLONG_MAX");
if (overflow != 0)
return raiseTestError("test_long_long_and_overflow",
"overflow was not cleared");
num = PyLong_FromLongLong(PY_LLONG_MIN);
if (num == NULL)
return NULL;
overflow = 0;
value = PyLong_AsLongLongAndOverflow(num, &overflow);
Py_DECREF(num);
if (value == -1 && PyErr_Occurred())
return NULL;
if (value != PY_LLONG_MIN)
return raiseTestError("test_long_long_and_overflow",
"expected return value PY_LLONG_MIN");
if (overflow != 0)
return raiseTestError("test_long_long_and_overflow",
"overflow was not cleared");
Py_INCREF(Py_None);
return Py_None;
}
/* Test the L code for PyArg_ParseTuple. This should deliver a PY_LONG_LONG
for both long and int arguments. The test may leak a little memory if
it fails.
*/
static PyObject *
test_L_code(PyObject *self)
{
PyObject *tuple, *num;
PY_LONG_LONG value;
tuple = PyTuple_New(1);
if (tuple == NULL)
return NULL;
num = PyLong_FromLong(42);
if (num == NULL)
return NULL;
PyTuple_SET_ITEM(tuple, 0, num);
value = -1;
if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
return NULL;
if (value != 42)
return raiseTestError("test_L_code",
"L code returned wrong value for long 42");
Py_DECREF(num);
num = PyInt_FromLong(42);
if (num == NULL)
return NULL;
PyTuple_SET_ITEM(tuple, 0, num);
value = -1;
if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
return NULL;
if (value != 42)
return raiseTestError("test_L_code",
"L code returned wrong value for int 42");
Py_DECREF(tuple);
Py_INCREF(Py_None);
return Py_None;
}
#endif /* ifdef HAVE_LONG_LONG */
static PyObject *
return_none(void *unused)
{
Py_RETURN_NONE;
}
static PyObject *
raise_error(void *unused)
{
PyErr_SetNone(PyExc_ValueError);
return NULL;
}
static int
test_buildvalue_N_error(const char *fmt)
{
PyObject *arg, *res;
arg = PyList_New(0);
if (arg == NULL) {
return -1;
}
Py_INCREF(arg);
res = Py_BuildValue(fmt, return_none, NULL, arg);
if (res == NULL) {
return -1;
}
Py_DECREF(res);
if (Py_REFCNT(arg) != 1) {
PyErr_Format(TestError, "test_buildvalue_N: "
"arg was not decrefed in successful "
"Py_BuildValue(\"%s\")", fmt);
return -1;
}
Py_INCREF(arg);
res = Py_BuildValue(fmt, raise_error, NULL, arg);
if (res != NULL || !PyErr_Occurred()) {
PyErr_Format(TestError, "test_buildvalue_N: "
"Py_BuildValue(\"%s\") didn't complain", fmt);
return -1;
}
PyErr_Clear();
if (Py_REFCNT(arg) != 1) {
PyErr_Format(TestError, "test_buildvalue_N: "
"arg was not decrefed in failed "
"Py_BuildValue(\"%s\")", fmt);
return -1;
}
Py_DECREF(arg);
return 0;
}
static PyObject *
test_buildvalue_N(PyObject *self, PyObject *noargs)
{
PyObject *arg, *res;
arg = PyList_New(0);
if (arg == NULL) {
return NULL;
}
Py_INCREF(arg);
res = Py_BuildValue("N", arg);
if (res == NULL) {
return NULL;
}
if (res != arg) {
return raiseTestError("test_buildvalue_N",
"Py_BuildValue(\"N\") returned wrong result");
}
if (Py_REFCNT(arg) != 2) {
return raiseTestError("test_buildvalue_N",
"arg was not decrefed in Py_BuildValue(\"N\")");
}
Py_DECREF(res);
Py_DECREF(arg);
if (test_buildvalue_N_error("O&N") < 0)
return NULL;
if (test_buildvalue_N_error("(O&N)") < 0)
return NULL;
if (test_buildvalue_N_error("[O&N]") < 0)
return NULL;
if (test_buildvalue_N_error("{O&N}") < 0)
return NULL;
if (test_buildvalue_N_error("{()O&(())N}") < 0)
return NULL;
Py_RETURN_NONE;
}
static PyObject *
get_args(PyObject *self, PyObject *args)
{
if (args == NULL) {
args = Py_None;
}
Py_INCREF(args);
return args;
}
static PyObject *
get_kwargs(PyObject *self, PyObject *args, PyObject *kwargs)
{
if (kwargs == NULL) {
kwargs = Py_None;
}
Py_INCREF(kwargs);
return kwargs;
}
/* Test tuple argument processing */
static PyObject *
getargs_tuple(PyObject *self, PyObject *args)
{
int a, b, c;
if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c))
return NULL;
return Py_BuildValue("iii", a, b, c);
}
/* test PyArg_ParseTupleAndKeywords */
static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL};
static char *fmt="(ii)i|(i(ii))(iii)i";
int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
&int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4],
&int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9]))
return NULL;
return Py_BuildValue("iiiiiiiiii",
int_args[0], int_args[1], int_args[2], int_args[3], int_args[4],
int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]);
}
/* Functions to call PyArg_ParseTuple with integer format codes,
and return the result.
*/
static PyObject *
getargs_b(PyObject *self, PyObject *args)
{
unsigned char value;
if (!PyArg_ParseTuple(args, "b", &value))
return NULL;
return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_B(PyObject *self, PyObject *args)
{
unsigned char value;
if (!PyArg_ParseTuple(args, "B", &value))
return NULL;
return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_h(PyObject *self, PyObject *args)
{
short value;
if (!PyArg_ParseTuple(args, "h", &value))
return NULL;
return PyLong_FromLong((long)value);
}
static PyObject *
getargs_H(PyObject *self, PyObject *args)
{
unsigned short value;
if (!PyArg_ParseTuple(args, "H", &value))
return NULL;
return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_I(PyObject *self, PyObject *args)
{
unsigned int value;
if (!PyArg_ParseTuple(args, "I", &value))
return NULL;
return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_k(PyObject *self, PyObject *args)
{
unsigned long value;
if (!PyArg_ParseTuple(args, "k", &value))
return NULL;
return PyLong_FromUnsignedLong(value);
}
static PyObject *
getargs_i(PyObject *self, PyObject *args)
{
int value;
if (!PyArg_ParseTuple(args, "i", &value))
return NULL;
return PyLong_FromLong((long)value);
}
static PyObject *
getargs_l(PyObject *self, PyObject *args)
{
long value;
if (!PyArg_ParseTuple(args, "l", &value))
return NULL;
return PyLong_FromLong(value);
}
static PyObject *
getargs_n(PyObject *self, PyObject *args)
{
Py_ssize_t value;
if (!PyArg_ParseTuple(args, "n", &value))
return NULL;
return PyInt_FromSsize_t(value);
}
#ifdef HAVE_LONG_LONG
static PyObject *
getargs_L(PyObject *self, PyObject *args)
{
PY_LONG_LONG value;
if (!PyArg_ParseTuple(args, "L", &value))
return NULL;
return PyLong_FromLongLong(value);
}
static PyObject *
getargs_K(PyObject *self, PyObject *args)
{
unsigned PY_LONG_LONG value;
if (!PyArg_ParseTuple(args, "K", &value))
return NULL;
return PyLong_FromUnsignedLongLong(value);
}
#endif
/* This function not only tests the 'k' getargs code, but also the
PyInt_AsUnsignedLongMask() and PyInt_AsUnsignedLongMask() functions. */
static PyObject *
test_k_code(PyObject *self)
{
PyObject *tuple, *num;
unsigned long value;
tuple = PyTuple_New(1);
if (tuple == NULL)
return NULL;
/* a number larger than ULONG_MAX even on 64-bit platforms */
num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
if (num == NULL)
return NULL;
value = PyInt_AsUnsignedLongMask(num);
if (value != ULONG_MAX)
return raiseTestError("test_k_code",
"PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
PyTuple_SET_ITEM(tuple, 0, num);
value = 0;
if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
return NULL;
if (value != ULONG_MAX)
return raiseTestError("test_k_code",
"k code returned wrong value for long 0xFFF...FFF");
Py_DECREF(num);
num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
if (num == NULL)
return NULL;
value = PyInt_AsUnsignedLongMask(num);
if (value != (unsigned long)-0x42)
return raiseTestError("test_k_code",
"PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
PyTuple_SET_ITEM(tuple, 0, num);
value = 0;
if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
return NULL;
if (value != (unsigned long)-0x42)
return raiseTestError("test_k_code",
"k code returned wrong value for long -0xFFF..000042");
Py_DECREF(tuple);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
getargs_f(PyObject *self, PyObject *args)
{
float f;
if (!PyArg_ParseTuple(args, "f", &f))
return NULL;
return PyFloat_FromDouble(f);
}
static PyObject *
getargs_d(PyObject *self, PyObject *args)
{
double d;
if (!PyArg_ParseTuple(args, "d", &d))
return NULL;
return PyFloat_FromDouble(d);
}
static PyObject *
getargs_D(PyObject *self, PyObject *args)
{
Py_complex cval;
if (!PyArg_ParseTuple(args, "D", &cval))
return NULL;
return PyComplex_FromCComplex(cval);
}
static PyObject *
getargs_S(PyObject *self, PyObject *args)
{
PyObject *obj;
if (!PyArg_ParseTuple(args, "S", &obj))
return NULL;
Py_INCREF(obj);
return obj;
}
static PyObject *
getargs_Y(PyObject *self, PyObject *args)
{
PyObject *obj;
if (!PyArg_ParseTuple(args, "Y", &obj))
return NULL;
Py_INCREF(obj);
return obj;
}
#ifdef Py_USING_UNICODE
static PyObject *
getargs_U(PyObject *self, PyObject *args)
{
PyObject *obj;
if (!PyArg_ParseTuple(args, "U", &obj))
return NULL;
Py_INCREF(obj);
return obj;
}
#endif
static PyObject *
getargs_c(PyObject *self, PyObject *args)
{
char c;
if (!PyArg_ParseTuple(args, "c", &c))
return NULL;
return PyInt_FromLong((unsigned char)c);
}
static PyObject *
getargs_s(PyObject *self, PyObject *args)
{
const char *str;
if (!PyArg_ParseTuple(args, "s", &str))
return NULL;
return PyBytes_FromString(str);
}
static PyObject *
getargs_s_star(PyObject *self, PyObject *args)
{
Py_buffer buffer;
PyObject *bytes;
if (!PyArg_ParseTuple(args, "s*", &buffer))
return NULL;
bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
return bytes;
}
static PyObject *
getargs_s_hash(PyObject *self, PyObject *args)
{
const char *str;
int size;
if (!PyArg_ParseTuple(args, "s#", &str, &size))
return NULL;
return PyBytes_FromStringAndSize(str, size);
}
static PyObject *
getargs_t_hash(PyObject *self, PyObject *args)
{
const char *str;
int size;
if (!PyArg_ParseTuple(args, "t#", &str, &size))
return NULL;
return PyBytes_FromStringAndSize(str, size);
}
static PyObject *
getargs_z(PyObject *self, PyObject *args)
{
const char *str;
if (!PyArg_ParseTuple(args, "z", &str))
return NULL;
if (str != NULL)
return PyBytes_FromString(str);
else
Py_RETURN_NONE;
}
static PyObject *
getargs_z_star(PyObject *self, PyObject *args)
{
Py_buffer buffer;
PyObject *bytes;
if (!PyArg_ParseTuple(args, "z*", &buffer))
return NULL;
if (buffer.buf != NULL)
bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
else {
Py_INCREF(Py_None);
bytes = Py_None;
}
PyBuffer_Release(&buffer);
return bytes;
}
static PyObject *
getargs_z_hash(PyObject *self, PyObject *args)
{
const char *str;
int size;
if (!PyArg_ParseTuple(args, "z#", &str, &size))
return NULL;
if (str != NULL)
return PyBytes_FromStringAndSize(str, size);
else
Py_RETURN_NONE;
}
static PyObject *
getargs_w(PyObject *self, PyObject *args)
{
char *str;
Py_ssize_t size;
if (!PyArg_ParseTuple(args, "wn", &str, &size))
return NULL;
if (2 <= size) {
str[0] = '[';
str[size-1] = ']';
}
return PyBytes_FromStringAndSize(str, size);
}
static PyObject *
getargs_w_hash(PyObject *self, PyObject *args)
{
char *str;
int size;
if (!PyArg_ParseTuple(args, "w#", &str, &size))
return NULL;
if (2 <= size) {
str[0] = '[';
str[size-1] = ']';
}
return PyBytes_FromStringAndSize(str, size);
}
static PyObject *
getargs_w_star(PyObject *self, PyObject *args)
{
Py_buffer buffer;
PyObject *result;
char *str;
if (!PyArg_ParseTuple(args, "w*", &buffer))
return NULL;
if (2 <= buffer.len) {
str = buffer.buf;
str[0] = '[';
str[buffer.len-1] = ']';
}
result = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
return result;
}
#ifdef Py_USING_UNICODE
static int
_ustrlen(const Py_UNICODE *u)
{
int i = 0;
const Py_UNICODE *v = u;
while (*v != 0) { i++; v++; }
return i;
}
static PyObject *
getargs_u(PyObject *self, PyObject *args)
{
const Py_UNICODE *str;
int size;
if (!PyArg_ParseTuple(args, "u", &str))
return NULL;
size = _ustrlen(str);
return PyUnicode_FromUnicode(str, size);
}
static PyObject *
getargs_u_hash(PyObject *self, PyObject *args)
{
const Py_UNICODE *str;
int size;
if (!PyArg_ParseTuple(args, "u#", &str, &size))
return NULL;
return PyUnicode_FromUnicode(str, size);
}
#endif
static PyObject *
getargs_es(PyObject *self, PyObject *args)
{
PyObject *arg, *result;
const char *encoding = NULL;
char *str;
if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
return NULL;
if (!PyArg_Parse(arg, "es", encoding, &str))
return NULL;
result = PyBytes_FromString(str);
PyMem_Free(str);
return result;
}
static PyObject *
getargs_et(PyObject *self, PyObject *args)
{
PyObject *arg, *result;
const char *encoding = NULL;
char *str;
if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
return NULL;
if (!PyArg_Parse(arg, "et", encoding, &str))
return NULL;
result = PyBytes_FromString(str);
PyMem_Free(str);
return result;
}
static PyObject *
getargs_es_hash(PyObject *self, PyObject *args)
{
PyObject *arg, *result;
const char *encoding = NULL;
PyByteArrayObject *buffer = NULL;
char *str = NULL;
int size;
if (!PyArg_ParseTuple(args, "O|sO!",
&arg, &encoding, &PyByteArray_Type, &buffer))
return NULL;
if (buffer != NULL) {
str = PyByteArray_AS_STRING(buffer);
size = PyByteArray_GET_SIZE(buffer);
}
if (!PyArg_Parse(arg, "es#", encoding, &str, &size))
return NULL;
result = PyBytes_FromStringAndSize(str, size);
if (buffer == NULL)
PyMem_Free(str);
return result;
}
static PyObject *
getargs_et_hash(PyObject *self, PyObject *args)
{
PyObject *arg, *result;
const char *encoding = NULL;
PyByteArrayObject *buffer = NULL;
char *str = NULL;
int size;
if (!PyArg_ParseTuple(args, "O|sO!",
&arg, &encoding, &PyByteArray_Type, &buffer))
return NULL;
if (buffer != NULL) {
str = PyByteArray_AS_STRING(buffer);
size = PyByteArray_GET_SIZE(buffer);
}
if (!PyArg_Parse(arg, "et#", encoding, &str, &size))
return NULL;
result = PyBytes_FromStringAndSize(str, size);
if (buffer == NULL)
PyMem_Free(str);
return result;
}
#ifdef Py_USING_UNICODE
static volatile int x;
/* Test the u and u# codes for PyArg_ParseTuple. May leak memory in case
of an error.
*/
static PyObject *
test_u_code(PyObject *self)
{
PyObject *tuple, *obj;
Py_UNICODE *value;
int len;
/* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
/* Just use the macro and check that it compiles */
x = Py_UNICODE_ISSPACE(25);
tuple = PyTuple_New(1);
if (tuple == NULL)
return NULL;
obj = PyUnicode_Decode("test", strlen("test"),
"ascii", NULL);
if (obj == NULL)
return NULL;
PyTuple_SET_ITEM(tuple, 0, obj);
value = 0;
if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0)
return NULL;
if (value != PyUnicode_AS_UNICODE(obj))
return raiseTestError("test_u_code",
"u code returned wrong value for u'test'");
value = 0;
if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0)
return NULL;
if (value != PyUnicode_AS_UNICODE(obj) ||
len != PyUnicode_GET_SIZE(obj))
return raiseTestError("test_u_code",
"u# code returned wrong values for u'test'");
Py_DECREF(tuple);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
test_widechar(PyObject *self)
{
#if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
size_t wtextlen = 1;
#else
const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
size_t wtextlen = 2;
#endif
PyObject *wide, *utf8;
wide = PyUnicode_FromWideChar(wtext, wtextlen);
if (wide == NULL)
return NULL;
utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d");
if (utf8 == NULL) {
Py_DECREF(wide);
return NULL;
}
if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) {
Py_DECREF(wide);
Py_DECREF(utf8);
return raiseTestError("test_widechar",
"wide string and utf8 string have different length");
}
if (PyUnicode_Compare(wide, utf8)) {
Py_DECREF(wide);
Py_DECREF(utf8);
if (PyErr_Occurred())
return NULL;
return raiseTestError("test_widechar",
"wide string and utf8 string are differents");
}
Py_DECREF(wide);
Py_DECREF(utf8);
Py_RETURN_NONE;
}
static PyObject *
unicode_encodedecimal(PyObject *self, PyObject *args)
{
Py_UNICODE *unicode;
int length;
char *errors = NULL;
PyObject *decimal;
Py_ssize_t decimal_length, new_length;
int res;
if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length, &errors))
return NULL;
decimal_length = length * 10; /* len('') */
decimal = PyBytes_FromStringAndSize(NULL, decimal_length);
if (decimal == NULL)
return NULL;
res = PyUnicode_EncodeDecimal(unicode, length,
PyBytes_AS_STRING(decimal),
errors);
if (res < 0) {
Py_DECREF(decimal);
return NULL;
}
new_length = strlen(PyBytes_AS_STRING(decimal));
assert(new_length <= decimal_length);
res = _PyBytes_Resize(&decimal, new_length);
if (res < 0)
return NULL;
return decimal;
}
static PyObject *
test_empty_argparse(PyObject *self)
{
/* Test that formats can begin with '|'. See issue #4720. */
PyObject *tuple, *dict = NULL;
static char *kwlist[] = {NULL};
int result;
tuple = PyTuple_New(0);
if (!tuple)
return NULL;
if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0)
goto done;
dict = PyDict_New();
if (!dict)
goto done;
result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
done:
Py_DECREF(tuple);
Py_XDECREF(dict);
if (result < 0)
return NULL;
else {
Py_RETURN_NONE;
}
}
static PyObject *
codec_incrementalencoder(PyObject *self, PyObject *args)
{
const char *encoding, *errors = NULL;
if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder",
&encoding, &errors))
return NULL;
return PyCodec_IncrementalEncoder(encoding, errors);
}
static PyObject *
codec_incrementaldecoder(PyObject *self, PyObject *args)
{
const char *encoding, *errors = NULL;
if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder",
&encoding, &errors))
return NULL;
return PyCodec_IncrementalDecoder(encoding, errors);
}
#endif
/* Simple test of _PyLong_NumBits and _PyLong_Sign. */
static PyObject *
test_long_numbits(PyObject *self)
{
struct triple {
long input;
size_t nbits;
int sign;
} testcases[] = {{0, 0, 0},
{1L, 1, 1},
{-1L, 1, -1},
{2L, 2, 1},
{-2L, 2, -1},
{3L, 2, 1},
{-3L, 2, -1},
{4L, 3, 1},
{-4L, 3, -1},
{0x7fffL, 15, 1}, /* one Python long digit */
{-0x7fffL, 15, -1},
{0xffffL, 16, 1},
{-0xffffL, 16, -1},
{0xfffffffL, 28, 1},
{-0xfffffffL, 28, -1}};
int i;
for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) {
PyObject *plong = PyLong_FromLong(testcases[i].input);
size_t nbits = _PyLong_NumBits(plong);
int sign = _PyLong_Sign(plong);
Py_DECREF(plong);
if (nbits != testcases[i].nbits)
return raiseTestError("test_long_numbits",
"wrong result for _PyLong_NumBits");
if (sign != testcases[i].sign)
return raiseTestError("test_long_numbits",
"wrong result for _PyLong_Sign");
}
Py_INCREF(Py_None);
return Py_None;
}
/* Example passing NULLs to PyObject_Str(NULL) and PyObject_Unicode(NULL). */
static PyObject *
test_null_strings(PyObject *self)
{
PyObject *o1 = PyObject_Str(NULL);
#ifdef Py_USING_UNICODE
PyObject *o2 = PyObject_Unicode(NULL);
#else
PyObject *o2 = PyObject_Str(NULL);
#endif
PyObject *tuple = PyTuple_Pack(2, o1, o2);
Py_XDECREF(o1);
Py_XDECREF(o2);
return tuple;
}
static PyObject *
raise_exception(PyObject *self, PyObject *args)
{
PyObject *exc;
PyObject *exc_args, *v;
int num_args, i;
if (!PyArg_ParseTuple(args, "Oi:raise_exception",
&exc, &num_args))
return NULL;
if (!PyExceptionClass_Check(exc)) {
PyErr_Format(PyExc_TypeError, "an exception class is required");
return NULL;
}
exc_args = PyTuple_New(num_args);
if (exc_args == NULL)
return NULL;
for (i = 0; i < num_args; ++i) {
v = PyInt_FromLong(i);
if (v == NULL) {
Py_DECREF(exc_args);
return NULL;
}
PyTuple_SET_ITEM(exc_args, i, v);
}
PyErr_SetObject(exc, exc_args);
Py_DECREF(exc_args);
return NULL;
}
static PyObject *
set_errno(PyObject *self, PyObject *args)
{
int new_errno;
if (!PyArg_ParseTuple(args, "i:set_errno", &new_errno))
return NULL;
errno = new_errno;
Py_RETURN_NONE;
}
#ifdef Py_USING_UNICODE
static int test_run_counter = 0;
static PyObject *
test_datetime_capi(PyObject *self, PyObject *args) {
if (PyDateTimeAPI) {
if (test_run_counter) {
/* Probably regrtest.py -R */
Py_RETURN_NONE;
}
else {
PyErr_SetString(PyExc_AssertionError,
"PyDateTime_CAPI somehow initialized");
return NULL;
}
}
test_run_counter++;
PyDateTime_IMPORT;
if (PyDateTimeAPI)
Py_RETURN_NONE;
else
return NULL;
}
#endif
#ifdef WITH_THREAD
/* test_thread_state spawns a thread of its own, and that thread releases
* `thread_done` when it's finished. The driver code has to know when the
* thread finishes, because the thread uses a PyObject (the callable) that
* may go away when the driver finishes. The former lack of this explicit
* synchronization caused rare segfaults, so rare that they were seen only
* on a Mac buildbot (although they were possible on any box).
*/
static PyThread_type_lock thread_done = NULL;
static int
_make_call(void *callable)
{
PyObject *rc;
int success;
PyGILState_STATE s = PyGILState_Ensure();
rc = PyObject_CallFunction((PyObject *)callable, "");
success = (rc != NULL);
Py_XDECREF(rc);
PyGILState_Release(s);
return success;
}
/* Same thing, but releases `thread_done` when it returns. This variant
* should be called only from threads spawned by test_thread_state().
*/
static void
_make_call_from_thread(void *callable)
{
_make_call(callable);
PyThread_release_lock(thread_done);
}
static PyObject *
test_thread_state(PyObject *self, PyObject *args)
{
PyObject *fn;
int success = 1;
if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
return NULL;
if (!PyCallable_Check(fn)) {
PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
fn->ob_type->tp_name);
return NULL;
}
/* Ensure Python is set up for threading */
PyEval_InitThreads();
thread_done = PyThread_allocate_lock();
if (thread_done == NULL)
return PyErr_NoMemory();
PyThread_acquire_lock(thread_done, 1);
/* Start a new thread with our callback. */
PyThread_start_new_thread(_make_call_from_thread, fn);
/* Make the callback with the thread lock held by this thread */
success &= _make_call(fn);
/* Do it all again, but this time with the thread-lock released */
Py_BEGIN_ALLOW_THREADS
success &= _make_call(fn);
PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
Py_END_ALLOW_THREADS
/* And once more with and without a thread
XXX - should use a lock and work out exactly what we are trying
to test <wink>
*/
Py_BEGIN_ALLOW_THREADS
PyThread_start_new_thread(_make_call_from_thread, fn);
success &= _make_call(fn);
PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
Py_END_ALLOW_THREADS
/* Release lock we acquired above. This is required on HP-UX. */
PyThread_release_lock(thread_done);
PyThread_free_lock(thread_done);
if (!success)
return NULL;
Py_RETURN_NONE;
}
/* test Py_AddPendingCalls using threads */
static int _pending_callback(void *arg)
{
/* we assume the argument is callable object to which we own a reference */
PyObject *callable = (PyObject *)arg;
PyObject *r = PyObject_CallObject(callable, NULL);
Py_DECREF(callable);
Py_XDECREF(r);
return r != NULL ? 0 : -1;
}
/* The following requests n callbacks to _pending_callback. It can be
* run from any python thread.
*/
PyObject *pending_threadfunc(PyObject *self, PyObject *arg)
{
PyObject *callable;
int r;
if (PyArg_ParseTuple(arg, "O", &callable) == 0)
return NULL;
/* create the reference for the callbackwhile we hold the lock */
Py_INCREF(callable);
Py_BEGIN_ALLOW_THREADS
r = Py_AddPendingCall(&_pending_callback, callable);
Py_END_ALLOW_THREADS
if (r<0) {
Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
Py_INCREF(Py_False);
return Py_False;
}
Py_INCREF(Py_True);
return Py_True;
}
#endif
/* Some tests of PyString_FromFormat(). This needs more tests. */
static PyObject *
test_string_from_format(PyObject *self, PyObject *args)
{
PyObject *result;
char *msg;
#define CHECK_1_FORMAT(FORMAT, TYPE) \
result = PyString_FromFormat(FORMAT, (TYPE)1); \
if (result == NULL) \
return NULL; \
if (strcmp(PyString_AsString(result), "1")) { \
msg = FORMAT " failed at 1"; \
goto Fail; \
} \
Py_DECREF(result)
CHECK_1_FORMAT("%d", int);
CHECK_1_FORMAT("%ld", long);
/* The z width modifier was added in Python 2.5. */
CHECK_1_FORMAT("%zd", Py_ssize_t);
/* The u type code was added in Python 2.5. */
CHECK_1_FORMAT("%u", unsigned int);
CHECK_1_FORMAT("%lu", unsigned long);
CHECK_1_FORMAT("%zu", size_t);
/* "%lld" and "%llu" support added in Python 2.7. */
#ifdef HAVE_LONG_LONG
CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG);
CHECK_1_FORMAT("%lld", PY_LONG_LONG);
#endif
Py_RETURN_NONE;
Fail:
Py_XDECREF(result);
return raiseTestError("test_string_from_format", msg);
#undef CHECK_1_FORMAT
}
/* Coverage testing of capsule objects. */
static const char *capsule_name = "capsule name";
static char *capsule_pointer = "capsule pointer";
static char *capsule_context = "capsule context";
static const char *capsule_error = NULL;
static int
capsule_destructor_call_count = 0;
static void
capsule_destructor(PyObject *o) {
capsule_destructor_call_count++;
if (PyCapsule_GetContext(o) != capsule_context) {
capsule_error = "context did not match in destructor!";
} else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
capsule_error = "destructor did not match in destructor! (woah!)";
} else if (PyCapsule_GetName(o) != capsule_name) {
capsule_error = "name did not match in destructor!";
} else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
capsule_error = "pointer did not match in destructor!";
}
}
typedef struct {
char *name;
char *module;
char *attribute;
} known_capsule;
static PyObject *
test_capsule(PyObject *self, PyObject *args)
{
PyObject *object;
const char *error = NULL;
void *pointer;
void *pointer2;
known_capsule known_capsules[] = {
#define KNOWN_CAPSULE(module, name) { module "." name, module, name }
KNOWN_CAPSULE("_socket", "CAPI"),
KNOWN_CAPSULE("_curses", "_C_API"),
KNOWN_CAPSULE("datetime", "datetime_CAPI"),
{ NULL, NULL },
};
known_capsule *known = &known_capsules[0];
#define FAIL(x) { error = (x); goto exit; }
#define CHECK_DESTRUCTOR \
if (capsule_error) { \
FAIL(capsule_error); \
} \
else if (!capsule_destructor_call_count) { \
FAIL("destructor not called!"); \
} \
capsule_destructor_call_count = 0; \
object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
PyCapsule_SetContext(object, capsule_context);
capsule_destructor(object);
CHECK_DESTRUCTOR;
Py_DECREF(object);
CHECK_DESTRUCTOR;
object = PyCapsule_New(known, "ignored", NULL);
PyCapsule_SetPointer(object, capsule_pointer);
PyCapsule_SetName(object, capsule_name);
PyCapsule_SetDestructor(object, capsule_destructor);
PyCapsule_SetContext(object, capsule_context);
capsule_destructor(object);
CHECK_DESTRUCTOR;
/* intentionally access using the wrong name */
pointer2 = PyCapsule_GetPointer(object, "the wrong name");
if (!PyErr_Occurred()) {
FAIL("PyCapsule_GetPointer should have failed but did not!");
}
PyErr_Clear();
if (pointer2) {
if (pointer2 == capsule_pointer) {
FAIL("PyCapsule_GetPointer should not have"
" returned the internal pointer!");
} else {
FAIL("PyCapsule_GetPointer should have "
"returned NULL pointer but did not!");
}
}
PyCapsule_SetDestructor(object, NULL);
Py_DECREF(object);
if (capsule_destructor_call_count) {
FAIL("destructor called when it should not have been!");
}
for (known = &known_capsules[0]; known->module != NULL; known++) {
/* yeah, ordinarily I wouldn't do this either,
but it's fine for this test harness.
*/
static char buffer[256];
#undef FAIL
#define FAIL(x) \
{ \
sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
x, known->module, known->attribute); \
error = buffer; \
goto exit; \
} \
PyObject *module = PyImport_ImportModule(known->module);
if (module) {
pointer = PyCapsule_Import(known->name, 0);
if (!pointer) {
Py_DECREF(module);
FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
}
object = PyObject_GetAttrString(module, known->attribute);
if (!object) {
Py_DECREF(module);
return NULL;
}
pointer2 = PyCapsule_GetPointer(object,
"weebles wobble but they don't fall down");
if (!PyErr_Occurred()) {
Py_DECREF(object);
Py_DECREF(module);
FAIL("PyCapsule_GetPointer should have failed but did not!");
}
PyErr_Clear();
if (pointer2) {
Py_DECREF(module);
Py_DECREF(object);
if (pointer2 == pointer) {
FAIL("PyCapsule_GetPointer should not have"
" returned its internal pointer!");
} else {
FAIL("PyCapsule_GetPointer should have"
" returned NULL pointer but did not!");
}
}
Py_DECREF(object);
Py_DECREF(module);
}
else
PyErr_Clear();
}
exit:
if (error) {
return raiseTestError("test_capsule", error);
}
Py_RETURN_NONE;
#undef FAIL
}
/* This is here to provide a docstring for test_descr. */
static PyObject *
test_with_docstring(PyObject *self)
{
Py_RETURN_NONE;
}
/* To test the format of tracebacks as printed out. */
static PyObject *
traceback_print(PyObject *self, PyObject *args)
{
PyObject *file;
PyObject *traceback;
int result;
if (!PyArg_ParseTuple(args, "OO:traceback_print",
&traceback, &file))
return NULL;
result = PyTraceBack_Print(traceback, file);
if (result < 0)
return NULL;
Py_RETURN_NONE;
}
/* To test that the result of PyCode_NewEmpty has the right members. */
static PyObject *
code_newempty(PyObject *self, PyObject *args)
{
const char *filename;
const char *funcname;
int firstlineno;
if (!PyArg_ParseTuple(args, "ssi:code_newempty",
&filename, &funcname, &firstlineno))
return NULL;
return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno);
}
/* Test PyErr_NewExceptionWithDoc (also exercise PyErr_NewException).
Run via Lib/test/test_exceptions.py */
static PyObject *
make_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs)
{
char *name;
char *doc = NULL;
PyObject *base = NULL;
PyObject *dict = NULL;
static char *kwlist[] = {"name", "doc", "base", "dict", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"s|sOO:make_exception_with_doc", kwlist,
&name, &doc, &base, &dict))
return NULL;
return PyErr_NewExceptionWithDoc(name, doc, base, dict);
}
static PyObject *
sequence_delitem(PyObject *self, PyObject *args)
{
PyObject *seq;
Py_ssize_t i;
if (!PyArg_ParseTuple(args, "On", &seq, &i))
return NULL;
if (PySequence_DelItem(seq, i) < 0)
return NULL;
Py_RETURN_NONE;
}
#ifdef WITH_THREAD
typedef struct {
PyThread_type_lock start_event;
PyThread_type_lock exit_event;
PyObject *callback;
} test_c_thread_t;
static void
temporary_c_thread(void *data)
{
test_c_thread_t *test_c_thread = data;
PyGILState_STATE state;
PyObject *res;
PyThread_release_lock(test_c_thread->start_event);
/* Allocate a Python thread state for this thread */
state = PyGILState_Ensure();
res = PyObject_CallFunction(test_c_thread->callback, "", NULL);
Py_CLEAR(test_c_thread->callback);
if (res == NULL) {
PyErr_Print();
}
else {
Py_DECREF(res);
}
/* Destroy the Python thread state for this thread */
PyGILState_Release(state);
PyThread_release_lock(test_c_thread->exit_event);
PyThread_exit_thread();
}
static PyObject *
call_in_temporary_c_thread(PyObject *self, PyObject *callback)
{
PyObject *res = NULL;
test_c_thread_t test_c_thread;
long thread;
PyEval_InitThreads();
test_c_thread.start_event = PyThread_allocate_lock();
test_c_thread.exit_event = PyThread_allocate_lock();
test_c_thread.callback = NULL;
if (!test_c_thread.start_event || !test_c_thread.exit_event) {
PyErr_SetString(PyExc_RuntimeError, "could not allocate lock");
goto exit;
}
Py_INCREF(callback);
test_c_thread.callback = callback;
PyThread_acquire_lock(test_c_thread.start_event, 1);
PyThread_acquire_lock(test_c_thread.exit_event, 1);
thread = PyThread_start_new_thread(temporary_c_thread, &test_c_thread);
if (thread == -1) {
PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
PyThread_release_lock(test_c_thread.start_event);
PyThread_release_lock(test_c_thread.exit_event);
goto exit;
}
PyThread_acquire_lock(test_c_thread.start_event, 1);
PyThread_release_lock(test_c_thread.start_event);
Py_BEGIN_ALLOW_THREADS
PyThread_acquire_lock(test_c_thread.exit_event, 1);
PyThread_release_lock(test_c_thread.exit_event);
Py_END_ALLOW_THREADS
Py_INCREF(Py_None);
res = Py_None;
exit:
Py_CLEAR(test_c_thread.callback);
if (test_c_thread.start_event)
PyThread_free_lock(test_c_thread.start_event);
if (test_c_thread.exit_event)
PyThread_free_lock(test_c_thread.exit_event);
return res;
}
#endif /* WITH_THREAD */
/* marshal */
static PyObject*
pymarshal_write_long_to_file(PyObject* self, PyObject *args)
{
long value;
char *filename;
int version;
FILE *fp;
if (!PyArg_ParseTuple(args, "lsi:pymarshal_write_long_to_file",
&value, &filename, &version))
return NULL;
fp = fopen(filename, "wb");
if (fp == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
PyMarshal_WriteLongToFile(value, fp, version);
fclose(fp);
if (PyErr_Occurred())
return NULL;
Py_RETURN_NONE;
}
static PyObject*
pymarshal_write_object_to_file(PyObject* self, PyObject *args)
{
PyObject *obj;
char *filename;
int version;
FILE *fp;
if (!PyArg_ParseTuple(args, "Osi:pymarshal_write_object_to_file",
&obj, &filename, &version))
return NULL;
fp = fopen(filename, "wb");
if (fp == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
PyMarshal_WriteObjectToFile(obj, fp, version);
fclose(fp);
if (PyErr_Occurred())
return NULL;
Py_RETURN_NONE;
}
static PyObject*
pymarshal_read_short_from_file(PyObject* self, PyObject *args)
{
int value;
long pos;
char *filename;
FILE *fp;
if (!PyArg_ParseTuple(args, "s:pymarshal_read_short_from_file", &filename))
return NULL;
fp = fopen(filename, "rb");
if (fp == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
value = PyMarshal_ReadShortFromFile(fp);
pos = ftell(fp);
fclose(fp);
if (PyErr_Occurred())
return NULL;
return Py_BuildValue("il", value, pos);
}
static PyObject*
pymarshal_read_long_from_file(PyObject* self, PyObject *args)
{
long value, pos;
char *filename;
FILE *fp;
if (!PyArg_ParseTuple(args, "s:pymarshal_read_long_from_file", &filename))
return NULL;
fp = fopen(filename, "rb");
if (fp == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
value = PyMarshal_ReadLongFromFile(fp);
pos = ftell(fp);
fclose(fp);
if (PyErr_Occurred())
return NULL;
return Py_BuildValue("ll", value, pos);
}
static PyObject*
pymarshal_read_last_object_from_file(PyObject* self, PyObject *args)
{
PyObject *obj;
long pos;
char *filename;
FILE *fp;
if (!PyArg_ParseTuple(args, "s:pymarshal_read_last_object_from_file", &filename))
return NULL;
fp = fopen(filename, "rb");
if (fp == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
obj = PyMarshal_ReadLastObjectFromFile(fp);
pos = ftell(fp);
fclose(fp);
return Py_BuildValue("Nl", obj, pos);
}
static PyObject*
pymarshal_read_object_from_file(PyObject* self, PyObject *args)
{
PyObject *obj;
long pos;
char *filename;
FILE *fp;
if (!PyArg_ParseTuple(args, "s:pymarshal_read_object_from_file", &filename))
return NULL;
fp = fopen(filename, "rb");
if (fp == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
obj = PyMarshal_ReadObjectFromFile(fp);
pos = ftell(fp);
fclose(fp);
return Py_BuildValue("Nl", obj, pos);
}
static PyMethodDef TestMethods[] = {
{"raise_exception", raise_exception, METH_VARARGS},
{"set_errno", set_errno, METH_VARARGS},
{"test_config", (PyCFunction)test_config, METH_NOARGS},
#ifdef Py_USING_UNICODE
{"test_datetime_capi", test_datetime_capi, METH_NOARGS},
#endif
{"test_list_api", (PyCFunction)test_list_api, METH_NOARGS},
{"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS},
{"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
{"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS},
{"test_to_contiguous", (PyCFunction)test_to_contiguous, METH_NOARGS},
{"test_from_contiguous", (PyCFunction)test_from_contiguous, METH_NOARGS},
{"test_long_api", (PyCFunction)test_long_api, METH_NOARGS},
{"test_long_and_overflow", (PyCFunction)test_long_and_overflow,
METH_NOARGS},
{"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS},
{"test_k_code", (PyCFunction)test_k_code, METH_NOARGS},
#ifdef Py_USING_UNICODE
{"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS},
#endif
{"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS},
{"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
{"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
PyDoc_STR("This is a pretty normal docstring.")},
{"test_buildvalue_N", test_buildvalue_N, METH_NOARGS},
{"get_args", get_args, METH_VARARGS},
{"get_kwargs", (PyCFunction)get_kwargs, METH_VARARGS|METH_KEYWORDS},
{"getargs_tuple", getargs_tuple, METH_VARARGS},
{"getargs_keywords", (PyCFunction)getargs_keywords,
METH_VARARGS|METH_KEYWORDS},
{"getargs_b", getargs_b, METH_VARARGS},
{"getargs_B", getargs_B, METH_VARARGS},
{"getargs_h", getargs_h, METH_VARARGS},
{"getargs_H", getargs_H, METH_VARARGS},
{"getargs_I", getargs_I, METH_VARARGS},
{"getargs_k", getargs_k, METH_VARARGS},
{"getargs_i", getargs_i, METH_VARARGS},
{"getargs_l", getargs_l, METH_VARARGS},
{"getargs_n", getargs_n, METH_VARARGS},
#ifdef HAVE_LONG_LONG
{"getargs_L", getargs_L, METH_VARARGS},
{"getargs_K", getargs_K, METH_VARARGS},
{"test_longlong_api", test_longlong_api, METH_NOARGS},
{"test_long_long_and_overflow",
(PyCFunction)test_long_long_and_overflow, METH_NOARGS},
{"test_L_code", (PyCFunction)test_L_code, METH_NOARGS},
#endif
{"getargs_f", getargs_f, METH_VARARGS},
{"getargs_d", getargs_d, METH_VARARGS},
{"getargs_D", getargs_D, METH_VARARGS},
{"getargs_S", getargs_S, METH_VARARGS},
{"getargs_Y", getargs_Y, METH_VARARGS},
#ifdef Py_USING_UNICODE
{"getargs_U", getargs_U, METH_VARARGS},
#endif
{"getargs_c", getargs_c, METH_VARARGS},
{"getargs_s", getargs_s, METH_VARARGS},
{"getargs_s_star", getargs_s_star, METH_VARARGS},
{"getargs_s_hash", getargs_s_hash, METH_VARARGS},
{"getargs_t_hash", getargs_t_hash, METH_VARARGS},
{"getargs_z", getargs_z, METH_VARARGS},
{"getargs_z_star", getargs_z_star, METH_VARARGS},
{"getargs_z_hash", getargs_z_hash, METH_VARARGS},
{"getargs_w", getargs_w, METH_VARARGS},
{"getargs_w_star", getargs_w_star, METH_VARARGS},
{"getargs_w_hash", getargs_w_hash, METH_VARARGS},
#ifdef Py_USING_UNICODE
{"getargs_u", getargs_u, METH_VARARGS},
{"getargs_u_hash", getargs_u_hash, METH_VARARGS},
#endif
{"getargs_es", getargs_es, METH_VARARGS},
{"getargs_et", getargs_et, METH_VARARGS},
{"getargs_es_hash", getargs_es_hash, METH_VARARGS},
{"getargs_et_hash", getargs_et_hash, METH_VARARGS},
#ifdef Py_USING_UNICODE
{"codec_incrementalencoder",
(PyCFunction)codec_incrementalencoder, METH_VARARGS},
{"codec_incrementaldecoder",
(PyCFunction)codec_incrementaldecoder, METH_VARARGS},
{"test_u_code", (PyCFunction)test_u_code, METH_NOARGS},
{"test_widechar", (PyCFunction)test_widechar, METH_NOARGS},
{"unicode_encodedecimal", unicode_encodedecimal, METH_VARARGS},
#endif
#ifdef WITH_THREAD
{"_test_thread_state", test_thread_state, METH_VARARGS},
{"_pending_threadfunc", pending_threadfunc, METH_VARARGS},
#endif
{"test_capsule", (PyCFunction)test_capsule, METH_NOARGS},
{"traceback_print", traceback_print, METH_VARARGS},
{"code_newempty", code_newempty, METH_VARARGS},
{"make_exception_with_doc", (PyCFunction)make_exception_with_doc,
METH_VARARGS | METH_KEYWORDS},
{"sequence_delitem", (PyCFunction)sequence_delitem, METH_VARARGS},
#ifdef WITH_THREAD
{"call_in_temporary_c_thread", call_in_temporary_c_thread, METH_O,
PyDoc_STR("set_error_class(error_class) -> None")},
#endif
{"pymarshal_write_long_to_file",
pymarshal_write_long_to_file, METH_VARARGS},
{"pymarshal_write_object_to_file",
pymarshal_write_object_to_file, METH_VARARGS},
{"pymarshal_read_short_from_file",
pymarshal_read_short_from_file, METH_VARARGS},
{"pymarshal_read_long_from_file",
pymarshal_read_long_from_file, METH_VARARGS},
{"pymarshal_read_last_object_from_file",
pymarshal_read_last_object_from_file, METH_VARARGS},
{"pymarshal_read_object_from_file",
pymarshal_read_object_from_file, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
#define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);}
typedef struct {
char bool_member;
char byte_member;
unsigned char ubyte_member;
short short_member;
unsigned short ushort_member;
int int_member;
unsigned int uint_member;
long long_member;
unsigned long ulong_member;
float float_member;
double double_member;
char inplace_member[6];
#ifdef HAVE_LONG_LONG
PY_LONG_LONG longlong_member;
unsigned PY_LONG_LONG ulonglong_member;
#endif
} all_structmembers;
typedef struct {
PyObject_HEAD
all_structmembers structmembers;
} test_structmembers;
static struct PyMemberDef test_members[] = {
{"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL},
{"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL},
{"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL},
{"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL},
{"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL},
{"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL},
{"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL},
{"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL},
{"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
{"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
{"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
{"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL},
#ifdef HAVE_LONG_LONG
{"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
{"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
#endif
{NULL}
};
static PyObject *
test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {
"T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
"T_INT", "T_UINT", "T_LONG", "T_ULONG",
"T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
#ifdef HAVE_LONG_LONG
"T_LONGLONG", "T_ULONGLONG",
#endif
NULL};
static char *fmt = "|bbBhHiIlkfds#"
#ifdef HAVE_LONG_LONG
"LK"
#endif
;
test_structmembers *ob;
const char *s = NULL;
int string_len = 0;
ob = PyObject_New(test_structmembers, type);
if (ob == NULL)
return NULL;
memset(&ob->structmembers, 0, sizeof(all_structmembers));
if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
&ob->structmembers.bool_member,
&ob->structmembers.byte_member,
&ob->structmembers.ubyte_member,
&ob->structmembers.short_member,
&ob->structmembers.ushort_member,
&ob->structmembers.int_member,
&ob->structmembers.uint_member,
&ob->structmembers.long_member,
&ob->structmembers.ulong_member,
&ob->structmembers.float_member,
&ob->structmembers.double_member,
&s, &string_len
#ifdef HAVE_LONG_LONG
, &ob->structmembers.longlong_member,
&ob->structmembers.ulonglong_member
#endif
)) {
Py_DECREF(ob);
return NULL;
}
if (s != NULL) {
if (string_len > 5) {
Py_DECREF(ob);
PyErr_SetString(PyExc_ValueError, "string too long");
return NULL;
}
strcpy(ob->structmembers.inplace_member, s);
}
else {
strcpy(ob->structmembers.inplace_member, "");
}
return (PyObject *)ob;
}
static void
test_structmembers_free(PyObject *ob)
{
PyObject_FREE(ob);
}
static PyTypeObject test_structmembersType = {
PyVarObject_HEAD_INIT(NULL, 0)
"test_structmembersType",
sizeof(test_structmembers), /* tp_basicsize */
0, /* tp_itemsize */
test_structmembers_free, /* destructor tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
"Type containing all structmember types",
0, /* traverseproc tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
test_members, /* tp_members */
0,
0,
0,
0,
0,
0,
0,
0,
test_structmembers_new, /* tp_new */
};
PyMODINIT_FUNC
init_testcapi(void)
{
PyObject *m;
m = Py_InitModule("_testcapi", TestMethods);
if (m == NULL)
return;
Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type;
Py_TYPE(&test_structmembersType)=&PyType_Type;
Py_INCREF(&test_structmembersType);
/* don't use a name starting with "test", since we don't want
test_capi to automatically call this */
PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType);
PyModule_AddObject(m, "CHAR_MAX", PyInt_FromLong(CHAR_MAX));
PyModule_AddObject(m, "CHAR_MIN", PyInt_FromLong(CHAR_MIN));
PyModule_AddObject(m, "UCHAR_MAX", PyInt_FromLong(UCHAR_MAX));
PyModule_AddObject(m, "SHRT_MAX", PyInt_FromLong(SHRT_MAX));
PyModule_AddObject(m, "SHRT_MIN", PyInt_FromLong(SHRT_MIN));
PyModule_AddObject(m, "USHRT_MAX", PyInt_FromLong(USHRT_MAX));
PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
PyModule_AddObject(m, "LONG_MAX", PyInt_FromLong(LONG_MAX));
PyModule_AddObject(m, "LONG_MIN", PyInt_FromLong(LONG_MIN));
PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX));
PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN));
PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyInt_FromSsize_t(PY_SSIZE_T_MAX));
PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyInt_FromSsize_t(PY_SSIZE_T_MIN));
PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyInt_FromSsize_t(sizeof(PyGC_Head)));
TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
Py_INCREF(TestError);
PyModule_AddObject(m, "error", TestError);
}
```
|
Nurteria bicolor is a species of fly first described by Octave Parent in 1934. It belongs to the genus Nurteria and the family Dolichopodidae.
References
Sympycninae
Taxa named by Octave Parent
Insects described in 1934
|
Kiel University, officially the Christian-Albrecht University of Kiel, (, abbreviated CAU, known informally as Christiana Albertina) is a public research university in the city of Kiel, Germany. It was founded in 1665 as the Academia Holsatorum Chiloniensis by Christian Albert, Duke of Holstein-Gottorp and has approximately 27,000 students today. It is the largest, oldest, and most prestigious university in the state of Schleswig-Holstein.
Until 1866, it was not only the northernmost university in Germany but at the same time the 2nd largest university of Denmark. Faculty, alumni, and researchers of Kiel University have won 12 Nobel Prizes. Kiel University has been a member of the German Universities Excellence Initiative since 2006. The Cluster of Excellence The Future Ocean, which was established in cooperation with the GEOMAR Helmholtz Centre for Ocean Research Kiel in 2006, is internationally recognized. The second Cluster of Excellence "Inflammation at Interfaces" deals with chronic inflammatory diseases. The Kiel Institute for the World Economy is also affiliated with Kiel University. The university has a great reputation for its focus on public international law. The oldest public international law institution in Germany and Europe – the Walther Schuecking Institute for International Law – is based in Kiel.
History
Kiel University was founded under the name Christiana Albertina on 5 October 1665 by Christian Albert, Duke of Holstein-Gottorp. The citizens of the city of Kiel were initially quite sceptical about the upcoming influx of students, thinking that these could be "quite a pest with their gluttony, heavy drinking and their questionable character" (German: mit Fressen, Sauffen und allerley leichtfertigem Wesen sehr ärgerlich seyn). But those in the city who envisioned economic advantages of a university in the city won, and Kiel thus became the northernmost university in the German Holy Roman Empire.
After 1773, when Kiel had come under Danish rule, the university began to thrive, and when Kiel became part of Prussia in the year 1867, the university grew rapidly in size. The university opened one of the first botanical gardens in Germany (now the Alter Botanischer Garten Kiel), and Martin Gropius designed many of the new buildings needed to teach the growing number of students.
The Christiana Albertina was one of the first German universities to obey the Gleichschaltung in 1933 and agreed to remove many professors and students from the school, for instance Ferdinand Tönnies or Felix Jacoby. During World War II, Kiel University suffered heavy damage, therefore it was later rebuilt at a different location with only a few of the older buildings housing the medical school.
In 2019, it was announced it has banned full-face coverings in classrooms, citing the need for open communication that includes facial expressions and gestures.
Faculties
Christian-Albrechts-Universität currently consists of the following eight faculties:
Faculty of Theology
Faculty of Law
Faculty of Business, Economics and Social Sciences
Faculty of Medicine
Faculty of Arts and Humanities
Faculty of Mathematics and Natural Sciences
Faculty of Agricultural Science and Nutrition
Faculty of Engineering
Notable people
Alumni
See also :Category:University of Kiel alumni
Franz Boas (1858–1942), anthropologist
Alice Bota (born 1979), journalist
Georg von Dadelsen (1918–2007), musicologist, Neue Bach-Ausgabe
Gerhard Domagk, bacteriologist, Nobel laureate
Andre Franke, geneticist
Johanna Hellman (1889–1982), surgeon
Mareile Höppner, television presenter
Doris König, current judge of the Federal Constitutional Court of Germany
Wolfgang Kubicki, politician, vice chairman of the FDP in Germany, from 1992 to 1993 and since 1996 he is faction leader of the FDP in the Landtag, the parliament of Schleswig-Holstein, member of the Bundestag
Oswald Pohl (1892–1951), Nazi SS officer executed for war crimes
Viktoria Schmidt-Linsenhoff (1944–2013), German art historian and professor
Gerhard Stoltenberg, politician, former prime minister of Schleswig-Holstein, former finance minister of Germany
Peer Steinbrück, politician, former prime minister of North Rhine Westphalia, former finance minister of Germany
Erich Walter Sternberg, composer
Sibylle Kessal-Wulf, current judge of the Federal Constitutional Court of Germany, Germany's highest court
Surya Hermawan, lecturer at Petra Christian University, Indonesia
Academics
Nobel Prize winners
Rankings
Kiel University is recognized in several university ranking systems. According to the 2024 QS World University Rankings, the institution is globally positioned at 530 and holds the 33rd place nationally. In the 2024 THE World University Rankings, it is placed within the 301–350 bracket worldwide and ranks between 32nd and 33rd nationally. The ARWU World Rankings for 2023 presents the university within the global 201–300 range, while its national rank is within the 10th to 19th positions.
Academic publishing
The Ethnographisch-Archaeologische Zeitschrift (EAZ) is an interdisciplinary journal dedicated to the study of human societies from prehistory to the present day by bridging archaeology, anthropology, and philosophy and addressing topics like social inequality, climate change, and indigenous sovereignty. The EAZ was founded in 1960 as the successor to the publication series Ethnographisch-Archäologische Forschungen, which was published from 1953 to 1959. First published at Humboldt University Berlin in 1960, the EAZ later moved to Leipzig in 2010, and since 2023 it is published at Kiel University.
Points of interest
Botanischer Garten der Christian-Albrechts-Universität zu Kiel, the university's botanical garden
Gallery
Holstein Study Award
CAU's most renowned award is the Holstein Study Award (Holsteiner Studienpreis), which is awarded to the university's top three students each year since 2001. The award's criteria include extraordinary academic achievements, a broad intellectual horizon and political or social involvement. It is endowed with a prize money of €500 for the 2nd and 3rd prize and €1000 for the 1st prize. The Holstein Study Award is funded by the association 'Iuventus Academiae Holsatorum'. The award's expert jury includes professors of various faculties and the prizes are awarded by the university's president or vice-president in a formal ceremony in the top floor of the skyscraper on campus.
See also
List of early modern universities in Europe
Lists of universities and colleges
References
External links
Kiel University International Affairs
Students' Association at Kiel University
Universities and colleges in Schleswig-Holstein
University
Educational institutions established in the 1660s
1665 establishments in the Holy Roman Empire
|
```javascript
import { Feature } from 'toolkit/extension/features/feature';
import { getCurrentRouteName } from 'toolkit/extension/utils/ynab';
export class ViewZeroAsEmpty extends Feature {
shouldInvoke() {
return getCurrentRouteName().indexOf('reports.income-expense') !== -1;
}
destroy() {
$('.income-expense-level2 .user-data.zero').removeClass('tk-hidden');
}
invoke() {
$('.income-expense-level2 .user-data.zero').addClass('tk-hidden');
}
onRouteChanged() {
if (!this.shouldInvoke()) return;
this.invoke();
}
}
```
|
Jokhu Lal Yadav is an Indian politician from Samajwadi Party. Who has been MLA many times from Handia and Pratappur of Prayagraj District.
Early life
Yadav was born on August 16, 1956, in Dubki Khurd village of Allahabad. His father's name is Ranga Bahadur Yadav, He married to Shobha Yadav on February 22, 1978, He has four sons and three daughters.
Political life
Yadav was involved in politics during his student life, he was elected as the general secretary of the Mathematics Council of the Allahabad University during 1979–1980. In the academic session 1980-1981, He was Elected President of Students' Union of C.M.P. Degree College (a constituent College of University of Allahabad). He was elected member of the Legislative Assembly for the first time in support of the alliance of the Samajwadi Party and the Bahujan Samaj Party from the Handia Assembly constituency in the Uttar Pradesh Legislative Assembly Elections 1993, Elected MLA for the second time in the year 1996, and for the third time in the year 2007 as a Samajwadi Party candidate from Pratappur. From 2003 to 2007, he was also a District President of Samajwadi Party Allahabad unit. Prior to this, he was also has been District President of Bahujan Samaj Party Allahabad unit from 1990 to 1994.
References
Living people
Uttar Pradesh MLAs 1993–1996
Uttar Pradesh MLAs 1997–2002
Uttar Pradesh MLAs 2007–2012
Bahujan Samaj Party politicians from Uttar Pradesh
Samajwadi Party politicians from Uttar Pradesh
1956 births
University of Allahabad alumni
|
```smalltalk
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.UI.Packages.Prismjs;
using Volo.Abp.AspNetCore.Mvc.UI.Widgets;
namespace Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.Demo.Views.Components.Themes.Shared.Demos.CollapseDemo;
[Widget(
StyleTypes = new[] { typeof(PrismjsStyleBundleContributor) },
ScriptTypes = new[] { typeof(PrismjsScriptBundleContributor) }
)]
public class CollapseDemoViewComponent : AbpViewComponent
{
public const string ViewPath = "/Views/Components/Themes/Shared/Demos/CollapseDemo/Default.cshtml";
public virtual IViewComponentResult Invoke()
{
return View(ViewPath);
}
}
```
|
```shell
#!/bin/sh
#
# Test sudoers owner check
#
: ${TESTSUDOERS=testsudoers}
exec 2>&1
$TESTSUDOERS -U 1 root id <<EOF
@include $TESTDIR/test2.inc
EOF
exit 0
```
|
```html
<!--
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!-- build:css docker-registry-ui.css -->
<link href="../node_modules/riot-mui/build/styles/riot-mui.min.css" rel="stylesheet" type="text/css" />
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="material-icons.css" rel="stylesheet" type="text/css" />
<link href="roboto.css" rel="stylesheet" type="text/css" />
<!-- endbuild -->
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta property="og:site_name" content="Docker Registry UI" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@Joxit" />
<meta name="twitter:creator" content="@Jones Magloire" />
<title>Docker Registry UI</title>
</head>
<body>
<!-- build:keep production -->
<docker-registry-ui
registry-url="${REGISTRY_URL}"
name="${REGISTRY_TITLE}"
pull-url="${PULL_URL}"
show-content-digest="${SHOW_CONTENT_DIGEST}"
show-tag-history="${SHOW_TAG_HISTORY}"
is-image-remove-activated="${DELETE_IMAGES}"
catalog-elements-limit="${CATALOG_ELEMENTS_LIMIT}"
single-registry="${SINGLE_REGISTRY}"
default-registries="${DEFAULT_REGISTRIES}"
read-only-registries="${READ_ONLY_REGISTRIES}"
show-catalog-nb-tags="${SHOW_CATALOG_NB_TAGS}"
history-custom-labels="${HISTORY_CUSTOM_LABELS}"
use-control-cache-header="${USE_CONTROL_CACHE_HEADER}"
taglist-order="${TAGLIST_ORDER}"
catalog-default-expanded="${CATALOG_DEFAULT_EXPANDED}"
catalog-min-branches="${CATALOG_MIN_BRANCHES}"
catalog-max-branches="${CATALOG_MAX_BRANCHES}"
is-registry-secured="${REGISTRY_SECURED}"
theme="${THEME}"
theme-primary-text="${THEME_PRIMARY_TEXT}"
theme-neutral-text="${THEME_NEUTRAL_TEXT}"
theme-background="${THEME_BACKGROUND}"
theme-hover-background="${THEME_HOVER_BACKGROUND}"
theme-accent-text="${THEME_ACCENT_TEXT}"
theme-header-accent-text="${THEME_HEADER_ACCENT_TEXT}"
theme-header-text="${THEME_HEADER_TEXT}"
theme-header-background="${THEME_HEADER_BACKGROUND}"
theme-footer-text="${THEME_FOOTER_TEXT}"
theme-footer-neutral-text="${THEME_FOOTER_NEUTRAL_TEXT}"
theme-footer-background="${THEME_FOOTER_BACKGROUND}"
tags-per-page="${TAGLIST_PAGE_SIZE}"
>
</docker-registry-ui>
<!-- endbuild -->
<!-- build:keep developement -->
<docker-registry-ui
registry-url=""
name="Development Registry"
pull-url=""
show-content-digest="true"
show-tag-history="true"
is-image-remove-activated="true"
catalog-elements-limit="1000"
single-registry="false"
show-catalog-nb-tags="true"
history-custom-labels="first_custom_labels,second_custom_labels"
use-control-cache-header="false"
taglist-order=""
catalog-default-expanded=""
catalog-min-branches="1"
catalog-max-branches="1"
is-registry-secured="false"
theme="auto"
theme-primary-text=""
theme-neutral-text=""
theme-background=""
theme-hover-background=""
theme-accent-text=""
theme-header-accent-text=""
theme-header-text=""
theme-header-background=""
theme-footer-text=""
theme-footer-neutral-text=""
theme-footer-background=""
tags-per-page=""
>
</docker-registry-ui>
<!-- endbuild -->
<!-- build:js docker-registry-ui.js -->
<script src="../node_modules/riot/riot+compiler.min.js"></script>
<script src="../node_modules/riot-route/dist/route.js"></script>
<script src="../node_modules/riot-mui/build/js/riot-mui.js"></script>
<script src="tags/catalog.riot" type="riot/tag"></script>
<script src="tags/catalog-element.riot" type="riot/tag"></script>
<script src="tags/tag-history-button.riot" type="riot/tag"></script>
<script src="tags/tag-history.riot" type="riot/tag"></script>
<script src="tags/tag-history-element.riot" type="riot/tag"></script>
<script src="tags/taglist.riot" type="riot/tag"></script>
<script src="tags/image-tag.riot" type="riot/tag"></script>
<script src="tags/remove-image.riot" type="riot/tag"></script>
<script src="tags/copy-to-clipboard.riot" type="riot/tag"></script>
<script src="tags/dialogs/add.riot" type="riot/tag"></script>
<script src="tags/dialogs/change.riot" type="riot/tag"></script>
<script src="tags/dialogs/remove.riot" type="riot/tag"></script>
<script src="tags/dialogs/menu.riot" type="riot/tag"></script>
<script src="tags/image-size.riot" type="riot/tag"></script>
<script src="tags/image-date.riot" type="riot/tag"></script>
<script src="tags/image-content-digest.riot" type="riot/tag"></script>
<script src="tags/pagination.riot" type="riot/tag"></script>
<script src="tags/app.riot" type="riot/tag"></script>
<script src="scripts/http.js"></script>
<script src="scripts/script.js"></script>
<script src="scripts/utils.js"></script>
<!-- endbuild -->
</body>
</html>
```
|
```ruby
# frozen_string_literal: true
module Decidim
# Shared behaviour for force_users_to_authenticate_before_access_organization
module ForceAuthentication
extend ActiveSupport::Concern
included do
before_action :ensure_authenticated!, unless: :allow_unauthorized_path?
end
private
# For Devise helper functions, see:
# path_to_url#getting-started
#
# Breaks the request lifecycle, if user is not authenticated.
# Otherwise returns.
def ensure_authenticated!
return true unless current_organization&.force_users_to_authenticate_before_access_organization
# Next stop: Check whether auth is ok
unless user_signed_in?
flash[:warning] = t("actions.login_before_access", scope: "decidim.core")
redirect_to decidim.new_user_session_path
end
end
# Check for all paths that should be allowed even if the user is not yet
# authorized
def allow_unauthorized_path?
return true if unauthorized_paths.any? { |path| /^#{path}/.match?(request.path) }
false
end
def unauthorized_paths
default_unauthorized_paths + Decidim::StaticPage.where(
organization: current_organization,
allow_public_access: true
).pluck(Arel.sql("CONCAT('/pages/', slug)"))
end
def default_unauthorized_paths
# /locale is for changing the locale and /manifest.webmanifest to request PWA manifest
%w(/locale /manifest.webmanifest)
end
end
end
```
|
To tow something is to pull it using a line or chain.
Tow or TOW may also refer to:
Places
Tow, Iran, Razavi Khorasan Province
Tow, Texas, United States
Tow Bay, South Sandwich Islands, south Atlantic
Tow Hill, a volcanic plug in British Columbia, Canada
People
Tow (surname), a Chinese, English, or Scottish family name, and a list of people so named
Other uses
Tow (fibre), a textiles by-product
Tug of war, a sport
BGM-71 TOW, an anti-tank missile
tow, the Jemez language of North America, by ISO 639-3 code
See also
Maximum takeoff weight, abbreviated MTOW
|
Gobalakrishnan Nagapan (born 23 March 1960), commonly referred to as N. Gobalakrishnan, is a Malaysian politician. He was the Member of the Parliament of Malaysia for the Padang Serai constituency in Kedah from 2008 to 2013. He was elected to the Parliament as a member of the People's Justice Party (PKR) in the opposition Pakatan Rakyat coalition, but in 2011 left the party to sit as an Independent. Gobalakrishnan on 8 May 2017 rejoined the Malaysian Indian Congress (MIC) after leaving it 18 years ago to join PKR.
Personal life
Gobalakrishnan was born in 1960 in Sitiawan. He is married to Vasanthi Ramalingam, a former athlete, and has three children.
Controversy
In September 2009, Gobalakrishnan was arrested for allegedly using criminal force to obstruct a police officer. He was found guilty and fined 3,000 ringgit. In December 2010, he spoke out against his party's leader, Anwar Ibrahim, suggesting that he make way for his daughter Nurul Izzah Anwar. He resigned from the party the following month to sit as an independent, announcing plans to form a non-governmental organisation. He recontested Padang Serai at the 2013 election as an Independent, having unsuccessfully sought the nomination of the Barisan Nasional coalition. Without a party ticket he garnered less than one percent of the vote and lost his deposit.
In April 2019, the Putrajaya Court of Appeal ruled Gobalakrishnan has to pay RM150,000 in damages for defaming and RM5,000 in costs to lawyer and former Malaysian Bar president Manjeet Singh Dhillon.
Election results
References
Living people
1960 births
People from Sitiawan
Malaysian politicians of Indian descent
Malaysian Indian Congress politicians
Former People's Justice Party (Malaysia) politicians
Independent politicians in Malaysia
Members of the Dewan Rakyat
21st-century Malaysian politicians
|
```java
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package io.camunda.zeebe.client.impl;
import static io.camunda.zeebe.client.ClientProperties.CLOUD_CLIENT_ID;
import static io.camunda.zeebe.client.ClientProperties.CLOUD_CLIENT_SECRET;
import static io.camunda.zeebe.client.ClientProperties.CLOUD_CLUSTER_ID;
import static io.camunda.zeebe.client.ClientProperties.CLOUD_REGION;
import static io.camunda.zeebe.client.ClientProperties.STREAM_ENABLED;
import static io.camunda.zeebe.client.impl.command.ArgumentUtil.ensureNotNull;
import io.camunda.zeebe.client.CredentialsProvider;
import io.camunda.zeebe.client.ZeebeClient;
import io.camunda.zeebe.client.ZeebeClientBuilder;
import io.camunda.zeebe.client.ZeebeClientCloudBuilderStep1;
import io.camunda.zeebe.client.ZeebeClientCloudBuilderStep1.ZeebeClientCloudBuilderStep2;
import io.camunda.zeebe.client.ZeebeClientCloudBuilderStep1.ZeebeClientCloudBuilderStep2.ZeebeClientCloudBuilderStep3;
import io.camunda.zeebe.client.ZeebeClientCloudBuilderStep1.ZeebeClientCloudBuilderStep2.ZeebeClientCloudBuilderStep3.ZeebeClientCloudBuilderStep4;
import io.camunda.zeebe.client.api.ExperimentalApi;
import io.camunda.zeebe.client.api.JsonMapper;
import io.camunda.zeebe.client.impl.oauth.OAuthCredentialsProviderBuilder;
import io.grpc.ClientInterceptor;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.hc.client5.http.async.AsyncExecChainHandler;
public class ZeebeClientCloudBuilderImpl
implements ZeebeClientCloudBuilderStep1,
ZeebeClientCloudBuilderStep2,
ZeebeClientCloudBuilderStep3,
ZeebeClientCloudBuilderStep4 {
private static final String BASE_ADDRESS = "zeebe.camunda.io";
private static final String BASE_AUTH_URL = "path_to_url";
private static final String DEFAULT_REGION = "bru-2";
private final ZeebeClientBuilderImpl innerBuilder = new ZeebeClientBuilderImpl();
private String clusterId;
private String clientId;
private String clientSecret;
private String region = DEFAULT_REGION;
@Override
public ZeebeClientCloudBuilderStep2 withClusterId(final String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public ZeebeClientCloudBuilderStep3 withClientId(final String clientId) {
this.clientId = clientId;
return this;
}
@Override
public ZeebeClientCloudBuilderStep4 withClientSecret(final String clientSecret) {
this.clientSecret = clientSecret;
return this;
}
@Override
public ZeebeClientCloudBuilderStep4 withRegion(final String region) {
this.region = region;
return this;
}
@Override
public ZeebeClientBuilder withProperties(final Properties properties) {
BuilderUtils.applyIfNotNull(properties, CLOUD_CLUSTER_ID, this::withClusterId);
BuilderUtils.applyIfNotNull(properties, CLOUD_CLIENT_ID, this::withClientId);
BuilderUtils.applyIfNotNull(properties, CLOUD_CLIENT_SECRET, this::withClientId);
BuilderUtils.applyIfNotNull(properties, CLOUD_REGION, this::withRegion);
BuilderUtils.applyIfNotNull(
properties,
STREAM_ENABLED,
value -> defaultJobWorkerStreamEnabled(Boolean.parseBoolean(value)));
innerBuilder.withProperties(properties);
// todo(#14106): allow default tenant id setting for cloud client
innerBuilder.defaultTenantId("");
innerBuilder.defaultJobWorkerTenantIds(Collections.emptyList());
return this;
}
@Override
public ZeebeClientBuilder applyEnvironmentVariableOverrides(
final boolean applyEnvironmentVariableOverrides) {
innerBuilder.applyEnvironmentVariableOverrides(applyEnvironmentVariableOverrides);
return this;
}
@Override
public ZeebeClientBuilder gatewayAddress(final String gatewayAddress) {
innerBuilder.gatewayAddress(gatewayAddress);
return this;
}
@Override
public ZeebeClientBuilder restAddress(final URI restAddress) {
innerBuilder.restAddress(restAddress);
return this;
}
@Override
public ZeebeClientBuilder grpcAddress(final URI grpcAddress) {
innerBuilder.grpcAddress(grpcAddress);
return this;
}
@Override
@ExperimentalApi("path_to_url")
public ZeebeClientBuilder defaultTenantId(final String tenantId) {
Loggers.LOGGER.debug(
"Multi-tenancy in Camunda 8 SaaS will be supported with path_to_url");
return this;
}
@Override
@ExperimentalApi("path_to_url")
public ZeebeClientBuilder defaultJobWorkerTenantIds(final List<String> tenantIds) {
Loggers.LOGGER.debug(
"Multi-tenancy in Camunda 8 SaaS will be supported with path_to_url");
return this;
}
@Override
public ZeebeClientBuilder defaultJobWorkerMaxJobsActive(final int maxJobsActive) {
innerBuilder.defaultJobWorkerMaxJobsActive(maxJobsActive);
return this;
}
@Override
public ZeebeClientBuilder numJobWorkerExecutionThreads(final int numThreads) {
innerBuilder.numJobWorkerExecutionThreads(numThreads);
return this;
}
@Override
public ZeebeClientBuilder jobWorkerExecutor(
final ScheduledExecutorService executor, final boolean takeOwnership) {
innerBuilder.jobWorkerExecutor(executor, takeOwnership);
return this;
}
@Override
public ZeebeClientBuilder defaultJobWorkerName(final String workerName) {
innerBuilder.defaultJobWorkerName(workerName);
return this;
}
@Override
public ZeebeClientBuilder defaultJobTimeout(final Duration timeout) {
innerBuilder.defaultJobTimeout(timeout);
return this;
}
@Override
public ZeebeClientBuilder defaultJobPollInterval(final Duration pollInterval) {
innerBuilder.defaultJobPollInterval(pollInterval);
return this;
}
@Override
public ZeebeClientBuilder defaultMessageTimeToLive(final Duration timeToLive) {
innerBuilder.defaultMessageTimeToLive(timeToLive);
return this;
}
@Override
public ZeebeClientBuilder defaultRequestTimeout(final Duration requestTimeout) {
innerBuilder.defaultRequestTimeout(requestTimeout);
return this;
}
@Override
public ZeebeClientBuilder usePlaintext() {
innerBuilder.usePlaintext();
return this;
}
@Override
public ZeebeClientBuilder caCertificatePath(final String certificatePath) {
innerBuilder.caCertificatePath(certificatePath);
return this;
}
@Override
public ZeebeClientBuilder credentialsProvider(final CredentialsProvider credentialsProvider) {
innerBuilder.credentialsProvider(credentialsProvider);
return this;
}
@Override
public ZeebeClientBuilder keepAlive(final Duration keepAlive) {
innerBuilder.keepAlive(keepAlive);
return this;
}
@Override
public ZeebeClientBuilder withInterceptors(final ClientInterceptor... interceptor) {
innerBuilder.withInterceptors(interceptor);
return this;
}
@Override
public ZeebeClientCloudBuilderStep4 withChainHandlers(
final AsyncExecChainHandler... chainHandler) {
innerBuilder.withChainHandlers(chainHandler);
return this;
}
@Override
public ZeebeClientBuilder withJsonMapper(final JsonMapper jsonMapper) {
innerBuilder.withJsonMapper(jsonMapper);
return this;
}
@Override
public ZeebeClientBuilder overrideAuthority(final String authority) {
innerBuilder.overrideAuthority(authority);
return this;
}
@Override
public ZeebeClientBuilder maxMessageSize(final int maxMessageSize) {
innerBuilder.maxMessageSize(maxMessageSize);
return this;
}
@Override
public ZeebeClientBuilder maxMetadataSize(final int maxMetadataSize) {
return innerBuilder.maxMetadataSize(maxMetadataSize);
}
@Override
public ZeebeClientBuilder defaultJobWorkerStreamEnabled(final boolean streamEnabled) {
innerBuilder.defaultJobWorkerStreamEnabled(streamEnabled);
return this;
}
@Override
public ZeebeClientBuilder useDefaultRetryPolicy(final boolean useDefaultRetryPolicy) {
innerBuilder.useDefaultRetryPolicy(useDefaultRetryPolicy);
return this;
}
@Override
public ZeebeClientBuilder preferRestOverGrpc(final boolean preferRestOverGrpc) {
innerBuilder.preferRestOverGrpc(preferRestOverGrpc);
return this;
}
@Override
public ZeebeClient build() {
innerBuilder.grpcAddress(determineGrpcAddress());
innerBuilder.restAddress(determineRestAddress());
innerBuilder.credentialsProvider(determineCredentialsProvider());
return innerBuilder.build();
}
private URI determineRestAddress() {
if (isNeedToSetCloudRestAddress()) {
ensureNotNull("cluster id", clusterId);
final String cloudRestAddress =
String.format("path_to_url", region, BASE_ADDRESS, clusterId);
return getURIFromString(cloudRestAddress);
} else {
Loggers.LOGGER.debug(
"Expected to use 'cluster id' to set REST API address in the client cloud builder, "
+ "but overwriting with explicitly defined REST API address: {}.",
innerBuilder.getRestAddress());
return innerBuilder.getRestAddress();
}
}
private URI determineGrpcAddress() {
if (isNeedToSetCloudGrpcAddress() && isNeedToSetCloudGatewayAddress()) {
ensureNotNull("cluster id", clusterId);
final String cloudGrpcAddress =
String.format("path_to_url", clusterId, region, BASE_ADDRESS);
return getURIFromString(cloudGrpcAddress);
} else {
if (!isNeedToSetCloudGrpcAddress()) {
Loggers.LOGGER.debug(
"Expected to use 'cluster id' to set gateway address in the client cloud builder, "
+ "but overwriting with explicitly defined gateway address: {}.",
innerBuilder.getGrpcAddress());
return innerBuilder.getGrpcAddress();
}
Loggers.LOGGER.debug(
"Expected to use 'cluster id' to set gateway address in the client cloud builder, "
+ "but overwriting with explicitly defined gateway address: {}.",
innerBuilder.getGatewayAddress());
return getURIFromString("https://" + innerBuilder.getGatewayAddress());
}
}
private CredentialsProvider determineCredentialsProvider() {
final CredentialsProvider provider = innerBuilder.getCredentialsProvider();
if (provider == null) {
ensureNotNull("cluster id", clusterId);
ensureNotNull("client id", clientId);
ensureNotNull("client secret", clientSecret);
final OAuthCredentialsProviderBuilder builder = new OAuthCredentialsProviderBuilder();
if (innerBuilder.isPlaintextConnectionEnabled()) {
Loggers.LOGGER.debug("Expected setting 'usePlaintext' to be 'false', but found 'true'.");
}
return builder
.audience(String.format("%s.%s.%s", clusterId, region, BASE_ADDRESS))
.clientId(clientId)
.clientSecret(clientSecret)
.authorizationServerUrl(BASE_AUTH_URL)
.build();
} else {
Loggers.LOGGER.debug(
"Expected to use 'cluster id', 'client id' and 'client secret' to set credentials provider in the client cloud builder, "
+ "but overwriting with explicitly defined credentials provider.");
return provider;
}
}
private boolean isNeedToSetCloudGrpcAddress() {
return innerBuilder.getGrpcAddress() == null
|| Objects.equals(
innerBuilder.getGrpcAddress(), ZeebeClientBuilderImpl.DEFAULT_GRPC_ADDRESS);
}
private boolean isNeedToSetCloudGatewayAddress() {
return innerBuilder.getGatewayAddress() == null
|| Objects.equals(
innerBuilder.getGatewayAddress(), ZeebeClientBuilderImpl.DEFAULT_GATEWAY_ADDRESS);
}
private boolean isNeedToSetCloudRestAddress() {
return innerBuilder.getRestAddress() == null
|| Objects.equals(
innerBuilder.getRestAddress(), ZeebeClientBuilderImpl.DEFAULT_REST_ADDRESS);
}
private URI getURIFromString(final String uri) {
try {
return new URI(uri);
} catch (final URISyntaxException e) {
throw new RuntimeException("Failed to parse URI string", e);
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(innerBuilder.toString());
BuilderUtils.appendProperty(sb, "clusterId", clusterId);
BuilderUtils.appendProperty(sb, "clientId", clientId);
BuilderUtils.appendProperty(sb, "region", region);
return sb.toString();
}
}
```
|
```c++
/* sctp_graph_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
*
* This program is free software; you can redistribute it and/or
* as published by the Free Software Foundation; either version 2
*
* 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
*
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <wsutil/utf8_entities.h>
#include "sctp_graph_dialog.h"
#include <ui_sctp_graph_dialog.h>
#include "sctp_assoc_analyse_dialog.h"
#include <file.h>
#include <math.h>
#include <epan/dissectors/packet-sctp.h>
#include "epan/packet.h"
#include "ui/tap-sctp-analysis.h"
#include <QFileDialog>
#include <QMessageBox>
#include "qcustomplot.h"
#include "wireshark_application.h"
SCTPGraphDialog::SCTPGraphDialog(QWidget *parent, sctp_assoc_info_t *assoc, capture_file *cf, int dir) :
QDialog(parent),
ui(new Ui::SCTPGraphDialog),
selected_assoc(assoc),
cap_file_(cf),
frame_num(0),
direction(dir),
gIsSackChunkPresent(false),
gIsNRSackChunkPresent(false)
{
ui->setupUi(this);
if (!selected_assoc) {
selected_assoc = SCTPAssocAnalyseDialog::findAssocForPacket(cap_file_);
}
Qt::WindowFlags flags = Qt::Window | Qt::WindowSystemMenuHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowMaximizeButtonHint
| Qt::WindowCloseButtonHint;
this->setWindowFlags(flags);
this->setWindowTitle(QString(tr("SCTP TSNs and SACKs over Time: %1 Port1 %2 Port2 %3")).arg(cf_get_display_name(cap_file_)).arg(selected_assoc->port1).arg(selected_assoc->port2));
if ((direction == 1 && selected_assoc->n_array_tsn1 == 0) || (direction == 2 && selected_assoc->n_array_tsn2 == 0)) {
QMessageBox msgBox;
msgBox.setText(tr("No Data Chunks sent"));
msgBox.exec();
return;
} else {
drawGraph(3);
}
}
SCTPGraphDialog::~SCTPGraphDialog()
{
delete ui;
}
void SCTPGraphDialog::drawNRSACKGraph()
{
tsn_t *sack;
GList *list=NULL, *tlist;
guint16 gap_start=0, gap_end=0, i, numberOf_gaps, numberOf_nr_gaps;
guint8 type;
guint32 tsnumber, j, min_tsn;
struct nr_sack_chunk_header *nr_sack_header;
struct gaps *nr_gap;
/* This holds the sum of gap acks and nr gap acks */
guint16 total_gaps = 0;
if (direction == 1) {
list = g_list_last(selected_assoc->sack1);
min_tsn = selected_assoc->min_tsn1;
} else {
list = g_list_last(selected_assoc->sack2);
min_tsn = selected_assoc->min_tsn2;
}
while (list) {
sack = (tsn_t*) (list->data);
tlist = g_list_first(sack->tsns);
while (tlist) {
type = ((struct chunk_header *)tlist->data)->type;
if (type == SCTP_NR_SACK_CHUNK_ID) {
gIsNRSackChunkPresent = 1;
nr_sack_header =(struct nr_sack_chunk_header *)tlist->data;
numberOf_nr_gaps=g_ntohs(nr_sack_header->nr_of_nr_gaps);
numberOf_gaps=g_ntohs(nr_sack_header->nr_of_gaps);
tsnumber = g_ntohl(nr_sack_header->cum_tsn_ack);
total_gaps = numberOf_gaps + numberOf_nr_gaps;
/* If the number of nr_gaps is greater than 0 */
if (total_gaps > 0) {
nr_gap = &nr_sack_header->gaps[0];
for (i = 0; i < total_gaps; i++) {
gap_start = g_ntohs(nr_gap->start);
gap_end = g_ntohs(nr_gap->end);
for (j = gap_start; j <= gap_end; j++) {
if (i >= numberOf_gaps) {
yn.append(j + tsnumber);
xn.append(sack->secs + sack->usecs/1000000.0);
fn.append(sack->frame_number);
} else {
yg.append(j + tsnumber);
xg.append(sack->secs + sack->usecs/1000000.0);
fg.append(sack->frame_number);
}
}
if (i < total_gaps-1)
nr_gap++;
}
if (tsnumber>=min_tsn) {
ys.append(j + tsnumber);
xs.append(sack->secs + sack->usecs/1000000.0);
fs.append(sack->frame_number);
}
}
}
tlist = g_list_next(tlist);
}
list = g_list_previous(list);
}
}
void SCTPGraphDialog::drawSACKGraph()
{
GList *listSACK = NULL, *tlist;
guint16 gap_start=0, gap_end=0, nr, dup_nr;
struct sack_chunk_header *sack_header;
struct gaps *gap;
tsn_t *tsn;
guint8 type;
guint32 tsnumber=0;
guint32 minTSN;
guint32 *dup_list;
int i, j;
if (direction == 1) {
minTSN = selected_assoc->min_tsn1;
listSACK = g_list_last(selected_assoc->sack1);
} else {
minTSN = selected_assoc->min_tsn2;
listSACK = g_list_last(selected_assoc->sack2);
}
while (listSACK) {
tsn = (tsn_t*) (listSACK->data);
tlist = g_list_first(tsn->tsns);
while (tlist) {
type = ((struct chunk_header *)tlist->data)->type;
if (type == SCTP_SACK_CHUNK_ID) {
gIsSackChunkPresent = 1;
sack_header =(struct sack_chunk_header *)tlist->data;
nr=g_ntohs(sack_header->nr_of_gaps);
tsnumber = g_ntohl(sack_header->cum_tsn_ack);
dup_nr=g_ntohs(sack_header->nr_of_dups);
if (nr>0) { // Gap Reports green
gap = &sack_header->gaps[0];
for(i=0;i<nr; i++) {
gap_start=g_ntohs(gap->start);
gap_end = g_ntohs(gap->end);
for (j=gap_start; j<=gap_end; j++) {
yg.append(j+tsnumber);
xg.append(tsn->secs + tsn->usecs/1000000.0);
fg.append(tsn->frame_number);
}
if (i < nr-1)
gap++;
}
}
if (tsnumber>=minTSN) { // CumTSNAck red
ys.append(tsnumber);
xs.append(tsn->secs + tsn->usecs/1000000.0);
fs.append(tsn->frame_number);
}
if (dup_nr > 0) { // Duplicates cyan
dup_list = &sack_header->a_rwnd + 2 + nr;
for (i = 0; i < dup_nr; i++) {
tsnumber = g_ntohl(dup_list[i]);
if (tsnumber >= minTSN) {
yd.append(tsnumber);
xd.append(tsn->secs + tsn->usecs/1000000.0);
fd.append(tsn->frame_number);
}
}
}
}
tlist = g_list_next(tlist);
}
listSACK = g_list_previous(listSACK);
}
QCPScatterStyle myScatter;
myScatter.setShape(QCPScatterStyle::ssCircle);
myScatter.setSize(3);
int graphcount = ui->sctpPlot->graphCount();
// create graph and assign data to it:
// Add SACK graph
if (xs.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph();
gr->setName(QString("SACK"));
myScatter.setPen(QPen(Qt::red));
myScatter.setBrush(Qt::red);
ui->sctpPlot->graph(graphcount)->setScatterStyle(myScatter);
ui->sctpPlot->graph(graphcount)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(graphcount)->setData(xs, ys);
typeStrings.insert(graphcount, QString(tr("CumTSNAck")));
graphcount++;
}
// Add Gap Acks
if (xg.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph();
gr->setName(QString("GAP"));
myScatter.setPen(QPen(Qt::green));
myScatter.setBrush(Qt::green);
ui->sctpPlot->graph(graphcount)->setScatterStyle(myScatter);
ui->sctpPlot->graph(graphcount)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(graphcount)->setData(xg, yg);
typeStrings.insert(graphcount, QString(tr("Gap Ack")));
graphcount++;
}
// Add NR Gap Acks
if (xn.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph();
gr->setName(QString("NR_GAP"));
myScatter.setPen(QPen(Qt::blue));
myScatter.setBrush(Qt::blue);
ui->sctpPlot->graph(graphcount)->setScatterStyle(myScatter);
ui->sctpPlot->graph(graphcount)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(graphcount)->setData(xn, yn);
typeStrings.insert(graphcount, QString(tr("NR Gap Ack")));
graphcount++;
}
// Add Duplicates
if (xd.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph();
gr->setName(QString("DUP"));
myScatter.setPen(QPen(Qt::cyan));
myScatter.setBrush(Qt::cyan);
ui->sctpPlot->graph(graphcount)->setScatterStyle(myScatter);
ui->sctpPlot->graph(graphcount)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(graphcount)->setData(xd, yd);
typeStrings.insert(graphcount, QString(tr("Duplicate Ack")));
}
}
void SCTPGraphDialog::drawTSNGraph()
{
GList *listTSN = NULL,*tlist;
tsn_t *tsn;
guint8 type;
guint32 tsnumber=0;
if (direction == 1) {
listTSN = g_list_last(selected_assoc->tsn1);
} else {
listTSN = g_list_last(selected_assoc->tsn2);
}
while (listTSN) {
tsn = (tsn_t*) (listTSN->data);
tlist = g_list_first(tsn->tsns);
while (tlist)
{
type = ((struct chunk_header *)tlist->data)->type;
if (type == SCTP_DATA_CHUNK_ID || type == SCTP_I_DATA_CHUNK_ID || type == SCTP_FORWARD_TSN_CHUNK_ID) {
tsnumber = g_ntohl(((struct data_chunk_header *)tlist->data)->tsn);
yt.append(tsnumber);
xt.append(tsn->secs + tsn->usecs/1000000.0);
ft.append(tsn->frame_number);
}
tlist = g_list_next(tlist);
}
listTSN = g_list_previous(listTSN);
}
QCPScatterStyle myScatter;
myScatter.setShape(QCPScatterStyle::ssCircle);
myScatter.setSize(3);
int graphcount = ui->sctpPlot->graphCount();
// create graph and assign data to it:
// Add TSN graph
if (xt.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph();
gr->setName(QString("TSN"));
myScatter.setPen(QPen(Qt::black));
myScatter.setBrush(Qt::black);
ui->sctpPlot->graph(graphcount)->setScatterStyle(myScatter);
ui->sctpPlot->graph(graphcount)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(graphcount)->setData(xt, yt);
typeStrings.insert(graphcount, QString(tr("TSN")));
}
}
void SCTPGraphDialog::drawGraph(int which)
{
guint32 maxTSN, minTSN;
gint64 minBound;
gIsSackChunkPresent = false;
gIsNRSackChunkPresent = false;
if (direction == 1) {
maxTSN = selected_assoc->max_tsn1;
minTSN = selected_assoc->min_tsn1;
} else {
maxTSN = selected_assoc->max_tsn2;
minTSN = selected_assoc->min_tsn2;
}
ui->sctpPlot->clearGraphs();
switch (which) {
case 1: drawSACKGraph();
drawNRSACKGraph();
break;
case 2: drawTSNGraph();
break;
case 3: drawTSNGraph();
drawSACKGraph();
drawNRSACKGraph();
break;
default: drawTSNGraph();
drawSACKGraph();
drawNRSACKGraph();
}
// give the axes some labels:
ui->sctpPlot->xAxis->setLabel(tr("time [secs]"));
ui->sctpPlot->yAxis->setLabel(tr("TSNs"));
ui->sctpPlot->setInteractions(QCP::iRangeZoom | QCP::iRangeDrag | QCP::iSelectPlottables);
connect(ui->sctpPlot, SIGNAL(plottableClick(QCPAbstractPlottable*,QMouseEvent*)), this, SLOT(graphClicked(QCPAbstractPlottable*, QMouseEvent*)));
// set axes ranges, so we see all data:
QCPRange myXRange(selected_assoc->min_secs, (selected_assoc->max_secs+1));
if (maxTSN - minTSN < 5) {
minBound = 0;
} else {
minBound = minTSN;
}
QCPRange myYRange(minBound, maxTSN);
ui->sctpPlot->xAxis->setRange(myXRange);
ui->sctpPlot->yAxis->setRange(myYRange);
ui->sctpPlot->replot();
}
void SCTPGraphDialog::on_pushButton_clicked()
{
drawGraph(1);
}
void SCTPGraphDialog::on_pushButton_2_clicked()
{
drawGraph(2);
}
void SCTPGraphDialog::on_pushButton_3_clicked()
{
drawGraph(3);
}
void SCTPGraphDialog::on_pushButton_4_clicked()
{
ui->sctpPlot->xAxis->setRange(selected_assoc->min_secs, selected_assoc->max_secs+1);
if (direction == 1) {
ui->sctpPlot->yAxis->setRange(selected_assoc->min_tsn1, selected_assoc->max_tsn1);
} else {
ui->sctpPlot->yAxis->setRange(selected_assoc->min_tsn2, selected_assoc->max_tsn2);
}
ui->sctpPlot->replot();
}
void SCTPGraphDialog::graphClicked(QCPAbstractPlottable* plottable, QMouseEvent* event)
{
frame_num = 0;
int i=0;
double times = ui->sctpPlot->xAxis->pixelToCoord(event->pos().x());
if (plottable->name().contains("TSN", Qt::CaseInsensitive)) {
for (i = 0; i < xt.size(); i++) {
if (times <= xt.value(i)) {
frame_num = ft.at(i);
break;
}
}
} else if (plottable->name().contains("SACK", Qt::CaseInsensitive)) {
for (i = 0; i < xs.size(); i++) {
if (times <= xs.value(i)) {
frame_num = fs.at(i);
break;
}
}
} else if (plottable->name().contains("DUP", Qt::CaseInsensitive)) {
for (i = 0; i < xd.size(); i++) {
if (times <= xd.value(i)) {
frame_num = fd.at(i);
break;
}
}
} else if (plottable->name().contains("NR_GAP", Qt::CaseInsensitive)) {
for (i = 0; i < xn.size(); i++) {
if (times <= xn.value(i)) {
frame_num = fn.at(i);
break;
}
}
} else if (plottable->name().contains("GAP", Qt::CaseInsensitive)) {
for (i = 0; i < xs.size(); i++) {
if (times <= xs.value(i)) {
frame_num = fs.at(i);
break;
}
}
}
if (cap_file_ && frame_num > 0) {
cf_goto_frame(cap_file_, frame_num);
}
ui->hintLabel->setText(QString(tr("<small><i>%1: %2 Time: %3 secs </i></small>"))
.arg(plottable->name())
.arg(floor(ui->sctpPlot->yAxis->pixelToCoord(event->pos().y()) + 0.5))
.arg(ui->sctpPlot->xAxis->pixelToCoord(event->pos().x())));
}
void SCTPGraphDialog::save_graph(QDialog *dlg, QCustomPlot *plot)
{
QString file_name, extension;
QDir path(wsApp->lastOpenDir());
QString pdf_filter = tr("Portable Document Format (*.pdf)");
QString png_filter = tr("Portable Network Graphics (*.png)");
QString bmp_filter = tr("Windows Bitmap (*.bmp)");
// Gaze upon my beautiful graph with lossy artifacts!
QString jpeg_filter = tr("JPEG File Interchange Format (*.jpeg *.jpg)");
QString filter = QString("%1;;%2;;%3;;%4")
.arg(pdf_filter)
.arg(png_filter)
.arg(bmp_filter)
.arg(jpeg_filter);
file_name = QFileDialog::getSaveFileName(dlg, wsApp->windowTitleString(tr("Save Graph As" UTF8_HORIZONTAL_ELLIPSIS)),
path.canonicalPath(), filter, &extension);
if (file_name.length() > 0) {
bool save_ok = false;
if (extension.compare(pdf_filter) == 0) {
save_ok = plot->savePdf(file_name);
} else if (extension.compare(png_filter) == 0) {
save_ok = plot->savePng(file_name);
} else if (extension.compare(bmp_filter) == 0) {
save_ok = plot->saveBmp(file_name);
} else if (extension.compare(jpeg_filter) == 0) {
save_ok = plot->saveJpg(file_name);
}
// else error dialog?
if (save_ok) {
path = QDir(file_name);
wsApp->setLastOpenDir(path.canonicalPath().toUtf8().constData());
}
}
}
void SCTPGraphDialog::on_saveButton_clicked()
{
save_graph(this, ui->sctpPlot);
}
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
```
|
```markdown
# Array2D
In C and Objective-C, you can write the following line,
int cookies[9][7];
to make a 9x7 grid of cookies. This creates a two-dimensional array of 63 elements. To find the cookie at column 3 and row 6, you can write:
myCookie = cookies[3][6];
This statement is not acceptable in Swift. To create a multi-dimensional array in Swift, you can write:
```swift
var cookies = [[Int]]()
for _ in 1...9 {
var row = [Int]()
for _ in 1...7 {
row.append(0)
}
cookies.append(row)
}
```
Then, to find a cookie, you can write:
```swift
let myCookie = cookies[3][6]
```
You can also create the array in a single line of code:
```swift
var cookies = [[Int]](repeating: [Int](repeating: 0, count: 7), count: 9)
```
This looks complicated, but you can simplify it with a helper function:
```swift
func dim<T>(_ count: Int, _ value: T) -> [T] {
return [T](repeating: value, count: count)
}
```
Then, you can create the array:
```swift
var cookies = dim(9, dim(7, 0))
```
Swift infers that the datatype of the array must be `Int` because you specified `0` as the default value of the array elements. To use a string instead, you can write:
```swift
var cookies = dim(9, dim(7, "yum"))
```
The `dim()` function makes it easy to go into even more dimensions:
```swift
var threeDimensions = dim(2, dim(3, dim(4, 0)))
```
The downside of using multi-dimensional arrays or multiple nested arrays in this way is to lose track of what dimension represents what.
Instead, you can create your own type that acts like a 2-D array which is more convenient to use:
```swift
public struct Array2D<T> {
public let columns: Int
public let rows: Int
fileprivate var array: [T]
public init(columns: Int, rows: Int, initialValue: T) {
self.columns = columns
self.rows = rows
array = .init(repeating: initialValue, count: rows*columns)
}
public subscript(column: Int, row: Int) -> T {
get {
precondition(column < columns, "Column \(column) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))")
precondition(row < rows, "Row \(row) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))")
return array[row*columns + column]
}
set {
precondition(column < columns, "Column \(column) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))")
precondition(row < rows, "Row \(row) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))")
array[row*columns + column] = newValue
}
}
}
```
`Array2D` is a generic type, so it can hold any kind of object, not just numbers.
To create an instance of `Array2D`, you can write:
```swift
var cookies = Array2D(columns: 9, rows: 7, initialValue: 0)
```
By using the `subscript` function, you can retrieve an object from the array:
```swift
let myCookie = cookies[column, row]
```
Or, you can change it:
```swift
cookies[column, row] = newCookie
```
Internally, `Array2D` uses a single one-dimensional array to store the data. The index of an object in that array is given by `(row x numberOfColumns) + column`, but as a user of `Array2D`, you only need to think in terms of "column" and "row", and the details will be done by `Array2D`. This is the advantage of wrapping primitive types into a wrapper class or struct.
*Written for Swift Algorithm Club by Matthijs Hollemans*
```
|
```c
/* vi:set et sw=2 sts=2 cin cino=t0,f0,(0,{s,>2s,n-s,^-s,e-s:
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
*
* 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
*
* You should have received a copy of the GNU Lesser General Public
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include <errno.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <gio/gio.h>
#include <gio/gunixfdlist.h>
#include "flatpak-dbus-generated.h"
#include "flatpak-session-helper.h"
#include "flatpak-utils-base-private.h"
static GStrv original_environ = NULL;
static char *monitor_dir;
static char *p11_kit_server_socket_path;
static int p11_kit_server_pid = 0;
static GHashTable *client_pid_data_hash = NULL;
static GDBusConnection *session_bus = NULL;
static void
do_atexit (void)
{
if (p11_kit_server_pid != 0)
kill (p11_kit_server_pid, SIGTERM);
}
static void
handle_sigterm (int signum)
{
struct sigaction action = { 0 };
do_atexit ();
action.sa_handler = SIG_DFL;
sigaction (signum, &action, NULL);
raise (signum);
}
typedef struct
{
GPid pid;
char *client;
guint child_watch;
gboolean watch_bus;
} PidData;
static void
pid_data_free (PidData *data)
{
g_free (data->client);
g_free (data);
}
static gboolean
handle_request_session (FlatpakSessionHelper *object,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
GVariantBuilder builder;
g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
g_variant_builder_add (&builder, "{s@v}", "path",
g_variant_new_variant (g_variant_new_string (monitor_dir)));
if (p11_kit_server_socket_path)
g_variant_builder_add (&builder, "{s@v}", "pkcs11-socket",
g_variant_new_variant (g_variant_new_string (p11_kit_server_socket_path)));
flatpak_session_helper_complete_request_session (object, invocation,
g_variant_builder_end (&builder));
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static void
child_watch_died (GPid pid,
gint status,
gpointer user_data)
{
PidData *pid_data = user_data;
g_autoptr(GVariant) signal_variant = NULL;
g_info ("Client Pid %d died", pid_data->pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, status));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
FLATPAK_SESSION_HELPER_PATH_DEVELOPMENT,
FLATPAK_SESSION_HELPER_INTERFACE_DEVELOPMENT,
"HostCommandExited",
signal_variant,
NULL);
/* This frees the pid_data, so be careful */
g_hash_table_remove (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid));
}
typedef struct
{
int from;
int to;
int final;
} FdMapEntry;
typedef struct
{
FdMapEntry *fd_map;
int fd_map_len;
gboolean set_tty;
int tty;
} ChildSetupData;
static void
child_setup_func (gpointer user_data)
{
ChildSetupData *data = (ChildSetupData *) user_data;
FdMapEntry *fd_map = data->fd_map;
sigset_t set;
int i;
/* Unblock all signals */
sigemptyset (&set);
if (pthread_sigmask (SIG_SETMASK, &set, NULL) == -1)
{
g_error ("Failed to unblock signals when starting child");
return;
}
/* Reset the handlers for all signals to their defaults. */
for (i = 1; i < NSIG; i++)
{
if (i != SIGSTOP && i != SIGKILL)
signal (i, SIG_DFL);
}
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from != fd_map[i].to)
{
dup2 (fd_map[i].from, fd_map[i].to);
close (fd_map[i].from);
}
}
/* Second pass in case we needed an in-between fd value to avoid conflicts */
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].to != fd_map[i].final)
{
dup2 (fd_map[i].to, fd_map[i].final);
close (fd_map[i].to);
}
}
/* We become our own session and process group, because it never makes sense
to share the flatpak-session-helper dbus activated process group */
setsid ();
setpgid (0, 0);
if (data->set_tty)
{
/* data->tty is our from fd which is closed at this point.
* so locate the destination fd and use it for the ioctl.
*/
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from == data->tty)
{
if (ioctl (fd_map[i].final, TIOCSCTTY, 0) == -1)
g_info ("ioctl(%d, TIOCSCTTY, 0) failed: %s",
fd_map[i].final, strerror (errno));
break;
}
}
}
}
static gboolean
handle_host_command (FlatpakDevelopment *object,
GDBusMethodInvocation *invocation,
GUnixFDList *fd_list,
const gchar *arg_cwd_path,
const gchar *const *arg_argv,
GVariant *arg_fds,
GVariant *arg_envs,
guint flags)
{
g_autoptr(GError) error = NULL;
ChildSetupData child_setup_data = { NULL };
GPid pid;
PidData *pid_data;
gsize i, j, n_fds, n_envs;
const gint *fds;
g_autofree FdMapEntry *fd_map = NULL;
gchar **env;
gint32 max_fd;
if (*arg_cwd_path == 0)
arg_cwd_path = NULL;
if (arg_argv == NULL || *arg_argv == NULL || *arg_argv[0] == 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No command given");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (!g_variant_is_of_type (arg_fds, G_VARIANT_TYPE ("a{uh}")) ||
!g_variant_is_of_type (arg_envs, G_VARIANT_TYPE ("a{ss}")) ||
(flags & ~(FLATPAK_HOST_COMMAND_FLAGS_CLEAR_ENV |
FLATPAK_HOST_COMMAND_FLAGS_WATCH_BUS)) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Unexpected argument");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_info ("Running host command %s", arg_argv[0]);
n_fds = 0;
fds = NULL;
if (fd_list != NULL)
{
n_fds = g_variant_n_children (arg_fds);
fds = g_unix_fd_list_peek_fds (fd_list, NULL);
}
fd_map = g_new0 (FdMapEntry, n_fds);
child_setup_data.fd_map = fd_map;
child_setup_data.fd_map_len = n_fds;
max_fd = -1;
for (i = 0; i < n_fds; i++)
{
gint32 handle, fd;
g_variant_get_child (arg_fds, i, "{uh}", &fd, &handle);
fd_map[i].to = fd;
fd_map[i].from = fds[i];
fd_map[i].final = fd_map[i].to;
/* If stdin/out/err is a tty we try to set it as the controlling
tty for the app, this way we can use this to run in a terminal. */
if ((fd == 0 || fd == 1 || fd == 2) &&
!child_setup_data.set_tty &&
isatty (fds[i]))
{
child_setup_data.set_tty = TRUE;
child_setup_data.tty = fds[i];
}
max_fd = MAX (max_fd, fd_map[i].to);
max_fd = MAX (max_fd, fd_map[i].from);
}
/* We make a second pass over the fds to find if any "to" fd index
overlaps an already in use fd (i.e. one in the "from" category
that are allocated randomly). If a fd overlaps "to" fd then its
a caller issue and not our fault, so we ignore that. */
for (i = 0; i < n_fds; i++)
{
int to_fd = fd_map[i].to;
gboolean conflict = FALSE;
/* At this point we're fine with using "from" values for this
value (because we handle to==from in the code), or values
that are before "i" in the fd_map (because those will be
closed at this point when dup:ing). However, we can't
reuse a fd that is in "from" for j > i. */
for (j = i + 1; j < n_fds; j++)
{
int from_fd = fd_map[j].from;
if (from_fd == to_fd)
{
conflict = TRUE;
break;
}
}
if (conflict)
fd_map[i].to = ++max_fd;
}
if (flags & FLATPAK_HOST_COMMAND_FLAGS_CLEAR_ENV)
{
char *empty[] = { NULL };
env = g_strdupv (empty);
}
else
env = g_strdupv (original_environ);
n_envs = g_variant_n_children (arg_envs);
for (i = 0; i < n_envs; i++)
{
const char *var = NULL;
const char *val = NULL;
g_variant_get_child (arg_envs, i, "{&s&s}", &var, &val);
env = g_environ_setenv (env, var, val, TRUE);
}
if (!g_spawn_async_with_pipes (arg_cwd_path,
(char **) arg_argv,
env,
G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
child_setup_func, &child_setup_data,
&pid,
NULL,
NULL,
NULL,
&error))
{
gint code = G_DBUS_ERROR_FAILED;
if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_ACCES))
code = G_DBUS_ERROR_ACCESS_DENIED;
else if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT))
code = G_DBUS_ERROR_FILE_NOT_FOUND;
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, code,
"Failed to start command: %s",
error->message);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
pid_data = g_new0 (PidData, 1);
pid_data->pid = pid;
pid_data->client = g_strdup (g_dbus_method_invocation_get_sender (invocation));
pid_data->watch_bus = (flags & FLATPAK_HOST_COMMAND_FLAGS_WATCH_BUS) != 0;
pid_data->child_watch = g_child_watch_add_full (G_PRIORITY_DEFAULT,
pid,
child_watch_died,
pid_data,
NULL);
g_info ("Client Pid is %d", pid_data->pid);
g_hash_table_replace (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid),
pid_data);
flatpak_development_complete_host_command (object, invocation, NULL,
pid_data->pid);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static gboolean
handle_host_command_signal (FlatpakDevelopment *object,
GDBusMethodInvocation *invocation,
guint arg_pid,
guint arg_signal,
gboolean to_process_group)
{
PidData *pid_data = NULL;
pid_data = g_hash_table_lookup (client_pid_data_hash, GUINT_TO_POINTER (arg_pid));
if (pid_data == NULL ||
strcmp (pid_data->client, g_dbus_method_invocation_get_sender (invocation)) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,
"No such pid");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_info ("Sending signal %d to client pid %d", arg_signal, arg_pid);
if (to_process_group)
killpg (pid_data->pid, arg_signal);
else
kill (pid_data->pid, arg_signal);
flatpak_development_complete_host_command_signal (object, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static void
name_owner_changed (GDBusConnection *connection,
const gchar *sender_name,
const gchar *object_path,
const gchar *interface_name,
const gchar *signal_name,
GVariant *parameters,
gpointer user_data)
{
const char *name, *from, *to;
g_variant_get (parameters, "(&s&s&s)", &name, &from, &to);
if (name[0] == ':' &&
strcmp (name, from) == 0 &&
strcmp (to, "") == 0)
{
GHashTableIter iter;
PidData *pid_data = NULL;
gpointer value = NULL;
GList *list = NULL, *l;
g_hash_table_iter_init (&iter, client_pid_data_hash);
while (g_hash_table_iter_next (&iter, NULL, &value))
{
pid_data = value;
if (pid_data->watch_bus && g_str_equal (pid_data->client, name))
list = g_list_prepend (list, pid_data);
}
for (l = list; l; l = l->next)
{
pid_data = l->data;
killpg (pid_data->pid, SIGINT);
}
g_list_free (list);
}
}
#define DBUS_NAME_DBUS "org.freedesktop.DBus"
#define DBUS_INTERFACE_DBUS DBUS_NAME_DBUS
#define DBUS_PATH_DBUS "/org/freedesktop/DBus"
static void
on_bus_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
FlatpakSessionHelper *helper;
FlatpakDevelopment *devel;
GError *error = NULL;
g_dbus_connection_signal_subscribe (connection,
DBUS_NAME_DBUS,
DBUS_INTERFACE_DBUS,
"NameOwnerChanged",
DBUS_PATH_DBUS,
NULL,
G_DBUS_SIGNAL_FLAGS_NONE,
name_owner_changed,
NULL, NULL);
helper = flatpak_session_helper_skeleton_new ();
flatpak_session_helper_set_version (FLATPAK_SESSION_HELPER (helper), 1);
g_signal_connect (helper, "handle-request-session", G_CALLBACK (handle_request_session), NULL);
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (helper),
connection,
FLATPAK_SESSION_HELPER_PATH,
&error))
{
g_warning ("error: %s", error->message);
g_error_free (error);
}
devel = flatpak_development_skeleton_new ();
flatpak_development_set_version (FLATPAK_DEVELOPMENT (devel), 1);
g_signal_connect (devel, "handle-host-command", G_CALLBACK (handle_host_command), NULL);
g_signal_connect (devel, "handle-host-command-signal", G_CALLBACK (handle_host_command_signal), NULL);
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (devel),
connection,
FLATPAK_SESSION_HELPER_PATH_DEVELOPMENT,
&error))
{
g_warning ("error: %s", error->message);
g_error_free (error);
}
}
static void
on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
}
static void
on_name_lost (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
exit (1);
}
/*
* In the case that the monitored file is a symlink, we set up a separate
* GFileMonitor for the real target of the link so that we don't miss updates
* to the linked file contents. This is critical in the case of resolv.conf
* which on stateless systems is often a symlink to a dyamically-generated
* or updated file in /run.
*/
typedef struct
{
const gchar *source;
char *real;
GFileMonitor *monitor_source;
GFileMonitor *monitor_real;
} MonitorData;
static void
monitor_data_free (MonitorData *data)
{
free (data->real);
g_signal_handlers_disconnect_by_data (data->monitor_source, data);
g_object_unref (data->monitor_source);
if (data->monitor_real)
{
g_signal_handlers_disconnect_by_data (data->monitor_real, data);
g_object_unref (data->monitor_real);
}
g_free (data);
}
G_DEFINE_AUTOPTR_CLEANUP_FUNC (MonitorData, monitor_data_free)
static void
copy_file (const char *source,
const char *target_dir)
{
char *basename = g_path_get_basename (source);
char *dest = g_build_filename (target_dir, basename, NULL);
gchar *contents = NULL;
gsize len;
if (g_file_get_contents (source, &contents, &len, NULL))
g_file_set_contents (dest, contents, len, NULL);
g_free (basename);
g_free (dest);
g_free (contents);
}
static void file_changed (GFileMonitor *monitor,
GFile *file,
GFile *other_file,
GFileMonitorEvent event_type,
MonitorData *data);
static void
update_real_monitor (MonitorData *data)
{
char *real = realpath (data->source, NULL);
if (real == NULL)
{
g_info ("unable to get real path to monitor host file %s: %s", data->source,
g_strerror (errno));
return;
}
/* source path matches real path, second monitor is not required, but an old
* one may still exist. set to NULL and compare to what we have. */
if (!g_strcmp0 (data->source, real))
{
free (real);
real = NULL;
}
/* no more work needed if the monitor we have matches the additional monitor
we need (including NULL == NULL) */
if (!g_strcmp0 (data->real, real))
{
free (real);
return;
}
/* otherwise we're not monitoring the right thing and need to remove
any old monitor and make a new one if needed */
free (data->real);
data->real = real;
if (data->monitor_real)
{
g_signal_handlers_disconnect_by_data (data->monitor_real, data);
g_clear_object (&(data->monitor_real));
}
if (!real)
return;
g_autoptr(GFile) r = g_file_new_for_path (real);
g_autoptr(GError) err = NULL;
data->monitor_real = g_file_monitor_file (r, G_FILE_MONITOR_NONE, NULL, &err);
if (!data->monitor_real)
{
g_info ("failed to monitor host file %s (real path of %s): %s",
real, data->source, err->message);
return;
}
g_signal_connect (data->monitor_real, "changed", G_CALLBACK (file_changed), data);
}
static void
file_monitor_do (MonitorData *data)
{
update_real_monitor (data);
copy_file (data->source, monitor_dir);
if (strcmp (data->source, "/etc/localtime") == 0)
{
/* We can't update the /etc/localtime symlink at runtime, nor can we make it a of the
* correct form "../usr/share/zoneinfo/$timezone". So, instead we use the old debian
* /etc/timezone file for telling the sandbox the timezone. */
g_autofree char *dest = g_build_filename (monitor_dir, "timezone", NULL);
g_autofree char *raw_timezone = flatpak_get_timezone ();
g_autofree char *timezone_content = g_strdup_printf ("%s\n", raw_timezone);
g_file_set_contents (dest, timezone_content, -1, NULL);
}
}
static void
file_changed (GFileMonitor *monitor,
GFile *file,
GFile *other_file,
GFileMonitorEvent event_type,
MonitorData *data)
{
if (event_type != G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT)
return;
file_monitor_do (data);
}
static MonitorData *
setup_file_monitor (const char *source)
{
g_autoptr(GFile) s = g_file_new_for_path (source);
g_autoptr(GError) err = NULL;
GFileMonitor *monitor = NULL;
MonitorData *data = NULL;
data = g_new0 (MonitorData, 1);
data->source = source;
monitor = g_file_monitor_file (s, G_FILE_MONITOR_NONE, NULL, &err);
if (monitor)
{
data->monitor_source = monitor;
g_signal_connect (monitor, "changed", G_CALLBACK (file_changed), data);
}
else
{
g_info ("failed to monitor host file %s: %s", source, err->message);
}
file_monitor_do (data);
return data;
}
static void
message_handler (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer user_data)
{
/* Make this look like normal console output */
if (log_level & (G_LOG_LEVEL_DEBUG | G_LOG_LEVEL_INFO))
g_printerr ("F: %s\n", message);
else
g_printerr ("%s: %s\n", g_get_prgname (), message);
}
static void
start_p11_kit_server (const char *flatpak_dir)
{
g_autofree char *socket_basename = g_strdup_printf ("pkcs11-flatpak-%d", getpid ());
g_autofree char *socket_path = g_build_filename (flatpak_dir, socket_basename, NULL);
g_autofree char *p11_kit_stdout = NULL;
gint exit_status;
g_autoptr(GError) local_error = NULL;
g_auto(GStrv) stdout_lines = NULL;
int i;
char *p11_argv[] = {
"p11-kit", "server",
/* We explicitly request --sh here, because we then fail on earlier versions that doesn't support
* this flag. This is good, because those earlier versions did not properly daemonize and caused
* the spawn_sync to hang forever, waiting for the pipe to close.
*/
"--sh",
"-n", socket_path,
"--provider", "p11-kit-trust.so",
"pkcs11:model=p11-kit-trust?write-protected=yes",
NULL
};
g_info ("starting p11-kit server");
if (!g_spawn_sync (NULL,
p11_argv, NULL, G_SPAWN_SEARCH_PATH | G_SPAWN_STDERR_TO_DEV_NULL,
NULL, NULL,
&p11_kit_stdout, NULL,
&exit_status, &local_error))
{
g_warning ("Unable to start p11-kit server: %s", local_error->message);
return;
}
if (!g_spawn_check_exit_status (exit_status, &local_error))
{
g_warning ("Unable to start p11-kit server: %s", local_error->message);
return;
}
stdout_lines = g_strsplit (p11_kit_stdout, "\n", 0);
/* Output is something like:
P11_KIT_SERVER_ADDRESS=unix:path=/run/user/1000/p11-kit/pkcs11-2603742; export P11_KIT_SERVER_ADDRESS;
P11_KIT_SERVER_PID=2603743; export P11_KIT_SERVER_PID;
*/
for (i = 0; stdout_lines[i] != NULL; i++)
{
char *line = stdout_lines[i];
if (g_str_has_prefix (line, "P11_KIT_SERVER_PID="))
{
char *pid = line + strlen ("P11_KIT_SERVER_PID=");
char *p = pid;
while (g_ascii_isdigit (*p))
p++;
*p = 0;
p11_kit_server_pid = atol (pid);
}
}
if (p11_kit_server_pid != 0)
{
g_info ("Using p11-kit socket path %s, pid %d", socket_path, p11_kit_server_pid);
p11_kit_server_socket_path = g_steal_pointer (&socket_path);
}
else
g_info ("Not using p11-kit due to older version");
}
int
main (int argc,
char **argv)
{
guint owner_id;
GMainLoop *loop;
gboolean replace;
gboolean verbose;
gboolean show_version;
g_autoptr(GOptionContext) context = NULL;
GBusNameOwnerFlags flags;
g_autofree char *pk11_program = NULL;
g_autofree char *flatpak_dir = NULL;
g_autoptr(GError) error = NULL;
const GOptionEntry options[] = {
{ "replace", 'r', 0, G_OPTION_ARG_NONE, &replace, "Replace old daemon.", NULL },
{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Enable debug output.", NULL },
{ "version", 0, 0, G_OPTION_ARG_NONE, &show_version, "Show program version.", NULL},
{ NULL }
};
g_autoptr(MonitorData) m_resolv_conf = NULL,
m_host_conf = NULL,
m_hosts = NULL,
m_gai_conf = NULL,
m_localtime = NULL;
struct sigaction action;
/* Save the enviroment before changing anything, so that subprocesses
* can get the unchanged version */
original_environ = g_get_environ ();
atexit (do_atexit);
memset (&action, 0, sizeof (struct sigaction));
action.sa_handler = handle_sigterm;
sigaction (SIGTERM, &action, NULL);
sigaction (SIGHUP, &action, NULL);
sigaction (SIGINT, &action, NULL);
setlocale (LC_ALL, "");
g_setenv ("GIO_USE_VFS", "local", TRUE);
g_set_prgname (argv[0]);
g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, message_handler, NULL);
context = g_option_context_new ("");
replace = FALSE;
verbose = FALSE;
show_version = FALSE;
g_option_context_set_summary (context, "Flatpak session helper");
g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);
if (!g_option_context_parse (context, &argc, &argv, &error))
{
g_printerr ("%s: %s", g_get_application_name (), error->message);
g_printerr ("\n");
g_printerr ("Try \"%s --help\" for more information.",
g_get_prgname ());
g_printerr ("\n");
return 1;
}
g_clear_pointer (&context, g_option_context_free);
if (show_version)
{
g_print (PACKAGE_STRING "\n");
return 0;
}
if (verbose)
g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_INFO, message_handler, NULL);
client_pid_data_hash = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) pid_data_free);
session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
if (session_bus == NULL)
{
g_printerr ("Can't find bus: %s\n", error->message);
return 1;
}
flatpak_dir = g_build_filename (g_get_user_runtime_dir (), ".flatpak-helper", NULL);
if (g_mkdir_with_parents (flatpak_dir, 0700) != 0)
{
g_print ("Can't create %s\n", monitor_dir);
exit (1);
}
pk11_program = g_find_program_in_path ("p11-kit");
if (pk11_program)
start_p11_kit_server (flatpak_dir);
else
g_info ("p11-kit not found");
monitor_dir = g_build_filename (flatpak_dir, "monitor", NULL);
if (g_mkdir_with_parents (monitor_dir, 0755) != 0)
{
g_print ("Can't create %s\n", monitor_dir);
exit (1);
}
m_resolv_conf = setup_file_monitor ("/etc/resolv.conf");
m_host_conf = setup_file_monitor ("/etc/host.conf");
m_hosts = setup_file_monitor ("/etc/hosts");
m_gai_conf = setup_file_monitor ("/etc/gai.conf");
m_localtime = setup_file_monitor ("/etc/localtime");
flags = G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT;
if (replace)
flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE;
owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
FLATPAK_SESSION_HELPER_BUS_NAME,
flags,
on_bus_acquired,
on_name_acquired,
on_name_lost,
NULL,
NULL);
loop = g_main_loop_new (NULL, FALSE);
g_main_loop_run (loop);
g_bus_unown_name (owner_id);
g_strfreev (original_environ);
return 0;
}
```
|
Pant Halt railway station served the hamlet of Pant-pastynog, Denbighshire, Wales, from 1905 to 1915 on the Pontcysyllte branch.
History
The station was opened on 1 May 1905 by the Great Western Railway when they introduced railmotor services from Wrexham General station as far as Wynn Hall Halt. It was situated on the south side of the B5097. It had no station buildings or any other facilities but nearby was The Pant Brickworks, which was served by rail. The station closed on 22 March 1915 after losing to the competition of the newly introduced bus services. The Pontcysyllte branch remained in use for goods traffic until 1953, and after that the line to the south of Pant was closed and lifted, but the section of the line from Pant northwards remained open to serve the brick works. The station's final use was a rail tour on 18 April 1959. The section of the line finally closed on 14 October 1963, and the line was lifted in 1964.
References
Disused railway stations in Denbighshire
Former Great Western Railway stations
Railway stations in Great Britain opened in 1905
Railway stations in Great Britain closed in 1915
1905 establishments in Wales
1915 disestablishments in Wales
|
The Cougar Fund is a non-profit educational organization concerned with protecting the cougar throughout the Americas. It is based in Jackson, Wyoming.
History
The Cougar Fund was founded in 2001 by the writer Cara Blessley Lowe and the photographer Tom Mangelsen after a first-hand experience observing a lion and her three cubs on the National Elk Refuge in Jackson Hole, Wyoming. Frequent collaborators, Blessley Lowe and Mangelsen produced a book called Spirit of the Rockies: The Mountain Lions of Jackson Hole and a subsequent documentary short film on the historical event. These two pieces went on to garner major national media attention, broadly publicizing the principal issues facing cougars at the dawn of the 21st century: lack of scientific data on cougar populations within state game agencies, inadequate regulations on protection for female cougars and their dependent young, and a dwindling natural habitat further fragmented by human development.
In 2002, Jane Goodall joined the Board of Directors of the Cougar Fund. Since 2010, the Humane Society Wildlife Land Trust supports the Cougar Fund.
Description
The Cougar Fund is a 501(c)3 non-profit educational organization based in Jackson, Wyoming, concerned with protecting the cougar throughout the Americas. The Cougar Fund educates the public on the value of cougars in nature and promotes the gathering and application of sound science in their management.
Important to The Cougar Fund is an ethic of collaborative efforts in approaching predator conservation and management. There is room for all stakeholders to participate in The Cougar Fund, and its membership base includes hunters and non-hunters alike.
Board of directors
President: Rick Hopkins
Vice-President, Co-Founder: Thomas D. Mangelsen
Treasurer, Co-Founder: Cara Blessley Lowe
Members:
Marc Bekoff
Patricio Robles Gil
Jane Goodall, DBE
Corinne E. Rutledge
Bibliography
References
External links
Official website
Cat conservation organizations
Non-profit organizations based in Wyoming
Jackson, Wyoming
Environmental organizations established in 2001
2001 establishments in Wyoming
|
```c++
#include <Storages/ReadInOrderOptimizer.h>
#include <Core/Settings.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/TreeRewriter.h>
#include <Interpreters/replaceAliasColumnsInQuery.h>
#include <Functions/IFunction.h>
#include <Functions/FunctionFactory.h>
#include <Interpreters/TableJoin.h>
#include <Interpreters/Context.h>
#include <Parsers/ASTSelectQuery.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTIdentifier.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
}
namespace
{
/// Finds expression like x = 'y' or f(x) = 'y',
/// where `x` is identifier, 'y' is literal and `f` is injective functions.
ASTPtr getFixedPoint(const ASTPtr & ast, const ContextPtr & context)
{
const auto * func = ast->as<ASTFunction>();
if (!func || func->name != "equals")
return nullptr;
if (!func->arguments || func->arguments->children.size() != 2)
return nullptr;
const auto & lhs = func->arguments->children[0];
const auto & rhs = func->arguments->children[1];
if (!lhs->as<ASTLiteral>() && !rhs->as<ASTLiteral>())
return nullptr;
/// Case of two literals doesn't make sense.
if (lhs->as<ASTLiteral>() && rhs->as<ASTLiteral>())
return nullptr;
/// If indetifier is wrapped into injective functions, remove them.
auto argument = lhs->as<ASTLiteral>() ? rhs : lhs;
while (const auto * arg_func = argument->as<ASTFunction>())
{
if (!arg_func->arguments || arg_func->arguments->children.size() != 1)
return nullptr;
auto func_resolver = FunctionFactory::instance().tryGet(arg_func->name, context);
if (!func_resolver || !func_resolver->isInjective({}))
return nullptr;
argument = arg_func->arguments->children[0];
}
return argument->as<ASTIdentifier>() ? argument : nullptr;
}
NameSet getFixedSortingColumns(
const ASTSelectQuery & query, const Names & sorting_key_columns, const ContextPtr & context)
{
ASTPtr condition;
if (query.where() && query.prewhere())
condition = makeASTFunction("and", query.where(), query.prewhere());
else if (query.where())
condition = query.where();
else if (query.prewhere())
condition = query.prewhere();
if (!condition)
return {};
/// Convert condition to CNF for more convenient analysis.
auto cnf = TreeCNFConverter::tryConvertToCNF(condition);
if (!cnf)
return {};
NameSet fixed_points;
NameSet sorting_key_columns_set(sorting_key_columns.begin(), sorting_key_columns.end());
/// If we met expression like 'column = x', where 'x' is literal,
/// in clause of size 1 in CNF, then we can guarantee
/// that in all filtered rows 'column' will be equal to 'x'.
cnf->iterateGroups([&](const auto & group)
{
if (group.size() == 1 && !group.begin()->negative)
{
auto fixed_point = getFixedPoint(group.begin()->ast, context);
if (fixed_point)
{
auto column_name = fixed_point->getColumnName();
if (sorting_key_columns_set.contains(column_name))
fixed_points.insert(column_name);
}
}
});
return fixed_points;
}
struct MatchResult
{
/// One of {-1, 0, 1} - direction of the match. 0 means - doesn't match.
int direction = 0;
/// If true then current key must be the last in the matched prefix of sort description.
bool is_last_key = false;
};
/// Optimize in case of exact match with order key element
/// or in some simple cases when order key element is wrapped into monotonic function.
MatchResult matchSortDescriptionAndKey(
const ExpressionActions::Actions & actions,
const SortColumnDescription & sort_column,
const String & sorting_key_column)
{
/// If required order depend on collation, it cannot be matched with primary key order.
/// Because primary keys cannot have collations.
if (sort_column.collator)
return {};
MatchResult result{sort_column.direction, false};
/// For the path: order by (sort_column, ...)
if (sort_column.column_name == sorting_key_column)
return result;
/// For the path: order by (function(sort_column), ...)
/// Allow only one simple monotonic functions with one argument
/// Why not allow multi monotonic functions?
bool found_function = false;
for (const auto & action : actions)
{
if (action.node->type != ActionsDAG::ActionType::FUNCTION)
continue;
if (found_function)
return {};
found_function = true;
if (action.node->children.size() != 1 || action.node->children.at(0)->result_name != sorting_key_column)
return {};
const auto & func = *action.node->function_base;
if (!func.hasInformationAboutMonotonicity())
return {};
auto monotonicity = func.getMonotonicityForRange(*func.getArgumentTypes().at(0), {}, {});
if (!monotonicity.is_monotonic)
return {};
/// If function is not strict monotonic, it can break order
/// if it's not last in the prefix of sort description.
/// E.g. if we have ORDER BY (d, u) -- ('2020-01-01', 1), ('2020-01-02', 0), ('2020-01-03', 1)
/// ORDER BY (toStartOfMonth(d), u) -- ('2020-01-01', 1), ('2020-01-01', 0), ('2020-01-01', 1)
if (!monotonicity.is_strict)
result.is_last_key = true;
if (!monotonicity.is_positive)
result.direction *= -1;
}
if (!found_function)
return {};
return result;
}
}
ReadInOrderOptimizer::ReadInOrderOptimizer(
const ASTSelectQuery & query_,
const ManyExpressionActions & elements_actions_,
const SortDescription & required_sort_description_,
const TreeRewriterResultPtr & syntax_result)
: elements_actions(elements_actions_)
, required_sort_description(required_sort_description_)
, query(query_)
{
if (elements_actions.size() != required_sort_description.size())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Sizes of sort description and actions are mismatched");
/// Do not analyze joined columns.
/// They may have aliases and come to description as is.
/// We can mismatch them with order key columns at stage of fetching columns.
forbidden_columns = syntax_result->getArrayJoinSourceNameSet();
// array join result columns cannot be used in alias expansion.
array_join_result_to_source = syntax_result->array_join_result_to_source;
}
InputOrderInfoPtr ReadInOrderOptimizer::getInputOrderImpl(
const StorageMetadataPtr & metadata_snapshot,
const SortDescription & description,
const ManyExpressionActions & actions,
const ContextPtr & context,
UInt64 limit) const
{
const Names & sorting_key_columns = metadata_snapshot->getSortingKeyColumns();
int read_direction = description.at(0).direction;
auto fixed_sorting_columns = getFixedSortingColumns(query, sorting_key_columns, context);
SortDescription sort_description_for_merging;
sort_description_for_merging.reserve(description.size());
size_t desc_pos = 0;
size_t key_pos = 0;
while (desc_pos < description.size() && key_pos < sorting_key_columns.size())
{
if (forbidden_columns.contains(description[desc_pos].column_name))
break;
auto match = matchSortDescriptionAndKey(actions[desc_pos]->getActions(), description[desc_pos], sorting_key_columns[key_pos]);
bool is_matched = match.direction && (desc_pos == 0 || match.direction == read_direction);
if (!is_matched)
{
/// If one of the sorting columns is constant after filtering,
/// skip it, because it won't affect order anymore.
if (fixed_sorting_columns.contains(sorting_key_columns[key_pos]))
{
++key_pos;
continue;
}
break;
}
if (desc_pos == 0)
read_direction = match.direction;
sort_description_for_merging.push_back(description[desc_pos]);
++desc_pos;
++key_pos;
if (match.is_last_key)
break;
}
if (sort_description_for_merging.empty())
return {};
return std::make_shared<InputOrderInfo>(std::move(sort_description_for_merging), key_pos, read_direction, limit);
}
InputOrderInfoPtr ReadInOrderOptimizer::getInputOrder(
const StorageMetadataPtr & metadata_snapshot, ContextPtr context, UInt64 limit) const
{
if (!metadata_snapshot->hasSortingKey())
return {};
auto aliased_columns = metadata_snapshot->getColumns().getAliases();
/// Replace alias column with proper expressions.
/// Currently we only support alias column without any function wrapper,
/// i.e.: `order by aliased_column` can have this optimization, but `order by function(aliased_column)` can not.
/// This suits most cases.
if (context->getSettingsRef().optimize_respect_aliases && !aliased_columns.empty())
{
SortDescription aliases_sort_description = required_sort_description;
ManyExpressionActions aliases_actions = elements_actions;
for (size_t i = 0; i < required_sort_description.size(); ++i)
{
if (!aliased_columns.contains(required_sort_description[i].column_name))
continue;
auto column_expr = metadata_snapshot->getColumns().get(required_sort_description[i].column_name).default_desc.expression->clone();
replaceAliasColumnsInQuery(column_expr, metadata_snapshot->getColumns(), array_join_result_to_source, context);
auto syntax_analyzer_result = TreeRewriter(context).analyze(column_expr, metadata_snapshot->getColumns().getAll());
auto expression_analyzer = ExpressionAnalyzer(column_expr, syntax_analyzer_result, context);
aliases_sort_description[i].column_name = column_expr->getColumnName();
aliases_actions[i] = expression_analyzer.getActions(true);
}
return getInputOrderImpl(metadata_snapshot, aliases_sort_description, aliases_actions, context, limit);
}
return getInputOrderImpl(metadata_snapshot, required_sort_description, elements_actions, context, limit);
}
}
```
|
"Lil Star" is the second international single from Kelis' fourth studio album, Kelis Was Here (2006). Released outside US (where "Blindfold Me" served as the second single), the single features Cee-Lo, who was at the time half of the duo Gnarls Barkley. Following the moderate success of "Bossy", the single has proven to be a return to form for Kelis; it debuted at number eight in Ireland and was also a huge hit in the United Kingdom reaching number three on the UK Singles Chart. The track was hailed by many music fans and critics as Kelis' "comeback" single, despite the fact "Bossy" was written specifically for Kelis' return to music.
Background and lyrics
"Lil Star" features Kelis singing about the times when she has self-doubt. "I can't be confident and bold and obnoxious all the time", Kelis says. "What kind of person would I be? I'm a human being and I have other sides, too. I'm not always secure and I'm not always confident. I have moments where I get self-conscious."
The song was tentatively set to be released on January 8, 2007, but to allow time for promotion the release date was pushed back to February 19. However, on January 8, the song was added to the C List of BBC Radio 1 Playlist, and has since been promoted to their A List, guaranteeing at least 20 plays a week.
The video for "Lil Star" was filmed by Marc Klasfeld, and has been on rotation since January 13, 2007 when it was added to British urban music channel MTV Base's videos roster.
"Lil Star" debuted on the UK Singles Chart at number 37 on January 28, 2007. The following week, high download sales enabled an 18-position jump to number 19. On February 12, 2007 "Lil Star" moved into the UK top 15 at the number-13 position. During its fourth week in the top 40, the song es slid down two placto number 15. However, on February 26, 2007, in the fifth week on the UK chart it moved from number 15 to the top three. "Lil Star" landed at number three on the UK Singles Chart in the week of its physical release.
Chart performance
"Lil Star" made its debut on the UK Singles Chart at number eighty-four on January 21, 2007 based on downloads alone five weeks before its release and climbed the charts rapidly to number thirty-seven within a matter of weeks due to strong download sales. Several weeks later it managed to make its initial peak at number thirteen based on downloads sales. After its official release it peaked at number three, becoming the first single from Kelis Was Here to reach the top three in the UK, and became Kelis' highest-charting single since 2004's "Millionaire". "Lil Star" also entered several other UK charts including the UK R&B Singles Chart where it peaked at number one, the UK Airplay Chart where it peaked at number three, the UK Official Download Chart where it reached number nine, and the UK iTunes Top 100 countdown where it peaked at number eleven. To date, "Lil Star" remains one of Kelis' best-selling singles in the UK where it sold over 118,000 copies. "Lil Star" also peaked at number eight in Ireland, her highest-peaking single since "Milkshake" back in 2003. "Lil Star" found similar success in Eastern Europe; it peaked at number four in Slovenia, number seven in Hungary, and number eighteen in Slovakia. Although "Lil Star" performed well in European countries such as the UK and Ireland, it became a commercial failure in Germany, peaking at number ninety-nine, Kelis' lowest-charting single there to date. "Lil Star" was to be released in Australia as the second single from Kelis Was Here, with its video having been aired on music programs around Australia, but for unknown reasons it did not happen and instead "I Don't Think So" was released.
Music video
The video for "Lil Star" was filmed in Los Angeles in December 2006 and directed by Marc Klasfeld, who had previously worked with Kelis on "Bossy" and "Blindfold Me" earlier in 2006. In the video Kelis is walking down a street in a large space suit-style coat, then singing to the stars. The stars take the formation of Cee-Lo and Kelis as they both sing, all wrapped up in a very mellow and calm atmosphere, relating to the song's theme. It premiered on MTV UK on January 13, 2007.
Track listings
UK CD 1
"Lil Star" (Radio Edit)
"80's Joint"
UK CD 2
"Lil Star" (Album Version)
"Lil Star" (Linus Loves Remix)
"Lil Star" (Soundboy Remix)
"Lil Star" (Future Cut Throw Back Mix)
"Lil Star" (Video)
12" single
Side A:
"Lil Star" (Main)
"Lil Star" (Instrumental)
Side B:
"Lil Star" (Main)
"Lil Star" (A Capella)
Promo remixes CD
"Lil Star" (Linus Loves Remix featuring Cee-Lo)
"Lil Star" (Linus Loves Dub featuring Cee-Lo)
"Lil Star" (Future Cut Remix featuring Cee-Lo)
"Lil Star" (Soundbwoy Remix featuring Cee-Lo)
"Lil Star" (Soundbwoy Instrumental)
"Lil Star" (Al Usher 12" Mix featuring Cee-Lo)
Charts
Weekly charts
Year-end charts
References
2000s ballads
2006 songs
2007 singles
Kelis songs
CeeLo Green songs
Music videos directed by Marc Klasfeld
Contemporary R&B ballads
Songs written by CeeLo Green
Songs written by Kelis
|
```c++
/*
*/
#include "opengl_impl_device.hpp"
#include "opengl_impl_device_context.hpp"
#include "opengl_impl_type_convert.hpp"
#include "opengl_hooks.hpp" // Fix name clashes with gl3w
#include "hook_manager.hpp"
#include "addon_manager.hpp"
#include <cstring> // std::memset, std::strlen
#define gl gl3wProcs.gl
struct DrawArraysIndirectCommand
{
GLuint count;
GLuint primcount;
GLuint first;
GLuint baseinstance;
};
struct DrawElementsIndirectCommand
{
GLuint count;
GLuint primcount;
GLuint firstindex;
GLuint basevertex;
GLuint baseinstance;
};
// Initialize thread local variable in this translation unit, to avoid the compiler generating calls to '__dyn_tls_on_demand_init' on every use in the frequently called functions below
thread_local reshade::opengl::device_context_impl *g_opengl_context = nullptr;
#if RESHADE_ADDON
reshade::api::pipeline_layout get_opengl_pipeline_layout();
// Helper class invoking the 'create/init_resource' add-on events for OpenGL resources
class init_resource
{
public:
init_resource(GLenum target, GLuint object, GLsizeiptr buffer_size, GLbitfield storage_flags) :
_target(GL_BUFFER), _object(object)
{
// Get object from current binding in case it was not specified
if (object == 0)
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), reinterpret_cast<GLint *>(&_object));
_desc = reshade::opengl::convert_resource_desc(target, buffer_size, storage_flags);
}
init_resource(GLenum target, GLuint object, GLsizei levels, GLsizei samples, GLenum internal_format, GLsizei width, GLsizei height, GLsizei depth) :
_target(target), _object(object)
{
GLint swizzle_mask[4] = { GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA };
if (target != GL_RENDERBUFFER)
{
if (object != 0)
{
// Get actual texture target from the texture object
gl.GetTextureParameteriv(object, GL_TEXTURE_TARGET, reinterpret_cast<GLint *>(&_target));
gl.GetTextureParameteriv(object, GL_TEXTURE_SWIZZLE_RGBA, swizzle_mask);
}
else
{
assert(!(target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z));
gl.GetTexParameteriv(target, GL_TEXTURE_SWIZZLE_RGBA, swizzle_mask);
}
}
if (object == 0)
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), reinterpret_cast<GLint *>(&_object));
_desc = reshade::opengl::convert_resource_desc(target, levels, samples, internal_format, width, height, depth, swizzle_mask);
}
explicit init_resource(const reshade::api::resource_desc &desc) :
_target(GL_NONE), _object(0), _desc(desc)
{
}
void invoke_create_event(GLsizeiptr *buffer_size, GLbitfield *storage_flags, const void *&data)
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
_initial_data.data = const_cast<void *>(data); // Row and depth pitch are unused for buffer data
if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(device, _desc, data != nullptr ? &_initial_data : nullptr, reshade::api::resource_usage::general))
{
reshade::opengl::convert_resource_desc(_desc, *buffer_size, *storage_flags);
data = _initial_data.data;
}
}
void invoke_create_event(GLsizei *levels, GLsizei *samples, GLenum *internal_format, GLsizei *width, GLsizei *height, GLsizei *depth)
{
auto pixels = static_cast<const void *>(nullptr);
invoke_create_event(levels, samples, internal_format, width, height, depth, GL_NONE, GL_NONE, pixels);
}
void invoke_create_event(GLsizei *levels, GLsizei *samples, GLenum *internal_format, GLsizei *width, GLsizei *height, GLsizei *depth, GLenum format, GLenum type, const void *&pixels)
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
reshade::api::subresource_data *const data = convert_mapped_subresource(format, type, pixels, _desc.texture.width, _desc.texture.height, _desc.texture.depth_or_layers);
if (reshade::invoke_addon_event<reshade::addon_event::create_resource>(device, _desc, data, reshade::api::resource_usage::general))
{
if (levels != nullptr)
*levels = _desc.texture.levels;
else
assert(_desc.texture.levels <= 1);
if (samples != nullptr)
*samples = _desc.texture.samples;
else
assert(_desc.texture.samples <= 1);
*internal_format = reshade::opengl::convert_format(_desc.texture.format);
if (width != nullptr)
*width = _desc.texture.width;
else
assert(_desc.texture.width == 1);
if (height != nullptr)
*height = _desc.texture.height;
else
assert(_desc.texture.height == 1);
if (depth != nullptr)
*depth = _desc.texture.depth_or_layers;
else
assert(_desc.texture.depth_or_layers == 1);
// Skip initial upload, data is uploaded after creation in 'invoke_initialize_event' below
pixels = nullptr;
_update_texture = (_initial_data.data != nullptr);
}
}
void invoke_initialize_event()
{
assert(_object != 0);
if (!reshade::has_addon_event<reshade::addon_event::init_resource>() && !reshade::has_addon_event<reshade::addon_event::init_resource_view>() && !_update_texture)
return;
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
const reshade::api::resource resource = reshade::opengl::make_resource_handle(_target, _object);
if (_update_texture)
{
assert(_target != GL_BUFFER);
device->update_texture_region(_initial_data, resource, 0, nullptr);
}
reshade::invoke_addon_event<reshade::addon_event::init_resource>(
device, _desc, _initial_data.data != nullptr ? &_initial_data : nullptr, reshade::api::resource_usage::general, resource);
if (_target == GL_BUFFER)
return;
const reshade::api::resource_usage usage_type = (_target == GL_RENDERBUFFER) ? reshade::api::resource_usage::render_target : reshade::api::resource_usage::undefined;
// Register all possible views of this texture too
reshade::invoke_addon_event<reshade::addon_event::init_resource_view>(
device, resource, usage_type, reshade::api::resource_view_desc(
reshade::opengl::convert_resource_view_type(_target), _desc.texture.format, 0, UINT32_MAX, 0, UINT32_MAX), reshade::opengl::make_resource_view_handle(_target, _object));
if (_target == GL_TEXTURE_CUBE_MAP)
{
for (GLuint face = 0; face < 6; ++face)
{
const GLenum face_target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + face;
reshade::invoke_addon_event<reshade::addon_event::init_resource_view>(
device, resource, usage_type, reshade::api::resource_view_desc(
reshade::opengl::convert_resource_view_type(face_target), _desc.texture.format, 0, UINT32_MAX, face, 1), reshade::opengl::make_resource_view_handle(face_target, _object));
}
}
}
reshade::api::subresource_data *convert_mapped_subresource(GLenum format, GLenum type, const void *pixels, GLuint width, GLuint height = 1, GLuint depth = 1)
{
if (pixels == nullptr)
return nullptr; // Likely a 'GL_PIXEL_UNPACK_BUFFER' currently bound ...
if (_target != GL_NONE && ((_desc.type != reshade::api::resource_type::texture_3d && _desc.texture.depth_or_layers != 1) || _desc.texture.levels > 1))
return nullptr; // Currently only a single subresource data element is passed to 'create_resource' and 'init_resource' (see '_initial_data'), so cannot handle textures with multiple subresources
GLint row_length = 0;
gl.GetIntegerv(GL_UNPACK_ROW_LENGTH, &row_length);
GLint slice_height = 0;
gl.GetIntegerv(GL_UNPACK_IMAGE_HEIGHT, &slice_height);
if (0 != row_length)
width = row_length;
if (0 != slice_height)
height = slice_height;
// Convert RGB to RGBA format (GL_RGB -> GL_RGBA, GL_BGR -> GL_BRGA, etc.)
const bool convert_rgb_to_rgba = (format == GL_RGB || format == GL_RGB_INTEGER || format == GL_BGR || format == GL_BGR_INTEGER) && type == GL_UNSIGNED_BYTE;
if (convert_rgb_to_rgba)
{
format += 1;
_temp_data.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * static_cast<size_t>(depth) * 4);
for (size_t z = 0; z < static_cast<size_t>(depth); ++z)
{
for (size_t y = 0; y < static_cast<size_t>(height); ++y)
{
for (size_t x = 0; x < static_cast<size_t>(width); ++x)
{
const size_t in_index = (z * width * height + y * width + x) * 3;
const size_t out_index = (z * width * height + y * width + x) * 4;
for (size_t c = 0; c < 3; ++c)
_temp_data[out_index + c] = static_cast<const uint8_t *>(pixels)[in_index + c];
_temp_data[out_index + 3] = 0xFF;
}
}
}
pixels = _temp_data.data();
}
// Convert BGRA to RGBA format (GL_BGRA -> GLRGBA)
const bool convert_bgra_to_rgba = (format == GL_BGRA || format == GL_BGRA_INTEGER) && type == GL_UNSIGNED_BYTE;
if (convert_bgra_to_rgba)
{
switch (format)
{
case GL_BGRA:
format = GL_RGBA;
break;
case GL_BGRA_INTEGER:
format = GL_RGBA_INTEGER;
break;
}
_temp_data.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * static_cast<size_t>(depth) * 4);
for (size_t z = 0; z < static_cast<size_t>(depth); ++z)
{
for (size_t y = 0; y < static_cast<size_t>(height); ++y)
{
for (size_t x = 0; x < static_cast<size_t>(width); ++x)
{
const size_t in_index = (z * width * height + y * width + x) * 4;
const size_t out_index = (z * width * height + y * width + x) * 4;
uint8_t b = static_cast<const uint8_t *>(pixels)[in_index + 0];
uint8_t r = static_cast<const uint8_t *>(pixels)[in_index + 2];
_temp_data[out_index + 0] = r;
_temp_data[out_index + 1] = static_cast<const uint8_t *>(pixels)[in_index + 1];
_temp_data[out_index + 2] = b;
_temp_data[out_index + 3] = static_cast<const uint8_t *>(pixels)[in_index + 3];;
}
}
}
pixels = _temp_data.data();
}
const auto pixels_format = reshade::opengl::convert_upload_format(format, type);
if (reshade::api::format_to_typeless(pixels_format) != reshade::api::format_to_typeless(_desc.texture.format) && !convert_rgb_to_rgba)
return nullptr;
_initial_data.row_pitch = reshade::api::format_row_pitch(pixels_format, width);
_initial_data.slice_pitch = reshade::api::format_slice_pitch(pixels_format, _initial_data.row_pitch, height);
GLint skip_rows = 0;
gl.GetIntegerv(GL_UNPACK_SKIP_ROWS, &skip_rows);
GLint skip_slices = 0;
gl.GetIntegerv(GL_UNPACK_SKIP_IMAGES, &skip_slices);
GLint skip_pixels = 0;
gl.GetIntegerv(GL_UNPACK_SKIP_PIXELS, &skip_pixels);
_initial_data.data =
static_cast<uint8_t *>(const_cast<void *>(pixels)) +
skip_rows * static_cast<size_t>(_initial_data.row_pitch) +
skip_slices * static_cast<size_t>(_initial_data.slice_pitch) +
skip_pixels * static_cast<size_t>(_initial_data.row_pitch / width);
return &_initial_data;
}
static bool is_texture_uninitialized(GLenum target)
{
GLint exists = 0;
gl.GetTexLevelParameteriv(target == GL_TEXTURE_CUBE_MAP || target == GL_TEXTURE_CUBE_MAP_ARRAY ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : target, 0, GL_TEXTURE_WIDTH, &exists);
return 0 == exists;
}
private:
GLenum _target;
GLuint _object;
reshade::api::resource_desc _desc;
std::vector<uint8_t> _temp_data;
reshade::api::subresource_data _initial_data = {};
bool _update_texture = false;
};
// Helper class invoking the 'create/init_resource_view' add-on events for OpenGL resource views
class init_resource_view
{
public:
init_resource_view(GLenum target, GLuint object, GLuint orig_buffer, GLenum internal_format, GLintptr offset, GLsizeiptr size) :
_target(target), _object(object)
{
// Get object from current binding in case it was not specified
if (object == 0)
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), reinterpret_cast<GLint *>(&_object));
_resource = reshade::opengl::make_resource_handle(GL_BUFFER, orig_buffer);
_desc = reshade::opengl::convert_resource_view_desc(target, internal_format, offset, size);
}
init_resource_view(GLenum target, GLuint object, GLuint orig_texture, GLenum internal_format, GLuint min_level, GLuint num_levels, GLuint min_layer, GLuint num_layers) :
_target(target), _object(object)
{
// Default parent target to the same target as the new texture view
GLenum orig_texture_target = target;
// 'glTextureView' is available since OpenGL 4.3, so no guarantee that 'glGetTextureParameteriv' exists, since it was introduced in OpenGL 4.5
if (gl.GetTextureParameteriv != nullptr)
gl.GetTextureParameteriv(orig_texture, GL_TEXTURE_TARGET, reinterpret_cast<GLint *>(&orig_texture_target));
if (object == 0)
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), reinterpret_cast<GLint *>(&_object));
_resource = reshade::opengl::make_resource_handle(orig_texture_target, orig_texture);
_desc = reshade::opengl::convert_resource_view_desc(target, internal_format, min_level, num_levels, min_layer, num_layers);
}
void invoke_create_event(GLenum *internal_format, GLintptr *offset, GLintptr *size)
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
if (reshade::invoke_addon_event<reshade::addon_event::create_resource_view>(device, _resource, reshade::api::resource_usage::undefined, _desc))
{
*internal_format = reshade::opengl::convert_format(_desc.format);
assert(_desc.buffer.offset <= static_cast<uint64_t>(std::numeric_limits<GLintptr>::max()));
*offset = static_cast<GLintptr>(_desc.buffer.offset);
assert(_desc.buffer.size <= static_cast<uint64_t>(std::numeric_limits<GLsizeiptr>::max()));
*size = static_cast<GLsizeiptr>(_desc.buffer.size);
}
}
void invoke_create_event(GLenum *internal_format, GLuint *min_level, GLuint *num_levels, GLuint *min_layer, GLuint *num_layers)
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
if (reshade::invoke_addon_event<reshade::addon_event::create_resource_view>(device, _resource, reshade::api::resource_usage::undefined, _desc))
{
*internal_format = reshade::opengl::convert_format(_desc.format);
*min_level = _desc.texture.first_level;
*min_layer = _desc.texture.first_layer;
if (_desc.texture.level_count == UINT32_MAX)
*num_levels = device->get_resource_desc(_resource).texture.levels;
else
*num_levels = _desc.texture.level_count;
if (_desc.texture.layer_count == UINT32_MAX)
*num_layers = device->get_resource_desc(_resource).texture.depth_or_layers;
else
*num_layers = _desc.texture.layer_count;
}
}
void invoke_initialize_event()
{
assert(_object != 0);
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
reshade::invoke_addon_event<reshade::addon_event::init_resource_view>(
device, _resource, reshade::api::resource_usage::undefined, _desc, reshade::opengl::make_resource_view_handle(_target, _object));
}
private:
GLenum _target;
GLuint _object;
reshade::api::resource _resource;
reshade::api::resource_view_desc _desc;
};
static void destroy_resource_or_view(GLenum target, GLuint object)
{
if (!g_opengl_context || (!reshade::has_addon_event<reshade::addon_event::destroy_resource>() && !reshade::has_addon_event<reshade::addon_event::destroy_resource_view>()))
return;
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
if (target != GL_BUFFER)
{
// Get actual texture target from the texture object
if (target == GL_TEXTURE && gl.GetTextureParameteriv != nullptr)
gl.GetTextureParameteriv(object, GL_TEXTURE_TARGET, reinterpret_cast<GLint *>(&target));
reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(device, reshade::opengl::make_resource_view_handle(target, object));
if (target == GL_TEXTURE_CUBE_MAP)
{
for (GLuint face = 0; face < 6; ++face)
{
const GLenum face_target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + face;
reshade::invoke_addon_event<reshade::addon_event::destroy_resource_view>(device, reshade::opengl::make_resource_view_handle(face_target, object));
}
}
}
if (target != GL_TEXTURE_BUFFER)
{
reshade::invoke_addon_event<reshade::addon_event::destroy_resource>(device, reshade::opengl::make_resource_handle(target, object));
}
}
static void update_framebuffer_object(GLenum target, GLuint framebuffer = 0)
{
if (!g_opengl_context || !(target == GL_FRAMEBUFFER || target == GL_DRAW_FRAMEBUFFER))
return;
// Only interested in existing framebuffers that are being bound to the render pipeline
if (gl.CheckFramebufferStatus(target) != GL_FRAMEBUFFER_COMPLETE)
return;
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
// Get object from current binding in case it was not specified (though it may still be zero)
if (framebuffer == 0)
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), reinterpret_cast<GLint *>(&framebuffer));
const reshade::api::resource_view default_attachment = device->get_framebuffer_attachment(framebuffer, GL_COLOR, 0);
g_opengl_context->update_current_window_height(default_attachment);
if (!reshade::has_addon_event<reshade::addon_event::bind_render_targets_and_depth_stencil>())
return;
uint32_t count = 0;
reshade::api::resource_view rtvs[8], dsv;
if (default_attachment != 0)
{
rtvs[0] = default_attachment;
for (count = 1; count < 8; ++count)
{
rtvs[count] = device->get_framebuffer_attachment(framebuffer, GL_COLOR, count);
if (rtvs[count] == 0)
break;
}
}
dsv = device->get_framebuffer_attachment(framebuffer, GL_DEPTH_STENCIL, 0);
reshade::invoke_addon_event<reshade::addon_event::bind_render_targets_and_depth_stencil>(g_opengl_context, count, rtvs, dsv);
}
#endif
#if RESHADE_ADDON >= 2
static bool copy_buffer_region(GLenum src_target, GLuint src_object, GLintptr src_offset, GLenum dst_target, GLuint dst_object, GLintptr dst_offset, GLsizeiptr size)
{
if (!g_opengl_context || !reshade::has_addon_event<reshade::addon_event::copy_buffer_region>())
return false;
if (src_object == 0)
gl.GetIntegerv(reshade::opengl::get_binding_for_target(src_target), reinterpret_cast<GLint *>(&src_object));
assert(src_object != 0);
if (dst_object == 0)
gl.GetIntegerv(reshade::opengl::get_binding_for_target(dst_target), reinterpret_cast<GLint *>(&dst_object));
assert(dst_object != 0);
reshade::api::resource src = reshade::opengl::make_resource_handle(GL_BUFFER, src_object);
reshade::api::resource dst = reshade::opengl::make_resource_handle(GL_BUFFER, dst_object);
return reshade::invoke_addon_event<reshade::addon_event::copy_buffer_region>(g_opengl_context, src, src_offset, dst, dst_offset, size);
}
static bool copy_texture_region(GLenum src_target, GLuint src_object, GLint src_level, GLint x, GLint y, GLint z, GLenum dst_target, GLuint dst_object, GLint dst_level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum filter = GL_NONE)
{
if (!g_opengl_context || !reshade::has_addon_event<reshade::addon_event::copy_texture_region>())
return false;
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
if (src_object == 0)
{
if (src_target == GL_FRAMEBUFFER_DEFAULT)
gl.GetIntegerv(GL_READ_BUFFER, reinterpret_cast<GLint *>(&src_object));
else
gl.GetIntegerv(reshade::opengl::get_binding_for_target(src_target), reinterpret_cast<GLint *>(&src_object));
assert(src_object != 0);
}
else
{
if (src_target == GL_TEXTURE && gl.GetTextureParameteriv != nullptr)
gl.GetTextureParameteriv(src_object, GL_TEXTURE_TARGET, reinterpret_cast<GLint *>(&src_target));
}
if (dst_object == 0)
{
if (src_target == GL_FRAMEBUFFER_DEFAULT)
gl.GetIntegerv(GL_DRAW_BUFFER, reinterpret_cast<GLint *>(&dst_object));
else
gl.GetIntegerv(reshade::opengl::get_binding_for_target(dst_target), reinterpret_cast<GLint *>(&dst_object));
assert(dst_object != 0);
}
else
{
if (dst_target == GL_TEXTURE && gl.GetTextureParameteriv != nullptr)
gl.GetTextureParameteriv(dst_object, GL_TEXTURE_TARGET, reinterpret_cast<GLint *>(&dst_target));
}
reshade::api::resource src = reshade::opengl::make_resource_handle(src_target, src_object);
// Check if this is actually referencing the default framebuffer, or really an attachment of a framebuffer object
if (src_target == GL_FRAMEBUFFER_DEFAULT && (src_object >= GL_COLOR_ATTACHMENT0 && src_object <= GL_COLOR_ATTACHMENT31))
{
GLint src_fbo = 0;
gl.GetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &src_fbo);
src = device->get_resource_from_view(device->get_framebuffer_attachment(src_fbo, GL_COLOR, src_object - GL_COLOR_ATTACHMENT0));
}
reshade::api::resource dst = reshade::opengl::make_resource_handle(dst_target, dst_object);
if (dst_target == GL_FRAMEBUFFER_DEFAULT && (dst_object >= GL_COLOR_ATTACHMENT0 && dst_object <= GL_COLOR_ATTACHMENT31))
{
GLint dst_fbo = 0;
gl.GetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &dst_fbo);
dst = device->get_resource_from_view(device->get_framebuffer_attachment(dst_fbo, GL_COLOR, dst_object - GL_COLOR_ATTACHMENT0));
}
const reshade::api::subresource_box src_box = { x, y, z, x + width, y + height, z + depth };
const reshade::api::subresource_box dst_box = { xoffset, yoffset, zoffset, xoffset + width, yoffset + height, zoffset + depth };
return reshade::invoke_addon_event<reshade::addon_event::copy_texture_region>(g_opengl_context, src, src_level, &src_box, dst, dst_level, &dst_box,
(filter == GL_NONE || filter == GL_NEAREST) ? reshade::api::filter_mode::min_mag_mip_point : reshade::api::filter_mode::min_mag_mip_linear);
}
static bool update_buffer_region(GLenum target, GLuint object, GLintptr offset, GLsizeiptr size, const void *data)
{
assert(data != nullptr);
if (!g_opengl_context || !reshade::has_addon_event<reshade::addon_event::update_buffer_region>())
return false;
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
// Get object from current binding in case it was not specified
if (object == 0)
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), reinterpret_cast<GLint *>(&object));
assert(object != 0);
reshade::api::resource dst = reshade::opengl::make_resource_handle(GL_BUFFER, object);
return reshade::invoke_addon_event<reshade::addon_event::update_buffer_region>(device, data, dst, static_cast<uint64_t>(offset), static_cast<uint64_t>(size));
}
static bool update_texture_region(GLenum target, GLuint object, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels)
{
if (!g_opengl_context || (!reshade::has_addon_event<reshade::addon_event::update_texture_region>() && !reshade::has_addon_event<reshade::addon_event::copy_buffer_to_texture>()))
return false;
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
// Get actual texture target from the texture object
if (target == GL_TEXTURE && gl.GetTextureParameteriv != nullptr)
gl.GetTextureParameteriv(object, GL_TEXTURE_TARGET, reinterpret_cast<GLint *>(&target));
// Get object from current binding in case it was not specified
if (object == 0)
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), reinterpret_cast<GLint *>(&object));
assert(object != 0);
reshade::api::resource dst = reshade::opengl::make_resource_handle(target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z ? GL_TEXTURE_CUBE_MAP : target, object);
const reshade::api::resource_desc desc = device->get_resource_desc(dst);
GLuint subresource = level;
if (target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z)
subresource += (target - GL_TEXTURE_CUBE_MAP_POSITIVE_X) * desc.texture.levels;
const reshade::api::subresource_box dst_box = { xoffset, yoffset, zoffset, xoffset + width, yoffset + height, zoffset + depth };
GLint unpack = 0;
gl.GetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &unpack);
if (0 == unpack)
{
assert(pixels != nullptr);
init_resource resource(desc);
reshade::api::subresource_data *const data = resource.convert_mapped_subresource(format, type, pixels, width, height, depth);
if (!data)
return false;
return reshade::invoke_addon_event<reshade::addon_event::update_texture_region>(device, *data, dst, subresource, &dst_box);
}
else
{
reshade::api::resource src = reshade::opengl::make_resource_handle(GL_BUFFER, unpack);
GLint row_length = 0;
gl.GetIntegerv(GL_UNPACK_ROW_LENGTH, &row_length);
GLint slice_height = 0;
gl.GetIntegerv(GL_UNPACK_IMAGE_HEIGHT, &slice_height);
return reshade::invoke_addon_event<reshade::addon_event::copy_buffer_to_texture>(g_opengl_context, src, reinterpret_cast<uintptr_t>(pixels), row_length, slice_height, dst, subresource, &dst_box);
}
}
static void update_current_input_layout()
{
if (g_opengl_context->_current_vao_dirty &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline>())
{
// Changing the vertex array binding also changes the vertex and index buffer bindings, so force an update of those next
g_opengl_context->_current_vbo_dirty = true;
g_opengl_context->_current_ibo_dirty = true;
g_opengl_context->_current_vao_dirty = false;
GLint count = 0;
gl.GetIntegerv(GL_MAX_VERTEX_ATTRIBS, &count);
std::vector<reshade::api::input_element> elements;
elements.reserve(count);
for (GLsizei i = 0; i < count; ++i)
{
GLint enabled = GL_FALSE;
gl.GetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &enabled);
if (GL_FALSE == enabled)
continue;
reshade::api::input_element &element = elements.emplace_back();
element.location = i;
GLint attrib_size = 0;
gl.GetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_SIZE, &attrib_size);
GLint attrib_type = 0;
gl.GetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_TYPE, &attrib_type);
GLint attrib_normalized = 0;
gl.GetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &attrib_normalized);
element.format = reshade::opengl::convert_attrib_format(attrib_size, static_cast<GLenum>(attrib_type), static_cast<GLboolean>(attrib_normalized));
gl.GetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, reinterpret_cast<GLint *>(&element.stride));
gl.GetVertexAttribiv(i, GL_VERTEX_ATTRIB_RELATIVE_OFFSET, reinterpret_cast<GLint *>(&element.offset));
gl.GetVertexAttribiv(i, GL_VERTEX_ATTRIB_BINDING, reinterpret_cast<GLint *>(&element.buffer_binding));
gl.GetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_DIVISOR, reinterpret_cast<GLint *>(&element.instance_step_rate));
}
GLint vertex_array_binding = 0;
gl.GetIntegerv(GL_VERTEX_ARRAY_BINDING, &vertex_array_binding);
reshade::api::pipeline_subobject subobject;
subobject.type = reshade::api::pipeline_subobject_type::input_layout;
subobject.count = static_cast<uint32_t>(elements.size());
subobject.data = elements.data();
reshade::invoke_addon_event<reshade::addon_event::init_pipeline>(
g_opengl_context->get_device(),
get_opengl_pipeline_layout(),
1,
&subobject,
reshade::api::pipeline { (static_cast<uint64_t>(GL_VERTEX_ARRAY) << 40) | vertex_array_binding });
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline>(
g_opengl_context,
reshade::api::pipeline_stage::input_assembler,
reshade::api::pipeline { (static_cast<uint64_t>(GL_VERTEX_ARRAY) << 40) | vertex_array_binding });
}
}
#endif
#if RESHADE_ADDON
static void update_current_primitive_topology(GLenum mode)
{
#if RESHADE_ADDON >= 2
update_current_input_layout();
if (g_opengl_context->_current_vbo_dirty &&
reshade::has_addon_event<reshade::addon_event::bind_vertex_buffers>())
{
g_opengl_context->_current_vbo_dirty = false;
GLint count = 0;
gl.GetIntegerv(GL_MAX_VERTEX_ATTRIB_BINDINGS, &count);
temp_mem<reshade::api::resource> buffer_handles(count);
temp_mem<uint64_t> offsets_64(count);
temp_mem<uint32_t> strides_32(count);
for (GLsizei i = 0; i < count; ++i)
{
offsets_64[i] = 0;
strides_32[i] = 0;
GLint vertex_buffer_binding = 0;
gl.GetIntegeri_v(GL_VERTEX_BINDING_BUFFER, i, &vertex_buffer_binding);
if (0 != vertex_buffer_binding)
{
buffer_handles[i] = reshade::opengl::make_resource_handle(GL_BUFFER, vertex_buffer_binding);
gl.GetIntegeri_v(GL_VERTEX_BINDING_STRIDE, i, reinterpret_cast<GLint *>(&strides_32[i]));
assert(strides_32[i] != 0);
gl.GetInteger64i_v(GL_VERTEX_BINDING_OFFSET, i, reinterpret_cast<GLint64 *>(&offsets_64[i]));
}
else
{
buffer_handles[i] = { 0 };
}
}
reshade::invoke_addon_event<reshade::addon_event::bind_vertex_buffers>(
g_opengl_context,
0,
count,
buffer_handles.p,
offsets_64.p,
strides_32.p);
}
#endif
if (mode != g_opengl_context->_current_prim_mode)
{
g_opengl_context->_current_prim_mode = mode;
#if RESHADE_ADDON >= 2
const reshade::api::dynamic_state state = reshade::api::dynamic_state::primitive_topology;
uint32_t value = static_cast<uint32_t>(reshade::opengl::convert_primitive_topology(mode));
if (mode == GL_PATCHES)
{
GLint cps = 1;
gl.GetIntegerv(GL_PATCH_VERTICES, &cps);
assert(value == static_cast<uint32_t>(reshade::api::primitive_topology::patch_list_01_cp));
value += cps - 1;
}
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, 1, &state, &value);
#endif
}
}
static void update_current_primitive_topology(GLenum mode, GLenum index_type)
{
update_current_primitive_topology(mode);
g_opengl_context->_current_index_type = index_type;
#if RESHADE_ADDON >= 2
if (g_opengl_context->_current_ibo_dirty &&
reshade::has_addon_event<reshade::addon_event::bind_index_buffer>())
{
g_opengl_context->_current_ibo_dirty = false;
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
reshade::invoke_addon_event<reshade::addon_event::bind_index_buffer>(
g_opengl_context,
reshade::opengl::make_resource_handle(GL_BUFFER, index_buffer_binding),
0,
reshade::opengl::get_index_type_size(index_type));
}
#endif
}
#endif
#ifdef GL_VERSION_1_0
extern "C" void APIENTRY glTexImage1D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
{
static const auto trampoline = reshade::hooks::call(glTexImage1D);
#if RESHADE_ADDON
internalformat = reshade::opengl::convert_sized_internal_format(internalformat);
// Ignore proxy texture objects
const bool proxy_object = (target == GL_PROXY_TEXTURE_1D);
if (g_opengl_context && level == 0 && !proxy_object)
{
init_resource resource(target, 0, 0, 1, static_cast<GLenum>(internalformat), width, 1, 1);
resource.invoke_create_event(nullptr, nullptr, reinterpret_cast<GLenum *>(&internalformat), &width, nullptr, nullptr, format, type, pixels);
trampoline(target, level, internalformat, width, border, format, type, pixels);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, level, internalformat, width, border, format, type, pixels);
}
extern "C" void APIENTRY glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
{
static const auto trampoline = reshade::hooks::call(glTexImage2D);
#if RESHADE_ADDON
internalformat = reshade::opengl::convert_sized_internal_format(internalformat);
// Ignore proxy texture objects
const bool proxy_object = (target == GL_PROXY_TEXTURE_2D || target == GL_PROXY_TEXTURE_1D_ARRAY || target == GL_PROXY_TEXTURE_RECTANGLE || target == GL_PROXY_TEXTURE_CUBE_MAP);
if (g_opengl_context && level == 0 && !proxy_object)
{
if (target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z)
{
if (init_resource::is_texture_uninitialized(GL_TEXTURE_CUBE_MAP_POSITIVE_X))
{
// Initialize resource, so that 'glGetTex(ture)LevelParameter' returns valid information
for (GLint face = 0; face < 6; ++face)
trampoline(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, internalformat, width, height, border, format, type, nullptr);
// Assume only 1 mipmap level, so that the subresource index calculation in 'update_texture_region' below matches
init_resource resource(GL_TEXTURE_CUBE_MAP, 0, 1, 1, static_cast<GLenum>(internalformat), width, height, 1);
resource.invoke_initialize_event();
}
#endif
#if RESHADE_ADDON >= 2
if (!update_texture_region(target, 0, level, 0, 0, 0, width, height, 1, format, type, pixels))
#endif
#if RESHADE_ADDON
trampoline(target, level, internalformat, width, height, border, format, type, pixels);
return;
}
init_resource resource(target, 0, 0, 1, static_cast<GLenum>(internalformat), width, height, 1);
resource.invoke_create_event(nullptr, nullptr, reinterpret_cast<GLenum *>(&internalformat), &width, &height, nullptr, format, type, pixels);
trampoline(target, level, internalformat, width, height, border, format, type, pixels);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, level, internalformat, width, height, border, format, type, pixels);
}
extern "C" void APIENTRY glCopyPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type)
{
#if RESHADE_ADDON >= 2
if (copy_texture_region(GL_FRAMEBUFFER_DEFAULT, 0, 0, x, y, 0, GL_FRAMEBUFFER_DEFAULT, 0, 0, 0, 0, 0, width, height, 1))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCopyPixels);
trampoline(x, y, width, height, type);
}
extern "C" void APIENTRY glClear(GLbitfield mask)
{
#if RESHADE_ADDON
if (g_opengl_context && (
reshade::has_addon_event<reshade::addon_event::clear_depth_stencil_view>() ||
reshade::has_addon_event<reshade::addon_event::clear_render_target_view>()))
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
GLint dst_fbo = 0;
gl.GetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &dst_fbo);
if (const GLbitfield current_mask = mask & (GL_COLOR_BUFFER_BIT))
{
GLfloat color_value[4] = {};
gl.GetFloatv(GL_COLOR_CLEAR_VALUE, color_value);
const reshade::api::resource_view view = device->get_framebuffer_attachment(dst_fbo, current_mask, 0);
if (reshade::invoke_addon_event<reshade::addon_event::clear_render_target_view>(g_opengl_context, view, color_value, 0, nullptr))
mask ^= current_mask;
}
if (const GLbitfield current_mask = mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
{
GLfloat depth_value = 0.0f;
gl.GetFloatv(GL_DEPTH_CLEAR_VALUE, &depth_value);
GLint stencil_value = 0;
gl.GetIntegerv(GL_STENCIL_CLEAR_VALUE, &stencil_value);
const reshade::api::resource_view view = device->get_framebuffer_attachment(dst_fbo, current_mask, 0);
if (reshade::invoke_addon_event<reshade::addon_event::clear_depth_stencil_view>(g_opengl_context, view, mask & GL_DEPTH_BUFFER_BIT ? &depth_value : nullptr, mask & GL_STENCIL_BUFFER_BIT ? reinterpret_cast<const uint8_t *>(&stencil_value) : nullptr, 0, nullptr))
mask ^= current_mask;
}
if (mask == 0)
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glClear);
trampoline(mask);
}
extern "C" void APIENTRY glEnable(GLenum cap)
{
static const auto trampoline = reshade::hooks::call(glEnable);
trampoline(cap);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
uint32_t value = GL_TRUE;
reshade::api::dynamic_state state = { reshade::api::dynamic_state::unknown };
switch (cap)
{
case 0x0BC0 /* GL_ALPHA_TEST */:
state = reshade::api::dynamic_state::alpha_test_enable;
break;
case GL_BLEND:
state = reshade::api::dynamic_state::blend_enable;
break;
case GL_CULL_FACE:
state = reshade::api::dynamic_state::cull_mode;
break;
case GL_DEPTH_CLAMP:
value = GL_FALSE;
state = reshade::api::dynamic_state::depth_clip_enable;
break;
case GL_DEPTH_TEST:
state = reshade::api::dynamic_state::depth_enable;
break;
case GL_FRAMEBUFFER_SRGB:
state = reshade::api::dynamic_state::srgb_write_enable;
break;
case GL_LINE_SMOOTH:
state = reshade::api::dynamic_state::antialiased_line_enable;
break;
case GL_MULTISAMPLE:
state = reshade::api::dynamic_state::multisample_enable;
break;
case GL_SAMPLE_ALPHA_TO_COVERAGE:
state = reshade::api::dynamic_state::alpha_to_coverage_enable;
break;
case GL_SCISSOR_TEST:
state = reshade::api::dynamic_state::scissor_enable;
break;
case GL_STENCIL_TEST:
state = reshade::api::dynamic_state::stencil_enable;
break;
case GL_COLOR_LOGIC_OP:
state = reshade::api::dynamic_state::logic_op_enable;
break;
}
if (reshade::api::dynamic_state::unknown != state)
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, 1, &state, &value);
}
#endif
}
extern "C" void APIENTRY glDisable(GLenum cap)
{
static const auto trampoline = reshade::hooks::call(glDisable);
trampoline(cap);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
uint32_t value = GL_FALSE;
reshade::api::dynamic_state state = reshade::api::dynamic_state::unknown;
switch (cap)
{
case 0x0BC0 /* GL_ALPHA_TEST */:
state = reshade::api::dynamic_state::alpha_test_enable;
break;
case GL_BLEND:
state = reshade::api::dynamic_state::blend_enable;
break;
case GL_CULL_FACE:
state = reshade::api::dynamic_state::cull_mode;
break;
case GL_DEPTH_CLAMP:
value = GL_TRUE;
state = reshade::api::dynamic_state::depth_clip_enable;
break;
case GL_DEPTH_TEST:
state = reshade::api::dynamic_state::depth_enable;
break;
case GL_FRAMEBUFFER_SRGB:
state = reshade::api::dynamic_state::srgb_write_enable;
break;
case GL_LINE_SMOOTH:
state = reshade::api::dynamic_state::antialiased_line_enable;
break;
case GL_MULTISAMPLE:
state = reshade::api::dynamic_state::multisample_enable;
break;
case GL_SAMPLE_ALPHA_TO_COVERAGE:
state = reshade::api::dynamic_state::alpha_to_coverage_enable;
break;
case GL_SCISSOR_TEST:
state = reshade::api::dynamic_state::scissor_enable;
break;
case GL_STENCIL_TEST:
state = reshade::api::dynamic_state::stencil_enable;
break;
case GL_COLOR_LOGIC_OP:
state = reshade::api::dynamic_state::logic_op_enable;
break;
}
if (reshade::api::dynamic_state::unknown != state)
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, 1, &state, &value);
}
#endif
}
extern "C" void APIENTRY glCullFace(GLenum mode)
{
static const auto trampoline = reshade::hooks::call(glCullFace);
trampoline(mode);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[1] = { reshade::api::dynamic_state::cull_mode };
const uint32_t values[1] = { static_cast<uint32_t>(reshade::opengl::convert_cull_mode(mode)) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glFrontFace(GLenum mode)
{
static const auto trampoline = reshade::hooks::call(glFrontFace);
trampoline(mode);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[1] = { reshade::api::dynamic_state::front_counter_clockwise };
const uint32_t values[1] = { mode == GL_CCW };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glHint(GLenum target, GLenum mode)
{
static const auto trampoline = reshade::hooks::call(glHint);
trampoline(target, mode);
}
extern "C" void APIENTRY glLineWidth(GLfloat width)
{
static const auto trampoline = reshade::hooks::call(glLineWidth);
trampoline(width);
}
extern "C" void APIENTRY glPointSize(GLfloat size)
{
static const auto trampoline = reshade::hooks::call(glPointSize);
trampoline(size);
}
extern "C" void APIENTRY glPolygonMode(GLenum face, GLenum mode)
{
static const auto trampoline = reshade::hooks::call(glPolygonMode);
trampoline(face, mode);
#if RESHADE_ADDON >= 2
if (g_opengl_context && face == GL_FRONT_AND_BACK &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[1] = { reshade::api::dynamic_state::fill_mode };
const uint32_t values[1] = { static_cast<uint32_t>(reshade::opengl::convert_fill_mode(mode)) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glAlphaFunc(GLenum func, GLclampf ref)
{
static const auto trampoline = reshade::hooks::call(glAlphaFunc);
trampoline(func, ref);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[2] = { reshade::api::dynamic_state::alpha_func, reshade::api::dynamic_state::alpha_reference_value };
const uint32_t values[2] = { static_cast<uint32_t>(reshade::opengl::convert_compare_op(func)), *reinterpret_cast<const uint32_t *>(&ref) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glBlendFunc(GLenum sfactor, GLenum dfactor)
{
static const auto trampoline = reshade::hooks::call(glBlendFunc);
trampoline(sfactor, dfactor);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[4] = { reshade::api::dynamic_state::source_color_blend_factor, reshade::api::dynamic_state::dest_color_blend_factor, reshade::api::dynamic_state::source_alpha_blend_factor, reshade::api::dynamic_state::dest_alpha_blend_factor };
const uint32_t values[4] = { static_cast<uint32_t>(reshade::opengl::convert_blend_factor(sfactor)), static_cast<uint32_t>(reshade::opengl::convert_blend_factor(dfactor)), static_cast<uint32_t>(reshade::opengl::convert_blend_factor(sfactor)), static_cast<uint32_t>(reshade::opengl::convert_blend_factor(dfactor)) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glLogicOp(GLenum opcode)
{
static const auto trampoline = reshade::hooks::call(glLogicOp);
trampoline(opcode);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[1] = { reshade::api::dynamic_state::logic_op };
const uint32_t values[1] = { static_cast<uint32_t>(reshade::opengl::convert_logic_op(opcode)) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
{
static const auto trampoline = reshade::hooks::call(glColorMask);
trampoline(red, green, blue, alpha);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[1] = { reshade::api::dynamic_state::render_target_write_mask };
const uint32_t values[1] = { static_cast<uint32_t>((red) | (green << 1) | (blue << 2) | (alpha << 3)) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glDepthFunc(GLenum func)
{
static const auto trampoline = reshade::hooks::call(glDepthFunc);
trampoline(func);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[1] = { reshade::api::dynamic_state::depth_func };
const uint32_t values[1] = { static_cast<uint32_t>(reshade::opengl::convert_compare_op(func)) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glDepthMask(GLboolean flag)
{
static const auto trampoline = reshade::hooks::call(glDepthMask);
trampoline(flag);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[1] = { reshade::api::dynamic_state::depth_write_mask };
const uint32_t values[1] = { flag };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glStencilFunc(GLenum func, GLint ref, GLuint mask)
{
static const auto trampoline = reshade::hooks::call(glStencilFunc);
trampoline(func, ref, mask);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const auto stencil_func = reshade::opengl::convert_compare_op(func);
const reshade::api::dynamic_state states[6] = { reshade::api::dynamic_state::front_stencil_func, reshade::api::dynamic_state::front_stencil_reference_value, reshade::api::dynamic_state::front_stencil_read_mask, reshade::api::dynamic_state::back_stencil_func, reshade::api::dynamic_state::back_stencil_reference_value, reshade::api::dynamic_state::back_stencil_read_mask };
const uint32_t values[6] = { static_cast<uint32_t>(stencil_func), static_cast<uint32_t>(ref), mask, static_cast<uint32_t>(stencil_func), static_cast<uint32_t>(ref), mask };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glStencilOp(GLenum fail, GLenum zfail, GLenum zpass)
{
static const auto trampoline = reshade::hooks::call(glStencilOp);
trampoline(fail, zfail, zpass);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const auto stencil_fail_op = reshade::opengl::convert_stencil_op(fail);
const auto stencil_depth_fail_op = reshade::opengl::convert_stencil_op(zfail);
const auto stencil_pass_op = reshade::opengl::convert_stencil_op(zpass);
const reshade::api::dynamic_state states[6] = { reshade::api::dynamic_state::front_stencil_fail_op, reshade::api::dynamic_state::front_stencil_depth_fail_op, reshade::api::dynamic_state::front_stencil_pass_op, reshade::api::dynamic_state::back_stencil_fail_op, reshade::api::dynamic_state::back_stencil_depth_fail_op, reshade::api::dynamic_state::back_stencil_pass_op };
const uint32_t values[6] = { static_cast<uint32_t>(stencil_fail_op), static_cast<uint32_t>(stencil_depth_fail_op), static_cast<uint32_t>(stencil_pass_op), static_cast<uint32_t>(stencil_fail_op), static_cast<uint32_t>(stencil_depth_fail_op), static_cast<uint32_t>(stencil_pass_op) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glStencilMask(GLuint mask)
{
static const auto trampoline = reshade::hooks::call(glStencilMask);
trampoline(mask);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[2] = { reshade::api::dynamic_state::front_stencil_write_mask, reshade::api::dynamic_state::back_stencil_write_mask };
const uint32_t values[2] = { mask, mask };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glScissor(GLint left, GLint bottom, GLsizei width, GLsizei height)
{
static const auto trampoline = reshade::hooks::call(glScissor);
trampoline(left, bottom, width, height);
#if RESHADE_ADDON
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_scissor_rects>())
{
GLint clip_origin = GL_LOWER_LEFT;
if (gl.ClipControl != nullptr)
gl.GetIntegerv(GL_CLIP_ORIGIN, &clip_origin);
reshade::api::rect rect_data;
rect_data.left = left;
rect_data.right = left + width;
if (clip_origin == GL_UPPER_LEFT)
{
rect_data.top = bottom;
rect_data.bottom = bottom + height;
}
else
{
assert(g_opengl_context->_current_window_height != 0);
rect_data.top = g_opengl_context->_current_window_height - (bottom + height);
rect_data.bottom = g_opengl_context->_current_window_height - bottom;
}
reshade::invoke_addon_event<reshade::addon_event::bind_scissor_rects>(g_opengl_context, 0, 1, &rect_data);
}
#endif
}
extern "C" void APIENTRY glViewport(GLint x, GLint y, GLsizei width, GLsizei height)
{
static const auto trampoline = reshade::hooks::call(glViewport);
trampoline(x, y, width, height);
#if RESHADE_ADDON
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_viewports>())
{
const reshade::api::viewport viewport_data = {
static_cast<float>(x),
static_cast<float>(y),
static_cast<float>(width),
static_cast<float>(height)
};
reshade::invoke_addon_event<reshade::addon_event::bind_viewports>(g_opengl_context, 0, 1, &viewport_data);
}
#endif
}
extern "C" void APIENTRY glDepthRange(GLclampd zNear, GLclampd zFar)
{
static const auto trampoline = reshade::hooks::call(glDepthRange);
trampoline(zNear, zFar);
}
#endif
#ifdef GL_VERSION_1_1
extern "C" void APIENTRY glDeleteTextures(GLsizei n, const GLuint *textures)
{
#if RESHADE_ADDON
for (GLsizei i = 0; i < n; ++i)
if (gl.IsTexture(textures[i]))
destroy_resource_or_view(GL_TEXTURE, textures[i]);
#endif
static const auto trampoline = reshade::hooks::call(glDeleteTextures);
trampoline(n, textures);
}
extern "C" void APIENTRY glTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(target, 0, level, xoffset, 0, 0, width, 1, 1, format, type, pixels))
return;
#endif
static const auto trampoline = reshade::hooks::call(glTexSubImage1D);
trampoline(target, level, xoffset, width, format, type, pixels);
}
extern "C" void APIENTRY glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(target, 0, level, xoffset, yoffset, 0, width, height, 1, format, type, pixels))
return;
#endif
static const auto trampoline = reshade::hooks::call(glTexSubImage2D);
trampoline(target, level, xoffset, yoffset, width, height, format, type, pixels);
}
extern "C" void APIENTRY glCopyTexImage1D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border)
{
static const auto trampoline = reshade::hooks::call(glCopyTexImage1D);
trampoline(target, level, internalformat, x, y, width, border);
}
extern "C" void APIENTRY glCopyTexImage2D(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
{
static const auto trampoline = reshade::hooks::call(glCopyTexImage2D);
trampoline(target, level, internalFormat, x, y, width, height, border);
}
extern "C" void APIENTRY glCopyTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width)
{
#if RESHADE_ADDON >= 2
if (copy_texture_region(GL_FRAMEBUFFER_DEFAULT, 0, 0, x, y, 0, target, 0, level, xoffset, 0, 0, width, 1, 1))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCopyTexSubImage1D);
trampoline(target, level, xoffset, x, y, width);
}
extern "C" void APIENTRY glCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
{
#if RESHADE_ADDON >= 2
if (copy_texture_region(GL_FRAMEBUFFER_DEFAULT, 0, 0, x, y, 0, target, 0, level, xoffset, yoffset, 0, width, height, 1))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCopyTexSubImage2D);
trampoline(target, level, xoffset, yoffset, x, y, width, height);
}
extern "C" void APIENTRY glBindTexture(GLenum target, GLuint texture)
{
static const auto trampoline = reshade::hooks::call(glBindTexture);
trampoline(target, texture);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::push_descriptors>())
{
// Only interested in existing textures that are being bound to the render pipeline
if (init_resource::is_texture_uninitialized(target))
return;
GLint texunit = GL_TEXTURE0;
gl.GetIntegerv(GL_ACTIVE_TEXTURE, &texunit);
texunit -= GL_TEXTURE0;
// Could technically get current sampler via "GL_SAMPLER_BINDING", but that only works if sampler objects are used and bound before the texture, which is not necessarily the case
reshade::api::sampler_with_resource_view descriptor_data = {
reshade::api::sampler { 0 },
reshade::opengl::make_resource_view_handle(target, texture)
};
reshade::invoke_addon_event<reshade::addon_event::push_descriptors>(
g_opengl_context,
reshade::api::shader_stage::all,
// See global pipeline layout specified in 'wgl_device::wgl_device'
get_opengl_pipeline_layout(), 0,
reshade::api::descriptor_table_update { {}, static_cast<GLuint>(texunit), 0, 1, reshade::api::descriptor_type::sampler_with_resource_view, &descriptor_data });
}
#endif
}
extern "C" void APIENTRY glPolygonOffset(GLfloat factor, GLfloat units)
{
static const auto trampoline = reshade::hooks::call(glPolygonOffset);
trampoline(factor, units);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[2] = { reshade::api::dynamic_state::depth_bias_slope_scaled, reshade::api::dynamic_state::depth_bias };
const uint32_t values[2] = { *reinterpret_cast<const uint32_t *>(&factor), *reinterpret_cast<const uint32_t *>(&units) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
extern "C" void APIENTRY glDrawArrays(GLenum mode, GLint first, GLsizei count)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode);
if (reshade::invoke_addon_event<reshade::addon_event::draw>(g_opengl_context, count, 1, first, 0))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawArrays);
trampoline(mode, first, count);
}
extern "C" void APIENTRY glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode, type);
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
const uint32_t offset = (index_buffer_binding != 0) ? static_cast<uint32_t>(reinterpret_cast<uintptr_t>(indices) / reshade::opengl::get_index_type_size(type)) : 0;
if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(g_opengl_context, count, 1, offset, 0, 0))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawElements);
trampoline(mode, count, type, indices);
}
#endif
#ifdef GL_VERSION_1_2
void APIENTRY glTexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
{
static const auto trampoline = reshade::hooks::call(glTexImage3D);
#if RESHADE_ADDON
internalformat = reshade::opengl::convert_sized_internal_format(internalformat);
// Ignore proxy texture objects
const bool proxy_object = (target == GL_PROXY_TEXTURE_3D || target == GL_PROXY_TEXTURE_2D_ARRAY || target == GL_PROXY_TEXTURE_CUBE_MAP_ARRAY);
if (g_opengl_context && level == 0 && !proxy_object)
{
init_resource resource(target, 0, 0, 1, static_cast<GLenum>(internalformat), width, height, depth);
resource.invoke_create_event(nullptr, nullptr, reinterpret_cast<GLenum *>(&internalformat), &width, &height, &depth, format, type, pixels);
trampoline(target, level, internalformat, width, height, depth, border, format, type, pixels);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, level, internalformat, width, height, depth, border, format, type, pixels);
}
void APIENTRY glTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(target, 0, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels))
return;
#endif
static const auto trampoline = reshade::hooks::call(glTexSubImage3D);
trampoline(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
}
void APIENTRY glCopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
{
#if RESHADE_ADDON >= 2
if (copy_texture_region(GL_FRAMEBUFFER_DEFAULT, 0, 0, x, y, 0, target, 0, level, xoffset, yoffset, zoffset, width, height, 1))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCopyTexSubImage3D);
trampoline(target, level, xoffset, yoffset, zoffset, x, y, width, height);
}
void APIENTRY glDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode, type);
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
const uint32_t offset = (index_buffer_binding != 0) ? static_cast<uint32_t>(reinterpret_cast<uintptr_t>(indices) / reshade::opengl::get_index_type_size(type)) : 0;
if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(g_opengl_context, count, 1, offset, 0, 0))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawRangeElements);
trampoline(mode, start, end, count, type, indices);
}
#endif
#ifdef GL_VERSION_1_3
void APIENTRY glCompressedTexImage1D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data)
{
static const auto trampoline = reshade::hooks::call(glCompressedTexImage1D);
#if RESHADE_ADDON
// Ignore proxy texture objects
const bool proxy_object = (target == GL_PROXY_TEXTURE_1D);
if (g_opengl_context && level == 0 && !proxy_object)
{
init_resource resource(target, 0, 0, 1, internalformat, width, 1, 1);
resource.invoke_create_event(nullptr, nullptr, &internalformat, &width, nullptr, nullptr, internalformat, GL_UNSIGNED_BYTE, data);
trampoline(target, level, internalformat, width, border, imageSize, data);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, level, internalformat, width, border, imageSize, data);
}
void APIENTRY glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data)
{
static const auto trampoline = reshade::hooks::call(glCompressedTexImage2D);
#if RESHADE_ADDON
// Ignore proxy texture objects
const bool proxy_object = (target == GL_PROXY_TEXTURE_2D || target == GL_PROXY_TEXTURE_1D_ARRAY || target == GL_PROXY_TEXTURE_CUBE_MAP);
if (g_opengl_context && level == 0 && !proxy_object)
{
if (target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z)
{
if (init_resource::is_texture_uninitialized(GL_TEXTURE_CUBE_MAP_POSITIVE_X))
{
// Initialize resource, so that 'glGetTex(ture)LevelParameter' returns valid information
for (GLint face = 0; face < 6; ++face)
trampoline(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, internalformat, width, height, border, imageSize, nullptr);
// Assume only 1 mipmap level, so that the subresource index calculation in 'update_texture_region' below matches
init_resource resource(GL_TEXTURE_CUBE_MAP, 0, 1, 1, internalformat, width, height, 1);
resource.invoke_initialize_event();
}
#endif
#if RESHADE_ADDON >= 2
if (!update_texture_region(target, 0, level, 0, 0, 0, width, height, 1, internalformat, GL_UNSIGNED_BYTE, data))
#endif
#if RESHADE_ADDON
trampoline(target, level, internalformat, width, height, border, imageSize, data);
return;
}
init_resource resource(target, 0, 0, 1, internalformat, width, height, 1);
resource.invoke_create_event(nullptr, nullptr, &internalformat, &width, &height, nullptr, internalformat, GL_UNSIGNED_BYTE, data);
trampoline(target, level, internalformat, width, height, border, imageSize, data);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, level, internalformat, width, height, border, imageSize, data);
}
void APIENTRY glCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data)
{
static const auto trampoline = reshade::hooks::call(glCompressedTexImage3D);
#if RESHADE_ADDON
// Ignore proxy texture objects
const bool proxy_object = (target == GL_PROXY_TEXTURE_3D || target == GL_PROXY_TEXTURE_2D_ARRAY || target == GL_PROXY_TEXTURE_CUBE_MAP_ARRAY);
if (g_opengl_context && level == 0 && !proxy_object)
{
init_resource resource(target, 0, 0, 1, internalformat, width, height, depth);
resource.invoke_create_event(nullptr, nullptr, &internalformat, &width, &height, &depth, internalformat, GL_UNSIGNED_BYTE, data);
trampoline(target, level, internalformat, width, height, depth, border, imageSize, data);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, level, internalformat, width, height, depth, border, imageSize, data);
}
void APIENTRY glCompressedTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(target, 0, level, xoffset, 0, 0, width, 1, 1, format, GL_UNSIGNED_BYTE, data))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCompressedTexSubImage1D);
trampoline(target, level, xoffset, width, format, imageSize, data);
}
void APIENTRY glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(target, 0, level, xoffset, yoffset, 0, width, height, 1, format, GL_UNSIGNED_BYTE, data))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCompressedTexSubImage2D);
trampoline(target, level, xoffset, yoffset, width, height, format, imageSize, data);
}
void APIENTRY glCompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(target, 0, level, xoffset, yoffset, zoffset, width, height, depth, format, GL_UNSIGNED_BYTE, data))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCompressedTexSubImage3D);
trampoline(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
}
#endif
#ifdef GL_VERSION_1_4
void APIENTRY glBlendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha)
{
static const auto trampoline = reshade::hooks::call(glBlendFuncSeparate);
trampoline(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[4] = { reshade::api::dynamic_state::source_color_blend_factor, reshade::api::dynamic_state::dest_color_blend_factor, reshade::api::dynamic_state::source_alpha_blend_factor, reshade::api::dynamic_state::dest_alpha_blend_factor };
const uint32_t values[4] = { static_cast<uint32_t>(reshade::opengl::convert_blend_factor(sfactorRGB)), static_cast<uint32_t>(reshade::opengl::convert_blend_factor(dfactorRGB)), static_cast<uint32_t>(reshade::opengl::convert_blend_factor(sfactorAlpha)), static_cast<uint32_t>(reshade::opengl::convert_blend_factor(dfactorAlpha)) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
void APIENTRY glBlendColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
{
static const auto trampoline = reshade::hooks::call(glBlendColor);
trampoline(red, green, blue, alpha);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[1] = { reshade::api::dynamic_state::blend_constant };
const uint32_t values[1] = {
((static_cast<uint32_t>(red * 255.f) & 0xFF)) |
((static_cast<uint32_t>(green * 255.f) & 0xFF) << 8) |
((static_cast<uint32_t>(blue * 255.f) & 0xFF) << 16) |
((static_cast<uint32_t>(alpha * 255.f) & 0xFF) << 24) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
void APIENTRY glBlendEquation(GLenum mode)
{
static const auto trampoline = reshade::hooks::call(glBlendEquation);
trampoline(mode);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[2] = { reshade::api::dynamic_state::color_blend_op, reshade::api::dynamic_state::alpha_blend_op };
const uint32_t values[2] = { static_cast<uint32_t>(reshade::opengl::convert_blend_op(mode)), static_cast<uint32_t>(reshade::opengl::convert_blend_op(mode)) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
void APIENTRY glMultiDrawArrays(GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode);
for (GLsizei i = 0; i < drawcount; ++i)
if (reshade::invoke_addon_event<reshade::addon_event::draw>(g_opengl_context, count[i], 1, first[i], 0))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glMultiDrawArrays);
trampoline(mode, first, count, drawcount);
}
void APIENTRY glMultiDrawElements(GLenum mode, const GLsizei *count, GLenum type, const GLvoid *const *indices, GLsizei drawcount)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode, type);
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
for (GLsizei i = 0; i < drawcount; ++i)
{
const uint32_t offset = (index_buffer_binding != 0) ? static_cast<uint32_t>(reinterpret_cast<uintptr_t>(indices[i]) / reshade::opengl::get_index_type_size(type)) : 0;
if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(g_opengl_context, count[i], 1, offset, 0, 0))
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glMultiDrawElements);
trampoline(mode, count, type, indices, drawcount);
}
#endif
#ifdef GL_VERSION_1_5
void APIENTRY glDeleteBuffers(GLsizei n, const GLuint *buffers)
{
#if RESHADE_ADDON
for (GLsizei i = 0; i < n; ++i)
if (gl.IsBuffer(buffers[i]))
destroy_resource_or_view(GL_BUFFER, buffers[i]);
#endif
static const auto trampoline = reshade::hooks::call(glDeleteBuffers);
trampoline(n, buffers);
}
void APIENTRY glBufferData(GLenum target, GLsizeiptr size, const void *data, GLenum usage)
{
static const auto trampoline = reshade::hooks::call(glBufferData);
#if RESHADE_ADDON
if (g_opengl_context)
{
GLbitfield storage_flags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_DYNAMIC_STORAGE_BIT;
init_resource resource(target, 0, size, storage_flags);
resource.invoke_create_event(&size, &storage_flags, data);
trampoline(target, size, data, usage);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, size, data, usage);
}
void APIENTRY glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void *data)
{
#if RESHADE_ADDON >= 2
if (update_buffer_region(target, 0, offset, size, data))
return;
#endif
static const auto trampoline = reshade::hooks::call(glBufferSubData);
trampoline(target, offset, size, data);
}
auto APIENTRY glMapBuffer(GLenum target, GLenum access) -> void *
{
static const auto trampoline = reshade::hooks::call(glMapBuffer);
void *result = trampoline(target, access);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::map_buffer_region>())
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
GLint object = 0;
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), &object);
reshade::invoke_addon_event<reshade::addon_event::map_buffer_region>(
device,
reshade::opengl::make_resource_handle(GL_BUFFER, object),
0,
UINT64_MAX,
reshade::opengl::convert_access_flags(access),
&result);
}
#endif
return result;
}
void APIENTRY glUnmapBuffer(GLenum target)
{
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::unmap_buffer_region>())
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
GLint object = 0;
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), &object);
reshade::invoke_addon_event<reshade::addon_event::unmap_buffer_region>(
device,
reshade::opengl::make_resource_handle(GL_BUFFER, object));
}
#endif
static const auto trampoline = reshade::hooks::call(glUnmapBuffer);
trampoline(target);
}
void APIENTRY glBindBuffer(GLenum target, GLuint buffer)
{
static const auto trampoline = reshade::hooks::call(glBindBuffer);
trampoline(target, buffer);
#if RESHADE_ADDON >= 2
if (g_opengl_context)
{
switch (target)
{
case GL_ARRAY_BUFFER:
g_opengl_context->_current_vbo_dirty = true;
break;
case GL_ELEMENT_ARRAY_BUFFER:
g_opengl_context->_current_ibo_dirty = true;
break;
}
}
#endif
}
#endif
#ifdef GL_VERSION_2_0
void APIENTRY glDeleteProgram(GLuint program)
{
#if RESHADE_ADDON
if (g_opengl_context && program != 0)
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
GLint status = GL_FALSE;
gl.GetProgramiv(program, GL_LINK_STATUS, &status);
// Only invoke 'destroy_pipeline' event for programs that had a corresponding 'init_pipeline' event invoked in 'glLinkProgram'
if (GL_FALSE != status)
{
reshade::invoke_addon_event<reshade::addon_event::destroy_pipeline>(device, reshade::api::pipeline { (static_cast<uint64_t>(GL_PROGRAM) << 40) | program });
}
}
#endif
static const auto trampoline = reshade::hooks::call(glDeleteProgram);
trampoline(program);
}
void APIENTRY glLinkProgram(GLuint program)
{
static const auto trampoline = reshade::hooks::call(glLinkProgram);
trampoline(program);
#if RESHADE_ADDON
if (g_opengl_context && program != 0)
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
// Only invoke 'init_pipeline' event for programs that were successfully compiled and linked
GLint status = GL_FALSE;
gl.GetProgramiv(program, GL_LINK_STATUS, &status);
if (GL_FALSE != status)
{
std::vector<std::pair<reshade::api::shader_desc, std::vector<char>>> sources;
sources.reserve(16);
std::vector<reshade::api::pipeline_subobject> subobjects;
subobjects.reserve(16);
GLuint shaders[16] = {};
gl.GetAttachedShaders(program, 16, nullptr, shaders);
for (const GLuint shader : shaders)
{
if (shader == 0)
break;
GLint type = GL_NONE;
gl.GetShaderiv(shader, GL_SHADER_TYPE, &type);
reshade::api::pipeline_subobject_type subobject_type = reshade::api::pipeline_subobject_type::unknown;
switch (type)
{
case GL_VERTEX_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::vertex_shader;
break;
case GL_TESS_CONTROL_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::hull_shader;
break;
case GL_TESS_EVALUATION_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::domain_shader;
break;
case GL_GEOMETRY_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::geometry_shader;
break;
case GL_FRAGMENT_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::pixel_shader;
break;
case GL_COMPUTE_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::compute_shader;
break;
default:
assert(false);
continue;
}
GLint size = 0;
gl.GetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &size);
std::pair<reshade::api::shader_desc, std::vector<char>> &source = sources.emplace_back();
source.second.resize(size);
gl.GetShaderSource(shader, size, nullptr, source.second.data());
reshade::api::shader_desc &desc = source.first;
desc.code = source.second.data();
desc.code_size = size;
desc.entry_point = "main";
subobjects.push_back({ subobject_type, 1, &desc });
}
reshade::invoke_addon_event<reshade::addon_event::init_pipeline>(device, get_opengl_pipeline_layout(), static_cast<uint32_t>(subobjects.size()), subobjects.data(), reshade::api::pipeline { (static_cast<uint64_t>(GL_PROGRAM) << 40) | program });
}
}
#endif
}
void APIENTRY glShaderSource(GLuint shader, GLsizei count, const GLchar *const *string, const GLint *length)
{
#if RESHADE_ADDON
std::string combined_source;
const GLchar *combined_source_ptr = nullptr;
GLint combined_source_length = -1;
if (g_opengl_context)
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
if (count == 1)
{
combined_source_ptr = *string;
combined_source_length = (length != nullptr) ? *length : static_cast<GLint>(std::strlen(combined_source_ptr));
}
else if (length != nullptr)
{
for (GLsizei i = 0; i < count; ++i)
combined_source.append(string[i], length[i]);
combined_source_ptr = combined_source.data();
combined_source_length = static_cast<GLint>(combined_source.size());
}
else
{
for (GLsizei i = 0; i < count; ++i)
combined_source.append(string[i]);
combined_source_ptr = combined_source.data();
combined_source_length = static_cast<GLint>(combined_source.size());
}
GLint type = GL_NONE;
gl.GetShaderiv(shader, GL_SHADER_TYPE, &type);
reshade::api::pipeline_subobject_type subobject_type;
switch (type)
{
case GL_VERTEX_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::vertex_shader;
break;
case GL_TESS_CONTROL_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::hull_shader;
break;
case GL_TESS_EVALUATION_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::domain_shader;
break;
case GL_GEOMETRY_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::geometry_shader;
break;
case GL_FRAGMENT_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::pixel_shader;
break;
case GL_COMPUTE_SHADER:
subobject_type = reshade::api::pipeline_subobject_type::compute_shader;
break;
default:
assert(false);
subobject_type = reshade::api::pipeline_subobject_type::unknown;
break;
}
reshade::api::shader_desc desc = {};
desc.code = combined_source_ptr;
desc.code_size = combined_source_length;
desc.entry_point = "main";
const reshade::api::pipeline_subobject subobject = { subobject_type, 1, &desc };
if (reshade::invoke_addon_event<reshade::addon_event::create_pipeline>(device, get_opengl_pipeline_layout(), 1, &subobject))
{
assert(desc.code_size <= static_cast<size_t>(std::numeric_limits<GLint>::max()));
combined_source_ptr = static_cast<const GLchar *>(desc.code);
combined_source_length = static_cast<GLint>(desc.code_size);
count = 1;
string = &combined_source_ptr;
length = &combined_source_length;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glShaderSource);
trampoline(shader, count, string, length);
}
void APIENTRY glUseProgram(GLuint program)
{
static const auto trampoline = reshade::hooks::call(glUseProgram);
trampoline(program);
#if RESHADE_ADDON >= 2
if (g_opengl_context)
{
const auto pipeline = (program != 0) ? reshade::api::pipeline { (static_cast<uint64_t>(GL_PROGRAM) << 40) | program } : reshade::api::pipeline {};
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline>(g_opengl_context, reshade::api::pipeline_stage::all_shader_stages, pipeline);
}
#endif
}
void APIENTRY glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha)
{
static const auto trampoline = reshade::hooks::call(glBlendEquationSeparate);
trampoline(modeRGB, modeAlpha);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[2] = { reshade::api::dynamic_state::color_blend_op, reshade::api::dynamic_state::alpha_blend_op };
const uint32_t values[2] = { static_cast<uint32_t>(reshade::opengl::convert_blend_op(modeRGB)), static_cast<uint32_t>(reshade::opengl::convert_blend_op(modeAlpha)) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, static_cast<uint32_t>(std::size(states)), states, values);
}
#endif
}
void APIENTRY glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
{
static const auto trampoline = reshade::hooks::call(glStencilFuncSeparate);
trampoline(face, func, ref, mask);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const auto stencil_func = reshade::opengl::convert_compare_op(func);
const reshade::api::dynamic_state states[6] = { reshade::api::dynamic_state::front_stencil_func, reshade::api::dynamic_state::front_stencil_reference_value, reshade::api::dynamic_state::front_stencil_read_mask, reshade::api::dynamic_state::back_stencil_func, reshade::api::dynamic_state::back_stencil_reference_value, reshade::api::dynamic_state::back_stencil_read_mask };
const uint32_t values[6] = { static_cast<uint32_t>(stencil_func), static_cast<uint32_t>(ref), mask, static_cast<uint32_t>(stencil_func), static_cast<uint32_t>(ref), mask };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, face == GL_FRONT_AND_BACK ? 6 : 3, &states[face == GL_BACK ? 3 : 0], values);
}
#endif
}
void APIENTRY glStencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
{
static const auto trampoline = reshade::hooks::call(glStencilOpSeparate);
trampoline(face, fail, zfail, zpass);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const auto stencil_fail_op = reshade::opengl::convert_stencil_op(fail);
const auto stencil_depth_fail_op = reshade::opengl::convert_stencil_op(zfail);
const auto stencil_pass_op = reshade::opengl::convert_stencil_op(zpass);
const reshade::api::dynamic_state states[6] = { reshade::api::dynamic_state::front_stencil_fail_op, reshade::api::dynamic_state::front_stencil_depth_fail_op, reshade::api::dynamic_state::front_stencil_pass_op, reshade::api::dynamic_state::back_stencil_fail_op, reshade::api::dynamic_state::back_stencil_depth_fail_op, reshade::api::dynamic_state::back_stencil_pass_op };
const uint32_t values[6] = { static_cast<uint32_t>(stencil_fail_op), static_cast<uint32_t>(stencil_depth_fail_op), static_cast<uint32_t>(stencil_pass_op), static_cast<uint32_t>(stencil_fail_op), static_cast<uint32_t>(stencil_depth_fail_op), static_cast<uint32_t>(stencil_pass_op) };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, face == GL_FRONT_AND_BACK ? 6 : 3, &states[face == GL_BACK ? 3 : 0], values);
}
#endif
}
void APIENTRY glStencilMaskSeparate(GLenum face, GLuint mask)
{
static const auto trampoline = reshade::hooks::call(glStencilMaskSeparate);
trampoline(face, mask);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_pipeline_states>())
{
const reshade::api::dynamic_state states[2] = { reshade::api::dynamic_state::front_stencil_write_mask, reshade::api::dynamic_state::back_stencil_write_mask };
const uint32_t values[2] = { mask, mask };
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline_states>(g_opengl_context, face == GL_FRONT_AND_BACK ? 2 : 1, &states[face == GL_BACK ? 1 : 0], values);
}
#endif
}
void APIENTRY glUniform1f(GLint location, GLfloat v0)
{
static const auto trampoline = reshade::hooks::call(glUniform1f);
trampoline(location, v0);
#if RESHADE_ADDON >= 2
// If location is equal to -1, the data passed in will be silently ignored
if (location < 0)
return;
if (g_opengl_context)
{
const GLfloat v[1] = { v0 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
// See global pipeline layout specified in 'wgl_device::wgl_device'
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, 1, reinterpret_cast<const uint32_t *>(v));
}
#endif
}
void APIENTRY glUniform2f(GLint location, GLfloat v0, GLfloat v1)
{
static const auto trampoline = reshade::hooks::call(glUniform2f);
trampoline(location, v0, v1);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLfloat v[2] = { v0, v1 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, 2, reinterpret_cast<const uint32_t *>(v));
}
#endif
}
void APIENTRY glUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2)
{
static const auto trampoline = reshade::hooks::call(glUniform3f);
trampoline(location, v0, v1, v2);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLfloat v[3] = { v0, v1, v2 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, 3, reinterpret_cast<const uint32_t *>(v));
}
#endif
}
void APIENTRY glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3)
{
static const auto trampoline = reshade::hooks::call(glUniform4f);
trampoline(location, v0, v1, v2, v3);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLfloat v[4] = { v0, v1, v2, v3 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, 4, reinterpret_cast<const uint32_t *>(v));
}
#endif
}
void APIENTRY glUniform1i(GLint location, GLint v0)
{
static const auto trampoline = reshade::hooks::call(glUniform1i);
trampoline(location, v0);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLint v[1] = { v0 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 5, location * 4, 1, reinterpret_cast<const uint32_t *>(v));
}
#endif
}
void APIENTRY glUniform2i(GLint location, GLint v0, GLint v1)
{
static const auto trampoline = reshade::hooks::call(glUniform2i);
trampoline(location, v0, v1);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLint v[2] = { v0, v1 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 5, location * 4, 2, reinterpret_cast<const uint32_t *>(v));
}
#endif
}
void APIENTRY glUniform3i(GLint location, GLint v0, GLint v1, GLint v2)
{
static const auto trampoline = reshade::hooks::call(glUniform3i);
trampoline(location, v0, v1, v2);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLint v[3] = { v0, v1, v2 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 5, location * 4, 3, reinterpret_cast<const uint32_t *>(v));
}
#endif
}
void APIENTRY glUniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3)
{
static const auto trampoline = reshade::hooks::call(glUniform4i);
trampoline(location, v0, v1, v2, v3);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLint v[4] = { v0, v1, v2, v3 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 5, location * 4, 4, reinterpret_cast<const uint32_t *>(v));
}
#endif
}
void APIENTRY glUniform1fv(GLint location, GLsizei count, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniform1fv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 1, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniform2fv(GLint location, GLsizei count, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniform2fv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 2, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniform3fv(GLint location, GLsizei count, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniform3fv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 3, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniform4fv(GLint location, GLsizei count, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniform4fv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 4, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniform1iv(GLint location, GLsizei count, const GLint *value)
{
static const auto trampoline = reshade::hooks::call(glUniform1iv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 5, location * 4, count * 1, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniform2iv(GLint location, GLsizei count, const GLint *value)
{
static const auto trampoline = reshade::hooks::call(glUniform2iv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 5, location * 4, count * 2, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniform3iv(GLint location, GLsizei count, const GLint *value)
{
static const auto trampoline = reshade::hooks::call(glUniform3iv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 5, location * 4, count * 3, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniform4iv(GLint location, GLsizei count, const GLint *value)
{
static const auto trampoline = reshade::hooks::call(glUniform4iv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 5, location * 4, count * 4, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniformMatrix2fv);
trampoline(location, count, transpose, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 2 * 2, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniformMatrix3fv);
trampoline(location, count, transpose, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 3 * 3, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniformMatrix4fv);
trampoline(location, count, transpose, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 4 * 4, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer)
{
static const auto trampoline = reshade::hooks::call(glVertexAttribPointer);
trampoline(index, size, type, normalized, stride, pointer);
#if RESHADE_ADDON >= 2
if (g_opengl_context != nullptr)
g_opengl_context->_current_vao_dirty = true;
#endif
}
#endif
#ifdef GL_VERSION_2_1
void APIENTRY glUniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniformMatrix2x3fv);
trampoline(location, count, transpose, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 2 * 3, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniformMatrix3x2fv);
trampoline(location, count, transpose, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 3 * 2, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniformMatrix2x4fv);
trampoline(location, count, transpose, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 2 * 4, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniformMatrix4x2fv);
trampoline(location, count, transpose, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 4 * 2, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniformMatrix3x4fv);
trampoline(location, count, transpose, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 3 * 4, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
void APIENTRY glUniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
{
static const auto trampoline = reshade::hooks::call(glUniformMatrix3x4fv);
trampoline(location, count, transpose, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 4, location * 4, count * 4 * 3, reinterpret_cast<const uint32_t *>(value));
}
#endif
}
#endif
#ifdef GL_VERSION_3_0
void APIENTRY glDeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers)
{
#if RESHADE_ADDON
for (GLsizei i = 0; i < n; ++i)
if (gl.IsRenderbuffer(renderbuffers[i]))
destroy_resource_or_view(GL_RENDERBUFFER, renderbuffers[i]);
#endif
static const auto trampoline = reshade::hooks::call(glDeleteRenderbuffers);
trampoline(n, renderbuffers);
}
void APIENTRY glDeleteVertexArrays(GLsizei n, const GLuint *arrays)
{
#if RESHADE_ADDON
if (g_opengl_context != nullptr)
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
for (GLsizei i = 0; i < n; ++i)
if (gl.IsVertexArray(arrays[i]))
reshade::invoke_addon_event<reshade::addon_event::destroy_pipeline>(device, reshade::api::pipeline { (static_cast<uint64_t>(GL_VERTEX_ARRAY) << 40) | arrays[i] });
}
#endif
static const auto trampoline = reshade::hooks::call(glDeleteVertexArrays);
trampoline(n, arrays);
}
void APIENTRY glFramebufferTexture1D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
{
static const auto trampoline = reshade::hooks::call(glFramebufferTexture1D);
trampoline(target, attachment, textarget, texture, level);
#if RESHADE_ADDON
update_framebuffer_object(target);
#endif
}
void APIENTRY glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
{
static const auto trampoline = reshade::hooks::call(glFramebufferTexture2D);
trampoline(target, attachment, textarget, texture, level);
#if RESHADE_ADDON
update_framebuffer_object(target);
#endif
}
void APIENTRY glFramebufferTexture3D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint layer)
{
static const auto trampoline = reshade::hooks::call(glFramebufferTexture3D);
trampoline(target, attachment, textarget, texture, level, layer);
#if RESHADE_ADDON
update_framebuffer_object(target);
#endif
}
void APIENTRY glFramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer)
{
static const auto trampoline = reshade::hooks::call(glFramebufferTextureLayer);
trampoline(target, attachment, texture, level, layer);
#if RESHADE_ADDON
update_framebuffer_object(target);
#endif
}
void APIENTRY glFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
{
static const auto trampoline = reshade::hooks::call(glFramebufferRenderbuffer);
trampoline(target, attachment, renderbuffertarget, renderbuffer);
#if RESHADE_ADDON
update_framebuffer_object(target);
#endif
}
void APIENTRY glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
{
static const auto trampoline = reshade::hooks::call(glRenderbufferStorage);
#if RESHADE_ADDON
internalformat = reshade::opengl::convert_sized_internal_format(internalformat);
if (g_opengl_context)
{
init_resource resource(target, 0, 1, 1, internalformat, width, height, 1);
resource.invoke_create_event(nullptr, nullptr, &internalformat, &width, &height, nullptr);
trampoline(target, internalformat, width, height);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, internalformat, width, height);
}
void APIENTRY glRenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
{
static const auto trampoline = reshade::hooks::call(glRenderbufferStorageMultisample);
#if RESHADE_ADDON
internalformat = reshade::opengl::convert_sized_internal_format(internalformat);
if (g_opengl_context)
{
init_resource resource(target, 0, 1, samples, internalformat, width, height, 1);
resource.invoke_create_event(nullptr, &samples, &internalformat, &width, &height, nullptr);
trampoline(target, samples, internalformat, width, height);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, samples, internalformat, width, height);
}
auto APIENTRY glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLenum access) -> void *
{
static const auto trampoline = reshade::hooks::call(glMapBufferRange);
void *result = trampoline(target, offset, length, access);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::map_buffer_region>())
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
GLint object = 0;
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), &object);
reshade::invoke_addon_event<reshade::addon_event::map_buffer_region>(
device,
reshade::opengl::make_resource_handle(GL_BUFFER, object),
offset,
length,
reshade::opengl::convert_access_flags(access),
&result);
}
#endif
return result;
}
void APIENTRY glClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint *value)
{
#if RESHADE_ADDON
if (g_opengl_context && (
reshade::has_addon_event<reshade::addon_event::clear_depth_stencil_view>() ||
reshade::has_addon_event<reshade::addon_event::clear_render_target_view>()))
{
assert(buffer == GL_COLOR || (buffer == GL_STENCIL && drawbuffer == 0));
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
GLint fbo = 0;
gl.GetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fbo);
const reshade::api::resource_view view = device->get_framebuffer_attachment(fbo, buffer, drawbuffer);
if (view != 0)
{
if (buffer != GL_COLOR ?
reshade::invoke_addon_event<reshade::addon_event::clear_depth_stencil_view>(g_opengl_context, view, nullptr, reinterpret_cast<const uint8_t *>(value), 0, nullptr) :
reshade::invoke_addon_event<reshade::addon_event::clear_render_target_view>(g_opengl_context, view, reinterpret_cast<const float *>(value), 0, nullptr))
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glClearBufferiv);
trampoline(buffer, drawbuffer, value);
}
void APIENTRY glClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint *value)
{
#if RESHADE_ADDON
if (g_opengl_context && (
reshade::has_addon_event<reshade::addon_event::clear_depth_stencil_view>() ||
reshade::has_addon_event<reshade::addon_event::clear_render_target_view>()))
{
assert(buffer == GL_COLOR || (buffer == GL_STENCIL && drawbuffer == 0));
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
GLint fbo = 0;
gl.GetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fbo);
const reshade::api::resource_view view = device->get_framebuffer_attachment(fbo, buffer, drawbuffer);
if (view != 0)
{
if (buffer != GL_COLOR ?
reshade::invoke_addon_event<reshade::addon_event::clear_depth_stencil_view>(g_opengl_context, view, nullptr, reinterpret_cast<const uint8_t *>(value), 0, nullptr) :
reshade::invoke_addon_event<reshade::addon_event::clear_render_target_view>(g_opengl_context, view, reinterpret_cast<const float *>(value), 0, nullptr))
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glClearBufferuiv);
trampoline(buffer, drawbuffer, value);
}
void APIENTRY glClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat *value)
{
#if RESHADE_ADDON
if (g_opengl_context && (
reshade::has_addon_event<reshade::addon_event::clear_depth_stencil_view>() ||
reshade::has_addon_event<reshade::addon_event::clear_render_target_view>()))
{
assert(buffer == GL_COLOR || (buffer == GL_DEPTH && drawbuffer == 0));
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
GLint fbo = 0;
gl.GetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fbo);
const reshade::api::resource_view view = device->get_framebuffer_attachment(fbo, buffer, drawbuffer);
if (view != 0)
{
if (buffer != GL_COLOR ?
reshade::invoke_addon_event<reshade::addon_event::clear_depth_stencil_view>(g_opengl_context, view, value, nullptr, 0, nullptr) :
reshade::invoke_addon_event<reshade::addon_event::clear_render_target_view>(g_opengl_context, view, value, 0, nullptr))
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glClearBufferfv);
trampoline(buffer, drawbuffer, value);
}
void APIENTRY glClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)
{
#if RESHADE_ADDON
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::clear_depth_stencil_view>())
{
assert(buffer == GL_DEPTH_STENCIL && drawbuffer == 0);
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
GLint fbo = 0;
gl.GetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fbo);
const reshade::api::resource_view dsv = device->get_framebuffer_attachment(fbo, buffer, drawbuffer);
if (dsv != 0 &&
reshade::invoke_addon_event<reshade::addon_event::clear_depth_stencil_view>(g_opengl_context, dsv, &depth, reinterpret_cast<const uint8_t *>(&stencil), 0, nullptr))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glClearBufferfi);
trampoline(buffer, drawbuffer, depth, stencil);
}
void APIENTRY glBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)
{
#if RESHADE_ADDON >= 2
if (g_opengl_context && (
reshade::has_addon_event<reshade::addon_event::copy_texture_region>() ||
reshade::has_addon_event<reshade::addon_event::resolve_texture_region>()))
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
GLint src_fbo = 0;
gl.GetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &src_fbo);
GLint dst_fbo = 0;
gl.GetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &dst_fbo);
constexpr GLbitfield flags[3] = { GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT };
for (GLbitfield flag : flags)
{
if ((mask & flag) != flag)
continue;
reshade::api::resource src = device->get_resource_from_view(device->get_framebuffer_attachment(src_fbo, flag, 0));
reshade::api::resource dst = device->get_resource_from_view(device->get_framebuffer_attachment(dst_fbo, flag, 0));
if (device->get_resource_desc(src).texture.samples <= 1)
{
const reshade::api::subresource_box src_box = { srcX0, srcY0, 0, srcX1, srcY1, 1 }, dst_box = { dstX0, dstY0, 0, dstX1, dstY1, 1 };
if (reshade::invoke_addon_event<reshade::addon_event::copy_texture_region>(g_opengl_context, src, 0, &src_box, dst, 0, &dst_box, (filter == GL_NONE || filter == GL_NEAREST) ? reshade::api::filter_mode::min_mag_mip_point : reshade::api::filter_mode::min_mag_mip_linear))
mask ^= flag;
}
else
{
assert((srcX1 - srcX0) == (dstX1 - dstX0) && (srcY1 - srcY0) == (dstY1 - dstY0));
const reshade::api::subresource_box src_box = { srcX0, srcY0, 0, srcX1, srcY1, 1 };
if (reshade::invoke_addon_event<reshade::addon_event::resolve_texture_region>(g_opengl_context, src, 0, &src_box, dst, 0, dstX0, dstY0, 0, reshade::api::format::unknown))
mask ^= flag;
}
}
if (mask == 0)
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glBlitFramebuffer);
trampoline(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
}
void APIENTRY glGenerateMipmap(GLenum target)
{
#if RESHADE_ADDON >= 2
if (g_opengl_context)
{
GLint object = 0;
gl.GetIntegerv(reshade::opengl::get_binding_for_target(target), &object);
if (reshade::invoke_addon_event<reshade::addon_event::generate_mipmaps>(g_opengl_context, reshade::opengl::make_resource_view_handle(target, object)))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glGenerateMipmap);
trampoline(target);
}
void APIENTRY glBindBufferBase(GLenum target, GLuint index, GLuint buffer)
{
static const auto trampoline = reshade::hooks::call(glBindBufferBase);
trampoline(target, index, buffer);
#if RESHADE_ADDON >= 2
if (g_opengl_context)
{
if ((target == GL_UNIFORM_BUFFER || target == GL_SHADER_STORAGE_BUFFER) && reshade::has_addon_event<reshade::addon_event::push_descriptors>())
{
const reshade::api::buffer_range descriptor_data = {
reshade::opengl::make_resource_handle(GL_BUFFER, buffer),
0,
UINT64_MAX
};
const auto type = (target == GL_UNIFORM_BUFFER) ? reshade::api::descriptor_type::constant_buffer : reshade::api::descriptor_type::shader_storage_buffer;
const auto layout_param = (target == GL_UNIFORM_BUFFER) ? 2 : 1;
reshade::invoke_addon_event<reshade::addon_event::push_descriptors>(
g_opengl_context,
reshade::api::shader_stage::all,
// See global pipeline layout specified in 'wgl_device::wgl_device'
get_opengl_pipeline_layout(), layout_param,
reshade::api::descriptor_table_update { {}, index, 0, 1, type, &descriptor_data });
}
else if ((target == GL_TRANSFORM_FEEDBACK_BUFFER) && reshade::has_addon_event<reshade::addon_event::bind_stream_output_buffers>())
{
const reshade::api::resource buffer_handle = reshade::opengl::make_resource_handle(GL_BUFFER, buffer);
uint64_t offset_64 = 0;
uint64_t max_size_64 = UINT64_MAX;
reshade::invoke_addon_event<reshade::addon_event::bind_stream_output_buffers>(g_opengl_context, index, 1, &buffer_handle, &offset_64, &max_size_64, nullptr, nullptr);
}
}
#endif
}
void APIENTRY glBindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size)
{
static const auto trampoline = reshade::hooks::call(glBindBufferRange);
trampoline(target, index, buffer, offset, size);
#if RESHADE_ADDON >= 2
if (g_opengl_context)
{
if ((target == GL_UNIFORM_BUFFER || target == GL_SHADER_STORAGE_BUFFER) && reshade::has_addon_event<reshade::addon_event::push_descriptors>())
{
const reshade::api::buffer_range descriptor_data = {
reshade::opengl::make_resource_handle(GL_BUFFER, buffer),
static_cast<uint64_t>(offset),
static_cast<uint64_t>(size)
};
const auto type = (target == GL_UNIFORM_BUFFER) ? reshade::api::descriptor_type::constant_buffer : reshade::api::descriptor_type::shader_storage_buffer;
const auto layout_param = (target == GL_UNIFORM_BUFFER) ? 2 : 1;
reshade::invoke_addon_event<reshade::addon_event::push_descriptors>(
g_opengl_context,
reshade::api::shader_stage::all,
// See global pipeline layout specified in 'wgl_device::wgl_device'
get_opengl_pipeline_layout(), layout_param,
reshade::api::descriptor_table_update { {}, index, 0, 1, type, &descriptor_data });
}
else if ((target == GL_TRANSFORM_FEEDBACK_BUFFER) && reshade::has_addon_event<reshade::addon_event::bind_stream_output_buffers>())
{
const reshade::api::resource buffer_handle = reshade::opengl::make_resource_handle(GL_BUFFER, buffer);
uint64_t offset_64 = offset;
uint64_t max_size_64 = size;
reshade::invoke_addon_event<reshade::addon_event::bind_stream_output_buffers>(g_opengl_context, index, 1, &buffer_handle, &offset_64, &max_size_64, nullptr, nullptr);
}
}
#endif
}
void APIENTRY glBindFramebuffer(GLenum target, GLuint framebuffer)
{
static const auto trampoline = reshade::hooks::call(glBindFramebuffer);
trampoline(target, framebuffer);
#if RESHADE_ADDON
update_framebuffer_object(target, framebuffer);
#endif
}
void APIENTRY glBindVertexArray(GLuint array)
{
static const auto trampoline = reshade::hooks::call(glBindVertexArray);
trampoline(array);
#if RESHADE_ADDON >= 2
if (g_opengl_context)
{
g_opengl_context->_current_vao_dirty = true;
update_current_input_layout();
}
#endif
}
void APIENTRY glUniform1ui(GLint location, GLuint v0)
{
static const auto trampoline = reshade::hooks::call(glUniform1ui);
trampoline(location, v0);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLuint v[1] = { v0 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
// See global pipeline layout specified in 'wgl_device::wgl_device'
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 6, location * 4, 1, v);
}
#endif
}
void APIENTRY glUniform2ui(GLint location, GLuint v0, GLuint v1)
{
static const auto trampoline = reshade::hooks::call(glUniform2ui);
trampoline(location, v0, v1);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLuint v[2] = { v0, v1 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 6, location * 4, 2, v);
}
#endif
}
void APIENTRY glUniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2)
{
static const auto trampoline = reshade::hooks::call(glUniform3ui);
trampoline(location, v0, v1, v2);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLuint v[3] = { v0, v1, v2 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 6, location * 4, 3, v);
}
#endif
}
void APIENTRY glUniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3)
{
static const auto trampoline = reshade::hooks::call(glUniform4ui);
trampoline(location, v0, v1, v2, v3);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
const GLuint v[4] = { v0, v1, v2, v3 };
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 6, location * 4, 4, v);
}
#endif
}
void APIENTRY glUniform1uiv(GLint location, GLsizei count, const GLuint *value)
{
static const auto trampoline = reshade::hooks::call(glUniform1uiv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 6, location * 4, count * 1, value);
}
#endif
}
void APIENTRY glUniform2uiv(GLint location, GLsizei count, const GLuint *value)
{
static const auto trampoline = reshade::hooks::call(glUniform2uiv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 6, location * 4, count * 2, value);
}
#endif
}
void APIENTRY glUniform3uiv(GLint location, GLsizei count, const GLuint *value)
{
static const auto trampoline = reshade::hooks::call(glUniform3uiv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 6, location * 4, count * 3, value);
}
#endif
}
void APIENTRY glUniform4uiv(GLint location, GLsizei count, const GLuint *value)
{
static const auto trampoline = reshade::hooks::call(glUniform4uiv);
trampoline(location, count, value);
#if RESHADE_ADDON >= 2
if (location < 0)
return;
if (g_opengl_context)
{
reshade::invoke_addon_event<reshade::addon_event::push_constants>(
g_opengl_context, reshade::api::shader_stage::all, get_opengl_pipeline_layout(), 6, location * 4, count * 4, value);
}
#endif
}
void APIENTRY glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer)
{
static const auto trampoline = reshade::hooks::call(glVertexAttribIPointer);
trampoline(index, size, type, stride, pointer);
#if RESHADE_ADDON >= 2
if (g_opengl_context != nullptr)
g_opengl_context->_current_vao_dirty = true;
#endif
}
#endif
#ifdef GL_VERSION_3_1
void APIENTRY glTexBuffer(GLenum target, GLenum internalformat, GLuint buffer)
{
#if RESHADE_ADDON
glTexBufferRange(target, internalformat, buffer, 0, -1);
#else
static const auto trampoline = reshade::hooks::call(glTexBuffer);
trampoline(target, internalformat, buffer);
#endif
}
void APIENTRY glCopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size)
{
#if RESHADE_ADDON >= 2
if (copy_buffer_region(readTarget, 0, readOffset, writeTarget, 0, writeOffset, size))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCopyBufferSubData);
trampoline(readTarget, writeTarget, readOffset, writeOffset, size);
}
void APIENTRY glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei primcount)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode);
if (reshade::invoke_addon_event<reshade::addon_event::draw>(g_opengl_context, primcount, count, first, 0))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawArraysInstanced);
trampoline(mode, first, count, primcount);
}
void APIENTRY glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode, type);
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
const uint32_t offset = (index_buffer_binding != 0) ? static_cast<uint32_t>(reinterpret_cast<uintptr_t>(indices) / reshade::opengl::get_index_type_size(type)) : 0;
if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(g_opengl_context, primcount, count, offset, 0, 0))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawElementsInstanced);
trampoline(mode, count, type, indices, primcount);
}
#endif
#ifdef GL_VERSION_3_2
void APIENTRY glFramebufferTexture(GLenum target, GLenum attachment, GLuint texture, GLint level)
{
static const auto trampoline = reshade::hooks::call(glFramebufferTexture);
trampoline(target, attachment, texture, level);
#if RESHADE_ADDON
// Need to update render target and depth-stencil bindings after the current framebuffer was updated again
update_framebuffer_object(target);
#endif
}
void APIENTRY glTexImage2DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)
{
static const auto trampoline = reshade::hooks::call(glTexImage2DMultisample);
#if RESHADE_ADDON
internalformat = reshade::opengl::convert_sized_internal_format(internalformat);
// Ignore proxy texture objects
const bool proxy_object = (target == GL_PROXY_TEXTURE_2D_MULTISAMPLE);
if (g_opengl_context && !proxy_object)
{
init_resource resource(target, 0, 1, samples, internalformat, width, height, 1);
resource.invoke_create_event(nullptr, &samples, &internalformat, &width, &height, nullptr);
trampoline(target, samples, internalformat, width, height, fixedsamplelocations);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, samples, internalformat, width, height, fixedsamplelocations);
}
void APIENTRY glTexImage3DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations)
{
static const auto trampoline = reshade::hooks::call(glTexImage3DMultisample);
#if RESHADE_ADDON
internalformat = reshade::opengl::convert_sized_internal_format(internalformat);
// Ignore proxy texture objects
const bool proxy_object = (target == GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY);
if (g_opengl_context && !proxy_object)
{
init_resource resource(target, 0, 1, samples, internalformat, width, height, depth);
resource.invoke_create_event(nullptr, &samples, &internalformat, &width, &height, &depth);
trampoline(target, samples, internalformat, width, height, depth, fixedsamplelocations);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, samples, internalformat, width, height, depth, fixedsamplelocations);
}
void APIENTRY glDrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode, type);
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
const uint32_t offset = (index_buffer_binding != 0) ? static_cast<uint32_t>(reinterpret_cast<uintptr_t>(indices) / reshade::opengl::get_index_type_size(type)) : 0;
if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(g_opengl_context, count, 1, offset, basevertex, 0))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawElementsBaseVertex);
trampoline(mode, count, type, indices, basevertex);
}
void APIENTRY glDrawRangeElementsBaseVertex(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode, type);
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
const uint32_t offset = (index_buffer_binding != 0) ? static_cast<uint32_t>(reinterpret_cast<uintptr_t>(indices) / reshade::opengl::get_index_type_size(type)) : 0;
if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(g_opengl_context, count, 1, offset, basevertex, 0))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawRangeElementsBaseVertex);
trampoline(mode, start, end, count, type, indices, basevertex);
}
void APIENTRY glDrawElementsInstancedBaseVertex(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount, GLint basevertex)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode, type);
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
const uint32_t offset = (index_buffer_binding != 0) ? static_cast<uint32_t>(reinterpret_cast<uintptr_t>(indices) / reshade::opengl::get_index_type_size(type)) : 0;
if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(g_opengl_context, primcount, count, offset, basevertex, 0))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawElementsInstancedBaseVertex);
trampoline(mode, count, type, indices, primcount, basevertex);
}
void APIENTRY glMultiDrawElementsBaseVertex(GLenum mode, const GLsizei *count, GLenum type, const GLvoid *const *indices, GLsizei drawcount, const GLint *basevertex)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode, type);
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
for (GLsizei i = 0; i < drawcount; ++i)
{
const uint32_t offset = (index_buffer_binding != 0) ? static_cast<uint32_t>(reinterpret_cast<uintptr_t>(indices[i]) / reshade::opengl::get_index_type_size(type)) : 0;
if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(g_opengl_context, count[i], 1, offset, basevertex[i], 0))
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glMultiDrawElementsBaseVertex);
trampoline(mode, count, type, indices, drawcount, basevertex);
}
#endif
#ifdef GL_VERSION_4_0
void APIENTRY glDrawArraysIndirect(GLenum mode, const GLvoid *indirect)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
GLint indirect_buffer_binding = 0;
gl.GetIntegerv(GL_DRAW_INDIRECT_BUFFER_BINDING, &indirect_buffer_binding);
if (0 != indirect_buffer_binding)
{
update_current_primitive_topology(mode);
if (reshade::invoke_addon_event<reshade::addon_event::draw_or_dispatch_indirect>(
g_opengl_context,
reshade::api::indirect_command::draw,
reshade::opengl::make_resource_handle(GL_BUFFER, indirect_buffer_binding),
reinterpret_cast<uintptr_t>(indirect),
1,
0))
return;
}
else
{
// Redirect to non-indirect draw call so proper event is invoked
const auto cmd = static_cast<const DrawArraysIndirectCommand *>(indirect);
glDrawArraysInstancedBaseInstance(mode, cmd->first, cmd->count, cmd->primcount, cmd->baseinstance);
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawArraysIndirect);
trampoline(mode, indirect);
}
void APIENTRY glDrawElementsIndirect(GLenum mode, GLenum type, const GLvoid *indirect)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
GLint indirect_buffer_binding = 0;
gl.GetIntegerv(GL_DRAW_INDIRECT_BUFFER_BINDING, &indirect_buffer_binding);
if (0 != indirect_buffer_binding)
{
update_current_primitive_topology(mode, type);
if (reshade::invoke_addon_event<reshade::addon_event::draw_or_dispatch_indirect>(
g_opengl_context,
reshade::api::indirect_command::draw_indexed,
reshade::opengl::make_resource_handle(GL_BUFFER, indirect_buffer_binding),
reinterpret_cast<uintptr_t>(indirect),
1,
0))
return;
}
else
{
// Redirect to non-indirect draw call so proper event is invoked
const auto cmd = static_cast<const DrawElementsIndirectCommand *>(indirect);
glDrawElementsInstancedBaseVertexBaseInstance(
mode,
cmd->count,
type,
reinterpret_cast<const GLvoid *>(static_cast<uintptr_t>(static_cast<size_t>(cmd->firstindex) * reshade::opengl::get_index_type_size(type))),
cmd->primcount,
cmd->basevertex,
cmd->baseinstance);
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawElementsIndirect);
trampoline(mode, type, indirect);
}
#endif
#ifdef GL_VERSION_4_1
void APIENTRY glScissorArrayv(GLuint first, GLsizei count, const GLint *v)
{
static const auto trampoline = reshade::hooks::call(glScissorArrayv);
trampoline(first, count, v);
#if RESHADE_ADDON
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_scissor_rects>())
{
GLint clip_origin = GL_LOWER_LEFT;
if (gl.ClipControl != nullptr)
gl.GetIntegerv(GL_CLIP_ORIGIN, &clip_origin);
temp_mem<reshade::api::rect> rect_data(count);
for (GLsizei i = 0; i < count; ++i, v += 4)
{
rect_data[i].left = v[0];
rect_data[i].right = v[0] + v[2];
if (clip_origin == GL_UPPER_LEFT)
{
rect_data[i].top = v[1];
rect_data[i].bottom = v[1] + v[3];
}
else
{
assert(g_opengl_context->_current_window_height != 0);
rect_data[i].top = g_opengl_context->_current_window_height - (v[1] + v[3]);
rect_data[i].bottom = g_opengl_context->_current_window_height - v[1];
}
}
reshade::invoke_addon_event<reshade::addon_event::bind_scissor_rects>(g_opengl_context, first, count, rect_data.p);
}
#endif
}
void APIENTRY glScissorIndexed(GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height)
{
static const auto trampoline = reshade::hooks::call(glScissorIndexed);
trampoline(index, left, bottom, width, height);
#if RESHADE_ADDON
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_scissor_rects>())
{
GLint clip_origin = GL_LOWER_LEFT;
if (gl.ClipControl != nullptr)
gl.GetIntegerv(GL_CLIP_ORIGIN, &clip_origin);
reshade::api::rect rect_data;
rect_data.left = left;
rect_data.right = left + width;
if (clip_origin == GL_UPPER_LEFT)
{
rect_data.top = bottom;
rect_data.bottom = bottom + height;
}
else
{
assert(g_opengl_context->_current_window_height != 0);
rect_data.top = g_opengl_context->_current_window_height - (bottom + height);
rect_data.bottom = g_opengl_context->_current_window_height - bottom;
}
reshade::invoke_addon_event<reshade::addon_event::bind_scissor_rects>(g_opengl_context, index, 1, &rect_data);
}
#endif
}
void APIENTRY glScissorIndexedv(GLuint index, const GLint *v)
{
static const auto trampoline = reshade::hooks::call(glScissorIndexedv);
trampoline(index, v);
#if RESHADE_ADDON
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_scissor_rects>())
{
GLint clip_origin = GL_LOWER_LEFT;
if (gl.ClipControl != nullptr)
gl.GetIntegerv(GL_CLIP_ORIGIN, &clip_origin);
reshade::api::rect rect_data;
rect_data.left = v[0];
rect_data.right = v[0] + v[2];
if (clip_origin == GL_UPPER_LEFT)
{
rect_data.top = v[1];
rect_data.bottom = v[1] + v[3];
}
else
{
assert(g_opengl_context->_current_window_height != 0);
rect_data.top = g_opengl_context->_current_window_height - (v[1] + v[3]);
rect_data.bottom = g_opengl_context->_current_window_height - v[1];
}
reshade::invoke_addon_event<reshade::addon_event::bind_scissor_rects>(g_opengl_context, index, 1, &rect_data);
}
#endif
}
void APIENTRY glViewportArrayv(GLuint first, GLsizei count, const GLfloat *v)
{
static const auto trampoline = reshade::hooks::call(glViewportArrayv);
trampoline(first, count, v);
#if RESHADE_ADDON
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_viewports>())
{
temp_mem<reshade::api::viewport> viewport_data(count);
for (GLsizei i = 0; i < count; ++i, v += 4)
{
viewport_data[i].x = v[0];
viewport_data[i].y = v[1];
viewport_data[i].width = v[2];
viewport_data[i].height = v[3];
viewport_data[i].min_depth = 0.0f; // This is set via 'glDepthRange', so just assume defaults here for now
viewport_data[i].max_depth = 1.0f;
}
reshade::invoke_addon_event<reshade::addon_event::bind_viewports>(g_opengl_context, first, count, viewport_data.p);
}
#endif
}
void APIENTRY glViewportIndexedf(GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h)
{
static const auto trampoline = reshade::hooks::call(glViewportIndexedf);
trampoline(index, x, y, w, h);
#if RESHADE_ADDON
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_viewports>())
{
const reshade::api::viewport viewport_data = { x, y, w, h, 0.0f, 1.0f };
reshade::invoke_addon_event<reshade::addon_event::bind_viewports>(g_opengl_context, index, 1, &viewport_data);
}
#endif
}
void APIENTRY glViewportIndexedfv(GLuint index, const GLfloat *v)
{
static const auto trampoline = reshade::hooks::call(glViewportIndexedfv);
trampoline(index, v);
#if RESHADE_ADDON
if (g_opengl_context)
{
const reshade::api::viewport viewport_data = { v[0], v[1], v[2], v[3], 0.0f, 1.0f };
reshade::invoke_addon_event<reshade::addon_event::bind_viewports>(g_opengl_context, index, 1, &viewport_data);
}
#endif
}
void APIENTRY glVertexAttribLPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer)
{
static const auto trampoline = reshade::hooks::call(glVertexAttribLPointer);
trampoline(index, size, type, stride, pointer);
#if RESHADE_ADDON >= 2
if (g_opengl_context != nullptr)
g_opengl_context->_current_vao_dirty = true;
#endif
}
#endif
#ifdef GL_VERSION_4_2
void APIENTRY glTexStorage1D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width)
{
static const auto trampoline = reshade::hooks::call(glTexStorage1D);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(target, 0, levels, 1, internalformat, width, 1, 1);
resource.invoke_create_event(&levels, nullptr, &internalformat, &width, nullptr, nullptr);
trampoline(target, levels, internalformat, width);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, levels, internalformat, width);
}
void APIENTRY glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
{
static const auto trampoline = reshade::hooks::call(glTexStorage2D);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(target, 0, levels, 1, internalformat, width, height, 1);
resource.invoke_create_event(&levels, nullptr, &internalformat, &width, &height, nullptr);
trampoline(target, levels, internalformat, width, height);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, levels, internalformat, width, height);
}
void APIENTRY glTexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth)
{
static const auto trampoline = reshade::hooks::call(glTexStorage3D);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(target, 0, levels, 1, internalformat, width, height, depth);
resource.invoke_create_event(&levels, nullptr, &internalformat, &width, &height, &depth);
trampoline(target, levels, internalformat, width, height, depth);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, levels, internalformat, width, height, depth);
}
void APIENTRY glBindImageTexture(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format)
{
static const auto trampoline = reshade::hooks::call(glBindImageTexture);
trampoline(unit, texture, level, layered, layer, access, format);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::push_descriptors>())
{
GLint target = GL_TEXTURE;
if (gl.GetTextureParameteriv != nullptr)
gl.GetTextureParameteriv(texture, GL_TEXTURE_TARGET, &target);
const reshade::api::resource_view descriptor_data = reshade::opengl::make_resource_view_handle(target, texture);
reshade::invoke_addon_event<reshade::addon_event::push_descriptors>(
g_opengl_context,
reshade::api::shader_stage::all,
// See global pipeline layout specified in 'wgl_device::wgl_device'
get_opengl_pipeline_layout(), 3,
reshade::api::descriptor_table_update { {}, unit, 0, 1, reshade::api::descriptor_type::unordered_access_view, &descriptor_data });
}
#endif
}
void APIENTRY glDrawArraysInstancedBaseInstance(GLenum mode, GLint first, GLsizei count, GLsizei primcount, GLuint baseinstance)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode);
if (reshade::invoke_addon_event<reshade::addon_event::draw>(g_opengl_context, primcount, count, first, baseinstance))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawArraysInstancedBaseInstance);
trampoline(mode, first, count, primcount, baseinstance);
}
void APIENTRY glDrawElementsInstancedBaseInstance(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount, GLuint baseinstance)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode, type);
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
const uint32_t offset = (index_buffer_binding != 0) ? static_cast<uint32_t>(reinterpret_cast<uintptr_t>(indices) / reshade::opengl::get_index_type_size(type)) : 0;
if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(g_opengl_context, primcount, count, offset, 0, baseinstance))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawElementsInstancedBaseInstance);
trampoline(mode, count, type, indices, primcount, baseinstance);
}
void APIENTRY glDrawElementsInstancedBaseVertexBaseInstance(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount, GLint basevertex, GLuint baseinstance)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
update_current_primitive_topology(mode, type);
GLint index_buffer_binding = 0;
gl.GetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &index_buffer_binding);
const uint32_t offset = (index_buffer_binding != 0) ? static_cast<uint32_t>(reinterpret_cast<uintptr_t>(indices) / reshade::opengl::get_index_type_size(type)) : 0;
if (reshade::invoke_addon_event<reshade::addon_event::draw_indexed>(g_opengl_context, primcount, count, offset, basevertex, baseinstance))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDrawElementsInstancedBaseVertexBaseInstance);
trampoline(mode, count, type, indices, primcount, basevertex, baseinstance);
}
#endif
#ifdef GL_VERSION_4_3
void APIENTRY glTextureView(GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers)
{
static const auto trampoline = reshade::hooks::call(glTextureView);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource_view resource_view(target, texture, origtexture, internalformat, minlevel, numlevels, minlayer, numlayers);
resource_view.invoke_create_event(&internalformat, &minlevel, &numlevels, &minlayer, &numlayers);
trampoline(texture, target, origtexture, internalformat, minlevel, numlevels, minlayer, numlayers);
resource_view.invoke_initialize_event();
}
else
#endif
trampoline(texture, target, origtexture, internalformat, minlevel, numlevels, minlayer, numlayers);
}
void APIENTRY glTexBufferRange(GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size)
{
static const auto trampoline = reshade::hooks::call(glTexBufferRange);
#if RESHADE_ADDON
if (size == -1)
{
if (gl.GetNamedBufferParameteri64v != nullptr)
{
#ifndef _WIN64
gl.GetNamedBufferParameteriv(buffer, GL_BUFFER_SIZE, reinterpret_cast<GLint *>(&size));
#else
gl.GetNamedBufferParameteri64v(buffer, GL_BUFFER_SIZE, &size);
#endif
}
else
{
GLint prev_binding = 0;
gl.GetIntegerv(GL_COPY_READ_BUFFER_BINDING, &prev_binding);
gl.BindBuffer(GL_COPY_READ_BUFFER, buffer);
#ifndef _WIN64
gl.GetBufferParameteriv(GL_COPY_READ_BUFFER, GL_BUFFER_SIZE, reinterpret_cast<GLint *>(&size));
#else
gl.GetBufferParameteri64v(GL_COPY_READ_BUFFER, GL_BUFFER_SIZE, &size);
#endif
gl.BindBuffer(GL_COPY_READ_BUFFER, prev_binding);
}
}
if (g_opengl_context)
{
init_resource_view resource_view(target, 0, buffer, internalformat, offset, size);
resource_view.invoke_create_event(&internalformat, &offset, &size);
trampoline(target, internalformat, buffer, offset, size);
resource_view.invoke_initialize_event();
}
else
#endif
trampoline(target, internalformat, buffer, offset, size);
}
void APIENTRY glTexStorage2DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)
{
static const auto trampoline = reshade::hooks::call(glTexStorage2DMultisample);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(target, 0, 1, samples, internalformat, width, height, 1);
resource.invoke_create_event(nullptr, &samples, &internalformat, &width, &height, nullptr);
trampoline(target, samples, internalformat, width, height, fixedsamplelocations);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, samples, internalformat, width, height, fixedsamplelocations);
}
void APIENTRY glTexStorage3DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations)
{
static const auto trampoline = reshade::hooks::call(glTexStorage3DMultisample);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(target, 0, 1, samples, internalformat, width, height, depth);
resource.invoke_create_event(nullptr, &samples, &internalformat, &width, &height, &depth);
trampoline(target, samples, internalformat, width, height, depth, fixedsamplelocations);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, samples, internalformat, width, height, depth, fixedsamplelocations);
}
void APIENTRY glCopyImageSubData(GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth)
{
#if RESHADE_ADDON >= 2
if (copy_texture_region(srcTarget, srcName, srcLevel, srcX, srcY, srcZ, dstTarget, dstName, dstLevel, dstX, dstY, dstZ, srcWidth, srcHeight, srcDepth))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCopyImageSubData);
trampoline(srcName, srcTarget, srcLevel, srcX, srcY, srcZ, dstName, dstTarget, dstLevel, dstX, dstY, dstZ, srcWidth, srcHeight, srcDepth);
}
void APIENTRY glBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride)
{
static const auto trampoline = reshade::hooks::call(glBindVertexBuffer);
trampoline(bindingindex, buffer, offset, stride);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_vertex_buffers>())
{
g_opengl_context->_current_vbo_dirty = false;
const reshade::api::resource buffer_handle = reshade::opengl::make_resource_handle(GL_BUFFER, buffer);
uint64_t offset_64 = offset;
uint32_t stride_32 = stride;
reshade::invoke_addon_event<reshade::addon_event::bind_vertex_buffers>(g_opengl_context, bindingindex, 1, &buffer_handle, &offset_64, &stride_32);
}
#endif
}
void APIENTRY glDispatchCompute(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
if (reshade::invoke_addon_event<reshade::addon_event::dispatch>(g_opengl_context, num_groups_x, num_groups_y, num_groups_z))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glDispatchCompute);
trampoline(num_groups_x, num_groups_y, num_groups_z);
}
void APIENTRY glDispatchComputeIndirect(GLintptr indirect)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
GLint indirect_buffer_binding = 0;
gl.GetIntegerv(GL_DISPATCH_INDIRECT_BUFFER_BINDING, &indirect_buffer_binding);
if (0 != indirect_buffer_binding)
{
if (reshade::invoke_addon_event<reshade::addon_event::draw_or_dispatch_indirect>(
g_opengl_context,
reshade::api::indirect_command::dispatch,
reshade::opengl::make_resource_handle(GL_DISPATCH_INDIRECT_BUFFER, indirect_buffer_binding),
indirect,
1,
0))
return;
}
else
{
assert(false);
}
}
#endif
static const auto trampoline = reshade::hooks::call(glDispatchComputeIndirect);
trampoline(indirect);
}
void APIENTRY glMultiDrawArraysIndirect(GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
GLint indirect_buffer_binding = 0;
gl.GetIntegerv(GL_DRAW_INDIRECT_BUFFER_BINDING, &indirect_buffer_binding);
if (0 != indirect_buffer_binding)
{
update_current_primitive_topology(mode);
if (reshade::invoke_addon_event<reshade::addon_event::draw_or_dispatch_indirect>(
g_opengl_context,
reshade::api::indirect_command::draw,
reshade::opengl::make_resource_handle(GL_BUFFER, indirect_buffer_binding),
reinterpret_cast<uintptr_t>(indirect),
drawcount,
stride))
return;
}
else
{
// Redirect to non-indirect draw calls so proper events are invoked
for (GLsizei i = 0; i < drawcount; ++i)
{
const auto cmd = reinterpret_cast<const DrawArraysIndirectCommand *>(static_cast<const uint8_t *>(indirect) + i * (stride != 0 ? stride : sizeof(DrawArraysIndirectCommand)));
glDrawArraysInstancedBaseInstance(mode, cmd->first, cmd->count, cmd->primcount, cmd->baseinstance);
}
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glMultiDrawArraysIndirect);
trampoline(mode, indirect, drawcount, stride);
}
void APIENTRY glMultiDrawElementsIndirect(GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
GLint indirect_buffer_binding = 0;
gl.GetIntegerv(GL_DRAW_INDIRECT_BUFFER_BINDING, &indirect_buffer_binding);
if (0 != indirect_buffer_binding)
{
update_current_primitive_topology(mode, type);
if (reshade::invoke_addon_event<reshade::addon_event::draw_or_dispatch_indirect>(
g_opengl_context,
reshade::api::indirect_command::draw_indexed,
reshade::opengl::make_resource_handle(GL_BUFFER, indirect_buffer_binding),
reinterpret_cast<uintptr_t>(indirect),
drawcount,
stride))
return;
}
else
{
// Redirect to non-indirect draw calls so proper events are invoked
for (GLsizei i = 0; i < drawcount; ++i)
{
const auto cmd = reinterpret_cast<const DrawElementsIndirectCommand *>(static_cast<const uint8_t *>(indirect) + i * (stride != 0 ? stride : sizeof(DrawElementsIndirectCommand)));
glDrawElementsInstancedBaseVertexBaseInstance(
mode,
cmd->count,
type,
reinterpret_cast<const GLvoid *>(static_cast<uintptr_t>(static_cast<size_t>(cmd->firstindex) * reshade::opengl::get_index_type_size(type))),
cmd->primcount,
cmd->basevertex,
cmd->baseinstance);
}
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glMultiDrawElementsIndirect);
trampoline(mode, type, indirect, drawcount, stride);
}
#endif
#ifdef GL_VERSION_4_4
void APIENTRY glBufferStorage(GLenum target, GLsizeiptr size, const void *data, GLbitfield flags)
{
static const auto trampoline = reshade::hooks::call(glBufferStorage);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(target, 0, size, flags);
resource.invoke_create_event(&size, &flags, data);
trampoline(target, size, data, flags);
resource.invoke_initialize_event();
}
else
#endif
trampoline(target, size, data, flags);
}
void APIENTRY glBindBuffersBase(GLenum target, GLuint first, GLsizei count, const GLuint *buffers)
{
static const auto trampoline = reshade::hooks::call(glBindBuffersBase);
trampoline(target, first, count, buffers);
#if RESHADE_ADDON >= 2
if (g_opengl_context)
{
if ((target == GL_UNIFORM_BUFFER || target == GL_SHADER_STORAGE_BUFFER) && reshade::has_addon_event<reshade::addon_event::push_descriptors>())
{
temp_mem<reshade::api::buffer_range> descriptor_data(count);
if (buffers != nullptr)
{
for (GLsizei i = 0; i < count; ++i)
{
descriptor_data[i].buffer = reshade::opengl::make_resource_handle(GL_BUFFER, buffers[i]);
descriptor_data[i].offset = 0;
descriptor_data[i].size = UINT64_MAX;
}
}
else
{
std::memset(descriptor_data.p, 0, count * sizeof(reshade::api::buffer_range));
}
const auto type = (target == GL_UNIFORM_BUFFER) ? reshade::api::descriptor_type::constant_buffer : reshade::api::descriptor_type::shader_storage_buffer;
const auto layout_param = (target == GL_UNIFORM_BUFFER) ? 2 : 1;
reshade::invoke_addon_event<reshade::addon_event::push_descriptors>(
g_opengl_context,
reshade::api::shader_stage::all,
// See global pipeline layout specified in 'wgl_device::wgl_device'
get_opengl_pipeline_layout(), layout_param,
reshade::api::descriptor_table_update { {}, first, 0, static_cast<uint32_t>(count), type, descriptor_data.p });
}
else if ((target == GL_TRANSFORM_FEEDBACK_BUFFER) && reshade::has_addon_event<reshade::addon_event::bind_stream_output_buffers>())
{
temp_mem<reshade::api::resource> buffer_handles(count);
temp_mem<uint64_t> offsets_64(count);
temp_mem<uint64_t> max_sizes_64(count);
if (buffers != nullptr)
{
for (GLsizei i = 0; i < count; ++i)
{
buffer_handles[i] = reshade::opengl::make_resource_handle(GL_BUFFER, buffers[i]);
offsets_64[i] = 0;
max_sizes_64[i] = UINT64_MAX;
}
}
else
{
std::memset(buffer_handles.p, 0, count * sizeof(reshade::api::resource));
std::memset(offsets_64.p, 0, count * sizeof(reshade::api::resource));
std::memset(max_sizes_64.p, 0, count * sizeof(reshade::api::resource));
}
reshade::invoke_addon_event<reshade::addon_event::bind_stream_output_buffers>(g_opengl_context, first, count, buffer_handles.p, offsets_64.p, max_sizes_64.p, nullptr, nullptr);
}
}
#endif
}
void APIENTRY glBindBuffersRange(GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLintptr *sizes)
{
static const auto trampoline = reshade::hooks::call(glBindBuffersRange);
trampoline(target, first, count, buffers, offsets, sizes);
#if RESHADE_ADDON >= 2
if (g_opengl_context)
{
if ((target == GL_UNIFORM_BUFFER || target == GL_SHADER_STORAGE_BUFFER) && reshade::has_addon_event<reshade::addon_event::push_descriptors>())
{
temp_mem<reshade::api::buffer_range> descriptor_data(count);
if (buffers != nullptr)
{
assert(offsets != nullptr && sizes != nullptr);
for (GLsizei i = 0; i < count; ++i)
{
descriptor_data[i].buffer = reshade::opengl::make_resource_handle(GL_BUFFER, buffers[i]);
descriptor_data[i].offset = static_cast<uint64_t>(offsets[i]);
descriptor_data[i].size = static_cast<uint64_t>(sizes[i]);
}
}
else
{
std::memset(descriptor_data.p, 0, count * sizeof(reshade::api::buffer_range));
}
const auto type = (target == GL_UNIFORM_BUFFER) ? reshade::api::descriptor_type::constant_buffer : reshade::api::descriptor_type::shader_storage_buffer;
const auto layout_param = (target == GL_UNIFORM_BUFFER) ? 2 : 1;
reshade::invoke_addon_event<reshade::addon_event::push_descriptors>(
g_opengl_context,
reshade::api::shader_stage::all,
// See global pipeline layout specified in 'wgl_device::wgl_device'
get_opengl_pipeline_layout(), layout_param,
reshade::api::descriptor_table_update { {}, first, 0, static_cast<uint32_t>(count), type, descriptor_data.p });
}
else if ((target == GL_TRANSFORM_FEEDBACK_BUFFER) && reshade::has_addon_event<reshade::addon_event::bind_stream_output_buffers>())
{
temp_mem<reshade::api::resource> buffer_handles(count);
temp_mem<uint64_t> offsets_64(count);
temp_mem<uint64_t> max_sizes_64(count);
if (buffers != nullptr)
{
for (GLsizei i = 0; i < count; ++i)
{
buffer_handles[i] = reshade::opengl::make_resource_handle(GL_BUFFER, buffers[i]);
offsets_64[i] = static_cast<uint64_t>(offsets[i]);
max_sizes_64[i] = static_cast<uint64_t>(sizes[i]);
}
}
else
{
std::memset(buffer_handles.p, 0, count * sizeof(reshade::api::resource));
std::memset(offsets_64.p, 0, count * sizeof(reshade::api::resource));
std::memset(max_sizes_64.p, 0, count * sizeof(reshade::api::resource));
}
reshade::invoke_addon_event<reshade::addon_event::bind_stream_output_buffers>(g_opengl_context, first, count, buffer_handles.p, offsets_64.p, max_sizes_64.p, nullptr, nullptr);
}
}
#endif
}
void APIENTRY glBindTextures(GLuint first, GLsizei count, const GLuint *textures)
{
static const auto trampoline = reshade::hooks::call(glBindTextures);
trampoline(first, count, textures);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::push_descriptors>())
{
temp_mem<reshade::api::sampler_with_resource_view> descriptor_data(count);
if (textures != nullptr)
{
for (GLsizei i = 0; i < count; ++i)
{
GLint target = GL_TEXTURE;
if (gl.GetTextureParameteriv != nullptr)
gl.GetTextureParameteriv(textures[i], GL_TEXTURE_TARGET, &target);
descriptor_data[i].view = reshade::opengl::make_resource_view_handle(target, textures[i]);
descriptor_data[i].sampler = { 0 };
}
}
else
{
std::memset(descriptor_data.p, 0, count * sizeof(reshade::api::sampler_with_resource_view));
}
reshade::invoke_addon_event<reshade::addon_event::push_descriptors>(
g_opengl_context,
reshade::api::shader_stage::all,
// See global pipeline layout specified in 'wgl_device::wgl_device'
get_opengl_pipeline_layout(), 0,
reshade::api::descriptor_table_update { {}, first, 0, static_cast<uint32_t>(count), reshade::api::descriptor_type::sampler_with_resource_view, descriptor_data.p });
}
#endif
}
void APIENTRY glBindImageTextures(GLuint first, GLsizei count, const GLuint *textures)
{
static const auto trampoline = reshade::hooks::call(glBindImageTextures);
trampoline(first, count, textures);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::push_descriptors>())
{
temp_mem<reshade::api::resource_view> descriptor_data(count);
if (textures != nullptr)
{
for (GLsizei i = 0; i < count; ++i)
{
GLint target = GL_TEXTURE;
if (gl.GetTextureParameteriv != nullptr)
gl.GetTextureParameteriv(textures[i], GL_TEXTURE_TARGET, &target);
descriptor_data[i] = reshade::opengl::make_resource_view_handle(target, textures[i]);
}
}
else
{
std::memset(descriptor_data.p, 0, count * sizeof(reshade::api::resource_view));
}
reshade::invoke_addon_event<reshade::addon_event::push_descriptors>(
g_opengl_context,
reshade::api::shader_stage::all,
// See global pipeline layout specified in 'wgl_device::wgl_device'
get_opengl_pipeline_layout(), 3,
reshade::api::descriptor_table_update { {}, first, 0, static_cast<uint32_t>(count), reshade::api::descriptor_type::unordered_access_view, descriptor_data.p });
}
#endif
}
void APIENTRY glBindVertexBuffers(GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides)
{
static const auto trampoline = reshade::hooks::call(glBindVertexBuffers);
trampoline(first, count, buffers, offsets, strides);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::bind_vertex_buffers>())
{
g_opengl_context->_current_vbo_dirty = false;
temp_mem<reshade::api::resource> buffer_handles(count);
temp_mem<uint64_t> offsets_64(count);
if (buffers != nullptr)
{
assert(offsets != nullptr && strides != nullptr);
for (GLsizei i = 0; i < count; ++i)
{
buffer_handles[i] = reshade::opengl::make_resource_handle(GL_BUFFER, buffers[i]);
offsets_64[i] = offsets[i];
}
}
else
{
std::memset(buffer_handles.p, 0, count * sizeof(reshade::api::resource));
std::memset(offsets_64.p, 0, count * sizeof(uint64_t));
}
reshade::invoke_addon_event<reshade::addon_event::bind_vertex_buffers>(
g_opengl_context, first, count, buffer_handles.p, offsets_64.p, reinterpret_cast<const uint32_t *>(strides));
}
#endif
}
#endif
#ifdef GL_VERSION_4_5
void APIENTRY glTextureBuffer(GLuint texture, GLenum internalformat, GLuint buffer)
{
#if RESHADE_ADDON
glTextureBufferRange(texture, internalformat, buffer, 0, -1);
#else
static const auto trampoline = reshade::hooks::call(glTextureBuffer);
trampoline(texture, internalformat, buffer);
#endif
}
void APIENTRY glTextureBufferRange(GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size)
{
static const auto trampoline = reshade::hooks::call(glTextureBufferRange);
#if RESHADE_ADDON
if (size == -1)
{
#ifndef _WIN64
assert(gl.GetNamedBufferParameteriv != nullptr);
gl.GetNamedBufferParameteriv(buffer, GL_BUFFER_SIZE, reinterpret_cast<GLint *>(&size));
#else
assert(gl.GetNamedBufferParameteri64v != nullptr);
gl.GetNamedBufferParameteri64v(buffer, GL_BUFFER_SIZE, &size);
#endif
}
if (g_opengl_context)
{
init_resource_view resource_view(GL_TEXTURE_BUFFER, texture, buffer, internalformat, offset, size);
resource_view.invoke_create_event(&internalformat, &offset, &size);
trampoline(texture, internalformat, buffer, offset, size);
resource_view.invoke_initialize_event();
}
else
#endif
trampoline(texture, internalformat, buffer, offset, size);
}
void APIENTRY glNamedBufferData(GLuint buffer, GLsizeiptr size, const void *data, GLenum usage)
{
static const auto trampoline = reshade::hooks::call(glNamedBufferData);
#if RESHADE_ADDON
if (g_opengl_context)
{
GLbitfield storage_flags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_DYNAMIC_STORAGE_BIT;
init_resource resource(GL_BUFFER, buffer, size, storage_flags);
resource.invoke_create_event(&size, &storage_flags, data);
trampoline(buffer, size, data, usage);
resource.invoke_initialize_event();
}
else
#endif
trampoline(buffer, size, data, usage);
}
void APIENTRY glNamedBufferStorage(GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags)
{
static const auto trampoline = reshade::hooks::call(glNamedBufferStorage);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(GL_BUFFER, buffer, size, flags);
resource.invoke_create_event(&size, &flags, data);
trampoline(buffer, size, data, flags);
resource.invoke_initialize_event();
}
else
#endif
trampoline(buffer, size, data, flags);
}
void APIENTRY glTextureStorage1D(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width)
{
static const auto trampoline = reshade::hooks::call(glTextureStorage1D);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(GL_TEXTURE_1D, texture, levels, 1, internalformat, width, 1, 1);
resource.invoke_create_event(&levels, nullptr, &internalformat, &width, nullptr, nullptr);
trampoline(texture, levels, internalformat, width);
resource.invoke_initialize_event();
}
else
#endif
trampoline(texture, levels, internalformat, width);
}
void APIENTRY glTextureStorage2D(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
{
static const auto trampoline = reshade::hooks::call(glTextureStorage2D);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(GL_TEXTURE_2D, texture, levels, 1, internalformat, width, height, 1);
resource.invoke_create_event(&levels, nullptr, &internalformat, &width, &height, nullptr);
trampoline(texture, levels, internalformat, width, height);
resource.invoke_initialize_event();
}
else
#endif
trampoline(texture, levels, internalformat, width, height);
}
void APIENTRY glTextureStorage2DMultisample(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)
{
static const auto trampoline = reshade::hooks::call(glTextureStorage2DMultisample);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(GL_TEXTURE_2D, texture, 1, samples, internalformat, width, height, 1);
resource.invoke_create_event(nullptr, &samples, &internalformat, &width, &height, nullptr);
trampoline(texture, samples, internalformat, width, height, fixedsamplelocations);
resource.invoke_initialize_event();
}
else
#endif
trampoline(texture, samples, internalformat, width, height, fixedsamplelocations);
}
void APIENTRY glTextureStorage3D(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth)
{
static const auto trampoline = reshade::hooks::call(glTextureStorage3D);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(GL_TEXTURE_3D, texture, levels, 1, internalformat, width, height, depth);
resource.invoke_create_event(&levels, nullptr, &internalformat, &width, &height, &depth);
trampoline(texture, levels, internalformat, width, height, depth);
resource.invoke_initialize_event();
}
else
#endif
trampoline(texture, levels, internalformat, width, height, depth);
}
void APIENTRY glTextureStorage3DMultisample(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations)
{
static const auto trampoline = reshade::hooks::call(glTextureStorage3DMultisample);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(GL_TEXTURE_3D, texture, 1, samples, internalformat, width, height, depth);
resource.invoke_create_event(nullptr, &samples, &internalformat, &width, &height, &depth);
trampoline(texture, samples, internalformat, width, height, depth, fixedsamplelocations);
resource.invoke_initialize_event();
}
else
#endif
trampoline(texture, samples, internalformat, width, height, depth, fixedsamplelocations);
}
void APIENTRY glNamedBufferSubData(GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data)
{
#if RESHADE_ADDON >= 2
if (update_buffer_region(GL_BUFFER, buffer, offset, size, data))
return;
#endif
static const auto trampoline = reshade::hooks::call(glNamedBufferSubData);
trampoline(buffer, offset, size, data);
}
void APIENTRY glTextureSubImage1D(GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid* pixels)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(GL_TEXTURE, texture, level, xoffset, 0, 0, width, 1, 1, format, type, pixels))
return;
#endif
static const auto trampoline = reshade::hooks::call(glTextureSubImage1D);
trampoline(texture, level, xoffset, width, format, type, pixels);
}
void APIENTRY glTextureSubImage2D(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(GL_TEXTURE, texture, level, xoffset, yoffset, 0, width, height, 1, format, type, pixels))
return;
#endif
static const auto trampoline = reshade::hooks::call(glTextureSubImage2D);
trampoline(texture, level, xoffset, yoffset, width, height, format, type, pixels);
}
void APIENTRY glTextureSubImage3D(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* pixels)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(GL_TEXTURE, texture, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels))
return;
#endif
static const auto trampoline = reshade::hooks::call(glTextureSubImage3D);
trampoline(texture, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
}
void APIENTRY glCompressedTextureSubImage1D(GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(GL_TEXTURE, texture, level, xoffset, 0, 0, width, 1, 1, format, GL_UNSIGNED_BYTE, data))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCompressedTextureSubImage1D);
trampoline(texture, level, xoffset, width, format, imageSize, data);
}
void APIENTRY glCompressedTextureSubImage2D(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(GL_TEXTURE, texture, level, xoffset, yoffset, 0, width, height, 1, format, GL_UNSIGNED_BYTE, data))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCompressedTextureSubImage2D);
trampoline(texture, level, xoffset, yoffset, width, height, format, imageSize, data);
}
void APIENTRY glCompressedTextureSubImage3D(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data)
{
#if RESHADE_ADDON >= 2
if (update_texture_region(GL_TEXTURE, texture, level, xoffset, yoffset, zoffset, width, height, depth, format, GL_UNSIGNED_BYTE, data))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCompressedTextureSubImage3D);
trampoline(texture, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
}
void APIENTRY glCopyTextureSubImage1D(GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width)
{
#if RESHADE_ADDON >= 2
if (copy_texture_region(GL_FRAMEBUFFER_DEFAULT, 0, 0, x, y, 0, GL_TEXTURE, texture, level, xoffset, 0, 0, width, 1, 1))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCopyTextureSubImage1D);
trampoline(texture, level, xoffset, x, y, width);
}
void APIENTRY glCopyTextureSubImage2D(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
{
#if RESHADE_ADDON >= 2
if (copy_texture_region(GL_FRAMEBUFFER_DEFAULT, 0, 0, x, y, 0, GL_TEXTURE, texture, level, xoffset, yoffset, 0, width, height, 1))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCopyTextureSubImage2D);
trampoline(texture, level, xoffset, yoffset, x, y, width, height);
}
void APIENTRY glCopyTextureSubImage3D(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
{
#if RESHADE_ADDON >= 2
if (copy_texture_region(GL_FRAMEBUFFER_DEFAULT, 0, 0, x, y, 0, GL_TEXTURE, texture, level, xoffset, yoffset, zoffset, width, height, 1))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCopyTextureSubImage3D);
trampoline(texture, level, xoffset, yoffset, zoffset, x, y, width, height);
}
auto APIENTRY glMapNamedBuffer(GLuint buffer, GLenum access) -> void *
{
static const auto trampoline = reshade::hooks::call(glMapNamedBuffer);
void *result = trampoline(buffer, access);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::map_buffer_region>())
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
reshade::invoke_addon_event<reshade::addon_event::map_buffer_region>(
device,
reshade::opengl::make_resource_handle(GL_BUFFER, buffer),
0,
UINT64_MAX,
reshade::opengl::convert_access_flags(access),
&result);
}
#endif
return result;
}
auto APIENTRY glMapNamedBufferRange(GLuint buffer, GLintptr offset, GLsizeiptr length, GLenum access) -> void *
{
static const auto trampoline = reshade::hooks::call(glMapNamedBufferRange);
void *result = trampoline(buffer, offset, length, access);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::map_buffer_region>())
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
reshade::invoke_addon_event<reshade::addon_event::map_buffer_region>(
device,
reshade::opengl::make_resource_handle(GL_BUFFER, buffer),
offset,
length,
reshade::opengl::convert_access_flags(access),
&result);
}
#endif
return result;
}
void APIENTRY glUnmapNamedBuffer(GLuint buffer)
{
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::unmap_buffer_region>())
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
reshade::invoke_addon_event<reshade::addon_event::unmap_buffer_region>(
device,
reshade::opengl::make_resource_handle(GL_BUFFER, buffer));
}
#endif
static const auto trampoline = reshade::hooks::call(glUnmapNamedBuffer);
trampoline(buffer);
}
void APIENTRY glCopyNamedBufferSubData(GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size)
{
#if RESHADE_ADDON >= 2
if (copy_buffer_region(GL_BUFFER, readBuffer, readOffset, GL_BUFFER, writeBuffer, writeOffset, size))
return;
#endif
static const auto trampoline = reshade::hooks::call(glCopyNamedBufferSubData);
trampoline(readBuffer, writeBuffer, readOffset, writeOffset, size);
}
void APIENTRY glNamedRenderbufferStorage(GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height)
{
static const auto trampoline = reshade::hooks::call(glNamedRenderbufferStorage);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(GL_RENDERBUFFER, renderbuffer, 1, 1, internalformat, width, height, 1);
resource.invoke_create_event(nullptr, nullptr, &internalformat, &width, &height, nullptr);
trampoline(renderbuffer, internalformat, width, height);
resource.invoke_initialize_event();
}
else
#endif
trampoline(renderbuffer, internalformat, width, height);
}
void APIENTRY glNamedRenderbufferStorageMultisample(GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
{
static const auto trampoline = reshade::hooks::call(glNamedRenderbufferStorageMultisample);
#if RESHADE_ADDON
if (g_opengl_context)
{
init_resource resource(GL_RENDERBUFFER, renderbuffer, 1, samples, internalformat, width, height, 1);
resource.invoke_create_event(nullptr, &samples, &internalformat, &width, &height, nullptr);
trampoline(renderbuffer, samples, internalformat, width, height);
resource.invoke_initialize_event();
}
else
#endif
trampoline(renderbuffer, samples, internalformat, width, height);
}
void APIENTRY glClearNamedFramebufferiv(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value)
{
#if RESHADE_ADDON
if (g_opengl_context && (
reshade::has_addon_event<reshade::addon_event::clear_depth_stencil_view>() ||
reshade::has_addon_event<reshade::addon_event::clear_render_target_view>()))
{
assert(buffer == GL_COLOR || (buffer == GL_STENCIL && drawbuffer == 0));
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
const reshade::api::resource_view view = device->get_framebuffer_attachment(framebuffer, buffer, drawbuffer);
if (view != 0)
{
if (buffer != GL_COLOR ?
reshade::invoke_addon_event<reshade::addon_event::clear_depth_stencil_view>(g_opengl_context, view, nullptr, reinterpret_cast<const uint8_t *>(value), 0, nullptr) :
reshade::invoke_addon_event<reshade::addon_event::clear_render_target_view>(g_opengl_context, view, reinterpret_cast<const float *>(value), 0, nullptr))
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glClearNamedFramebufferiv);
trampoline(framebuffer, buffer, drawbuffer, value);
}
void APIENTRY glClearNamedFramebufferuiv(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value)
{
#if RESHADE_ADDON
if (g_opengl_context && (
reshade::has_addon_event<reshade::addon_event::clear_depth_stencil_view>() ||
reshade::has_addon_event<reshade::addon_event::clear_render_target_view>()))
{
assert(buffer == GL_COLOR || (buffer == GL_STENCIL && drawbuffer == 0));
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
const reshade::api::resource_view view = device->get_framebuffer_attachment(framebuffer, buffer, drawbuffer);
if (view != 0)
{
if (buffer != GL_COLOR ?
reshade::invoke_addon_event<reshade::addon_event::clear_depth_stencil_view>(g_opengl_context, view, nullptr, reinterpret_cast<const uint8_t *>(value), 0, nullptr) :
reshade::invoke_addon_event<reshade::addon_event::clear_render_target_view>(g_opengl_context, view, reinterpret_cast<const float *>(value), 0, nullptr))
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glClearNamedFramebufferuiv);
trampoline(framebuffer, buffer, drawbuffer, value);
}
void APIENTRY glClearNamedFramebufferfv(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value)
{
#if RESHADE_ADDON
if (g_opengl_context && (
reshade::has_addon_event<reshade::addon_event::clear_depth_stencil_view>() ||
reshade::has_addon_event<reshade::addon_event::clear_render_target_view>()))
{
assert(buffer == GL_COLOR || (buffer == GL_DEPTH && drawbuffer == 0));
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
const reshade::api::resource_view view = device->get_framebuffer_attachment(framebuffer, buffer, drawbuffer);
if (view != 0)
{
if (buffer != GL_COLOR ?
reshade::invoke_addon_event<reshade::addon_event::clear_depth_stencil_view>(g_opengl_context, view, value, nullptr, 0, nullptr) :
reshade::invoke_addon_event<reshade::addon_event::clear_render_target_view>(g_opengl_context, view, value, 0, nullptr))
return;
}
}
#endif
static const auto trampoline = reshade::hooks::call(glClearNamedFramebufferfv);
trampoline(framebuffer, buffer, drawbuffer, value);
}
void APIENTRY glClearNamedFramebufferfi(GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)
{
#if RESHADE_ADDON
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::clear_depth_stencil_view>())
{
assert(buffer == GL_DEPTH_STENCIL && drawbuffer == 0);
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
const reshade::api::resource_view dsv = device->get_framebuffer_attachment(framebuffer, buffer, drawbuffer);
if (dsv != 0 &&
reshade::invoke_addon_event<reshade::addon_event::clear_depth_stencil_view>(g_opengl_context, dsv, &depth, reinterpret_cast<const uint8_t *>(&stencil), 0, nullptr))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glClearNamedFramebufferfi);
trampoline(framebuffer, buffer, drawbuffer, depth, stencil);
}
void APIENTRY glBlitNamedFramebuffer(GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)
{
#if RESHADE_ADDON >= 2
if (g_opengl_context && (
reshade::has_addon_event<reshade::addon_event::copy_texture_region>() ||
reshade::has_addon_event<reshade::addon_event::resolve_texture_region>()))
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
constexpr GLbitfield flags[3] = { GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT };
for (GLbitfield flag : flags)
{
if ((mask & flag) != flag)
continue;
reshade::api::resource src = device->get_resource_from_view(device->get_framebuffer_attachment(readFramebuffer, flag, 0));
reshade::api::resource dst = device->get_resource_from_view(device->get_framebuffer_attachment(drawFramebuffer, flag, 0));
if (device->get_resource_desc(src).texture.samples <= 1)
{
const reshade::api::subresource_box src_box = { srcX0, srcY0, 0, srcX1, srcY1, 1 }, dst_box = { dstX0, dstY0, 0, dstX1, dstY1, 1 };
if (reshade::invoke_addon_event<reshade::addon_event::copy_texture_region>(g_opengl_context, src, 0, &src_box, dst, 0, &dst_box, (filter == GL_NONE || filter == GL_NEAREST) ? reshade::api::filter_mode::min_mag_mip_point : reshade::api::filter_mode::min_mag_mip_linear))
mask ^= flag;
}
else
{
assert((srcX1 - srcX0) == (dstX1 - dstX0) && (srcY1 - srcY0) == (dstY1 - dstY0));
const reshade::api::subresource_box src_box = { srcX0, srcY0, 0, srcX1, srcY1, 1 };
if (reshade::invoke_addon_event<reshade::addon_event::resolve_texture_region>(g_opengl_context, src, 0, &src_box, dst, 0, dstX0, dstY0, 0, reshade::api::format::unknown))
mask ^= flag;
}
}
if (mask == 0)
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glBlitNamedFramebuffer);
trampoline(readFramebuffer, drawFramebuffer, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
}
void APIENTRY glGenerateTextureMipmap(GLuint texture)
{
#if RESHADE_ADDON >= 2
if (g_opengl_context)
{
GLint target = GL_TEXTURE;
gl.GetTextureParameteriv(texture, GL_TEXTURE_TARGET, &target);
if (reshade::invoke_addon_event<reshade::addon_event::generate_mipmaps>(g_opengl_context, reshade::opengl::make_resource_view_handle(target, texture)))
return;
}
#endif
static const auto trampoline = reshade::hooks::call(glGenerateTextureMipmap);
trampoline(texture);
}
void APIENTRY glBindTextureUnit(GLuint unit, GLuint texture)
{
static const auto trampoline = reshade::hooks::call(glBindTextureUnit);
trampoline(unit, texture);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::push_descriptors>())
{
GLint target = GL_TEXTURE;
gl.GetTextureParameteriv(texture, GL_TEXTURE_TARGET, &target);
reshade::api::sampler_with_resource_view descriptor_data = {
reshade::api::sampler { 0 },
reshade::opengl::make_resource_view_handle(target, texture)
};
reshade::invoke_addon_event<reshade::addon_event::push_descriptors>(
g_opengl_context,
reshade::api::shader_stage::all,
// See global pipeline layout specified in 'wgl_device::wgl_device'
get_opengl_pipeline_layout(), 0,
reshade::api::descriptor_table_update { {}, unit, 0, 1, reshade::api::descriptor_type::sampler_with_resource_view, &descriptor_data });
}
#endif
}
#endif
void APIENTRY glBindProgramARB(GLenum target, GLuint program)
{
static const auto trampoline = reshade::hooks::call(glBindProgramARB);
trampoline(target, program);
#if RESHADE_ADDON >= 2
if (g_opengl_context)
{
reshade::api::pipeline_stage stage;
switch (target)
{
case 0x8620 /* GL_VERTEX_PROGRAM_ARB */:
stage = reshade::api::pipeline_stage::vertex_shader;
break;
case 0x8804 /* GL_FRAGMENT_PROGRAM_ARB */:
stage = reshade::api::pipeline_stage::pixel_shader;
break;
default:
assert(false);
return;
}
const auto pipeline = (program != 0) ? reshade::api::pipeline { (static_cast<uint64_t>(GL_PROGRAM) << 40) | program } : reshade::api::pipeline {};
reshade::invoke_addon_event<reshade::addon_event::bind_pipeline>(g_opengl_context, stage, pipeline);
}
#endif
}
void APIENTRY glProgramStringARB(GLenum target, GLenum format, GLsizei length, const GLvoid *string)
{
static const auto trampoline = reshade::hooks::call(glProgramStringARB);
#if RESHADE_ADDON
if (g_opengl_context)
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
reshade::api::pipeline_subobject_type subobject_type;
switch (target)
{
case 0x8620 /* GL_VERTEX_PROGRAM_ARB */:
subobject_type = reshade::api::pipeline_subobject_type::vertex_shader;
break;
case 0x8804 /* GL_FRAGMENT_PROGRAM_ARB */:
subobject_type = reshade::api::pipeline_subobject_type::pixel_shader;
break;
default:
assert(false);
subobject_type = reshade::api::pipeline_subobject_type::unknown;
break;
}
reshade::api::shader_desc desc = {};
desc.code = string;
desc.code_size = length;
desc.entry_point = nullptr;
const reshade::api::pipeline_subobject subobject = { subobject_type, 1, &desc };
if (reshade::invoke_addon_event<reshade::addon_event::create_pipeline>(device, get_opengl_pipeline_layout(), 1, &subobject))
{
assert(desc.code_size <= static_cast<size_t>(std::numeric_limits<GLsizei>::max()));
string = desc.code;
length = static_cast<GLsizei>(desc.code_size);
}
trampoline(target, format, length, string);
GLuint program = 0;
const auto glGetProgramivARB = reinterpret_cast<void(APIENTRY *)(GLenum target, GLenum pname, GLint *params)>(wglGetProcAddress("glGetProgramivARB"));
assert(glGetProgramivARB != nullptr);
glGetProgramivARB(target, 0x8677 /* GL_PROGRAM_BINDING_ARB */, reinterpret_cast<GLint *>(&program));
// Only invoke 'init_pipeline' event for programs that were successfully loaded
GLint status = -1;
gl.GetIntegerv(0x864B /* GL_PROGRAM_ERROR_POSITION_ARB */, &status);
if (program != 0 && status < 0)
{
reshade::invoke_addon_event<reshade::addon_event::init_pipeline>(device, get_opengl_pipeline_layout(), 1, &subobject, reshade::api::pipeline { (static_cast<uint64_t>(GL_PROGRAM) << 40) | program });
}
}
else
#endif
trampoline(target, format, length, string);
}
void APIENTRY glDeleteProgramsARB(GLsizei n, const GLuint *programs)
{
#if RESHADE_ADDON
if (g_opengl_context)
{
const auto device = static_cast<reshade::opengl::device_impl *>(g_opengl_context->get_device());
for (GLsizei i = 0; i < n; ++i)
if (programs[i] != 0)
reshade::invoke_addon_event<reshade::addon_event::destroy_pipeline>(device, reshade::api::pipeline { (static_cast<uint64_t>(GL_PROGRAM) << 40) | programs[i] });
}
#endif
static const auto trampoline = reshade::hooks::call(glDeleteProgramsARB);
trampoline(n, programs);
}
void APIENTRY glBindFramebufferEXT(GLenum target, GLuint framebuffer)
{
static const auto trampoline = reshade::hooks::call(glBindFramebufferEXT);
trampoline(target, framebuffer);
#if RESHADE_ADDON
update_framebuffer_object(target, framebuffer);
#endif
}
void APIENTRY glBindMultiTextureEXT(GLenum texunit, GLenum target, GLuint texture)
{
static const auto trampoline = reshade::hooks::call(glBindMultiTextureEXT);
trampoline(texunit, target, texture);
#if RESHADE_ADDON >= 2
if (g_opengl_context &&
reshade::has_addon_event<reshade::addon_event::push_descriptors>())
{
assert(texunit >= GL_TEXTURE0);
texunit -= GL_TEXTURE0;
reshade::api::sampler_with_resource_view descriptor_data = {
reshade::api::sampler { 0 },
reshade::opengl::make_resource_view_handle(target, texture)
};
reshade::invoke_addon_event<reshade::addon_event::push_descriptors>(
g_opengl_context,
reshade::api::shader_stage::all,
// See global pipeline layout specified in 'wgl_device::wgl_device'
get_opengl_pipeline_layout(), 0,
reshade::api::descriptor_table_update { {}, texunit, 0, 1, reshade::api::descriptor_type::sampler_with_resource_view, &descriptor_data });
}
#endif
}
```
|
```javascript
/* your_sha256_hash--------------
*
* # D3.js - histogram chart
*
* Demo d3.js histogram chart setup with tooltip and random data
*
* Version: 1.0
* Latest update: August 1, 2015
*
* your_sha256_hash------------ */
$(function () {
// Initialize chart
stackedMultiples('#d3-histogram', 400);
// Chart setup
function stackedMultiples(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 15, right: 20, bottom: 20, left: 60},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Generate a Bates distribution of 10 random variables.
var values = d3.range(1000).map(d3.random.bates(4));
// Data format
var formatCount = d3.format(",.0f");
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.domain([0, 1])
.range([0, width]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(20))
(values);
// Vertical
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([height, 0]);
// Colors
var color = d3.scale.ordinal().range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Add tooltip
// ------------------------------
// Create tooltip
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-25, 0])
.html(function(d) {
return "Current value: " + "<span class='text-semibold'>" + formatCount(d.y) + "</span>";
})
// Initialize tooltip
svg.call(tip);
//
// Append chart elements
//
// Add bars
// ------------------------------
// Group each bar
var bar = svg.selectAll(".d3-bar")
.data(data)
.enter()
.append("g")
.attr("class", "d3-bar")
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; })
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
// Append bars
bar.append("rect")
.attr("x", 1)
.attr("width", x(data[0].dx) - 3)
.attr("height", function(d) { return height - y(d.y); })
.style("fill", function(d) { return color(d); });
// Append text
bar.append("text")
.attr("dy", ".75em")
.attr("y", -15)
.attr("x", x(data[0].dx) / 2)
.style("text-anchor", "middle")
.style("fill", "#333")
.text(function(d) { return formatCount(d.y); });
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Bar group
svg.selectAll('.d3-bar').attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
// Bar rect
svg.selectAll('.d3-bar rect').attr("x", 1).attr("width", x(data[0].dx) - 3);
// Bar text
svg.selectAll('.d3-bar text').attr("x", x(data[0].dx) / 2);
}
}
});
```
|
```yaml
Resources:
NotSupportedPullTrigger:
Type: AWS::Serverless::Function
Properties:
CodeUri: s3://sam-demo-bucket/filtered_events.zip
Handler: index.handler
Runtime: nodejs16.x
Events:
DDBEvent:
Type: DynamoDB
Properties:
Stream: arn:aws:dynamodb:us-east-1:012345678901:table/TestTable/stream/2015-05-11T21:21:33.291
StartingPosition: TRIM_HORIZON
ConsumerGroupId: consumergroup1
NotSupportedPushTrigger:
Type: AWS::Serverless::Function
Properties:
CodeUri: s3://sam-demo-bucket/filtered_events.zip
Handler: index.handler
Runtime: nodejs16.x
Events:
SNSEvent:
Type: SNS
Properties:
Topic: arn:aws:sns:us-east-1:123456789012:my_topic
ConsumerGroupId: consumergroup1
```
|
```java
Floating garbage and how to deal with it
Metadata: creating a user-defined file attribute
Locks in `static synchronized` methods
There is no such thing as *pass-by-reference* in Java
Avoid using `static` variables
```
|
Operating system Wi-Fi support is the support in the operating system for Wi-Fi and usually consists of two pieces: driver level support, and configuration and management support.
Driver support is usually provided by multiple manufacturers of the chip set hardware or end manufacturers. Also available are Unix clones such as Linux, sometimes through open source projects.
Configuration and management support consists of software to enumerate, join, and check the status of available Wi-Fi networks. This also includes support for various encryption methods. These systems are often provided by the operating system backed by a standard driver model. In most cases, drivers emulate an Ethernet device and use the configuration and management utilities built into the operating system. In cases where built-in configuration and management support is non-existent or inadequate, hardware manufacturers may include their own software to handle the respective tasks.
Microsoft Windows
Microsoft Windows has comprehensive driver-level support for Wi-Fi, the quality of which depends on the hardware manufacturer. Hardware manufacturers almost always ship Windows drivers with their products. Windows ships with very few Wi-Fi drivers and depends on the original equipment manufacturers (OEMs) and device manufacturers to make sure users get drivers. Configuration and management depend on the version of Windows.
Earlier versions of Windows, such as 98, ME and 2000 do not have built-in configuration and management support and must depend on software provided by the manufacturer
Microsoft Windows XP has built-in configuration and management support. The original shipping version of Windows XP included rudimentary support which was dramatically improved in Service Pack 2. Support for WPA2 and some other security protocols require updates from Microsoft. Many hardware manufacturers include their own software and require the user to disable Windows’ built-in Wi-Fi support.
Windows Vista, Windows 7, Windows 8, and Windows 10 have improved Wi-Fi support over Windows XP with a better interface and a suggestion to connect to a public Wi-Fi when no other connection is available.
macOS and Classic Mac OS
Apple was an early adopter of Wi-Fi, introducing its AirPort product line, based on the 802.11b standard, in July 1999. Apple later introduced AirPort Extreme, an implementation of 802.11g. All Apple computers, starting with the original iBook in 1999, either included AirPort 802.11 networking or were designed specifically to provide 802.11 networking with only the addition of the internal AirPort Card (or, later, an AirPort Extreme Card), connecting to the computer's built-in antennae. All Intel-based Macs either come with built-in AirPort Extreme or a slot for an AirPort card, and all portable Macs (all MacBooks and the earlier iBooks and PowerBooks) have included Wi-Fi for several years. In late 2006, Apple began shipping Macs with Broadcom Wi-Fi chips that also supported the Draft 802.11n standard, but this capability was disabled and Apple did not claim or advertise the hardware's capability until some time later when the draft had progressed further. At the January 2007 Macworld Expo, Apple announced that their computers would begin shipping with Draft 802.11n support. Systems shipped with this hidden capability can easily be unlocked through software, but due to the accounting requirements of Sarbanes-Oxley, Apple cannot freely add features to already-sold hardware and so must nominally sell an upgrade. This "upgrade" is included in the price of an AirPort Extreme Base Station for all computers owned by the purchaser, and Apple sells the "upgrade" separately (as the "AirPort Extreme 802.11n Enabler for Mac") for about US$2 in the United States and at similar prices elsewhere.
Apple produces the operating system, the computer hardware, the accompanying drivers, AirPort Wi-Fi base stations, and configuration and management software, simplifying Wi-Fi integration, set-up, and maintenance (including security updates). The built-in configuration and management is integrated throughout many of the operating system's applications and utilities. Mac OS X has Wi-Fi support, including WPA2, and ships with drivers for all of Apple's current and past AirPort Extreme and AirPort cards. Many third-party manufacturers make compatible hardware along with the appropriate drivers which work with Mac OS X's built-in configuration and management software. Other manufacturers distribute their own software.
Apple's older Mac OS 9 supported AirPort and AirPort Extreme as well, and drivers exist for other equipment from other manufacturers, providing Wi-Fi options for earlier systems not designed for AirPort cards. Versions of Mac OS before Mac OS 9 predate Wi-Fi and do not have any Wi-Fi support, although some third-party hardware manufacturers have made drivers and connection software that allows earlier OSes to use Wi-Fi.
Open-source Unix-like systems
Linux, FreeBSD and similar Unix-like clones have much coarser support for Wi-Fi. Due to the open source nature of these operating systems,
many different standards have been developed for configuring and managing Wi-Fi devices. The open source nature also fosters open source drivers which have enabled many third party and proprietary devices to work under these operating systems. See Comparison of Open Source Wireless Drivers for more information on those drivers.
Linux has patchy Wi-Fi support. This is especially true for older kernel versions, such as the 2.6 series, which is still widely used by enterprise distributions. Native drivers for many Wi-Fi chipsets are available either commercially or at no cost, although some manufacturers don't produce a Linux driver, only a Windows one. Consequently, many popular chipsets either don't have a native Linux driver at all, or only have a half-finished one. For these, the freely available NdisWrapper and its commercial competitor DriverLoader allow Windows x86 and 64 bit variants NDIS drivers to be used on x86-based Linux systems and 86_64 architectures as of January 6, 2005. As well as the lack of native drivers, some Linux distributions do not offer a convenient user interface and configuring Wi-Fi on them can be a clumsy and complicated operation compared to configuring wired Ethernet drivers. This is changing with the adoption of utilities such as NetworkManager and wicd that allow users to automatically switch between networks, without root access or command-line invocation of the traditional wireless tools. But some distributions include a large number of preinstalled drivers, like Ubuntu.
FreeBSD has Wi-Fi support similar to Linux. FreeBSD 7.0 introduced full support for WPA and WPA2, although in some cases this is driver dependent. FreeBSD comes with drivers for many wireless cards and chipsets, including those made by Atheros, Intel Centrino, Ralink, Cisco, D-link, and Netgear, and provides support for others through the ports collection. FreeBSD also has "Project Evil", which provides the ability to use Windows x86 NDIS drivers on x86-based FreeBSD systems as NdisWrapper does on Linux, and Windows amd64 NDIS drivers on amd64-based systems.
NetBSD, OpenBSD, and DragonFly BSD have Wi-Fi support similar to FreeBSD. Code for some of the drivers, as well as the kernel framework to support them, is mostly shared among the 4 BSDs.
Haiku has preliminary Wi-Fi support since September 2009.
Solaris and OpenSolaris have the Wireless Networking Project to provide Wi-Fi drivers and support.
Android has built in support for WiFi, with it being preferred over Mobile telephony networks.
Unison OS has built in support for embedded WiFi for a broad set of modules, with it being preferred over Mobile telephony networks (which also have off the shelf support). Mixed WiFi and Bluetooth for embedded systems is also provided.
See also
List of WLAN channels
Wireless access point
References
External links
Wi-Fi Alliance
IEEE 802.11
Computer networking
Wi-Fi
|
```php
<?php
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
*/
namespace Google\Service\Contactcenterinsights;
class your_sha256_hashscriptObjectConfig extends \Google\Model
{
/**
* @var string
*/
public $medium;
/**
* @param string
*/
public function setMedium($medium)
{
$this->medium = $medium;
}
/**
* @return string
*/
public function getMedium()
{
return $this->medium;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(your_sha256_hashscriptObjectConfig::class, your_sha256_hashightsV1IngestConversationsRequestTranscriptObjectConfig');
```
|
Apistogramma trifasciata, also known as three-striped dwarf cichlid is a species of fish from the ‘Arroyo Chagalalina’ in Paraguay extending towards the rio Guaporé drainage in the southern Amazon basin though the connected rio Paraguay watershed in Brazil and Paraguay and on as far as the middle Paraná basin in Argentina.
References
trifasciata
Fish of Paraguay
Fish described in 1903
Fish of Brazil
Fish of Argentina
|
Pierre-Christophe Baguet (born 11 May 1955) is a French politician, mayor of Boulogne-Billancourt and member of the National Assembly of France between 1997 and 2012. He represents the Hauts-de-Seine department, and is a member of The Republicans.
References
External links
Official website
1955 births
Living people
Politicians from Paris
Social Democratic Party (France) politicians
Union for French Democracy politicians
Union for a Popular Movement politicians
The Republicans (France) politicians
Deputies of the 11th National Assembly of the French Fifth Republic
Deputies of the 12th National Assembly of the French Fifth Republic
Deputies of the 13th National Assembly of the French Fifth Republic
Members of Parliament for Hauts-de-Seine
French general councillors
Departmental councillors (France)
Mayors of Boulogne-Billancourt
Knights of the Ordre national du Mérite
|
```css
/*
* jQuery UI CSS Framework 1.8.16
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* path_to_url
*
* path_to_url
*/
/* Layout helpers
----------------------------------*/
.ui-helper-hidden { display: none; }
.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); }
.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
.ui-helper-clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
.ui-helper-clearfix { display: inline-block; }
/* required comment for clearfix to work in Opera \*/
* html .ui-helper-clearfix { height:1%; }
.ui-helper-clearfix { display:block; }
/* end clearfix */
.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
/* Interaction Cues
----------------------------------*/
.ui-state-disabled { cursor: default !important; }
/* Icons
----------------------------------*/
/* states and images */
.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
/* Misc visuals
----------------------------------*/
/* Overlays */
.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
/*
* jQuery UI CSS Framework 1.8.16
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* path_to_url
*
* path_to_url
*
* To view and modify this theme, visit path_to_url
*/
/* Component containers
----------------------------------*/
.ui-widget { font-family: Verdana,Arial,sans-serif; font-size: 1.1em; }
.ui-widget .ui-widget { font-size: 1em; }
.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Verdana,Arial,sans-serif; font-size: 1em; }
.ui-widget-content { border: 1px solid #aaaaaa; background: #ffffff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x; color: #222222; }
.ui-widget-content a { color: #222222; }
.ui-widget-header { border: 1px solid #aaaaaa; background: #cccccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x; color: #222222; font-weight: bold; }
.ui-widget-header a { color: #222222; }
/* Interaction states
----------------------------------*/
.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #d3d3d3; background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #555555; }
.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555; text-decoration: none; }
.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #999999; background: #dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #212121; }
.ui-state-hover a, .ui-state-hover a:hover { color: #212121; text-decoration: none; }
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #aaaaaa; background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #212121; }
.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #212121; text-decoration: none; }
.ui-widget :active { outline: none; }
/* Interaction Cues
----------------------------------*/
.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #fcefa1; background: #fbf9ee url(images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x; color: #363636; }
.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; }
.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x; color: #cd0a0a; }
.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #cd0a0a; }
.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #cd0a0a; }
.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; }
.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
/* Icons
----------------------------------*/
/* states and images */
.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_222222_256x240.png); }
.ui-widget-content .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); }
.ui-widget-header .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); }
.ui-state-default .ui-icon { background-image: url(images/ui-icons_888888_256x240.png); }
.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_454545_256x240.png); }
.ui-state-active .ui-icon {background-image: url(images/ui-icons_454545_256x240.png); }
.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_2e83ff_256x240.png); }
.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_cd0a0a_256x240.png); }
/* positioning */
.ui-icon-carat-1-n { background-position: 0 0; }
.ui-icon-carat-1-ne { background-position: -16px 0; }
.ui-icon-carat-1-e { background-position: -32px 0; }
.ui-icon-carat-1-se { background-position: -48px 0; }
.ui-icon-carat-1-s { background-position: -64px 0; }
.ui-icon-carat-1-sw { background-position: -80px 0; }
.ui-icon-carat-1-w { background-position: -96px 0; }
.ui-icon-carat-1-nw { background-position: -112px 0; }
.ui-icon-carat-2-n-s { background-position: -128px 0; }
.ui-icon-carat-2-e-w { background-position: -144px 0; }
.ui-icon-triangle-1-n { background-position: 0 -16px; }
.ui-icon-triangle-1-ne { background-position: -16px -16px; }
.ui-icon-triangle-1-e { background-position: -32px -16px; }
.ui-icon-triangle-1-se { background-position: -48px -16px; }
.ui-icon-triangle-1-s { background-position: -64px -16px; }
.ui-icon-triangle-1-sw { background-position: -80px -16px; }
.ui-icon-triangle-1-w { background-position: -96px -16px; }
.ui-icon-triangle-1-nw { background-position: -112px -16px; }
.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
.ui-icon-arrow-1-n { background-position: 0 -32px; }
.ui-icon-arrow-1-ne { background-position: -16px -32px; }
.ui-icon-arrow-1-e { background-position: -32px -32px; }
.ui-icon-arrow-1-se { background-position: -48px -32px; }
.ui-icon-arrow-1-s { background-position: -64px -32px; }
.ui-icon-arrow-1-sw { background-position: -80px -32px; }
.ui-icon-arrow-1-w { background-position: -96px -32px; }
.ui-icon-arrow-1-nw { background-position: -112px -32px; }
.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
.ui-icon-arrow-4 { background-position: 0 -80px; }
.ui-icon-arrow-4-diag { background-position: -16px -80px; }
.ui-icon-extlink { background-position: -32px -80px; }
.ui-icon-newwin { background-position: -48px -80px; }
.ui-icon-refresh { background-position: -64px -80px; }
.ui-icon-shuffle { background-position: -80px -80px; }
.ui-icon-transfer-e-w { background-position: -96px -80px; }
.ui-icon-transferthick-e-w { background-position: -112px -80px; }
.ui-icon-folder-collapsed { background-position: 0 -96px; }
.ui-icon-folder-open { background-position: -16px -96px; }
.ui-icon-document { background-position: -32px -96px; }
.ui-icon-document-b { background-position: -48px -96px; }
.ui-icon-note { background-position: -64px -96px; }
.ui-icon-mail-closed { background-position: -80px -96px; }
.ui-icon-mail-open { background-position: -96px -96px; }
.ui-icon-suitcase { background-position: -112px -96px; }
.ui-icon-comment { background-position: -128px -96px; }
.ui-icon-person { background-position: -144px -96px; }
.ui-icon-print { background-position: -160px -96px; }
.ui-icon-trash { background-position: -176px -96px; }
.ui-icon-locked { background-position: -192px -96px; }
.ui-icon-unlocked { background-position: -208px -96px; }
.ui-icon-bookmark { background-position: -224px -96px; }
.ui-icon-tag { background-position: -240px -96px; }
.ui-icon-home { background-position: 0 -112px; }
.ui-icon-flag { background-position: -16px -112px; }
.ui-icon-calendar { background-position: -32px -112px; }
.ui-icon-cart { background-position: -48px -112px; }
.ui-icon-pencil { background-position: -64px -112px; }
.ui-icon-clock { background-position: -80px -112px; }
.ui-icon-disk { background-position: -96px -112px; }
.ui-icon-calculator { background-position: -112px -112px; }
.ui-icon-zoomin { background-position: -128px -112px; }
.ui-icon-zoomout { background-position: -144px -112px; }
.ui-icon-search { background-position: -160px -112px; }
.ui-icon-wrench { background-position: -176px -112px; }
.ui-icon-gear { background-position: -192px -112px; }
.ui-icon-heart { background-position: -208px -112px; }
.ui-icon-star { background-position: -224px -112px; }
.ui-icon-link { background-position: -240px -112px; }
.ui-icon-cancel { background-position: 0 -128px; }
.ui-icon-plus { background-position: -16px -128px; }
.ui-icon-plusthick { background-position: -32px -128px; }
.ui-icon-minus { background-position: -48px -128px; }
.ui-icon-minusthick { background-position: -64px -128px; }
.ui-icon-close { background-position: -80px -128px; }
.ui-icon-closethick { background-position: -96px -128px; }
.ui-icon-key { background-position: -112px -128px; }
.ui-icon-lightbulb { background-position: -128px -128px; }
.ui-icon-scissors { background-position: -144px -128px; }
.ui-icon-clipboard { background-position: -160px -128px; }
.ui-icon-copy { background-position: -176px -128px; }
.ui-icon-contact { background-position: -192px -128px; }
.ui-icon-image { background-position: -208px -128px; }
.ui-icon-video { background-position: -224px -128px; }
.ui-icon-script { background-position: -240px -128px; }
.ui-icon-alert { background-position: 0 -144px; }
.ui-icon-info { background-position: -16px -144px; }
.ui-icon-notice { background-position: -32px -144px; }
.ui-icon-help { background-position: -48px -144px; }
.ui-icon-check { background-position: -64px -144px; }
.ui-icon-bullet { background-position: -80px -144px; }
.ui-icon-radio-off { background-position: -96px -144px; }
.ui-icon-radio-on { background-position: -112px -144px; }
.ui-icon-pin-w { background-position: -128px -144px; }
.ui-icon-pin-s { background-position: -144px -144px; }
.ui-icon-play { background-position: 0 -160px; }
.ui-icon-pause { background-position: -16px -160px; }
.ui-icon-seek-next { background-position: -32px -160px; }
.ui-icon-seek-prev { background-position: -48px -160px; }
.ui-icon-seek-end { background-position: -64px -160px; }
.ui-icon-seek-start { background-position: -80px -160px; }
/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */
.ui-icon-seek-first { background-position: -80px -160px; }
.ui-icon-stop { background-position: -96px -160px; }
.ui-icon-eject { background-position: -112px -160px; }
.ui-icon-volume-off { background-position: -128px -160px; }
.ui-icon-volume-on { background-position: -144px -160px; }
.ui-icon-power { background-position: 0 -176px; }
.ui-icon-signal-diag { background-position: -16px -176px; }
.ui-icon-signal { background-position: -32px -176px; }
.ui-icon-battery-0 { background-position: -48px -176px; }
.ui-icon-battery-1 { background-position: -64px -176px; }
.ui-icon-battery-2 { background-position: -80px -176px; }
.ui-icon-battery-3 { background-position: -96px -176px; }
.ui-icon-circle-plus { background-position: 0 -192px; }
.ui-icon-circle-minus { background-position: -16px -192px; }
.ui-icon-circle-close { background-position: -32px -192px; }
.ui-icon-circle-triangle-e { background-position: -48px -192px; }
.ui-icon-circle-triangle-s { background-position: -64px -192px; }
.ui-icon-circle-triangle-w { background-position: -80px -192px; }
.ui-icon-circle-triangle-n { background-position: -96px -192px; }
.ui-icon-circle-arrow-e { background-position: -112px -192px; }
.ui-icon-circle-arrow-s { background-position: -128px -192px; }
.ui-icon-circle-arrow-w { background-position: -144px -192px; }
.ui-icon-circle-arrow-n { background-position: -160px -192px; }
.ui-icon-circle-zoomin { background-position: -176px -192px; }
.ui-icon-circle-zoomout { background-position: -192px -192px; }
.ui-icon-circle-check { background-position: -208px -192px; }
.ui-icon-circlesmall-plus { background-position: 0 -208px; }
.ui-icon-circlesmall-minus { background-position: -16px -208px; }
.ui-icon-circlesmall-close { background-position: -32px -208px; }
.ui-icon-squaresmall-plus { background-position: -48px -208px; }
.ui-icon-squaresmall-minus { background-position: -64px -208px; }
.ui-icon-squaresmall-close { background-position: -80px -208px; }
.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
/* Misc visuals
----------------------------------*/
/* Corner radius */
.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -khtml-border-top-left-radius: 4px; border-top-left-radius: 4px; }
.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -khtml-border-top-right-radius: 4px; border-top-right-radius: 4px; }
.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -khtml-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; }
.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; -khtml-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; }
/* Overlays */
.ui-widget-overlay { background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); }
.ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -khtml-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; }/*
* jQuery UI Resizable 1.8.16
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* path_to_url
*
* path_to_url#theming
*/
.ui-resizable { position: relative;}
.ui-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block; }
.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; }
.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; }
.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; }
.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; }
.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; }
.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; }
.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; }
.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; }
.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}/*
* jQuery UI Selectable 1.8.16
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* path_to_url
*
* path_to_url#theming
*/
.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; }
/*
* jQuery UI Slider 1.8.16
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* path_to_url
*
* path_to_url#theming
*/
.ui-slider { position: relative; text-align: left; }
.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; }
.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
.ui-slider-horizontal { height: .8em; }
.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; }
.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; }
.ui-slider-horizontal .ui-slider-range-min { left: 0; }
.ui-slider-horizontal .ui-slider-range-max { right: 0; }
.ui-slider-vertical { width: .8em; height: 100px; }
.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; }
.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; }
.ui-slider-vertical .ui-slider-range-min { bottom: 0; }
.ui-slider-vertical .ui-slider-range-max { top: 0; }/*
* jQuery UI Datepicker 1.8.16
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* path_to_url
*
* path_to_url#theming
*/
.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; }
.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; }
.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; }
.ui-datepicker .ui-datepicker-prev { left:2px; }
.ui-datepicker .ui-datepicker-next { right:2px; }
.ui-datepicker .ui-datepicker-prev-hover { left:1px; }
.ui-datepicker .ui-datepicker-next-hover { right:1px; }
.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; }
.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; }
.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
.ui-datepicker select.ui-datepicker-month,
.ui-datepicker select.ui-datepicker-year { width: 49%;}
.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; }
.ui-datepicker td { border: 0; padding: 1px; }
.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; }
/* with multiple calendars */
.ui-datepicker.ui-datepicker-multi { width:auto; }
.ui-datepicker-multi .ui-datepicker-group { float:left; }
.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; }
.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; }
/* RTL support */
.ui-datepicker-rtl { direction: rtl; }
.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; }
.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; }
.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; }
.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; }
.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; }
.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; }
.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; }
.ui-datepicker-rtl .ui-datepicker-group { float:right; }
.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */
.ui-datepicker-cover {
display: none; /*sorry for IE5*/
display/**/: block; /*sorry for IE5*/
position: absolute; /*must have*/
z-index: -1; /*must have*/
filter: mask(); /*must have*/
top: -4px; /*must have*/
left: -4px; /*must have*/
width: 200px; /*must have*/
height: 200px; /*must have*/
}
```
|
```java
/*
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing,
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* specific language governing permissions and limitations
*/
package org.apache.weex.ui.component;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import org.apache.weex.WXSDKInstance;
import org.apache.weex.WXSDKManager;
import org.apache.weex.annotation.JSMethod;
import org.apache.weex.bridge.WXBridgeManager;
import org.apache.weex.common.Constants;
import org.apache.weex.common.WXThread;
import org.apache.weex.dom.CSSConstants;
import org.apache.weex.dom.WXStyle;
import org.apache.weex.layout.ContentBoxMeasurement;
import org.apache.weex.layout.MeasureMode;
import org.apache.weex.ui.action.BasicComponentData;
import org.apache.weex.ui.component.helper.SoftKeyboardDetector;
import org.apache.weex.ui.component.helper.WXTimeInputHelper;
import org.apache.weex.ui.view.WXEditText;
import org.apache.weex.utils.TypefaceUtil;
import org.apache.weex.utils.WXLogUtils;
import org.apache.weex.utils.WXResourceUtils;
import org.apache.weex.utils.WXUtils;
import org.apache.weex.utils.WXViewUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import static org.apache.weex.dom.WXStyle.UNSET;
/**
* Created by sospartan on 7/11/16.
*/
public abstract class AbstractEditComponent extends WXComponent<WXEditText> {
private final InputMethodManager mInputMethodManager;
private String mBeforeText = "";
private boolean mAutoFocus;
private String mType = "text";
private String mMax = null;
private String mMin = null;
private String mLastValue = "";
private int mEditorAction = EditorInfo.IME_ACTION_DONE;
private String mReturnKeyType = null;
private List<TextView.OnEditorActionListener> mEditorActionListeners;
private boolean mListeningKeyboard = false;
private SoftKeyboardDetector.Unregister mUnregister;
private boolean mIgnoreNextOnInputEvent = false;
private boolean mKeepSelectionIndex = false;
private TextFormatter mFormatter = null;
private List<TextWatcher> mTextChangedListeners;
private TextWatcher mTextChangedEventDispatcher;
private int mFormatRepeatCount = 0;
private static final int MAX_TEXT_FORMAT_REPEAT = 3;
private TextPaint mPaint = new TextPaint();
private int mLineHeight = UNSET;
public AbstractEditComponent(WXSDKInstance instance, WXVContainer parent, boolean isLazy, BasicComponentData basicComponentData) {
super(instance, parent, isLazy, basicComponentData);
mInputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
setContentBoxMeasurement(new ContentBoxMeasurement() {
/** uiThread = false **/
@Override
public void measureInternal(float width, float height, int widthMeasureMode, int heightMeasureMode) {
if (CSSConstants.isUndefined(width) || widthMeasureMode == MeasureMode.UNSPECIFIED) {
width = 0;
}
mMeasureWidth = width;
mMeasureHeight = getMeasureHeight();
}
/** uiThread = false **/
@Override
public void layoutBefore() {
updateStyleAndAttrs();
}
/** uiThread = false **/
@Override
public void layoutAfter(float computedWidth, float computedHeight) {
}
});
}
@Override
protected void layoutDirectionDidChanged(boolean isRTL) {
String alignStr = (String) getStyles().get(Constants.Name.TEXT_ALIGN);
int textAlign = getTextAlign(alignStr);
if (textAlign <= 0) {
textAlign = Gravity.START;
}
if (getHostView() instanceof WXEditText) {
getHostView().setGravity(textAlign | getVerticalGravity());
}
}
protected final float getMeasuredLineHeight() {
return mLineHeight != UNSET && mLineHeight > 0 ? mLineHeight : mPaint.getFontMetrics(null);
}
protected float getMeasureHeight() {
return getMeasuredLineHeight();
}
protected void updateStyleAndAttrs() {
if (getStyles().size() > 0) {
int fontSize = UNSET, fontStyle = UNSET, fontWeight = UNSET;
String fontFamily = null;
if (getStyles().containsKey(Constants.Name.FONT_SIZE)) {
fontSize = WXStyle.getFontSize(getStyles(),getViewPortWidth());
}
if (getStyles().containsKey(Constants.Name.FONT_FAMILY)) {
fontFamily = WXStyle.getFontFamily(getStyles());
}
if (getStyles().containsKey(Constants.Name.FONT_STYLE)) {
fontStyle = WXStyle.getFontStyle(getStyles());
}
if (getStyles().containsKey(Constants.Name.FONT_WEIGHT)) {
fontWeight = WXStyle.getFontWeight(getStyles());
}
int lineHeight = WXStyle.getLineHeight(getStyles(),getViewPortWidth());
if (lineHeight != UNSET)
mLineHeight = lineHeight;
if (fontSize != UNSET)
mPaint.setTextSize(fontSize);
if (fontFamily != null) {
TypefaceUtil.applyFontStyle(mPaint, fontStyle, fontWeight, fontFamily);
}
}
}
@Override
protected WXEditText initComponentHostView(@NonNull Context context) {
final WXEditText inputView = new WXEditText(context);
appleStyleAfterCreated(inputView);
return inputView;
}
@Override
protected void onHostViewInitialized(WXEditText host) {
super.onHostViewInitialized(host);
addFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(boolean hasFocus) {
if (!hasFocus) {
decideSoftKeyboard();
}
setPseudoClassStatus(Constants.PSEUDO.FOCUS,hasFocus);
}
});
addKeyboardListener(host);
}
@Override
protected boolean isConsumeTouch() {
//EditText always consume touch event except disabled.
return !isDisabled();
}
private OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onHostViewClick() {
switch (mType) {
case Constants.Value.DATE:
hideSoftKeyboard();
if (getParent() != null) {
getParent().interceptFocus();
}
WXTimeInputHelper.pickDate(mMax, mMin, AbstractEditComponent.this);
break;
case Constants.Value.TIME:
hideSoftKeyboard();
if (getParent() != null) {
getParent().interceptFocus();
}
WXTimeInputHelper.pickTime(AbstractEditComponent.this);
break;
}
}
};
private void applyOnClickListener() {
addClickListener(mOnClickListener);
}
protected int getVerticalGravity(){
return Gravity.CENTER_VERTICAL;
}
/**
* Process view after created.
*
* @param editText
*/
protected void appleStyleAfterCreated(final WXEditText editText) {
String alignStr = (String) getStyles().get(Constants.Name.TEXT_ALIGN);
int textAlign = getTextAlign(alignStr);
if (textAlign <= 0) {
textAlign = Gravity.START;
}
editText.setGravity(textAlign | getVerticalGravity());
final int colorInt = WXResourceUtils.getColor("#999999");
if (colorInt != Integer.MIN_VALUE) {
editText.setHintTextColor(colorInt);
}
mTextChangedEventDispatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (mTextChangedListeners != null) {
for (TextWatcher watcher : mTextChangedListeners) {
watcher.beforeTextChanged(s, start, count, after);
}
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (mFormatter != null) {
String raw = mFormatter.recover(s.toString());
String result = mFormatter.format(raw);
// prevent infinite loop caused by bad format and recover regexp
if (!result.equals(s.toString()) && mFormatRepeatCount < MAX_TEXT_FORMAT_REPEAT) {
mFormatRepeatCount = mFormatRepeatCount + 1;
int index = editText.getSelectionStart();
int cursorIndex = mFormatter.format(mFormatter.recover(s.subSequence(0, index).toString())).length();
editText.setText(result);
editText.setSelection(cursorIndex);
return;
}
mFormatRepeatCount = 0;
}
if (mTextChangedListeners != null) {
for (TextWatcher watcher : mTextChangedListeners) {
watcher.onTextChanged(s, start, before, count);
}
}
}
@Override
public void afterTextChanged(Editable s) {
if (mTextChangedListeners != null) {
for (TextWatcher watcher : mTextChangedListeners) {
watcher.afterTextChanged(s);
}
}
}
};
editText.addTextChangedListener(mTextChangedEventDispatcher);
editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, WXStyle.getFontSize(getStyles(), getInstance().getInstanceViewPortWidth()));
}
@Override
public void addEvent(final String type) {
super.addEvent(type);
if (getHostView() == null || TextUtils.isEmpty(type)) {
return;
}
final TextView text = getHostView();
if (type.equals(Constants.Event.CHANGE)) {
addFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(boolean hasFocus) {
if (hasFocus) {
mLastValue = text.getText().toString();
} else {
CharSequence newValue = text.getText();
newValue = newValue == null ? "" : newValue;
if (!newValue.toString().equals(mLastValue)) {
fireEvent(Constants.Event.CHANGE, newValue.toString());
mLastValue = text.getText().toString();
}
}
}
});
addEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == mEditorAction) {
CharSequence newValue = text.getText();
newValue = newValue == null ? "" : newValue;
if (!newValue.toString().equals(mLastValue)) {
fireEvent(Constants.Event.CHANGE, newValue.toString());
mLastValue = text.getText().toString();
}
if (getParent() != null) {
getParent().interceptFocus();
}
hideSoftKeyboard();
return true;
}
return false;
}
});
} else if (type.equals(Constants.Event.INPUT)) {
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (mIgnoreNextOnInputEvent) {
mIgnoreNextOnInputEvent = false;
mBeforeText = s.toString();
return;
}
if (mBeforeText.equals(s.toString())) {
return;
}
mBeforeText = s.toString();
fireEvent(Constants.Event.INPUT, s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
if (Constants.Event.RETURN.equals(type)) {
addEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == mEditorAction) {
Map<String, Object> ret = new HashMap<>(2);
ret.put("returnKeyType", mReturnKeyType);
ret.put("value", v.getText().toString());
fireEvent(Constants.Event.RETURN, ret);
return true;
}
return false;
}
});
}
if (Constants.Event.KEYBOARD.equals(type)) {
mListeningKeyboard = true;
}
}
private void fireEvent(String event, String value) {
if (event != null) {
Map<String, Object> params = new HashMap<>(2);
params.put("value", value);
params.put("timeStamp", System.currentTimeMillis());
Map<String, Object> domChanges = new HashMap<>();
Map<String, Object> attrsChanges = new HashMap<>();
attrsChanges.put("value", value);
domChanges.put("attrs", attrsChanges);
WXSDKManager.getInstance().fireEvent(getInstanceId(), getRef(), event, params, domChanges);
}
}
public void performOnChange(String value) {
if (getEvents() != null) {
String event = getEvents().contains(Constants.Event.CHANGE) ? Constants.Event.CHANGE : null;
fireEvent(event, value);
}
}
@Override
protected boolean setProperty(String key, Object param) {
switch (key) {
case Constants.Name.DISABLED:
Boolean disabled = WXUtils.getBoolean(param, null);
if (disabled != null && mHost != null) {
if (disabled) {
mHost.setFocusable(false);
mHost.setFocusableInTouchMode(false);
} else {
mHost.setFocusableInTouchMode(true);
mHost.setFocusable(true);
}
}
return true;
case Constants.Name.PLACEHOLDER:
String placeholder = WXUtils.getString(param, null);
if (placeholder != null)
setPlaceholder(placeholder);
return true;
case Constants.Name.PLACEHOLDER_COLOR:
String placeholder_color = WXUtils.getString(param, null);
if (placeholder_color != null)
setPlaceholderColor(placeholder_color);
return true;
case Constants.Name.TYPE:
String input_type = WXUtils.getString(param, null);
if (input_type != null)
setType(input_type);
return true;
case Constants.Name.AUTOFOCUS:
Boolean result = WXUtils.getBoolean(param, null);
if (result != null)
setAutofocus(result);
return true;
case Constants.Name.COLOR:
String color = WXUtils.getString(param, null);
if (color != null)
setColor(color);
return true;
case Constants.Name.FONT_SIZE:
String fontsize = WXUtils.getString(param, null);
if (fontsize != null)
setFontSize(fontsize);
return true;
case Constants.Name.TEXT_ALIGN:
String text_align = WXUtils.getString(param, null);
if (text_align != null)
setTextAlign(text_align);
return true;
case Constants.Name.SINGLELINE:
Boolean singLineResult = WXUtils.getBoolean(param, null);
if (singLineResult != null)
setSingleLine(singLineResult);
return true;
case Constants.Name.LINES:
Integer lines = WXUtils.getInteger(param, null);
if (lines != null)
setLines(lines);
return true;
case Constants.Name.MAX_LENGTH:
Integer maxlength = WXUtils.getInteger(param, null);
if (maxlength != null)
setMaxLength(maxlength);
return true;
case Constants.Name.MAXLENGTH:
Integer maxLength = WXUtils.getInteger(param, null);
if (maxLength != null)
setMaxLength(maxLength);
return true;
case Constants.Name.MAX:
setMax(String.valueOf(param));
return true;
case Constants.Name.MIN:
setMin(String.valueOf(param));
return true;
case Constants.Name.RETURN_KEY_TYPE:
setReturnKeyType(String.valueOf(param));
return true;
case Constants.Name.KEEP_SELECTION_INDEX:
boolean keepIndex = WXUtils.getBoolean(param, false);
mKeepSelectionIndex = keepIndex;
return true;
case Constants.Name.ALLOW_COPY_PASTE:
boolean allowCopyPaste = WXUtils.getBoolean(param, true);
if (getHostView() != null) {
getHostView().setAllowCopyPaste(allowCopyPaste);
}
return true;
}
return super.setProperty(key, param);
}
@WXComponentProp(name = Constants.Name.RETURN_KEY_TYPE)
public void setReturnKeyType(String type) {
if (getHostView() == null) {
return;
}
mReturnKeyType = type;
switch (type) {
case ReturnTypes.DEFAULT:
mEditorAction = EditorInfo.IME_ACTION_UNSPECIFIED;
break;
case ReturnTypes.GO:
mEditorAction = EditorInfo.IME_ACTION_GO;
break;
case ReturnTypes.NEXT:
mEditorAction = EditorInfo.IME_ACTION_NEXT;
break;
case ReturnTypes.SEARCH:
mEditorAction = EditorInfo.IME_ACTION_SEARCH;
break;
case ReturnTypes.SEND:
mEditorAction = EditorInfo.IME_ACTION_SEND;
break;
case ReturnTypes.DONE:
mEditorAction = EditorInfo.IME_ACTION_DONE;
break;
default:
break;
}
//remove focus and hide keyboard first, the ImeOptions will take effect when show keyboard next time
blur();
getHostView().setImeOptions(mEditorAction);
}
@WXComponentProp(name = Constants.Name.PLACEHOLDER)
public void setPlaceholder(String placeholder) {
if (placeholder == null || getHostView() == null) {
return;
}
((WXEditText) getHostView()).setHint(placeholder);
}
@WXComponentProp(name = Constants.Name.PLACEHOLDER_COLOR)
public void setPlaceholderColor(String color) {
if (getHostView() != null && !TextUtils.isEmpty(color)) {
int colorInt = WXResourceUtils.getColor(color);
if (colorInt != Integer.MIN_VALUE) {
((WXEditText) getHostView()).setHintTextColor(colorInt);
}
}
}
@WXComponentProp(name = Constants.Name.TYPE)
public void setType(String type) {
Log.e("weex", "setType=" + type);
if (type == null || getHostView() == null) {
return;
}
mType = type;
((EditText) getHostView()).setRawInputType(getInputType(mType));
switch (mType) {
case Constants.Value.DATE:
case Constants.Value.TIME:
applyOnClickListener();
break;
}
}
@WXComponentProp(name = Constants.Name.AUTOFOCUS)
public void setAutofocus(boolean autofocus) {
if (getHostView() == null) {
return;
}
mAutoFocus = autofocus;
EditText inputView = getHostView();
if (mAutoFocus) {
inputView.setFocusable(true);
inputView.requestFocus();
inputView.setFocusableInTouchMode(true);
showSoftKeyboard();
} else {
hideSoftKeyboard();
}
}
@WXComponentProp(name = Constants.Name.VALUE)
public void setValue(String value) {
WXEditText view;
if ((view = getHostView()) == null) {
return;
}
if (TextUtils.equals(view.getText(), value)) {
return;
}
mIgnoreNextOnInputEvent = true;
int oldIndex = view.getSelectionStart();
view.setText(value);
int index = mKeepSelectionIndex ? oldIndex : value.length();
view.setSelection(value == null ? 0 : index);
}
@WXComponentProp(name = Constants.Name.COLOR)
public void setColor(String color) {
if (getHostView() != null && !TextUtils.isEmpty(color)) {
int colorInt = WXResourceUtils.getColor(color);
if (colorInt != Integer.MIN_VALUE) {
getHostView().setTextColor(colorInt);
}
}
}
@WXComponentProp(name = Constants.Name.FONT_SIZE)
public void setFontSize(String fontSize) {
if (getHostView() != null && fontSize != null ) {
Map<String, Object> map = new HashMap<>(1);
map.put(Constants.Name.FONT_SIZE, fontSize);
getHostView().setTextSize(TypedValue.COMPLEX_UNIT_PX, WXStyle.getFontSize(map, getInstance().getInstanceViewPortWidth()));
}
}
@WXComponentProp(name = Constants.Name.TEXT_ALIGN)
public void setTextAlign(String textAlign) {
int align = getTextAlign(textAlign);
if (align > 0) {
getHostView().setGravity(align | getVerticalGravity());
}
}
@WXComponentProp(name = Constants.Name.SINGLELINE)
public void setSingleLine(boolean singleLine) {
if (getHostView() == null) {
return;
}
getHostView().setSingleLine(singleLine);
}
@WXComponentProp(name = Constants.Name.LINES)
public void setLines(int lines) {
if (getHostView() == null) {
return;
}
getHostView().setLines(lines);
}
/**
* Compatible with both 'max-length' and 'maxlength'
* @param maxLength
*/
@WXComponentProp(name = Constants.Name.MAX_LENGTH)
public void setMaxLength(int maxLength) {
if (getHostView() == null) {
return;
}
getHostView().setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
}
/**
* Compatible with both 'max-length' and 'maxlength'
* @param maxLength
*/
@WXComponentProp(name = Constants.Name.MAXLENGTH)
@Deprecated
public void setMaxlength(int maxLength) {
setMaxLength(maxLength);
}
private int getInputType(String type) {
int inputType;
switch (type) {
case Constants.Value.TEXT:
inputType = InputType.TYPE_CLASS_TEXT;
break;
case Constants.Value.DATE:
inputType = InputType.TYPE_NULL;
getHostView().setFocusable(false);
break;
case Constants.Value.DATETIME:
inputType = InputType.TYPE_CLASS_DATETIME;
break;
case Constants.Value.EMAIL:
inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
case Constants.Value.PASSWORD:
inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
if(getHostView() != null){
getHostView().setTransformationMethod(PasswordTransformationMethod.getInstance());
}
break;
case Constants.Value.TEL:
inputType = InputType.TYPE_CLASS_PHONE;
break;
case Constants.Value.TIME:
inputType = InputType.TYPE_NULL;
if(getHostView() != null){
getHostView().setFocusable(false);
}
break;
case Constants.Value.URL:
inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
break;
case Constants.Value.NUMBER:
inputType = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL;
break;
default:
inputType = InputType.TYPE_CLASS_TEXT;
}
return inputType;
}
@WXComponentProp(name = Constants.Name.MAX)
public void setMax(String max) {
mMax = max;
}
@WXComponentProp(name = Constants.Name.MIN)
public void setMin(String min) {
mMin = min;
}
private boolean showSoftKeyboard() {
if (getHostView() == null) {
return false;
} else {
getHostView().postDelayed(WXThread.secure(new Runnable() {
@Override
public void run() {
if (getInstance() != null && getInstance().getApmForInstance() != null){
getInstance().getApmForInstance().forceStopRecordInteraction = true;
}
mInputMethodManager.showSoftInput(getHostView(), InputMethodManager.SHOW_IMPLICIT);
}
}), 100);
}
return true;
}
private void hideSoftKeyboard() {
if (getHostView() != null) {
getHostView().postDelayed(WXThread.secure(new Runnable() {
@Override
public void run() {
mInputMethodManager.hideSoftInputFromWindow(getHostView().getWindowToken(), 0);
}
}), 16);
}
}
private int getTextAlign(String textAlign) {
boolean isRTL = isLayoutRTL();
int align = isRTL ? Gravity.END : Gravity.START;
if (TextUtils.isEmpty(textAlign)) {
return align;
}
if (textAlign.equals(Constants.Value.LEFT)) {
align = Gravity.START;
} else if (textAlign.equals(Constants.Value.CENTER)) {
align = Gravity.CENTER;
} else if (textAlign.equals(Constants.Value.RIGHT)) {
align = Gravity.END;
}
return align;
}
@JSMethod
public void blur() {
WXEditText host = getHostView();
if (host != null && host.hasFocus()) {
if (getParent() != null) {
getParent().interceptFocus();
}
host.clearFocus();
hideSoftKeyboard();
}
}
@JSMethod
public void focus() {
WXEditText host = getHostView();
if (host != null && !host.hasFocus()) {
if (getParent() != null) {
getParent().ignoreFocus();
}
host.requestFocus();
host.setFocusable(true);
host.setFocusableInTouchMode(true);
showSoftKeyboard();
}
}
@Override
protected Object convertEmptyProperty(String propName, Object originalValue) {
switch (propName) {
case Constants.Name.FONT_SIZE:
return WXText.sDEFAULT_SIZE;
case Constants.Name.COLOR:
return "black";
}
return super.convertEmptyProperty(propName, originalValue);
}
private void decideSoftKeyboard() {
View hostView;
if ((hostView = getHostView()) != null) {
final Context context = getContext();
if (context != null && context instanceof Activity) {
hostView.postDelayed(WXThread.secure(new Runnable() {
@Override
public void run() {
View currentFocus = ((Activity) context).getCurrentFocus();
if (!(currentFocus instanceof EditText)) {
mInputMethodManager.hideSoftInputFromWindow(getHostView().getWindowToken(), 0);
}
}
}), 16);
}
}
}
@JSMethod
public void setSelectionRange(int selectionStart, int selectionEnd) {
EditText hostView;
if ((hostView = getHostView()) != null) {
int length = getHostView().length();
if (selectionStart > length || selectionEnd > length) {
return;
}
focus();
hostView.setSelection(selectionStart, selectionEnd);
}
}
@JSMethod
public void getSelectionRange(String callbackId) {
EditText hostView;
Map<String, Object> result = new HashMap<>(2);
if ((hostView = getHostView()) != null) {
int start = hostView.getSelectionStart();
int end = hostView.getSelectionEnd();
if (!hostView.hasFocus()) {
//The default behavior, same as iOS and web
start = 0;
end = 0;
}
result.put(Constants.Name.SELECTION_START, start);
result.put(Constants.Name.SELECTION_END, end);
}
WXBridgeManager.getInstance().callback(getInstanceId(), callbackId, result, false);
}
@JSMethod
public void setTextFormatter(JSONObject params) {
try {
String formatRule = params.getString("formatRule");
String formatReplace = params.getString("formatReplace");
String recoverRule = params.getString("recoverRule");
String recoverReplace = params.getString("recoverReplace");
PatternWrapper format = parseToPattern(formatRule, formatReplace);
PatternWrapper recover = parseToPattern(recoverRule, recoverReplace);
if (format != null && recover != null) {
mFormatter = new TextFormatter(format, recover);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
protected final void addEditorActionListener(TextView.OnEditorActionListener listener) {
TextView view;
if (listener != null && (view = getHostView()) != null) {
if (mEditorActionListeners == null) {
mEditorActionListeners = new ArrayList<>();
view.setOnEditorActionListener(new TextView.OnEditorActionListener() {
private boolean handled = true;
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
for (TextView.OnEditorActionListener l : mEditorActionListeners) {
if (l != null) {
handled = handled & l.onEditorAction(v, actionId, event);
}
}
return handled;
}
});
}
mEditorActionListeners.add(listener);
}
}
public final void addTextChangedListener(TextWatcher watcher) {
if (mTextChangedListeners == null) {
mTextChangedListeners = new ArrayList<>();
}
mTextChangedListeners.add(watcher);
}
private void addKeyboardListener(final WXEditText host) {
if (host == null) {
return;
}
final Context context = host.getContext();
if (context != null && context instanceof Activity) {
mUnregister = SoftKeyboardDetector.registerKeyboardEventListener((Activity) context, new SoftKeyboardDetector.OnKeyboardEventListener() {
@Override
public void onKeyboardEvent(boolean isShown) {
if (mListeningKeyboard) {
Map<String, Object> event = new HashMap<>(1);
event.put("isShow", isShown);
if (isShown) {
Rect r = new Rect();
((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
float keyboardSize = WXViewUtils.getWebPxByWidth(WXViewUtils.getScreenHeight(context) - (r.bottom - r.top),
getInstance().getInstanceViewPortWidth());
event.put("keyboardSize", keyboardSize);
}
fireEvent(Constants.Event.KEYBOARD, event);
}
if (!isShown) {
blur();
}
}
});
}
}
@Override
public void destroy() {
super.destroy();
if (mUnregister != null) {
try {
mUnregister.execute();
mUnregister = null;
} catch (Throwable throwable) {
WXLogUtils.w("Unregister throw ", throwable);
}
}
}
private PatternWrapper parseToPattern(String jsPattern, String replace) {
if (jsPattern == null || replace == null) {
return null;
}
String checker = "/[\\S]+/[i]?[m]?[g]?";
if (!Pattern.compile(checker).matcher(jsPattern).matches()) {
WXLogUtils.w("WXInput", "Illegal js pattern syntax: " + jsPattern);
return null;
}
int flags = 0;
boolean global = false;
String flagsStr = jsPattern.substring(jsPattern.lastIndexOf("/") + 1);
String regExp = jsPattern.substring(jsPattern.indexOf("/") + 1, jsPattern.lastIndexOf("/"));
if (flagsStr.contains("i")) {
flags |= Pattern.CASE_INSENSITIVE;
}
if (flagsStr.contains("m")) {
flags |= Pattern.DOTALL;
}
if (flagsStr.contains("g")) {
global = true;
}
Pattern pattern = null;
try {
pattern = Pattern.compile(regExp, flags);
} catch (PatternSyntaxException e) {
WXLogUtils.w("WXInput", "Pattern syntax error: " + regExp);
}
if (pattern == null) {
return null;
}
PatternWrapper wrapper = new PatternWrapper();
wrapper.global = global;
wrapper.matcher = pattern;
wrapper.replace = replace;
return wrapper;
}
private interface ReturnTypes {
String DEFAULT = "default";
String GO = "go";
String NEXT = "next";
String SEARCH = "search";
String SEND = "send";
String DONE = "done";
}
private static class PatternWrapper {
private boolean global = false;
private Pattern matcher;
private String replace;
}
private static class TextFormatter {
private PatternWrapper format;
private PatternWrapper recover;
private TextFormatter(PatternWrapper format, PatternWrapper recover) {
this.format = format;
this.recover = recover;
}
private String format(String src) {
try {
if (format != null) {
if (format.global) {
return format.matcher.matcher(src).replaceAll(format.replace);
} else {
return format.matcher.matcher(src).replaceFirst(format.replace);
}
}
} catch (Throwable t) {
//maybe IndexOutOfBoundsException caused by illegal replace
WXLogUtils.w("WXInput", "[format] " + t.getMessage());
}
return src;
}
private String recover(String formatted) {
try {
if (recover != null) {
if (recover.global) {
return recover.matcher.matcher(formatted).replaceAll(recover.replace);
} else {
return recover.matcher.matcher(formatted).replaceFirst(recover.replace);
}
}
} catch (Throwable t) {
//same cause as format
WXLogUtils.w("WXInput", "[formatted] " + t.getMessage());
}
return formatted;
}
}
}
```
|
Karaköy is a neighbourhood in the municipality and district of Susurluk, Balıkesir Province in Turkey. Its population is 535 (2022).
References
Neighbourhoods in Susurluk District
|
Taunton Metro Rail (TMR) was a light rail network proposed in 2009 to use a combination of existing rail infrastructure and the construction of new infrastructure in and around Taunton, Somerset.
Proposal
Project Taunton, the authority responsible for Taunton's major regeneration project, revealed plans for TMR in 2009 as part of their transport sustainability plan. A feasibility proposal was to be drawn for Somerset County Council.
It was anticipated that TMR will be modelled against driverless systems such as London's Docklands Light Railway, providing an anticipated peak frequency of five trains per hour and an off-peak frequency of three trains per hour.
If implemented, the avoiding line in Taunton's Station Road would be used as a calling point, rather than integrating it to Taunton's National Rail station. Also, this will mean that Wellington's rail station would be reopened, which had been already proposed by the Conservative Party. The move to re-open Wellington's former rail station gained widespread support from local businesses and residents.
The proposal was due to be submitted in Autumn 2009. However, due to the economic climate and a lack of funding, this has been delayed until further notice.
History
Somerset once had a much more extensive rail network than today. However, many stations and routes were closed following the Reshaping of British Railways report of 1963. A tram system opened in 1901 serving Taunton but closed in 1921 due to a dispute about electricity costs.
References
Taunton
Rail transport in Somerset
Light rail in the United Kingdom
Proposed transport infrastructure in the South West of England
|
Start-Up PH is a 2022 Philippine television drama romance series broadcast by GMA Network. The series is an adaptation of the 2020 South Korean television drama series Start-Up. Directed by Jerry Lopez Sineneng and Dominic Zapata, it stars Alden Richards, Bea Alonzo, Yasmien Kurdi, and Jeric Gonzales. It premiered on September 26, 2022 on the network's Telebabad line up. The series concluded on December 23, 2022 with a total of 65 episodes.
The series is streaming online on YouTube.
Cast and characters
Lead cast
Alden Richards as Tristan "Good Boy" Hernandez
Bea Alonzo as Danica "Dani" C. Sison-Hernandez
Yasmien Kurdi as Katrina "Ina" C. Sison / Katrina "Ina" C. Diaz
Jeric Gonzales as Davidson "Dave" Navarro
Supporting cast
Gina Alajar as Ligaya "Joy" Sison
Kim Domingo as Stephanie Rios
Royce Cabrera as Jefferson "Jeff" Katipunan
Boy 2 Quizon as Wilson Espiritu
Ayen Munji-Laurel as Alicia "Alice" Cortez-Sison / Alicia "Alice" Cortez-Diaz
Jackie Lou Blanco as Cassandra "Sandra" Castillejos-Yoon
Gabby Eigenmann as Arnold Diaz
Niño Muhlach as Samuel "Sammy" Navarro
Lovely Rivero as Rhodora "Dang" Navarro
Kevin Santos as Darwin Pascual
Tim Yap as Angelo "Mr. A" Angeles
Kaloy Tingcungco as Spencer Diaz
Jay Arcilla as Angelo Joseph "Anjo" Perez
Brianna Bunagan as Joanna "Joan" Perez
Guest cast
Neil Ryan Sese as Romualdo "Chito" Sison
Marco Masa as young Tristan Hernandez
Princess Aguilar as young Danica Sison
Dayara Shane as young Katrina Sison
Seth dela Cruz as young Davidson Navarro
Benjie Paras as himself
Jojo Alejar as Master Mentor
Production
Principal photography commenced on April 4, 2022.
Episodes
References
External links
2022 Philippine television series debuts
2022 Philippine television series endings
Filipino-language television shows
GMA Network drama series
Philippine romance television series
Philippine television series based on South Korean television series
Television shows set in Metro Manila
Workplace drama television series
|
Amine Khazen (also Amine el-Khazen; born 6 December 1941, in Ajaltoun, Lebanon) is a Lebanese diplomat and a member of the noble Khazen family.
Education
Amine primarily studied at Saint Joseph University, in Beirut. He is fluent in Arabic, French, English, and Spanish.
Work
He was the Lebanese ambassador to the United Nations from 1990 to 1999. He also served as an ambassador in Mexico and Central America. His diplomatic work has put him in contact with high-profile figures from around the world, including Pope John Paul II and Fidel Castro.
References
External links
el-Khazen website
Ambassador Sheikh Amine El Khazen (Circle of Ambassadors)
Dinner of Cheikh Amine el Khazen at Liza restaurant January 21st, 2014 (Mondanite)
Amine
20th-century Lebanese diplomats
Permanent Representatives of Lebanon to the United Nations
Living people
Saint Joseph University alumni
1941 births
People from Keserwan District
|
Ormosia jamaicensis is a species of flowering plant in the family Fabaceae. It is found only in Jamaica.
References
jamaicensis
Flora of Jamaica
Endangered plants
Endemic flora of Jamaica
Taxonomy articles created by Polbot
Plants described in 1908
|
```php
<?php
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
*/
namespace Google\Service\Sheets;
class AddDimensionGroupRequest extends \Google\Model
{
protected $rangeType = DimensionRange::class;
protected $rangeDataType = '';
/**
* @param DimensionRange
*/
public function setRange(DimensionRange $range)
{
$this->range = $range;
}
/**
* @return DimensionRange
*/
public function getRange()
{
return $this->range;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(AddDimensionGroupRequest::class, 'Google_Service_Sheets_AddDimensionGroupRequest');
```
|
USCGC Campbell (WPG-32) was a Secretary-class (also known as ) United States Coast Guard ship built at the Philadelphia Navy Yard in 1935-1936 and commissioned in 1936. Seven similar "combat cutters" were built and named for secretaries of the United States Treasury.
Campbell was named for George Washington Campbell. She earned the title "Queen of the Seas" during a 46-year career, spanning World War II, the Korean War, and Vietnam War.
Launch and early service
George W. Campbell was launched on 3 June 1936 and sailed to her homeport of Stapleton, New York, under the command of Commander E.G. Rose, USCG, assigned to conduct search and rescue and law enforcement patrols. She left New York on 22 October 1936 for her shakedown cruise to Southampton, England, returning to New York on 16 November. Her peace-time armament consisted of two 51 caliber and two signal guns, all mounted forward. Unlike the other Secretary-class cutters, George W. Campbell and did not continue to carry aircraft, though they had originally been equipped to do so.
In August 1937, her official name was shortened to Campbell and it was also during this time that her mascot Sinbad reported aboard. Sinbad remained aboard Campbell throughout her tour of duty during World War II, caused at least two international incidents in foreign harbors, faithfully manned his battle station during combat, and generally kept the crew amused during her long voyages over eleven years; Sinbad died on 30 December 1951, after many years of service, and was the first and one of the few Coast Guardsmen to have a published biography.
Wartime duties
On 5 September 1939, President Franklin D. Roosevelt proclaimed American neutrality in the conflict and ordered the formation of a neutrality patrol by the Navy to report and track any belligerent air, surface, or submarine activity in the waters off the East Coast and in the West Indies. The United States Navy determined that its destroyers were not capable of extended cruises in the North Atlantic and asked that the Coast Guard conduct these patrols. The Coast Guard assigned Campbell to conduct the first Coast Guard neutrality patrol, which were referred to as "Grand Banks Patrols." Campbell would perform five such cruises, each lasting approximately two weeks, the last such cruise returning to New York on 29 January 1940.
When prepared for convoy escort duty prior to her sailing for Portugal, workers at the New York Navy Yard added three 51 caliber guns in-line, aft. Her two signal guns that were directly forward of the bridge were replaced with a single 3-inch 50 caliber gun. Her two 5-inch 51 caliber main batteries remained unchanged. Campbell was the first Secretary-class cutter to transfer for duty with the Navy (on 1 July 1941) and the first to sail on escort of convoy duties when she escorted Convoy HX 159 which sailed on 10 November 1941. Campbells permanent station was changed from Stapleton to Boston in February 1942, and she later exchanged a for a gun, installed six more 20 mm guns, substituted two "K" guns for "Y" guns and had splinter protection built around three gun decks, bridge and wheel house.
Campbell, along with , were the first U.S. warships equipped with HF/DF, pioneered by the Royal Navy for the fight against the German U-boat fleet. The two cutters had been selected by the Navy to serve as test ships to gain experience with HF/DF, using British FH3 systems (carrying the U.S. designation Type DAR) installed in the American shipyard in Northern Ireland under the supervision of experts from the Admiralty Signals Establishment. As the Royal Navy had already discovered, HF/DF was an important part of combatting the threat posed to Allied convoys by U-boats, and the experience with the interim DAR equipment provided impetus to the U.S. development of its own Type DAQ system.
Convoys escorted; 1941 – early 1943 (later convoys not listed)
When the British and Canadians assumed full responsibility for convoys in the North Atlantic in mid-1943, the U.S. took control of all mid-Atlantic and Mediterranean convoys, where the cutters faced a constant threat from U-boats and the Luftwaffe. Convoys were especially vulnerable once they cleared Gibraltar. Campbell sailed as an escort for Mediterranean convoys in 1943–1944 and saw considerable action against both U-boats and aircraft, with two incidents in particular of note.
U-boat attack, February 1943
On 21 February 1943, Campbell was escorting the 48-ship convoy ON 166 when the convoy was surrounded by a U-boat "wolf pack". and torpedoed and sank whale factory ship N.T. Nielsen Alonso. Dispatched to assist, Campbell rescued fifty survivors and then turned to attack U-753, damaging it so badly that it had to withdraw. Throughout 21 and 22 February, Campbell attacked several U-boats, inflicting damage and driving them off. Later on 22 February, , having sustained heavy damage inflicted by the Polish destroyer , surfaced in the midst of the convoy attempting a surface attack. Campbell struck the U-boat a glancing blow that gashed Campbells hull in the engine room below the waterline, but continued to attack, dropping two depth charges which exploded and lifted the U-boat out of the water. The crew brought all guns to bear on the U-boat, fighting on until water in the engine room shorted out all electricity. As the ship lost power and the searchlights illuminating the U-boat went out, the U-boat's commander ordered the vessel abandoned. Campbell ceased fire and lowered boats to rescue the U-boat's survivors. Campbell, disabled in the attack, was towed to port nine days later, repaired and returned to escort duty.
Illustrator Anton Otto Fischer, working for Life magazine, was serving as a lieutenant commander aboard Campbell for this voyage. His series of detailed oil paintings depicting the battle and its aftermath appeared in Lifes 5 July 1943 edition.
Luftwaffe attack, May 1944
In April 1944, the Convoy UGS-40, consisting of some 80 vessels, sailed for the Mediterranean, led by Campbell. The escort screen contained three destroyers, six American destroyer escorts from CortDiv 5, and two French destroyer escorts. Due to recent attacks by the Luftwaffe against Allied convoys in the western Mediterranean, UGS-40 sailed with an elaborate air defense plan, formulated by the convoy's screen commander, Comdr. Jesse C. Sowell, aboard Campbell. Practiced in Hampton Roads prior to the convoy's departure and as it crossed the Atlantic, these tactics were designed to meet mass aerial attacks by German aircraft carrying a variety of weapons ranging from bombs, to torpedoes, to radio-controlled glider bombs. Off Gibraltar, UGS-40 acquired additional escorts: British antiaircraft cruiser , the destroyer escort , the destroyer , and two American minesweepers ( and ) carrying special apparatus to jam radar transmissions and thus confuse the German glider bombs. On 9 May 1944, the convoy passed through the Straits of Gibraltar en route to Bizerte, Tunisia, without incident, but two days later detected German "snoopers" trailing the convoy. In the next few hours, ten successive shore-based fighter interception sorties failed to drive off the enemy reconnaissance aircraft. First alerted by shore-based radar, the escort screen went to general quarters at 13:16 on 11 May, beginning the first of five successive alerts. In Campbell, Commander Sowell warned the escorts to be alert to the possibility of a dusk attack. At 20:25, radar noted the approach of enemy aircraft, and Sowell formed the convoy into eight columns apart for maneuvering room. When the enemy was reported north of Cape Corbelin, UGS-40 steered due east, past Cape Bengut. Shortly after sunset, escort ships commenced laying smoke screens, as the German aircraft, a mixed force of Junkers Ju 88s, Heinkel He 111s, and Dornier Do 217s, approached from the stern of the convoy and broke into groups to attack from different points of the compass. The destroyer escorts and friendly fighter craft downed an estimated 17 of the enemy planes, and drove away all the remainder, and the Allied convoy emerged unscathed.
Later service
After conversion to an Amphibious Command Ship (Type AGC) in the Boston Navy Yard between 4 January and 28 March 1945, Campbell was assigned to duty in the Pacific as an Amphibious Flagship. She sailed from Pearl Harbor for Saipan and arrived on 3 August 1945, sailing again for Manila on 10 August, and Leyte on 19 August. On 1 October 1945 she was anchored at Wakanoura Wan, Honshū, Japan as the flagship for Communications Service Division 103. On 30 October she sailed to Sasebo and stayed until 30 November when she was ordered back to the U.S. In August 1948, Campbell found wreckage from an Air France Latécoère 631 aircraft which had crashed into the Atlantic Ocean with the loss of all 52 people on board. In January 1959, Campbell was one of the ships which answered the distress call of which had struck an iceberg off Greenland. She participated in the search until it was called off on 7 February.
Vietnam
Campbell was assigned to combat duty in Vietnam from January to July 1968. During Operation Market Time, Campbell destroyed or damaged 105 Viet Cong structures and steamed over in the Vietnamese War Zone.
After returning from Vietnam, Campbell was assigned to routine Search-and-Rescue, Maritime Law Enforcement, Military Readiness, and Ocean Station duties.
She was homeported at Governors Island in New York City until 1969 when she moved to Portland, Maine. In 1974 her homeport was again changed, this time to Port Angeles, Washington. There she continued her peacetime duties until decommissioned in 1982. At the time of decommissioning, Campbell was the oldest active continually commissioned vessel in the United States Coast Guard.
Sinking
USCGC Campbell was sunk on 29 November 1984 as a target in the mid-Pacific Ocean by the United States Navy at coordinates , northwest of Hawaii, and rests at . A final message was transmitted as the ship, which remained largely intact after a Harpoon missile strike, went down. It said:
Awards
Source:
Coast Guard Meritorious Unit Commendation
American Defense Service Medal with "FLEET" clasp and "A" device
American Campaign Medal with "A" device
European-African-Middle Eastern Campaign Medal with three battle stars
Asiatic-Pacific Campaign Medal
World War II Victory Medal
Navy Occupation Medal with "ASIA" clasp
National Defense Service Medal with one service star
Vietnam Service Medal with two campaign stars
Humanitarian Service Medal
Philippine Presidential Unit Citation
Vietnam Gallantry Cross with palm
Philippine Liberation Medal with two service stars
Republic of Vietnam Campaign Medal
References
External links
USCGC Campbell Association
USCGC Campbell at history.uscg.mil
1936 ships
History of the United States Coast Guard
Maritime incidents in 1984
Ships built in Philadelphia
Ships of the United States Coast Guard
Ships sunk as targets
Treasury-class cutters
|
```objective-c
/**
* @file TinyGsmClientSim7080.h
* @author Volodymyr Shymanskyy
* @license LGPL-3.0
* @date Nov 2016
*/
#ifndef SRC_TINYGSMCLIENTSIM7080_H_
#define SRC_TINYGSMCLIENTSIM7080_H_
// #define TINY_GSM_DEBUG Serial
// #define TINY_GSM_USE_HEX
#define TINY_GSM_MUX_COUNT 12
#define TINY_GSM_BUFFER_READ_AND_CHECK_SIZE
#include "TinyGsmClientSIM70xx.h"
#include "TinyGsmTCP.tpp"
#include "TinyGsmSSL.tpp"
#include "TinyGsmSMS.tpp"
#include "TinyGsmGSMLocation.tpp"
#include "TinyGsmTime.tpp"
#include "TinyGsmNTP.tpp"
#include "TinyGsmBattery.tpp"
class TinyGsmSim7080 : public TinyGsmSim70xx<TinyGsmSim7080>,
public TinyGsmTCP<TinyGsmSim7080, TINY_GSM_MUX_COUNT>,
public TinyGsmSSL<TinyGsmSim7080, TINY_GSM_MUX_COUNT>,
public TinyGsmSMS<TinyGsmSim7080>,
public TinyGsmGSMLocation<TinyGsmSim7080>,
public TinyGsmTime<TinyGsmSim7080>,
public TinyGsmNTP<TinyGsmSim7080>,
public TinyGsmBattery<TinyGsmSim7080> {
friend class TinyGsmSim70xx<TinyGsmSim7080>;
friend class TinyGsmModem<TinyGsmSim7080>;
friend class TinyGsmGPRS<TinyGsmSim7080>;
friend class TinyGsmTCP<TinyGsmSim7080, TINY_GSM_MUX_COUNT>;
friend class TinyGsmSSL<TinyGsmSim7080, TINY_GSM_MUX_COUNT>;
friend class TinyGsmSMS<TinyGsmSim7080>;
friend class TinyGsmGSMLocation<TinyGsmSim7080>;
friend class TinyGsmGPS<TinyGsmSim7080>;
friend class TinyGsmTime<TinyGsmSim7080>;
friend class TinyGsmNTP<TinyGsmSim7080>;
friend class TinyGsmBattery<TinyGsmSim7080>;
/*
* Inner Client
*/
public:
class GsmClientSim7080 : public GsmClient {
friend class TinyGsmSim7080;
public:
GsmClientSim7080() {}
explicit GsmClientSim7080(TinyGsmSim7080& modem, uint8_t mux = 0) {
init(&modem, mux);
}
bool init(TinyGsmSim7080* modem, uint8_t mux = 0) {
this->at = modem;
sock_available = 0;
prev_check = 0;
sock_connected = false;
got_data = false;
if (mux < TINY_GSM_MUX_COUNT) {
this->mux = mux;
} else {
this->mux = (mux % TINY_GSM_MUX_COUNT);
}
at->sockets[this->mux] = this;
return true;
}
public:
virtual int connect(const char* host, uint16_t port, int timeout_s) {
stop();
TINY_GSM_YIELD();
rx.clear();
sock_connected = at->modemConnect(host, port, mux, false, timeout_s);
return sock_connected;
}
TINY_GSM_CLIENT_CONNECT_OVERRIDES
void stop(uint32_t maxWaitMs) {
dumpModemBuffer(maxWaitMs);
at->sendAT(GF("+CACLOSE="), mux);
sock_connected = false;
at->waitResponse(3000);
}
void stop() override {
stop(15000L);
}
/*
* Extended API
*/
String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
};
/*
* Inner Secure Client
*/
public:
class GsmClientSecureSIM7080 : public GsmClientSim7080 {
public:
GsmClientSecureSIM7080() {}
explicit GsmClientSecureSIM7080(TinyGsmSim7080& modem, uint8_t mux = 0)
: GsmClientSim7080(modem, mux) {}
bool setCertificate(const String& certificateName) {
return at->setCertificate(certificateName, mux);
}
int connect(const char* host, uint16_t port, int timeout_s) override {
stop();
TINY_GSM_YIELD();
rx.clear();
sock_connected = at->modemConnect(host, port, mux, true, timeout_s);
return sock_connected;
}
TINY_GSM_CLIENT_CONNECT_OVERRIDES
};
/*
* Constructor
*/
public:
explicit TinyGsmSim7080(Stream& stream)
: TinyGsmSim70xx<TinyGsmSim7080>(stream) {
memset(sockets, 0, sizeof(sockets));
}
/*
* Basic functions
*/
protected:
bool initImpl(const char* pin = nullptr) {
DBG(GF("### TinyGSM Version:"), TINYGSM_VERSION);
DBG(GF("### TinyGSM Compiled Module: TinyGsmClientSIM7080"));
bool gotATOK = false;
for (uint32_t start = millis(); millis() - start < 10000L;) {
sendAT(GF(""));
int8_t resp = waitResponse(200L, GFP(GSM_OK), GFP(GSM_ERROR), GF("AT"));
if (resp == 1) {
gotATOK = true;
break;
} else if (resp == 3) {
waitResponse(200L); // get the OK
sendAT(GF("E0")); // Echo Off
DBG(GF("## Turning off echo!"));
waitResponse(2000L);
}
delay(100);
}
if (!gotATOK) { return false; }
#ifdef TINY_GSM_DEBUG
sendAT(GF("+CMEE=2")); // turn on verbose error codes
#else
sendAT(GF("+CMEE=0")); // turn off error codes
#endif
waitResponse();
DBG(GF("### Modem:"), getModemName());
// Enable Local Time Stamp for getting network time
sendAT(GF("+CLTS=1"));
if (waitResponse(10000L) != 1) { return false; }
// Enable battery checks
sendAT(GF("+CBATCHK=1"));
if (waitResponse() != 1) { return false; }
SimStatus ret = getSimStatus();
// if the sim isn't ready and a pin has been provided, try to unlock the sim
if (ret != SIM_READY && pin != nullptr && strlen(pin) > 0) {
simUnlock(pin);
return (getSimStatus() == SIM_READY);
} else {
// if the sim is ready, or it's locked but no pin has been provided,
// return true
return (ret == SIM_READY || ret == SIM_LOCKED);
}
}
void maintainImpl() {
// Keep listening for modem URC's and proactively iterate through
// sockets asking if any data is avaiable
bool check_socks = false;
for (int mux = 0; mux < TINY_GSM_MUX_COUNT; mux++) {
GsmClientSim7080* sock = sockets[mux];
if (sock && sock->got_data) {
sock->got_data = false;
check_socks = true;
}
}
// modemGetAvailable checks all socks, so we only want to do it once
// modemGetAvailable calls modemGetConnected(), which also checks allf
if (check_socks) { modemGetAvailable(0); }
while (stream.available()) { waitResponse(15, nullptr, nullptr); }
}
/*
* Power functions
*/
protected:
bool restartImpl(const char* pin = nullptr) {
bool success = true;
bool gotATOK = false;
for (uint32_t start = millis(); millis() - start < 10000L;) {
sendAT(GF(""));
int8_t resp = waitResponse(200L, GFP(GSM_OK), GFP(GSM_ERROR), GF("AT"));
if (resp == 1) {
gotATOK = true;
break;
} else if (resp == 3) {
waitResponse(200L); // get the OK
DBG(GF("## Turning off echo!"));
sendAT(GF("E0")); // Echo Off
waitResponse(2000L);
}
delay(100);
}
if (!gotATOK) { return false; }
sendAT(GF("+CREBOOT")); // Reboot
success &= waitResponse() == 1;
waitResponse(30000L, GF("SMS Ready"));
success &= initImpl(pin);
return success;
}
/*
* Generic network functions
*/
protected:
String getLocalIPImpl() {
sendAT(GF("+CNACT?"));
if (waitResponse(GF(AT_NL "+CNACT:")) != 1) { return ""; }
streamSkipUntil('\"');
String res = stream.readStringUntil('\"');
waitResponse();
return res;
}
/*
* Secure socket layer (SSL) functions
*/
// Follows functions as inherited from TinyGsmSSL.tpp
/*
* WiFi functions
*/
// No functions of this type supported
/*
* GPRS functions
*/
protected:
bool gprsConnectImpl(const char* apn, const char* user = nullptr,
const char* pwd = nullptr) {
gprsDisconnect();
// Define the PDP context
sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
waitResponse();
// Attach to GPRS
sendAT(GF("+CGATT=1"));
if (waitResponse(60000L) != 1) { return false; }
// NOTE: **DO NOT** activate the PDP context
// For who only knows what reason, doing so screws up the rest of the
// process
// Check the APN returned by the server
// not sure why, but the connection is more consistent with this
sendAT(GF("+CGNAPN"));
waitResponse();
// Bearer settings for applications based on IP
// Set the user name and password
// AT+CNCFG=<pdpidx>,<ip_type>,[<APN>,[<usename>,<password>,[<authentication>]]]
// <pdpidx> PDP Context Identifier - for reasons not understood by me,
// use PDP context identifier of 0 for what we defined as 1 above
// <ip_type> 0: Dual PDN Stack
// 1: Internet Protocol Version 4
// 2: Internet Protocol Version 6
// <authentication> 0: NONE
// 1: PAP
// 2: CHAP
// 3: PAP or CHAP
if (pwd && strlen(pwd) > 0 && user && strlen(user) > 0) {
sendAT(GF("+CNCFG=0,1,\""), apn, "\",\"", user, "\",\"", pwd, "\",3");
waitResponse();
} else if (user && strlen(user) > 0) {
// Set the user name only
sendAT(GF("+CNCFG=0,1,\""), apn, "\",\"", user, '"');
waitResponse();
} else {
// Set the APN only
sendAT(GF("+CNCFG=0,1,\""), apn, '"');
waitResponse();
}
// Activate application network connection
// AT+CNACT=<pdpidx>,<action>
// <pdpidx> PDP Context Identifier - for reasons not understood by me,
// use PDP context identifier of 0 for what we defined as 1 above
// <action> 0: Deactive
// 1: Active
// 2: Auto Active
bool res = false;
int ntries = 0;
while (!res && ntries < 5) {
sendAT(GF("+CNACT=0,1"));
res = waitResponse(60000L, GF(AT_NL "+APP PDP: 0,ACTIVE"),
GF(AT_NL "+APP PDP: 0,DEACTIVE"));
waitResponse();
ntries++;
}
return res;
}
bool gprsDisconnectImpl() {
// Shut down the general application TCP/IP connection
// CNACT will close *all* open application connections
sendAT(GF("+CNACT=0,0"));
if (waitResponse(60000L) != 1) { return false; }
sendAT(GF("+CGATT=0")); // Deactivate the bearer context
if (waitResponse(60000L) != 1) { return false; }
return true;
}
/*
* SIM card functions
*/
// Follows functions as inherited from TinyGsmClientSIM70xx.h
/*
* Phone Call functions
*/
// No functions of this type supported
/*
* Audio functions
*/
// No functions of this type supported
/*
* Text messaging (SMS) functions
*/
// Follows all text messaging (SMS) functions as inherited from TinyGsmSMS.tpp
/*
* GSM Location functions
*/
// Follows all GSM-based location functions as inherited from
// TinyGsmGSMLocation.tpp
/*
* GPS/GNSS/GLONASS location functions
*/
// Follows functions as inherited from TinyGsmClientSIM70xx.h
/*
* Time functions
*/
// Follows all clock functions as inherited from TinyGsmTime.tpp
/*
* NTP server functions
*/
protected:
byte NTPServerSyncImpl(String server = "pool.ntp.org", int TimeZone = 0) {
// Set GPRS bearer profile to associate with NTP sync
// this may fail, it's not supported by all modules
sendAT(GF("+CNTPCID=0")); // CID must be 0. With 1 (like other modules)
// does not work!
waitResponse(10000L);
// Set NTP server and timezone
sendAT(GF("+CNTP=\""), server, "\",", String(TimeZone));
if (waitResponse(10000L) != 1) { return -1; }
// Request network synchronization
sendAT(GF("+CNTP"));
if (waitResponse(10000L, GF("+CNTP:"))) {
String result = stream.readStringUntil('\n');
// Check for ',' in case the module appends the time next to the return
// code. Eg: +CNTP: <code>[,<time>]
int index = result.indexOf(',');
if (index > 0) { result.remove(index); }
result.trim();
if (TinyGsmIsValidNumber(result)) { return result.toInt(); }
} else {
return -1;
}
return -1;
}
String ShowNTPErrorImpl(byte error) {
switch (error) {
case 1: return "Network time synchronization is successful";
case 61: return "Network error";
case 62: return "DNS resolution error";
case 63: return "Connection error";
case 64: return "Service response error";
case 65: return "Service response timeout";
default: return "Unknown error: " + String(error);
}
}
/*
* BLE functions
*/
// No functions of this type supported
/*
* Battery functions
*/
// Follows all battery functions as inherited from TinyGsmBattery.tpp
/*
* Temperature functions
*/
// No functions of this type supported
/*
* Client related functions
*/
protected:
bool modemConnect(const char* host, uint16_t port, uint8_t mux,
bool ssl = false, int timeout_s = 75) {
uint32_t timeout_ms = ((uint32_t)timeout_s) * 1000;
// set the connection (mux) identifier to use
sendAT(GF("+CACID="), mux);
if (waitResponse(timeout_ms) != 1) return false;
if (ssl) {
// set the ssl version
// AT+CSSLCFG="SSLVERSION",<ctxindex>,<sslversion>
// <ctxindex> PDP context identifier - for reasons not understood by me,
// use PDP context identifier of 0 for what we defined as 1 in
// the gprsConnect function
// <sslversion> 0: QAPI_NET_SSL_PROTOCOL_UNKNOWN
// 1: QAPI_NET_SSL_PROTOCOL_TLS_1_0
// 2: QAPI_NET_SSL_PROTOCOL_TLS_1_1
// 3: QAPI_NET_SSL_PROTOCOL_TLS_1_2
// 4: QAPI_NET_SSL_PROTOCOL_DTLS_1_0
// 5: QAPI_NET_SSL_PROTOCOL_DTLS_1_2
// NOTE: despite docs using caps, "sslversion" must be in lower case
sendAT(GF("+CSSLCFG=\"sslversion\",0,3")); // TLS 1.2
if (waitResponse(5000L) != 1) return false;
}
// enable or disable ssl
// AT+CASSLCFG=<cid>,"SSL",<sslFlag>
// <cid> Application connection ID (set with AT+CACID above)
// <sslFlag> 0: Not support SSL
// 1: Support SSL
sendAT(GF("+CASSLCFG="), mux, ',', GF("SSL,"), ssl);
waitResponse();
if (ssl) {
// set the PDP context to apply SSL to
// AT+CSSLCFG="CTXINDEX",<ctxindex>
// <ctxindex> PDP context identifier - for reasons not understood by me,
// use PDP context identifier of 0 for what we defined as 1 in
// the gprsConnect function
// NOTE: despite docs using "CRINDEX" in all caps, the module only
// accepts the command "ctxindex" and it must be in lower case
sendAT(GF("+CSSLCFG=\"ctxindex\",0"));
if (waitResponse(5000L, GF("+CSSLCFG:")) != 1) return false;
streamSkipUntil('\n'); // read out the certificate information
waitResponse();
if (certificates[mux] != "") {
// apply the correct certificate to the connection
// AT+CASSLCFG=<cid>,"CACERT",<caname>
// <cid> Application connection ID (set with AT+CACID above)
// <certname> certificate name
sendAT(GF("+CASSLCFG="), mux, ",CACERT,\"", certificates[mux].c_str(),
"\"");
if (waitResponse(5000L) != 1) return false;
}
// set the SSL SNI (server name indication)
// AT+CSSLCFG="SNI",<ctxindex>,<servername>
// <ctxindex> PDP context identifier - for reasons not understood by me,
// use PDP context identifier of 0 for what we defined as 1 in
// the gprsConnect function
// NOTE: despite docs using caps, "sni" must be in lower case
sendAT(GF("+CSSLCFG=\"sni\",0,"), GF("\""), host, GF("\""));
waitResponse();
}
// actually open the connection
// AT+CAOPEN=<cid>,<pdp_index>,<conn_type>,<server>,<port>[,<recv_mode>]
// <cid> TCP/UDP identifier
// <pdp_index> Index of PDP connection; we set up PCP context 1 above
// <conn_type> "TCP" or "UDP"
// <recv_mode> 0: The received data can only be read manually using
// AT+CARECV=<cid>
// 1: After receiving the data, it will automatically report
// URC:
// +CAURC:
// "recv",<id>,<length>,<remoteIP>,<remote_port><CR><LF><data>
// NOTE: including the <recv_mode> fails
sendAT(GF("+CAOPEN="), mux, GF(",0,\"TCP\",\""), host, GF("\","), port);
if (waitResponse(timeout_ms, GF(AT_NL "+CAOPEN:")) != 1) { return 0; }
// returns OK/r/n/r/n+CAOPEN: <cid>,<result>
// <result> 0: Success
// 1: Socket error
// 2: No memory
// 3: Connection limit
// 4: Parameter invalid
// 6: Invalid IP address
// 7: Not support the function
// 12: Cant bind the port
// 13: Cant listen the port
// 20: Cant resolve the host
// 21: Network not active
// 23: Remote refuse
// 24: Certificates time expired
// 25: Certificates common name does not match
// 26: Certificates common name does not match and time expired
// 27: Connect failed
streamSkipUntil(','); // Skip mux
// make sure the connection really opened
int8_t res = streamGetIntBefore('\n');
waitResponse();
return 0 == res;
}
int16_t modemSend(const void* buff, size_t len, uint8_t mux) {
// send data on prompt
sendAT(GF("+CASEND="), mux, ',', (uint16_t)len);
if (waitResponse(GF(">")) != 1) { return 0; }
stream.write(reinterpret_cast<const uint8_t*>(buff), len);
stream.flush();
// OK after posting data
if (waitResponse() != 1) { return 0; }
return len;
}
size_t modemRead(size_t size, uint8_t mux) {
if (!sockets[mux]) { return 0; }
sendAT(GF("+CARECV="), mux, ',', (uint16_t)size);
if (waitResponse(GF("+CARECV:")) != 1) { return 0; }
// uint8_t ret_mux = stream.parseInt();
// streamSkipUntil(',');
// const int16_t len_confirmed = streamGetIntBefore('\n');
// DBG("### READING:", len_confirmed, "from", ret_mux);
// if (ret_mux != mux) {
// DBG("### Data from wrong mux! Got", ret_mux, "expected", mux);
// waitResponse();
// sockets[mux]->sock_available = modemGetAvailable(mux);
// return 0;
// }
// NOTE: manual says the mux number is returned before the number of
// characters available, but in tests only the number is returned
int16_t len_confirmed = stream.parseInt();
streamSkipUntil(','); // skip the comma
if (len_confirmed <= 0) {
waitResponse();
sockets[mux]->sock_available = modemGetAvailable(mux);
return 0;
}
for (int i = 0; i < len_confirmed; i++) {
uint32_t startMillis = millis();
while (!stream.available() &&
(millis() - startMillis < sockets[mux]->_timeout)) {
TINY_GSM_YIELD();
}
char c = stream.read();
sockets[mux]->rx.put(c);
}
waitResponse();
// make sure the sock available number is accurate again
sockets[mux]->sock_available = modemGetAvailable(mux);
return len_confirmed;
}
size_t modemGetAvailable(uint8_t mux) {
// If the socket doesn't exist, just return
if (!sockets[mux]) { return 0; }
// NOTE: This gets how many characters are available on all connections that
// have data. It does not return all the connections, just those with data.
sendAT(GF("+CARECV?"));
for (int muxNo = 0; muxNo < TINY_GSM_MUX_COUNT; muxNo++) {
// after the last connection, there's an ok, so we catch it right away
int res = waitResponse(3000, GF("+CARECV:"), GFP(GSM_OK), GFP(GSM_ERROR));
// if we get the +CARECV: response, read the mux number and the number of
// characters available
if (res == 1) {
int ret_mux = streamGetIntBefore(',');
size_t result = streamGetIntBefore('\n');
GsmClientSim7080* sock = sockets[ret_mux];
if (sock) { sock->sock_available = result; }
// if the first returned mux isn't 0 (or is higher than expected)
// we need to fill in the missing muxes
if (ret_mux > muxNo) {
for (int extra_mux = muxNo; extra_mux < ret_mux; extra_mux++) {
GsmClientSim7080* isock = sockets[extra_mux];
if (isock) { isock->sock_available = 0; }
}
muxNo = ret_mux;
}
} else if (res == 2) {
// if we get an OK, we've reached the last socket with available data
// so we set any we haven't gotten to yet to 0
for (int extra_mux = muxNo; extra_mux < TINY_GSM_MUX_COUNT;
extra_mux++) {
GsmClientSim7080* isock = sockets[extra_mux];
if (isock) { isock->sock_available = 0; }
}
break;
} else {
// if we got an error, give up
break;
}
// Should be a final OK at the end.
// If every connection was returned, catch the OK here.
// If only a portion were returned, catch it above.
if (muxNo == TINY_GSM_MUX_COUNT - 1) { waitResponse(); }
}
modemGetConnected(mux); // check the state of all connections
if (!sockets[mux]) { return 0; }
return sockets[mux]->sock_available;
}
bool modemGetConnected(uint8_t mux) {
// NOTE: This gets the state of all connections that have been opened
// since the last connection
sendAT(GF("+CASTATE?"));
for (int muxNo = 0; muxNo < TINY_GSM_MUX_COUNT; muxNo++) {
// after the last connection, there's an ok, so we catch it right away
int res = waitResponse(3000, GF("+CASTATE:"), GFP(GSM_OK),
GFP(GSM_ERROR));
// if we get the +CASTATE: response, read the mux number and the status
if (res == 1) {
int ret_mux = streamGetIntBefore(',');
size_t status = streamGetIntBefore('\n');
// 0: Closed by remote server or internal error
// 1: Connected to remote server
// 2: Listening (server mode)
GsmClientSim7080* sock = sockets[ret_mux];
if (sock) { sock->sock_connected = (status == 1); }
// if the first returned mux isn't 0 (or is higher than expected)
// we need to fill in the missing muxes
if (ret_mux > muxNo) {
for (int extra_mux = muxNo; extra_mux < ret_mux; extra_mux++) {
GsmClientSim7080* isock = sockets[extra_mux];
if (isock) { isock->sock_connected = false; }
}
muxNo = ret_mux;
}
} else if (res == 2) {
// if we get an OK, we've reached the last socket with available data
// so we set any we haven't gotten to yet to 0
for (int extra_mux = muxNo; extra_mux < TINY_GSM_MUX_COUNT;
extra_mux++) {
GsmClientSim7080* isock = sockets[extra_mux];
if (isock) { isock->sock_connected = false; }
}
break;
} else {
// if we got an error, give up
break;
}
// Should be a final OK at the end.
// If every connection was returned, catch the OK here.
// If only a portion were returned, catch it above.
if (muxNo == TINY_GSM_MUX_COUNT - 1) { waitResponse(); }
}
return sockets[mux]->sock_connected;
}
/*
* Utilities
*/
public:
bool handleURCs(String& data) {
if (data.endsWith(GF("+CARECV:"))) {
int8_t mux = streamGetIntBefore(',');
int16_t len = streamGetIntBefore('\n');
if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
sockets[mux]->got_data = true;
if (len >= 0 && len <= 1024) { sockets[mux]->sock_available = len; }
}
data = "";
DBG("### Got Data:", len, "on", mux);
return true;
} else if (data.endsWith(GF("+CADATAIND:"))) {
int8_t mux = streamGetIntBefore('\n');
if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
sockets[mux]->got_data = true;
}
data = "";
DBG("### Got Data:", mux);
return true;
} else if (data.endsWith(GF("+CASTATE:"))) {
int8_t mux = streamGetIntBefore(',');
int8_t state = streamGetIntBefore('\n');
if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
if (state != 1) {
sockets[mux]->sock_connected = false;
DBG("### Closed: ", mux);
}
}
data = "";
return true;
} else if (data.endsWith(GF("*PSNWID:"))) {
streamSkipUntil('\n'); // Refresh network name by network
data = "";
DBG("### Network name updated.");
return true;
} else if (data.endsWith(GF("*PSUTTZ:"))) {
streamSkipUntil('\n'); // Refresh time and time zone by network
data = "";
DBG("### Network time and time zone updated.");
return true;
} else if (data.endsWith(GF("+CTZV:"))) {
streamSkipUntil('\n'); // Refresh network time zone by network
data = "";
DBG("### Network time zone updated.");
return true;
} else if (data.endsWith(GF("DST: "))) {
streamSkipUntil('\n'); // Refresh Network Daylight Saving Time by network
data = "";
DBG("### Daylight savings time state updated.");
return true;
} else if (data.endsWith(GF(AT_NL "SMS Ready" AT_NL))) {
data = "";
DBG("### Unexpected module reset!");
init();
data = "";
return true;
}
return false;
}
protected:
GsmClientSim7080* sockets[TINY_GSM_MUX_COUNT];
String certificates[TINY_GSM_MUX_COUNT];
};
#endif // SRC_TINYGSMCLIENTSIM7080_H_
```
|
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>15G1004</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>IntelMausiEthernet</string>
<key>CFBundleIdentifier</key>
<string>com.insanelymac.IntelMausiEthernet</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>IntelMausiEthernet</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>2.2.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>2.2.0</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>7D1014</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>15E60</string>
<key>DTSDKName</key>
<string>macosx10.11</string>
<key>DTXcode</key>
<string>0731</string>
<key>DTXcodeBuild</key>
<string>7D1014</string>
<key>IOKitPersonalities</key>
<dict>
<key>IntelMausi</key>
<dict>
<key>CFBundleIdentifier</key>
<string>com.insanelymac.IntelMausiEthernet</string>
<key>Driver_Version</key>
<string>2.2.0</string>
<key>IOClass</key>
<string>IntelMausi</string>
<key>IOPCIMatch</key>
<string>0x10EA8086 0x10EB8086 0x10EF8086 0x10F08086 0x15028086 0x15038086 0x153A8086 0x153B8086 0x155A8086 0x15598086 0x15A08086 0x15A18086 0x15A28086 0x15A38086 0x156F8086 0x15708086 0x15B78086 0x15B88086</string>
<key>IOProbeScore</key>
<integer>1000</integer>
<key>IOProviderClass</key>
<string>IOPCIDevice</string>
<key>enableCSO6</key>
<true/>
<key>enableTSO4</key>
<false/>
<key>enableTSO6</key>
<false/>
<key>maxIntrRate</key>
<integer>7000</integer>
</dict>
</dict>
<key>OSBundleLibraries</key>
<dict>
<key>com.apple.iokit.IONetworkingFamily</key>
<string>1.5.0</string>
<key>com.apple.iokit.IOPCIFamily</key>
<string>1.7</string>
<key>com.apple.kpi.bsd</key>
<string>8.10.0</string>
<key>com.apple.kpi.iokit</key>
<string>8.10.0</string>
<key>com.apple.kpi.libkern</key>
<string>8.10.0</string>
<key>com.apple.kpi.mach</key>
<string>8.10.0</string>
</dict>
<key>OSBundleRequired</key>
<string>Network-Root</string>
</dict>
</plist>
```
|
```objective-c
#pragma once
#include <ATen/core/Tensor.h>
#include <ATen/native/DispatchStub.h>
#include <ATen/core/IListRef.h>
namespace at::native {
using cat_serial_fn = void(*)(const Tensor &, const MaterializedITensorListRef&, int64_t);
DECLARE_DISPATCH(cat_serial_fn, cat_serial_stub);
} // namespace at::native
```
|
```objective-c
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef BRCMFMAC_FLOWRING_H
#define BRCMFMAC_FLOWRING_H
#define BRCMF_FLOWRING_HASHSIZE 256
#define BRCMF_FLOWRING_INVALID_ID 0xFFFFFFFF
struct brcmf_flowring_hash {
u8 mac[ETH_ALEN];
u8 fifo;
u8 ifidx;
u8 flowid;
};
enum ring_status {
RING_CLOSED,
RING_CLOSING,
RING_OPEN
};
struct brcmf_flowring_ring {
u16 hash_id;
bool blocked;
enum ring_status status;
struct sk_buff_head skblist;
};
struct brcmf_flowring_tdls_entry {
u8 mac[ETH_ALEN];
struct brcmf_flowring_tdls_entry *next;
};
struct brcmf_flowring {
struct device *dev;
struct brcmf_flowring_hash hash[BRCMF_FLOWRING_HASHSIZE];
struct brcmf_flowring_ring **rings;
spinlock_t block_lock;
enum proto_addr_mode addr_mode[BRCMF_MAX_IFS];
u16 nrofrings;
bool tdls_active;
struct brcmf_flowring_tdls_entry *tdls_entry;
};
u32 brcmf_flowring_lookup(struct brcmf_flowring *flow, u8 da[ETH_ALEN],
u8 prio, u8 ifidx);
u32 brcmf_flowring_create(struct brcmf_flowring *flow, u8 da[ETH_ALEN],
u8 prio, u8 ifidx);
void brcmf_flowring_delete(struct brcmf_flowring *flow, u8 flowid);
void brcmf_flowring_open(struct brcmf_flowring *flow, u8 flowid);
u8 brcmf_flowring_tid(struct brcmf_flowring *flow, u8 flowid);
u32 brcmf_flowring_enqueue(struct brcmf_flowring *flow, u8 flowid,
struct sk_buff *skb);
struct sk_buff *brcmf_flowring_dequeue(struct brcmf_flowring *flow, u8 flowid);
void brcmf_flowring_reinsert(struct brcmf_flowring *flow, u8 flowid,
struct sk_buff *skb);
u32 brcmf_flowring_qlen(struct brcmf_flowring *flow, u8 flowid);
u8 brcmf_flowring_ifidx_get(struct brcmf_flowring *flow, u8 flowid);
struct brcmf_flowring *brcmf_flowring_attach(struct device *dev, u16 nrofrings);
void brcmf_flowring_detach(struct brcmf_flowring *flow);
void brcmf_flowring_configure_addr_mode(struct brcmf_flowring *flow, int ifidx,
enum proto_addr_mode addr_mode);
void brcmf_flowring_delete_peer(struct brcmf_flowring *flow, int ifidx,
u8 peer[ETH_ALEN]);
void brcmf_flowring_add_tdls_peer(struct brcmf_flowring *flow, int ifidx,
u8 peer[ETH_ALEN]);
#endif /* BRCMFMAC_FLOWRING_H */
```
|
```go
// +build !linux,!windows,!darwin,!freebsd,!openbsd,!netbsd
package sysutil
import "time"
func init() {
btime = time.Now()
}
```
|
```c++
/*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcState.h"
#include "SkBitmapScaler.h"
#include "SkColorPriv.h"
#include "SkPaint.h"
#include "SkUtils.h"
static void SI8_D16_nofilter_DX_mips_dsp(const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count, uint16_t* SK_RESTRICT colors) {
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fInvType <= (SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask));
SkASSERT(kNone_SkFilterQuality == s.fFilterLevel);
const uint16_t* SK_RESTRICT table = s.fPixmap.ctable()->read16BitCache();
const uint8_t* SK_RESTRICT srcAddr = (const uint8_t*)s.fPixmap.addr();
SkASSERT((unsigned)xy[0] < (unsigned)s.fPixmap.height());
srcAddr = (const uint8_t*)((const char*)srcAddr + xy[0] * s.fPixmap.rowBytes());
uint8_t src;
if (1 == s.fPixmap.width()) {
src = srcAddr[0];
uint16_t dstValue = table[src];
sk_memset16(colors, dstValue, count);
} else {
int count8;
const uint16_t* SK_RESTRICT xx = (const uint16_t*)(xy + 1);
__asm__ volatile (
".set push \n\t"
".set noreorder \n\t"
".set noat \n\t"
"sra %[count8], %[count], 3 \n\t"
"beqz %[count8], 3f \n\t"
" addiu %[count8], %[count8], -1 \n\t"
"1: \n\t"
"beqz %[count8], 2f \n\t"
" addiu %[count8], %[count8], -1 \n\t"
"pref 0, 16(%[xx]) \n\t"
"lhu $t0, 0(%[xx]) \n\t"
"lhu $t1, 2(%[xx]) \n\t"
"lhu $t2, 4(%[xx]) \n\t"
"lhu $t3, 6(%[xx]) \n\t"
"lhu $t4, 8(%[xx]) \n\t"
"lhu $t5, 10(%[xx]) \n\t"
"lhu $t6, 12(%[xx]) \n\t"
"lhu $t7, 14(%[xx]) \n\t"
"pref 0, 8(%[srcAddr]) \n\t"
"lbux $t0, $t0(%[srcAddr]) \n\t"
"lbux $t1, $t1(%[srcAddr]) \n\t"
"lbux $t2, $t2(%[srcAddr]) \n\t"
"lbux $t3, $t3(%[srcAddr]) \n\t"
"lbux $t4, $t4(%[srcAddr]) \n\t"
"lbux $t5, $t5(%[srcAddr]) \n\t"
"lbux $t6, $t6(%[srcAddr]) \n\t"
"lbux $t7, $t7(%[srcAddr]) \n\t"
"addu $t0, $t0, $t0 \n\t"
"addu $t1, $t1, $t1 \n\t"
"addu $t2, $t2, $t2 \n\t"
"addu $t3, $t3, $t3 \n\t"
"addu $t4, $t4, $t4 \n\t"
"addu $t5, $t5, $t5 \n\t"
"addu $t6, $t6, $t6 \n\t"
"addu $t7, $t7, $t7 \n\t"
"pref 0, 16(%[table]) \n\t"
"lhx $t0, $t0(%[table]) \n\t"
"lhx $t1, $t1(%[table]) \n\t"
"lhx $t2, $t2(%[table]) \n\t"
"lhx $t3, $t3(%[table]) \n\t"
"lhx $t4, $t4(%[table]) \n\t"
"lhx $t5, $t5(%[table]) \n\t"
"lhx $t6, $t6(%[table]) \n\t"
"lhx $t7, $t7(%[table]) \n\t"
"sh $t0, 0(%[colors]) \n\t"
"sh $t1, 2(%[colors]) \n\t"
"sh $t2, 4(%[colors]) \n\t"
"sh $t3, 6(%[colors]) \n\t"
"sh $t4, 8(%[colors]) \n\t"
"sh $t5, 10(%[colors]) \n\t"
"sh $t6, 12(%[colors]) \n\t"
"sh $t7, 14(%[colors]) \n\t"
"addiu %[xx], %[xx], 16 \n\t"
"bgtz %[count8], 1b \n\t"
" addiu %[colors], %[colors], 16 \n\t"
"2: \n\t"
"lhu $t0, 0(%[xx]) \n\t"
"lhu $t1, 2(%[xx]) \n\t"
"lhu $t2, 4(%[xx]) \n\t"
"lhu $t3, 6(%[xx]) \n\t"
"lhu $t4, 8(%[xx]) \n\t"
"lhu $t5, 10(%[xx]) \n\t"
"lhu $t6, 12(%[xx]) \n\t"
"lhu $t7, 14(%[xx]) \n\t"
"lbux $t0, $t0(%[srcAddr]) \n\t"
"lbux $t1, $t1(%[srcAddr]) \n\t"
"lbux $t2, $t2(%[srcAddr]) \n\t"
"lbux $t3, $t3(%[srcAddr]) \n\t"
"lbux $t4, $t4(%[srcAddr]) \n\t"
"lbux $t5, $t5(%[srcAddr]) \n\t"
"lbux $t6, $t6(%[srcAddr]) \n\t"
"lbux $t7, $t7(%[srcAddr]) \n\t"
"addu $t0, $t0, $t0 \n\t"
"addu $t1, $t1, $t1 \n\t"
"addu $t2, $t2, $t2 \n\t"
"addu $t3, $t3, $t3 \n\t"
"addu $t4, $t4, $t4 \n\t"
"addu $t5, $t5, $t5 \n\t"
"addu $t6, $t6, $t6 \n\t"
"addu $t7, $t7, $t7 \n\t"
"lhx $t0, $t0(%[table]) \n\t"
"lhx $t1, $t1(%[table]) \n\t"
"lhx $t2, $t2(%[table]) \n\t"
"lhx $t3, $t3(%[table]) \n\t"
"lhx $t4, $t4(%[table]) \n\t"
"lhx $t5, $t5(%[table]) \n\t"
"lhx $t6, $t6(%[table]) \n\t"
"lhx $t7, $t7(%[table]) \n\t"
"sh $t0, 0(%[colors]) \n\t"
"sh $t1, 2(%[colors]) \n\t"
"sh $t2, 4(%[colors]) \n\t"
"sh $t3, 6(%[colors]) \n\t"
"sh $t4, 8(%[colors]) \n\t"
"sh $t5, 10(%[colors]) \n\t"
"sh $t6, 12(%[colors]) \n\t"
"sh $t7, 14(%[colors]) \n\t"
"addiu %[xx], %[xx], 16 \n\t"
"addiu %[colors], %[colors], 16 \n\t"
"3: \n\t"
".set pop \n\t"
: [xx]"+r"(xx), [count8]"=&r"(count8), [colors]"+r"(colors)
: [table]"r"(table), [srcAddr]"r"(srcAddr), [count]"r"(count)
: "memory","t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"
);
for (int i = (count & 7); i > 0; --i) {
src = srcAddr[*xx++]; *colors++ = table[src];
}
}
}
static void SI8_opaque_D32_nofilter_DX_mips_dsp(const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count, SkPMColor* SK_RESTRICT colors) {
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fInvType <= (SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask));
SkASSERT(kNone_SkFilterQuality == s.fFilterLevel);
const SkPMColor* SK_RESTRICT table = s.fPixmap.ctable()->readColors();
const uint8_t* SK_RESTRICT srcAddr = (const uint8_t*)s.fPixmap.addr();
srcAddr = (const uint8_t*)((const char*)srcAddr + xy[0] * s.fPixmap.rowBytes());
if (1 == s.fPixmap.width()) {
uint8_t src = srcAddr[0];
SkPMColor dstValue = table[src];
sk_memset32(colors, dstValue, count);
} else {
const uint16_t* xx = (const uint16_t*)(xy + 1);
int s0, s1, s2, s3, s4, s5, s6, s7;
__asm__ volatile (
".set push \n\t"
".set noreorder \n\t"
".set noat \n\t"
"srl $t8, %[count], 4 \n\t"
"beqz $t8, 3f \n\t"
" nop \n\t"
"1: \n\t"
"addiu $t8, $t8, -1 \n\t"
"beqz $t8, 2f \n\t"
" addiu %[count], %[count], -16 \n\t"
"pref 0, 32(%[xx]) \n\t"
"lhu $t0, 0(%[xx]) \n\t"
"lhu $t1, 2(%[xx]) \n\t"
"lhu $t2, 4(%[xx]) \n\t"
"lhu $t3, 6(%[xx]) \n\t"
"lhu $t4, 8(%[xx]) \n\t"
"lhu $t5, 10(%[xx]) \n\t"
"lhu $t6, 12(%[xx]) \n\t"
"lhu $t7, 14(%[xx]) \n\t"
"lhu %[s0], 16(%[xx]) \n\t"
"lhu %[s1], 18(%[xx]) \n\t"
"lhu %[s2], 20(%[xx]) \n\t"
"lhu %[s3], 22(%[xx]) \n\t"
"lhu %[s4], 24(%[xx]) \n\t"
"lhu %[s5], 26(%[xx]) \n\t"
"lhu %[s6], 28(%[xx]) \n\t"
"lhu %[s7], 30(%[xx]) \n\t"
"lbux $t0, $t0(%[srcAddr]) \n\t"
"lbux $t1, $t1(%[srcAddr]) \n\t"
"lbux $t2, $t2(%[srcAddr]) \n\t"
"lbux $t3, $t3(%[srcAddr]) \n\t"
"lbux $t4, $t4(%[srcAddr]) \n\t"
"lbux $t5, $t5(%[srcAddr]) \n\t"
"lbux $t6, $t6(%[srcAddr]) \n\t"
"lbux $t7, $t7(%[srcAddr]) \n\t"
"lbux %[s0], %[s0](%[srcAddr]) \n\t"
"lbux %[s1], %[s1](%[srcAddr]) \n\t"
"lbux %[s2], %[s2](%[srcAddr]) \n\t"
"lbux %[s3], %[s3](%[srcAddr]) \n\t"
"lbux %[s4], %[s4](%[srcAddr]) \n\t"
"lbux %[s5], %[s5](%[srcAddr]) \n\t"
"lbux %[s6], %[s6](%[srcAddr]) \n\t"
"lbux %[s7], %[s7](%[srcAddr]) \n\t"
"sll $t0, $t0, 2 \n\t"
"sll $t1, $t1, 2 \n\t"
"sll $t2, $t2, 2 \n\t"
"sll $t3, $t3, 2 \n\t"
"sll $t4, $t4, 2 \n\t"
"sll $t5, $t5, 2 \n\t"
"sll $t6, $t6, 2 \n\t"
"sll $t7, $t7, 2 \n\t"
"sll %[s0], %[s0], 2 \n\t"
"sll %[s1], %[s1], 2 \n\t"
"sll %[s2], %[s2], 2 \n\t"
"sll %[s3], %[s3], 2 \n\t"
"sll %[s4], %[s4], 2 \n\t"
"sll %[s5], %[s5], 2 \n\t"
"sll %[s6], %[s6], 2 \n\t"
"sll %[s7], %[s7], 2 \n\t"
"pref 0, 64(%[table]) \n\t"
"lwx $t0, $t0(%[table]) \n\t"
"lwx $t1, $t1(%[table]) \n\t"
"lwx $t2, $t2(%[table]) \n\t"
"lwx $t3, $t3(%[table]) \n\t"
"lwx $t4, $t4(%[table]) \n\t"
"lwx $t5, $t5(%[table]) \n\t"
"lwx $t6, $t6(%[table]) \n\t"
"lwx $t7, $t7(%[table]) \n\t"
"lwx %[s0], %[s0](%[table]) \n\t"
"lwx %[s1], %[s1](%[table]) \n\t"
"lwx %[s2], %[s2](%[table]) \n\t"
"lwx %[s3], %[s3](%[table]) \n\t"
"lwx %[s4], %[s4](%[table]) \n\t"
"lwx %[s5], %[s5](%[table]) \n\t"
"lwx %[s6], %[s6](%[table]) \n\t"
"lwx %[s7], %[s7](%[table]) \n\t"
"pref 30, 64(%[colors]) \n\t"
"sw $t0, 0(%[colors]) \n\t"
"sw $t1, 4(%[colors]) \n\t"
"sw $t2, 8(%[colors]) \n\t"
"sw $t3, 12(%[colors]) \n\t"
"sw $t4, 16(%[colors]) \n\t"
"sw $t5, 20(%[colors]) \n\t"
"sw $t6, 24(%[colors]) \n\t"
"sw $t7, 28(%[colors]) \n\t"
"sw %[s0], 32(%[colors]) \n\t"
"sw %[s1], 36(%[colors]) \n\t"
"sw %[s2], 40(%[colors]) \n\t"
"sw %[s3], 44(%[colors]) \n\t"
"sw %[s4], 48(%[colors]) \n\t"
"sw %[s5], 52(%[colors]) \n\t"
"sw %[s6], 56(%[colors]) \n\t"
"sw %[s7], 60(%[colors]) \n\t"
"addiu %[xx], %[xx], 32 \n\t"
"b 1b \n\t"
" addiu %[colors], %[colors], 64 \n\t"
"2: \n\t"
"lhu $t0, 0(%[xx]) \n\t"
"lhu $t1, 2(%[xx]) \n\t"
"lhu $t2, 4(%[xx]) \n\t"
"lhu $t3, 6(%[xx]) \n\t"
"lhu $t4, 8(%[xx]) \n\t"
"lhu $t5, 10(%[xx]) \n\t"
"lhu $t6, 12(%[xx]) \n\t"
"lhu $t7, 14(%[xx]) \n\t"
"lhu %[s0], 16(%[xx]) \n\t"
"lhu %[s1], 18(%[xx]) \n\t"
"lhu %[s2], 20(%[xx]) \n\t"
"lhu %[s3], 22(%[xx]) \n\t"
"lhu %[s4], 24(%[xx]) \n\t"
"lhu %[s5], 26(%[xx]) \n\t"
"lhu %[s6], 28(%[xx]) \n\t"
"lhu %[s7], 30(%[xx]) \n\t"
"lbux $t0, $t0(%[srcAddr]) \n\t"
"lbux $t1, $t1(%[srcAddr]) \n\t"
"lbux $t2, $t2(%[srcAddr]) \n\t"
"lbux $t3, $t3(%[srcAddr]) \n\t"
"lbux $t4, $t4(%[srcAddr]) \n\t"
"lbux $t5, $t5(%[srcAddr]) \n\t"
"lbux $t6, $t6(%[srcAddr]) \n\t"
"lbux $t7, $t7(%[srcAddr]) \n\t"
"lbux %[s0], %[s0](%[srcAddr]) \n\t"
"lbux %[s1], %[s1](%[srcAddr]) \n\t"
"lbux %[s2], %[s2](%[srcAddr]) \n\t"
"lbux %[s3], %[s3](%[srcAddr]) \n\t"
"lbux %[s4], %[s4](%[srcAddr]) \n\t"
"lbux %[s5], %[s5](%[srcAddr]) \n\t"
"lbux %[s6], %[s6](%[srcAddr]) \n\t"
"lbux %[s7], %[s7](%[srcAddr]) \n\t"
"sll $t0, $t0, 2 \n\t"
"sll $t1, $t1, 2 \n\t"
"sll $t2, $t2, 2 \n\t"
"sll $t3, $t3, 2 \n\t"
"sll $t4, $t4, 2 \n\t"
"sll $t5, $t5, 2 \n\t"
"sll $t6, $t6, 2 \n\t"
"sll $t7, $t7, 2 \n\t"
"sll %[s0], %[s0], 2 \n\t"
"sll %[s1], %[s1], 2 \n\t"
"sll %[s2], %[s2], 2 \n\t"
"sll %[s3], %[s3], 2 \n\t"
"sll %[s4], %[s4], 2 \n\t"
"sll %[s5], %[s5], 2 \n\t"
"sll %[s6], %[s6], 2 \n\t"
"sll %[s7], %[s7], 2 \n\t"
"lwx $t0, $t0(%[table]) \n\t"
"lwx $t1, $t1(%[table]) \n\t"
"lwx $t2, $t2(%[table]) \n\t"
"lwx $t3, $t3(%[table]) \n\t"
"lwx $t4, $t4(%[table]) \n\t"
"lwx $t5, $t5(%[table]) \n\t"
"lwx $t6, $t6(%[table]) \n\t"
"lwx $t7, $t7(%[table]) \n\t"
"lwx %[s0], %[s0](%[table]) \n\t"
"lwx %[s1], %[s1](%[table]) \n\t"
"lwx %[s2], %[s2](%[table]) \n\t"
"lwx %[s3], %[s3](%[table]) \n\t"
"lwx %[s4], %[s4](%[table]) \n\t"
"lwx %[s5], %[s5](%[table]) \n\t"
"lwx %[s6], %[s6](%[table]) \n\t"
"lwx %[s7], %[s7](%[table]) \n\t"
"sw $t0, 0(%[colors]) \n\t"
"sw $t1, 4(%[colors]) \n\t"
"sw $t2, 8(%[colors]) \n\t"
"sw $t3, 12(%[colors]) \n\t"
"sw $t4, 16(%[colors]) \n\t"
"sw $t5, 20(%[colors]) \n\t"
"sw $t6, 24(%[colors]) \n\t"
"sw $t7, 28(%[colors]) \n\t"
"sw %[s0], 32(%[colors]) \n\t"
"sw %[s1], 36(%[colors]) \n\t"
"sw %[s2], 40(%[colors]) \n\t"
"sw %[s3], 44(%[colors]) \n\t"
"sw %[s4], 48(%[colors]) \n\t"
"sw %[s5], 52(%[colors]) \n\t"
"sw %[s6], 56(%[colors]) \n\t"
"sw %[s7], 60(%[colors]) \n\t"
"addiu %[xx], %[xx], 32 \n\t"
"beqz %[count], 4f \n\t"
" addiu %[colors], %[colors], 64 \n\t"
"3: \n\t"
"addiu %[count], %[count], -1 \n\t"
"lhu $t0, 0(%[xx]) \n\t"
"lbux $t1, $t0(%[srcAddr]) \n\t"
"sll $t1, $t1, 2 \n\t"
"lwx $t2, $t1(%[table]) \n\t"
"sw $t2, 0(%[colors]) \n\t"
"addiu %[xx], %[xx], 2 \n\t"
"bnez %[count], 3b \n\t"
" addiu %[colors], %[colors], 4 \n\t"
"4: \n\t"
".set pop \n\t"
: [xx]"+r"(xx), [count]"+r"(count), [colors]"+r"(colors),
[s0]"=&r"(s0), [s1]"=&r"(s1), [s2]"=&r"(s2), [s3]"=&r"(s3),
[s4]"=&r"(s4), [s5]"=&r"(s5), [s6]"=&r"(s6), [s7]"=&r"(s7)
: [table]"r"(table), [srcAddr]"r"(srcAddr)
: "memory", "t0", "t1", "t2", "t3",
"t4", "t5", "t6", "t7", "t8"
);
}
}
/* If we replace a sampleproc, then we null-out the associated shaderproc,
otherwise the shader won't even look at the matrix/sampler
*/
void SkBitmapProcState::platformProcs() {
bool isOpaque = 256 == fAlphaScale;
bool justDx = false;
if (fInvType <= (SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask)) {
justDx = true;
}
switch (fPixmap.colorType()) {
case kIndex_8_SkColorType:
if (justDx && kNone_SkFilterQuality == fFilterLevel) {
fSampleProc16 = SI8_D16_nofilter_DX_mips_dsp;
fShaderProc16 = NULL;
if (isOpaque) {
fSampleProc32 = SI8_opaque_D32_nofilter_DX_mips_dsp;
fShaderProc32 = NULL;
}
}
break;
default:
break;
}
}
void SkBitmapScaler::PlatformConvolutionProcs(SkConvolutionProcs*) {}
```
|
Anna Ivey is a published author and nationally known graduate school admissions counselor at her own firm, Anna Ivey Admissions Counseling.
She is the author of The Ivey Guide to Law School Admissions, published by Harcourt.
In the past, she was Dean of Admissions at University of Chicago Law School. She has been interviewed in The New York Times, The Wall Street Journal, and the Chicago Sun-Times. She has also been a guest on numerous radio stations.
Ivey received her B.A. from Columbia University, and spent her junior year at the University of Cambridge. She received her J.D. from the University of Chicago Law School. in 1997.
References
External links
Living people
Year of birth missing (living people)
University of Chicago faculty
American legal writers
Columbia University alumni
Place of birth missing (living people)
American legal scholars
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.