text
stringlengths 2
100k
| meta
dict |
---|---|
{
let a := mload(0)
mstore(0, sub(a, a))
}
// ----
// step: fullSimplify
//
// { mstore(0, 0) }
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Generated on Wed, Apr 19, 2017 07:44+1000 for FHIR v3.0.1
Note: the schemas & schematrons do not contain all of the rules about what makes resources
valid. Implementers will still need to be familiar with the content of the specification and with
any profiles that apply to the resources in order to make a conformant implementation.
-->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://hl7.org/fhir" xmlns:xhtml="http://www.w3.org/1999/xhtml" targetNamespace="http://hl7.org/fhir" elementFormDefault="qualified" version="1.0">
<xs:include schemaLocation="fhir-base.xsd"/>
<xs:element name="AppointmentResponse" type="AppointmentResponse">
<xs:annotation>
<xs:documentation xml:lang="en">A reply to an appointment request for a patient and/or practitioner(s), such as a confirmation or rejection.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:complexType name="AppointmentResponse">
<xs:annotation>
<xs:documentation xml:lang="en">A reply to an appointment request for a patient and/or practitioner(s), such as a confirmation or rejection.</xs:documentation>
<xs:documentation xml:lang="en">If the element is present, it must have either a @value, an @id, or extensions</xs:documentation>
</xs:annotation>
<xs:complexContent>
<xs:extension base="DomainResource">
<xs:sequence>
<xs:element name="identifier" minOccurs="0" maxOccurs="unbounded" type="Identifier">
<xs:annotation>
<xs:documentation xml:lang="en">This records identifiers associated with this appointment response concern that are defined by business processes and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="appointment" minOccurs="1" maxOccurs="1" type="Reference">
<xs:annotation>
<xs:documentation xml:lang="en">Appointment that this response is replying to.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="start" minOccurs="0" maxOccurs="1" type="instant">
<xs:annotation>
<xs:documentation xml:lang="en">Date/Time that the appointment is to take place, or requested new start time.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="end" minOccurs="0" maxOccurs="1" type="instant">
<xs:annotation>
<xs:documentation xml:lang="en">This may be either the same as the appointment request to confirm the details of the appointment, or alternately a new time to request a re-negotiation of the end time.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="participantType" minOccurs="0" maxOccurs="unbounded" type="CodeableConcept">
<xs:annotation>
<xs:documentation xml:lang="en">Role of participant in the appointment.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="actor" minOccurs="0" maxOccurs="1" type="Reference">
<xs:annotation>
<xs:documentation xml:lang="en">A Person, Location/HealthcareService or Device that is participating in the appointment.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="participantStatus" minOccurs="1" maxOccurs="1" type="ParticipationStatus">
<xs:annotation>
<xs:documentation xml:lang="en">Participation status of the participant. When the status is declined or tentative if the start/end times are different to the appointment, then these times should be interpreted as a requested time change. When the status is accepted, the times can either be the time of the appointment (as a confirmation of the time) or can be empty.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="comment" minOccurs="0" maxOccurs="1" type="string">
<xs:annotation>
<xs:documentation xml:lang="en">Additional comments about the appointment.</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from collab.server import CollabServer
def main(argv):
if len(argv) == 1:
if ':' not in argv[0]:
sys.stderr.write("please provide `host:port' to bind or just `host:' for default port\n")
return -2
else:
host, port = argv[0].split(':', 1)
elif len(argv) == 2:
host,port = [x.strip() for x in argv]
elif len(argv) > 2:
sys.stderr.write("use `host:port' arguments\n")
return -3
else:
host, port = '', ''
if host == '':
host = '0.0.0.0'
if port == '':
port = 6633
try:
sys.stderr.write('Starting at ' + host +':' + str(port) + '...')
server = CollabServer({'host':host, 'port': int(port)})
sys.stderr.write(' started.\n')
server.run_forever()
except KeyboardInterrupt:
sys.stderr.write("^C received, server stopped")
return -1
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| {
"pile_set_name": "Github"
} |
/*
* Command line execution tool. Useful for test cases and manual testing.
*
* To enable linenoise and other fancy stuff, compile with -DDUK_CMDLINE_FANCY.
* It is not the default to maximize portability. You can also compile in
* support for example allocators, grep for DUK_CMDLINE_*.
*/
/* Helper define to enable a feature set; can also use separate defines. */
#if defined(DUK_CMDLINE_FANCY)
#define DUK_CMDLINE_LINENOISE
#define DUK_CMDLINE_LINENOISE_COMPLETION
#define DUK_CMDLINE_RLIMIT
#define DUK_CMDLINE_SIGNAL
#endif
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || \
defined(WIN64) || defined(_WIN64) || defined(__WIN64__)
/* Suppress warnings about plain fopen() etc. */
#define _CRT_SECURE_NO_WARNINGS
#if defined(_MSC_VER) && (_MSC_VER < 1900)
/* Workaround for snprintf() missing in older MSVC versions.
* Note that _snprintf() may not NUL terminate the string, but
* this difference does not matter here as a NUL terminator is
* always explicitly added.
*/
#define snprintf _snprintf
#endif
#endif
#define GREET_CODE(variant) \
"print('((o) Duktape" variant " ' + " \
"Math.floor(Duktape.version / 10000) + '.' + " \
"Math.floor(Duktape.version / 100) % 100 + '.' + " \
"Duktape.version % 100" \
", '(" DUK_GIT_DESCRIBE ")');"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(DUK_CMDLINE_SIGNAL)
#include <signal.h>
#endif
#if defined(DUK_CMDLINE_RLIMIT)
#include <sys/resource.h>
#endif
#if defined(DUK_CMDLINE_LINENOISE)
#include "linenoise.h"
#endif
#if defined(DUK_CMDLINE_FILEIO)
#include <errno.h>
#endif
#if defined(EMSCRIPTEN)
#include <emscripten.h>
#endif
#if defined(DUK_CMDLINE_ALLOC_LOGGING)
#include "duk_alloc_logging.h"
#endif
#if defined(DUK_CMDLINE_ALLOC_TORTURE)
#include "duk_alloc_torture.h"
#endif
#if defined(DUK_CMDLINE_ALLOC_HYBRID)
#include "duk_alloc_hybrid.h"
#endif
#include "duktape.h"
#if defined(DUK_CMDLINE_AJSHEAP)
/* Defined in duk_cmdline_ajduk.c or alljoyn.js headers. */
void ajsheap_init(void);
void ajsheap_free(void);
void ajsheap_dump(void);
void ajsheap_register(duk_context *ctx);
void ajsheap_start_exec_timeout(void);
void ajsheap_clear_exec_timeout(void);
void *ajsheap_alloc_wrapped(void *udata, duk_size_t size);
void *ajsheap_realloc_wrapped(void *udata, void *ptr, duk_size_t size);
void ajsheap_free_wrapped(void *udata, void *ptr);
void *AJS_Alloc(void *udata, duk_size_t size);
void *AJS_Realloc(void *udata, void *ptr, duk_size_t size);
void AJS_Free(void *udata, void *ptr);
#endif
#if defined(DUK_CMDLINE_DEBUGGER_SUPPORT)
#include "duk_trans_socket.h"
#endif
#define MEM_LIMIT_NORMAL (128*1024*1024) /* 128 MB */
#define MEM_LIMIT_HIGH (2047*1024*1024) /* ~2 GB */
#define LINEBUF_SIZE 65536
static int main_argc = 0;
static char **main_argv = NULL;
static int interactive_mode = 0;
#if defined(DUK_CMDLINE_DEBUGGER_SUPPORT)
static int debugger_reattach = 0;
#endif
/*
* Misc helpers
*/
#if defined(DUK_CMDLINE_RLIMIT)
static void set_resource_limits(rlim_t mem_limit_value) {
int rc;
struct rlimit lim;
rc = getrlimit(RLIMIT_AS, &lim);
if (rc != 0) {
fprintf(stderr, "Warning: cannot read RLIMIT_AS\n");
return;
}
if (lim.rlim_max < mem_limit_value) {
fprintf(stderr, "Warning: rlim_max < mem_limit_value (%d < %d)\n", (int) lim.rlim_max, (int) mem_limit_value);
return;
}
lim.rlim_cur = mem_limit_value;
lim.rlim_max = mem_limit_value;
rc = setrlimit(RLIMIT_AS, &lim);
if (rc != 0) {
fprintf(stderr, "Warning: setrlimit failed\n");
return;
}
#if 0
fprintf(stderr, "Set RLIMIT_AS to %d\n", (int) mem_limit_value);
#endif
}
#endif /* DUK_CMDLINE_RLIMIT */
#if defined(DUK_CMDLINE_SIGNAL)
static void my_sighandler(int x) {
fprintf(stderr, "Got signal %d\n", x);
fflush(stderr);
}
static void set_sigint_handler(void) {
(void) signal(SIGINT, my_sighandler);
(void) signal(SIGPIPE, SIG_IGN); /* avoid SIGPIPE killing process */
}
#endif /* DUK_CMDLINE_SIGNAL */
static int get_stack_raw(duk_context *ctx) {
if (!duk_is_object(ctx, -1)) {
return 1;
}
if (!duk_has_prop_string(ctx, -1, "stack")) {
return 1;
}
if (!duk_is_error(ctx, -1)) {
/* Not an Error instance, don't read "stack". */
return 1;
}
duk_get_prop_string(ctx, -1, "stack"); /* caller coerces */
duk_remove(ctx, -2);
return 1;
}
/* Print error to stderr and pop error. */
static void print_pop_error(duk_context *ctx, FILE *f) {
/* Print error objects with a stack trace specially.
* Note that getting the stack trace may throw an error
* so this also needs to be safe call wrapped.
*/
(void) duk_safe_call(ctx, get_stack_raw, 1 /*nargs*/, 1 /*nrets*/);
fprintf(f, "%s\n", duk_safe_to_string(ctx, -1));
fflush(f);
duk_pop(ctx);
}
static int wrapped_compile_execute(duk_context *ctx) {
const char *src_data;
duk_size_t src_len;
int comp_flags;
/* XXX: Here it'd be nice to get some stats for the compilation result
* when a suitable command line is given (e.g. code size, constant
* count, function count. These are available internally but not through
* the public API.
*/
/* Use duk_compile_lstring_filename() variant which avoids interning
* the source code. This only really matters for low memory environments.
*/
/* [ ... bytecode_filename src_data src_len filename ] */
src_data = (const char *) duk_require_pointer(ctx, -3);
src_len = (duk_size_t) duk_require_uint(ctx, -2);
if (src_data != NULL && src_len >= 2 && src_data[0] == (char) 0xff) {
/* Bytecode. */
duk_push_lstring(ctx, src_data, src_len);
duk_to_buffer(ctx, -1, NULL);
duk_load_function(ctx);
} else {
/* Source code. */
comp_flags = 0;
duk_compile_lstring_filename(ctx, comp_flags, src_data, src_len);
}
/* [ ... bytecode_filename src_data src_len function ] */
/* Optional bytecode dump. */
if (duk_is_string(ctx, -4)) {
FILE *f;
void *bc_ptr;
duk_size_t bc_len;
size_t wrote;
char fnbuf[256];
const char *filename;
duk_dup_top(ctx);
duk_dump_function(ctx);
bc_ptr = duk_require_buffer(ctx, -1, &bc_len);
filename = duk_require_string(ctx, -5);
#if defined(EMSCRIPTEN)
if (filename[0] == '/') {
snprintf(fnbuf, sizeof(fnbuf), "%s", filename);
} else {
snprintf(fnbuf, sizeof(fnbuf), "/working/%s", filename);
}
#else
snprintf(fnbuf, sizeof(fnbuf), "%s", filename);
#endif
fnbuf[sizeof(fnbuf) - 1] = (char) 0;
f = fopen(fnbuf, "wb");
if (!f) {
duk_error(ctx, DUK_ERR_ERROR, "failed to open bytecode output file");
}
wrote = fwrite(bc_ptr, 1, (size_t) bc_len, f); /* XXX: handle partial writes */
(void) fclose(f);
if (wrote != bc_len) {
duk_error(ctx, DUK_ERR_ERROR, "failed to write all bytecode");
}
return 0; /* duk_safe_call() cleans up */
}
#if 0
/* Manual test for bytecode dump/load cycle: dump and load before
* execution. Enable manually, then run "make qecmatest" for a
* reasonably good coverage of different functions and programs.
*/
duk_dump_function(ctx);
duk_load_function(ctx);
#endif
#if defined(DUK_CMDLINE_AJSHEAP)
ajsheap_start_exec_timeout();
#endif
duk_push_global_object(ctx); /* 'this' binding */
duk_call_method(ctx, 0);
#if defined(DUK_CMDLINE_AJSHEAP)
ajsheap_clear_exec_timeout();
#endif
if (interactive_mode) {
/*
* In interactive mode, write to stdout so output won't
* interleave as easily.
*
* NOTE: the ToString() coercion may fail in some cases;
* for instance, if you evaluate:
*
* ( {valueOf: function() {return {}},
* toString: function() {return {}}});
*
* The error is:
*
* TypeError: failed to coerce with [[DefaultValue]]
* duk_api.c:1420
*
* These are handled now by the caller which also has stack
* trace printing support. User code can print out errors
* safely using duk_safe_to_string().
*/
fprintf(stdout, "= %s\n", duk_to_string(ctx, -1));
fflush(stdout);
} else {
/* In non-interactive mode, success results are not written at all.
* It is important that the result value is not string coerced,
* as the string coercion may cause an error in some cases.
*/
}
return 0; /* duk_safe_call() cleans up */
}
/*
* Minimal Linenoise completion support
*/
#if defined(DUK_CMDLINE_LINENOISE_COMPLETION)
static duk_context *completion_ctx;
static int completion_idpart(unsigned char c) {
/* Very simplified "is identifier part" check. */
if ((c >= (unsigned char) 'a' && c <= (unsigned char) 'z') ||
(c >= (unsigned char) 'A' && c <= (unsigned char) 'Z') ||
(c >= (unsigned char) '0' && c <= (unsigned char) '9') ||
c == (unsigned char) '$' || c == (unsigned char) '_') {
return 1;
}
return 0;
}
static int completion_digit(unsigned char c) {
return (c >= (unsigned char) '0' && c <= (unsigned char) '9');
}
static duk_ret_t linenoise_completion_lookup(duk_context *ctx) {
duk_size_t len;
const char *orig;
const unsigned char *p;
const unsigned char *p_curr;
const unsigned char *p_end;
const char *key;
const char *prefix;
linenoiseCompletions *lc;
duk_idx_t idx_obj;
orig = duk_require_string(ctx, -3);
p_curr = (const unsigned char *) duk_require_lstring(ctx, -2, &len);
p_end = p_curr + len;
lc = duk_require_pointer(ctx, -1);
duk_push_global_object(ctx);
idx_obj = duk_require_top_index(ctx);
while (p_curr <= p_end) {
/* p_curr == p_end allowed on purpose, to handle 'Math.' for example. */
p = p_curr;
while (p < p_end && p[0] != (unsigned char) '.') {
p++;
}
/* 'p' points to a NUL (p == p_end) or a period. */
prefix = duk_push_lstring(ctx, (const char *) p_curr, (duk_size_t) (p - p_curr));
#if 0
fprintf(stderr, "Completion check: '%s'\n", prefix);
fflush(stderr);
#endif
if (p == p_end) {
/* 'idx_obj' points to the object matching the last
* full component, use [p_curr,p[ as a filter for
* that object.
*/
duk_enum(ctx, idx_obj, DUK_ENUM_INCLUDE_NONENUMERABLE);
while (duk_next(ctx, -1, 0 /*get_value*/)) {
key = duk_get_string(ctx, -1);
#if 0
fprintf(stderr, "Key: %s\n", key ? key : "");
fflush(stderr);
#endif
if (!key) {
/* Should never happen, just in case. */
goto next;
}
/* Ignore array index keys: usually not desirable, and would
* also require ['0'] quoting.
*/
if (completion_digit(key[0])) {
goto next;
}
/* XXX: There's no key quoting now, it would require replacing the
* last component with a ['foo\nbar'] style lookup when appropriate.
*/
if (strlen(prefix) == 0) {
/* Partial ends in a period, e.g. 'Math.' -> complete all Math properties. */
duk_push_string(ctx, orig); /* original, e.g. 'Math.' */
duk_push_string(ctx, key);
duk_concat(ctx, 2);
linenoiseAddCompletion(lc, duk_require_string(ctx, -1));
duk_pop(ctx);
} else if (prefix && strcmp(key, prefix) == 0) {
/* Full completion, add a period, e.g. input 'Math' -> 'Math.'. */
duk_push_string(ctx, orig); /* original, including partial last component */
duk_push_string(ctx, ".");
duk_concat(ctx, 2);
linenoiseAddCompletion(lc, duk_require_string(ctx, -1));
duk_pop(ctx);
} else if (prefix && strncmp(key, prefix, strlen(prefix)) == 0) {
/* Last component is partial, complete. */
duk_push_string(ctx, orig); /* original, including partial last component */
duk_push_string(ctx, key + strlen(prefix)); /* completion to last component */
duk_concat(ctx, 2);
linenoiseAddCompletion(lc, duk_require_string(ctx, -1));
duk_pop(ctx);
}
next:
duk_pop(ctx);
}
return 0;
} else {
if (duk_get_prop(ctx, idx_obj)) {
duk_to_object(ctx, -1); /* for properties of plain strings etc */
duk_replace(ctx, idx_obj);
p_curr = p + 1;
} else {
/* Not found. */
return 0;
}
}
}
return 0;
}
static void linenoise_completion(const char *buf, linenoiseCompletions *lc) {
duk_context *ctx;
const unsigned char *p_start;
const unsigned char *p_end;
const unsigned char *p;
duk_int_t rc;
if (!buf) {
return;
}
ctx = completion_ctx;
if (!ctx) {
return;
}
p_start = (const unsigned char *) buf;
p_end = (const unsigned char *) (buf + strlen(buf));
p = p_end;
/* Scan backwards for a maximal string which looks like a property
* chain (e.g. foo.bar.quux).
*/
while (--p >= p_start) {
if (p[0] == (unsigned char) '.') {
if (p <= p_start) {
break;
}
if (!completion_idpart(p[-1])) {
/* Catches e.g. 'foo..bar' -> we want 'bar' only. */
break;
}
} else if (!completion_idpart(p[0])) {
break;
}
}
/* 'p' will either be p_start - 1 (ran out of buffer) or point to
* the first offending character.
*/
p++;
if (p < p_start || p >= p_end) {
return; /* should never happen, but just in case */
}
/* 'p' now points to a string of the form 'foo.bar.quux'. Look up
* all the components except the last; treat the last component as
* a partial name which is used as a filter for the previous full
* component. All lookups are from the global object now.
*/
#if 0
fprintf(stderr, "Completion starting point: '%s'\n", p);
fflush(stderr);
#endif
duk_push_string(ctx, (const char *) buf);
duk_push_lstring(ctx, (const char *) p, (duk_size_t) (p_end - p));
duk_push_pointer(ctx, (void *) lc);
rc = duk_safe_call(ctx, linenoise_completion_lookup, 3 /*nargs*/, 1 /*nrets*/);
if (rc != DUK_EXEC_SUCCESS) {
fprintf(stderr, "Completion handling failure: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);
}
#endif /* DUK_CMDLINE_LINENOISE_COMPLETION */
/*
* Execute from file handle etc
*/
static int handle_fh(duk_context *ctx, FILE *f, const char *filename, const char *bytecode_filename) {
char *buf = NULL;
size_t bufsz;
size_t bufoff;
size_t got;
int rc;
int retval = -1;
buf = (char *) malloc(1024);
if (!buf) {
goto error;
}
bufsz = 1024;
bufoff = 0;
/* Read until EOF, avoid fseek/stat because it won't work with stdin. */
for (;;) {
size_t avail;
avail = bufsz - bufoff;
if (avail < 1024) {
size_t newsz;
char *buf_new;
#if 0
fprintf(stderr, "resizing read buffer: %ld -> %ld\n", (long) bufsz, (long) (bufsz * 2));
#endif
newsz = bufsz + (bufsz >> 2) + 1024; /* +25% and some extra */
buf_new = (char *) realloc(buf, newsz);
if (!buf_new) {
goto error;
}
buf = buf_new;
bufsz = newsz;
}
avail = bufsz - bufoff;
#if 0
fprintf(stderr, "reading input: buf=%p bufsz=%ld bufoff=%ld avail=%ld\n",
(void *) buf, (long) bufsz, (long) bufoff, (long) avail);
#endif
got = fread((void *) (buf + bufoff), (size_t) 1, avail, f);
#if 0
fprintf(stderr, "got=%ld\n", (long) got);
#endif
if (got == 0) {
break;
}
bufoff += got;
/* Emscripten specific: stdin EOF doesn't work as expected.
* Instead, when 'emduk' is executed using Node.js, a file
* piped to stdin repeats (!). Detect that repeat and cut off
* the stdin read. Ensure the loop repeats enough times to
* avoid detecting spurious loops.
*
* This only seems to work for inputs up to 256 bytes long.
*/
#if defined(EMSCRIPTEN)
if (bufoff >= 16384) {
size_t i, j, nloops;
int looped = 0;
for (i = 16; i < bufoff / 8; i++) {
int ok;
nloops = bufoff / i;
ok = 1;
for (j = 1; j < nloops; j++) {
if (memcmp((void *) buf, (void *) (buf + i * j), i) != 0) {
ok = 0;
break;
}
}
if (ok) {
fprintf(stderr, "emscripten workaround: detect looping at index %ld, verified with %ld loops\n", (long) i, (long) (nloops - 1));
bufoff = i;
looped = 1;
break;
}
}
if (looped) {
break;
}
}
#endif
}
duk_push_string(ctx, bytecode_filename);
duk_push_pointer(ctx, (void *) buf);
duk_push_uint(ctx, (duk_uint_t) bufoff);
duk_push_string(ctx, filename);
interactive_mode = 0; /* global */
rc = duk_safe_call(ctx, wrapped_compile_execute, 4 /*nargs*/, 1 /*nret*/);
#if defined(DUK_CMDLINE_AJSHEAP)
ajsheap_clear_exec_timeout();
#endif
free(buf);
buf = NULL;
if (rc != DUK_EXEC_SUCCESS) {
print_pop_error(ctx, stderr);
goto error;
} else {
duk_pop(ctx);
retval = 0;
}
/* fall thru */
cleanup:
if (buf) {
free(buf);
buf = NULL;
}
return retval;
error:
fprintf(stderr, "error in executing file %s\n", filename);
fflush(stderr);
goto cleanup;
}
static int handle_file(duk_context *ctx, const char *filename, const char *bytecode_filename) {
FILE *f = NULL;
int retval;
char fnbuf[256];
/* Example of sending an application specific debugger notification. */
duk_push_string(ctx, "DebuggerHandleFile");
duk_push_string(ctx, filename);
duk_debugger_notify(ctx, 2);
#if defined(EMSCRIPTEN)
if (filename[0] == '/') {
snprintf(fnbuf, sizeof(fnbuf), "%s", filename);
} else {
snprintf(fnbuf, sizeof(fnbuf), "/working/%s", filename);
}
#else
snprintf(fnbuf, sizeof(fnbuf), "%s", filename);
#endif
fnbuf[sizeof(fnbuf) - 1] = (char) 0;
f = fopen(fnbuf, "rb");
if (!f) {
fprintf(stderr, "failed to open source file: %s\n", filename);
fflush(stderr);
goto error;
}
retval = handle_fh(ctx, f, filename, bytecode_filename);
fclose(f);
return retval;
error:
return -1;
}
static int handle_eval(duk_context *ctx, char *code) {
int rc;
int retval = -1;
duk_push_pointer(ctx, (void *) code);
duk_push_uint(ctx, (duk_uint_t) strlen(code));
duk_push_string(ctx, "eval");
interactive_mode = 0; /* global */
rc = duk_safe_call(ctx, wrapped_compile_execute, 3 /*nargs*/, 1 /*nret*/);
#if defined(DUK_CMDLINE_AJSHEAP)
ajsheap_clear_exec_timeout();
#endif
if (rc != DUK_EXEC_SUCCESS) {
print_pop_error(ctx, stderr);
} else {
duk_pop(ctx);
retval = 0;
}
return retval;
}
#if defined(DUK_CMDLINE_LINENOISE)
static int handle_interactive(duk_context *ctx) {
const char *prompt = "duk> ";
char *buffer = NULL;
int retval = 0;
int rc;
duk_eval_string(ctx, GREET_CODE(" [linenoise]"));
duk_pop(ctx);
linenoiseSetMultiLine(1);
linenoiseHistorySetMaxLen(64);
#if defined(DUK_CMDLINE_LINENOISE_COMPLETION)
linenoiseSetCompletionCallback(linenoise_completion);
#endif
for (;;) {
if (buffer) {
linenoiseFree(buffer);
buffer = NULL;
}
#if defined(DUK_CMDLINE_LINENOISE_COMPLETION)
completion_ctx = ctx;
#endif
buffer = linenoise(prompt);
#if defined(DUK_CMDLINE_LINENOISE_COMPLETION)
completion_ctx = NULL;
#endif
if (!buffer) {
break;
}
if (buffer && buffer[0] != (char) 0) {
linenoiseHistoryAdd(buffer);
}
duk_push_pointer(ctx, (void *) buffer);
duk_push_uint(ctx, (duk_uint_t) strlen(buffer));
duk_push_string(ctx, "input");
interactive_mode = 1; /* global */
rc = duk_safe_call(ctx, wrapped_compile_execute, 3 /*nargs*/, 1 /*nret*/);
#if defined(DUK_CMDLINE_AJSHEAP)
ajsheap_clear_exec_timeout();
#endif
if (buffer) {
linenoiseFree(buffer);
buffer = NULL;
}
if (rc != DUK_EXEC_SUCCESS) {
/* in interactive mode, write to stdout */
print_pop_error(ctx, stdout);
retval = -1; /* an error 'taints' the execution */
} else {
duk_pop(ctx);
}
}
if (buffer) {
linenoiseFree(buffer);
buffer = NULL;
}
return retval;
}
#else /* DUK_CMDLINE_LINENOISE */
static int handle_interactive(duk_context *ctx) {
const char *prompt = "duk> ";
char *buffer = NULL;
int retval = 0;
int rc;
int got_eof = 0;
duk_eval_string(ctx, GREET_CODE(""));
duk_pop(ctx);
buffer = (char *) malloc(LINEBUF_SIZE);
if (!buffer) {
fprintf(stderr, "failed to allocated a line buffer\n");
fflush(stderr);
retval = -1;
goto done;
}
while (!got_eof) {
size_t idx = 0;
fwrite(prompt, 1, strlen(prompt), stdout);
fflush(stdout);
for (;;) {
int c = fgetc(stdin);
if (c == EOF) {
got_eof = 1;
break;
} else if (c == '\n') {
break;
} else if (idx >= LINEBUF_SIZE) {
fprintf(stderr, "line too long\n");
fflush(stderr);
retval = -1;
goto done;
} else {
buffer[idx++] = (char) c;
}
}
duk_push_pointer(ctx, (void *) buffer);
duk_push_uint(ctx, (duk_uint_t) idx);
duk_push_string(ctx, "input");
interactive_mode = 1; /* global */
rc = duk_safe_call(ctx, wrapped_compile_execute, 3 /*nargs*/, 1 /*nret*/);
#if defined(DUK_CMDLINE_AJSHEAP)
ajsheap_clear_exec_timeout();
#endif
if (rc != DUK_EXEC_SUCCESS) {
/* in interactive mode, write to stdout */
print_pop_error(ctx, stdout);
retval = -1; /* an error 'taints' the execution */
} else {
duk_pop(ctx);
}
}
done:
if (buffer) {
free(buffer);
buffer = NULL;
}
return retval;
}
#endif /* DUK_CMDLINE_LINENOISE */
/*
* Simple file read/write bindings
*/
#if defined(DUK_CMDLINE_FILEIO)
static duk_ret_t fileio_read_file(duk_context *ctx) {
const char *fn;
char *buf;
size_t len;
size_t off;
int rc;
FILE *f;
fn = duk_require_string(ctx, 0);
f = fopen(fn, "rb");
if (!f) {
duk_error(ctx, DUK_ERR_TYPE_ERROR, "cannot open file %s for reading, errno %ld: %s",
fn, (long) errno, strerror(errno));
}
rc = fseek(f, 0, SEEK_END);
if (rc < 0) {
(void) fclose(f);
duk_error(ctx, DUK_ERR_TYPE_ERROR, "fseek() failed for %s, errno %ld: %s",
fn, (long) errno, strerror(errno));
}
len = (size_t) ftell(f);
rc = fseek(f, 0, SEEK_SET);
if (rc < 0) {
(void) fclose(f);
duk_error(ctx, DUK_ERR_TYPE_ERROR, "fseek() failed for %s, errno %ld: %s",
fn, (long) errno, strerror(errno));
}
buf = (char *) duk_push_fixed_buffer(ctx, (duk_size_t) len);
for (off = 0; off < len;) {
size_t got;
got = fread((void *) (buf + off), 1, len - off, f);
if (ferror(f)) {
(void) fclose(f);
duk_error(ctx, DUK_ERR_TYPE_ERROR, "error while reading %s", fn);
}
if (got == 0) {
if (feof(f)) {
break;
} else {
(void) fclose(f);
duk_error(ctx, DUK_ERR_TYPE_ERROR, "error while reading %s", fn);
}
}
off += got;
}
if (f) {
(void) fclose(f);
}
return 1;
}
static duk_ret_t fileio_write_file(duk_context *ctx) {
const char *fn;
const char *buf;
size_t len;
size_t off;
FILE *f;
fn = duk_require_string(ctx, 0);
f = fopen(fn, "wb");
if (!f) {
duk_error(ctx, DUK_ERR_TYPE_ERROR, "cannot open file %s for writing, errno %ld: %s",
fn, (long) errno, strerror(errno));
}
len = 0;
buf = (char *) duk_to_buffer(ctx, 1, &len);
for (off = 0; off < len;) {
size_t got;
got = fwrite((const void *) (buf + off), 1, len - off, f);
if (ferror(f)) {
(void) fclose(f);
duk_error(ctx, DUK_ERR_TYPE_ERROR, "error while writing %s", fn);
}
if (got == 0) {
(void) fclose(f);
duk_error(ctx, DUK_ERR_TYPE_ERROR, "error while writing %s", fn);
}
off += got;
}
if (f) {
(void) fclose(f);
}
return 0;
}
#endif /* DUK_CMDLINE_FILEIO */
/*
* Duktape heap lifecycle
*/
#if defined(DUK_CMDLINE_DEBUGGER_SUPPORT)
static duk_idx_t debugger_request(duk_context *ctx, void *udata, duk_idx_t nvalues) {
const char *cmd;
int i;
(void) udata;
if (nvalues < 1) {
duk_push_string(ctx, "missing AppRequest argument(s)");
return -1;
}
cmd = duk_get_string(ctx, -nvalues + 0);
if (cmd && strcmp(cmd, "CommandLine") == 0) {
if (!duk_check_stack(ctx, main_argc)) {
/* Callback should avoid errors for now, so use
* duk_check_stack() rather than duk_require_stack().
*/
duk_push_string(ctx, "failed to extend stack");
return -1;
}
for (i = 0; i < main_argc; i++) {
duk_push_string(ctx, main_argv[i]);
}
return main_argc;
}
duk_push_sprintf(ctx, "command not supported");
return -1;
}
static void debugger_detached(void *udata) {
duk_context *ctx = (duk_context *) udata;
(void) ctx;
fprintf(stderr, "Debugger detached, udata: %p\n", (void *) udata);
fflush(stderr);
/* Ensure socket is closed even when detach is initiated by Duktape
* rather than debug client.
*/
duk_trans_socket_finish();
if (debugger_reattach) {
/* For automatic reattach testing. */
duk_trans_socket_init();
duk_trans_socket_waitconn();
fprintf(stderr, "Debugger reconnected, call duk_debugger_attach()\n");
fflush(stderr);
#if 0
/* This is not necessary but should be harmless. */
duk_debugger_detach(ctx);
#endif
duk_debugger_attach_custom(ctx,
duk_trans_socket_read_cb,
duk_trans_socket_write_cb,
duk_trans_socket_peek_cb,
duk_trans_socket_read_flush_cb,
duk_trans_socket_write_flush_cb,
debugger_request,
debugger_detached,
(void *) ctx);
}
}
#endif
#define ALLOC_DEFAULT 0
#define ALLOC_LOGGING 1
#define ALLOC_TORTURE 2
#define ALLOC_HYBRID 3
#define ALLOC_AJSHEAP 4
static duk_context *create_duktape_heap(int alloc_provider, int debugger, int ajsheap_log) {
duk_context *ctx;
(void) ajsheap_log; /* suppress warning */
ctx = NULL;
if (!ctx && alloc_provider == ALLOC_LOGGING) {
#if defined(DUK_CMDLINE_ALLOC_LOGGING)
ctx = duk_create_heap(duk_alloc_logging,
duk_realloc_logging,
duk_free_logging,
(void *) 0xdeadbeef,
NULL);
#else
fprintf(stderr, "Warning: option --alloc-logging ignored, no logging allocator support\n");
fflush(stderr);
#endif
}
if (!ctx && alloc_provider == ALLOC_TORTURE) {
#if defined(DUK_CMDLINE_ALLOC_TORTURE)
ctx = duk_create_heap(duk_alloc_torture,
duk_realloc_torture,
duk_free_torture,
(void *) 0xdeadbeef,
NULL);
#else
fprintf(stderr, "Warning: option --alloc-torture ignored, no torture allocator support\n");
fflush(stderr);
#endif
}
if (!ctx && alloc_provider == ALLOC_HYBRID) {
#if defined(DUK_CMDLINE_ALLOC_HYBRID)
void *udata = duk_alloc_hybrid_init();
if (!udata) {
fprintf(stderr, "Failed to init hybrid allocator\n");
fflush(stderr);
} else {
ctx = duk_create_heap(duk_alloc_hybrid,
duk_realloc_hybrid,
duk_free_hybrid,
udata,
NULL);
}
#else
fprintf(stderr, "Warning: option --alloc-hybrid ignored, no hybrid allocator support\n");
fflush(stderr);
#endif
}
if (!ctx && alloc_provider == ALLOC_AJSHEAP) {
#if defined(DUK_CMDLINE_AJSHEAP)
ajsheap_init();
ctx = duk_create_heap(
ajsheap_log ? ajsheap_alloc_wrapped : AJS_Alloc,
ajsheap_log ? ajsheap_realloc_wrapped : AJS_Realloc,
ajsheap_log ? ajsheap_free_wrapped : AJS_Free,
(void *) 0xdeadbeef, /* heap_udata: ignored by AjsHeap, use as marker */
NULL
); /* fatal_handler */
#else
fprintf(stderr, "Warning: option --alloc-ajsheap ignored, no ajsheap allocator support\n");
fflush(stderr);
#endif
}
if (!ctx && alloc_provider == ALLOC_DEFAULT) {
ctx = duk_create_heap_default();
}
if (!ctx) {
fprintf(stderr, "Failed to create Duktape heap\n");
fflush(stderr);
exit(-1);
}
#if defined(DUK_CMDLINE_AJSHEAP)
if (alloc_provider == ALLOC_AJSHEAP) {
fprintf(stdout, "Pool dump after heap creation\n");
ajsheap_dump();
}
#endif
#if defined(DUK_CMDLINE_AJSHEAP)
if (alloc_provider == ALLOC_AJSHEAP) {
ajsheap_register(ctx);
}
#endif
#if defined(DUK_CMDLINE_FILEIO)
duk_push_c_function(ctx, fileio_read_file, 1 /*nargs*/);
duk_put_global_string(ctx, "readFile");
duk_push_c_function(ctx, fileio_write_file, 2 /*nargs*/);
duk_put_global_string(ctx, "writeFile");
#endif
if (debugger) {
#if defined(DUK_CMDLINE_DEBUGGER_SUPPORT)
fprintf(stderr, "Debugger enabled, create socket and wait for connection\n");
fflush(stderr);
duk_trans_socket_init();
duk_trans_socket_waitconn();
fprintf(stderr, "Debugger connected, call duk_debugger_attach() and then execute requested file(s)/eval\n");
fflush(stderr);
duk_debugger_attach_custom(ctx,
duk_trans_socket_read_cb,
duk_trans_socket_write_cb,
duk_trans_socket_peek_cb,
duk_trans_socket_read_flush_cb,
duk_trans_socket_write_flush_cb,
debugger_request,
debugger_detached,
(void *) ctx);
#else
fprintf(stderr, "Warning: option --debugger ignored, no debugger support\n");
fflush(stderr);
#endif
}
#if 0
/* Manual test for duk_debugger_cooperate() */
{
for (i = 0; i < 60; i++) {
printf("cooperate: %d\n", i);
usleep(1000000);
duk_debugger_cooperate(ctx);
}
}
#endif
return ctx;
}
static void destroy_duktape_heap(duk_context *ctx, int alloc_provider) {
(void) alloc_provider;
#if defined(DUK_CMDLINE_AJSHEAP)
if (alloc_provider == ALLOC_AJSHEAP) {
fprintf(stdout, "Pool dump before duk_destroy_heap(), before forced gc\n");
ajsheap_dump();
duk_gc(ctx, 0);
fprintf(stdout, "Pool dump before duk_destroy_heap(), after forced gc\n");
ajsheap_dump();
}
#endif
if (ctx) {
duk_destroy_heap(ctx);
}
#if defined(DUK_CMDLINE_AJSHEAP)
if (alloc_provider == ALLOC_AJSHEAP) {
fprintf(stdout, "Pool dump after duk_destroy_heap() (should have zero allocs)\n");
ajsheap_dump();
}
ajsheap_free();
#endif
}
/*
* Main
*/
int main(int argc, char *argv[]) {
duk_context *ctx = NULL;
int retval = 0;
int have_files = 0;
int have_eval = 0;
int interactive = 0;
int memlimit_high = 1;
int alloc_provider = ALLOC_DEFAULT;
int ajsheap_log = 0;
int debugger = 0;
int recreate_heap = 0;
int no_heap_destroy = 0;
int verbose = 0;
int run_stdin = 0;
const char *compile_filename = NULL;
int i;
main_argc = argc;
main_argv = (char **) argv;
#if defined(EMSCRIPTEN)
/* Try to use NODEFS to provide access to local files. Mount the
* CWD as /working, and then prepend "/working/" to relative native
* paths in file calls to get something that works reasonably for
* relative paths. Emscripten doesn't support replacing virtual
* "/" with host "/" (the default MEMFS at "/" can't be unmounted)
* but we can mount "/tmp" as host "/tmp" to allow testcase runs.
*
* https://kripken.github.io/emscripten-site/docs/api_reference/Filesystem-API.html#filesystem-api-nodefs
* https://github.com/kripken/emscripten/blob/master/tests/fs/test_nodefs_rw.c
*/
EM_ASM(
/* At the moment it's not possible to replace the default MEMFS mounted at '/':
* https://github.com/kripken/emscripten/issues/2040
* https://github.com/kripken/emscripten/blob/incoming/src/library_fs.js#L1341-L1358
*/
/*
try {
FS.unmount("/");
} catch (e) {
console.log("Failed to unmount default '/' MEMFS mount: " + e);
}
*/
try {
FS.mkdir("/working");
FS.mount(NODEFS, { root: "." }, "/working");
} catch (e) {
console.log("Failed to mount NODEFS /working: " + e);
}
/* A virtual '/tmp' exists by default:
* https://gist.github.com/evanw/e6be28094f34451bd5bd#file-temp-js-L3806-L3809
*/
/*
try {
FS.mkdir("/tmp");
} catch (e) {
console.log("Failed to create virtual /tmp: " + e);
}
*/
try {
FS.mount(NODEFS, { root: "/tmp" }, "/tmp");
} catch (e) {
console.log("Failed to mount NODEFS /tmp: " + e);
}
);
#endif /* EMSCRIPTEN */
#if defined(DUK_CMDLINE_AJSHEAP)
alloc_provider = ALLOC_AJSHEAP;
#endif
(void) ajsheap_log;
/*
* Signal handling setup
*/
#if defined(DUK_CMDLINE_SIGNAL)
set_sigint_handler();
/* This is useful at the global level; libraries should avoid SIGPIPE though */
/*signal(SIGPIPE, SIG_IGN);*/
#endif
/*
* Parse options
*/
for (i = 1; i < argc; i++) {
char *arg = argv[i];
if (!arg) {
goto usage;
}
if (strcmp(arg, "--restrict-memory") == 0) {
memlimit_high = 0;
} else if (strcmp(arg, "-i") == 0) {
interactive = 1;
} else if (strcmp(arg, "-c") == 0) {
if (i == argc - 1) {
goto usage;
}
i++;
compile_filename = argv[i];
} else if (strcmp(arg, "-e") == 0) {
have_eval = 1;
if (i == argc - 1) {
goto usage;
}
i++; /* skip code */
} else if (strcmp(arg, "--alloc-default") == 0) {
alloc_provider = ALLOC_DEFAULT;
} else if (strcmp(arg, "--alloc-logging") == 0) {
alloc_provider = ALLOC_LOGGING;
} else if (strcmp(arg, "--alloc-torture") == 0) {
alloc_provider = ALLOC_TORTURE;
} else if (strcmp(arg, "--alloc-hybrid") == 0) {
alloc_provider = ALLOC_HYBRID;
} else if (strcmp(arg, "--alloc-ajsheap") == 0) {
alloc_provider = ALLOC_AJSHEAP;
} else if (strcmp(arg, "--ajsheap-log") == 0) {
ajsheap_log = 1;
} else if (strcmp(arg, "--debugger") == 0) {
debugger = 1;
#if defined(DUK_CMDLINE_DEBUGGER_SUPPORT)
} else if (strcmp(arg, "--reattach") == 0) {
debugger_reattach = 1;
#endif
} else if (strcmp(arg, "--recreate-heap") == 0) {
recreate_heap = 1;
} else if (strcmp(arg, "--no-heap-destroy") == 0) {
no_heap_destroy = 1;
} else if (strcmp(arg, "--verbose") == 0) {
verbose = 1;
} else if (strcmp(arg, "--run-stdin") == 0) {
run_stdin = 1;
} else if (strlen(arg) >= 1 && arg[0] == '-') {
goto usage;
} else {
have_files = 1;
}
}
if (!have_files && !have_eval && !run_stdin) {
interactive = 1;
}
/*
* Memory limit
*/
#if defined(DUK_CMDLINE_RLIMIT)
set_resource_limits(memlimit_high ? MEM_LIMIT_HIGH : MEM_LIMIT_NORMAL);
#else
if (memlimit_high == 0) {
fprintf(stderr, "Warning: option --restrict-memory ignored, no rlimit support\n");
fflush(stderr);
}
#endif
/*
* Create heap
*/
ctx = create_duktape_heap(alloc_provider, debugger, ajsheap_log);
/*
* Execute any argument file(s)
*/
for (i = 1; i < argc; i++) {
char *arg = argv[i];
if (!arg) {
continue;
} else if (strlen(arg) == 2 && strcmp(arg, "-e") == 0) {
/* Here we know the eval arg exists but check anyway */
if (i == argc - 1) {
retval = 1;
goto cleanup;
}
if (handle_eval(ctx, argv[i + 1]) != 0) {
retval = 1;
goto cleanup;
}
i++; /* skip code */
continue;
} else if (strlen(arg) == 2 && strcmp(arg, "-c") == 0) {
i++; /* skip filename */
continue;
} else if (strlen(arg) >= 1 && arg[0] == '-') {
continue;
}
if (verbose) {
fprintf(stderr, "*** Executing file: %s\n", arg);
fflush(stderr);
}
if (handle_file(ctx, arg, compile_filename) != 0) {
retval = 1;
goto cleanup;
}
if (recreate_heap) {
if (verbose) {
fprintf(stderr, "*** Recreating heap...\n");
fflush(stderr);
}
destroy_duktape_heap(ctx, alloc_provider);
ctx = create_duktape_heap(alloc_provider, debugger, ajsheap_log);
}
}
if (run_stdin) {
/* Running stdin like a full file (reading all lines before
* compiling) is useful with emduk:
* cat test.js | ./emduk --run-stdin
*/
if (handle_fh(ctx, stdin, "stdin", compile_filename) != 0) {
retval = 1;
goto cleanup;
}
if (recreate_heap) {
if (verbose) {
fprintf(stderr, "*** Recreating heap...\n");
fflush(stderr);
}
destroy_duktape_heap(ctx, alloc_provider);
ctx = create_duktape_heap(alloc_provider, debugger, ajsheap_log);
}
}
/*
* Enter interactive mode if options indicate it
*/
if (interactive) {
if (handle_interactive(ctx) != 0) {
retval = 1;
goto cleanup;
}
}
/*
* Cleanup and exit
*/
cleanup:
if (interactive) {
fprintf(stderr, "Cleaning up...\n");
fflush(stderr);
}
if (ctx && no_heap_destroy) {
duk_gc(ctx, 0);
}
if (ctx && !no_heap_destroy) {
destroy_duktape_heap(ctx, alloc_provider);
}
ctx = NULL;
return retval;
/*
* Usage
*/
usage:
fprintf(stderr, "Usage: duk [options] [<filenames>]\n"
"\n"
" -i enter interactive mode after executing argument file(s) / eval code\n"
" -e CODE evaluate code\n"
" -c FILE compile into bytecode (use with only one file argument)\n"
" --run-stdin treat stdin like a file, i.e. compile full input (not line by line)\n"
" --verbose verbose messages to stderr\n"
" --restrict-memory use lower memory limit (used by test runner)\n"
" --alloc-default use Duktape default allocator\n"
#if defined(DUK_CMDLINE_ALLOC_LOGGING)
" --alloc-logging use logging allocator (writes to /tmp)\n"
#endif
#if defined(DUK_CMDLINE_ALLOC_TORTURE)
" --alloc-torture use torture allocator\n"
#endif
#if defined(DUK_CMDLINE_ALLOC_HYBRID)
" --alloc-hybrid use hybrid allocator\n"
#endif
#if defined(DUK_CMDLINE_AJSHEAP)
" --alloc-ajsheap use ajsheap allocator (enabled by default with 'ajduk')\n"
" --ajsheap-log write alloc log to /tmp/ajduk-alloc-log.txt\n"
#endif
#if defined(DUK_CMDLINE_DEBUGGER_SUPPORT)
" --debugger start example debugger\n"
" --reattach automatically reattach debugger on detach\n"
#endif
" --recreate-heap recreate heap after every file\n"
" --no-heap-destroy force GC, but don't destroy heap at end (leak testing)\n"
"\n"
"If <filename> is omitted, interactive mode is started automatically.\n");
fflush(stderr);
exit(1);
}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <swiftCore/_TtCs12_SwiftObject.h>
@interface _TtC13ControlCenter13AirPlayDevice : _TtCs12_SwiftObject
{
// Error parsing type: , name: id
// Error parsing type: , name: name
// Error parsing type: , name: symbol
// Error parsing type: , name: deviceType
// Error parsing type: , name: display
// Error parsing type: , name: __actions
}
@end
| {
"pile_set_name": "Github"
} |
/* Float object interface */
/*
PyFloatObject represents a (double precision) floating point number.
*/
#ifndef Py_FLOATOBJECT_H
#define Py_FLOATOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef Py_LIMITED_API
typedef struct {
PyObject_HEAD
double ob_fval;
} PyFloatObject;
#endif
PyAPI_DATA(PyTypeObject) PyFloat_Type;
#define PyFloat_Check(op) PyObject_TypeCheck(op, &PyFloat_Type)
#define PyFloat_CheckExact(op) (Py_TYPE(op) == &PyFloat_Type)
#ifdef Py_NAN
#define Py_RETURN_NAN return PyFloat_FromDouble(Py_NAN)
#endif
#define Py_RETURN_INF(sign) do \
if (copysign(1., sign) == 1.) { \
return PyFloat_FromDouble(Py_HUGE_VAL); \
} else { \
return PyFloat_FromDouble(-Py_HUGE_VAL); \
} while(0)
PyAPI_FUNC(double) PyFloat_GetMax(void);
PyAPI_FUNC(double) PyFloat_GetMin(void);
PyAPI_FUNC(PyObject *) PyFloat_GetInfo(void);
/* Return Python float from string PyObject. */
PyAPI_FUNC(PyObject *) PyFloat_FromString(PyObject*);
/* Return Python float from C double. */
PyAPI_FUNC(PyObject *) PyFloat_FromDouble(double);
/* Extract C double from Python float. The macro version trades safety for
speed. */
PyAPI_FUNC(double) PyFloat_AsDouble(PyObject *);
#ifndef Py_LIMITED_API
#define PyFloat_AS_DOUBLE(op) (((PyFloatObject *)(op))->ob_fval)
#endif
#ifndef Py_LIMITED_API
/* _PyFloat_{Pack,Unpack}{4,8}
*
* The struct and pickle (at least) modules need an efficient platform-
* independent way to store floating-point values as byte strings.
* The Pack routines produce a string from a C double, and the Unpack
* routines produce a C double from such a string. The suffix (4 or 8)
* specifies the number of bytes in the string.
*
* On platforms that appear to use (see _PyFloat_Init()) IEEE-754 formats
* these functions work by copying bits. On other platforms, the formats the
* 4- byte format is identical to the IEEE-754 single precision format, and
* the 8-byte format to the IEEE-754 double precision format, although the
* packing of INFs and NaNs (if such things exist on the platform) isn't
* handled correctly, and attempting to unpack a string containing an IEEE
* INF or NaN will raise an exception.
*
* On non-IEEE platforms with more precision, or larger dynamic range, than
* 754 supports, not all values can be packed; on non-IEEE platforms with less
* precision, or smaller dynamic range, not all values can be unpacked. What
* happens in such cases is partly accidental (alas).
*/
/* The pack routines write 2, 4 or 8 bytes, starting at p. le is a bool
* argument, true if you want the string in little-endian format (exponent
* last, at p+1, p+3 or p+7), false if you want big-endian format (exponent
* first, at p).
* Return value: 0 if all is OK, -1 if error (and an exception is
* set, most likely OverflowError).
* There are two problems on non-IEEE platforms:
* 1): What this does is undefined if x is a NaN or infinity.
* 2): -0.0 and +0.0 produce the same string.
*/
PyAPI_FUNC(int) _PyFloat_Pack2(double x, unsigned char *p, int le);
PyAPI_FUNC(int) _PyFloat_Pack4(double x, unsigned char *p, int le);
PyAPI_FUNC(int) _PyFloat_Pack8(double x, unsigned char *p, int le);
/* Needed for the old way for marshal to store a floating point number.
Returns the string length copied into p, -1 on error.
*/
PyAPI_FUNC(int) _PyFloat_Repr(double x, char *p, size_t len);
/* Used to get the important decimal digits of a double */
PyAPI_FUNC(int) _PyFloat_Digits(char *buf, double v, int *signum);
PyAPI_FUNC(void) _PyFloat_DigitsInit(void);
/* The unpack routines read 2, 4 or 8 bytes, starting at p. le is a bool
* argument, true if the string is in little-endian format (exponent
* last, at p+1, p+3 or p+7), false if big-endian (exponent first, at p).
* Return value: The unpacked double. On error, this is -1.0 and
* PyErr_Occurred() is true (and an exception is set, most likely
* OverflowError). Note that on a non-IEEE platform this will refuse
* to unpack a string that represents a NaN or infinity.
*/
PyAPI_FUNC(double) _PyFloat_Unpack2(const unsigned char *p, int le);
PyAPI_FUNC(double) _PyFloat_Unpack4(const unsigned char *p, int le);
PyAPI_FUNC(double) _PyFloat_Unpack8(const unsigned char *p, int le);
/* free list api */
PyAPI_FUNC(int) PyFloat_ClearFreeList(void);
PyAPI_FUNC(void) _PyFloat_DebugMallocStats(FILE* out);
/* Format the object based on the format_spec, as defined in PEP 3101
(Advanced String Formatting). */
PyAPI_FUNC(int) _PyFloat_FormatAdvancedWriter(
_PyUnicodeWriter *writer,
PyObject *obj,
PyObject *format_spec,
Py_ssize_t start,
Py_ssize_t end);
#endif /* Py_LIMITED_API */
#ifdef __cplusplus
}
#endif
#endif /* !Py_FLOATOBJECT_H */
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2015 Goldman Sachs.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*/
/**
* This package contains implementations of {@link org.eclipse.collections.api.bag.sorted.MutableSortedBag}.
* <p>
* This package contains 2 sorted mutable bag implementation:
* <ul>
* <li>
* {@link org.eclipse.collections.impl.bag.sorted.mutable.TreeBag} - a sorted bag backed by Tree data structure..
* </li>
* <li>
* {@link org.eclipse.collections.impl.bag.sorted.mutable.UnmodifiableSortedBag} - an unmodifiable view of a SortedBag.
* </li>
* </ul>
*/
package org.eclipse.collections.impl.bag.sorted.mutable;
| {
"pile_set_name": "Github"
} |
import os
import glob
from django.core.management.base import BaseCommand
from django.db import transaction
from common.utils import progress_bar
from photos.add import add_photo
from intrinsic.tasks import sample_intrinsic_points_task
from django.contrib.auth.models import User
from photos.models import PhotoSceneCategory, PhotoLightStack
from intrinsic.models import IntrinsicPoint, IntrinsicPointComparison
class Command(BaseCommand):
args = ''
help = 'Import photos of static scenes with multiple lighting conditions'
def handle(self, *args, **options):
admin_user = User.objects.get_or_create(
username='admin')[0].get_profile()
with transaction.atomic():
for root in progress_bar(glob.glob('%s/*' % args[0])):
slug = os.path.basename(root)
print slug
if 'janivar50' in slug or 'kitchen' in slug:
scene_category = PhotoSceneCategory.objects.get(
name='kitchen')
elif 'mike_indoor' in slug or 'sofas' in slug:
scene_category = PhotoSceneCategory.objects.get(
name='living room')
else:
raise ValueError("Unknown")
light_stack = PhotoLightStack.objects.create(slug=slug)
files = glob.glob('%s/*' % root)
photos = [
add_photo(
path=f,
user=admin_user,
scene_category=scene_category,
light_stack=light_stack,
)
for f in files
]
| {
"pile_set_name": "Github"
} |
# $NetBSD: Makefile,v 1.4 2020/05/10 04:31:46 markd Exp $
DISTNAME= gillius
PKGNAME= tex-${DISTNAME}-2014
PKGREVISION= 1
TEXLIVE_REV= 32068
MAINTAINER= [email protected]
HOMEPAGE= https://ctan.org/pkg/gillius
COMMENT= Gillius fonts with LaTeX support
LICENSE= gnu-gpl-v2
TEX_MAP_FILES+= gillius.map
TEXLIVE_UNVERSIONED= yes
.include "../../print/texlive/package.mk"
.include "../../mk/bsd.pkg.mk"
| {
"pile_set_name": "Github"
} |
using Nethereum.Generators.Core;
using Nethereum.Generators.CQS;
namespace Nethereum.Generators.DTOs
{
public class EventDTOVbTemplate : ClassTemplateBase<EventDTOModel>
{
private ParameterABIEventDTOVbTemplate _parameterAbiEventDtoVbTemplate;
public EventDTOVbTemplate(EventDTOModel eventDTOModel) : base(eventDTOModel)
{
_parameterAbiEventDtoVbTemplate = new ParameterABIEventDTOVbTemplate();
ClassFileTemplate = new VbClassFileTemplate(Model, this);
}
public override string GenerateClass()
{
if (Model.CanGenerateOutputDTO())
{
return
$@"{GetPartialMainClass()}
{SpaceUtils.OneTab}<[Event](""{Model.EventABI.Name}"")>
{SpaceUtils.OneTab}Public Class {Model.GetTypeName()}Base
{SpaceUtils.TwoTabs}Implements IEventDTO
{SpaceUtils.TwoTabs}
{_parameterAbiEventDtoVbTemplate.GenerateAllProperties(Model.EventABI.InputParameters)}
{SpaceUtils.OneTab}
{SpaceUtils.OneTab}End Class";
}
return null;
}
public string GetPartialMainClass()
{
return $@"{SpaceUtils.OneTab}Public Partial Class {Model.GetTypeName()}
{SpaceUtils.TwoTabs}Inherits {Model.GetTypeName()}Base
{SpaceUtils.OneTab}End Class";
}
}
} | {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<!--<link rel="icon" href="../../favicon.ico">-->
<title>Modal - FooTable</title>
<!-- Bootstrap core CSS -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" rel="stylesheet">
<!-- Prism -->
<link href="../../css/prism.css" rel="stylesheet">
<!-- FooTable Bootstrap CSS -->
<link href="../../../compiled/footable.bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../../css/docs.css" rel="stylesheet">
<script src="../../js/demo-rows.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="//oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="docs">
<!-- Fixed navbar -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="../../../index.html" class="navbar-brand">FooTable</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="../../getting-started.html">Getting started</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Components <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="../../components/editing.html">Editing</a></li>
<li><a href="../../components/filtering.html">Filtering</a></li>
<li><a href="../../components/paging.html">Paging</a></li>
<li><a href="../../components/sorting.html">Sorting</a></li>
<li><a href="../../components/state.html">State</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="../../jsdocs/index.html" target="_blank">JSDocs</a></li>
<li><a href="https://github.com/fooplugins/FooTable" target="_blank">GitHub</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<!-- Header -->
<div class="jumbotron">
<div class="container">
<h1>Modal</h1>
<h2>Shows using FooTable with Bootstraps' modal component.</h2>
</div>
</div>
<!-- Content -->
<div class="container">
<div class="docs-section">
<div class="callout callout-info">
<h4>Notes</h4>
<ul>
<li>This example makes use of <a href="http://getbootstrap.com/javascript/#modals" target="_blank">Bootstraps' modal component</a>.</li>
<li>
The base table in the example below is a clone of the <a href="../component/showcase.html">showcase example</a> to demonstrate that various table operations
such as filtering, sorting, paging still function correctly.
</li>
<li>
Seeing as the modal is a lot smaller than the viewport and the <a href="../../content/columns.json" target="_blank">columns.json</a> file uses the default
breakpoints, the below example makes use of the <a href="../../getting-started.html#useParentWidth">useParentWidth</a> option so the columns collapse accordingly.
</li>
</ul>
</div>
<div class="example">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<table id="modal-example-1" class="table" data-paging="true" data-filtering="true" data-sorting="true"></table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<pre class="language-javascript between" data-lang="javascript"><code>jQuery(function($){
$('#modal-example-1').footable({
"useParentWidth": true,
"columns": $.get('columns.json'),
"rows": $.get('rows.json')
});
});</code></pre>
<pre class="language-markup" data-lang="markup"><code><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<table id="modal-example-1" class="table" data-paging="true" data-filtering="true" data-sorting="true"></table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div></code></pre>
</div>
</div> <!-- /container -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../../js/prism.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../js/ie10-viewport-bug-workaround.js"></script>
<!-- Add in any FooTable dependencies we may need -->
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<!-- Add in FooTable itself -->
<script src="../../../compiled/footable.js"></script>
<!-- Initialize FooTable -->
<script>
jQuery(function($){
$('#modal-example-1').footable({
"useParentWidth": true,
"columns": $.get("../../content/columns.json"),
"rows": $.get("../../content/rows.json")
});
});
</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import googlemac_iPhone_Shared_SSOAuth_SSOAuth
@testable import third_party_sciencejournal_ios_ScienceJournalOpen
/// A mock drive constructor used for testing.
class MockDriveConstructor: DriveConstructor {
let mockDriveSyncManager = MockDriveSyncManager()
/// Returns a mock drive sync manager when called.
func driveSyncManager(withAuthorization authorization: GTMFetcherAuthorizationProtocol,
experimentDataDeleter: ExperimentDataDeleter,
metadataManager: MetadataManager,
networkAvailability: NetworkAvailability,
preferenceManager: PreferenceManager,
sensorDataManager: SensorDataManager,
analyticsReporter: AnalyticsReporter) -> DriveSyncManager? {
return mockDriveSyncManager
}
}
/// A Drive sync manager that calls completion with a mock value when `experimentLibraryExists()` is
/// called.
class MockDriveSyncManager: DriveSyncManager {
var delegate: DriveSyncManagerDelegate?
func syncExperimentLibrary(andReconcile shouldReconcile: Bool, userInitiated: Bool) {}
func syncExperiment(withID experimentID: String,
condition: DriveExperimentSyncCondition) {}
func syncTrialSensorData(atURL url: URL, experimentID: String) {}
func deleteExperiment(withID experimentID: String) {}
func deleteImageAssets(atURLs urls: [URL], experimentID: String) {}
func deleteSensorDataAsset(atURL url: URL, experimentID: String) {}
func debug_removeAllUserDriveData(completion: @escaping (Int, [Error]) -> Void) {}
var mockExperimentLibraryExistsValue: Bool?
var tearDownCalled = false
func experimentLibraryExists(completion: @escaping (Bool?) -> Void) {
completion(mockExperimentLibraryExistsValue)
}
func tearDown() {
tearDownCalled = true
}
}
| {
"pile_set_name": "Github"
} |
/**************************************************************************
*
* Copyright 2003 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************/
#include "i915_reg.h"
#include "i915_context.h"
#include "i915_screen.h"
#include "i915_debug.h"
#include "i915_debug_private.h"
#include "i915_batch.h"
#include "util/u_debug.h"
static const struct debug_named_value debug_options[] = {
{"blit", DBG_BLIT, "Print when using the 2d blitter"},
{"emit", DBG_EMIT, "State emit information"},
{"atoms", DBG_ATOMS, "Print dirty state atoms"},
{"flush", DBG_FLUSH, "Flushing information"},
{"texture", DBG_TEXTURE, "Texture information"},
{"constants", DBG_CONSTANTS, "Constant buffers"},
DEBUG_NAMED_VALUE_END
};
unsigned i915_debug = 0;
DEBUG_GET_ONCE_FLAGS_OPTION(i915_debug, "I915_DEBUG", debug_options, 0)
DEBUG_GET_ONCE_BOOL_OPTION(i915_no_tiling, "I915_NO_TILING", FALSE)
DEBUG_GET_ONCE_BOOL_OPTION(i915_lie, "I915_LIE", TRUE)
DEBUG_GET_ONCE_BOOL_OPTION(i915_use_blitter, "I915_USE_BLITTER", FALSE)
void i915_debug_init(struct i915_screen *is)
{
i915_debug = debug_get_option_i915_debug();
is->debug.tiling = !debug_get_option_i915_no_tiling();
is->debug.lie = debug_get_option_i915_lie();
is->debug.use_blitter = debug_get_option_i915_use_blitter();
}
/***********************************************************************
* Batchbuffer dumping
*/
static void
PRINTF(
struct debug_stream *stream,
const char *fmt,
... )
{
va_list args;
va_start( args, fmt );
debug_vprintf( fmt, args );
va_end( args );
}
static boolean debug( struct debug_stream *stream, const char *name, unsigned len )
{
unsigned i;
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
if (len == 0) {
PRINTF(stream, "Error - zero length packet (0x%08x)\n", stream->ptr[0]);
assert(0);
return FALSE;
}
if (stream->print_addresses)
PRINTF(stream, "%08x: ", stream->offset);
PRINTF(stream, "%s (%d dwords):\n", name, len);
for (i = 0; i < len; i++)
PRINTF(stream, "\t0x%08x\n", ptr[i]);
PRINTF(stream, "\n");
stream->offset += len * sizeof(unsigned);
return TRUE;
}
static const char *get_prim_name( unsigned val )
{
switch (val & PRIM3D_MASK) {
case PRIM3D_TRILIST: return "TRILIST"; break;
case PRIM3D_TRISTRIP: return "TRISTRIP"; break;
case PRIM3D_TRISTRIP_RVRSE: return "TRISTRIP_RVRSE"; break;
case PRIM3D_TRIFAN: return "TRIFAN"; break;
case PRIM3D_POLY: return "POLY"; break;
case PRIM3D_LINELIST: return "LINELIST"; break;
case PRIM3D_LINESTRIP: return "LINESTRIP"; break;
case PRIM3D_RECTLIST: return "RECTLIST"; break;
case PRIM3D_POINTLIST: return "POINTLIST"; break;
case PRIM3D_DIB: return "DIB"; break;
case PRIM3D_CLEAR_RECT: return "CLEAR_RECT"; break;
case PRIM3D_ZONE_INIT: return "ZONE_INIT"; break;
default: return "????"; break;
}
}
static boolean debug_prim( struct debug_stream *stream, const char *name,
boolean dump_floats,
unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
const char *prim = get_prim_name( ptr[0] );
unsigned i;
PRINTF(stream, "%s %s (%d dwords):\n", name, prim, len);
PRINTF(stream, "\t0x%08x\n", ptr[0]);
for (i = 1; i < len; i++) {
if (dump_floats)
PRINTF(stream, "\t0x%08x // %f\n", ptr[i], *(float *)&ptr[i]);
else
PRINTF(stream, "\t0x%08x\n", ptr[i]);
}
PRINTF(stream, "\n");
stream->offset += len * sizeof(unsigned);
return TRUE;
}
static boolean debug_program( struct debug_stream *stream, const char *name, unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
if (len == 0) {
PRINTF(stream, "Error - zero length packet (0x%08x)\n", stream->ptr[0]);
assert(0);
return FALSE;
}
if (stream->print_addresses)
PRINTF(stream, "%08x: ", stream->offset);
PRINTF(stream, "%s (%d dwords):\n", name, len);
i915_disassemble_program( stream, ptr, len );
stream->offset += len * sizeof(unsigned);
return TRUE;
}
static boolean debug_chain( struct debug_stream *stream, const char *name, unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
unsigned old_offset = stream->offset + len * sizeof(unsigned);
unsigned i;
PRINTF(stream, "%s (%d dwords):\n", name, len);
for (i = 0; i < len; i++)
PRINTF(stream, "\t0x%08x\n", ptr[i]);
stream->offset = ptr[1] & ~0x3;
if (stream->offset < old_offset)
PRINTF(stream, "\n... skipping backwards from 0x%x --> 0x%x ...\n\n",
old_offset, stream->offset );
else
PRINTF(stream, "\n... skipping from 0x%x --> 0x%x ...\n\n",
old_offset, stream->offset );
return TRUE;
}
static boolean debug_variable_length_prim( struct debug_stream *stream )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
const char *prim = get_prim_name( ptr[0] );
unsigned i, len;
ushort *idx = (ushort *)(ptr+1);
for (i = 0; idx[i] != 0xffff; i++)
;
len = 1+(i+2)/2;
PRINTF(stream, "3DPRIM, %s variable length %d indicies (%d dwords):\n", prim, i, len);
for (i = 0; i < len; i++)
PRINTF(stream, "\t0x%08x\n", ptr[i]);
PRINTF(stream, "\n");
stream->offset += len * sizeof(unsigned);
return TRUE;
}
static void
BITS(
struct debug_stream *stream,
unsigned dw,
unsigned hi,
unsigned lo,
const char *fmt,
... )
{
va_list args;
unsigned himask = 0xFFFFFFFFUL >> (31 - (hi));
PRINTF(stream, "\t\t ");
va_start( args, fmt );
debug_vprintf( fmt, args );
va_end( args );
PRINTF(stream, ": 0x%x\n", ((dw) & himask) >> (lo));
}
#ifdef DEBUG
#define MBZ( dw, hi, lo) do { \
unsigned x = (dw) >> (lo); \
unsigned lomask = (1 << (lo)) - 1; \
unsigned himask; \
himask = (1UL << (hi)) - 1; \
assert ((x & himask & ~lomask) == 0); \
} while (0)
#else
#define MBZ( dw, hi, lo) do { \
} while (0)
#endif
static void
FLAG(
struct debug_stream *stream,
unsigned dw,
unsigned bit,
const char *fmt,
... )
{
if (((dw) >> (bit)) & 1) {
va_list args;
PRINTF(stream, "\t\t ");
va_start( args, fmt );
debug_vprintf( fmt, args );
va_end( args );
PRINTF(stream, "\n");
}
}
static boolean debug_load_immediate( struct debug_stream *stream,
const char *name,
unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
unsigned bits = (ptr[0] >> 4) & 0xff;
unsigned j = 0;
PRINTF(stream, "%s (%d dwords, flags: %x):\n", name, len, bits);
PRINTF(stream, "\t0x%08x\n", ptr[j++]);
if (bits & (1<<0)) {
PRINTF(stream, "\t LIS0: 0x%08x\n", ptr[j]);
PRINTF(stream, "\t vb address: 0x%08x\n", (ptr[j] & ~0x3));
BITS(stream, ptr[j], 0, 0, "vb invalidate disable");
j++;
}
if (bits & (1<<1)) {
PRINTF(stream, "\t LIS1: 0x%08x\n", ptr[j]);
BITS(stream, ptr[j], 29, 24, "vb dword width");
BITS(stream, ptr[j], 21, 16, "vb dword pitch");
BITS(stream, ptr[j], 15, 0, "vb max index");
j++;
}
if (bits & (1<<2)) {
int i;
PRINTF(stream, "\t LIS2: 0x%08x\n", ptr[j]);
for (i = 0; i < 8; i++) {
unsigned tc = (ptr[j] >> (i * 4)) & 0xf;
if (tc != 0xf)
BITS(stream, tc, 3, 0, "tex coord %d", i);
}
j++;
}
if (bits & (1<<3)) {
PRINTF(stream, "\t LIS3: 0x%08x\n", ptr[j]);
j++;
}
if (bits & (1<<4)) {
PRINTF(stream, "\t LIS4: 0x%08x\n", ptr[j]);
BITS(stream, ptr[j], 31, 23, "point width");
BITS(stream, ptr[j], 22, 19, "line width");
FLAG(stream, ptr[j], 18, "alpha flatshade");
FLAG(stream, ptr[j], 17, "fog flatshade");
FLAG(stream, ptr[j], 16, "spec flatshade");
FLAG(stream, ptr[j], 15, "rgb flatshade");
BITS(stream, ptr[j], 14, 13, "cull mode");
FLAG(stream, ptr[j], 12, "vfmt: point width");
FLAG(stream, ptr[j], 11, "vfmt: specular/fog");
FLAG(stream, ptr[j], 10, "vfmt: rgba");
FLAG(stream, ptr[j], 9, "vfmt: depth offset");
BITS(stream, ptr[j], 8, 6, "vfmt: position (2==xyzw)");
FLAG(stream, ptr[j], 5, "force dflt diffuse");
FLAG(stream, ptr[j], 4, "force dflt specular");
FLAG(stream, ptr[j], 3, "local depth offset enable");
FLAG(stream, ptr[j], 2, "vfmt: fp32 fog coord");
FLAG(stream, ptr[j], 1, "sprite point");
FLAG(stream, ptr[j], 0, "antialiasing");
j++;
}
if (bits & (1<<5)) {
PRINTF(stream, "\t LIS5: 0x%08x\n", ptr[j]);
BITS(stream, ptr[j], 31, 28, "rgba write disables");
FLAG(stream, ptr[j], 27, "force dflt point width");
FLAG(stream, ptr[j], 26, "last pixel enable");
FLAG(stream, ptr[j], 25, "global z offset enable");
FLAG(stream, ptr[j], 24, "fog enable");
BITS(stream, ptr[j], 23, 16, "stencil ref");
BITS(stream, ptr[j], 15, 13, "stencil test");
BITS(stream, ptr[j], 12, 10, "stencil fail op");
BITS(stream, ptr[j], 9, 7, "stencil pass z fail op");
BITS(stream, ptr[j], 6, 4, "stencil pass z pass op");
FLAG(stream, ptr[j], 3, "stencil write enable");
FLAG(stream, ptr[j], 2, "stencil test enable");
FLAG(stream, ptr[j], 1, "color dither enable");
FLAG(stream, ptr[j], 0, "logiop enable");
j++;
}
if (bits & (1<<6)) {
PRINTF(stream, "\t LIS6: 0x%08x\n", ptr[j]);
FLAG(stream, ptr[j], 31, "alpha test enable");
BITS(stream, ptr[j], 30, 28, "alpha func");
BITS(stream, ptr[j], 27, 20, "alpha ref");
FLAG(stream, ptr[j], 19, "depth test enable");
BITS(stream, ptr[j], 18, 16, "depth func");
FLAG(stream, ptr[j], 15, "blend enable");
BITS(stream, ptr[j], 14, 12, "blend func");
BITS(stream, ptr[j], 11, 8, "blend src factor");
BITS(stream, ptr[j], 7, 4, "blend dst factor");
FLAG(stream, ptr[j], 3, "depth write enable");
FLAG(stream, ptr[j], 2, "color write enable");
BITS(stream, ptr[j], 1, 0, "provoking vertex");
j++;
}
PRINTF(stream, "\n");
assert(j == len);
stream->offset += len * sizeof(unsigned);
return TRUE;
}
static boolean debug_load_indirect( struct debug_stream *stream,
const char *name,
unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
unsigned bits = (ptr[0] >> 8) & 0x3f;
unsigned i, j = 0;
PRINTF(stream, "%s (%d dwords):\n", name, len);
PRINTF(stream, "\t0x%08x\n", ptr[j++]);
for (i = 0; i < 6; i++) {
if (bits & (1<<i)) {
switch (1<<(8+i)) {
case LI0_STATE_STATIC_INDIRECT:
PRINTF(stream, " STATIC: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++;
PRINTF(stream, " 0x%08x\n", ptr[j++]);
break;
case LI0_STATE_DYNAMIC_INDIRECT:
PRINTF(stream, " DYNAMIC: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++;
break;
case LI0_STATE_SAMPLER:
PRINTF(stream, " SAMPLER: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++;
PRINTF(stream, " 0x%08x\n", ptr[j++]);
break;
case LI0_STATE_MAP:
PRINTF(stream, " MAP: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++;
PRINTF(stream, " 0x%08x\n", ptr[j++]);
break;
case LI0_STATE_PROGRAM:
PRINTF(stream, " PROGRAM: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++;
PRINTF(stream, " 0x%08x\n", ptr[j++]);
break;
case LI0_STATE_CONSTANTS:
PRINTF(stream, " CONSTANTS: 0x%08x | %x\n", ptr[j]&~3, ptr[j]&3); j++;
PRINTF(stream, " 0x%08x\n", ptr[j++]);
break;
default:
assert(0);
break;
}
}
}
if (bits == 0) {
PRINTF(stream, "\t DUMMY: 0x%08x\n", ptr[j++]);
}
PRINTF(stream, "\n");
assert(j == len);
stream->offset += len * sizeof(unsigned);
return TRUE;
}
static void BR13( struct debug_stream *stream,
unsigned val )
{
PRINTF(stream, "\t0x%08x\n", val);
FLAG(stream, val, 30, "clipping enable");
BITS(stream, val, 25, 24, "color depth (3==32bpp)");
BITS(stream, val, 23, 16, "raster op");
BITS(stream, val, 15, 0, "dest pitch");
}
static void BR22( struct debug_stream *stream,
unsigned val )
{
PRINTF(stream, "\t0x%08x\n", val);
BITS(stream, val, 31, 16, "dest y1");
BITS(stream, val, 15, 0, "dest x1");
}
static void BR23( struct debug_stream *stream,
unsigned val )
{
PRINTF(stream, "\t0x%08x\n", val);
BITS(stream, val, 31, 16, "dest y2");
BITS(stream, val, 15, 0, "dest x2");
}
static void BR09( struct debug_stream *stream,
unsigned val )
{
PRINTF(stream, "\t0x%08x -- dest address\n", val);
}
static void BR26( struct debug_stream *stream,
unsigned val )
{
PRINTF(stream, "\t0x%08x\n", val);
BITS(stream, val, 31, 16, "src y1");
BITS(stream, val, 15, 0, "src x1");
}
static void BR11( struct debug_stream *stream,
unsigned val )
{
PRINTF(stream, "\t0x%08x\n", val);
BITS(stream, val, 15, 0, "src pitch");
}
static void BR12( struct debug_stream *stream,
unsigned val )
{
PRINTF(stream, "\t0x%08x -- src address\n", val);
}
static void BR16( struct debug_stream *stream,
unsigned val )
{
PRINTF(stream, "\t0x%08x -- color\n", val);
}
static boolean debug_copy_blit( struct debug_stream *stream,
const char *name,
unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
int j = 0;
PRINTF(stream, "%s (%d dwords):\n", name, len);
PRINTF(stream, "\t0x%08x\n", ptr[j++]);
BR13(stream, ptr[j++]);
BR22(stream, ptr[j++]);
BR23(stream, ptr[j++]);
BR09(stream, ptr[j++]);
BR26(stream, ptr[j++]);
BR11(stream, ptr[j++]);
BR12(stream, ptr[j++]);
stream->offset += len * sizeof(unsigned);
assert(j == len);
return TRUE;
}
static boolean debug_color_blit( struct debug_stream *stream,
const char *name,
unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
int j = 0;
PRINTF(stream, "%s (%d dwords):\n", name, len);
PRINTF(stream, "\t0x%08x\n", ptr[j++]);
BR13(stream, ptr[j++]);
BR22(stream, ptr[j++]);
BR23(stream, ptr[j++]);
BR09(stream, ptr[j++]);
BR16(stream, ptr[j++]);
stream->offset += len * sizeof(unsigned);
assert(j == len);
return TRUE;
}
static boolean debug_modes4( struct debug_stream *stream,
const char *name,
unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
int j = 0;
PRINTF(stream, "%s (%d dwords):\n", name, len);
PRINTF(stream, "\t0x%08x\n", ptr[j]);
BITS(stream, ptr[j], 21, 18, "logicop func");
FLAG(stream, ptr[j], 17, "stencil test mask modify-enable");
FLAG(stream, ptr[j], 16, "stencil write mask modify-enable");
BITS(stream, ptr[j], 15, 8, "stencil test mask");
BITS(stream, ptr[j], 7, 0, "stencil write mask");
j++;
stream->offset += len * sizeof(unsigned);
assert(j == len);
return TRUE;
}
static boolean debug_map_state( struct debug_stream *stream,
const char *name,
unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
unsigned j = 0;
PRINTF(stream, "%s (%d dwords):\n", name, len);
PRINTF(stream, "\t0x%08x\n", ptr[j++]);
{
PRINTF(stream, "\t0x%08x\n", ptr[j]);
BITS(stream, ptr[j], 15, 0, "map mask");
j++;
}
while (j < len) {
{
PRINTF(stream, "\t TMn.0: 0x%08x\n", ptr[j]);
PRINTF(stream, "\t map address: 0x%08x\n", (ptr[j] & ~0x3));
FLAG(stream, ptr[j], 1, "vertical line stride");
FLAG(stream, ptr[j], 0, "vertical line stride offset");
j++;
}
{
PRINTF(stream, "\t TMn.1: 0x%08x\n", ptr[j]);
BITS(stream, ptr[j], 31, 21, "height");
BITS(stream, ptr[j], 20, 10, "width");
BITS(stream, ptr[j], 9, 7, "surface format");
BITS(stream, ptr[j], 6, 3, "texel format");
FLAG(stream, ptr[j], 2, "use fence regs");
FLAG(stream, ptr[j], 1, "tiled surface");
FLAG(stream, ptr[j], 0, "tile walk ymajor");
j++;
}
{
PRINTF(stream, "\t TMn.2: 0x%08x\n", ptr[j]);
BITS(stream, ptr[j], 31, 21, "dword pitch");
BITS(stream, ptr[j], 20, 15, "cube face enables");
BITS(stream, ptr[j], 14, 9, "max lod");
FLAG(stream, ptr[j], 8, "mip layout right");
BITS(stream, ptr[j], 7, 0, "depth");
j++;
}
}
stream->offset += len * sizeof(unsigned);
assert(j == len);
return TRUE;
}
static boolean debug_sampler_state( struct debug_stream *stream,
const char *name,
unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
unsigned j = 0;
PRINTF(stream, "%s (%d dwords):\n", name, len);
PRINTF(stream, "\t0x%08x\n", ptr[j++]);
{
PRINTF(stream, "\t0x%08x\n", ptr[j]);
BITS(stream, ptr[j], 15, 0, "sampler mask");
j++;
}
while (j < len) {
{
PRINTF(stream, "\t TSn.0: 0x%08x\n", ptr[j]);
FLAG(stream, ptr[j], 31, "reverse gamma");
FLAG(stream, ptr[j], 30, "planar to packed");
FLAG(stream, ptr[j], 29, "yuv->rgb");
BITS(stream, ptr[j], 28, 27, "chromakey index");
BITS(stream, ptr[j], 26, 22, "base mip level");
BITS(stream, ptr[j], 21, 20, "mip mode filter");
BITS(stream, ptr[j], 19, 17, "mag mode filter");
BITS(stream, ptr[j], 16, 14, "min mode filter");
BITS(stream, ptr[j], 13, 5, "lod bias (s4.4)");
FLAG(stream, ptr[j], 4, "shadow enable");
FLAG(stream, ptr[j], 3, "max-aniso-4");
BITS(stream, ptr[j], 2, 0, "shadow func");
j++;
}
{
PRINTF(stream, "\t TSn.1: 0x%08x\n", ptr[j]);
BITS(stream, ptr[j], 31, 24, "min lod");
MBZ( ptr[j], 23, 18 );
FLAG(stream, ptr[j], 17, "kill pixel enable");
FLAG(stream, ptr[j], 16, "keyed tex filter mode");
FLAG(stream, ptr[j], 15, "chromakey enable");
BITS(stream, ptr[j], 14, 12, "tcx wrap mode");
BITS(stream, ptr[j], 11, 9, "tcy wrap mode");
BITS(stream, ptr[j], 8, 6, "tcz wrap mode");
FLAG(stream, ptr[j], 5, "normalized coords");
BITS(stream, ptr[j], 4, 1, "map (surface) index");
FLAG(stream, ptr[j], 0, "EAST deinterlacer enable");
j++;
}
{
PRINTF(stream, "\t TSn.2: 0x%08x (default color)\n", ptr[j]);
j++;
}
}
stream->offset += len * sizeof(unsigned);
assert(j == len);
return TRUE;
}
static boolean debug_dest_vars( struct debug_stream *stream,
const char *name,
unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
int j = 0;
PRINTF(stream, "%s (%d dwords):\n", name, len);
PRINTF(stream, "\t0x%08x\n", ptr[j++]);
{
PRINTF(stream, "\t0x%08x\n", ptr[j]);
FLAG(stream, ptr[j], 31, "early classic ztest");
FLAG(stream, ptr[j], 30, "opengl tex default color");
FLAG(stream, ptr[j], 29, "bypass iz");
FLAG(stream, ptr[j], 28, "lod preclamp");
BITS(stream, ptr[j], 27, 26, "dither pattern");
FLAG(stream, ptr[j], 25, "linear gamma blend");
FLAG(stream, ptr[j], 24, "debug dither");
BITS(stream, ptr[j], 23, 20, "dstorg x");
BITS(stream, ptr[j], 19, 16, "dstorg y");
MBZ (ptr[j], 15, 15 );
BITS(stream, ptr[j], 14, 12, "422 write select");
BITS(stream, ptr[j], 11, 8, "cbuf format");
BITS(stream, ptr[j], 3, 2, "zbuf format");
FLAG(stream, ptr[j], 1, "vert line stride");
FLAG(stream, ptr[j], 1, "vert line stride offset");
j++;
}
stream->offset += len * sizeof(unsigned);
assert(j == len);
return TRUE;
}
static boolean debug_buf_info( struct debug_stream *stream,
const char *name,
unsigned len )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
int j = 0;
PRINTF(stream, "%s (%d dwords):\n", name, len);
PRINTF(stream, "\t0x%08x\n", ptr[j++]);
{
PRINTF(stream, "\t0x%08x\n", ptr[j]);
BITS(stream, ptr[j], 28, 28, "aux buffer id");
BITS(stream, ptr[j], 27, 24, "buffer id (7=depth, 3=back)");
FLAG(stream, ptr[j], 23, "use fence regs");
FLAG(stream, ptr[j], 22, "tiled surface");
FLAG(stream, ptr[j], 21, "tile walk ymajor");
MBZ (ptr[j], 20, 14);
BITS(stream, ptr[j], 13, 2, "dword pitch");
MBZ (ptr[j], 2, 0);
j++;
}
PRINTF(stream, "\t0x%08x -- buffer base address\n", ptr[j++]);
stream->offset += len * sizeof(unsigned);
assert(j == len);
return TRUE;
}
static boolean i915_debug_packet( struct debug_stream *stream )
{
unsigned *ptr = (unsigned *)(stream->ptr + stream->offset);
unsigned cmd = *ptr;
switch (((cmd >> 29) & 0x7)) {
case 0x0:
switch ((cmd >> 23) & 0x3f) {
case 0x0:
return debug(stream, "MI_NOOP", 1);
case 0x3:
return debug(stream, "MI_WAIT_FOR_EVENT", 1);
case 0x4:
return debug(stream, "MI_FLUSH", 1);
case 0xA:
debug(stream, "MI_BATCH_BUFFER_END", 1);
return FALSE;
case 0x22:
return debug(stream, "MI_LOAD_REGISTER_IMM", 3);
case 0x31:
return debug_chain(stream, "MI_BATCH_BUFFER_START", 2);
default:
(void)debug(stream, "UNKNOWN 0x0 case!", 1);
assert(0);
break;
}
break;
case 0x1:
(void) debug(stream, "UNKNOWN 0x1 case!", 1);
assert(0);
break;
case 0x2:
switch ((cmd >> 22) & 0xff) {
case 0x50:
return debug_color_blit(stream, "XY_COLOR_BLT", (cmd & 0xff) + 2);
case 0x53:
return debug_copy_blit(stream, "XY_SRC_COPY_BLT", (cmd & 0xff) + 2);
default:
return debug(stream, "blit command", (cmd & 0xff) + 2);
}
break;
case 0x3:
switch ((cmd >> 24) & 0x1f) {
case 0x6:
return debug(stream, "3DSTATE_ANTI_ALIASING", 1);
case 0x7:
return debug(stream, "3DSTATE_RASTERIZATION_RULES", 1);
case 0x8:
return debug(stream, "3DSTATE_BACKFACE_STENCIL_OPS", 2);
case 0x9:
return debug(stream, "3DSTATE_BACKFACE_STENCIL_MASKS", 1);
case 0xb:
return debug(stream, "3DSTATE_INDEPENDENT_ALPHA_BLEND", 1);
case 0xc:
return debug(stream, "3DSTATE_MODES5", 1);
case 0xd:
return debug_modes4(stream, "3DSTATE_MODES4", 1);
case 0x15:
return debug(stream, "3DSTATE_FOG_COLOR", 1);
case 0x16:
return debug(stream, "3DSTATE_COORD_SET_BINDINGS", 1);
case 0x1c:
/* 3DState16NP */
switch((cmd >> 19) & 0x1f) {
case 0x10:
return debug(stream, "3DSTATE_SCISSOR_ENABLE", 1);
case 0x11:
return debug(stream, "3DSTATE_DEPTH_SUBRECTANGLE_DISABLE", 1);
default:
(void) debug(stream, "UNKNOWN 0x1c case!", 1);
assert(0);
break;
}
break;
case 0x1d:
/* 3DStateMW */
switch ((cmd >> 16) & 0xff) {
case 0x0:
return debug_map_state(stream, "3DSTATE_MAP_STATE", (cmd & 0x1f) + 2);
case 0x1:
return debug_sampler_state(stream, "3DSTATE_SAMPLER_STATE", (cmd & 0x1f) + 2);
case 0x4:
return debug_load_immediate(stream, "3DSTATE_LOAD_STATE_IMMEDIATE", (cmd & 0xf) + 2);
case 0x5:
return debug_program(stream, "3DSTATE_PIXEL_SHADER_PROGRAM", (cmd & 0x1ff) + 2);
case 0x6:
return debug(stream, "3DSTATE_PIXEL_SHADER_CONSTANTS", (cmd & 0xff) + 2);
case 0x7:
return debug_load_indirect(stream, "3DSTATE_LOAD_INDIRECT", (cmd & 0xff) + 2);
case 0x80:
return debug(stream, "3DSTATE_DRAWING_RECTANGLE", (cmd & 0xffff) + 2);
case 0x81:
return debug(stream, "3DSTATE_SCISSOR_RECTANGLE", (cmd & 0xffff) + 2);
case 0x83:
return debug(stream, "3DSTATE_SPAN_STIPPLE", (cmd & 0xffff) + 2);
case 0x85:
return debug_dest_vars(stream, "3DSTATE_DEST_BUFFER_VARS", (cmd & 0xffff) + 2);
case 0x88:
return debug(stream, "3DSTATE_CONSTANT_BLEND_COLOR", (cmd & 0xffff) + 2);
case 0x89:
return debug(stream, "3DSTATE_FOG_MODE", (cmd & 0xffff) + 2);
case 0x8e:
return debug_buf_info(stream, "3DSTATE_BUFFER_INFO", (cmd & 0xffff) + 2);
case 0x97:
return debug(stream, "3DSTATE_DEPTH_OFFSET_SCALE", (cmd & 0xffff) + 2);
case 0x98:
return debug(stream, "3DSTATE_DEFAULT_Z", (cmd & 0xffff) + 2);
case 0x99:
return debug(stream, "3DSTATE_DEFAULT_DIFFUSE", (cmd & 0xffff) + 2);
case 0x9a:
return debug(stream, "3DSTATE_DEFAULT_SPECULAR", (cmd & 0xffff) + 2);
case 0x9c:
return debug(stream, "3DSTATE_CLEAR_PARAMETERS", (cmd & 0xffff) + 2);
default:
assert(0);
return 0;
}
break;
case 0x1e:
if (cmd & (1 << 23))
return debug(stream, "???", (cmd & 0xffff) + 1);
else
return debug(stream, "", 1);
break;
case 0x1f:
if ((cmd & (1 << 23)) == 0)
return debug_prim(stream, "3DPRIM (inline)", 1, (cmd & 0x1ffff) + 2);
else if (cmd & (1 << 17))
{
if ((cmd & 0xffff) == 0)
return debug_variable_length_prim(stream);
else
return debug_prim(stream, "3DPRIM (indexed)", 0, (((cmd & 0xffff) + 1) / 2) + 1);
}
else
return debug_prim(stream, "3DPRIM (indirect sequential)", 0, 2);
break;
default:
return debug(stream, "", 0);
}
break;
default:
assert(0);
return 0;
}
assert(0);
return 0;
}
void
i915_dump_batchbuffer( struct i915_winsys_batchbuffer *batch )
{
struct debug_stream stream;
unsigned *start = (unsigned*)batch->map;
unsigned *end = (unsigned*)batch->ptr;
unsigned long bytes = (unsigned long) (end - start) * 4;
boolean done = FALSE;
stream.offset = 0;
stream.ptr = (char *)start;
stream.print_addresses = 0;
if (!start || !end) {
debug_printf( "\n\nBATCH: ???\n");
return;
}
debug_printf( "\n\nBATCH: (%d)\n", (int)bytes / 4);
while (!done &&
stream.offset < bytes)
{
if (!i915_debug_packet( &stream ))
break;
assert(stream.offset <= bytes);
}
debug_printf( "END-BATCH\n\n\n");
}
/***********************************************************************
* Dirty state atom dumping
*/
void
i915_dump_dirty(struct i915_context *i915, const char *func)
{
struct {
unsigned dirty;
const char *name;
} l[] = {
{I915_NEW_VIEWPORT, "viewport"},
{I915_NEW_RASTERIZER, "rasterizer"},
{I915_NEW_FS, "fs"},
{I915_NEW_BLEND, "blend"},
{I915_NEW_CLIP, "clip"},
{I915_NEW_SCISSOR, "scissor"},
{I915_NEW_STIPPLE, "stipple"},
{I915_NEW_FRAMEBUFFER, "framebuffer"},
{I915_NEW_ALPHA_TEST, "alpha_test"},
{I915_NEW_DEPTH_STENCIL, "depth_stencil"},
{I915_NEW_SAMPLER, "sampler"},
{I915_NEW_SAMPLER_VIEW, "sampler_view"},
{I915_NEW_VS_CONSTANTS, "vs_const"},
{I915_NEW_FS_CONSTANTS, "fs_const"},
{I915_NEW_VBO, "vbo"},
{I915_NEW_VS, "vs"},
{0, NULL},
};
int i;
debug_printf("%s: ", func);
for (i = 0; l[i].name; i++)
if (i915->dirty & l[i].dirty)
debug_printf("%s ", l[i].name);
debug_printf("\n");
}
void
i915_dump_hardware_dirty(struct i915_context *i915, const char *func)
{
struct {
unsigned dirty;
const char *name;
} l[] = {
{I915_HW_STATIC, "static"},
{I915_HW_DYNAMIC, "dynamic"},
{I915_HW_SAMPLER, "sampler"},
{I915_HW_MAP, "map"},
{I915_HW_PROGRAM, "program"},
{I915_HW_CONSTANTS, "constants"},
{I915_HW_IMMEDIATE, "immediate"},
{I915_HW_INVARIANT, "invariant"},
{0, NULL},
};
int i;
debug_printf("%s: ", func);
for (i = 0; l[i].name; i++)
if (i915->hardware_dirty & l[i].dirty)
debug_printf("%s ", l[i].name);
debug_printf("\n");
}
| {
"pile_set_name": "Github"
} |
###########################################################################
#
# This file is auto-generated by the Perl DateTime Suite time locale
# generator (0.03). This code generator comes with the
# DateTime::Locale distribution in the tools/ directory, and is called
# generate_from_cldr.
#
# This file as generated from the CLDR XML locale data. See the
# LICENSE.cldr file included in this distribution for license details.
#
# This file was generated from the source file en_BW.xml.
# The source file version number was 1.36, generated on
# 2006/06/28 01:23:32.
#
# Do not edit this file directly.
#
###########################################################################
package DateTime::Locale::en_BW;
use strict;
BEGIN
{
if ( $] >= 5.006 )
{
require utf8; utf8->import;
}
}
use DateTime::Locale::en;
@DateTime::Locale::en_BW::ISA = qw(DateTime::Locale::en);
my $date_parts_order = "dmy";
sub full_date_format { "\%A\ \%d\ \%B\ \%\{ce_year\}" }
sub long_date_format { "\%d\ \%B\ \%\{ce_year\}" }
sub medium_date_format { "\%b\ \%d\,\%y" }
sub short_date_format { "\%d\/\%m\/\%y" }
sub full_time_format { "\%\{hour_12\}\:\%M\:\%S\ \%p" }
sub long_time_format { "\%\{hour_12\}\:\%M\:\%S\ \%p" }
sub date_parts_order { $date_parts_order }
1;
| {
"pile_set_name": "Github"
} |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import k3d\n",
"import math\n",
"import numpy as np\n",
"\n",
"# Y-Z flip\n",
"model_matrix = [\n",
" 1.0, 0.0, 0.0, 0.0,\n",
" 0.0, -1.0, 0.0, 0.0,\n",
" 0.0, 0.0, 1.0, 0.0,\n",
" 0.0, 0.0, 0.0, 1.0\n",
"]\n",
"\n",
"texture = k3d.texture(open('assets/texture.png', 'br').read(), 'png', \n",
" rotation=[math.radians(90),1,0,0], \n",
" model_matrix = model_matrix,\n",
" name='Photo')\n",
"\n",
"plot = k3d.plot()\n",
"plot += texture\n",
"plot.display()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"texture.binary = open('assets/mandelbrot.jpg', 'br').read()\n",
"texture.name = 'Fractal'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"texture.model_matrix = np.identity(4, dtype=np.float32)\n",
"texture.transform.rotation = np.zeros_like(texture.transform.rotation)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"texture.puv = np.array([\n",
" -5.0, 0.0, -5.0, # p\n",
" 10.0, 0.0, 0.0, # u\n",
" 0.0, 0.0, 10.0 # v\n",
"], dtype=np.float32)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot.camera_reset()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from k3d.helpers import download\n",
"filename = download('https://github.com/FNNDSC/data/raw/master/nifti/adi_brain/adi_brain.nii.gz')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import nibabel as nib\n",
"nii_source = nib.load(filename)\n",
"img = nii_source.get_fdata()\n",
"dx, dy, dz = nii_source.header.get_zooms()\n",
"img = np.swapaxes(img,0,2)\n",
"nz, ny, nx = img.shape"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from ipywidgets import widgets,interact\n",
"\n",
"plot = k3d.plot()\n",
"\n",
"bounds = [0, nx * dx, 0, ny * dy, 0, nz * dz]\n",
"\n",
"texture = k3d.texture(attribute=img[0,:,:], \n",
" color_map=k3d.basic_color_maps.Jet, \n",
" color_range=[0.0, 1024.0],\n",
" bounds=bounds,\n",
" name='Slice')\n",
"plot += texture\n",
"\n",
"@interact(x=widgets.IntRangeSlider(value=[0, 1024], min=0, max=np.max(img), step=1, description='Color range:'))\n",
"def g(x):\n",
" texture.color_range = x\n",
" \n",
"@interact(z=widgets.IntSlider(value=0,min=0,max=img.shape[0]-1,step=1, description='Slice:'))\n",
"def g(z):\n",
" texture.attribute =img[z, :, :]\n",
" texture.transform.bounds = [bounds[0], bounds[1], bounds[2], bounds[3], -1 + z * dz, 1 + z * dz]\n",
"\n",
"plot.display()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot.grid_auto_fit = False\n",
"plot.camera_auto_fit = False"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot += k3d.marching_cubes(img.astype(np.float32), level=900, bounds=bounds, color=0xff0000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"bounds = [0, nx * dx, 0, ny * dy, 0, nz * dz]\n",
"\n",
"texture = k3d.texture(attribute=img[0,:,:], \n",
" color_map=k3d.basic_color_maps.Jet, \n",
" color_range=[0.0, 1024.0],\n",
" bounds=bounds,\n",
" name='Slice')\n",
"plot += texture"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
| {
"pile_set_name": "Github"
} |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="AuditTypeSystem" type="JUnit" factoryName="JUnit" folderName="Tests from IDEA Project">
<module name="testbench" />
<option name="PACKAGE_NAME" value="jetbrains.mps.testbench.junit.suites" />
<option name="MAIN_CLASS_NAME" value="jetbrains.mps.testbench.junit.suites.MPSAuditTypesystem" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-ea -Dmps.junit.project=. -noverify -Xmx2048m -XX:NewSize=384m -XX:+HeapDumpOnOutOfMemoryError -client" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<RunnerSettings RunnerId="Profile " />
<RunnerSettings RunnerId="Run" />
<ConfigurationWrapper RunnerId="Run" />
<method v="2">
<option name="Make" enabled="true" />
<option name="BuildArtifacts" enabled="true">
<artifact name="bootstrap:mps-annotations" />
<artifact name="bootstrap:mps-core" />
<artifact name="bootstrap:mps-editor" />
<artifact name="bootstrap:mps-openapi" />
<artifact name="bootstrap:mps-platform" />
<artifact name="bootstrap:mps-testbench" />
<artifact name="bootstrap:mps-workbench" />
<artifact name="migration-platform" />
</option>
<option name="AntTarget" enabled="true" antfile="file://$PROJECT_DIR$/testbench/cleanup.xml" target="cleanup" />
</method>
</configuration>
</component> | {
"pile_set_name": "Github"
} |
@extends('themes.default1.layouts.login')
@section('body')
<div class="row">
<div class="col-xs-12">
<!-- check whether success or not -->
@if(Session::has('success'))
<div class="alert alert-success alert-dismissable">
<i class="fa fa-check-circle"></i>
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{{Session::get('success')}}
</div>
@endif
<!-- failure message -->
@if(Session::has('fails'))
<div class="alert alert-danger alert-dismissable">
<i class="fa fa-ban"></i><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<b>{!! Lang::get('lang.alert') !!} !</b>
{{Session::get('fails')}}
</div>
@endif
<h3>Database Update Required</h3>
<p>{{ucfirst(Config::get('app.name'))}} has been updated! Before we send you on your own way,
we have to update your database to the newest version.</p>
<p>The update process may take a little while, so please be patient.</p>
<p><a href="{{$url}}" class="btn btn-default">Update {{ucfirst(Config::get('app.name'))}} Database</a></p>
</div>
</div>
@stop | {
"pile_set_name": "Github"
} |
----
-- Copyright (c) 2012-2017 Apple Inc. All rights reserved.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
----
---------------------------------------------------
-- Upgrade database schema from VERSION 58 to 59 --
---------------------------------------------------
-- New indexes
create index JOB_PRIORITY_ASSIGNED_6d49a082 on JOB (
"PRIORITY",
"ASSIGNED",
"PAUSE",
"NOT_BEFORE"
);
create index JOB_ASSIGNED_PAUSE_NO_b2540b3b on JOB (
"ASSIGNED",
"PAUSE",
"NOT_BEFORE"
);
create index JOB_ASSIGNED_OVERDUE_e88f7afc on JOB (
"ASSIGNED",
"OVERDUE"
);
create or replace function next_job_all(now timestamp)
return integer is
cursor c1 is
select JOB_ID from JOB
where ASSIGNED is NULL and PAUSE = 0 and NOT_BEFORE <= now
order by PRIORITY desc
for update skip locked;
result integer;
begin
open c1;
fetch c1 into result;
close c1;
return result;
end;
/
create or replace function next_job_medium_high(now timestamp)
return integer is
cursor c1 is
select JOB_ID from JOB
where PRIORITY != 0 and ASSIGNED is NULL and PAUSE = 0 and NOT_BEFORE <= now
order by PRIORITY desc
for update skip locked;
result integer;
begin
open c1;
fetch c1 into result;
close c1;
return result;
end;
/
create or replace function next_job_high(now timestamp)
return integer is
cursor c1 is
select JOB_ID from JOB
where PRIORITY = 2 and ASSIGNED is NULL and PAUSE = 0 and NOT_BEFORE <= now
order by PRIORITY desc
for update skip locked;
result integer;
begin
open c1;
fetch c1 into result;
close c1;
return result;
end;
/
create or replace function overdue_job(now timestamp)
return integer is
cursor c1 is
select JOB_ID from JOB
where ASSIGNED is not NULL and OVERDUE <= now
for update skip locked;
result integer;
begin
open c1;
fetch c1 into result;
close c1;
return result;
end;
/
-- update the version
update CALENDARSERVER set VALUE = '59' where NAME = 'VERSION';
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<!--<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>-->
<typeAliases>
<typeAlias type="org.sang.bean.User" alias="user"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="userMapper.xml"/>
<mapper resource="provinceMapper.xml"/>
<mapper resource="aliasMapper.xml"/>
<mapper resource="cityMapper.xml"/>
<mapper resource="riceMapper.xml"/>
<mapper resource="noodleMapper.xml"/>
</mappers>
</configuration> | {
"pile_set_name": "Github"
} |
#############################################################################
# Tables adapted from the Xotl FACTION ASSIGNMENT & RARITY TABLES #
# Original tables can be found here: #
# http://www.classicbattletech.com/forums/index.php/topic,1219.0.html #
# As noted in the original files, these are fan works and should not be #
# taken as official in any way. #
# #
# Adaptation performed by Deric Page (aka Netzilla on #
# http://www.classicbattletech.com/forums/) #
# If any discrepancies are found between these files and the original #
# Xotl tables, please contact me by PM on the forums or via email: #
# [email protected]. #
# #
# Notes on adaptation: #
# * The original Xotl tables use a d1,000 to randomly determine the unit. #
# For the adaptation I simply use the frequency of the entry as the #
# MegaMek RAT Weight value. So, a unit that appears on rolls 101-200 #
# receives a base Weight of 100. #
#############################################################################
Mercenary Periphery General 3028 Assault Vehicles F
@Davion 3028 Assault Vehicles F,40
@Kurita 3028 Assault Vehicles F,40
@Liao 3028 Assault Vehicles F,40
@Marik 3028 Assault Vehicles F,40
@Steiner 3028 Assault Vehicles F,40
Partisan Heavy Tank (AC2),16
Partisan Heavy Tank (Standard),153
Schrek AC Carrier (Standard),16
Schrek PPC Carrier (Standard),90
Demolisher Heavy Tank (Standard Mk. I),185
Partisan Heavy Tank (LRM),16
Devastator Heavy Tank (Standard),53
Behemoth Heavy Tank (Standard),265
Rhino Fire Support Tank (Flamer),6 | {
"pile_set_name": "Github"
} |
; <<>> DiG 9.9.5-3ubuntu0.8-Ubuntu <<>> AXFR mt. @a.ns.mt. +nocomments +nocmd +noquestion +nostats +time=15
;; global options: +cmd
; Transfer failed.
| {
"pile_set_name": "Github"
} |
<body>
<p>This is <b>bold</b> text</p>
</body>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `assert_edn_parses_to` macro in crate `mentat_parser_utils`.">
<meta name="keywords" content="rust, rustlang, rust-lang, assert_edn_parses_to">
<title>mentat_parser_utils::assert_edn_parses_to - Rust</title>
<link rel="stylesheet" type="text/css" href="../normalize.css">
<link rel="stylesheet" type="text/css" href="../rustdoc.css"
id="mainThemeStyle">
<link rel="stylesheet" type="text/css" href="../dark.css">
<link rel="stylesheet" type="text/css" href="../light.css" id="themeStyle">
<script src="../storage.js"></script>
</head>
<body class="rustdoc macro">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<div class="sidebar-menu">☰</div>
<div class="sidebar-elems"><p class='location'><a href='index.html'>mentat_parser_utils</a></p><script>window.sidebarCurrent = {name: 'assert_edn_parses_to', ty: 'macro', relpath: ''};</script><script defer src="sidebar-items.js"></script></div>
</nav>
<div class="theme-picker">
<button id="theme-picker" aria-label="Pick another theme!">
<img src="../brush.svg" width="18" alt="Pick another theme!">
</button>
<div id="theme-choices"></div>
</div>
<script src="../theme.js"></script>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content"><h1 class='fqn'><span class='in-band'>Macro <a href='index.html'>mentat_parser_utils</a>::<wbr><a class="macro" href=''>assert_edn_parses_to</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a class='srclink' href='../src/mentat_parser_utils/macros.rs.html#100-108' title='goto source code'>[src]</a></span></h1><div class="docblock type-decl"><pre class="rust macro">
<span class="macro">macro_rules</span><span class="macro">!</span> <span class="ident">assert_edn_parses_to</span> {
( <span class="macro-nonterminal">$</span><span class="macro-nonterminal">parser</span>: <span class="ident">expr</span>, <span class="macro-nonterminal">$</span><span class="macro-nonterminal">input</span>: <span class="ident">expr</span>, <span class="macro-nonterminal">$</span><span class="macro-nonterminal">expected</span>: <span class="ident">expr</span> ) <span class="op">=></span> { ... };
}</pre>
</div><div class='docblock'><p><code>assert_edn_parses_to!</code> simplifies some of the boilerplate around running a parser function
against string input and expecting a certain result.</p>
</div></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt><kbd>?</kbd></dt>
<dd>Show this help dialog</dd>
<dt><kbd>S</kbd></dt>
<dd>Focus the search field</dd>
<dt><kbd>↑</kbd></dt>
<dd>Move up in search results</dd>
<dt><kbd>↓</kbd></dt>
<dd>Move down in search results</dd>
<dt><kbd>↹</kbd></dt>
<dd>Switch tab</dd>
<dt><kbd>⏎</kbd></dt>
<dd>Go to active search result</dd>
<dt><kbd>+</kbd></dt>
<dd>Expand all sections</dd>
<dt><kbd>-</kbd></dt>
<dd>Collapse all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../";
window.currentCrate = "mentat_parser_utils";
</script>
<script src="../main.js"></script>
<script defer src="../search-index.js"></script>
</body>
</html> | {
"pile_set_name": "Github"
} |
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.bvt.sql.mysql.update;
import com.alibaba.druid.sql.MysqlTest;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.stat.TableStat.Column;
import com.alibaba.druid.wall.WallUtils;
import org.junit.Assert;
import java.util.List;
public class MySqlUpdateTest_10 extends MysqlTest {
public void test_0() throws Exception {
String sql = "UPDATE car_tt set gps_url=null WHERE id = ?";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
Assert.assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
Assert.assertEquals(1, visitor.getTables().size());
Assert.assertEquals(2, visitor.getColumns().size());
// Assert.assertEquals(2, visitor.getConditions().size());
Assert.assertTrue(visitor.containsTable("car_tt"));
Assert.assertTrue(visitor.getColumns().contains(new Column("car_tt", "id")));
Assert.assertTrue(visitor.getColumns().contains(new Column("car_tt", "gps_url")));
{
String output = SQLUtils.toMySqlString(stmt);
Assert.assertEquals("UPDATE car_tt\n" +
"SET gps_url = NULL\n" +
"WHERE id = ?", //
output);
}
{
String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
Assert.assertEquals("update car_tt\n" +
"set gps_url = null\n" +
"where id = ?", //
output);
}
assertTrue(WallUtils.isValidateMySql(sql));
}
}
| {
"pile_set_name": "Github"
} |
{
"name": "GetSocial",
"version": "6.24.6",
"summary": "GetSocial provides the whole social layer stack that powers engagement, retention, acquisition and revenue tools.",
"description": "GetSocial lets you create highly effective in-app social marketing platforms. \n\nIn fact, you can build in-app social networks within your eco-system of apps. We’ve made it incredibly easy to blend social engagement, user acquisition & promotional layers into your app – seamlessly – with full stack solutions. \n\nOur tool suite supports your app’s entire user lifecycle. And you get it all from just one great source. GetSocial.",
"homepage": "http://www.getsocial.im",
"social_media_url": "https://twitter.com/GetSocial_now",
"documentation_url": "http://docs.getsocial.im",
"license": {
"type": "Commercial",
"text": "See https://www.getsocial.im/legal/"
},
"authors": {
"GetSocial": "[email protected]"
},
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"preserve_paths": "GetSocial/README.md",
"source": {
"http": "https://downloads.getsocial.im/ios/GetSocial-iOS-v6.24.6.zip"
},
"subspecs": [
{
"name": "Core",
"compiler_flags": "-ObjC",
"vendored_frameworks": "GetSocial/GetSocial.framework"
},
{
"name": "UI",
"dependencies": {
"GetSocial/Core": [
]
},
"vendored_frameworks": "GetSocial/GetSocialUI.framework"
}
]
}
| {
"pile_set_name": "Github"
} |
# coding: utf-8
from __future__ import unicode_literals
import pytest
from spacy.util import get_lang_class
# Only include languages with no external dependencies
# "is" seems to confuse importlib, so we're also excluding it for now
# excluded: ja, ru, th, uk, vi, zh, is
LANGUAGES = [
pytest.param("fr", marks=pytest.mark.slow()),
pytest.param("af", marks=pytest.mark.slow()),
pytest.param("ar", marks=pytest.mark.slow()),
pytest.param("bg", marks=pytest.mark.slow()),
"bn",
pytest.param("ca", marks=pytest.mark.slow()),
pytest.param("cs", marks=pytest.mark.slow()),
pytest.param("da", marks=pytest.mark.slow()),
pytest.param("de", marks=pytest.mark.slow()),
"el",
"en",
pytest.param("es", marks=pytest.mark.slow()),
pytest.param("et", marks=pytest.mark.slow()),
pytest.param("fa", marks=pytest.mark.slow()),
pytest.param("fi", marks=pytest.mark.slow()),
"fr",
pytest.param("ga", marks=pytest.mark.slow()),
pytest.param("he", marks=pytest.mark.slow()),
pytest.param("hi", marks=pytest.mark.slow()),
pytest.param("hr", marks=pytest.mark.slow()),
"hu",
pytest.param("id", marks=pytest.mark.slow()),
pytest.param("it", marks=pytest.mark.slow()),
pytest.param("kn", marks=pytest.mark.slow()),
pytest.param("lb", marks=pytest.mark.slow()),
pytest.param("lt", marks=pytest.mark.slow()),
pytest.param("lv", marks=pytest.mark.slow()),
pytest.param("nb", marks=pytest.mark.slow()),
pytest.param("nl", marks=pytest.mark.slow()),
"pl",
pytest.param("pt", marks=pytest.mark.slow()),
pytest.param("ro", marks=pytest.mark.slow()),
pytest.param("si", marks=pytest.mark.slow()),
pytest.param("sk", marks=pytest.mark.slow()),
pytest.param("sl", marks=pytest.mark.slow()),
pytest.param("sq", marks=pytest.mark.slow()),
pytest.param("sr", marks=pytest.mark.slow()),
pytest.param("sv", marks=pytest.mark.slow()),
pytest.param("ta", marks=pytest.mark.slow()),
pytest.param("te", marks=pytest.mark.slow()),
pytest.param("tl", marks=pytest.mark.slow()),
pytest.param("tr", marks=pytest.mark.slow()),
pytest.param("tt", marks=pytest.mark.slow()),
pytest.param("ur", marks=pytest.mark.slow()),
]
@pytest.mark.parametrize("lang", LANGUAGES)
def test_tokenizer_explain(lang):
tokenizer = get_lang_class(lang).Defaults.create_tokenizer()
examples = pytest.importorskip("spacy.lang.{}.examples".format(lang))
for sentence in examples.sentences:
tokens = [t.text for t in tokenizer(sentence) if not t.is_space]
debug_tokens = [t[1] for t in tokenizer.explain(sentence)]
assert tokens == debug_tokens
| {
"pile_set_name": "Github"
} |
// an example CommonJs module
// content is omitted for brevity
exports.readFile = function() {};
// using module.exports would be equivalent,
// webpack doesn't care which syntax is used
// AMD modules are also possible and equivalent to CommonJs modules
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2018 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package levenshtein2
import "fmt"
// StateLimit is the maximum number of states allowed
const StateLimit = 10000
// ErrTooManyStates is returned if you attempt to build a Levenshtein
// automaton which requires too many states.
var ErrTooManyStates = fmt.Errorf("dfa contains more than %d states",
StateLimit)
// LevenshteinAutomatonBuilder wraps a precomputed
// datastructure that allows to produce small (but not minimal) DFA.
type LevenshteinAutomatonBuilder struct {
pDfa *ParametricDFA
}
// NewLevenshteinAutomatonBuilder creates a
// reusable, threadsafe Levenshtein automaton builder.
// `maxDistance` - maximum distance considered by the automaton.
// `transposition` - assign a distance of 1 for transposition
//
// Building this automaton builder is computationally intensive.
// While it takes only a few milliseconds for `d=2`, it grows
// exponentially with `d`. It is only reasonable to `d <= 5`.
func NewLevenshteinAutomatonBuilder(maxDistance uint8,
transposition bool) (*LevenshteinAutomatonBuilder, error) {
lnfa := newLevenshtein(maxDistance, transposition)
pdfa, err := fromNfa(lnfa)
if err != nil {
return nil, err
}
return &LevenshteinAutomatonBuilder{pDfa: pdfa}, nil
}
// BuildDfa builds the levenshtein automaton for serving
// queries with a given edit distance.
func (lab *LevenshteinAutomatonBuilder) BuildDfa(query string,
fuzziness uint8) (*DFA, error) {
return lab.pDfa.buildDfa(query, fuzziness, false)
}
// MaxDistance returns the MaxEdit distance supported by the
// LevenshteinAutomatonBuilder builder.
func (lab *LevenshteinAutomatonBuilder) MaxDistance() uint8 {
return lab.pDfa.maxDistance
}
| {
"pile_set_name": "Github"
} |
// TicketDesk - Attribution notice
// Original Code By:
// Samuel Neff - https://github.com/samuelneff/MimeTypeMap
//
// Contributor(s):
//
// Stephen Redd (https://github.com/stephenredd)
//
// This file is distributed under the terms of the Microsoft Public
// License (Ms-PL). See http://opensource.org/licenses/MS-PL
// for the complete terms of use.
//
// For any distribution that contains code from this file, this notice of
// attribution must remain intact, and a copy of the license must be
// provided to the recipient.
using System;
using System.Collections.Generic;
namespace TicketDesk.Web.Client
{
public static class MimeTypeMap
{
private static readonly IDictionary<string, string> Mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {
#region Big freaking list of mime types
// combination of values from Windows 7 Registry and
// from C:\Windows\System32\inetsrv\config\applicationHost.config
// some added, including .7z and .dat
{".323", "text/h323"},
{".3g2", "video/3gpp2"},
{".3gp", "video/3gpp"},
{".3gp2", "video/3gpp2"},
{".3gpp", "video/3gpp"},
{".7z", "application/x-7z-compressed"},
{".aa", "audio/audible"},
{".AAC", "audio/aac"},
{".aaf", "application/octet-stream"},
{".aax", "audio/vnd.audible.aax"},
{".ac3", "audio/ac3"},
{".aca", "application/octet-stream"},
{".accda", "application/msaccess.addin"},
{".accdb", "application/msaccess"},
{".accdc", "application/msaccess.cab"},
{".accde", "application/msaccess"},
{".accdr", "application/msaccess.runtime"},
{".accdt", "application/msaccess"},
{".accdw", "application/msaccess.webapplication"},
{".accft", "application/msaccess.ftemplate"},
{".acx", "application/internet-property-stream"},
{".AddIn", "text/xml"},
{".ade", "application/msaccess"},
{".adobebridge", "application/x-bridge-url"},
{".adp", "application/msaccess"},
{".ADT", "audio/vnd.dlna.adts"},
{".ADTS", "audio/aac"},
{".afm", "application/octet-stream"},
{".ai", "application/postscript"},
{".aif", "audio/x-aiff"},
{".aifc", "audio/aiff"},
{".aiff", "audio/aiff"},
{".air", "application/vnd.adobe.air-application-installer-package+zip"},
{".amc", "application/x-mpeg"},
{".application", "application/x-ms-application"},
{".art", "image/x-jg"},
{".asa", "application/xml"},
{".asax", "application/xml"},
{".ascx", "application/xml"},
{".asd", "application/octet-stream"},
{".asf", "video/x-ms-asf"},
{".ashx", "application/xml"},
{".asi", "application/octet-stream"},
{".asm", "text/plain"},
{".asmx", "application/xml"},
{".aspx", "application/xml"},
{".asr", "video/x-ms-asf"},
{".asx", "video/x-ms-asf"},
{".atom", "application/atom+xml"},
{".au", "audio/basic"},
{".avi", "video/x-msvideo"},
{".axs", "application/olescript"},
{".bas", "text/plain"},
{".bcpio", "application/x-bcpio"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".cab", "application/octet-stream"},
{".caf", "audio/x-caf"},
{".calx", "application/vnd.ms-office.calx"},
{".cat", "application/vnd.ms-pki.seccat"},
{".cc", "text/plain"},
{".cd", "text/plain"},
{".cdda", "audio/aiff"},
{".cdf", "application/x-cdf"},
{".cer", "application/x-x509-ca-cert"},
{".chm", "application/octet-stream"},
{".class", "application/x-java-applet"},
{".clp", "application/x-msclip"},
{".cmx", "image/x-cmx"},
{".cnf", "text/plain"},
{".cod", "image/cis-cod"},
{".config", "application/xml"},
{".contact", "text/x-ms-contact"},
{".coverage", "application/xml"},
{".cpio", "application/x-cpio"},
{".cpp", "text/plain"},
{".crd", "application/x-mscardfile"},
{".crl", "application/pkix-crl"},
{".crt", "application/x-x509-ca-cert"},
{".cs", "text/plain"},
{".csdproj", "text/plain"},
{".csh", "application/x-csh"},
{".csproj", "text/plain"},
{".css", "text/css"},
{".csv", "text/csv"},
{".cur", "application/octet-stream"},
{".cxx", "text/plain"},
{".dat", "application/octet-stream"},
{".datasource", "application/xml"},
{".dbproj", "text/plain"},
{".dcr", "application/x-director"},
{".def", "text/plain"},
{".deploy", "application/octet-stream"},
{".der", "application/x-x509-ca-cert"},
{".dgml", "application/xml"},
{".dib", "image/bmp"},
{".dif", "video/x-dv"},
{".dir", "application/x-director"},
{".disco", "text/xml"},
{".dll", "application/x-msdownload"},
{".dll.config", "text/xml"},
{".dlm", "text/dlm"},
{".doc", "application/msword"},
{".docm", "application/vnd.ms-word.document.macroEnabled.12"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".dot", "application/msword"},
{".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
{".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{".dsp", "application/octet-stream"},
{".dsw", "text/plain"},
{".dtd", "text/xml"},
{".dtsConfig", "text/xml"},
{".dv", "video/x-dv"},
{".dvi", "application/x-dvi"},
{".dwf", "drawing/x-dwf"},
{".dwp", "application/octet-stream"},
{".dxr", "application/x-director"},
{".eml", "message/rfc822"},
{".emz", "application/octet-stream"},
{".eot", "application/octet-stream"},
{".eps", "application/postscript"},
{".etl", "application/etl"},
{".etx", "text/x-setext"},
{".evy", "application/envoy"},
{".exe", "application/octet-stream"},
{".exe.config", "text/xml"},
{".fdf", "application/vnd.fdf"},
{".fif", "application/fractals"},
{".filters", "Application/xml"},
{".fla", "application/octet-stream"},
{".flr", "x-world/x-vrml"},
{".flv", "video/x-flv"},
{".fsscript", "application/fsharp-script"},
{".fsx", "application/fsharp-script"},
{".generictest", "application/xml"},
{".gif", "image/gif"},
{".group", "text/x-ms-group"},
{".gsm", "audio/x-gsm"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".hdf", "application/x-hdf"},
{".hdml", "text/x-hdml"},
{".hhc", "application/x-oleobject"},
{".hhk", "application/octet-stream"},
{".hhp", "application/octet-stream"},
{".hlp", "application/winhlp"},
{".hpp", "text/plain"},
{".hqx", "application/mac-binhex40"},
{".hta", "application/hta"},
{".htc", "text/x-component"},
{".htm", "text/html"},
{".html", "text/html"},
{".htt", "text/webviewhtml"},
{".hxa", "application/xml"},
{".hxc", "application/xml"},
{".hxd", "application/octet-stream"},
{".hxe", "application/xml"},
{".hxf", "application/xml"},
{".hxh", "application/octet-stream"},
{".hxi", "application/octet-stream"},
{".hxk", "application/xml"},
{".hxq", "application/octet-stream"},
{".hxr", "application/octet-stream"},
{".hxs", "application/octet-stream"},
{".hxt", "text/html"},
{".hxv", "application/xml"},
{".hxw", "application/octet-stream"},
{".hxx", "text/plain"},
{".i", "text/plain"},
{".ico", "image/x-icon"},
{".ics", "application/octet-stream"},
{".idl", "text/plain"},
{".ief", "image/ief"},
{".iii", "application/x-iphone"},
{".inc", "text/plain"},
{".inf", "application/octet-stream"},
{".inl", "text/plain"},
{".ins", "application/x-internet-signup"},
{".ipa", "application/x-itunes-ipa"},
{".ipg", "application/x-itunes-ipg"},
{".ipproj", "text/plain"},
{".ipsw", "application/x-itunes-ipsw"},
{".iqy", "text/x-ms-iqy"},
{".isp", "application/x-internet-signup"},
{".ite", "application/x-itunes-ite"},
{".itlp", "application/x-itunes-itlp"},
{".itms", "application/x-itunes-itms"},
{".itpc", "application/x-itunes-itpc"},
{".IVF", "video/x-ivf"},
{".jar", "application/java-archive"},
{".java", "application/octet-stream"},
{".jck", "application/liquidmotion"},
{".jcz", "application/liquidmotion"},
{".jfif", "image/pjpeg"},
{".jnlp", "application/x-java-jnlp-file"},
{".jpb", "application/octet-stream"},
{".jpe", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".json", "application/json"},
{".jsx", "text/jscript"},
{".jsxbin", "text/plain"},
{".latex", "application/x-latex"},
{".library-ms", "application/windows-library+xml"},
{".lit", "application/x-ms-reader"},
{".loadtest", "application/xml"},
{".lpk", "application/octet-stream"},
{".lsf", "video/x-la-asf"},
{".lst", "text/plain"},
{".lsx", "video/x-la-asf"},
{".lzh", "application/octet-stream"},
{".m13", "application/x-msmediaview"},
{".m14", "application/x-msmediaview"},
{".m1v", "video/mpeg"},
{".m2t", "video/vnd.dlna.mpeg-tts"},
{".m2ts", "video/vnd.dlna.mpeg-tts"},
{".m2v", "video/mpeg"},
{".m3u", "audio/x-mpegurl"},
{".m3u8", "audio/x-mpegurl"},
{".m4a", "audio/m4a"},
{".m4b", "audio/m4b"},
{".m4p", "audio/m4p"},
{".m4r", "audio/x-m4r"},
{".m4v", "video/x-m4v"},
{".mac", "image/x-macpaint"},
{".mak", "text/plain"},
{".man", "application/x-troff-man"},
{".manifest", "application/x-ms-manifest"},
{".map", "text/plain"},
{".master", "application/xml"},
{".mda", "application/msaccess"},
{".mdb", "application/x-msaccess"},
{".mde", "application/msaccess"},
{".mdp", "application/octet-stream"},
{".me", "application/x-troff-me"},
{".mfp", "application/x-shockwave-flash"},
{".mht", "message/rfc822"},
{".mhtml", "message/rfc822"},
{".mid", "audio/mid"},
{".midi", "audio/mid"},
{".mix", "application/octet-stream"},
{".mk", "text/plain"},
{".mmf", "application/x-smaf"},
{".mno", "text/xml"},
{".mny", "application/x-msmoney"},
{".mod", "video/mpeg"},
{".mov", "video/quicktime"},
{".movie", "video/x-sgi-movie"},
{".mp2", "video/mpeg"},
{".mp2v", "video/mpeg"},
{".mp3", "audio/mpeg"},
{".mp4", "video/mp4"},
{".mp4v", "video/mp4"},
{".mpa", "video/mpeg"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpf", "application/vnd.ms-mediapackage"},
{".mpg", "video/mpeg"},
{".mpp", "application/vnd.ms-project"},
{".mpv2", "video/mpeg"},
{".mqv", "video/quicktime"},
{".ms", "application/x-troff-ms"},
{".msi", "application/octet-stream"},
{".mso", "application/octet-stream"},
{".mts", "video/vnd.dlna.mpeg-tts"},
{".mtx", "application/xml"},
{".mvb", "application/x-msmediaview"},
{".mvc", "application/x-miva-compiled"},
{".mxp", "application/x-mmxp"},
{".nc", "application/x-netcdf"},
{".nsc", "video/x-ms-asf"},
{".nws", "message/rfc822"},
{".ocx", "application/octet-stream"},
{".oda", "application/oda"},
{".odc", "text/x-ms-odc"},
{".odh", "text/plain"},
{".odl", "text/plain"},
{".odp", "application/vnd.oasis.opendocument.presentation"},
{".ods", "application/oleobject"},
{".odt", "application/vnd.oasis.opendocument.text"},
{".one", "application/onenote"},
{".onea", "application/onenote"},
{".onepkg", "application/onenote"},
{".onetmp", "application/onenote"},
{".onetoc", "application/onenote"},
{".onetoc2", "application/onenote"},
{".orderedtest", "application/xml"},
{".osdx", "application/opensearchdescription+xml"},
{".p10", "application/pkcs10"},
{".p12", "application/x-pkcs12"},
{".p7b", "application/x-pkcs7-certificates"},
{".p7c", "application/pkcs7-mime"},
{".p7m", "application/pkcs7-mime"},
{".p7r", "application/x-pkcs7-certreqresp"},
{".p7s", "application/pkcs7-signature"},
{".pbm", "image/x-portable-bitmap"},
{".pcast", "application/x-podcast"},
{".pct", "image/pict"},
{".pcx", "application/octet-stream"},
{".pcz", "application/octet-stream"},
{".pdf", "application/pdf"},
{".pfb", "application/octet-stream"},
{".pfm", "application/octet-stream"},
{".pfx", "application/x-pkcs12"},
{".pgm", "image/x-portable-graymap"},
{".pic", "image/pict"},
{".pict", "image/pict"},
{".pkgdef", "text/plain"},
{".pkgundef", "text/plain"},
{".pko", "application/vnd.ms-pki.pko"},
{".pls", "audio/scpls"},
{".pma", "application/x-perfmon"},
{".pmc", "application/x-perfmon"},
{".pml", "application/x-perfmon"},
{".pmr", "application/x-perfmon"},
{".pmw", "application/x-perfmon"},
{".png", "image/png"},
{".pnm", "image/x-portable-anymap"},
{".pnt", "image/x-macpaint"},
{".pntg", "image/x-macpaint"},
{".pnz", "image/png"},
{".pot", "application/vnd.ms-powerpoint"},
{".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
{".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
{".ppa", "application/vnd.ms-powerpoint"},
{".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{".ppm", "image/x-portable-pixmap"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prf", "application/pics-rules"},
{".prm", "application/octet-stream"},
{".prx", "application/octet-stream"},
{".ps", "application/postscript"},
{".psc1", "application/PowerShell"},
{".psd", "application/octet-stream"},
{".psess", "application/xml"},
{".psm", "application/octet-stream"},
{".psp", "application/octet-stream"},
{".pub", "application/x-mspublisher"},
{".pwz", "application/vnd.ms-powerpoint"},
{".qht", "text/x-html-insertion"},
{".qhtm", "text/x-html-insertion"},
{".qt", "video/quicktime"},
{".qti", "image/x-quicktime"},
{".qtif", "image/x-quicktime"},
{".qtl", "application/x-quicktimeplayer"},
{".qxd", "application/octet-stream"},
{".ra", "audio/x-pn-realaudio"},
{".ram", "audio/x-pn-realaudio"},
{".rar", "application/octet-stream"},
{".ras", "image/x-cmu-raster"},
{".rat", "application/rat-file"},
{".rc", "text/plain"},
{".rc2", "text/plain"},
{".rct", "text/plain"},
{".rdlc", "application/xml"},
{".resx", "application/xml"},
{".rf", "image/vnd.rn-realflash"},
{".rgb", "image/x-rgb"},
{".rgs", "text/plain"},
{".rm", "application/vnd.rn-realmedia"},
{".rmi", "audio/mid"},
{".rmp", "application/vnd.rn-rn_music_package"},
{".roff", "application/x-troff"},
{".rpm", "audio/x-pn-realaudio-plugin"},
{".rqy", "text/x-ms-rqy"},
{".rtf", "application/rtf"},
{".rtx", "text/richtext"},
{".ruleset", "application/xml"},
{".s", "text/plain"},
{".safariextz", "application/x-safari-safariextz"},
{".scd", "application/x-msschedule"},
{".sct", "text/scriptlet"},
{".sd2", "audio/x-sd2"},
{".sdp", "application/sdp"},
{".sea", "application/octet-stream"},
{".searchConnector-ms", "application/windows-search-connector+xml"},
{".setpay", "application/set-payment-initiation"},
{".setreg", "application/set-registration-initiation"},
{".settings", "application/xml"},
{".sgimb", "application/x-sgimb"},
{".sgml", "text/sgml"},
{".sh", "application/x-sh"},
{".shar", "application/x-shar"},
{".shtml", "text/html"},
{".sit", "application/x-stuffit"},
{".sitemap", "application/xml"},
{".skin", "application/xml"},
{".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
{".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
{".slk", "application/vnd.ms-excel"},
{".sln", "text/plain"},
{".slupkg-ms", "application/x-ms-license"},
{".smd", "audio/x-smd"},
{".smi", "application/octet-stream"},
{".smx", "audio/x-smd"},
{".smz", "audio/x-smd"},
{".snd", "audio/basic"},
{".snippet", "application/xml"},
{".snp", "application/octet-stream"},
{".sol", "text/plain"},
{".sor", "text/plain"},
{".spc", "application/x-pkcs7-certificates"},
{".spl", "application/futuresplash"},
{".src", "application/x-wais-source"},
{".srf", "text/plain"},
{".SSISDeploymentManifest", "text/xml"},
{".ssm", "application/streamingmedia"},
{".sst", "application/vnd.ms-pki.certstore"},
{".stl", "application/vnd.ms-pki.stl"},
{".sv4cpio", "application/x-sv4cpio"},
{".sv4crc", "application/x-sv4crc"},
{".svc", "application/xml"},
{".swf", "application/x-shockwave-flash"},
{".t", "application/x-troff"},
{".tar", "application/x-tar"},
{".tcl", "application/x-tcl"},
{".testrunconfig", "application/xml"},
{".testsettings", "application/xml"},
{".tex", "application/x-tex"},
{".texi", "application/x-texinfo"},
{".texinfo", "application/x-texinfo"},
{".tgz", "application/x-compressed"},
{".thmx", "application/vnd.ms-officetheme"},
{".thn", "application/octet-stream"},
{".tif", "image/tiff"},
{".tiff", "image/tiff"},
{".tlh", "text/plain"},
{".tli", "text/plain"},
{".toc", "application/octet-stream"},
{".tr", "application/x-troff"},
{".trm", "application/x-msterminal"},
{".trx", "application/xml"},
{".ts", "video/vnd.dlna.mpeg-tts"},
{".tsv", "text/tab-separated-values"},
{".ttf", "application/octet-stream"},
{".tts", "video/vnd.dlna.mpeg-tts"},
{".txt", "text/plain"},
{".u32", "application/octet-stream"},
{".uls", "text/iuls"},
{".user", "text/plain"},
{".ustar", "application/x-ustar"},
{".vb", "text/plain"},
{".vbdproj", "text/plain"},
{".vbk", "video/mpeg"},
{".vbproj", "text/plain"},
{".vbs", "text/vbscript"},
{".vcf", "text/x-vcard"},
{".vcproj", "Application/xml"},
{".vcs", "text/plain"},
{".vcxproj", "Application/xml"},
{".vddproj", "text/plain"},
{".vdp", "text/plain"},
{".vdproj", "text/plain"},
{".vdx", "application/vnd.ms-visio.viewer"},
{".vml", "text/xml"},
{".vscontent", "application/xml"},
{".vsct", "text/xml"},
{".vsd", "application/vnd.visio"},
{".vsi", "application/ms-vsi"},
{".vsix", "application/vsix"},
{".vsixlangpack", "text/xml"},
{".vsixmanifest", "text/xml"},
{".vsmdi", "application/xml"},
{".vspscc", "text/plain"},
{".vss", "application/vnd.visio"},
{".vsscc", "text/plain"},
{".vssettings", "text/xml"},
{".vssscc", "text/plain"},
{".vst", "application/vnd.visio"},
{".vstemplate", "text/xml"},
{".vsto", "application/x-ms-vsto"},
{".vsw", "application/vnd.visio"},
{".vsx", "application/vnd.visio"},
{".vtx", "application/vnd.visio"},
{".wav", "audio/wav"},
{".wave", "audio/wav"},
{".wax", "audio/x-ms-wax"},
{".wbk", "application/msword"},
{".wbmp", "image/vnd.wap.wbmp"},
{".wcm", "application/vnd.ms-works"},
{".wdb", "application/vnd.ms-works"},
{".wdp", "image/vnd.ms-photo"},
{".webarchive", "application/x-safari-webarchive"},
{".webtest", "application/xml"},
{".wiq", "application/xml"},
{".wiz", "application/msword"},
{".wks", "application/vnd.ms-works"},
{".WLMP", "application/wlmoviemaker"},
{".wlpginstall", "application/x-wlpg-detect"},
{".wlpginstall3", "application/x-wlpg3-detect"},
{".wm", "video/x-ms-wm"},
{".wma", "audio/x-ms-wma"},
{".wmd", "application/x-ms-wmd"},
{".wmf", "application/x-msmetafile"},
{".wml", "text/vnd.wap.wml"},
{".wmlc", "application/vnd.wap.wmlc"},
{".wmls", "text/vnd.wap.wmlscript"},
{".wmlsc", "application/vnd.wap.wmlscriptc"},
{".wmp", "video/x-ms-wmp"},
{".wmv", "video/x-ms-wmv"},
{".wmx", "video/x-ms-wmx"},
{".wmz", "application/x-ms-wmz"},
{".wpl", "application/vnd.ms-wpl"},
{".wps", "application/vnd.ms-works"},
{".wri", "application/x-mswrite"},
{".wrl", "x-world/x-vrml"},
{".wrz", "x-world/x-vrml"},
{".wsc", "text/scriptlet"},
{".wsdl", "text/xml"},
{".wvx", "video/x-ms-wvx"},
{".x", "application/directx"},
{".xaf", "x-world/x-vrml"},
{".xaml", "application/xaml+xml"},
{".xap", "application/x-silverlight-app"},
{".xbap", "application/x-ms-xbap"},
{".xbm", "image/x-xbitmap"},
{".xdr", "text/plain"},
{".xht", "application/xhtml+xml"},
{".xhtml", "application/xhtml+xml"},
{".xla", "application/vnd.ms-excel"},
{".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
{".xlc", "application/vnd.ms-excel"},
{".xld", "application/vnd.ms-excel"},
{".xlk", "application/vnd.ms-excel"},
{".xll", "application/vnd.ms-excel"},
{".xlm", "application/vnd.ms-excel"},
{".xls", "application/vnd.ms-excel"},
{".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xlt", "application/vnd.ms-excel"},
{".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
{".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{".xlw", "application/vnd.ms-excel"},
{".xml", "text/xml"},
{".xmta", "application/xml"},
{".xof", "x-world/x-vrml"},
{".XOML", "text/plain"},
{".xpm", "image/x-xpixmap"},
{".xps", "application/vnd.ms-xpsdocument"},
{".xrm-ms", "text/xml"},
{".xsc", "application/xml"},
{".xsd", "text/xml"},
{".xsf", "text/xml"},
{".xsl", "text/xml"},
{".xslt", "text/xml"},
{".xsn", "application/octet-stream"},
{".xss", "application/xml"},
{".xtp", "application/octet-stream"},
{".xwd", "image/x-xwindowdump"},
{".z", "application/x-compress"},
{".zip", "application/x-zip-compressed"},
#endregion
};
public static string GetMimeType(string extension)
{
if (extension == null)
{
throw new ArgumentNullException("extension");
}
if (!extension.StartsWith("."))
{
extension = "." + extension;
}
string mime;
return Mappings.TryGetValue(extension, out mime) ? mime : "application/octet-stream";
}
}
}
| {
"pile_set_name": "Github"
} |
// Multiple extern declarations cause: Node is not in parent's child list,
// node: 0x2a97190010 = SgVariableDefinition = _variable_definition_APP_Unit_Range
// parent: 0x2a970a9030 = SgInitializedName
extern int APP_Unit_Range;
extern int APP_Unit_Range;
extern int APP_Unit_Range;
| {
"pile_set_name": "Github"
} |
use core::fmt::{self, Write};
extern "C" {
pub fn console_write_char(ch: u8);
}
pub static mut CONSOLE: Console = Console;
pub struct Console;
impl Write for Console {
fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
for byte in s.bytes() {
unsafe {
console_write_char(byte);
}
}
Ok(())
}
}
/// Print to console, with a newline.
#[macro_export]
macro_rules! println {
($fmt:expr) => (print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
}
/// Print to console.
#[macro_export]
macro_rules! print {
($($arg:tt)*) => ({
use core::fmt::Write;
unsafe { print::CONSOLE.write_fmt(format_args!($($arg)*)).unwrap(); }
});
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2003-2008 Takahiro Hirofuchi
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#ifndef __USBIP_COMMON_H
#define __USBIP_COMMON_H
#include <linux/compiler.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/net.h>
#include <linux/printk.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <linux/usb.h>
#include <linux/wait.h>
#include <uapi/linux/usbip.h>
#define USBIP_VERSION "1.0.0"
#undef pr_fmt
#ifdef DEBUG
#define pr_fmt(fmt) KBUILD_MODNAME ": %s:%d: " fmt, __func__, __LINE__
#else
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#endif
enum {
usbip_debug_xmit = (1 << 0),
usbip_debug_sysfs = (1 << 1),
usbip_debug_urb = (1 << 2),
usbip_debug_eh = (1 << 3),
usbip_debug_stub_cmp = (1 << 8),
usbip_debug_stub_dev = (1 << 9),
usbip_debug_stub_rx = (1 << 10),
usbip_debug_stub_tx = (1 << 11),
usbip_debug_vhci_rh = (1 << 8),
usbip_debug_vhci_hc = (1 << 9),
usbip_debug_vhci_rx = (1 << 10),
usbip_debug_vhci_tx = (1 << 11),
usbip_debug_vhci_sysfs = (1 << 12)
};
#define usbip_dbg_flag_xmit (usbip_debug_flag & usbip_debug_xmit)
#define usbip_dbg_flag_vhci_rh (usbip_debug_flag & usbip_debug_vhci_rh)
#define usbip_dbg_flag_vhci_hc (usbip_debug_flag & usbip_debug_vhci_hc)
#define usbip_dbg_flag_vhci_rx (usbip_debug_flag & usbip_debug_vhci_rx)
#define usbip_dbg_flag_vhci_tx (usbip_debug_flag & usbip_debug_vhci_tx)
#define usbip_dbg_flag_stub_rx (usbip_debug_flag & usbip_debug_stub_rx)
#define usbip_dbg_flag_stub_tx (usbip_debug_flag & usbip_debug_stub_tx)
#define usbip_dbg_flag_vhci_sysfs (usbip_debug_flag & usbip_debug_vhci_sysfs)
extern unsigned long usbip_debug_flag;
extern struct device_attribute dev_attr_usbip_debug;
#define usbip_dbg_with_flag(flag, fmt, args...) \
do { \
if (flag & usbip_debug_flag) \
pr_debug(fmt, ##args); \
} while (0)
#define usbip_dbg_sysfs(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_sysfs, fmt , ##args)
#define usbip_dbg_xmit(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_xmit, fmt , ##args)
#define usbip_dbg_urb(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_urb, fmt , ##args)
#define usbip_dbg_eh(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_eh, fmt , ##args)
#define usbip_dbg_vhci_rh(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_vhci_rh, fmt , ##args)
#define usbip_dbg_vhci_hc(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_vhci_hc, fmt , ##args)
#define usbip_dbg_vhci_rx(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_vhci_rx, fmt , ##args)
#define usbip_dbg_vhci_tx(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_vhci_tx, fmt , ##args)
#define usbip_dbg_vhci_sysfs(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_vhci_sysfs, fmt , ##args)
#define usbip_dbg_stub_cmp(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_stub_cmp, fmt , ##args)
#define usbip_dbg_stub_rx(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_stub_rx, fmt , ##args)
#define usbip_dbg_stub_tx(fmt, args...) \
usbip_dbg_with_flag(usbip_debug_stub_tx, fmt , ##args)
/*
* USB/IP request headers
*
* Each request is transferred across the network to its counterpart, which
* facilitates the normal USB communication. The values contained in the headers
* are basically the same as in a URB. Currently, four request types are
* defined:
*
* - USBIP_CMD_SUBMIT: a USB request block, corresponds to usb_submit_urb()
* (client to server)
*
* - USBIP_RET_SUBMIT: the result of USBIP_CMD_SUBMIT
* (server to client)
*
* - USBIP_CMD_UNLINK: an unlink request of a pending USBIP_CMD_SUBMIT,
* corresponds to usb_unlink_urb()
* (client to server)
*
* - USBIP_RET_UNLINK: the result of USBIP_CMD_UNLINK
* (server to client)
*
*/
#define USBIP_CMD_SUBMIT 0x0001
#define USBIP_CMD_UNLINK 0x0002
#define USBIP_RET_SUBMIT 0x0003
#define USBIP_RET_UNLINK 0x0004
#define USBIP_DIR_OUT 0x00
#define USBIP_DIR_IN 0x01
/**
* struct usbip_header_basic - data pertinent to every request
* @command: the usbip request type
* @seqnum: sequential number that identifies requests; incremented per
* connection
* @devid: specifies a remote USB device uniquely instead of busnum and devnum;
* in the stub driver, this value is ((busnum << 16) | devnum)
* @direction: direction of the transfer
* @ep: endpoint number
*/
struct usbip_header_basic {
__u32 command;
__u32 seqnum;
__u32 devid;
__u32 direction;
__u32 ep;
} __packed;
/**
* struct usbip_header_cmd_submit - USBIP_CMD_SUBMIT packet header
* @transfer_flags: URB flags
* @transfer_buffer_length: the data size for (in) or (out) transfer
* @start_frame: initial frame for isochronous or interrupt transfers
* @number_of_packets: number of isochronous packets
* @interval: maximum time for the request on the server-side host controller
* @setup: setup data for a control request
*/
struct usbip_header_cmd_submit {
__u32 transfer_flags;
__s32 transfer_buffer_length;
/* it is difficult for usbip to sync frames (reserved only?) */
__s32 start_frame;
__s32 number_of_packets;
__s32 interval;
unsigned char setup[8];
} __packed;
/**
* struct usbip_header_ret_submit - USBIP_RET_SUBMIT packet header
* @status: return status of a non-iso request
* @actual_length: number of bytes transferred
* @start_frame: initial frame for isochronous or interrupt transfers
* @number_of_packets: number of isochronous packets
* @error_count: number of errors for isochronous transfers
*/
struct usbip_header_ret_submit {
__s32 status;
__s32 actual_length;
__s32 start_frame;
__s32 number_of_packets;
__s32 error_count;
} __packed;
/**
* struct usbip_header_cmd_unlink - USBIP_CMD_UNLINK packet header
* @seqnum: the URB seqnum to unlink
*/
struct usbip_header_cmd_unlink {
__u32 seqnum;
} __packed;
/**
* struct usbip_header_ret_unlink - USBIP_RET_UNLINK packet header
* @status: return status of the request
*/
struct usbip_header_ret_unlink {
__s32 status;
} __packed;
/**
* struct usbip_header - common header for all usbip packets
* @base: the basic header
* @u: packet type dependent header
*/
struct usbip_header {
struct usbip_header_basic base;
union {
struct usbip_header_cmd_submit cmd_submit;
struct usbip_header_ret_submit ret_submit;
struct usbip_header_cmd_unlink cmd_unlink;
struct usbip_header_ret_unlink ret_unlink;
} u;
} __packed;
/*
* This is the same as usb_iso_packet_descriptor but packed for pdu.
*/
struct usbip_iso_packet_descriptor {
__u32 offset;
__u32 length; /* expected length */
__u32 actual_length;
__u32 status;
} __packed;
enum usbip_side {
USBIP_VHCI,
USBIP_STUB,
};
/* event handler */
#define USBIP_EH_SHUTDOWN (1 << 0)
#define USBIP_EH_BYE (1 << 1)
#define USBIP_EH_RESET (1 << 2)
#define USBIP_EH_UNUSABLE (1 << 3)
#define SDEV_EVENT_REMOVED (USBIP_EH_SHUTDOWN | USBIP_EH_RESET | USBIP_EH_BYE)
#define SDEV_EVENT_DOWN (USBIP_EH_SHUTDOWN | USBIP_EH_RESET)
#define SDEV_EVENT_ERROR_TCP (USBIP_EH_SHUTDOWN | USBIP_EH_RESET)
#define SDEV_EVENT_ERROR_SUBMIT (USBIP_EH_SHUTDOWN | USBIP_EH_RESET)
#define SDEV_EVENT_ERROR_MALLOC (USBIP_EH_SHUTDOWN | USBIP_EH_UNUSABLE)
#define VDEV_EVENT_REMOVED (USBIP_EH_SHUTDOWN | USBIP_EH_BYE)
#define VDEV_EVENT_DOWN (USBIP_EH_SHUTDOWN | USBIP_EH_RESET)
#define VDEV_EVENT_ERROR_TCP (USBIP_EH_SHUTDOWN | USBIP_EH_RESET)
#define VDEV_EVENT_ERROR_MALLOC (USBIP_EH_SHUTDOWN | USBIP_EH_UNUSABLE)
/* a common structure for stub_device and vhci_device */
struct usbip_device {
enum usbip_side side;
enum usbip_device_status status;
/* lock for status */
spinlock_t lock;
struct socket *tcp_socket;
struct task_struct *tcp_rx;
struct task_struct *tcp_tx;
unsigned long event;
struct task_struct *eh;
wait_queue_head_t eh_waitq;
struct eh_ops {
void (*shutdown)(struct usbip_device *);
void (*reset)(struct usbip_device *);
void (*unusable)(struct usbip_device *);
} eh_ops;
};
#define kthread_get_run(threadfn, data, namefmt, ...) \
({ \
struct task_struct *__k \
= kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \
if (!IS_ERR(__k)) { \
get_task_struct(__k); \
wake_up_process(__k); \
} \
__k; \
})
#define kthread_stop_put(k) \
do { \
kthread_stop(k); \
put_task_struct(k); \
} while (0)
/* usbip_common.c */
void usbip_dump_urb(struct urb *purb);
void usbip_dump_header(struct usbip_header *pdu);
int usbip_recv(struct socket *sock, void *buf, int size);
void usbip_pack_pdu(struct usbip_header *pdu, struct urb *urb, int cmd,
int pack);
void usbip_header_correct_endian(struct usbip_header *pdu, int send);
struct usbip_iso_packet_descriptor*
usbip_alloc_iso_desc_pdu(struct urb *urb, ssize_t *bufflen);
/* some members of urb must be substituted before. */
int usbip_recv_iso(struct usbip_device *ud, struct urb *urb);
void usbip_pad_iso(struct usbip_device *ud, struct urb *urb);
int usbip_recv_xbuff(struct usbip_device *ud, struct urb *urb);
/* usbip_event.c */
int usbip_start_eh(struct usbip_device *ud);
void usbip_stop_eh(struct usbip_device *ud);
void usbip_event_add(struct usbip_device *ud, unsigned long event);
int usbip_event_happened(struct usbip_device *ud);
static inline int interface_to_busnum(struct usb_interface *interface)
{
struct usb_device *udev = interface_to_usbdev(interface);
return udev->bus->busnum;
}
static inline int interface_to_devnum(struct usb_interface *interface)
{
struct usb_device *udev = interface_to_usbdev(interface);
return udev->devnum;
}
#endif /* __USBIP_COMMON_H */
| {
"pile_set_name": "Github"
} |
#include <cstdint>
#include <stddef.h>
#include <armadillo>
template< typename T>
class MappedCSR {
public:
MappedCSR();
MappedCSR(arma::uword n_rows,
arma::uword n_cols,
size_t nnz,
arma::uword * col_indices,
arma::uword * row_ptrs,
T * values):
n_rows(n_rows), n_cols(n_cols), nnz(nnz), col_indices(col_indices), row_ptrs(row_ptrs), values(values) {};
const arma::uword n_rows;
const arma::uword n_cols;
const size_t nnz;
arma::uword * col_indices;
arma::uword * row_ptrs;
T * values;
std::pair<arma::uvec, arma::Col<T>> get_row(const arma::uword i) const {
const arma::uword p1 = this->row_ptrs[i];
const arma::uword p2 = this->row_ptrs[i + 1];
const arma::uvec idx = arma::uvec(&this->col_indices[p1], p2 - p1, false, true);
const arma::Col<T> values = arma::Col<T>(&this->values[p1], p2 - p1, false, true);
return(std::pair<arma::uvec, arma::Col<T>>(idx, values));
};
};
using dMappedCSR = MappedCSR<double>;
using fMappedCSR = MappedCSR<float>;
template< typename T>
class MappedCSC {
public:
MappedCSC();
MappedCSC(arma::uword n_rows,
arma::uword n_cols,
size_t nnz,
arma::uword * row_indices,
arma::uword * col_ptrs,
T * values):
n_rows(n_rows), n_cols(n_cols), nnz(nnz), row_indices(row_indices), col_ptrs(col_ptrs), values(values) {};
const arma::uword n_rows;
const arma::uword n_cols;
const size_t nnz;
arma::uword * row_indices;
arma::uword * col_ptrs;
T * values;
};
using dMappedCSC = MappedCSC<double>;
using fMappedCSC = MappedCSC<float>;
| {
"pile_set_name": "Github"
} |
//
// DeviceResources.cpp - A wrapper for the Direct3D 11 device and swapchain
// (requires DirectX 11.X Xbox One Monolithic Runtime)
//
#include "pch.h"
#include "DeviceResources.h"
using namespace DirectX;
using namespace DX;
using Microsoft::WRL::ComPtr;
// Constructor for DeviceResources.
DeviceResources::DeviceResources(
DXGI_FORMAT backBufferFormat,
DXGI_FORMAT depthBufferFormat,
UINT backBufferCount,
unsigned int flags) noexcept :
m_screenViewport{},
m_backBufferFormat((flags & c_EnableHDR) ? DXGI_FORMAT_R10G10B10A2_UNORM : backBufferFormat),
m_depthBufferFormat(depthBufferFormat),
m_backBufferCount(backBufferCount),
m_window(nullptr),
m_d3dFeatureLevel(D3D_FEATURE_LEVEL_11_1),
m_outputSize{0, 0, 1920, 1080},
m_options(flags),
m_gameDVRFormat((flags & c_EnableHDR) ? backBufferFormat : DXGI_FORMAT_UNKNOWN)
{
}
// Configures the Direct3D device, and stores handles to it and the device context.
void DeviceResources::CreateDeviceResources()
{
D3D11X_CREATE_DEVICE_PARAMETERS params = {};
params.Version = D3D11_SDK_VERSION;
#ifdef _DEBUG
// Enable the debug layer.
params.Flags = D3D11_CREATE_DEVICE_DEBUG;
#elif defined(PROFILE)
// Enable the instrumented driver.
params.Flags = D3D11_CREATE_DEVICE_INSTRUMENTED;
#endif
if (m_options & c_FastSemantics)
{
params.Flags |= D3D11_CREATE_DEVICE_IMMEDIATE_CONTEXT_FAST_SEMANTICS;
}
// Create the Direct3D 11 API device object and a corresponding context.
ThrowIfFailed(D3D11XCreateDeviceX(
¶ms,
m_d3dDevice.ReleaseAndGetAddressOf(),
m_d3dContext.ReleaseAndGetAddressOf()
));
#ifndef NDEBUG
ComPtr<ID3D11InfoQueue> d3dInfoQueue;
if (SUCCEEDED(m_d3dDevice.As(&d3dInfoQueue)))
{
#ifdef _DEBUG
d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true);
d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true);
#endif
D3D11_MESSAGE_ID hide[] =
{
D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS,
};
D3D11_INFO_QUEUE_FILTER filter = {};
filter.DenyList.NumIDs = _countof(hide);
filter.DenyList.pIDList = hide;
d3dInfoQueue->AddStorageFilterEntries(&filter);
}
#endif
if (m_options & c_Enable4K_UHD)
{
#if _XDK_VER >= 0x3F6803F3 /* XDK Edition 170600 */
D3D11X_GPU_HARDWARE_CONFIGURATION hwConfig = {};
m_d3dDevice->GetGpuHardwareConfiguration(&hwConfig);
if (hwConfig.HardwareVersion >= D3D11X_HARDWARE_VERSION_XBOX_ONE_X)
{
m_outputSize = { 0, 0, 3840, 2160 };
#ifdef _DEBUG
OutputDebugStringA("INFO: Swapchain using 4k (3840 x 2160) on Xbox One X\n");
#endif
}
else
{
m_options &= ~c_Enable4K_UHD;
#ifdef _DEBUG
OutputDebugStringA("INFO: Swapchain using 1080p (1920 x 1080) on Xbox One or Xbox One S\n");
#endif
}
#else
m_options &= ~c_Enable4K_UHD;
#ifdef _DEBUG
OutputDebugStringA("WARNING: Hardware detection not supported on this XDK edition; Swapchain using 1080p (1920 x 1080)\n");
#endif
#endif
}
}
// These resources need to be recreated every time the window size is changed.
void DeviceResources::CreateWindowSizeDependentResources()
{
if (!m_window)
{
throw std::exception("Call SetWindow with a valid CoreWindow pointer");
}
// Clear the previous window size specific context.
ID3D11RenderTargetView* nullViews[] = {nullptr, nullptr};
m_d3dContext->OMSetRenderTargets(_countof(nullViews), nullViews, nullptr);
m_d3dRenderTargetView.Reset();
m_d3dDepthStencilView.Reset();
m_renderTarget.Reset();
m_depthStencil.Reset();
m_d3dGameDVRRenderTargetView.Reset();
m_d3dGameDVRRenderTarget.Reset();
m_d3dContext->Flush();
// Determine the render target size in pixels.
UINT backBufferWidth = std::max<UINT>(m_outputSize.right - m_outputSize.left, 1);
UINT backBufferHeight = std::max<UINT>(m_outputSize.bottom - m_outputSize.top, 1);
if (m_swapChain)
{
// If the swap chain already exists, resize it.
ThrowIfFailed(m_swapChain->ResizeBuffers(
m_backBufferCount,
backBufferWidth,
backBufferHeight,
m_backBufferFormat,
0
));
// Xbox One apps do not need to handle DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET.
if (m_swapChainGameDVR)
{
ThrowIfFailed(m_swapChainGameDVR->ResizeBuffers(
m_backBufferCount,
backBufferWidth,
backBufferHeight,
m_gameDVRFormat,
0
));
}
}
else
{
// Otherwise, create a new one using the same adapter as the existing Direct3D device.
// This sequence obtains the DXGI factory that was used to create the Direct3D device above.
ComPtr<IDXGIDevice1> dxgiDevice;
ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
ComPtr<IDXGIAdapter> dxgiAdapter;
ThrowIfFailed(dxgiDevice->GetAdapter(dxgiAdapter.GetAddressOf()));
ComPtr<IDXGIFactory2> dxgiFactory;
ThrowIfFailed(dxgiAdapter->GetParent(IID_GRAPHICS_PPV_ARGS(dxgiFactory.GetAddressOf())));
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
swapChainDesc.Width = backBufferWidth;
swapChainDesc.Height = backBufferHeight;
swapChainDesc.Format = m_backBufferFormat;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = m_backBufferCount;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.Scaling = DXGI_SCALING_STRETCH;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
swapChainDesc.Flags = (m_options & c_EnableHDR) ? DXGIX_SWAP_CHAIN_FLAG_COLORIMETRY_RGB_BT2020_ST2084 : DXGIX_SWAP_CHAIN_FLAG_QUANTIZATION_RGB_FULL;
// Create a SwapChain from a CoreWindow.
ThrowIfFailed(dxgiFactory->CreateSwapChainForCoreWindow(
m_d3dDevice.Get(),
m_window,
&swapChainDesc,
nullptr,
m_swapChain.GetAddressOf()
));
if ((m_options & c_EnableHDR) && !m_swapChainGameDVR)
{
swapChainDesc.Format = m_gameDVRFormat;
swapChainDesc.Flags = DXGIX_SWAP_CHAIN_FLAG_QUANTIZATION_RGB_FULL;
// Create a SwapChain from a CoreWindow.
ThrowIfFailed(dxgiFactory->CreateSwapChainForCoreWindow(
m_d3dDevice.Get(),
m_window,
&swapChainDesc,
nullptr,
m_swapChainGameDVR.GetAddressOf()
));
}
}
// Create a render target view of the swap chain back buffer.
ThrowIfFailed(m_swapChain->GetBuffer(0, IID_GRAPHICS_PPV_ARGS(m_renderTarget.ReleaseAndGetAddressOf())));
m_renderTarget->SetName(L"Render target");
ThrowIfFailed(m_d3dDevice->CreateRenderTargetView(
m_renderTarget.Get(),
nullptr,
m_d3dRenderTargetView.ReleaseAndGetAddressOf()
));
if (m_swapChainGameDVR)
{
ThrowIfFailed(m_swapChainGameDVR->GetBuffer(0, IID_GRAPHICS_PPV_ARGS(m_d3dGameDVRRenderTarget.ReleaseAndGetAddressOf())));
m_d3dGameDVRRenderTarget->SetName(L"GameDVR Render target");
ThrowIfFailed(m_d3dDevice->CreateRenderTargetView(
m_d3dGameDVRRenderTarget.Get(),
nullptr,
m_d3dGameDVRRenderTargetView.ReleaseAndGetAddressOf()
));
}
if (m_depthBufferFormat != DXGI_FORMAT_UNKNOWN)
{
// Create a depth stencil view for use with 3D rendering if needed.
CD3D11_TEXTURE2D_DESC depthStencilDesc(
m_depthBufferFormat,
backBufferWidth,
backBufferHeight,
1, // This depth stencil view has only one texture.
1, // Use a single mipmap level.
D3D11_BIND_DEPTH_STENCIL
);
ThrowIfFailed(m_d3dDevice->CreateTexture2D(
&depthStencilDesc,
nullptr,
m_depthStencil.ReleaseAndGetAddressOf()
));
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
ThrowIfFailed(m_d3dDevice->CreateDepthStencilView(
m_depthStencil.Get(),
&depthStencilViewDesc,
m_d3dDepthStencilView.ReleaseAndGetAddressOf()
));
}
// Set the 3D rendering viewport to target the entire window.
m_screenViewport = CD3D11_VIEWPORT(
0.0f,
0.0f,
static_cast<float>(backBufferWidth),
static_cast<float>(backBufferHeight)
);
m_outputSize.left = m_outputSize.top = 0;
m_outputSize.right = backBufferWidth;
m_outputSize.bottom = backBufferHeight;
}
// Prepare the render target for rendering.
void DeviceResources::Prepare()
{
if (m_options & c_FastSemantics)
{
ThrowIfFailed(m_swapChain->GetBuffer(0, IID_GRAPHICS_PPV_ARGS(m_renderTarget.ReleaseAndGetAddressOf())));
m_d3dDevice->PlaceSwapChainView(m_renderTarget.Get(), m_d3dRenderTargetView.Get());
m_d3dContext->InsertWaitOnPresent(0, m_renderTarget.Get());
if (m_swapChainGameDVR)
{
ThrowIfFailed(m_swapChainGameDVR->GetBuffer(0, IID_GRAPHICS_PPV_ARGS(m_d3dGameDVRRenderTarget.ReleaseAndGetAddressOf())));
m_d3dDevice->PlaceSwapChainView(m_d3dGameDVRRenderTarget.Get(), m_d3dGameDVRRenderTargetView.Get());
m_d3dContext->InsertWaitOnPresent(0, m_d3dGameDVRRenderTarget.Get());
}
}
}
// Present the contents of the swap chain to the screen.
void DeviceResources::Present(UINT decompressFlags)
{
if ((m_options & c_FastSemantics) != 0 && decompressFlags != 0)
{
m_d3dContext->DecompressResource(
m_renderTarget.Get(), 0, nullptr,
m_renderTarget.Get(), 0, nullptr,
m_backBufferFormat, decompressFlags);
if (m_d3dGameDVRRenderTarget)
{
m_d3dContext->DecompressResource(
m_d3dGameDVRRenderTarget.Get(), 0, nullptr,
m_d3dGameDVRRenderTarget.Get(), 0, nullptr,
m_gameDVRFormat, decompressFlags);
}
}
if (m_swapChainGameDVR)
{
IDXGISwapChain1* ppSwapChains[2] = { m_swapChain.Get(), m_swapChainGameDVR.Get() };
DXGIX_PRESENTARRAY_PARAMETERS presentParameterSets[2] = {};
presentParameterSets[0].SourceRect = m_outputSize;
presentParameterSets[0].ScaleFactorHorz = 1.0f;
presentParameterSets[0].ScaleFactorVert = 1.0f;
presentParameterSets[1] = presentParameterSets[0];
DXGIXPresentArray(1, 0, 0, _countof(presentParameterSets), ppSwapChains, presentParameterSets);
}
else
{
ThrowIfFailed(m_swapChain->Present(1, 0));
}
// Xbox One apps do not need to handle DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET.
}
| {
"pile_set_name": "Github"
} |
"""
```
BondLabor{T} <: AbstractModel{T}
```
### Fields
#### Parameters and Steady-States
* `parameters::Vector{AbstractParameter}`: Vector of all time-invariant model
parameters.
* `steady_state::Vector{AbstractParameter}`: Model steady-state values, computed
as a function of elements of `parameters`.
* `keys::OrderedDict{Symbol,Int}`: Maps human-readable names for all model
parameters and steady-states to their indices in `parameters` and
`steady_state`.
#### Inputs to Measurement and Equilibrium Condition Equations
The following fields are dictionaries that map human-readable names to row and
column indices in the matrix representations of of the measurement equation and
equilibrium conditions.
* `endogenous_states::OrderedDict{Symbol,Int}`: Maps each state to a column in
the measurement and equilibrium condition matrices.
* `exogenous_shocks::OrderedDict{Symbol,Int}`: Maps each shock to a column in
the measurement and equilibrium condition matrices.
* `expected_shocks::OrderedDict{Symbol,Int}`: Maps each expected shock to a
column in the measurement and equilibrium condition matrices.
* `equilibrium_conditions::OrderedDict{Symbol,Int}`: Maps each equlibrium
condition to a row in the model's equilibrium condition matrices.
* `observables::OrderedDict{Symbol,Int}`: Maps each observable to a row in the
model's measurement equation matrices.
#### Model Specifications and Settings
* `spec::String`: The model specification identifier, \"an_schorfheide\", cached
here for filepath computation.
* `subspec::String`: The model subspecification number, indicating that some
parameters from the original model spec (\"ss0\") are initialized
differently. Cached here for filepath computation.
* `settings::Dict{Symbol,Setting}`: Settings/flags that affect computation
without changing the economic or mathematical setup of the model.
* `test_settings::Dict{Symbol,Setting}`: Settings/flags for testing mode
#### Other Fields
* `rng::MersenneTwister`: Random number generator. Can be is seeded to ensure
reproducibility in algorithms that involve randomness (such as
Metropolis-Hastings).
* `testing::Bool`: Indicates whether the model is in testing mode. If `true`,
settings from `m.test_settings` are used in place of those in `m.settings`.
* `observable_mappings::OrderedDict{Symbol,Observable}`: A dictionary that
stores data sources, series mnemonics, and transformations to/from model units.
DSGE.jl will fetch data from the Federal Reserve Bank of
St. Louis's FRED database; all other data must be downloaded by the
user. See `load_data` and `Observable` for further details.
"""
mutable struct BondLabor{T} <: AbstractModel{T}
parameters::ParameterVector{T} # vector of all time-invariant model parameters
steady_state::ParameterVector{T} # model steady-state values
# Temporary to get it to work. Need to
# figure out a more flexible way to define
# "grids" that are not necessarily quadrature
# grids within the model
grids::OrderedDict{Symbol,Union{Grid, Vector}}
keys::OrderedDict{Symbol,Int} # human-readable names for all the model
# parameters and steady-states
state_variables::Vector{Symbol} # Vector of symbols of the state variables
jump_variables::Vector{Symbol} # Vector of symbols of the jump variables
normalized_model_states::Vector{Symbol} # All of the distributional model
# state variables that need to be normalized
endogenous_states_unnormalized::OrderedDict{Symbol,UnitRange} # Vector of unnormalized
# ranges of indices
endogenous_states::OrderedDict{Symbol,UnitRange} # Vector of ranges corresponding
# to normalized (post Klein solution) indices
exogenous_shocks::OrderedDict{Symbol,Int} #
expected_shocks::OrderedDict{Symbol,Int} #
equilibrium_conditions::OrderedDict{Symbol,UnitRange} #
observables::OrderedDict{Symbol,Int} #
spec::String # Model specification number (eg "m990")
subspec::String # Model subspecification (eg "ss0")
settings::Dict{Symbol,Setting} # Settings/flags for computation
test_settings::Dict{Symbol,Setting} # Settings/flags for testing mode
rng::MersenneTwister # Random number generator
testing::Bool # Whether we are in testing mode or not
observable_mappings::OrderedDict{Symbol, Observable}
end
description(m::BondLabor) = "BondLabor, $(m.subspec)"
"""
`init_model_indices!(m::BondLabor)`
Arguments:
`m:: BondLabor`: a model object
Description:
Initializes indices for all of `m`'s states, shocks, and equilibrium conditions.
"""
function init_model_indices!(m::BondLabor)
# Endogenous states
endogenous_states = collect([
# These states corresp. to the following in the original notation
# MUP, ZP, ELLP, RP
:μ′_t, :z′_t, :l′_t, :R′_t])
# Exogenous shocks
exogenous_shocks = collect([:z_sh])
# Equilibrium conditions
equilibrium_conditions = collect([
:eq_euler, :eq_kolmogorov_fwd, :eq_market_clearing, :eq_TFP])
# Observables
observables = keys(m.observable_mappings)
########################################################################################
# Setting indices of endogenous_states and equilibrium conditions manually for now
nx = get_setting(m, :nx)
ns = get_setting(m, :ns)
endo = m.endogenous_states_unnormalized
eqconds = m.equilibrium_conditions
# State variables
endo[:μ′_t] = 1:nx*ns
endo[:z′_t] = nx*ns+1:nx*ns+1
# Jump variables
endo[:l′_t] = nx*ns+2:2*nx*ns+1
endo[:R′_t] = 2*nx*ns+2:2*nx*ns+2
eqconds[:eq_euler] = 1:nx*ns
eqconds[:eq_kolmogorov_fwd] = nx*ns+1:2*nx*ns
eqconds[:eq_market_clearing] = 2*nx*ns+1:2*nx*ns+1
eqconds[:eq_TFP] = 2*nx*ns+2:2*nx*ns+2
########################################################################################
m.normalized_model_states = [:μ′_t]
m.endogenous_states = deepcopy(endo)
m.state_variables = m.endogenous_states.keys[get_setting(m, :state_indices)]
m.jump_variables = m.endogenous_states.keys[get_setting(m, :jump_indices)]
for (i,k) in enumerate(exogenous_shocks); m.exogenous_shocks[k] = i end
for (i,k) in enumerate(observables); m.observables[k] = i end
end
function BondLabor(subspec::String="ss0";
custom_settings::Dict{Symbol, Setting} = Dict{Symbol, Setting}(),
testing = false)
# Model-specific specifications
spec = "BondLabor"
subspec = subspec
settings = Dict{Symbol,Setting}()
test_settings = Dict{Symbol,Setting}()
rng = MersenneTwister(0)
# initialize empty model
m = BondLabor{Float64}(
# model parameters and steady state values
Vector{AbstractParameter{Float64}}(), Vector{Float64}(),
# grids and keys
OrderedDict{Symbol,Grid}(), OrderedDict{Symbol,Int}(),
# normalized_model_states, state_inds, jump_inds
Vector{Symbol}(), Vector{Symbol}(), Vector{Symbol}(),
# model indices
# endogenous states unnormalized, endogenous states normalized
OrderedDict{Symbol,UnitRange}(), OrderedDict{Symbol,UnitRange}(),
OrderedDict{Symbol,Int}(), OrderedDict{Symbol,Int}(),
OrderedDict{Symbol,UnitRange}(), OrderedDict{Symbol,Int}(),
spec,
subspec,
settings,
test_settings,
rng,
testing,
OrderedDict{Symbol,Observable}())
# Set settings
model_settings!(m)
# default_test_settings!(m)
for custom_setting in values(custom_settings)
m <= custom_setting
end
# Set observable transformations
init_observable_mappings!(m)
# Initialize parameters
init_parameters!(m)
# Initialize grids
init_grids!(m)
# Initialize model indices
init_model_indices!(m)
# Solve for the steady state
steadystate!(m)
# So that the indices of m.endogenous_states reflect the normalization
normalize_model_state_indices!(m)
return m
end
"""
```
init_parameters!(m::BondLabor)
```
Initializes the model's parameters, as well as empty values for the steady-state
parameters (in preparation for `steadystate!(m)` being called to initialize
those).
"""
function init_parameters!(m::BondLabor)
# Initialize parameters
m <= parameter(:R, 1.04, fixed = true,
description = "R: Steady-state gross real interest rate.", tex_label = "R")
m <= parameter(:γ, 1.0, fixed = true,
description = "γ: CRRA Parameter.", tex_label = "\\gamma")
m <= parameter(:ν, 1.0, fixed = true,
description = "Inverse Frisch elasticity of labor supply.", tex_label = "\\nu")
m <= parameter(:abar, -0.5, fixed = true,
description = "Borrowing floor.", tex_label = "\\bar{a}")
m <= parameter(:ρ_z, 0.95, (1e-5, 0.999), (1e-5, 0.999), SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
description="ρ_z: AR(1) coefficient in the technology process.",
tex_label="\\rho_z")
m <= parameter(:σ_z, sqrt(.007), (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2, 0.10), fixed=false,
description="σ_z: The standard deviation of the process describing the stationary component of productivity.",
tex_label="\\sigma_{z}")
m <= parameter(:μ_s, 0., fixed = true, description = "μ_s: Mu of log normal in income")
m <= parameter(:σ_s, 0.1, fixed = true,
description = "σ_s: Sigma of log normal in income")
m <= parameter(:e_y, 1e-3, fixed = true, description = "e_y: Measurement error on GDP",
tex_label = "e_y")
# Setting steady-state parameters
nx = get_setting(m, :nx)
ns = get_setting(m, :ns)
m <= SteadyStateParameterGrid(:lstar, fill(NaN, nx*ns), description = "Steady-state expected discounted
marginal utility of consumption", tex_label = "l_*")
m <= SteadyStateParameterGrid(:cstar, fill(NaN, nx*ns), description = "Steady-state consumption",
tex_label = "c_*")
m <= SteadyStateParameterGrid(:ηstar, fill(NaN, nx*ns), description = "Steady-state
level of labor supply",
tex_label = "\\eta_*")
m <= SteadyStateParameterGrid(:μstar, fill(NaN, nx*ns), description = "Steady-state cross-sectional
density of cash on hand", tex_label = "\\mu_*")
# Figure out a better description for this...
m <= SteadyStateParameterGrid(:χstar, fill(NaN, nx*ns), description = "Steady-state
solution for constrained consumption and labor supply",
tex_label = "\\chi_*")
m <= SteadyStateParameter(:βstar, NaN, description = "Steady-state discount factor",
tex_label = "\\beta_*")
# m <= SteadyStateParameter(:Lstar, NaN, description = "Steady-state labor", tex_label = "L_*")
# m <= SteadyStateParameter(:Wstar, NaN, description = "Steady-state wages", tex_label = "W_*")
# m <= SteadyStateParameterGrid(:KFstar, fill(NaN, (nw, nw)), description = "Steady-state Kolmogorov
# Forward Equation", tex_label = "KF_*")
end
"""
```
init_grids!(m::BondLabor)
```
"""
function init_grids!(m::BondLabor)
xscale = get_setting(m, :xscale)
xlo = get_setting(m, :xlo)
xhi = get_setting(m, :xhi)
nx = get_setting(m, :nx)
ns = get_setting(m, :ns)
λ = get_setting(m, :λ)
ehi = get_setting(m, :ehi)
grids = OrderedDict()
# Cash on hand grid
grids[:xgrid] = Grid(uniform_quadrature(xscale), xlo, xhi, nx, scale = xscale)
# Skill grid
lsgrid, sprob, sscale = tauchen86(m[:μ_s].value, m[:σ_s].value, ns, λ)
swts = (sscale/ns)*ones(ns)
sgrid = exp.(lsgrid) .+ ehi
grids[:sgrid] = Grid(sgrid, swts, sscale)
# Density of skill across skill grid
grids[:ggrid] = sprob./swts
# Total grid vectorized across both dimensions
grids[:sgrid_total] = kron(sgrid, ones(nx))
grids[:xgrid_total] = kron(ones(ns), grids[:xgrid].points)
grids[:weights_total] = kron(swts, grids[:xgrid].weights)
m.grids = grids
end
function model_settings!(m::BondLabor)
default_settings!(m)
# Defaults
# Data settings for released and conditional data. Default behavior is to set vintage
# of data to today's date.
vint = Dates.format(now(), DSGE_DATE_FORMAT)
m <= Setting(:data_vintage, vint, true, "vint", "Data vintage")
saveroot = normpath(joinpath(dirname(@__FILE__), "../../../../","save"))
datapath = normpath(joinpath(dirname(@__FILE__), "../../../../","save","input_data"))
m <= Setting(:saveroot, saveroot, "Root of data directory structure")
m <= Setting(:dataroot, datapath, "Input data directory path")
# Solution method
m <= Setting(:solution_method, :klein)
# Anticipated shocks
m <= Setting(:n_anticipated_shocks, 0,
"Number of anticipated policy shocks")
# m <= Setting(:n_anticipated_shocks_padding, 20,
# "Padding for anticipated policy shocks")
# Number of states and jumps
m <= Setting(:normalize_distr_variables, true, "Whether or not to perform the
normalization of the distributional states in the Klein solution step")
m <= Setting(:n_predetermined_variables, 0, "Number of predetermined variables after
removing the densities. Calculated with the Jacobian normalization.
This set to 0 is just the default setting, since it will always be
overwritten once the Jacobian is calculated.")
m <= Setting(:state_indices, 1:2, "Which indices of m.endogenous_states correspond to
backward looking state variables")
m <= Setting(:jump_indices, 3:4, "Which indices of m.endogenous_states correspond to jump
variables")
# Mollifier setting parameters
m <= Setting(:In, 0.443993816237631, "Normalizing constant for the mollifier")
m <= Setting(:elo, 0.0, "Lower bound on stochastic consumption commitments")
m <= Setting(:ehi, 1.0, "Upper bound on stochastic consumption commitments")
# x: Cash on Hand Grid Setup
m <= Setting(:nx, 75, "Cash on hand distribution grid points")
m <= Setting(:xlo, -0.5 - 1.0, "Lower bound on cash on hand")
m <= Setting(:xhi, 4.0, "Upper Bound on cash on hand")
m <= Setting(:xscale, get_setting(m, :xhi) - get_setting(m, :xlo), "Size of the xgrid")
# s: Skill Distribution/ "Units of effective labor" Grid Setup
m <= Setting(:ns, 2, "Skill distribution grid points")
m <= Setting(:λ, 3.0, "The λ parameter in the Tauchen distribution calculation")
# Total grid x*s
m <= Setting(:n, get_setting(m, :nx) * get_setting(m, :ns), "Total grid size, multiplying
across grid dimensions.")
# Function-valued variables include distributional variables
m <= Setting(:n_function_valued_backward_looking_states, 1, "Number of function-valued
backward looking state variables")
m <= Setting(:n_backward_looking_distributional_vars, 1, "Number of state variables that are
distributional variables.")
m <= Setting(:n_function_valued_jumps, 1, "Number of function-valued jump variables")
m <= Setting(:n_jump_distributional_vars, 0, "Number of jump variables that are distributional
variables.")
# Note, these settings assume normalization.
# The n degrees of freedom removed depends on the distributions/dimensions
# of heterogeneity that we have discretized over, in this case,
# cash on hand and the skill distribution. In general the rule of
# thumb is, remove one degree of freedom for the first endogenous distribution (cash on
# hand), then one additional degree of freedom for each exogenous distribution (skill
# distribution). Multiple endogenous distributions only permit removing a single degree
# of freedom since it is then non-trivial to obtain the marginal distributions.
m <= Setting(:n_degrees_of_freedom_removed, 2, "Number of degrees of freedom from the
distributional variables to remove.")
n_dof_removed = get_setting(m, :n_degrees_of_freedom_removed)
####################################################
# Calculating the number of backward-looking states
####################################################
n_backward_looking_distr_vars = get_setting(m, :n_backward_looking_distributional_vars)
m <= Setting(:backward_looking_states_normalization_factor,
n_dof_removed*n_backward_looking_distr_vars, "The number of dimensions removed from the
backward looking state variables for the normalization.")
n = get_setting(m, :n)
n_backward_looking_vars = length(get_setting(m, :state_indices))
n_backward_looking_function_valued_vars = get_setting(m, :n_function_valued_backward_looking_states)
n_backward_looking_scalar_vars = n_backward_looking_vars - n_backward_looking_function_valued_vars
m <= Setting(:n_backward_looking_states, n*n_backward_looking_distr_vars +
n_backward_looking_scalar_vars - get_setting(m, :backward_looking_states_normalization_factor),
"Number of state variables, in the true sense (fully
backward looking) accounting for the discretization across the grid
of function-valued variables and the normalization of
distributional variables.")
##################################
# Calculating the number of jumps
##################################
n_jump_distr_vars = get_setting(m, :n_jump_distributional_vars)
m <= Setting(:jumps_normalization_factor,
n_dof_removed*n_jump_distr_vars, "The number of dimensions removed from the
jump variables for the normalization.")
n_jump_vars = length(get_setting(m, :jump_indices))
n_jump_function_valued_vars = get_setting(m, :n_function_valued_jumps)
n_jump_scalar_vars = n_jump_vars - n_jump_function_valued_vars
m <= Setting(:n_jumps, n*n_jump_function_valued_vars +
n_jump_scalar_vars - get_setting(m, :jumps_normalization_factor),
"Number of jump variables (forward looking) accounting for
the discretization across the grid of function-valued variables and the
normalization of distributional variables.")
m <= Setting(:n_model_states, get_setting(m, :n_backward_looking_states) + get_setting(m, :n_jumps),
"Number of 'states' in the state space model. Because backward and forward
looking variables need to be explicitly tracked for the Klein solution
method, we have n_states and n_jumps")
end
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2019 TAOS Data, Inc. <[email protected]>
*
* This program is free software: you can use, redistribute, and/or modify
* it under the terms of the GNU Affero General Public License, version 3
* or later ("AGPL"), as published by the Free Software Foundation.
*
* 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.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define _DEFAULT_SOURCE
#include "os.h"
#include "taosmsg.h"
#include "httpLog.h"
#include "httpJson.h"
#include "httpResp.h"
#include "httpTgHandle.h"
#include "httpTgJson.h"
void tgInitQueryJson(HttpContext *pContext) {
JsonBuf *jsonBuf = httpMallocJsonBuf(pContext);
if (jsonBuf == NULL) return;
httpInitJsonBuf(jsonBuf, pContext);
httpWriteJsonBufHead(jsonBuf);
// array begin
httpJsonItemToken(jsonBuf);
httpJsonToken(jsonBuf, JsonObjStt);
httpJsonPairHead(jsonBuf, "metrics", 7);
httpJsonItemToken(jsonBuf);
httpJsonToken(jsonBuf, JsonArrStt);
}
void tgCleanQueryJson(HttpContext *pContext) {
JsonBuf *jsonBuf = httpMallocJsonBuf(pContext);
if (jsonBuf == NULL) return;
// array end
httpJsonToken(jsonBuf, JsonArrEnd);
httpJsonToken(jsonBuf, JsonObjEnd);
httpWriteJsonBufEnd(jsonBuf);
}
void tgStartQueryJson(HttpContext *pContext, HttpSqlCmd *cmd, TAOS_RES *result) {
JsonBuf *jsonBuf = httpMallocJsonBuf(pContext);
if (jsonBuf == NULL) return;
// object begin
httpJsonItemToken(jsonBuf);
httpJsonToken(jsonBuf, JsonObjStt);
// data
httpJsonItemToken(jsonBuf);
httpJsonPair(jsonBuf, "metric", 6, httpGetCmdsString(pContext, cmd->stable),
(int32_t)strlen(httpGetCmdsString(pContext, cmd->metric)));
httpJsonItemToken(jsonBuf);
httpJsonPair(jsonBuf, "stable", 6, httpGetCmdsString(pContext, cmd->stable),
(int32_t)strlen(httpGetCmdsString(pContext, cmd->stable)));
httpJsonItemToken(jsonBuf);
httpJsonPair(jsonBuf, "table", 5, httpGetCmdsString(pContext, cmd->table),
(int32_t)strlen(httpGetCmdsString(pContext, cmd->table)));
httpJsonItemToken(jsonBuf);
httpJsonPair(jsonBuf, "timestamp", 9, httpGetCmdsString(pContext, cmd->timestamp),
(int32_t)strlen(httpGetCmdsString(pContext, cmd->timestamp))); // hack way
}
void tgStopQueryJson(HttpContext *pContext, HttpSqlCmd *cmd) {
JsonBuf *jsonBuf = httpMallocJsonBuf(pContext);
if (jsonBuf == NULL) return;
// data
httpJsonItemToken(jsonBuf);
httpJsonPairStatus(jsonBuf, cmd->code);
// object end
httpJsonToken(jsonBuf, JsonObjEnd);
}
void tgBuildSqlAffectRowsJson(HttpContext *pContext, HttpSqlCmd *cmd, int32_t affect_rows) {
JsonBuf *jsonBuf = httpMallocJsonBuf(pContext);
if (jsonBuf == NULL) return;
// data
httpJsonPairIntVal(jsonBuf, "affected_rows", 13, affect_rows);
}
bool tgCheckFinished(struct HttpContext *pContext, HttpSqlCmd *cmd, int32_t code) {
HttpSqlCmds *multiCmds = pContext->multiCmds;
httpDebug("context:%p, fd:%d, check telegraf command, code:%s, state:%d, type:%d, rettype:%d, tags:%d", pContext,
pContext->fd, tstrerror(code), cmd->cmdState, cmd->cmdType, cmd->cmdReturnType, cmd->tagNum);
if (cmd->cmdType == HTTP_CMD_TYPE_INSERT) {
if (cmd->cmdState == HTTP_CMD_STATE_NOT_RUN_YET) {
if (code == TSDB_CODE_MND_DB_NOT_SELECTED || code == TSDB_CODE_MND_INVALID_DB) {
cmd->cmdState = HTTP_CMD_STATE_RUN_FINISHED;
if (multiCmds->cmds[0].cmdState == HTTP_CMD_STATE_NOT_RUN_YET) {
multiCmds->pos = (int16_t)-1;
httpDebug("context:%p, fd:%d, import failed, try create database", pContext, pContext->fd);
return false;
}
} else if (code == TSDB_CODE_MND_INVALID_TABLE_NAME) {
cmd->cmdState = HTTP_CMD_STATE_RUN_FINISHED;
if (multiCmds->cmds[multiCmds->pos - 1].cmdState == HTTP_CMD_STATE_NOT_RUN_YET) {
multiCmds->pos = (int16_t)(multiCmds->pos - 2);
httpDebug("context:%p, fd:%d, import failed, try create stable", pContext, pContext->fd);
return false;
}
} else {
}
} else {
}
} else if (cmd->cmdType == HTTP_CMD_TYPE_CREATE_DB) {
cmd->cmdState = HTTP_CMD_STATE_RUN_FINISHED;
httpDebug("context:%p, fd:%d, code:%s, create database failed", pContext, pContext->fd, tstrerror(code));
} else if (cmd->cmdType == HTTP_CMD_TYPE_CREATE_STBALE) {
cmd->cmdState = HTTP_CMD_STATE_RUN_FINISHED;
httpDebug("context:%p, fd:%d, code:%s, create stable failed", pContext, pContext->fd, tstrerror(code));
} else {
}
return true;
}
void tgSetNextCmd(struct HttpContext *pContext, HttpSqlCmd *cmd, int32_t code) {
HttpSqlCmds *multiCmds = pContext->multiCmds;
httpDebug("context:%p, fd:%d, get telegraf next command, pos:%d, code:%s, state:%d, type:%d, rettype:%d, tags:%d",
pContext, pContext->fd, multiCmds->pos, tstrerror(code), cmd->cmdState, cmd->cmdType, cmd->cmdReturnType,
cmd->tagNum);
if (cmd->cmdType == HTTP_CMD_TYPE_INSERT) {
multiCmds->pos = (int16_t)(multiCmds->pos + 2);
} else if (cmd->cmdType == HTTP_CMD_TYPE_CREATE_DB) {
multiCmds->pos++;
} else if (cmd->cmdType == HTTP_CMD_TYPE_CREATE_STBALE) {
multiCmds->pos++;
} else {
multiCmds->pos++;
}
}
| {
"pile_set_name": "Github"
} |
package bsdp
import (
"fmt"
"golang.org/x/sys/unix"
)
// MakeVendorClassIdentifier calls the sysctl syscall on macOS to get the
// platform model.
func MakeVendorClassIdentifier() (string, error) {
// Fetch hardware model for class ID.
hwModel, err := unix.Sysctl("hw.model")
if err != nil {
return "", err
}
return fmt.Sprintf("%s/i386/%s", AppleVendorID, hwModel), nil
}
| {
"pile_set_name": "Github"
} |
/*!
@file
Defines `boost::hana::mult`.
@copyright Louis Dionne 2013-2016
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_MULT_HPP
#define BOOST_HANA_MULT_HPP
#include <boost/hana/fwd/mult.hpp>
#include <boost/hana/concept/constant.hpp>
#include <boost/hana/concept/ring.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/core/to.hpp>
#include <boost/hana/core/dispatch.hpp>
#include <boost/hana/detail/canonical_constant.hpp>
#include <boost/hana/detail/has_common_embedding.hpp>
#include <boost/hana/value.hpp>
#include <type_traits>
BOOST_HANA_NAMESPACE_BEGIN
//! @cond
template <typename X, typename Y>
constexpr decltype(auto) mult_t::operator()(X&& x, Y&& y) const {
using T = typename hana::tag_of<X>::type;
using U = typename hana::tag_of<Y>::type;
using Mult = BOOST_HANA_DISPATCH_IF(decltype(mult_impl<T, U>{}),
hana::Ring<T>::value &&
hana::Ring<U>::value &&
!is_default<mult_impl<T, U>>::value
);
#ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
static_assert(hana::Ring<T>::value,
"hana::mult(x, y) requires 'x' to be in a Ring");
static_assert(hana::Ring<U>::value,
"hana::mult(x, y) requires 'y' to be in a Ring");
static_assert(!is_default<mult_impl<T, U>>::value,
"hana::mult(x, y) requires 'x' and 'y' to be embeddable "
"in a common Ring");
#endif
return Mult::apply(static_cast<X&&>(x), static_cast<Y&&>(y));
}
//! @endcond
template <typename T, typename U, bool condition>
struct mult_impl<T, U, when<condition>> : default_ {
template <typename ...Args>
static constexpr auto apply(Args&& ...) = delete;
};
// Cross-type overload
template <typename T, typename U>
struct mult_impl<T, U, when<
detail::has_nontrivial_common_embedding<Ring, T, U>::value
>> {
using C = typename common<T, U>::type;
template <typename X, typename Y>
static constexpr decltype(auto) apply(X&& x, Y&& y) {
return hana::mult(hana::to<C>(static_cast<X&&>(x)),
hana::to<C>(static_cast<Y&&>(y)));
}
};
//////////////////////////////////////////////////////////////////////////
// Model for non-boolean arithmetic data types
//////////////////////////////////////////////////////////////////////////
template <typename T>
struct mult_impl<T, T, when<std::is_arithmetic<T>::value &&
!std::is_same<bool, T>::value>> {
template <typename X, typename Y>
static constexpr decltype(auto) apply(X&& x, Y&& y)
{ return static_cast<X&&>(x) * static_cast<Y&&>(y); }
};
//////////////////////////////////////////////////////////////////////////
// Model for Constants over a Ring
//////////////////////////////////////////////////////////////////////////
namespace detail {
template <typename C, typename X, typename Y>
struct constant_from_mult {
static constexpr auto value = hana::mult(hana::value<X>(), hana::value<Y>());
using hana_tag = detail::CanonicalConstant<typename C::value_type>;
};
}
template <typename C>
struct mult_impl<C, C, when<
hana::Constant<C>::value &&
Ring<typename C::value_type>::value
>> {
template <typename X, typename Y>
static constexpr decltype(auto) apply(X const&, Y const&)
{ return hana::to<C>(detail::constant_from_mult<C, X, Y>{}); }
};
BOOST_HANA_NAMESPACE_END
#endif // !BOOST_HANA_MULT_HPP
| {
"pile_set_name": "Github"
} |
path: "tensorflow.saved_model.tag_constants"
tf_module {
member {
name: "GPU"
mtype: "<type \'str\'>"
}
member {
name: "SERVING"
mtype: "<type \'str\'>"
}
member {
name: "TRAINING"
mtype: "<type \'str\'>"
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2005-2008 Intel Corporation. All Rights Reserved.
This file is part of Threading Building Blocks.
Threading Building Blocks is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
Threading Building Blocks is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Threading Building Blocks; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software
library without restriction. Specifically, if other files instantiate
templates or use macros or inline functions from this file, or you compile
this file and link it with other files to produce an executable, this
file does not by itself cause the resulting executable to be covered by
the GNU General Public License. This exception does not however
invalidate any other reasons why the executable file might be covered by
the GNU General Public License.
*/
#ifndef __TBB_concurrent_hash_map_H
#define __TBB_concurrent_hash_map_H
#include <stdexcept>
#include <iterator>
#include <utility> // Need std::pair from here
#include "tbb_stddef.h"
#include "cache_aligned_allocator.h"
#include "tbb_allocator.h"
#include "spin_rw_mutex.h"
#include "atomic.h"
#include "aligned_space.h"
#if TBB_PERFORMANCE_WARNINGS
#include <typeinfo>
#endif
namespace tbb {
template<typename Key, typename T, typename HashCompare, typename A = tbb_allocator<std::pair<Key, T> > >
class concurrent_hash_map;
//! @cond INTERNAL
namespace internal {
//! base class of concurrent_hash_map
class hash_map_base {
public:
// Mutex types for each layer of the container
typedef spin_rw_mutex node_mutex_t;
typedef spin_rw_mutex chain_mutex_t;
typedef spin_rw_mutex segment_mutex_t;
//! Type of a hash code.
typedef size_t hashcode_t;
//! Log2 of n_segment
static const size_t n_segment_bits = 6;
//! Number of segments
static const size_t n_segment = size_t(1)<<n_segment_bits;
//! Maximum size of array of chains
static const size_t max_physical_size = size_t(1)<<(8*sizeof(hashcode_t)-n_segment_bits);
};
template<typename Iterator>
class hash_map_range;
struct hash_map_segment_base {
//! Mutex that protects this segment
hash_map_base::segment_mutex_t my_mutex;
// Number of nodes
atomic<size_t> my_logical_size;
// Size of chains
/** Always zero or a power of two */
size_t my_physical_size;
//! True if my_logical_size>=my_physical_size.
/** Used to support Intel(R) Thread Checker. */
bool internal_grow_predicate() const;
};
//! Meets requirements of a forward iterator for STL */
/** Value is either the T or const T type of the container.
@ingroup containers */
template<typename Container, typename Value>
class hash_map_iterator
#if defined(_WIN64) && defined(_MSC_VER)
// Ensure that Microsoft's internal template function _Val_type works correctly.
: public std::iterator<std::forward_iterator_tag,Value>
#endif /* defined(_WIN64) && defined(_MSC_VER) */
{
typedef typename Container::node node;
typedef typename Container::chain chain;
//! concurrent_hash_map over which we are iterating.
Container* my_table;
//! Pointer to node that has current item
node* my_node;
//! Index into hash table's array for current item
size_t my_array_index;
//! Index of segment that has array for current item
size_t my_segment_index;
template<typename C, typename T, typename U>
friend bool operator==( const hash_map_iterator<C,T>& i, const hash_map_iterator<C,U>& j );
template<typename C, typename T, typename U>
friend bool operator!=( const hash_map_iterator<C,T>& i, const hash_map_iterator<C,U>& j );
template<typename C, typename T, typename U>
friend ptrdiff_t operator-( const hash_map_iterator<C,T>& i, const hash_map_iterator<C,U>& j );
template<typename C, typename U>
friend class internal::hash_map_iterator;
template<typename I>
friend class internal::hash_map_range;
void advance_to_next_node() {
size_t i = my_array_index+1;
do {
while( i<my_table->my_segment[my_segment_index].my_physical_size ) {
my_node = my_table->my_segment[my_segment_index].my_array[i].node_list;
if( my_node ) goto done;
++i;
}
i = 0;
} while( ++my_segment_index<my_table->n_segment );
done:
my_array_index = i;
}
#if !defined(_MSC_VER) || defined(__INTEL_COMPILER)
template<typename Key, typename T, typename HashCompare, typename A>
friend class tbb::concurrent_hash_map;
#else
public: // workaround
#endif
hash_map_iterator( const Container& table, size_t segment_index, size_t array_index=0, node* b=NULL );
public:
//! Construct undefined iterator
hash_map_iterator() {}
hash_map_iterator( const hash_map_iterator<Container,typename Container::value_type>& other ) :
my_table(other.my_table),
my_node(other.my_node),
my_array_index(other.my_array_index),
my_segment_index(other.my_segment_index)
{}
Value& operator*() const {
__TBB_ASSERT( my_node, "iterator uninitialized or at end of container?" );
return my_node->item;
}
Value* operator->() const {return &operator*();}
hash_map_iterator& operator++();
//! Post increment
Value* operator++(int) {
Value* result = &operator*();
operator++();
return result;
}
// STL support
typedef ptrdiff_t difference_type;
typedef Value value_type;
typedef Value* pointer;
typedef Value& reference;
typedef const Value& const_reference;
typedef std::forward_iterator_tag iterator_category;
};
template<typename Container, typename Value>
hash_map_iterator<Container,Value>::hash_map_iterator( const Container& table, size_t segment_index, size_t array_index, node* b ) :
my_table(const_cast<Container*>(&table)),
my_node(b),
my_array_index(array_index),
my_segment_index(segment_index)
{
if( segment_index<my_table->n_segment ) {
if( !my_node ) {
chain* first_chain = my_table->my_segment[segment_index].my_array;
if( first_chain ) my_node = first_chain[my_array_index].node_list;
}
if( !my_node ) advance_to_next_node();
}
}
template<typename Container, typename Value>
hash_map_iterator<Container,Value>& hash_map_iterator<Container,Value>::operator++() {
my_node=my_node->next;
if( !my_node ) advance_to_next_node();
return *this;
}
template<typename Container, typename T, typename U>
bool operator==( const hash_map_iterator<Container,T>& i, const hash_map_iterator<Container,U>& j ) {
return i.my_node==j.my_node;
}
template<typename Container, typename T, typename U>
bool operator!=( const hash_map_iterator<Container,T>& i, const hash_map_iterator<Container,U>& j ) {
return i.my_node!=j.my_node;
}
//! Range class used with concurrent_hash_map
/** @ingroup containers */
template<typename Iterator>
class hash_map_range {
private:
Iterator my_begin;
Iterator my_end;
mutable Iterator my_midpoint;
size_t my_grainsize;
//! Set my_midpoint to point approximately half way between my_begin and my_end.
void set_midpoint() const;
template<typename U> friend class hash_map_range;
public:
//! Type for size of a range
typedef std::size_t size_type;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::reference reference;
typedef typename Iterator::const_reference const_reference;
typedef typename Iterator::difference_type difference_type;
typedef Iterator iterator;
//! True if range is empty.
bool empty() const {return my_begin==my_end;}
//! True if range can be partitioned into two subranges.
bool is_divisible() const {
return my_midpoint!=my_end;
}
//! Split range.
hash_map_range( hash_map_range& r, split ) :
my_end(r.my_end),
my_grainsize(r.my_grainsize)
{
r.my_end = my_begin = r.my_midpoint;
set_midpoint();
r.set_midpoint();
}
//! type conversion
template<typename U>
hash_map_range( hash_map_range<U>& r) :
my_begin(r.my_begin),
my_end(r.my_end),
my_midpoint(r.my_midpoint),
my_grainsize(r.my_grainsize)
{}
//! Init range with iterators and grainsize specified
hash_map_range( const Iterator& begin_, const Iterator& end_, size_type grainsize = 1 ) :
my_begin(begin_),
my_end(end_),
my_grainsize(grainsize)
{
set_midpoint();
__TBB_ASSERT( grainsize>0, "grainsize must be positive" );
}
const Iterator& begin() const {return my_begin;}
const Iterator& end() const {return my_end;}
//! The grain size for this range.
size_type grainsize() const {return my_grainsize;}
};
template<typename Iterator>
void hash_map_range<Iterator>::set_midpoint() const {
size_t n = my_end.my_segment_index-my_begin.my_segment_index;
if( n>1 || (n==1 && my_end.my_array_index>0) ) {
// Split by groups of segments
my_midpoint = Iterator(*my_begin.my_table,(my_end.my_segment_index+my_begin.my_segment_index)/2u);
} else {
// Split by groups of nodes
size_t m = my_end.my_array_index-my_begin.my_array_index;
if( m>my_grainsize ) {
my_midpoint = Iterator(*my_begin.my_table,my_begin.my_segment_index,m/2u);
} else {
my_midpoint = my_end;
}
}
__TBB_ASSERT( my_midpoint.my_segment_index<=my_begin.my_table->n_segment, NULL );
}
} // namespace internal
//! @endcond
//! Unordered map from Key to T.
/** concurrent_hash_map is associative container with concurrent access.
@par Compatibility
The class meets all Container Requirements from C++ Standard (See ISO/IEC 14882:2003(E), clause 23.1).
@par Exception Safety
- Hash function is not permitted to throw an exception. User-defined types Key and T are forbidden from throwing an exception in destructors.
- If exception happens during insert() operations, it has no effect (unless exception raised by HashCompare::hash() function during grow_segment).
- If exception happens during operator=() operation, the container can have a part of source items, and methods size() and empty() can return wrong results.
@par Changes since TBB 2.0
- Fixed exception-safety
- Added template argument for allocator
- Added allocator argument in constructors
- Added constructor from a range of iterators
- Added several new overloaded insert() methods
- Added get_allocator()
- Added swap()
- Added count()
- Added overloaded erase(accessor &) and erase(const_accessor&)
- Added equal_range() [const]
- Added [const_]pointer, [const_]reference, and allocator_type types
- Added global functions: operator==(), operator!=(), and swap()
@ingroup containers */
template<typename Key, typename T, typename HashCompare, typename A>
class concurrent_hash_map : protected internal::hash_map_base {
template<typename Container, typename Value>
friend class internal::hash_map_iterator;
template<typename I>
friend class internal::hash_map_range;
struct node;
friend struct node;
typedef typename A::template rebind<node>::other node_allocator_type;
public:
class const_accessor;
friend class const_accessor;
class accessor;
typedef Key key_type;
typedef T mapped_type;
typedef std::pair<const Key,T> value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef value_type *pointer;
typedef const value_type *const_pointer;
typedef value_type &reference;
typedef const value_type &const_reference;
typedef internal::hash_map_iterator<concurrent_hash_map,value_type> iterator;
typedef internal::hash_map_iterator<concurrent_hash_map,const value_type> const_iterator;
typedef internal::hash_map_range<iterator> range_type;
typedef internal::hash_map_range<const_iterator> const_range_type;
typedef A allocator_type;
//! Combines data access, locking, and garbage collection.
class const_accessor {
friend class concurrent_hash_map;
friend class accessor;
void operator=( const accessor& ) const; // Deny access
const_accessor( const accessor& ); // Deny access
public:
//! Type of value
typedef const std::pair<const Key,T> value_type;
//! True if result is empty.
bool empty() const {return !my_node;}
//! Set to null
void release() {
if( my_node ) {
my_lock.release();
my_node = NULL;
}
}
//! Return reference to associated value in hash table.
const_reference operator*() const {
__TBB_ASSERT( my_node, "attempt to dereference empty accessor" );
return my_node->item;
}
//! Return pointer to associated value in hash table.
const_pointer operator->() const {
return &operator*();
}
//! Create empty result
const_accessor() : my_node(NULL) {}
//! Destroy result after releasing the underlying reference.
~const_accessor() {
my_node = NULL; // my_lock.release() is called in scoped_lock destructor
}
private:
node* my_node;
node_mutex_t::scoped_lock my_lock;
hashcode_t my_hash;
};
//! Allows write access to elements and combines data access, locking, and garbage collection.
class accessor: public const_accessor {
public:
//! Type of value
typedef std::pair<const Key,T> value_type;
//! Return reference to associated value in hash table.
reference operator*() const {
__TBB_ASSERT( this->my_node, "attempt to dereference empty accessor" );
return this->my_node->item;
}
//! Return pointer to associated value in hash table.
pointer operator->() const {
return &operator*();
}
};
//! Construct empty table.
concurrent_hash_map(const allocator_type &a = allocator_type())
: my_allocator(a)
{
initialize();
}
//! Copy constructor
concurrent_hash_map( const concurrent_hash_map& table, const allocator_type &a = allocator_type())
: my_allocator(a)
{
initialize();
internal_copy(table);
}
//! Construction with copying iteration range and given allocator instance
template<typename I>
concurrent_hash_map(I first, I last, const allocator_type &a = allocator_type())
: my_allocator(a)
{
initialize();
internal_copy(first, last);
}
//! Assignment
concurrent_hash_map& operator=( const concurrent_hash_map& table ) {
if( this!=&table ) {
clear();
internal_copy(table);
}
return *this;
}
//! Clear table
void clear();
//! Clear table and destroy it.
~concurrent_hash_map();
//------------------------------------------------------------------------
// Parallel algorithm support
//------------------------------------------------------------------------
range_type range( size_type grainsize=1 ) {
return range_type( begin(), end(), grainsize );
}
const_range_type range( size_type grainsize=1 ) const {
return const_range_type( begin(), end(), grainsize );
}
//------------------------------------------------------------------------
// STL support - not thread-safe methods
//------------------------------------------------------------------------
iterator begin() {return iterator(*this,0);}
iterator end() {return iterator(*this,n_segment);}
const_iterator begin() const {return const_iterator(*this,0);}
const_iterator end() const {return const_iterator(*this,n_segment);}
std::pair<iterator, iterator> equal_range( const Key& key ) { return internal_equal_range(key, end()); }
std::pair<const_iterator, const_iterator> equal_range( const Key& key ) const { return internal_equal_range(key, end()); }
//! Number of items in table.
/** Be aware that this method is relatively slow compared to the
typical size() method for an STL container. */
size_type size() const;
//! True if size()==0.
bool empty() const;
//! Upper bound on size.
size_type max_size() const {return (~size_type(0))/sizeof(node);}
//! return allocator object
allocator_type get_allocator() const { return this->my_allocator; }
//! swap two instances
void swap(concurrent_hash_map &table);
//------------------------------------------------------------------------
// concurrent map operations
//------------------------------------------------------------------------
//! Return count of items (0 or 1)
size_type count( const Key& key ) const {
return const_cast<concurrent_hash_map*>(this)->lookup</*insert*/false>(NULL, key, /*write=*/false, NULL );
}
//! Find item and acquire a read lock on the item.
/** Return true if item is found, false otherwise. */
bool find( const_accessor& result, const Key& key ) const {
return const_cast<concurrent_hash_map*>(this)->lookup</*insert*/false>(&result, key, /*write=*/false, NULL );
}
//! Find item and acquire a write lock on the item.
/** Return true if item is found, false otherwise. */
bool find( accessor& result, const Key& key ) {
return lookup</*insert*/false>(&result, key, /*write=*/true, NULL );
}
//! Insert item (if not already present) and acquire a read lock on the item.
/** Returns true if item is new. */
bool insert( const_accessor& result, const Key& key ) {
return lookup</*insert*/true>(&result, key, /*write=*/false, NULL );
}
//! Insert item (if not already present) and acquire a write lock on the item.
/** Returns true if item is new. */
bool insert( accessor& result, const Key& key ) {
return lookup</*insert*/true>(&result, key, /*write=*/true, NULL );
}
//! Insert item by copying if there is no such key present already and acquire a read lock on the item.
/** Returns true if item is new. */
bool insert( const_accessor& result, const value_type& value ) {
return lookup</*insert*/true>(&result, value.first, /*write=*/false, &value.second );
}
//! Insert item by copying if there is no such key present already and acquire a write lock on the item.
/** Returns true if item is new. */
bool insert( accessor& result, const value_type& value ) {
return lookup</*insert*/true>(&result, value.first, /*write=*/true, &value.second );
}
//! Insert item by copying if there is no such key present already
/** Returns true if item is inserted. */
bool insert( const value_type& value ) {
return lookup</*insert*/true>(NULL, value.first, /*write=*/false, &value.second );
}
//! Insert range [first, last)
template<typename I>
void insert(I first, I last) {
for(; first != last; ++first)
insert( *first );
}
//! Erase item.
/** Return true if item was erased by particularly this call. */
bool erase( const Key& key );
//! Erase item by const_accessor.
/** Return true if item was erased by particularly this call. */
bool erase( const_accessor& item_accessor ) {
return exclude( item_accessor, /*readonly=*/ true );
}
//! Erase item by accessor.
/** Return true if item was erased by particularly this call. */
bool erase( accessor& item_accessor ) {
return exclude( item_accessor, /*readonly=*/ false );
}
private:
//! Basic unit of storage used in chain.
struct node {
//! Next node in chain
node* next;
node_mutex_t mutex;
value_type item;
node( const Key& key ) : item(key, T()) {}
node( const Key& key, const T& t ) : item(key, t) {}
// exception-safe allocation, see C++ Standard 2003, clause 5.3.4p17
void* operator new( size_t size, node_allocator_type& a ) {
void *ptr = a.allocate(1);
if(!ptr) throw std::bad_alloc();
return ptr;
}
// match placement-new form above to be called if exception thrown in constructor
void operator delete( void* ptr, node_allocator_type& a ) {return a.deallocate(static_cast<node*>(ptr),1); }
};
struct chain;
friend struct chain;
//! A linked-list of nodes.
/** Should be zero-initialized before use. */
struct chain {
void push_front( node& b ) {
b.next = node_list;
node_list = &b;
}
chain_mutex_t mutex;
node* node_list;
};
struct segment;
friend struct segment;
//! Segment of the table.
/** The table is partioned into disjoint segments to reduce conflicts.
A segment should be zero-initialized before use. */
struct segment: internal::hash_map_segment_base {
#if TBB_DO_ASSERT
~segment() {
__TBB_ASSERT( !my_array, "should have been cleared earlier" );
}
#endif /* TBB_DO_ASSERT */
// Pointer to array of chains
chain* my_array;
// Get chain in this segment that corresponds to given hash code.
chain& get_chain( hashcode_t hashcode, size_t n_segment_bits ) {
return my_array[(hashcode>>n_segment_bits)&(my_physical_size-1)];
}
//! Allocate an array with at least new_size chains.
/** "new_size" is rounded up to a power of two that occupies at least one cache line.
Does not deallocate the old array. Overwrites my_array. */
void allocate_array( size_t new_size ) {
size_t n=(internal::NFS_GetLineSize()+sizeof(chain)-1)/sizeof(chain);
__TBB_ASSERT((n&(n-1))==0, NULL);
while( n<new_size ) n<<=1;
chain* array = cache_aligned_allocator<chain>().allocate( n );
// storing earlier might help overcome false positives of in deducing "bool grow" in concurrent threads
__TBB_store_with_release(my_physical_size, n);
memset( array, 0, n*sizeof(chain) );
my_array = array;
}
};
segment& get_segment( hashcode_t hashcode ) {
return my_segment[hashcode&(n_segment-1)];
}
node_allocator_type my_allocator;
HashCompare my_hash_compare;
segment* my_segment;
node* create_node(const Key& key, const T* t) {
// exception-safe allocation and construction
if(t) return new( my_allocator ) node(key, *t);
else return new( my_allocator ) node(key);
}
void delete_node(node* b) {
my_allocator.destroy(b);
my_allocator.deallocate(b, 1);
}
node* search_list( const Key& key, chain& c ) const {
node* b = c.node_list;
while( b && !my_hash_compare.equal(key, b->item.first) )
b = b->next;
return b;
}
//! Returns an iterator for an item defined by the key, or for the next item after it (if upper==true)
template<typename I>
std::pair<I, I> internal_equal_range( const Key& key, I end ) const;
//! delete item by accessor
bool exclude( const_accessor& item_accessor, bool readonly );
//! Grow segment for which caller has acquired a write lock.
void grow_segment( segment_mutex_t::scoped_lock& segment_lock, segment& s );
//! Does heavy lifting for "find" and "insert".
template<bool op_insert>
bool lookup( const_accessor* result, const Key& key, bool write, const T* t );
//! Perform initialization on behalf of a constructor
void initialize() {
my_segment = cache_aligned_allocator<segment>().allocate(n_segment);
memset( my_segment, 0, sizeof(segment)*n_segment );
}
//! Copy "source" to *this, where *this must start out empty.
void internal_copy( const concurrent_hash_map& source );
template<typename I>
void internal_copy(I first, I last);
};
template<typename Key, typename T, typename HashCompare, typename A>
concurrent_hash_map<Key,T,HashCompare,A>::~concurrent_hash_map() {
clear();
cache_aligned_allocator<segment>().deallocate( my_segment, n_segment );
}
template<typename Key, typename T, typename HashCompare, typename A>
typename concurrent_hash_map<Key,T,HashCompare,A>::size_type concurrent_hash_map<Key,T,HashCompare,A>::size() const {
size_type result = 0;
for( size_t k=0; k<n_segment; ++k )
result += my_segment[k].my_logical_size;
return result;
}
template<typename Key, typename T, typename HashCompare, typename A>
bool concurrent_hash_map<Key,T,HashCompare,A>::empty() const {
for( size_t k=0; k<n_segment; ++k )
if( my_segment[k].my_logical_size )
return false;
return true;
}
template<typename Key, typename T, typename HashCompare, typename A>
template<bool op_insert>
bool concurrent_hash_map<Key,T,HashCompare,A>::lookup( const_accessor* result, const Key& key, bool write, const T* t ) {
if( result /*&& result->my_node -- checked in release() */ )
result->release();
const hashcode_t h = my_hash_compare.hash( key );
segment& s = get_segment(h);
restart:
bool return_value = false;
// first check in double-check sequence
#if TBB_DO_THREADING_TOOLS||TBB_DO_ASSERT
const bool grow = op_insert && s.internal_grow_predicate();
#else
const bool grow = op_insert && s.my_logical_size >= s.my_physical_size
&& s.my_physical_size < max_physical_size; // check whether there are free bits
#endif /* TBB_DO_THREADING_TOOLS||TBB_DO_ASSERT */
segment_mutex_t::scoped_lock segment_lock( s.my_mutex, /*write=*/grow );
if( grow ) { // Load factor is too high
grow_segment( segment_lock, s );
}
if( !s.my_array ) {
__TBB_ASSERT( !op_insert, NULL );
return false;
}
__TBB_ASSERT( (s.my_physical_size&(s.my_physical_size-1))==0, NULL );
chain& c = s.get_chain( h, n_segment_bits );
chain_mutex_t::scoped_lock chain_lock( c.mutex, /*write=*/false );
node* b = search_list( key, c );
if( op_insert ) {
if( !b ) {
b = create_node(key, t);
// Search failed
if( !chain_lock.upgrade_to_writer() ) {
// Rerun search_list, in case another thread inserted the item during the upgrade.
node* b_temp = search_list( key, c );
if( b_temp ) { // unfortunately, it did
chain_lock.downgrade_to_reader();
delete_node( b );
b = b_temp;
goto done;
}
}
++s.my_logical_size; // we can't change it earlier due to correctness of size() and exception safety of equal()
return_value = true;
c.push_front( *b );
}
} else { // find or count
if( !b ) return false;
return_value = true;
}
done:
if( !result ) return return_value;
if( !result->my_lock.try_acquire( b->mutex, write ) ) {
// we are unlucky, prepare for longer wait
internal::AtomicBackoff trials;
do {
if( !trials.bounded_pause() ) {
// the wait takes really long, restart the operation
chain_lock.release(); segment_lock.release();
__TBB_Yield();
goto restart;
}
} while( !result->my_lock.try_acquire( b->mutex, write ) );
}
result->my_node = b;
result->my_hash = h;
return return_value;
}
template<typename Key, typename T, typename HashCompare, typename A>
template<typename I>
std::pair<I, I> concurrent_hash_map<Key,T,HashCompare,A>::internal_equal_range( const Key& key, I end ) const {
hashcode_t h = my_hash_compare.hash( key );
size_t segment_index = h&(n_segment-1);
segment& s = my_segment[segment_index ];
size_t chain_index = (h>>n_segment_bits)&(s.my_physical_size-1);
if( !s.my_array )
return std::make_pair(end, end);
chain& c = s.my_array[chain_index];
node* b = search_list( key, c );
if( !b )
return std::make_pair(end, end);
iterator lower(*this, segment_index, chain_index, b), upper(lower);
return std::make_pair(lower, ++upper);
}
template<typename Key, typename T, typename HashCompare, typename A>
bool concurrent_hash_map<Key,T,HashCompare,A>::erase( const Key &key ) {
hashcode_t h = my_hash_compare.hash( key );
segment& s = get_segment( h );
node* b;
{
bool chain_locked_for_write = false;
segment_mutex_t::scoped_lock segment_lock( s.my_mutex, /*write=*/false );
if( !s.my_array ) return false;
__TBB_ASSERT( (s.my_physical_size&(s.my_physical_size-1))==0, NULL );
chain& c = s.get_chain( h, n_segment_bits );
chain_mutex_t::scoped_lock chain_lock( c.mutex, /*write=*/false );
search:
node** p = &c.node_list;
b = *p;
while( b && !my_hash_compare.equal(key, b->item.first ) ) {
p = &b->next;
b = *p;
}
if( !b ) return false;
if( !chain_locked_for_write && !chain_lock.upgrade_to_writer() ) {
chain_locked_for_write = true;
goto search;
}
*p = b->next;
--s.my_logical_size;
}
{
node_mutex_t::scoped_lock item_locker( b->mutex, /*write=*/true );
}
// note: there should be no threads pretending to acquire this mutex again, do not try to upgrade const_accessor!
delete_node( b ); // Only one thread can delete it due to write lock on the chain_mutex
return true;
}
template<typename Key, typename T, typename HashCompare, typename A>
bool concurrent_hash_map<Key,T,HashCompare,A>::exclude( const_accessor &item_accessor, bool readonly ) {
__TBB_ASSERT( item_accessor.my_node, NULL );
const hashcode_t h = item_accessor.my_hash;
node *const b = item_accessor.my_node;
item_accessor.my_node = NULL; // we ought release accessor anyway
segment& s = get_segment( h );
{
segment_mutex_t::scoped_lock segment_lock( s.my_mutex, /*write=*/false );
__TBB_ASSERT( s.my_array, NULL );
__TBB_ASSERT( (s.my_physical_size&(s.my_physical_size-1))==0, NULL );
chain& c = s.get_chain( h, n_segment_bits );
chain_mutex_t::scoped_lock chain_lock( c.mutex, /*write=*/true );
node** p = &c.node_list;
while( *p && *p != b )
p = &(*p)->next;
if( !*p ) { // someone else was the first
item_accessor.my_lock.release();
return false;
}
__TBB_ASSERT( *p == b, NULL );
*p = b->next;
--s.my_logical_size;
}
if( readonly ) // need to get exclusive lock
item_accessor.my_lock.upgrade_to_writer(); // return value means nothing here
item_accessor.my_lock.release();
delete_node( b ); // Only one thread can delete it due to write lock on the chain_mutex
return true;
}
template<typename Key, typename T, typename HashCompare, typename A>
void concurrent_hash_map<Key,T,HashCompare,A>::swap(concurrent_hash_map<Key,T,HashCompare,A> &table) {
std::swap(this->my_allocator, table.my_allocator);
std::swap(this->my_hash_compare, table.my_hash_compare);
std::swap(this->my_segment, table.my_segment);
}
template<typename Key, typename T, typename HashCompare, typename A>
void concurrent_hash_map<Key,T,HashCompare,A>::clear() {
#if TBB_PERFORMANCE_WARNINGS
size_t total_physical_size = 0, min_physical_size = size_t(-1L), max_physical_size = 0; //< usage statistics
static bool reported = false;
#endif
for( size_t i=0; i<n_segment; ++i ) {
segment& s = my_segment[i];
size_t n = s.my_physical_size;
if( chain* array = s.my_array ) {
s.my_array = NULL;
s.my_physical_size = 0;
s.my_logical_size = 0;
for( size_t j=0; j<n; ++j ) {
while( node* b = array[j].node_list ) {
array[j].node_list = b->next;
delete_node(b);
}
}
cache_aligned_allocator<chain>().deallocate( array, n );
}
#if TBB_PERFORMANCE_WARNINGS
total_physical_size += n;
if(min_physical_size > n) min_physical_size = n;
if(max_physical_size < n) max_physical_size = n;
}
if( !reported
&& ( (total_physical_size >= n_segment*48 && min_physical_size < total_physical_size/n_segment/2)
|| (total_physical_size >= n_segment*128 && max_physical_size > total_physical_size/n_segment*2) ) )
{
reported = true;
internal::runtime_warning(
"Performance is not optimal because the hash function produces bad randomness in lower bits in %s",
typeid(*this).name() );
#endif
}
}
template<typename Key, typename T, typename HashCompare, typename A>
void concurrent_hash_map<Key,T,HashCompare,A>::grow_segment( segment_mutex_t::scoped_lock& segment_lock, segment& s ) {
// Following is second check in a double-check.
if( s.my_logical_size >= s.my_physical_size ) {
chain* old_array = s.my_array;
size_t old_size = s.my_physical_size;
s.allocate_array( s.my_logical_size+1 );
for( size_t k=0; k<old_size; ++k )
while( node* b = old_array[k].node_list ) {
old_array[k].node_list = b->next;
hashcode_t h = my_hash_compare.hash( b->item.first );
__TBB_ASSERT( &get_segment(h)==&s, "hash function changed?" );
s.get_chain(h,n_segment_bits).push_front(*b);
}
cache_aligned_allocator<chain>().deallocate( old_array, old_size );
}
segment_lock.downgrade_to_reader();
}
template<typename Key, typename T, typename HashCompare, typename A>
void concurrent_hash_map<Key,T,HashCompare,A>::internal_copy( const concurrent_hash_map& source ) {
for( size_t i=0; i<n_segment; ++i ) {
segment& s = source.my_segment[i];
__TBB_ASSERT( !my_segment[i].my_array, "caller should have cleared" );
if( s.my_logical_size ) {
segment& d = my_segment[i];
d.allocate_array( s.my_logical_size );
d.my_logical_size = s.my_logical_size;
size_t s_size = s.my_physical_size;
chain* s_array = s.my_array;
chain* d_array = d.my_array;
for( size_t k=0; k<s_size; ++k )
for( node* b = s_array[k].node_list; b; b=b->next ) {
__TBB_ASSERT( &get_segment(my_hash_compare.hash( b->item.first ))==&d, "hash function changed?" );
node* b_new = create_node(b->item.first, &b->item.second);
d_array[k].push_front(*b_new); // hashcode is the same and segment and my_physical sizes are the same
}
}
}
}
template<typename Key, typename T, typename HashCompare, typename A>
template<typename I>
void concurrent_hash_map<Key,T,HashCompare,A>::internal_copy(I first, I last) {
for(; first != last; ++first)
insert( *first );
}
template<typename Key, typename T, typename HashCompare, typename A1, typename A2>
inline bool operator==(const concurrent_hash_map<Key, T, HashCompare, A1> &a, const concurrent_hash_map<Key, T, HashCompare, A2> &b) {
if(a.size() != b.size()) return false;
typename concurrent_hash_map<Key, T, HashCompare, A1>::const_iterator i(a.begin()), i_end(a.end());
typename concurrent_hash_map<Key, T, HashCompare, A2>::const_iterator j, j_end(b.end());
for(; i != i_end; ++i) {
j = b.equal_range(i->first).first;
if( j == j_end || !(i->second == j->second) ) return false;
}
return true;
}
template<typename Key, typename T, typename HashCompare, typename A1, typename A2>
inline bool operator!=(const concurrent_hash_map<Key, T, HashCompare, A1> &a, const concurrent_hash_map<Key, T, HashCompare, A2> &b)
{ return !(a == b); }
template<typename Key, typename T, typename HashCompare, typename A>
inline void swap(concurrent_hash_map<Key, T, HashCompare, A> &a, concurrent_hash_map<Key, T, HashCompare, A> &b)
{ a.swap( b ); }
} // namespace tbb
#endif /* __TBB_concurrent_hash_map_H */
| {
"pile_set_name": "Github"
} |
// Package utils contains helper structures and function
package utils
// Buffer is a simple wrapper around a []byte to facilitate efficient marshaling of lattigo's objects
type Buffer struct {
buf []byte
}
// NewBuffer creates a new buffer from the provided backing slice
func NewBuffer(s []byte) *Buffer {
return &Buffer{s}
}
// WriteUint8 writes an uint8 on the target byte buffer.
func (b *Buffer) WriteUint8(c byte) {
b.buf = append(b.buf, c)
}
// WriteUint64 writes an uint64 on the target byte buffer.
func (b *Buffer) WriteUint64(v uint64) {
b.buf = append(b.buf, byte(v>>56),
byte(v>>48),
byte(v>>40),
byte(v>>32),
byte(v>>24),
byte(v>>16),
byte(v>>8),
byte(v))
}
// WriteUint64Slice writes an uint64 slice on the target byte buffer.
func (b *Buffer) WriteUint64Slice(s []uint64) {
for _, v := range s {
b.WriteUint64(v)
}
}
// WriteUint8Slice writes an uint8 slice on the target byte buffer.
func (b *Buffer) WriteUint8Slice(s []uint8) {
for _, v := range s {
b.WriteUint8(v)
}
}
// ReadUint8 reads an uint8 from the target byte buffer.
func (b *Buffer) ReadUint8() byte {
v := b.buf[0]
b.buf = b.buf[1:]
return v
}
// ReadUint64 reads an uint64 from the target byte buffer.
func (b *Buffer) ReadUint64() uint64 {
v := b.buf[:8]
b.buf = b.buf[8:]
return uint64(v[7]) | uint64(v[6])<<8 | uint64(v[5])<<16 | uint64(v[4])<<24 |
uint64(v[3])<<32 | uint64(v[2])<<40 | uint64(v[1])<<48 | uint64(v[0])<<56
}
// ReadUint64Slice reads an uint64 slice from the target byte buffer.
func (b *Buffer) ReadUint64Slice(rec []uint64) {
for i := range rec {
rec[i] = b.ReadUint64()
}
}
// ReadUint8Slice reads an uint8 slice from the target byte buffer.
func (b *Buffer) ReadUint8Slice(rec []uint8) {
for i := range rec {
rec[i] = b.ReadUint8()
}
}
// Bytes creates a new byte buffer
func (b *Buffer) Bytes() []byte {
return b.buf
}
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author Yurii Shyrma ([email protected]), created by on 06.04.2018
//
#ifndef LIBND4J_SRU_H
#define LIBND4J_SRU_H
#include <ops/declarable/helpers/helpers.h>
namespace sd {
namespace ops {
namespace helpers {
void sruCell(sd::LaunchContext * context, const NDArray* x, const NDArray* c0, const NDArray* w, const NDArray* b, NDArray* h, NDArray* c);
void sruTimeLoop(sd::LaunchContext * context, const NDArray* x, const NDArray* c0, const NDArray* w, const NDArray* b, NDArray* h, NDArray* c);
void sruBI(sd::LaunchContext * context, NDArray* x, const NDArray* w, const NDArray* b, const NDArray* c0, const NDArray* mask, NDArray* ht, NDArray* ct);
void sruBIBP(sd::LaunchContext * context, NDArray* x, const NDArray* w, const NDArray* b, const NDArray* c0, const NDArray* ct, const NDArray* inGradC0, const NDArray* inGradH, const NDArray* mask,
NDArray* gradI, NDArray* gradWeights, NDArray* gradB, NDArray* gradC0);
}
}
}
#endif //LIBND4J_SRU_H
| {
"pile_set_name": "Github"
} |
<tool id="compressed_neostorezip_neostore_conversion" name="Confirm neostore.zip is converted to neostore on demand">
<command>
cat '$input1' > '$out_file1'
</command>
<inputs>
<param name="input1" type="data" format="neostore.zip" label="Compressed Dataset"/>
</inputs>
<outputs>
<data name="out_file1" format="neostore"/>
</outputs>
<tests>
<test>
<param name="input1" value="neostore.zip"/>
<output name="out_file1" file="neostore"/>
</test>
</tests>
<help>
</help>
</tool>
| {
"pile_set_name": "Github"
} |
/*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.modules.home.commands;
import io.github.nucleuspowered.nucleus.api.module.home.NucleusHomeService;
import io.github.nucleuspowered.nucleus.api.module.home.data.Home;
import io.github.nucleuspowered.nucleus.api.teleport.data.TeleportResult;
import io.github.nucleuspowered.nucleus.modules.home.HomePermissions;
import io.github.nucleuspowered.nucleus.modules.home.config.HomeConfig;
import io.github.nucleuspowered.nucleus.modules.home.events.UseHomeEvent;
import io.github.nucleuspowered.nucleus.modules.home.parameters.HomeArgument;
import io.github.nucleuspowered.nucleus.modules.home.services.HomeService;
import io.github.nucleuspowered.nucleus.scaffold.command.ICommandContext;
import io.github.nucleuspowered.nucleus.scaffold.command.ICommandExecutor;
import io.github.nucleuspowered.nucleus.scaffold.command.ICommandResult;
import io.github.nucleuspowered.nucleus.scaffold.command.annotation.Command;
import io.github.nucleuspowered.nucleus.scaffold.command.annotation.CommandModifier;
import io.github.nucleuspowered.nucleus.scaffold.command.annotation.EssentialsEquivalent;
import io.github.nucleuspowered.nucleus.scaffold.command.modifier.CommandModifiers;
import io.github.nucleuspowered.nucleus.services.INucleusServiceCollection;
import io.github.nucleuspowered.nucleus.services.interfaces.IReloadableService;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.CauseStackManager;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import java.util.Optional;
@EssentialsEquivalent(value = {"home", "homes"}, notes = "'/homes' will list homes, '/home' will teleport like Essentials did.")
@Command(
aliases = {"home"},
basePermission = HomePermissions.BASE_HOME,
commandDescriptionKey = "home",
modifiers = {
@CommandModifier(value = CommandModifiers.HAS_COOLDOWN, exemptPermission = HomePermissions.EXEMPT_COOLDOWN_HOME),
@CommandModifier(value = CommandModifiers.HAS_WARMUP, exemptPermission = HomePermissions.EXEMPT_WARMUP_HOME),
@CommandModifier(value = CommandModifiers.HAS_COST, exemptPermission = HomePermissions.EXEMPT_COST_HOME)
},
associatedPermissions = HomePermissions.HOME_EXEMPT_SAMEDIMENSION
)
@NonnullByDefault
public class HomeCommand implements ICommandExecutor<Player>, IReloadableService.Reloadable {
private final String home = "home";
private boolean isSafeTeleport = true;
private boolean isPreventOverhang = true;
private boolean isOnlySameDimension = false;
@Override
public CommandElement[] parameters(INucleusServiceCollection serviceCollection) {
return new CommandElement[] {
GenericArguments.onlyOne(GenericArguments.optional(
new HomeArgument(Text.of(this.home), serviceCollection.getServiceUnchecked(HomeService.class), serviceCollection.messageProvider()))
)
};
}
@Override public ICommandResult execute(ICommandContext<? extends Player> context) throws CommandException {
HomeService homeService = context.getServiceCollection().getServiceUnchecked(HomeService.class);
Player player = context.getIfPlayer();
int max = homeService.getMaximumHomes(player) ;
int current = homeService.getHomeCount(player);
if (this.isPreventOverhang && max < current) {
// If the player has too many homes, tell them
return context.errorResult("command.home.overhang", max, current);
}
// Get the home.
Optional<Home> owl = context.getOne(this.home, Home.class);
Home wl;
if (owl.isPresent()) {
wl = owl.get();
} else {
Optional<Home> home = homeService.getHome(player, NucleusHomeService.DEFAULT_HOME_NAME);
if (!home.isPresent()) {
return context.errorResult("args.home.nohome", NucleusHomeService.DEFAULT_HOME_NAME);
}
wl = home.get();;
}
Sponge.getServer().loadWorld(wl.getWorldProperties()
.orElseThrow(() -> context.createException("command.home.invalid", wl.getName())));
Location<World> targetLocation = wl.getLocation().orElseThrow(() -> context.createException("command.home.invalid", wl.getName()));
if (this.isOnlySameDimension) {
if (!targetLocation.getExtent().getUniqueId().equals(player.getLocation().getExtent().getUniqueId())) {
if (!context.testPermission(HomePermissions.HOME_EXEMPT_SAMEDIMENSION)) {
return context.errorResult("command.home.invalid", wl.getName());
}
}
}
try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
frame.pushCause(player);
UseHomeEvent event = new UseHomeEvent(frame.getCurrentCause(), player, wl);
if (Sponge.getEventManager().post(event)) {
return event.getCancelMessage().map(x -> context.errorResultLiteral(Text.of(x)))
.orElseGet(() -> context.errorResult("nucleus.eventcancelled"));
}
}
TeleportResult result = homeService.warpToHome(
player,
wl,
this.isSafeTeleport
);
// Warp to it safely.
if (result.isSuccessful()) {
if (!wl.getName().equalsIgnoreCase(NucleusHomeService.DEFAULT_HOME_NAME)) {
context.sendMessage("command.home.success", wl.getName());
} else {
context.sendMessage("command.home.successdefault");
}
return context.successResult();
} else {
return context.errorResult("command.home.fail", wl.getName());
}
}
@Override
public void onReload(INucleusServiceCollection serviceCollection) {
HomeConfig hc = serviceCollection.moduleDataProvider().getModuleConfig(HomeConfig.class);
this.isSafeTeleport = hc.isSafeTeleport();
this.isPreventOverhang = hc.isPreventHomeCountOverhang();
this.isOnlySameDimension = hc.isOnlySameDimension();
}
}
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -emit-llvm -o %t %s
@interface BASE {
@private
void* _reserved;
}
@end
@class PVR;
@interface PVRHandldler
{
PVR *_imageBrowser;
}
@end
@implementation PVRHandldler @end
@interface PVR : BASE
@end
@implementation PVR
@end
// Reopen of an interface after use.
@interface A {
@public
int x;
}
@property int p0;
@end
int f0(A *a) {
return a.p0;
}
@implementation A
@synthesize p0 = _p0;
@end
@interface B
@end
@class B;
@implementation B
@end
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) 2014-2019 [email protected]
This file is part of dnSpy
dnSpy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dnSpy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace dnSpy.Debugger.DotNet.CorDebug.Native {
static class NativeMethods {
[DllImport("kernel32", SetLastError = true)]
public static extern bool GetExitCodeProcess(IntPtr hProcess, out int lpExitCode);
[DllImport("kernel32", SetLastError = true)]
public static extern SafeProcessHandle OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
public const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
const uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
const uint SYNCHRONIZE = 0x00100000;
public const uint PROCESS_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFFF;
[DllImport("kernel32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process(IntPtr hProcess, out bool Wow64Process);
[DllImport("mscoree", PreserveSig = false)]
[return: MarshalAs(UnmanagedType.Interface)]
public static extern object CLRCreateInstance(ref Guid clsid, ref Guid riid);
}
}
| {
"pile_set_name": "Github"
} |
using ShaderPlayground.Core.Util;
namespace ShaderPlayground.Core.Compilers.SpirvTools
{
internal sealed class SpirvAssemblerCompiler : IShaderCompiler
{
public string Name { get; } = CompilerNames.SpirvAssembler;
public string DisplayName { get; } = "spirv-as";
public string Url { get; } = "https://github.com/KhronosGroup/SPIRV-Tools#assembler-binary-parser-and-disassembler";
public string Description { get; } = "Reads the assembly language text, and emits the binary form.";
public string[] InputLanguages { get; } = { LanguageNames.SpirvAssembly };
public ShaderCompilerParameter[] Parameters { get; } =
{
CommonParameters.CreateVersionParameter("spirv-tools"),
new ShaderCompilerParameter("TargetEnv", "Target environment", ShaderCompilerParameterType.ComboBox, TargetEnvOptions, defaultValue: "spv1.0"),
CommonParameters.CreateOutputParameter(new[] { LanguageNames.SpirV })
};
private static readonly string[] TargetEnvOptions =
{
"vulkan1.0",
"vulkan1.1",
"spv1.0",
"spv1.1",
"spv1.2",
"spv1.3"
};
public ShaderCompilerResult Compile(ShaderCode shaderCode, ShaderCompilerArguments arguments)
{
var outputLanguage = arguments.GetString(CommonParameters.OutputLanguageParameterName);
using (var tempFile = TempFile.FromShaderCode(shaderCode))
{
var outputPath = $"{tempFile.FilePath}.out";
ProcessHelper.Run(
CommonParameters.GetBinaryPath("spirv-tools", arguments, "spirv-as.exe"),
$"-o \"{outputPath}\" --preserve-numeric-ids --target-env {arguments.GetString("TargetEnv")} \"{tempFile.FilePath}\"",
out var _,
out var stdError);
var binaryOutput = FileHelper.ReadAllBytesIfExists(outputPath);
var hasCompilationError = !string.IsNullOrEmpty(stdError);
string textOutput = null;
if (!hasCompilationError)
{
var textOutputPath = $"{tempFile.FilePath}.txt";
ProcessHelper.Run(
CommonParameters.GetBinaryPath("spirv-tools", arguments, "spirv-dis.exe"),
$"-o \"{textOutputPath}\" \"{outputPath}\"",
out var _,
out var _);
textOutput = FileHelper.ReadAllTextIfExists(textOutputPath);
FileHelper.DeleteIfExists(textOutputPath);
}
FileHelper.DeleteIfExists(outputPath);
return new ShaderCompilerResult(
!hasCompilationError,
!hasCompilationError ? new ShaderCode(outputLanguage, binaryOutput) : null,
hasCompilationError ? (int?) 1 : null,
new ShaderCompilerOutput("Output", outputLanguage, textOutput),
new ShaderCompilerOutput("Build errors", null, stdError));
}
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 1994-2000 The XFree86 Project, Inc. All Rights Reserved.
* Copyright (C) Colin Harrison 2005-2008
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE XFREE86 PROJECT BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Except as contained in this notice, the name of the XFree86 Project
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* from the XFree86 Project.
*
* Authors: Earle F. Philhower, III
* Colin Harrison
*/
#if !defined(WINPREFS_H)
#define WINPREFS_H
/* Need Bool */
#include <X11/Xdefs.h>
/* Need TRUE */
#include "misc.h"
/* Need to know how long paths can be... */
#include <limits.h>
/* Xwindows redefines PATH_MAX to at least 1024 */
#include <X11/Xwindows.h>
#include "winwindow.h"
#ifndef NAME_MAX
#define NAME_MAX PATH_MAX
#endif
#define MENU_MAX 128 /* Maximum string length of a menu name or item */
#define PARAM_MAX (4*PATH_MAX) /* Maximum length of a parameter to a MENU */
/* Supported commands in a MENU {} statement */
typedef enum MENUCOMMANDTYPE {
CMD_EXEC, /* /bin/sh -c the parameter */
CMD_MENU, /* Display a popup menu named param */
CMD_SEPARATOR, /* Menu separator */
CMD_ALWAYSONTOP, /* Toggle always-on-top mode */
CMD_RELOAD /* Reparse the .XWINRC file */
} MENUCOMMANDTYPE;
#define STYLE_NONE (0L) /* Dummy the first entry */
#define STYLE_NOTITLE (1L) /* Force window style no titlebar */
#define STYLE_OUTLINE (1L<<1) /* Force window style just thin-line border */
#define STYLE_NOFRAME (1L<<2) /* Force window style no frame */
#define STYLE_TOPMOST (1L<<3) /* Open a window always-on-top */
#define STYLE_MAXIMIZE (1L<<4) /* Open a window maximized */
#define STYLE_MINIMIZE (1L<<5) /* Open a window minimized */
#define STYLE_BOTTOM (1L<<6) /* Open a window at the bottom of the Z order */
/* Where to place a system menu */
typedef enum MENUPOSITION {
AT_START, /* Place menu at the top of the system menu */
AT_END /* Put it at the bottom of the menu (default) */
} MENUPOSITION;
/* Menu item definitions */
typedef struct MENUITEM {
char text[MENU_MAX + 1]; /* To be displayed in menu */
MENUCOMMANDTYPE cmd; /* What should it do? */
char param[PARAM_MAX + 1]; /* Any parameters? */
unsigned long commandID; /* Windows WM_COMMAND ID assigned at runtime */
} MENUITEM;
/* A completely read in menu... */
typedef struct MENUPARSED {
char menuName[MENU_MAX + 1]; /* What's it called in the text? */
MENUITEM *menuItem; /* Array of items */
int menuItems; /* How big's the array? */
} MENUPARSED;
/* To map between a window and a system menu to add for it */
typedef struct SYSMENUITEM {
char match[MENU_MAX + 1]; /* String to look for to apply this sysmenu */
char menuName[MENU_MAX + 1]; /* Which menu to show? Used to set *menu */
MENUPOSITION menuPos; /* Where to place it (ignored in root) */
} SYSMENUITEM;
/* To redefine icons for certain window types */
typedef struct ICONITEM {
char match[MENU_MAX + 1]; /* What string to search for? */
char iconFile[PATH_MAX + NAME_MAX + 2]; /* Icon location, WIN32 path */
HICON hicon; /* LoadImage() result */
} ICONITEM;
/* To redefine styles for certain window types */
typedef struct STYLEITEM {
char match[MENU_MAX + 1]; /* What string to search for? */
unsigned long type; /* What should it do? */
} STYLEITEM;
typedef struct WINPREFS {
/* Menu information */
MENUPARSED *menu; /* Array of created menus */
int menuItems; /* How big? */
/* Taskbar menu settings */
char rootMenuName[MENU_MAX + 1]; /* Menu for taskbar icon */
/* System menu addition menus */
SYSMENUITEM *sysMenu;
int sysMenuItems;
/* Which menu to add to unmatched windows? */
char defaultSysMenuName[MENU_MAX + 1];
MENUPOSITION defaultSysMenuPos; /* Where to place it */
/* Icon information */
char iconDirectory[PATH_MAX + 1]; /* Where do the .icos lie? (Win32 path) */
char defaultIconName[NAME_MAX + 1]; /* Replacement for x.ico */
char trayIconName[NAME_MAX + 1]; /* Replacement for tray icon */
ICONITEM *icon;
int iconItems;
STYLEITEM *style;
int styleItems;
/* Force exit flag */
Bool fForceExit;
/* Silent exit flag */
Bool fSilentExit;
} WINPREFS;
/* The global pref settings structure loaded by the winprefyacc.y parser */
extern WINPREFS pref;
/* Functions */
void
LoadPreferences(void);
void
SetupRootMenu(HMENU root);
void
SetupSysMenu(HWND hwnd);
void
HandleCustomWM_INITMENU(HWND hwnd, HMENU hmenu);
Bool
HandleCustomWM_COMMAND(HWND hwnd, WORD command, winPrivScreenPtr pScreenPriv);
int
winIconIsOverride(HICON hicon);
HICON winOverrideIcon(char *res_name, char *res_class, char *wmName);
unsigned long
winOverrideStyle(char *res_name, char *res_class, char *wmName);
HICON winTaskbarIcon(void);
HICON winOverrideDefaultIcon(int size);
#endif
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 Code Above Lab LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codeabovelab.dm.cluman.job;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Component of job scope.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Component
@Scope(value = JobScope.SCOPE_NAME)
public @interface JobComponent {
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="classes_8.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div id="SRResults"></div>
<script type="text/javascript"><!--
createResults();
--></script>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Optimize combinations of instructions
//
#include <algorithm>
#include <type_traits>
#include <ir/abstract.h>
#include <ir/bits.h>
#include <ir/cost.h>
#include <ir/effects.h>
#include <ir/literal-utils.h>
#include <ir/load-utils.h>
#include <ir/manipulation.h>
#include <ir/match.h>
#include <ir/properties.h>
#include <ir/utils.h>
#include <pass.h>
#include <support/threads.h>
#include <wasm-s-parser.h>
#include <wasm.h>
// TODO: Use the new sign-extension opcodes where appropriate. This needs to be
// conditionalized on the availability of atomics.
namespace wasm {
Name I32_EXPR = "i32.expr";
Name I64_EXPR = "i64.expr";
Name F32_EXPR = "f32.expr";
Name F64_EXPR = "f64.expr";
Name ANY_EXPR = "any.expr";
// Useful information about locals
struct LocalInfo {
static const Index kUnknown = Index(-1);
Index maxBits;
Index signExtedBits;
};
struct LocalScanner : PostWalker<LocalScanner> {
std::vector<LocalInfo>& localInfo;
const PassOptions& passOptions;
LocalScanner(std::vector<LocalInfo>& localInfo,
const PassOptions& passOptions)
: localInfo(localInfo), passOptions(passOptions) {}
void doWalkFunction(Function* func) {
// prepare
localInfo.resize(func->getNumLocals());
for (Index i = 0; i < func->getNumLocals(); i++) {
auto& info = localInfo[i];
if (func->isParam(i)) {
info.maxBits = getBitsForType(func->getLocalType(i)); // worst-case
info.signExtedBits = LocalInfo::kUnknown; // we will never know anything
} else {
info.maxBits = info.signExtedBits = 0; // we are open to learning
}
}
// walk
PostWalker<LocalScanner>::doWalkFunction(func);
// finalize
for (Index i = 0; i < func->getNumLocals(); i++) {
auto& info = localInfo[i];
if (info.signExtedBits == LocalInfo::kUnknown) {
info.signExtedBits = 0;
}
}
}
void visitLocalSet(LocalSet* curr) {
auto* func = getFunction();
if (func->isParam(curr->index)) {
return;
}
auto type = getFunction()->getLocalType(curr->index);
if (type != Type::i32 && type != Type::i64) {
return;
}
// an integer var, worth processing
auto* value = Properties::getFallthrough(
curr->value, passOptions, getModule()->features);
auto& info = localInfo[curr->index];
info.maxBits = std::max(info.maxBits, Bits::getMaxBits(value, this));
auto signExtBits = LocalInfo::kUnknown;
if (Properties::getSignExtValue(value)) {
signExtBits = Properties::getSignExtBits(value);
} else if (auto* load = value->dynCast<Load>()) {
if (LoadUtils::isSignRelevant(load) && load->signed_) {
signExtBits = load->bytes * 8;
}
}
if (info.signExtedBits == 0) {
info.signExtedBits = signExtBits; // first info we see
} else if (info.signExtedBits != signExtBits) {
// contradictory information, give up
info.signExtedBits = LocalInfo::kUnknown;
}
}
// define this for the templated getMaxBits method. we know nothing here yet
// about locals, so return the maxes
Index getMaxBitsForLocal(LocalGet* get) { return getBitsForType(get->type); }
Index getBitsForType(Type type) {
TODO_SINGLE_COMPOUND(type);
switch (type.getBasic()) {
case Type::i32:
return 32;
case Type::i64:
return 64;
default:
return -1;
}
}
};
// Create a custom matcher for checking side effects
template<class Opt> struct PureMatcherKind {};
template<class Opt>
struct Match::Internal::KindTypeRegistry<PureMatcherKind<Opt>> {
using matched_t = Expression*;
using data_t = Opt*;
};
template<class Opt> struct Match::Internal::MatchSelf<PureMatcherKind<Opt>> {
bool operator()(Expression* curr, Opt* opt) {
return !opt->effects(curr).hasSideEffects();
}
};
// Main pass class
struct OptimizeInstructions
: public WalkerPass<
PostWalker<OptimizeInstructions,
UnifiedExpressionVisitor<OptimizeInstructions>>> {
bool isFunctionParallel() override { return true; }
Pass* create() override { return new OptimizeInstructions; }
void prepareToRun(PassRunner* runner, Module* module) override {
#if 0
static DatabaseEnsurer ensurer;
#endif
}
void doWalkFunction(Function* func) {
// first, scan locals
{
LocalScanner scanner(localInfo, getPassOptions());
scanner.setModule(getModule());
scanner.walkFunction(func);
}
// main walk
super::doWalkFunction(func);
}
void visitExpression(Expression* curr) {
// we may be able to apply multiple patterns, one may open opportunities
// that look deeper NB: patterns must not have cycles
while (1) {
auto* handOptimized = handOptimize(curr);
if (handOptimized) {
curr = handOptimized;
replaceCurrent(curr);
continue;
}
#if 0
auto iter = database->patternMap.find(curr->_id);
if (iter == database->patternMap.end()) return;
auto& patterns = iter->second;
bool more = false;
for (auto& pattern : patterns) {
Match match(*getModule(), pattern);
if (match.check(curr)) {
curr = match.apply();
replaceCurrent(curr);
more = true;
break; // exit pattern for loop, return to main while loop
}
}
if (!more) break;
#else
break;
#endif
}
}
EffectAnalyzer effects(Expression* expr) {
return EffectAnalyzer(getPassOptions(), getModule()->features, expr);
}
decltype(auto) pure(Expression** binder) {
using namespace Match::Internal;
return Matcher<PureMatcherKind<OptimizeInstructions>>(binder, this);
}
bool canReorder(Expression* a, Expression* b) {
return EffectAnalyzer::canReorder(
getPassOptions(), getModule()->features, a, b);
}
// Optimizations that don't yet fit in the pattern DSL, but could be
// eventually maybe
Expression* handOptimize(Expression* curr) {
FeatureSet features = getModule()->features;
// if this contains dead code, don't bother trying to optimize it, the type
// might change (if might not be unreachable if just one arm is, for
// example). this optimization pass focuses on actually executing code. the
// only exceptions are control flow changes
if (curr->type == Type::unreachable && !curr->is<Break>() &&
!curr->is<Switch>() && !curr->is<If>()) {
return nullptr;
}
if (auto* binary = curr->dynCast<Binary>()) {
if (isSymmetric(binary)) {
canonicalize(binary);
}
}
{
// TODO: It is an ongoing project to port more transformations to the
// match API. Once most of the transformations have been ported, the
// `using namespace Match` can be hoisted to function scope and this extra
// block scope can be removed.
using namespace Match;
Builder builder(*getModule());
{
// X == 0 => eqz X
Expression* x;
if (matches(curr, binary(EqInt32, any(&x), i32(0)))) {
return Builder(*getModule()).makeUnary(EqZInt32, x);
}
}
{
// try to get rid of (0 - ..), that is, a zero only used to negate an
// int. an add of a subtract can be flipped in order to remove it:
// (i32.add
// (i32.sub
// (i32.const 0)
// X
// )
// Y
// )
// =>
// (i32.sub
// Y
// X
// )
// Note that this reorders X and Y, so we need to be careful about that.
Expression *x, *y;
Binary* sub;
if (matches(curr,
binary(AddInt32,
binary(&sub, SubInt32, i32(0), any(&x)),
any(&y))) &&
canReorder(x, y)) {
sub->left = y;
sub->right = x;
return sub;
}
}
{
// The flip case is even easier, as no reordering occurs:
// (i32.add
// Y
// (i32.sub
// (i32.const 0)
// X
// )
// )
// =>
// (i32.sub
// Y
// X
// )
Expression* y;
Binary* sub;
if (matches(curr,
binary(AddInt32,
any(&y),
binary(&sub, SubInt32, i32(0), any())))) {
sub->left = y;
return sub;
}
}
{
// try de-morgan's AND law,
// (eqz X) and (eqz Y) === eqz (X or Y)
// Note that the OR and XOR laws do not work here, as these
// are not booleans (we could check if they are, but a boolean
// would already optimize with the eqz anyhow, unless propagating).
// But for AND, the left is true iff X and Y are each all zero bits,
// and the right is true if the union of their bits is zero; same.
Unary* un;
Binary* bin;
Expression *x, *y;
if (matches(curr,
binary(&bin,
AndInt32,
unary(&un, EqZInt32, any(&x)),
unary(EqZInt32, any(&y))))) {
bin->op = OrInt32;
bin->left = x;
bin->right = y;
un->value = bin;
return un;
}
}
}
if (auto* select = curr->dynCast<Select>()) {
return optimizeSelect(select);
}
if (auto* binary = curr->dynCast<Binary>()) {
if (auto* ext = Properties::getAlmostSignExt(binary)) {
Index extraShifts;
auto bits = Properties::getAlmostSignExtBits(binary, extraShifts);
if (extraShifts == 0) {
if (auto* load =
Properties::getFallthrough(ext, getPassOptions(), features)
->dynCast<Load>()) {
// pattern match a load of 8 bits and a sign extend using a shl of
// 24 then shr_s of 24 as well, etc.
if (LoadUtils::canBeSigned(load) &&
((load->bytes == 1 && bits == 8) ||
(load->bytes == 2 && bits == 16))) {
// if the value falls through, we can't alter the load, as it
// might be captured in a tee
if (load->signed_ == true || load == ext) {
load->signed_ = true;
return ext;
}
}
}
}
// if the sign-extend input cannot have a sign bit, we don't need it
// we also don't need it if it already has an identical-sized sign
// extend
if (Bits::getMaxBits(ext, this) + extraShifts < bits ||
isSignExted(ext, bits)) {
return removeAlmostSignExt(binary);
}
} else if (binary->op == EqInt32 || binary->op == NeInt32) {
if (auto* c = binary->right->dynCast<Const>()) {
if (auto* ext = Properties::getSignExtValue(binary->left)) {
// we are comparing a sign extend to a constant, which means we can
// use a cheaper zext
auto bits = Properties::getSignExtBits(binary->left);
binary->left = makeZeroExt(ext, bits);
// when we replace the sign-ext of the non-constant with a zero-ext,
// we are forcing the high bits to be all zero, instead of all zero
// or all one depending on the sign bit. so we may be changing the
// high bits from all one to all zero:
// * if the constant value's higher bits are mixed, then it can't
// be equal anyhow
// * if they are all zero, we may get a false true if the
// non-constant's upper bits were one. this can only happen if
// the non-constant's sign bit is set, so this false true is a
// risk only if the constant's sign bit is set (otherwise,
// false). But a constant with a sign bit but with upper bits
// zero is impossible to be equal to a sign-extended value
// anyhow, so the entire thing is false.
// * if they were all one, we may get a false false, if the only
// difference is in those upper bits. that means we are equal on
// the other bits, including the sign bit. so we can just mask
// off the upper bits in the constant value, in this case,
// forcing them to zero like we do in the zero-extend.
int32_t constValue = c->value.geti32();
auto upperConstValue = constValue & ~Bits::lowBitMask(bits);
uint32_t count = PopCount(upperConstValue);
auto constSignBit = constValue & (1 << (bits - 1));
if ((count > 0 && count < 32 - bits) ||
(constSignBit && count == 0)) {
// mixed or [zero upper const bits with sign bit set]; the
// compared values can never be identical, so force something
// definitely impossible even after zext
assert(bits < 32);
c->value = Literal(int32_t(0x80000000));
// TODO: if no side effects, we can just replace it all with 1 or
// 0
} else {
// otherwise, they are all ones, so we can mask them off as
// mentioned before
c->value = c->value.and_(Literal(Bits::lowBitMask(bits)));
}
return binary;
}
} else if (auto* left = Properties::getSignExtValue(binary->left)) {
if (auto* right = Properties::getSignExtValue(binary->right)) {
auto bits = Properties::getSignExtBits(binary->left);
if (Properties::getSignExtBits(binary->right) == bits) {
// we are comparing two sign-exts with the same bits, so we may as
// well replace both with cheaper zexts
binary->left = makeZeroExt(left, bits);
binary->right = makeZeroExt(right, bits);
return binary;
}
} else if (auto* load = binary->right->dynCast<Load>()) {
// we are comparing a load to a sign-ext, we may be able to switch
// to zext
auto leftBits = Properties::getSignExtBits(binary->left);
if (load->signed_ && leftBits == load->bytes * 8) {
load->signed_ = false;
binary->left = makeZeroExt(left, leftBits);
return binary;
}
}
} else if (auto* load = binary->left->dynCast<Load>()) {
if (auto* right = Properties::getSignExtValue(binary->right)) {
// we are comparing a load to a sign-ext, we may be able to switch
// to zext
auto rightBits = Properties::getSignExtBits(binary->right);
if (load->signed_ && rightBits == load->bytes * 8) {
load->signed_ = false;
binary->right = makeZeroExt(right, rightBits);
return binary;
}
}
}
// note that both left and right may be consts, but then we let
// precompute compute the constant result
} else if (binary->op == AddInt32) {
if (auto* ret = optimizeAddedConstants(binary)) {
return ret;
}
} else if (binary->op == SubInt32) {
if (auto* ret = optimizeAddedConstants(binary)) {
return ret;
}
}
// a bunch of operations on a constant right side can be simplified
if (auto* right = binary->right->dynCast<Const>()) {
if (binary->op == AndInt32) {
auto mask = right->value.geti32();
// and with -1 does nothing (common in asm.js output)
if (mask == -1) {
return binary->left;
}
// small loads do not need to be masked, the load itself masks
if (auto* load = binary->left->dynCast<Load>()) {
if ((load->bytes == 1 && mask == 0xff) ||
(load->bytes == 2 && mask == 0xffff)) {
load->signed_ = false;
return binary->left;
}
} else if (auto maskedBits = Bits::getMaskedBits(mask)) {
if (Bits::getMaxBits(binary->left, this) <= maskedBits) {
// a mask of lower bits is not needed if we are already smaller
return binary->left;
}
}
}
// some math operations have trivial results
if (auto* ret = optimizeWithConstantOnRight(binary)) {
return ret;
}
// the square of some operations can be merged
if (auto* left = binary->left->dynCast<Binary>()) {
if (left->op == binary->op) {
if (auto* leftRight = left->right->dynCast<Const>()) {
if (left->op == AndInt32) {
leftRight->value = leftRight->value.and_(right->value);
return left;
} else if (left->op == OrInt32) {
leftRight->value = leftRight->value.or_(right->value);
return left;
} else if (left->op == ShlInt32 || left->op == ShrUInt32 ||
left->op == ShrSInt32 || left->op == ShlInt64 ||
left->op == ShrUInt64 || left->op == ShrSInt64) {
// shifts only use an effective amount from the constant, so
// adding must be done carefully
auto total = Bits::getEffectiveShifts(leftRight) +
Bits::getEffectiveShifts(right);
if (total == Bits::getEffectiveShifts(total, right->type)) {
// no overflow, we can do this
leftRight->value = Literal::makeFromInt32(total, right->type);
return left;
} // TODO: handle overflows
}
}
}
}
// math operations on a constant power of 2 right side can be optimized
if (right->type == Type::i32) {
uint32_t c = right->value.geti32();
if (IsPowerOf2(c)) {
switch (binary->op) {
case MulInt32:
return optimizePowerOf2Mul(binary, c);
case RemUInt32:
return optimizePowerOf2URem(binary, c);
case DivUInt32:
return optimizePowerOf2UDiv(binary, c);
default:
break;
}
}
}
if (right->type == Type::i64) {
uint64_t c = right->value.geti64();
if (IsPowerOf2(c)) {
switch (binary->op) {
case MulInt64:
return optimizePowerOf2Mul(binary, c);
case RemUInt64:
return optimizePowerOf2URem(binary, c);
case DivUInt64:
return optimizePowerOf2UDiv(binary, c);
default:
break;
}
}
}
}
// a bunch of operations on a constant left side can be simplified
if (binary->left->is<Const>()) {
if (auto* ret = optimizeWithConstantOnLeft(binary)) {
return ret;
}
}
// bitwise operations
// for and and or, we can potentially conditionalize
if (binary->op == AndInt32 || binary->op == OrInt32) {
if (auto* ret = conditionalizeExpensiveOnBitwise(binary)) {
return ret;
}
}
// for or, we can potentially combine
if (binary->op == OrInt32) {
if (auto* ret = combineOr(binary)) {
return ret;
}
}
// relation/comparisons allow for math optimizations
if (binary->isRelational()) {
if (auto* ret = optimizeRelational(binary)) {
return ret;
}
}
// finally, try more expensive operations on the binary in
// the case that they have no side effects
if (!effects(binary->left).hasSideEffects()) {
if (ExpressionAnalyzer::equal(binary->left, binary->right)) {
if (auto* ret = optimizeBinaryWithEqualEffectlessChildren(binary)) {
return ret;
}
}
}
if (auto* ret = deduplicateBinary(binary)) {
return ret;
}
} else if (auto* unary = curr->dynCast<Unary>()) {
if (unary->op == EqZInt32) {
if (auto* inner = unary->value->dynCast<Binary>()) {
// Try to invert a relational operation using De Morgan's law
auto op = invertBinaryOp(inner->op);
if (op != InvalidBinary) {
inner->op = op;
return inner;
}
}
// eqz of a sign extension can be of zero-extension
if (auto* ext = Properties::getSignExtValue(unary->value)) {
// we are comparing a sign extend to a constant, which means we can
// use a cheaper zext
auto bits = Properties::getSignExtBits(unary->value);
unary->value = makeZeroExt(ext, bits);
return unary;
}
}
if (auto* ret = deduplicateUnary(unary)) {
return ret;
}
} else if (auto* set = curr->dynCast<GlobalSet>()) {
// optimize out a set of a get
auto* get = set->value->dynCast<GlobalGet>();
if (get && get->name == set->name) {
ExpressionManipulator::nop(curr);
}
} else if (auto* iff = curr->dynCast<If>()) {
iff->condition = optimizeBoolean(iff->condition);
if (iff->ifFalse) {
if (auto* unary = iff->condition->dynCast<Unary>()) {
if (unary->op == EqZInt32) {
// flip if-else arms to get rid of an eqz
iff->condition = unary->value;
std::swap(iff->ifTrue, iff->ifFalse);
}
}
if (iff->condition->type != Type::unreachable &&
ExpressionAnalyzer::equal(iff->ifTrue, iff->ifFalse)) {
// sides are identical, fold
// if we can replace the if with one arm, and no side effects in the
// condition, do that
auto needCondition = effects(iff->condition).hasSideEffects();
auto isSubType = Type::isSubType(iff->ifTrue->type, iff->type);
if (isSubType && !needCondition) {
return iff->ifTrue;
} else {
Builder builder(*getModule());
if (isSubType) {
return builder.makeSequence(builder.makeDrop(iff->condition),
iff->ifTrue);
} else {
// the types diff. as the condition is reachable, that means the
// if must be concrete while the arm is not
assert(iff->type.isConcrete() &&
iff->ifTrue->type == Type::unreachable);
// emit a block with a forced type
auto* ret = builder.makeBlock();
if (needCondition) {
ret->list.push_back(builder.makeDrop(iff->condition));
}
ret->list.push_back(iff->ifTrue);
ret->finalize(iff->type);
return ret;
}
}
}
}
} else if (auto* br = curr->dynCast<Break>()) {
if (br->condition) {
br->condition = optimizeBoolean(br->condition);
}
} else if (auto* load = curr->dynCast<Load>()) {
optimizeMemoryAccess(load->ptr, load->offset);
} else if (auto* store = curr->dynCast<Store>()) {
optimizeMemoryAccess(store->ptr, store->offset);
// stores of fewer bits truncates anyhow
if (auto* binary = store->value->dynCast<Binary>()) {
if (binary->op == AndInt32) {
if (auto* right = binary->right->dynCast<Const>()) {
if (right->type == Type::i32) {
auto mask = right->value.geti32();
if ((store->bytes == 1 && mask == 0xff) ||
(store->bytes == 2 && mask == 0xffff)) {
store->value = binary->left;
}
}
}
} else if (auto* ext = Properties::getSignExtValue(binary)) {
// if sign extending the exact bit size we store, we can skip the
// extension if extending something bigger, then we just alter bits we
// don't save anyhow
if (Properties::getSignExtBits(binary) >= Index(store->bytes) * 8) {
store->value = ext;
}
}
} else if (auto* unary = store->value->dynCast<Unary>()) {
if (unary->op == WrapInt64) {
// instead of wrapping to 32, just store some of the bits in the i64
store->valueType = Type::i64;
store->value = unary->value;
}
}
} else if (auto* memCopy = curr->dynCast<MemoryCopy>()) {
assert(features.hasBulkMemory());
if (auto* ret = optimizeMemoryCopy(memCopy)) {
return ret;
}
}
return nullptr;
}
Index getMaxBitsForLocal(LocalGet* get) {
// check what we know about the local
return localInfo[get->index].maxBits;
}
private:
// Information about our locals
std::vector<LocalInfo> localInfo;
// Canonicalizing the order of a symmetric binary helps us
// write more concise pattern matching code elsewhere.
void canonicalize(Binary* binary) {
assert(isSymmetric(binary));
auto swap = [&]() {
assert(canReorder(binary->left, binary->right));
std::swap(binary->left, binary->right);
};
auto maybeSwap = [&]() {
if (canReorder(binary->left, binary->right)) {
swap();
}
};
// Prefer a const on the right.
if (binary->left->is<Const>() && !binary->right->is<Const>()) {
return swap();
}
if (binary->right->is<Const>()) {
return;
}
// Prefer a get on the right.
if (binary->left->is<LocalGet>() && !binary->right->is<LocalGet>()) {
return maybeSwap();
}
// Sort by the node id type, if different.
if (binary->left->_id != binary->right->_id) {
if (binary->left->_id > binary->right->_id) {
return maybeSwap();
}
return;
}
// If the children have the same node id, we have to go deeper.
if (auto* left = binary->left->dynCast<Unary>()) {
auto* right = binary->right->cast<Unary>();
if (left->op > right->op) {
return maybeSwap();
}
}
if (auto* left = binary->left->dynCast<Binary>()) {
auto* right = binary->right->cast<Binary>();
if (left->op > right->op) {
return maybeSwap();
}
}
if (auto* left = binary->left->dynCast<LocalGet>()) {
auto* right = binary->right->cast<LocalGet>();
if (left->index > right->index) {
return maybeSwap();
}
}
}
// Optimize given that the expression is flowing into a boolean context
Expression* optimizeBoolean(Expression* boolean) {
// TODO use a general getFallthroughs
if (auto* unary = boolean->dynCast<Unary>()) {
if (unary) {
if (unary->op == EqZInt32) {
auto* unary2 = unary->value->dynCast<Unary>();
if (unary2 && unary2->op == EqZInt32) {
// double eqz
return unary2->value;
}
if (auto* binary = unary->value->dynCast<Binary>()) {
// !(x <=> y) ==> x <!=> y
auto op = invertBinaryOp(binary->op);
if (op != InvalidBinary) {
binary->op = op;
return binary;
}
}
}
}
} else if (auto* binary = boolean->dynCast<Binary>()) {
if (binary->op == SubInt32) {
if (auto* c = binary->left->dynCast<Const>()) {
if (c->value.geti32() == 0) {
// bool(0 - x) ==> bool(x)
return binary->right;
}
}
} else if (binary->op == OrInt32) {
// an or flowing into a boolean context can consider each input as
// boolean
binary->left = optimizeBoolean(binary->left);
binary->right = optimizeBoolean(binary->right);
} else if (binary->op == NeInt32) {
if (auto* c = binary->right->dynCast<Const>()) {
// x != 0 is just x if it's used as a bool
if (c->value.geti32() == 0) {
return binary->left;
}
// TODO: Perhaps use it for separate final pass???
// x != -1 ==> x ^ -1
// if (num->value.geti32() == -1) {
// binary->op = XorInt32;
// return binary;
// }
}
}
if (auto* ext = Properties::getSignExtValue(binary)) {
// use a cheaper zero-extent, we just care about the boolean value
// anyhow
return makeZeroExt(ext, Properties::getSignExtBits(binary));
}
} else if (auto* block = boolean->dynCast<Block>()) {
if (block->type == Type::i32 && block->list.size() > 0) {
block->list.back() = optimizeBoolean(block->list.back());
}
} else if (auto* iff = boolean->dynCast<If>()) {
if (iff->type == Type::i32) {
iff->ifTrue = optimizeBoolean(iff->ifTrue);
iff->ifFalse = optimizeBoolean(iff->ifFalse);
}
} else if (auto* select = boolean->dynCast<Select>()) {
select->ifTrue = optimizeBoolean(select->ifTrue);
select->ifFalse = optimizeBoolean(select->ifFalse);
} else if (auto* tryy = boolean->dynCast<Try>()) {
if (tryy->type == Type::i32) {
tryy->body = optimizeBoolean(tryy->body);
tryy->catchBody = optimizeBoolean(tryy->catchBody);
}
}
// TODO: recurse into br values?
return boolean;
}
Expression* optimizeSelect(Select* curr) {
using namespace Match;
Builder builder(*getModule());
curr->condition = optimizeBoolean(curr->condition);
{
// Constant condition, we can just pick the correct side (barring side
// effects)
Expression *ifTrue, *ifFalse;
if (matches(curr, select(pure(&ifTrue), any(&ifFalse), i32(0)))) {
return ifFalse;
}
if (matches(curr, select(any(&ifTrue), any(&ifFalse), i32(0)))) {
return builder.makeSequence(builder.makeDrop(ifTrue), ifFalse);
}
int32_t cond;
if (matches(curr, select(any(&ifTrue), pure(&ifFalse), i32(&cond)))) {
// The condition must be non-zero because a zero would have matched one
// of the previous patterns.
assert(cond != 0);
return ifTrue;
}
// Don't bother when `ifFalse` isn't pure - we would need to reverse the
// order using a temp local, which would be bad
}
{
// Flip select to remove eqz if we can reorder
Select* s;
Expression *ifTrue, *ifFalse, *c;
if (matches(
curr,
select(
&s, any(&ifTrue), any(&ifFalse), unary(EqZInt32, any(&c)))) &&
canReorder(ifTrue, ifFalse)) {
s->ifTrue = ifFalse;
s->ifFalse = ifTrue;
s->condition = c;
}
}
{
// Simplify selects between 0 and 1
Expression* c;
bool reversed = matches(curr, select(ival(0), ival(1), any(&c)));
if (reversed || matches(curr, select(ival(1), ival(0), any(&c)))) {
if (reversed) {
c = optimizeBoolean(builder.makeUnary(EqZInt32, c));
}
if (!Properties::emitsBoolean(c)) {
// cond ? 1 : 0 ==> !!cond
c = builder.makeUnary(EqZInt32, builder.makeUnary(EqZInt32, c));
}
return curr->type == Type::i64 ? builder.makeUnary(ExtendUInt32, c) : c;
}
}
{
// Sides are identical, fold
Expression *ifTrue, *ifFalse, *c;
if (matches(curr, select(any(&ifTrue), any(&ifFalse), any(&c))) &&
ExpressionAnalyzer::equal(ifTrue, ifFalse)) {
auto value = effects(ifTrue);
if (value.hasSideEffects()) {
// At best we don't need the condition, but need to execute the
// value twice. a block is larger than a select by 2 bytes, and we
// must drop one value, so 3, while we save the condition, so it's
// not clear this is worth it, TODO
} else {
// value has no side effects
auto condition = effects(c);
if (!condition.hasSideEffects()) {
return ifTrue;
} else {
// The condition is last, so we need a new local, and it may be a
// bad idea to use a block like we do for an if. Do it only if we
// can reorder
if (!condition.invalidates(value)) {
return builder.makeSequence(builder.makeDrop(c), ifTrue);
}
}
}
}
}
return nullptr;
}
// find added constants in an expression tree, including multiplied/shifted,
// and combine them note that we ignore division/shift-right, as rounding
// makes this nonlinear, so not a valid opt
Expression* optimizeAddedConstants(Binary* binary) {
uint32_t constant = 0;
std::vector<Const*> constants;
struct SeekState {
Expression* curr;
int mul;
SeekState(Expression* curr, int mul) : curr(curr), mul(mul) {}
};
std::vector<SeekState> seekStack;
seekStack.emplace_back(binary, 1);
while (!seekStack.empty()) {
auto state = seekStack.back();
seekStack.pop_back();
auto curr = state.curr;
auto mul = state.mul;
if (auto* c = curr->dynCast<Const>()) {
uint32_t value = c->value.geti32();
if (value != 0) {
constant += value * mul;
constants.push_back(c);
}
continue;
} else if (auto* binary = curr->dynCast<Binary>()) {
if (binary->op == AddInt32) {
seekStack.emplace_back(binary->right, mul);
seekStack.emplace_back(binary->left, mul);
continue;
} else if (binary->op == SubInt32) {
// if the left is a zero, ignore it, it's how we negate ints
auto* left = binary->left->dynCast<Const>();
seekStack.emplace_back(binary->right, -mul);
if (!left || left->value.geti32() != 0) {
seekStack.emplace_back(binary->left, mul);
}
continue;
} else if (binary->op == ShlInt32) {
if (auto* c = binary->right->dynCast<Const>()) {
seekStack.emplace_back(binary->left,
mul * Pow2(Bits::getEffectiveShifts(c)));
continue;
}
} else if (binary->op == MulInt32) {
if (auto* c = binary->left->dynCast<Const>()) {
seekStack.emplace_back(binary->right, mul * c->value.geti32());
continue;
} else if (auto* c = binary->right->dynCast<Const>()) {
seekStack.emplace_back(binary->left, mul * c->value.geti32());
continue;
}
}
}
};
// find all factors
if (constants.size() <= 1) {
// nothing much to do, except for the trivial case of adding/subbing a
// zero
if (auto* c = binary->right->dynCast<Const>()) {
if (c->value.geti32() == 0) {
return binary->left;
}
}
return nullptr;
}
// wipe out all constants, we'll replace with a single added one
for (auto* c : constants) {
c->value = Literal(int32_t(0));
}
// remove added/subbed zeros
struct ZeroRemover : public PostWalker<ZeroRemover> {
// TODO: we could save the binarys and costs we drop, and reuse them later
PassOptions& passOptions;
ZeroRemover(PassOptions& passOptions) : passOptions(passOptions) {}
void visitBinary(Binary* curr) {
FeatureSet features = getModule()->features;
auto* left = curr->left->dynCast<Const>();
auto* right = curr->right->dynCast<Const>();
if (curr->op == AddInt32) {
if (left && left->value.geti32() == 0) {
replaceCurrent(curr->right);
return;
}
if (right && right->value.geti32() == 0) {
replaceCurrent(curr->left);
return;
}
} else if (curr->op == SubInt32) {
// we must leave a left zero, as it is how we negate ints
if (right && right->value.geti32() == 0) {
replaceCurrent(curr->left);
return;
}
} else if (curr->op == ShlInt32) {
// shifting a 0 is a 0, or anything by 0 has no effect, all unless the
// shift has side effects
if (((left && left->value.geti32() == 0) ||
(right && Bits::getEffectiveShifts(right) == 0)) &&
!EffectAnalyzer(passOptions, features, curr->right)
.hasSideEffects()) {
replaceCurrent(curr->left);
return;
}
} else if (curr->op == MulInt32) {
// multiplying by zero is a zero, unless the other side has side
// effects
if (left && left->value.geti32() == 0 &&
!EffectAnalyzer(passOptions, features, curr->right)
.hasSideEffects()) {
replaceCurrent(left);
return;
}
if (right && right->value.geti32() == 0 &&
!EffectAnalyzer(passOptions, features, curr->left)
.hasSideEffects()) {
replaceCurrent(right);
return;
}
}
}
};
Expression* walked = binary;
ZeroRemover remover(getPassOptions());
remover.setModule(getModule());
remover.walk(walked);
if (constant == 0) {
return walked; // nothing more to do
}
if (auto* c = walked->dynCast<Const>()) {
assert(c->value.geti32() == 0);
c->value = Literal(constant);
return c;
}
Builder builder(*getModule());
return builder.makeBinary(
AddInt32, walked, builder.makeConst(Literal(constant)));
}
// expensive1 | expensive2 can be turned into expensive1 ? 1 : expensive2,
// and expensive | cheap can be turned into cheap ? 1 : expensive,
// so that we can avoid one expensive computation, if it has no side effects.
Expression* conditionalizeExpensiveOnBitwise(Binary* binary) {
// this operation can increase code size, so don't always do it
auto& options = getPassRunner()->options;
if (options.optimizeLevel < 2 || options.shrinkLevel > 0) {
return nullptr;
}
const auto MIN_COST = 7;
assert(binary->op == AndInt32 || binary->op == OrInt32);
if (binary->right->is<Const>()) {
return nullptr; // trivial
}
// bitwise logical operator on two non-numerical values, check if they are
// boolean
auto* left = binary->left;
auto* right = binary->right;
if (!Properties::emitsBoolean(left) || !Properties::emitsBoolean(right)) {
return nullptr;
}
auto leftEffects = effects(left);
auto rightEffects = effects(right);
auto leftHasSideEffects = leftEffects.hasSideEffects();
auto rightHasSideEffects = rightEffects.hasSideEffects();
if (leftHasSideEffects && rightHasSideEffects) {
return nullptr; // both must execute
}
// canonicalize with side effects, if any, happening on the left
if (rightHasSideEffects) {
if (CostAnalyzer(left).cost < MIN_COST) {
return nullptr; // avoidable code is too cheap
}
if (leftEffects.invalidates(rightEffects)) {
return nullptr; // cannot reorder
}
std::swap(left, right);
} else if (leftHasSideEffects) {
if (CostAnalyzer(right).cost < MIN_COST) {
return nullptr; // avoidable code is too cheap
}
} else {
// no side effects, reorder based on cost estimation
auto leftCost = CostAnalyzer(left).cost;
auto rightCost = CostAnalyzer(right).cost;
if (std::max(leftCost, rightCost) < MIN_COST) {
return nullptr; // avoidable code is too cheap
}
// canonicalize with expensive code on the right
if (leftCost > rightCost) {
std::swap(left, right);
}
}
// worth it! perform conditionalization
Builder builder(*getModule());
if (binary->op == OrInt32) {
return builder.makeIf(
left, builder.makeConst(Literal(int32_t(1))), right);
} else { // &
return builder.makeIf(
left, right, builder.makeConst(Literal(int32_t(0))));
}
}
// We can combine `or` operations, e.g.
// (x > y) | (x == y) ==> x >= y
Expression* combineOr(Binary* binary) {
assert(binary->op == OrInt32);
if (auto* left = binary->left->dynCast<Binary>()) {
if (auto* right = binary->right->dynCast<Binary>()) {
if (left->op != right->op &&
ExpressionAnalyzer::equal(left->left, right->left) &&
ExpressionAnalyzer::equal(left->right, right->right) &&
!effects(left->left).hasSideEffects() &&
!effects(left->right).hasSideEffects()) {
switch (left->op) {
// (x > y) | (x == y) ==> x >= y
case EqInt32: {
if (right->op == GtSInt32) {
left->op = GeSInt32;
return left;
}
break;
}
default: {
}
}
}
}
}
return nullptr;
}
// fold constant factors into the offset
void optimizeMemoryAccess(Expression*& ptr, Address& offset) {
// ptr may be a const, but it isn't worth folding that in (we still have a
// const); in fact, it's better to do the opposite for gzip purposes as well
// as for readability.
auto* last = ptr->dynCast<Const>();
if (last) {
uint64_t value64 = last->value.getInteger();
uint64_t offset64 = offset;
if (getModule()->memory.is64()) {
last->value = Literal(int64_t(value64 + offset64));
offset = 0;
} else {
// don't do this if it would wrap the pointer
if (value64 <= uint64_t(std::numeric_limits<int32_t>::max()) &&
offset64 <= uint64_t(std::numeric_limits<int32_t>::max()) &&
value64 + offset64 <=
uint64_t(std::numeric_limits<int32_t>::max())) {
last->value = Literal(int32_t(value64 + offset64));
offset = 0;
}
}
}
}
// Optimize a multiply by a power of two on the right, which
// can be a shift.
// This doesn't shrink code size, and VMs likely optimize it anyhow,
// but it's still worth doing since
// * Often shifts are more common than muls.
// * The constant is smaller.
template<typename T> Expression* optimizePowerOf2Mul(Binary* binary, T c) {
static_assert(std::is_same<T, uint32_t>::value ||
std::is_same<T, uint64_t>::value,
"type mismatch");
auto shifts = CountTrailingZeroes<T>(c);
binary->op = std::is_same<T, uint32_t>::value ? ShlInt32 : ShlInt64;
binary->right->cast<Const>()->value = Literal(static_cast<T>(shifts));
return binary;
}
// Optimize an unsigned divide / remainder by a power of two on the right
// This doesn't shrink code size, and VMs likely optimize it anyhow,
// but it's still worth doing since
// * Usually ands are more common than urems.
// * The constant is slightly smaller.
template<typename T> Expression* optimizePowerOf2UDiv(Binary* binary, T c) {
static_assert(std::is_same<T, uint32_t>::value ||
std::is_same<T, uint64_t>::value,
"type mismatch");
auto shifts = CountTrailingZeroes<T>(c);
binary->op = std::is_same<T, uint32_t>::value ? ShrUInt32 : ShrUInt64;
binary->right->cast<Const>()->value = Literal(static_cast<T>(shifts));
return binary;
}
template<typename T> Expression* optimizePowerOf2URem(Binary* binary, T c) {
static_assert(std::is_same<T, uint32_t>::value ||
std::is_same<T, uint64_t>::value,
"type mismatch");
binary->op = std::is_same<T, uint32_t>::value ? AndInt32 : AndInt64;
binary->right->cast<Const>()->value = Literal(c - 1);
return binary;
}
Expression* makeZeroExt(Expression* curr, int32_t bits) {
Builder builder(*getModule());
return builder.makeBinary(
AndInt32, curr, builder.makeConst(Literal(Bits::lowBitMask(bits))));
}
// given an "almost" sign extend - either a proper one, or it
// has too many shifts left - we remove the sign extend. If there are
// too many shifts, we split the shifts first, so this removes the
// two sign extend shifts and adds one (smaller one)
Expression* removeAlmostSignExt(Binary* outer) {
auto* inner = outer->left->cast<Binary>();
auto* outerConst = outer->right->cast<Const>();
auto* innerConst = inner->right->cast<Const>();
auto* value = inner->left;
if (outerConst->value == innerConst->value) {
return value;
}
// add a shift, by reusing the existing node
innerConst->value = innerConst->value.sub(outerConst->value);
return inner;
}
// check if an expression is already sign-extended
bool isSignExted(Expression* curr, Index bits) {
if (Properties::getSignExtValue(curr)) {
return Properties::getSignExtBits(curr) == bits;
}
if (auto* get = curr->dynCast<LocalGet>()) {
// check what we know about the local
return localInfo[get->index].signExtedBits == bits;
}
return false;
}
// optimize trivial math operations, given that the right side of a binary
// is a constant
Expression* optimizeWithConstantOnRight(Binary* curr) {
using namespace Match;
Builder builder(*getModule());
Expression* left;
auto* right = curr->right->cast<Const>();
auto type = curr->right->type;
// Operations on zero
if (matches(curr, binary(Abstract::Shl, any(&left), ival(0))) ||
matches(curr, binary(Abstract::ShrU, any(&left), ival(0))) ||
matches(curr, binary(Abstract::ShrS, any(&left), ival(0))) ||
matches(curr, binary(Abstract::Or, any(&left), ival(0))) ||
matches(curr, binary(Abstract::Xor, any(&left), ival(0)))) {
return left;
}
if (matches(curr, binary(Abstract::Mul, pure(&left), ival(0))) ||
matches(curr, binary(Abstract::And, pure(&left), ival(0)))) {
return right;
}
// x == 0 ==> eqz x
if ((matches(curr, binary(Abstract::Eq, any(&left), ival(0))))) {
return builder.makeUnary(EqZInt64, left);
}
// Operations on one
// (signed)x % 1 ==> 0
if (matches(curr, binary(Abstract::RemS, pure(&left), ival(1)))) {
right->value = Literal::makeSingleZero(type);
return right;
}
// bool(x) | 1 ==> 1
if (matches(curr, binary(Abstract::Or, pure(&left), ival(1))) &&
Bits::getMaxBits(left, this) == 1) {
return right;
}
// bool(x) & 1 ==> bool(x)
if (matches(curr, binary(Abstract::And, any(&left), ival(1))) &&
Bits::getMaxBits(left, this) == 1) {
return left;
}
// bool(x) == 1 ==> bool(x)
if (matches(curr, binary(EqInt32, any(&left), i32(1))) &&
Bits::getMaxBits(left, this) == 1) {
return left;
}
// i64(bool(x)) == 1 ==> i32(bool(x))
if (matches(curr, binary(EqInt64, any(&left), i64(1))) &&
Bits::getMaxBits(left, this) == 1) {
return builder.makeUnary(WrapInt64, left);
}
// bool(x) != 1 ==> !bool(x)
if (matches(curr, binary(Abstract::Ne, any(&left), ival(1))) &&
Bits::getMaxBits(curr->left, this) == 1) {
return builder.makeUnary(Abstract::getUnary(type, Abstract::EqZ), left);
}
// Operations on all 1s
// x & -1 ==> x
if (matches(curr, binary(Abstract::And, any(&left), ival(-1)))) {
return left;
}
// x | -1 ==> -1
if (matches(curr, binary(Abstract::Or, pure(&left), ival(-1)))) {
return right;
}
// (signed)x % -1 ==> 0
if (matches(curr, binary(Abstract::RemS, pure(&left), ival(-1)))) {
right->value = Literal::makeSingleZero(type);
return right;
}
// (unsigned)x > -1 ==> 0
if (matches(curr, binary(Abstract::GtU, pure(&left), ival(-1)))) {
right->value = Literal::makeSingleZero(Type::i32);
right->type = Type::i32;
return right;
}
// (unsigned)x < -1 ==> x != -1
// Friendlier to JS emitting as we don't need to write an unsigned -1 value
// which is large.
if (matches(curr, binary(Abstract::LtU, any(), ival(-1)))) {
curr->op = Abstract::getBinary(type, Abstract::Ne);
return curr;
}
// (unsigned)x / -1 ==> x == -1
// TODO: i64 as well if sign-extension is enabled
if (matches(curr, binary(DivUInt32, any(), ival(-1)))) {
curr->op = Abstract::getBinary(type, Abstract::Eq);
return curr;
}
// x * -1 ==> 0 - x
if (matches(curr, binary(Abstract::Mul, any(&left), ival(-1)))) {
right->value = Literal::makeSingleZero(type);
curr->op = Abstract::getBinary(type, Abstract::Sub);
curr->left = right;
curr->right = left;
return curr;
}
// (unsigned)x <= -1 ==> 1
if (matches(curr, binary(Abstract::LeU, pure(&left), ival(-1)))) {
right->value = Literal::makeFromInt32(1, Type::i32);
right->type = Type::i32;
return right;
}
{
// Wasm binary encoding uses signed LEBs, which slightly favor negative
// numbers: -64 is more efficient than +64 etc., as well as other powers
// of two 7 bits etc. higher. we therefore prefer x - -64 over x + 64. in
// theory we could just prefer negative numbers over positive, but that
// can have bad effects on gzip compression (as it would mean more
// subtractions than the more common additions). TODO: Simplify this by
// adding an ival matcher than can bind int64_t vars.
int64_t value;
if ((matches(curr, binary(Abstract::Add, any(), ival(&value))) ||
matches(curr, binary(Abstract::Sub, any(), ival(&value)))) &&
(value == 0x40 || value == 0x2000 || value == 0x100000 ||
value == 0x8000000 || value == 0x400000000LL ||
value == 0x20000000000LL || value == 0x1000000000000LL ||
value == 0x80000000000000LL || value == 0x4000000000000000LL)) {
right->value = right->value.neg();
if (matches(curr, binary(Abstract::Add, any(), constant()))) {
curr->op = Abstract::getBinary(type, Abstract::Sub);
} else {
curr->op = Abstract::getBinary(type, Abstract::Add);
}
return curr;
}
}
{
double value;
if (matches(curr, binary(Abstract::Sub, any(), fval(&value))) &&
value == 0.0) {
// x - (-0.0) ==> x + 0.0
if (std::signbit(value)) {
curr->op = Abstract::getBinary(type, Abstract::Add);
right->value = right->value.neg();
return curr;
} else {
// x - 0.0 ==> x
return curr->left;
}
}
}
{
// x + (-0.0) ==> x
double value;
if (matches(curr, binary(Abstract::Add, any(), fval(&value))) &&
value == 0.0 && std::signbit(value)) {
return curr->left;
}
}
// Note that this is correct even on floats with a NaN on the left,
// as a NaN would skip the computation and just return the NaN,
// and that is precisely what we do here. but, the same with -1
// (change to a negation) would be incorrect for that reason.
if (matches(curr, binary(Abstract::Mul, any(&left), constant(1))) ||
matches(curr, binary(Abstract::DivS, any(&left), constant(1))) ||
matches(curr, binary(Abstract::DivU, any(&left), constant(1)))) {
return left;
}
return nullptr;
}
// optimize trivial math operations, given that the left side of a binary
// is a constant. since we canonicalize constants to the right for symmetrical
// operations, we only need to handle asymmetrical ones here
// TODO: templatize on type?
Expression* optimizeWithConstantOnLeft(Binary* binary) {
auto type = binary->left->type;
auto* left = binary->left->cast<Const>();
if (type.isInteger()) {
// operations on zero
if (left->value == Literal::makeFromInt32(0, type)) {
if ((binary->op == Abstract::getBinary(type, Abstract::Shl) ||
binary->op == Abstract::getBinary(type, Abstract::ShrU) ||
binary->op == Abstract::getBinary(type, Abstract::ShrS)) &&
!effects(binary->right).hasSideEffects()) {
return binary->left;
}
}
}
return nullptr;
}
// TODO: templatize on type?
Expression* optimizeRelational(Binary* binary) {
// TODO: inequalities can also work, if the constants do not overflow
auto type = binary->right->type;
// integer math, even on 2s complement, allows stuff like
// x + 5 == 7
// =>
// x == 2
if (binary->left->type.isInteger()) {
if (binary->op == Abstract::getBinary(type, Abstract::Eq) ||
binary->op == Abstract::getBinary(type, Abstract::Ne)) {
if (auto* left = binary->left->dynCast<Binary>()) {
if (left->op == Abstract::getBinary(type, Abstract::Add) ||
left->op == Abstract::getBinary(type, Abstract::Sub)) {
if (auto* leftConst = left->right->dynCast<Const>()) {
if (auto* rightConst = binary->right->dynCast<Const>()) {
return combineRelationalConstants(
binary, left, leftConst, nullptr, rightConst);
} else if (auto* rightBinary = binary->right->dynCast<Binary>()) {
if (rightBinary->op ==
Abstract::getBinary(type, Abstract::Add) ||
rightBinary->op ==
Abstract::getBinary(type, Abstract::Sub)) {
if (auto* rightConst = rightBinary->right->dynCast<Const>()) {
return combineRelationalConstants(
binary, left, leftConst, rightBinary, rightConst);
}
}
}
}
}
}
}
}
return nullptr;
}
Expression* deduplicateUnary(Unary* unaryOuter) {
if (auto* unaryInner = unaryOuter->value->dynCast<Unary>()) {
if (unaryInner->op == unaryOuter->op) {
switch (unaryInner->op) {
case NegFloat32:
case NegFloat64: {
// neg(neg(x)) ==> x
return unaryInner->value;
}
case AbsFloat32:
case CeilFloat32:
case FloorFloat32:
case TruncFloat32:
case NearestFloat32:
case AbsFloat64:
case CeilFloat64:
case FloorFloat64:
case TruncFloat64:
case NearestFloat64: {
// unaryOp(unaryOp(x)) ==> unaryOp(x)
return unaryInner;
}
case ExtendS8Int32:
case ExtendS16Int32: {
assert(getModule()->features.hasSignExt());
return unaryInner;
}
case EqZInt32: {
// eqz(eqz(bool(x))) ==> bool(x)
if (Bits::getMaxBits(unaryInner->value, this) == 1) {
return unaryInner->value;
}
break;
}
default: {
}
}
}
}
return nullptr;
}
Expression* deduplicateBinary(Binary* outer) {
Type type = outer->type;
if (type.isInteger()) {
if (auto* inner = outer->right->dynCast<Binary>()) {
if (outer->op == inner->op) {
if (!EffectAnalyzer(
getPassOptions(), getModule()->features, outer->left)
.hasSideEffects()) {
if (ExpressionAnalyzer::equal(inner->left, outer->left)) {
// x - (x - y) ==> y
// x ^ (x ^ y) ==> y
if (outer->op == Abstract::getBinary(type, Abstract::Sub) ||
outer->op == Abstract::getBinary(type, Abstract::Xor)) {
return inner->right;
}
// x & (x & y) ==> x & y
// x | (x | y) ==> x | y
if (outer->op == Abstract::getBinary(type, Abstract::And) ||
outer->op == Abstract::getBinary(type, Abstract::Or)) {
return inner;
}
}
if (ExpressionAnalyzer::equal(inner->right, outer->left)) {
// x ^ (y ^ x) ==> y
if (outer->op == Abstract::getBinary(type, Abstract::Xor)) {
return inner->left;
}
// x & (y & x) ==> y & x
// x | (y | x) ==> y | x
if (outer->op == Abstract::getBinary(type, Abstract::And) ||
outer->op == Abstract::getBinary(type, Abstract::Or)) {
return inner;
}
}
}
}
}
if (auto* inner = outer->left->dynCast<Binary>()) {
if (outer->op == inner->op) {
if (!EffectAnalyzer(
getPassOptions(), getModule()->features, outer->right)
.hasSideEffects()) {
if (ExpressionAnalyzer::equal(inner->right, outer->right)) {
// (x ^ y) ^ y ==> x
if (outer->op == Abstract::getBinary(type, Abstract::Xor)) {
return inner->left;
}
// (x % y) % y ==> x % y
// (x & y) & y ==> x & y
// (x | y) | y ==> x | y
if (outer->op == Abstract::getBinary(type, Abstract::RemS) ||
outer->op == Abstract::getBinary(type, Abstract::RemU) ||
outer->op == Abstract::getBinary(type, Abstract::And) ||
outer->op == Abstract::getBinary(type, Abstract::Or)) {
return inner;
}
}
if (ExpressionAnalyzer::equal(inner->left, outer->right)) {
// (x ^ y) ^ x ==> y
if (outer->op == Abstract::getBinary(type, Abstract::Xor)) {
return inner->right;
}
// (x & y) & x ==> x & y
// (x | y) | x ==> x | y
if (outer->op == Abstract::getBinary(type, Abstract::And) ||
outer->op == Abstract::getBinary(type, Abstract::Or)) {
return inner;
}
}
}
}
}
}
return nullptr;
}
// given a relational binary with a const on both sides, combine the constants
// left is also a binary, and has a constant; right may be just a constant, in
// which case right is nullptr
Expression* combineRelationalConstants(Binary* binary,
Binary* left,
Const* leftConst,
Binary* right,
Const* rightConst) {
auto type = binary->right->type;
// we fold constants to the right
Literal extra = leftConst->value;
if (left->op == Abstract::getBinary(type, Abstract::Sub)) {
extra = extra.neg();
}
if (right && right->op == Abstract::getBinary(type, Abstract::Sub)) {
extra = extra.neg();
}
rightConst->value = rightConst->value.sub(extra);
binary->left = left->left;
return binary;
}
Expression* optimizeMemoryCopy(MemoryCopy* memCopy) {
PassOptions options = getPassOptions();
if (options.ignoreImplicitTraps) {
if (ExpressionAnalyzer::equal(memCopy->dest, memCopy->source)) {
// memory.copy(x, x, sz) ==> {drop(x), drop(x), drop(sz)}
Builder builder(*getModule());
return builder.makeBlock({builder.makeDrop(memCopy->dest),
builder.makeDrop(memCopy->source),
builder.makeDrop(memCopy->size)});
}
}
// memory.copy(dst, src, C) ==> store(dst, load(src))
if (auto* csize = memCopy->size->dynCast<Const>()) {
auto bytes = csize->value.geti32();
Builder builder(*getModule());
switch (bytes) {
case 0: {
if (options.ignoreImplicitTraps) {
// memory.copy(dst, src, 0) ==> {drop(dst), drop(src)}
return builder.makeBlock({builder.makeDrop(memCopy->dest),
builder.makeDrop(memCopy->source)});
}
break;
}
case 1:
case 2:
case 4: {
return builder.makeStore(
bytes, // bytes
0, // offset
1, // align
memCopy->dest,
builder.makeLoad(bytes, false, 0, 1, memCopy->source, Type::i32),
Type::i32);
}
case 8: {
return builder.makeStore(
bytes, // bytes
0, // offset
1, // align
memCopy->dest,
builder.makeLoad(bytes, false, 0, 1, memCopy->source, Type::i64),
Type::i64);
}
case 16: {
if (options.shrinkLevel == 0) {
// This adds an extra 2 bytes so apply it only for
// minimal shrink level
if (getModule()->features.hasSIMD()) {
return builder.makeStore(
bytes, // bytes
0, // offset
1, // align
memCopy->dest,
builder.makeLoad(
bytes, false, 0, 1, memCopy->source, Type::v128),
Type::v128);
}
}
}
default: {
}
}
}
return nullptr;
}
// given a binary expression with equal children and no side effects in
// either, we can fold various things
Expression* optimizeBinaryWithEqualEffectlessChildren(Binary* binary) {
// TODO add: perhaps worth doing 2*x if x is quite large?
switch (binary->op) {
case SubInt32:
case XorInt32:
case SubInt64:
case XorInt64:
return LiteralUtils::makeZero(binary->left->type, *getModule());
case NeInt32:
case LtSInt32:
case LtUInt32:
case GtSInt32:
case GtUInt32:
case NeInt64:
case LtSInt64:
case LtUInt64:
case GtSInt64:
case GtUInt64:
return LiteralUtils::makeZero(Type::i32, *getModule());
case AndInt32:
case OrInt32:
case AndInt64:
case OrInt64:
return binary->left;
case EqInt32:
case LeSInt32:
case LeUInt32:
case GeSInt32:
case GeUInt32:
case EqInt64:
case LeSInt64:
case LeUInt64:
case GeSInt64:
case GeUInt64:
return LiteralUtils::makeFromInt32(1, Type::i32, *getModule());
default:
return nullptr;
}
}
BinaryOp invertBinaryOp(BinaryOp op) {
// use de-morgan's laws
switch (op) {
case EqInt32:
return NeInt32;
case NeInt32:
return EqInt32;
case LtSInt32:
return GeSInt32;
case LtUInt32:
return GeUInt32;
case LeSInt32:
return GtSInt32;
case LeUInt32:
return GtUInt32;
case GtSInt32:
return LeSInt32;
case GtUInt32:
return LeUInt32;
case GeSInt32:
return LtSInt32;
case GeUInt32:
return LtUInt32;
case EqInt64:
return NeInt64;
case NeInt64:
return EqInt64;
case LtSInt64:
return GeSInt64;
case LtUInt64:
return GeUInt64;
case LeSInt64:
return GtSInt64;
case LeUInt64:
return GtUInt64;
case GtSInt64:
return LeSInt64;
case GtUInt64:
return LeUInt64;
case GeSInt64:
return LtSInt64;
case GeUInt64:
return LtUInt64;
case EqFloat32:
return NeFloat32;
case NeFloat32:
return EqFloat32;
case EqFloat64:
return NeFloat64;
case NeFloat64:
return EqFloat64;
default:
return InvalidBinary;
}
}
bool isSymmetric(Binary* binary) {
if (Properties::isSymmetric(binary)) {
return true;
}
switch (binary->op) {
case AddFloat32:
case MulFloat32:
case AddFloat64:
case MulFloat64: {
// If the LHS is known to be non-NaN, the operands can commute.
// We don't care about the RHS because right now we only know if
// an expression is non-NaN if it is constant, but if the RHS is
// constant, then this expression is already canonicalized.
if (auto* c = binary->left->dynCast<Const>()) {
return !c->value.isNaN();
}
return false;
}
default:
return false;
}
}
};
Pass* createOptimizeInstructionsPass() { return new OptimizeInstructions(); }
} // namespace wasm
| {
"pile_set_name": "Github"
} |
"""
This script handles the skimage exif problem.
"""
from PIL import Image
import numpy as np
ORIENTATIONS = { # used in apply_orientation
2: (Image.FLIP_LEFT_RIGHT,),
3: (Image.ROTATE_180,),
4: (Image.FLIP_TOP_BOTTOM,),
5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90),
6: (Image.ROTATE_270,),
7: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_270),
8: (Image.ROTATE_90,)
}
def open_oriented_im(im_path):
im = Image.open(im_path)
if hasattr(im, '_getexif'):
exif = im._getexif()
if exif is not None and 274 in exif:
orientation = exif[274]
im = apply_orientation(im, orientation)
img = np.asarray(im).astype(np.float32) / 255.
if img.ndim == 2:
img = img[:, :, np.newaxis]
img = np.tile(img, (1, 1, 3))
elif img.shape[2] == 4:
img = img[:, :, :3]
return img
def apply_orientation(im, orientation):
if orientation in ORIENTATIONS:
for method in ORIENTATIONS[orientation]:
im = im.transpose(method)
return im
| {
"pile_set_name": "Github"
} |
package typings.dojo.dojox.mvc.Bind
import typings.dojo.dijit.WidgetBase
import typings.dojo.dojoStrings.style
import typings.std.HTMLElement
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation._
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mvc/Bind.Element.html
*
* A widget implicitly created by dojox/mvc/parserExtension.
* Maps "value" attribute to form element value, innerText/innerHTML to element's innerText/innerHTML, and other attributes to DOM attributes.
* Also, for form element, updates value (or checked for check box) as user edits.
*
* @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties.
* @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree
*/
@JSGlobal("dojox.mvc.Bind.Element")
@js.native
class Element () extends WidgetBase {
def this(params: js.Object) = this()
def this(params: js.Object, srcNodeRef: HTMLElement) = this()
/**
* HTML style attributes as cssText string or name/value hash
*
*/
@JSName("style")
var style_Element: String = js.native
/**
* Track specified handles and remove/destroy them when this instance is destroyed, unless they were
* already removed/destroyed manually.
*
*/
def own(): js.Any = js.native
@JSName("set")
def set_style(property: style, value: String): Unit = js.native
}
| {
"pile_set_name": "Github"
} |
//
// CueSheetDecoder.h
// CueSheet
//
// Created by Zaphod Beeblebrox on 10/8/07.
// Copyright 2007 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "Plugin.h"
@class CueSheet;
@class CueSheetTrack;
@interface CueSheetDecoder : NSObject <CogDecoder> {
id<CogSource> source;
id<CogDecoder> decoder;
int bytesPerFrame; //Number of bytes per frame, ie channels * (bitsPerSample/8)
long framePosition; //Current position in frames.
long trackStart; //Starting frame of track.
long trackEnd; //Frames until end of track.
CueSheet *cuesheet;
CueSheetTrack *track;
}
@end
| {
"pile_set_name": "Github"
} |
package toml
import "strings"
// MetaData allows access to meta information about TOML data that may not
// be inferrable via reflection. In particular, whether a key has been defined
// and the TOML type of a key.
type MetaData struct {
mapping map[string]interface{}
types map[string]tomlType
keys []Key
decoded map[string]bool
context Key // Used only during decoding.
}
// IsDefined returns true if the key given exists in the TOML data. The key
// should be specified hierarchially. e.g.,
//
// // access the TOML key 'a.b.c'
// IsDefined("a", "b", "c")
//
// IsDefined will return false if an empty key given. Keys are case sensitive.
func (md *MetaData) IsDefined(key ...string) bool {
if len(key) == 0 {
return false
}
var hash map[string]interface{}
var ok bool
var hashOrVal interface{} = md.mapping
for _, k := range key {
if hash, ok = hashOrVal.(map[string]interface{}); !ok {
return false
}
if hashOrVal, ok = hash[k]; !ok {
return false
}
}
return true
}
// Type returns a string representation of the type of the key specified.
//
// Type will return the empty string if given an empty key or a key that
// does not exist. Keys are case sensitive.
func (md *MetaData) Type(key ...string) string {
fullkey := strings.Join(key, ".")
if typ, ok := md.types[fullkey]; ok {
return typ.typeString()
}
return ""
}
// Key is the type of any TOML key, including key groups. Use (MetaData).Keys
// to get values of this type.
type Key []string
func (k Key) String() string {
return strings.Join(k, ".")
}
func (k Key) maybeQuotedAll() string {
var ss []string
for i := range k {
ss = append(ss, k.maybeQuoted(i))
}
return strings.Join(ss, ".")
}
func (k Key) maybeQuoted(i int) string {
quote := false
for _, c := range k[i] {
if !isBareKeyChar(c) {
quote = true
break
}
}
if quote {
return "\"" + strings.Replace(k[i], "\"", "\\\"", -1) + "\""
}
return k[i]
}
func (k Key) add(piece string) Key {
newKey := make(Key, len(k)+1)
copy(newKey, k)
newKey[len(k)] = piece
return newKey
}
// Keys returns a slice of every key in the TOML data, including key groups.
// Each key is itself a slice, where the first element is the top of the
// hierarchy and the last is the most specific.
//
// The list will have the same order as the keys appeared in the TOML data.
//
// All keys returned are non-empty.
func (md *MetaData) Keys() []Key {
return md.keys
}
// Undecoded returns all keys that have not been decoded in the order in which
// they appear in the original TOML document.
//
// This includes keys that haven't been decoded because of a Primitive value.
// Once the Primitive value is decoded, the keys will be considered decoded.
//
// Also note that decoding into an empty interface will result in no decoding,
// and so no keys will be considered decoded.
//
// In this sense, the Undecoded keys correspond to keys in the TOML document
// that do not have a concrete type in your representation.
func (md *MetaData) Undecoded() []Key {
undecoded := make([]Key, 0, len(md.keys))
for _, key := range md.keys {
if !md.decoded[key.String()] {
undecoded = append(undecoded, key)
}
}
return undecoded
}
| {
"pile_set_name": "Github"
} |
/* This is a compiled file, you should be editing the file in the templates directory */
.pace {
-webkit-pointer-events: none;
pointer-events: none;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
-webkit-perspective: 12rem;
-moz-perspective: 12rem;
-ms-perspective: 12rem;
-o-perspective: 12rem;
perspective: 12rem;
z-index: 2000;
position: fixed;
height: 6rem;
width: 6rem;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.pace.pace-inactive .pace-progress {
display: none;
}
.pace .pace-progress {
position: fixed;
z-index: 2000;
display: block;
position: absolute;
left: 0;
top: 0;
height: 6rem;
width: 6rem !important;
line-height: 6rem;
font-size: 2rem;
border-radius: 50%;
background: rgba(34, 153, 221, 0.8);
color: #fff;
font-family: "Helvetica Neue", sans-serif;
font-weight: 100;
text-align: center;
-webkit-animation: pace-3d-spinner linear infinite 2s;
-moz-animation: pace-3d-spinner linear infinite 2s;
-ms-animation: pace-3d-spinner linear infinite 2s;
-o-animation: pace-3d-spinner linear infinite 2s;
animation: pace-3d-spinner linear infinite 2s;
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
-ms-transform-style: preserve-3d;
-o-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.pace .pace-progress:after {
content: attr(data-progress-text);
display: block;
}
@-webkit-keyframes pace-3d-spinner {
from {
-webkit-transform: rotateY(0deg);
}
to {
-webkit-transform: rotateY(360deg);
}
}
@-moz-keyframes pace-3d-spinner {
from {
-moz-transform: rotateY(0deg);
}
to {
-moz-transform: rotateY(360deg);
}
}
@-ms-keyframes pace-3d-spinner {
from {
-ms-transform: rotateY(0deg);
}
to {
-ms-transform: rotateY(360deg);
}
}
@-o-keyframes pace-3d-spinner {
from {
-o-transform: rotateY(0deg);
}
to {
-o-transform: rotateY(360deg);
}
}
@keyframes pace-3d-spinner {
from {
transform: rotateY(0deg);
}
to {
transform: rotateY(360deg);
}
}
| {
"pile_set_name": "Github"
} |
{
"@context": {
"name": "http://xmlns.com/foaf/0.1/name",
"isKnownBy": { "@reverse": "http://xmlns.com/foaf/0.1/knows", "@type": "@id" }
},
"@id": "http://example.com/people/markus",
"name": "Markus Lanthaler",
"isKnownBy": [
"http://example.com/people/dave",
"http://example.com/people/gregg"
]
}
| {
"pile_set_name": "Github"
} |
#!/bin/bash
set -eu
if [ ! -d doc/build ]; then
echo 'Error: invalid directory. Deploy from repo root.'
exit 1
fi
[ "$GH_PASSWORD" ] || exit 12
sitemap() {
WEBSITE='https://pdpipe.github.io/pdpipe'
find . -name '*.html' |
sed "s,^\.,$WEBSITE," |
sed 's/index.html$//' |
grep -v '/google.*\.html$' |
sort -u > 'sitemap.txt'
echo "Sitemap: $WEBSITE/sitemap.txt" > 'robots.txt'
}
head=$(git rev-parse HEAD)
git clone -b gh-pages "https://shaypal5:[email protected]/$TRAVIS_REPO_SLUG.git" gh-pages
mkdir -p gh-pages/doc
cp -R doc/build/* gh-pages/doc/
cd gh-pages
sitemap
git add *
git diff --staged --quiet && echo "$0: No changes to commit." && exit 0
git commit -a -m "CI: Update docs for $TRAVIS_TAG ($head)"
git push
| {
"pile_set_name": "Github"
} |
// directory_management.hpp --------------------------------------------------------------//
// Copyright 2010 Vicente J. Botet Escriba
// Copyright 2015 Andrey Semashev
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
#ifndef BOOST_DETAIL_WINAPI_DIRECTORY_MANAGEMENT_HPP
#define BOOST_DETAIL_WINAPI_DIRECTORY_MANAGEMENT_HPP
#include <boost/detail/winapi/basic_types.hpp>
#include <boost/detail/winapi/get_system_directory.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#if !defined( BOOST_USE_WINDOWS_H )
extern "C" {
#if !defined( BOOST_NO_ANSI_APIS )
BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
CreateDirectoryA(boost::detail::winapi::LPCSTR_, ::_SECURITY_ATTRIBUTES*);
BOOST_SYMBOL_IMPORT boost::detail::winapi::DWORD_ WINAPI
GetTempPathA(boost::detail::winapi::DWORD_ length, boost::detail::winapi::LPSTR_ buffer);
BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
RemoveDirectoryA(boost::detail::winapi::LPCSTR_);
#endif
BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
CreateDirectoryW(boost::detail::winapi::LPCWSTR_, ::_SECURITY_ATTRIBUTES*);
BOOST_SYMBOL_IMPORT boost::detail::winapi::DWORD_ WINAPI
GetTempPathW(boost::detail::winapi::DWORD_ length, boost::detail::winapi::LPWSTR_ buffer);
BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
RemoveDirectoryW(boost::detail::winapi::LPCWSTR_);
}
#endif
namespace boost {
namespace detail {
namespace winapi {
#if !defined( BOOST_NO_ANSI_APIS )
using ::GetTempPathA;
using ::RemoveDirectoryA;
#endif
using ::GetTempPathW;
using ::RemoveDirectoryW;
#if !defined( BOOST_NO_ANSI_APIS )
BOOST_FORCEINLINE BOOL_ CreateDirectoryA(LPCSTR_ pPathName, PSECURITY_ATTRIBUTES_ pSecurityAttributes)
{
return ::CreateDirectoryA(pPathName, reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(pSecurityAttributes));
}
#endif
BOOST_FORCEINLINE BOOL_ CreateDirectoryW(LPCWSTR_ pPathName, PSECURITY_ATTRIBUTES_ pSecurityAttributes)
{
return ::CreateDirectoryW(pPathName, reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(pSecurityAttributes));
}
#if !defined( BOOST_NO_ANSI_APIS )
BOOST_FORCEINLINE BOOL_ create_directory(LPCSTR_ pPathName, PSECURITY_ATTRIBUTES_ pSecurityAttributes)
{
return ::CreateDirectoryA(pPathName, reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(pSecurityAttributes));
}
BOOST_FORCEINLINE DWORD_ get_temp_path(DWORD_ length, LPSTR_ buffer)
{
return ::GetTempPathA(length, buffer);
}
BOOST_FORCEINLINE BOOL_ remove_directory(LPCSTR_ pPathName)
{
return ::RemoveDirectoryA(pPathName);
}
#endif
BOOST_FORCEINLINE BOOL_ create_directory(LPCWSTR_ pPathName, PSECURITY_ATTRIBUTES_ pSecurityAttributes)
{
return ::CreateDirectoryW(pPathName, reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(pSecurityAttributes));
}
BOOST_FORCEINLINE DWORD_ get_temp_path(DWORD_ length, LPWSTR_ buffer)
{
return ::GetTempPathW(length, buffer);
}
BOOST_FORCEINLINE BOOL_ remove_directory(LPCWSTR_ pPathName)
{
return ::RemoveDirectoryW(pPathName);
}
} // namespace winapi
} // namespace detail
} // namespace boost
#endif // BOOST_DETAIL_WINAPI_DIRECTORY_MANAGEMENT_HPP
| {
"pile_set_name": "Github"
} |
//
// MPDiskLRUCache.m
//
// Copyright (c) 2014 MoPub. All rights reserved.
//
#import "MPDiskLRUCache.h"
#import "MPGlobal.h"
#import "MPLogging.h"
#import <CommonCrypto/CommonDigest.h>
// cached files that have not been access since kCacheFileMaxAge ago will be evicted
#define kCacheFileMaxAge (7 * 24 * 60 * 60) // 1 week
// once the cache hits this size AND we've added at least kCacheBytesStoredBeforeSizeCheck bytes,
// cached files will be evicted (LRU) until the total size drops below this limit
#define kCacheSoftMaxSize (100 * 1024 * 1024) // 100 MB
#define kCacheBytesStoredBeforeSizeCheck (kCacheSoftMaxSize / 10) // 10% of kCacheSoftMaxSize
@interface MPDiskLRUCacheFile : NSObject
@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, assign) NSTimeInterval lastModTimestamp;
@property (nonatomic, assign) uint64_t fileSize;
@end
@implementation MPDiskLRUCacheFile
@end
@interface MPDiskLRUCache ()
#if !OS_OBJECT_USE_OBJC
@property (nonatomic, assign) dispatch_queue_t diskIOQueue;
#else
@property (nonatomic, strong) dispatch_queue_t diskIOQueue;
#endif
@property (nonatomic, copy) NSString *diskCachePath;
@property (atomic, assign) uint64_t numBytesStoredForSizeCheck;
@end
@implementation MPDiskLRUCache
+ (MPDiskLRUCache *)sharedDiskCache
{
static dispatch_once_t once;
static MPDiskLRUCache *sharedDiskCache;
dispatch_once(&once, ^{
sharedDiskCache = [self new];
});
return sharedDiskCache;
}
- (id)init
{
self = [super init];
if (self != nil) {
_diskIOQueue = dispatch_queue_create("com.mopub.diskCacheIOQueue", DISPATCH_QUEUE_SERIAL);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
if (paths.count > 0) {
_diskCachePath = [[[paths objectAtIndex:0] stringByAppendingPathComponent:@"com.mopub.diskCache"] copy];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:_diskCachePath]) {
[fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:nil];
}
}
// check cache size on startup
[self ensureCacheSizeLimit];
}
return self;
}
- (void)dealloc
{
#if !OS_OBJECT_USE_OBJC
dispatch_release(_diskIOQueue);
#endif
}
#pragma mark Public
- (void)removeAllCachedFiles
{
dispatch_sync(self.diskIOQueue, ^{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *allFiles = [self cacheFilesSortedByModDate];
for (MPDiskLRUCacheFile *file in allFiles) {
[fileManager removeItemAtPath:file.filePath error:nil];
}
});
}
- (BOOL)cachedDataExistsForKey:(NSString *)key
{
__block BOOL result = NO;
dispatch_sync(self.diskIOQueue, ^{
NSFileManager *fileManager = [NSFileManager defaultManager];
result = [fileManager fileExistsAtPath:[self cacheFilePathForKey:key]];
});
return result;
}
- (NSData *)retrieveDataForKey:(NSString *)key
{
__block NSData *data = nil;
dispatch_sync(self.diskIOQueue, ^{
NSString *cachedFilePath = [self cacheFilePathForKey:key];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = NO;
if ([fileManager fileExistsAtPath:cachedFilePath isDirectory:&isDirectory]) {
data = [NSData dataWithContentsOfFile:cachedFilePath];
// "touch" file to mark access since NSFileManager doesn't return a last accessed date
[fileManager setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] ofItemAtPath:cachedFilePath error:nil];
}
});
return data;
}
- (void)storeData:(NSData *)data forKey:(NSString *)key
{
dispatch_sync(self.diskIOQueue, ^{
NSString *cacheFilePath = [self cacheFilePathForKey:key];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:cacheFilePath]) {
[fileManager createFileAtPath:cacheFilePath contents:data attributes:nil];
} else {
// overwrite existing file
[data writeToFile:cacheFilePath atomically:YES];
}
});
self.numBytesStoredForSizeCheck += data.length;
if (self.numBytesStoredForSizeCheck >= kCacheBytesStoredBeforeSizeCheck) {
[self ensureCacheSizeLimit];
self.numBytesStoredForSizeCheck = 0;
}
}
#pragma mark Private
- (void)ensureCacheSizeLimit
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
MPLogDebug(@"Checking cache size...");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableArray *cacheFilesSortedByModDate = [self cacheFilesSortedByModDate];
dispatch_async(self.diskIOQueue, ^{
@autoreleasepool {
// verify age
NSArray *expiredFiles = [self expiredCachedFilesInArray:cacheFilesSortedByModDate];
for (MPDiskLRUCacheFile *file in expiredFiles) {
MPLogDebug(@"Trying to remove %@ from cache due to expiration", file.filePath);
[fileManager removeItemAtPath:file.filePath error:nil];
[cacheFilesSortedByModDate removeObject:file];
}
// verify size
while ([self sizeOfCacheFilesInArray:cacheFilesSortedByModDate] >= kCacheSoftMaxSize && cacheFilesSortedByModDate.count > 0) {
NSString *oldestFilePath = ((MPDiskLRUCacheFile *)[cacheFilesSortedByModDate objectAtIndex:0]).filePath;
MPLogDebug(@"Trying to remove %@ from cache due to size", oldestFilePath);
[fileManager removeItemAtPath:oldestFilePath error:nil];
[cacheFilesSortedByModDate removeObjectAtIndex:0];
}
}
});
});
}
- (NSArray *)expiredCachedFilesInArray:(NSArray *)cachedFiles
{
NSMutableArray *result = [NSMutableArray array];
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
for (MPDiskLRUCacheFile *file in cachedFiles) {
if (now - file.lastModTimestamp >= kCacheFileMaxAge) {
[result addObject:file];
}
}
return result;
}
- (NSMutableArray *)cacheFilesSortedByModDate
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *cachedFiles = [fileManager contentsOfDirectoryAtPath:self.diskCachePath error:nil];
NSArray *sortedFiles = [cachedFiles sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSString *fileName1 = [self.diskCachePath stringByAppendingPathComponent:(NSString *)obj1];
NSString *fileName2 = [self.diskCachePath stringByAppendingPathComponent:(NSString *)obj2];
NSDictionary *fileAttrs1 = [fileManager attributesOfItemAtPath:fileName1 error:nil];
NSDictionary *fileAttrs2 = [fileManager attributesOfItemAtPath:fileName2 error:nil];
NSDate *lastModDate1 = [fileAttrs1 fileModificationDate];
NSDate *lastModDate2 = [fileAttrs2 fileModificationDate];
return [lastModDate1 compare:lastModDate2];
}];
NSMutableArray *result = [NSMutableArray array];
for (NSString *fileName in sortedFiles) {
if ([fileName hasPrefix:@"."]) {
continue;
}
MPDiskLRUCacheFile *cacheFile = [[MPDiskLRUCacheFile alloc] init];
cacheFile.filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
NSDictionary *fileAttrs = [fileManager attributesOfItemAtPath:cacheFile.filePath error:nil];
cacheFile.fileSize = [fileAttrs fileSize];
cacheFile.lastModTimestamp = [[fileAttrs fileModificationDate] timeIntervalSinceReferenceDate];
[result addObject:cacheFile];
}
return result;
}
- (uint64_t)sizeOfCacheFilesInArray:(NSArray *)files
{
uint64_t currentSize = 0;
for (MPDiskLRUCacheFile *file in files) {
currentSize += file.fileSize;
}
MPLogDebug(@"Current cache size %qu bytes", currentSize);
return currentSize;
}
- (NSString *)cacheFilePathForKey:(NSString *)key
{
NSString *hashedKey = MPSHA1Digest(key);
NSString *cachedFilePath = [self.diskCachePath stringByAppendingPathComponent:hashedKey];
return cachedFilePath;
}
@end
| {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_PlusDomains_ActivityObjectStatusForViewer extends Google_Model
{
public $canComment;
public $canPlusone;
public $canUpdate;
public $isPlusOned;
public $resharingDisabled;
public function setCanComment($canComment)
{
$this->canComment = $canComment;
}
public function getCanComment()
{
return $this->canComment;
}
public function setCanPlusone($canPlusone)
{
$this->canPlusone = $canPlusone;
}
public function getCanPlusone()
{
return $this->canPlusone;
}
public function setCanUpdate($canUpdate)
{
$this->canUpdate = $canUpdate;
}
public function getCanUpdate()
{
return $this->canUpdate;
}
public function setIsPlusOned($isPlusOned)
{
$this->isPlusOned = $isPlusOned;
}
public function getIsPlusOned()
{
return $this->isPlusOned;
}
public function setResharingDisabled($resharingDisabled)
{
$this->resharingDisabled = $resharingDisabled;
}
public function getResharingDisabled()
{
return $this->resharingDisabled;
}
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/elasticloadbalancing/model/DescribeLoadBalancerAttributesResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::ElasticLoadBalancing::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
DescribeLoadBalancerAttributesResult::DescribeLoadBalancerAttributesResult()
{
}
DescribeLoadBalancerAttributesResult::DescribeLoadBalancerAttributesResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
DescribeLoadBalancerAttributesResult& DescribeLoadBalancerAttributesResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (!rootNode.IsNull() && (rootNode.GetName() != "DescribeLoadBalancerAttributesResult"))
{
resultNode = rootNode.FirstChild("DescribeLoadBalancerAttributesResult");
}
if(!resultNode.IsNull())
{
XmlNode loadBalancerAttributesNode = resultNode.FirstChild("LoadBalancerAttributes");
if(!loadBalancerAttributesNode.IsNull())
{
m_loadBalancerAttributes = loadBalancerAttributesNode;
}
}
if (!rootNode.IsNull()) {
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::ElasticLoadBalancing::Model::DescribeLoadBalancerAttributesResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
}
return *this;
}
| {
"pile_set_name": "Github"
} |
define( [
"./class2type"
], function( class2type ) {
return class2type.toString;
} );
| {
"pile_set_name": "Github"
} |
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const CharacterCount = require('../../../src/js/components/character-count');
const INVALID_TEMPLATE_NO_WRAPPER = fs.readFileSync(path.join(__dirname, '/invalid-template-no-wrapper.template.html'));
describe('character count input without wrapping element', () => {
const { body } = document;
afterEach(() => {
body.textContent = '';
CharacterCount.off(body);
});
it('should throw an error when a character count component is created with no wrapping class', () => {
body.innerHTML = INVALID_TEMPLATE_NO_WRAPPER;
assert.throws(() => CharacterCount.on(), {
message: '.usa-character-count__field is missing outer .usa-character-count',
});
});
});
| {
"pile_set_name": "Github"
} |
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { Subscription } from 'rxjs';
import { JssContextService } from '../../jss-context.service';
import { Field, ComponentRendering } from '@sitecore-jss/sitecore-jss-angular';
@Component({
selector: 'app-styleguide-custom-route-type',
templateUrl: './styleguide-custom-route-type.component.html',
})
export class StyleguideCustomRouteTypeComponent implements OnInit, OnDestroy {
@Input() rendering: ComponentRendering;
contextFields: { [name: string]: Field };
private contextSubscription: Subscription;
constructor(private jssContext: JssContextService) { }
ngOnInit() {
this.contextSubscription = this.jssContext.state.subscribe((state) => {
this.contextFields = state.sitecore.route.fields;
});
}
ngOnDestroy() {
if (this.contextSubscription) {
this.contextSubscription.unsubscribe();
}
}
}
| {
"pile_set_name": "Github"
} |
::
ZIP: 306
Title: Security Considerations for Anchor Selection
Owners: Daira Hopwood <[email protected]>
Status: Reserved
Category: Informational
Discussions-To: <https://github.com/zcash/zips/issues/351>
| {
"pile_set_name": "Github"
} |
package com.nike.riposte.metrics.codahale;
import com.nike.internal.util.StringUtils;
import com.nike.riposte.metrics.MetricsListener;
import com.nike.riposte.metrics.codahale.impl.EndpointMetricsHandlerDefaultImpl;
import com.nike.riposte.server.config.ServerConfig;
import com.nike.riposte.server.http.Endpoint;
import com.nike.riposte.server.http.HttpProcessingState;
import com.nike.riposte.server.http.RequestInfo;
import com.nike.riposte.server.http.ResponseInfo;
import com.nike.riposte.server.http.ResponseSender;
import com.nike.riposte.server.metrics.ServerMetricsEvent;
import com.codahale.metrics.Counter;
import com.codahale.metrics.ExponentiallyDecayingReservoir;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Reservoir;
import com.codahale.metrics.SlidingTimeWindowArrayReservoir;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static com.codahale.metrics.MetricRegistry.name;
import static com.nike.riposte.metrics.codahale.CodahaleMetricsListener.ServerConfigMetricNames.BOSS_THREADS;
import static com.nike.riposte.metrics.codahale.CodahaleMetricsListener.ServerConfigMetricNames.ENDPOINTS;
import static com.nike.riposte.metrics.codahale.CodahaleMetricsListener.ServerConfigMetricNames.MAX_REQUEST_SIZE_IN_BYTES;
import static com.nike.riposte.metrics.codahale.CodahaleMetricsListener.ServerConfigMetricNames.WORKER_THREADS;
import static com.nike.riposte.metrics.codahale.CodahaleMetricsListener.ServerStatisticsMetricNames.FAILED_REQUESTS;
import static com.nike.riposte.metrics.codahale.CodahaleMetricsListener.ServerStatisticsMetricNames.INFLIGHT_REQUESTS;
import static com.nike.riposte.metrics.codahale.CodahaleMetricsListener.ServerStatisticsMetricNames.PROCESSED_REQUESTS;
import static com.nike.riposte.metrics.codahale.CodahaleMetricsListener.ServerStatisticsMetricNames.REQUEST_SIZES;
import static com.nike.riposte.metrics.codahale.CodahaleMetricsListener.ServerStatisticsMetricNames.RESPONSE_SIZES;
import static com.nike.riposte.metrics.codahale.CodahaleMetricsListener.ServerStatisticsMetricNames.RESPONSE_WRITE_FAILED;
/**
* Codahale-based {@link MetricsListener}. <b>Two things must occur during app startup for this class to be fully
* functional:</b>
*
* <pre>
* <ul>
* <li>
* You must expose the singleton instance of this class for your app via
* {@link ServerConfig#metricsListener()}. If you fail to do this then no metrics will ever be updated.
* </li>
* <li>
* {@link #initEndpointAndServerConfigMetrics(ServerConfig)} must be called independently at some point during
* app startup once you have a handle on the finalized {@link ServerConfig} that has all its values set and
* exposes all its endpoints via {@link ServerConfig#appEndpoints()}. If you fail to do this then you will not
* receive any server config or per-endpoint metrics.
* </li>
* </ul>
* </pre>
*
* It's recommended that you use the {@link Builder} for creating an instance of this class which will let you adjust
* any behavior options.
*/
@SuppressWarnings("WeakerAccess")
public class CodahaleMetricsListener implements MetricsListener {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
protected final CodahaleMetricsCollector metricsCollector;
// Aggregate metrics around "server statistics" (requests and data that the server is handling) - not related to
// specific endpoints. These are generic enough that we can handle them here in this class and don't need to
// farm them out to something separate like EndpointMetricsHandler.
protected Counter inflightRequests;
protected Counter processedRequests;
protected Counter failedRequests;
protected Counter responseWriteFailed;
protected Histogram responseSizes;
protected Histogram requestSizes;
// Endpoint related metrics are handled by a EndpointMetricsHandler impl.
protected final EndpointMetricsHandler endpointMetricsHandler;
protected final boolean includeServerConfigMetrics;
protected final MetricNamingStrategy<ServerStatisticsMetricNames> serverStatsMetricNamingStrategy;
protected final MetricNamingStrategy<ServerConfigMetricNames> serverConfigMetricNamingStrategy;
public static final Supplier<Histogram> DEFAULT_REQUEST_AND_RESPONSE_SIZE_HISTOGRAM_SUPPLIER =
() -> new Histogram(new ExponentiallyDecayingReservoir());
protected final Supplier<Histogram> requestAndResponseSizeHistogramSupplier;
/**
* Constructor that uses the given {@link CodahaleMetricsCollector} and defaults for everything else -
* see the {@link CodahaleMetricsListener#CodahaleMetricsListener(CodahaleMetricsCollector, EndpointMetricsHandler,
* boolean, MetricNamingStrategy, MetricNamingStrategy, Supplier) kitchen sink constructor} for info on defaults.
*
* @param cmc A {@link CodahaleMetricsCollector} instance which houses the registry to which server metrics will be
* sent. Cannot be null - an {@link IllegalArgumentException} will be thrown if you pass in null.
*/
public CodahaleMetricsListener(CodahaleMetricsCollector cmc) {
this(cmc, null, false, null, null, null);
}
/**
* The kitchen sink constructor that allows you to specify all the behavior settings. It's recommended that you
* use the {@link #newBuilder(CodahaleMetricsCollector)} to construct instances rather than directly calling
* this constructor.
*
* @param cmc A {@link CodahaleMetricsCollector} instance which houses the registry to which server metrics will be
* sent. Cannot be null - an {@link IllegalArgumentException} will be thrown if you pass in null.
* @param endpointMetricsHandler The {@link EndpointMetricsHandler} that should be used to track and report
* endpoint metrics. This can be null - if you pass null a new {@link EndpointMetricsHandlerDefaultImpl} will be
* used.
* @param includeServerConfigMetrics Pass in true to have some of the {@link ServerConfig} values exposed via metric
* gauges, or false to exclude those server config value metrics. These values don't change and are easily logged so
* creating metrics for them is usually wasteful, therefore it's recommended that you pass in false to exclude them
* unless you're sure you need them.
* @param serverStatsMetricNamingStrategy The naming strategy that should be used for the server statistics metrics.
* This can be null - if it is null then a new {@link DefaultMetricNamingStrategy} will be used.
* @param serverConfigMetricNamingStrategy The naming strategy that should be used for the {@link ServerConfig}
* gauge metrics. This can be null - if it is null then a new {@link DefaultMetricNamingStrategy} will be used.
*/
public CodahaleMetricsListener(CodahaleMetricsCollector cmc,
EndpointMetricsHandler endpointMetricsHandler,
boolean includeServerConfigMetrics,
MetricNamingStrategy<ServerStatisticsMetricNames> serverStatsMetricNamingStrategy,
MetricNamingStrategy<ServerConfigMetricNames> serverConfigMetricNamingStrategy,
Supplier<Histogram> requestAndResponseSizeHistogramSupplier) {
if (null == cmc) {
throw new IllegalArgumentException("cmc is required");
}
if (endpointMetricsHandler == null)
endpointMetricsHandler = new EndpointMetricsHandlerDefaultImpl();
if (serverStatsMetricNamingStrategy == null)
serverStatsMetricNamingStrategy = MetricNamingStrategy.defaultImpl();
if (serverConfigMetricNamingStrategy == null) {
serverConfigMetricNamingStrategy = new DefaultMetricNamingStrategy<>(
ServerConfig.class.getSimpleName(), DefaultMetricNamingStrategy.DEFAULT_WORD_DELIMITER
);
}
if (requestAndResponseSizeHistogramSupplier == null)
requestAndResponseSizeHistogramSupplier = DEFAULT_REQUEST_AND_RESPONSE_SIZE_HISTOGRAM_SUPPLIER;
this.metricsCollector = cmc;
this.endpointMetricsHandler = endpointMetricsHandler;
this.includeServerConfigMetrics = includeServerConfigMetrics;
this.serverStatsMetricNamingStrategy = serverStatsMetricNamingStrategy;
this.serverConfigMetricNamingStrategy = serverConfigMetricNamingStrategy;
this.requestAndResponseSizeHistogramSupplier = requestAndResponseSizeHistogramSupplier;
addServerStatisticsMetrics();
}
/**
* @param cmc The {@link CodahaleMetricsCollector} that should be used. This is a required field and must be
* non-null by the time {@link Builder#build()} is called or an {@link IllegalArgumentException} will be thrown.
*
* @return A new builder for {@link CodahaleMetricsListener}.
*/
public static Builder newBuilder(CodahaleMetricsCollector cmc) {
return new Builder(cmc);
}
/**
* Initialize the endpoint and server config metrics. Note that the server config values will not be added if
* {@link #includeServerConfigMetrics} is false, however {@link
* EndpointMetricsHandler#setupEndpointsMetrics(ServerConfig, MetricRegistry)} will always be called.
*
* @param config The {@link ServerConfig} that contains the endpoints and server config values.
*/
public void initEndpointAndServerConfigMetrics(ServerConfig config) {
if (includeServerConfigMetrics)
addServerConfigMetrics(config);
endpointMetricsHandler.setupEndpointsMetrics(config, metricsCollector.getMetricRegistry());
}
protected String getMatchingHttpMethodsAsCombinedString(Endpoint<?> endpoint) {
if (endpoint.requestMatcher().isMatchAllMethods())
return "ALL";
return StringUtils.join(endpoint.requestMatcher().matchingMethods(), ",");
}
protected void addServerStatisticsMetrics() {
this.inflightRequests = metricsCollector.getNamedCounter(
serverStatsMetricNamingStrategy.nameFor(INFLIGHT_REQUESTS)
);
this.processedRequests = metricsCollector.getNamedCounter(
serverStatsMetricNamingStrategy.nameFor(PROCESSED_REQUESTS)
);
this.failedRequests = metricsCollector.getNamedCounter(
serverStatsMetricNamingStrategy.nameFor(FAILED_REQUESTS)
);
this.responseWriteFailed = metricsCollector.getNamedCounter(
serverStatsMetricNamingStrategy.nameFor(RESPONSE_WRITE_FAILED)
);
this.responseSizes = metricsCollector.registerNamedMetric(
serverStatsMetricNamingStrategy.nameFor(RESPONSE_SIZES),
requestAndResponseSizeHistogramSupplier.get()
);
this.requestSizes = metricsCollector.registerNamedMetric(
serverStatsMetricNamingStrategy.nameFor(REQUEST_SIZES),
requestAndResponseSizeHistogramSupplier.get()
);
}
/**
* Adds metrics related to the given ServerConfig - usually gauges so you can inspect how the ServerConfig was setup.
* Usually not needed - better to log this info on startup.
*/
protected void addServerConfigMetrics(ServerConfig config) {
// add server config gauges
metricsCollector.registerNamedMetric(serverConfigMetricNamingStrategy.nameFor(BOSS_THREADS),
(Gauge<Integer>)config::numBossThreads);
metricsCollector.registerNamedMetric(serverConfigMetricNamingStrategy.nameFor(WORKER_THREADS),
(Gauge<Integer>)config::numWorkerThreads);
metricsCollector.registerNamedMetric(serverConfigMetricNamingStrategy.nameFor(MAX_REQUEST_SIZE_IN_BYTES),
(Gauge<Integer>)config::maxRequestSizeInBytes);
List<String> endpointsList =
config.appEndpoints()
.stream()
.map(
endpoint -> endpoint.getClass().getName() +
"-" + getMatchingHttpMethodsAsCombinedString(endpoint) +
"-" + endpoint.requestMatcher().matchingPathTemplates()
)
.collect(Collectors.toList());
metricsCollector.registerNamedMetric(serverConfigMetricNamingStrategy.nameFor(ENDPOINTS),
(Gauge<List<String>>)() -> endpointsList);
}
@Override
public void onEvent(@NotNull ServerMetricsEvent event, @Nullable Object value) {
try {
if (ServerMetricsEvent.REQUEST_RECEIVED.equals(event)) {
inflightRequests.inc();
if (logger.isDebugEnabled()) {
logger.debug("inflightRequests incremented {} - thread {}", inflightRequests.getCount(),
Thread.currentThread().toString());
}
}
else if (ServerMetricsEvent.RESPONSE_WRITE_FAILED.equals(event)) {
inflightRequests.dec();
processedRequests.inc();
responseWriteFailed.inc();
if (logger.isDebugEnabled()) {
logger.debug("inflightRequests decremented after response write failure");
}
}
else if (ServerMetricsEvent.RESPONSE_SENT.equals(event)) {
HttpProcessingState httpState;
if (value instanceof HttpProcessingState) {
httpState = (HttpProcessingState) value;
}
else {
logger.error("Metrics Error: value is not an HttpProcessingState");
return;
}
inflightRequests.dec();
processedRequests.inc();
// Make sure HttpProcessingState, RequestInfo, and ResponseInfo are populated with the things we need.
RequestInfo<?> requestInfo = httpState.getRequestInfo();
if (requestInfo == null) {
logger.error("Metrics Error: httpState.getRequestInfo() is null");
return;
}
if (logger.isDebugEnabled()) {
logger.debug("inflightRequests decremented {} - URI {} - Thread {}", inflightRequests.getCount(),
requestInfo.getUri(), Thread.currentThread().toString());
}
ResponseInfo<?> responseInfo = httpState.getResponseInfo();
if (responseInfo == null) {
logger.error("Metrics Error: httpState.getResponseInfo() is null");
return;
}
// Response end time should already be set by now, but just in case it hasn't (i.e. due to an exception
// preventing any response from being sent)...
httpState.setResponseEndTimeNanosToNowIfNotAlreadySet();
Long requestElapsedTimeMillis = httpState.calculateTotalRequestTimeMillis();
if (requestElapsedTimeMillis == null) {
// This should only happen if httpState.getRequestStartTimeNanos() is null,
// which means AccessLogStartHandler never executed for a Netty HttpRequest message. Something
// went really wrong with this request.
logger.error(
"Metrics Error: httpState.calculateTotalRequestTimeMillis() is null. "
+ "httpState.getRequestStartTimeNanos(): " + httpState.getRequestStartTimeNanos()
);
return;
}
final int responseHttpStatusCode =
responseInfo.getHttpStatusCodeWithDefault(ResponseSender.DEFAULT_HTTP_STATUS_CODE);
final int responseHttpStatusCodeXXValue = responseHttpStatusCode / 100;
endpointMetricsHandler.handleRequest(
requestInfo, responseInfo, httpState, responseHttpStatusCode, responseHttpStatusCodeXXValue,
requestElapsedTimeMillis
);
// If the http response status is greater than or equal to 400 then it should be marked as a
// failed request.
if (responseHttpStatusCodeXXValue >= 4) {
failedRequests.inc();
}
// meter request/response sizes
requestSizes.update(requestInfo.getRawContentLengthInBytes());
// TODO: Maybe add another metric for the raw uncompressed response length?
responseSizes
.update(responseInfo.getFinalContentLength() == null ? 0 : responseInfo.getFinalContentLength());
}
else {
logger.error("Metrics Error: unknown metrics event " + event);
}
}
catch (Throwable t) {
logger.error("Metrics Error: ", t);
}
}
public Counter getInflightRequests() {
return inflightRequests;
}
public Counter getProcessedRequests() {
return processedRequests;
}
public Counter getFailedRequests() {
return failedRequests;
}
public Counter getResponseWriteFailed() {
return responseWriteFailed;
}
public Histogram getResponseSizes() {
return responseSizes;
}
public Histogram getRequestSizes() {
return requestSizes;
}
public MetricRegistry getMetricRegistry() {
return metricsCollector.getMetricRegistry();
}
public CodahaleMetricsCollector getMetricsCollector() {
return metricsCollector;
}
public EndpointMetricsHandler getEndpointMetricsHandler() {
return endpointMetricsHandler;
}
public enum ServerStatisticsMetricNames {
INFLIGHT_REQUESTS,
PROCESSED_REQUESTS,
FAILED_REQUESTS,
RESPONSE_WRITE_FAILED,
REQUEST_SIZES,
RESPONSE_SIZES
}
public enum ServerConfigMetricNames {
BOSS_THREADS,
WORKER_THREADS,
MAX_REQUEST_SIZE_IN_BYTES,
ENDPOINTS
}
/**
* Interface describing a naming strategy for metric names. You can customize the names of the metrics created and
* tracked by {@link CodahaleMetricsListener} by implementing this interface and passing your custom impl when
* creating your app's {@link CodahaleMetricsListener}.
*
* @param <T> The enum representing the metric names that this instance knows how to handle.
*/
@FunctionalInterface
public interface MetricNamingStrategy<T extends Enum> {
String nameFor(T metricNameEnum);
/**
* @return A default {@link DefaultMetricNamingStrategy}.
*/
static <T extends Enum> MetricNamingStrategy<T> defaultImpl() {
return new DefaultMetricNamingStrategy<>();
}
/**
* @return A {@link DefaultMetricNamingStrategy} that has no prefix but is otherwise default.
*/
static <T extends Enum> MetricNamingStrategy<T> defaultNoPrefixImpl() {
return defaultImpl(null, DefaultMetricNamingStrategy.DEFAULT_WORD_DELIMITER);
}
/**
* @return A {@link DefaultMetricNamingStrategy} with the given prefix and word delimiter settings.
*/
static <T extends Enum> MetricNamingStrategy<T> defaultImpl(String prefix, String wordDelimiter) {
return new DefaultMetricNamingStrategy<>(prefix, wordDelimiter);
}
}
/**
* Default implementation of {@link MetricNamingStrategy}. This impl takes the enum passed into {@link
* #nameFor(Enum)} and lowercases its name to generate the name for the metric. There are two options you can use
* to adjust this class' behavior:
*
* <ul>
* <li>
* You can set an optional {@link #prefix} that will be prepended to the metric name, with a dot separating
* the prefix and the rest of the metric name. If you want to omit the prefix entirely then pass in null
* or the empty string.
* </li>
* <li>
* You can set an optional {@link #wordDelimiter} that will replace any underscores found in the metric
* enum names. By default this is set to "_", effectively leaving underscores as they are. If you want to
* omit the delimiter entirely then pass in null or the empty string.
* </li>
* </ul>
*
* @param <T> The enum representing the metric names that this instance knows how to handle.
*/
public static class DefaultMetricNamingStrategy<T extends Enum> implements MetricNamingStrategy<T> {
public static final String DEFAULT_PREFIX = CodahaleMetricsListener.class.getSimpleName();
public static final String DEFAULT_WORD_DELIMITER = "_";
protected final String prefix;
protected final String wordDelimiter;
public DefaultMetricNamingStrategy() {
this(DEFAULT_PREFIX, DEFAULT_WORD_DELIMITER);
}
public DefaultMetricNamingStrategy(String prefix, String wordDelimiter) {
if (wordDelimiter == null)
wordDelimiter = "";
this.prefix = prefix;
this.wordDelimiter = wordDelimiter;
}
@Override
public String nameFor(T metricNameEnum) {
return name(prefix, metricNameEnum.name().toLowerCase().replace("_", wordDelimiter));
}
}
/**
* Builder class for {@link CodahaleMetricsListener}.
*/
public static class Builder {
private CodahaleMetricsCollector metricsCollector;
private EndpointMetricsHandler endpointMetricsHandler;
private boolean includeServerConfigMetrics = false;
private MetricNamingStrategy<ServerStatisticsMetricNames> serverStatsMetricNamingStrategy;
private MetricNamingStrategy<ServerConfigMetricNames> serverConfigMetricNamingStrategy;
private Supplier<Histogram> requestAndResponseSizeHistogramSupplier;
private Builder(CodahaleMetricsCollector cmc) {
this.metricsCollector = cmc;
}
/**
* Sets the {@link CodahaleMetricsCollector} instance which houses the registry to which server metrics will be
* sent. Cannot be null - a {@link IllegalArgumentException} will be thrown when {@link #build()} is called
* if this is null.
*
* @param metricsCollector
* the {@code metricsCollector} to set
*
* @return A reference to this Builder.
*/
public Builder withMetricsCollector(CodahaleMetricsCollector metricsCollector) {
this.metricsCollector = metricsCollector;
return this;
}
/**
* Sets the {@link EndpointMetricsHandler} that should be used for tracking and reporting endpoint metrics.
* This can be null - a new {@link EndpointMetricsHandlerDefaultImpl} will be used if you don't specify a
* custom instance.
*
* @param endpointMetricsHandler
* the {@code endpointMetricsHandler} to set
*
* @return A reference to this Builder.
*/
public Builder withEndpointMetricsHandler(EndpointMetricsHandler endpointMetricsHandler) {
this.endpointMetricsHandler = endpointMetricsHandler;
return this;
}
/**
* Pass in true to have some of the {@link ServerConfig} values exposed via metric gauges, or false to exclude
* those server config value metrics. These values don't change and are easily logged so creating metrics for
* them is usually wasteful, therefore it's recommended that you leave this as false to exclude them unless
* you're sure you need them (false will be used by default if you don't specify anything).
*
* @param includeServerConfigMetrics
* the {@code includeServerConfigMetrics} to set
*
* @return A reference to this Builder.
*/
public Builder withIncludeServerConfigMetrics(boolean includeServerConfigMetrics) {
this.includeServerConfigMetrics = includeServerConfigMetrics;
return this;
}
/**
* Sets the naming strategy that should be used for the server statistics metrics. This can be null - if it is
* null then a new {@link DefaultMetricNamingStrategy} will be used.
*
* @param serverStatsMetricNamingStrategy
* the {@code serverStatsMetricNamingStrategy} to set
*
* @return a reference to this Builder
*/
public Builder withServerStatsMetricNamingStrategy(
MetricNamingStrategy<ServerStatisticsMetricNames> serverStatsMetricNamingStrategy
) {
this.serverStatsMetricNamingStrategy = serverStatsMetricNamingStrategy;
return this;
}
/**
* Sets the naming strategy that should be used for the {@link ServerConfig} gauge metrics. This can be null -
* if it is null then a new {@link DefaultMetricNamingStrategy} will be used.
*
* @param serverConfigMetricNamingStrategy
* the {@code serverConfigMetricNamingStrategy} to set
*
* @return a reference to this Builder
*/
public Builder withServerConfigMetricNamingStrategy(
MetricNamingStrategy<ServerConfigMetricNames> serverConfigMetricNamingStrategy
) {
this.serverConfigMetricNamingStrategy = serverConfigMetricNamingStrategy;
return this;
}
/**
* Sets the supplier that should be used to create the request-size and response-size Histogram metrics. You
* might want to set this in order to change the {@link Reservoir} type used by the histograms to a {@link
* SlidingTimeWindowArrayReservoir} with the sliding window time values that match your reporter's update frequency.
* i.e. if you passed in a supplier like this:
* {@code () -> new Histogram(new SlidingTimeWindowArrayReservoir(10L, TimeUnit.SECONDS))} then the request-size and
* response-size histograms generated would always give you data for *only* the 10 seconds previous to whenever
* you requested the data. This can be null - if it is null then {@link
* #DEFAULT_REQUEST_AND_RESPONSE_SIZE_HISTOGRAM_SUPPLIER} will be used.
*
* @param requestAndResponseSizeHistogramSupplier The supplier to use when generating the request-size and
* response-size {@link Histogram}s.
* @return a reference to this Builder
*/
public Builder withRequestAndResponseSizeHistogramSupplier(
Supplier<Histogram> requestAndResponseSizeHistogramSupplier
) {
this.requestAndResponseSizeHistogramSupplier = requestAndResponseSizeHistogramSupplier;
return this;
}
/**
* @return a {@link CodahaleMetricsListener} built with parameters from this builder.
*/
public CodahaleMetricsListener build() {
return new CodahaleMetricsListener(
metricsCollector, endpointMetricsHandler, includeServerConfigMetrics, serverStatsMetricNamingStrategy,
serverConfigMetricNamingStrategy, requestAndResponseSizeHistogramSupplier
);
}
}
}
| {
"pile_set_name": "Github"
} |
.\"
.\" Copyright 2012-2013 Samy Al Bahra.
.\" All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE 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.
.\"
.\"
.Dd October 18, 2013
.Dt CK_ARRAY_INITIALIZED 3
.Sh NAME
.Nm ck_array_initialized
.Nd indicates whether an array was recently initialized or deinitialized
.Sh LIBRARY
Concurrency Kit (libck, \-lck)
.Sh SYNOPSIS
.In ck_array.h
.Ft bool
.Fn ck_array_initialized "ck_array_t *array"
.Sh DESCRIPTION
The
.Fn ck_array_initialized 3
can be used to determine whether an array was recently initialized
with
.Fn ck_array_init 3
or deinitialized with
.Fn ck_array_deinit 3 .
Behavior is undefined if a user allocates internal allocator data
in through other means.
.Sh RETURN VALUES
This function returns true if the array is initialized, and false
otherwise.
.Sh SEE ALSO
.Xr ck_array_commit 3 ,
.Xr ck_array_put 3 ,
.Xr ck_array_put_unique 3 ,
.Xr ck_array_remove 3 ,
.Xr ck_array_init 3
.Xr ck_array_deinit 3 ,
.Xr ck_array_length 3 ,
.Xr ck_array_buffer 3 ,
.Xr CK_ARRAY_FOREACH 3
.Pp
Additional information available at http://concurrencykit.org/
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:background="@android:color/darker_gray"
android:paddingStart="15dp"
android:text="*Example that links the values added with 'setLinkedMention' and 'setLinkedHashtag'."
android:textColor="@android:color/black"
android:textStyle="italic"/>
<com.hasankucuk.socialtextview.SocialTextView
android:id="@+id/socialTextView"
android:layout_width="match_parent"
app:underLine="true"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="This project was #developed by @hasankucuk as #opensource. \n
[email protected] \n
https://medium.com/@hasann.kucuk \n
[email protected] \n
+1 123456789"
android:paddingTop="16dp"
android:paddingLeft="16dp"
app:highlightRadius="12"
android:paddingRight="16dp"
android:lineSpacingMultiplier="1.2"
app:emailColor="#FF9E80"
app:highlightColor="@android:color/holo_red_light"
app:highlightTextColor="@android:color/white"
app:hashtagColor="#82B1FF"
app:linkType="mention|hashtag|phone|email|url|highlight"
app:mentionColor="#BCBCCF"
app:normalTextColor="#18181F"
app:phoneColor="#03A9F4"
app:urlColor="#8BC34A"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/darker_gray"
android:paddingStart="15dp"
android:text="Linked example by selected 'linkType' "
android:textColor="@android:color/black"
android:textStyle="italic"/>
<com.hasankucuk.socialtextview.SocialTextView
android:id="@+id/socialTextView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="This project was #developed by @hasankucuk as #opensource. \n
[email protected] \n
https://medium.com/@hasann.kucuk \n
[email protected] \n
+1 123456789"
app:emailColor="#FF9E80"
app:hashtagColor="#82B1FF"
app:linkType="mention|hashtag|phone|email|url"
app:mentionColor="#BCBCCF"
app:normalTextColor="#18181F"
app:phoneColor="#03A9F4"
app:urlColor="#8BC34A"/>
</LinearLayout>
</LinearLayout> | {
"pile_set_name": "Github"
} |
// Copyright (c) Andrew Fischer. See LICENSE file for license terms.
#include <cstdio>
#include "circa/circa.h"
int main(int argc, char** argv)
{
caWorld* world = circa_initialize();
circa_add_module_search_path(world, "tests/embed");
circa::Value msg;
circa_set_int(&msg, 0);
circa_actor_post_message(world, "ActorA", &msg);
for (int i=0; i < 10; i++)
circa_actor_run_all_queues(world, 10);
printf("Resetting and starting actors C and D...\n");
circa_actor_clear_all(world);
circa_actor_post_message(world, "ActorC", &msg);
for (int i=0; i < 10; i++)
circa_actor_run_all_queues(world, 10);
circa_shutdown(world);
return 0;
}
| {
"pile_set_name": "Github"
} |
/*----------------------表单验证以及提交表单----------------------start*/
$(function () {
//bootstrap校验
$('form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
userEmail: {
message: '邮箱验证失败',
validators: {
notEmpty: {
message: '邮箱不能为空'
},
emailAddress: {
message: '邮箱地址格式有误'
}
}
},
userPassword: {
message: '密码验证失败',
validators: {
notEmpty: {
message: '密码不能为空'
},
stringLength: {
min: 6,
max: 12,
message: '密码长度必须在6到12位之间'
}
}
}
},
submitHandler: function (validator, form, submitButton) {
//ajax请求
$.ajax({
url: path + "/user/login.do",
type: "post",
async: false,
data: $("#loginForm").serialize(),
success: function (responseText) {
console.log(responseText);
if (responseText.message == "验证码错误") {
sweetAlert("验证码错误");
} else if (responseText.message == "密码错误") {
sweetAlert("密码错误");
} else if (responseText.message == "账号不存在/没有在邮箱中激活账户") {
sweetAlert("账号不存在/账户未激活");
} else if (responseText.message == "登陆成功") {
window.location.href = path + "/index.html";
} else {
//出错了也回到首页吧
window.location.href = path + "/index.html";
}
//只要错误了,就设置验证码为空,同时更新验证码
$("#inputCaptcha").val("");
$("#captcha").attr("src", path + "/user/getGifCode.do?time=" + new Date().getTime());
$("#submitButton").removeAttr("disabled");
},
error: function (response, ajaxOptions, thrownError) {
console.log(response);
console.log(ajaxOptions);
console.log(thrownError);
sweetAlert("系统错误");
}
});
//validator.defaultSubmit();
}
});
//点击图片换一张验证码
$("#captcha").click(function () {
$(this).attr("src", path + "/user/getGifCode.do?time=" + new Date().getTime());
});
});
/*----------------------表单验证以及提交表单----------------------end*/
/*封装错误信息(暂时还没用到)-----------------------------------start*/
/*
var Error = function () {
return {
// 初始化各个函数及对象
init: function () {
},
// 显示或者记录错误
displayError: function (response, ajaxOptions, thrownError) {
if (response.status == 404) {// 页面没有找到
pageContent.load($("#hdnContextPath").val() + "/page/404.action");
} else if (response.status == 401) {// session过期
SweetAlert.errorSessionExpire();
} else if (response.status == 507) {// 用户访问次数太频繁
SweetAlert.error("您的访问次数太频繁, 请过一会再试...");
} else {//其他错误
window.location = $("#hdnContextPath").val() + "/page/500.action";
}
console.log(thrownError);
}
};
}();
jQuery(document).ready(function () {
Error.init();
});
*/
/*封装错误信息(暂时还没用到)-----------------------------------end*/
| {
"pile_set_name": "Github"
} |
# Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
import("//build/config/ui.gni")
import("../../build/webrtc.gni")
use_desktop_capture_differ_sse2 =
(!is_ios && (cpu_arch == "x86" || cpu_arch == "x64"))
source_set("desktop_capture") {
sources = [
"cropped_desktop_frame.cc",
"cropped_desktop_frame.h",
"cropping_window_capturer.cc",
"cropping_window_capturer.h",
"cropping_window_capturer_win.cc",
"desktop_and_cursor_composer.cc",
"desktop_and_cursor_composer.h",
"desktop_capture_types.h",
"desktop_capturer.h",
"desktop_frame.cc",
"desktop_frame.h",
"desktop_frame_win.cc",
"desktop_frame_win.h",
"desktop_geometry.cc",
"desktop_geometry.h",
"desktop_capture_options.h",
"desktop_capture_options.cc",
"desktop_capturer.h",
"desktop_region.cc",
"desktop_region.h",
"differ.cc",
"differ.h",
"differ_block.cc",
"differ_block.h",
"mac/desktop_configuration.h",
"mac/desktop_configuration.mm",
"mac/desktop_configuration_monitor.h",
"mac/desktop_configuration_monitor.cc",
"mac/full_screen_chrome_window_detector.cc",
"mac/full_screen_chrome_window_detector.h",
"mac/scoped_pixel_buffer_object.cc",
"mac/scoped_pixel_buffer_object.h",
"mac/window_list_utils.cc",
"mac/window_list_utils.h",
"mouse_cursor.cc",
"mouse_cursor.h",
"mouse_cursor_monitor.h",
"mouse_cursor_monitor_mac.mm",
"mouse_cursor_monitor_win.cc",
"screen_capture_frame_queue.cc",
"screen_capture_frame_queue.h",
"screen_capturer.cc",
"screen_capturer.h",
"screen_capturer_helper.cc",
"screen_capturer_helper.h",
"screen_capturer_mac.mm",
"screen_capturer_win.cc",
"shared_desktop_frame.cc",
"shared_desktop_frame.h",
"shared_memory.cc",
"shared_memory.h",
"win/cursor.cc",
"win/cursor.h",
"win/desktop.cc",
"win/desktop.h",
"win/scoped_gdi_object.h",
"win/scoped_thread_desktop.cc",
"win/scoped_thread_desktop.h",
"win/screen_capturer_win_gdi.cc",
"win/screen_capturer_win_gdi.h",
"win/screen_capturer_win_magnifier.cc",
"win/screen_capturer_win_magnifier.h",
"win/screen_capture_utils.cc",
"win/screen_capture_utils.h",
"win/window_capture_utils.cc",
"win/window_capture_utils.h",
"window_capturer.cc",
"window_capturer.h",
"window_capturer_mac.mm",
"window_capturer_win.cc",
]
if (use_x11) {
sources += [
"mouse_cursor_monitor_x11.cc",
"screen_capturer_x11.cc",
"window_capturer_x11.cc",
"x11/shared_x_display.h",
"x11/shared_x_display.cc",
"x11/x_error_trap.cc",
"x11/x_error_trap.h",
"x11/x_server_pixel_buffer.cc",
"x11/x_server_pixel_buffer.h",
]
configs += ["//build/config/linux:x11"]
}
if (!is_win && !is_mac && !use_x11) {
sources += [
"mouse_cursor_monitor_null.cc",
"screen_capturer_null.cc",
"window_capturer_null.cc",
]
}
if (is_mac) {
libs = [
"AppKit.framework",
"IOKit.framework",
"OpenGL.framework",
]
}
configs += [ "../..:common_config" ]
public_configs = [ "../..:common_inherited_config"]
if (is_clang) {
# Suppress warnings from Chrome's Clang plugins.
# See http://code.google.com/p/webrtc/issues/detail?id=163 for details.
configs -= [ "//build/config/clang:find_bad_constructs" ]
}
deps = [
"../../base:rtc_base_approved",
"../../system_wrappers",
]
if (use_desktop_capture_differ_sse2) {
deps += [":desktop_capture_differ_sse2"]
}
}
if (use_desktop_capture_differ_sse2) {
# Have to be compiled as a separate target because it needs to be compiled
# with SSE2 enabled.
source_set("desktop_capture_differ_sse2") {
visibility = [ ":*" ]
sources = [
"differ_block_sse2.cc",
"differ_block_sse2.h",
]
configs += [ "../..:common_config" ]
public_configs = [ "../..:common_inherited_config" ]
if (is_posix && !is_mac) {
cflags = ["-msse2"]
}
}
}
| {
"pile_set_name": "Github"
} |
/* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* dlmcommon.h
*
* Copyright (C) 2004 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*
*/
#ifndef DLMCOMMON_H
#define DLMCOMMON_H
#include <linux/kref.h>
#define DLM_HB_NODE_DOWN_PRI (0xf000000)
#define DLM_HB_NODE_UP_PRI (0x8000000)
#define DLM_LOCKID_NAME_MAX 32
#define DLM_DOMAIN_NAME_MAX_LEN 255
#define DLM_LOCK_RES_OWNER_UNKNOWN O2NM_MAX_NODES
#define DLM_THREAD_SHUFFLE_INTERVAL 5 // flush everything every 5 passes
#define DLM_THREAD_MS 200 // flush at least every 200 ms
#define DLM_HASH_SIZE_DEFAULT (1 << 14)
#if DLM_HASH_SIZE_DEFAULT < PAGE_SIZE
# define DLM_HASH_PAGES 1
#else
# define DLM_HASH_PAGES (DLM_HASH_SIZE_DEFAULT / PAGE_SIZE)
#endif
#define DLM_BUCKETS_PER_PAGE (PAGE_SIZE / sizeof(struct hlist_head))
#define DLM_HASH_BUCKETS (DLM_HASH_PAGES * DLM_BUCKETS_PER_PAGE)
/* Intended to make it easier for us to switch out hash functions */
#define dlm_lockid_hash(_n, _l) full_name_hash(_n, _l)
enum dlm_mle_type {
DLM_MLE_BLOCK,
DLM_MLE_MASTER,
DLM_MLE_MIGRATION,
DLM_MLE_NUM_TYPES
};
struct dlm_master_list_entry {
struct hlist_node master_hash_node;
struct list_head hb_events;
struct dlm_ctxt *dlm;
spinlock_t spinlock;
wait_queue_head_t wq;
atomic_t woken;
struct kref mle_refs;
int inuse;
unsigned long maybe_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
unsigned long vote_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
unsigned long response_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
unsigned long node_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
u8 master;
u8 new_master;
enum dlm_mle_type type;
struct o2hb_callback_func mle_hb_up;
struct o2hb_callback_func mle_hb_down;
struct dlm_lock_resource *mleres;
unsigned char mname[DLM_LOCKID_NAME_MAX];
unsigned int mnamelen;
unsigned int mnamehash;
};
enum dlm_ast_type {
DLM_AST = 0,
DLM_BAST,
DLM_ASTUNLOCK
};
#define LKM_VALID_FLAGS (LKM_VALBLK | LKM_CONVERT | LKM_UNLOCK | \
LKM_CANCEL | LKM_INVVALBLK | LKM_FORCE | \
LKM_RECOVERY | LKM_LOCAL | LKM_NOQUEUE)
#define DLM_RECOVERY_LOCK_NAME "$RECOVERY"
#define DLM_RECOVERY_LOCK_NAME_LEN 9
static inline int dlm_is_recovery_lock(const char *lock_name, int name_len)
{
if (name_len == DLM_RECOVERY_LOCK_NAME_LEN &&
memcmp(lock_name, DLM_RECOVERY_LOCK_NAME, name_len)==0)
return 1;
return 0;
}
#define DLM_RECO_STATE_ACTIVE 0x0001
#define DLM_RECO_STATE_FINALIZE 0x0002
struct dlm_recovery_ctxt
{
struct list_head resources;
struct list_head received;
struct list_head node_data;
u8 new_master;
u8 dead_node;
u16 state;
unsigned long node_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
wait_queue_head_t event;
};
enum dlm_ctxt_state {
DLM_CTXT_NEW = 0,
DLM_CTXT_JOINED,
DLM_CTXT_IN_SHUTDOWN,
DLM_CTXT_LEAVING,
};
struct dlm_ctxt
{
struct list_head list;
struct hlist_head **lockres_hash;
struct list_head dirty_list;
struct list_head purge_list;
struct list_head pending_asts;
struct list_head pending_basts;
struct list_head tracking_list;
unsigned int purge_count;
spinlock_t spinlock;
spinlock_t ast_lock;
spinlock_t track_lock;
char *name;
u8 node_num;
u32 key;
u8 joining_node;
wait_queue_head_t dlm_join_events;
unsigned long live_nodes_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
unsigned long domain_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
unsigned long recovery_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
struct dlm_recovery_ctxt reco;
spinlock_t master_lock;
struct hlist_head **master_hash;
struct list_head mle_hb_events;
/* these give a really vague idea of the system load */
atomic_t mle_tot_count[DLM_MLE_NUM_TYPES];
atomic_t mle_cur_count[DLM_MLE_NUM_TYPES];
atomic_t res_tot_count;
atomic_t res_cur_count;
struct dlm_debug_ctxt *dlm_debug_ctxt;
struct dentry *dlm_debugfs_subroot;
/* NOTE: Next three are protected by dlm_domain_lock */
struct kref dlm_refs;
enum dlm_ctxt_state dlm_state;
unsigned int num_joins;
struct o2hb_callback_func dlm_hb_up;
struct o2hb_callback_func dlm_hb_down;
struct task_struct *dlm_thread_task;
struct task_struct *dlm_reco_thread_task;
struct workqueue_struct *dlm_worker;
wait_queue_head_t dlm_thread_wq;
wait_queue_head_t dlm_reco_thread_wq;
wait_queue_head_t ast_wq;
wait_queue_head_t migration_wq;
struct work_struct dispatched_work;
struct list_head work_list;
spinlock_t work_lock;
struct list_head dlm_domain_handlers;
struct list_head dlm_eviction_callbacks;
/* The filesystem specifies this at domain registration. We
* cache it here to know what to tell other nodes. */
struct dlm_protocol_version fs_locking_proto;
/* This is the inter-dlm communication version */
struct dlm_protocol_version dlm_locking_proto;
};
static inline struct hlist_head *dlm_lockres_hash(struct dlm_ctxt *dlm, unsigned i)
{
return dlm->lockres_hash[(i / DLM_BUCKETS_PER_PAGE) % DLM_HASH_PAGES] + (i % DLM_BUCKETS_PER_PAGE);
}
static inline struct hlist_head *dlm_master_hash(struct dlm_ctxt *dlm,
unsigned i)
{
return dlm->master_hash[(i / DLM_BUCKETS_PER_PAGE) % DLM_HASH_PAGES] +
(i % DLM_BUCKETS_PER_PAGE);
}
/* these keventd work queue items are for less-frequently
* called functions that cannot be directly called from the
* net message handlers for some reason, usually because
* they need to send net messages of their own. */
void dlm_dispatch_work(struct work_struct *work);
struct dlm_lock_resource;
struct dlm_work_item;
typedef void (dlm_workfunc_t)(struct dlm_work_item *, void *);
struct dlm_request_all_locks_priv
{
u8 reco_master;
u8 dead_node;
};
struct dlm_mig_lockres_priv
{
struct dlm_lock_resource *lockres;
u8 real_master;
u8 extra_ref;
};
struct dlm_assert_master_priv
{
struct dlm_lock_resource *lockres;
u8 request_from;
u32 flags;
unsigned ignore_higher:1;
};
struct dlm_deref_lockres_priv
{
struct dlm_lock_resource *deref_res;
u8 deref_node;
};
struct dlm_work_item
{
struct list_head list;
dlm_workfunc_t *func;
struct dlm_ctxt *dlm;
void *data;
union {
struct dlm_request_all_locks_priv ral;
struct dlm_mig_lockres_priv ml;
struct dlm_assert_master_priv am;
struct dlm_deref_lockres_priv dl;
} u;
};
static inline void dlm_init_work_item(struct dlm_ctxt *dlm,
struct dlm_work_item *i,
dlm_workfunc_t *f, void *data)
{
memset(i, 0, sizeof(*i));
i->func = f;
INIT_LIST_HEAD(&i->list);
i->data = data;
i->dlm = dlm; /* must have already done a dlm_grab on this! */
}
static inline void __dlm_set_joining_node(struct dlm_ctxt *dlm,
u8 node)
{
assert_spin_locked(&dlm->spinlock);
dlm->joining_node = node;
wake_up(&dlm->dlm_join_events);
}
#define DLM_LOCK_RES_UNINITED 0x00000001
#define DLM_LOCK_RES_RECOVERING 0x00000002
#define DLM_LOCK_RES_READY 0x00000004
#define DLM_LOCK_RES_DIRTY 0x00000008
#define DLM_LOCK_RES_IN_PROGRESS 0x00000010
#define DLM_LOCK_RES_MIGRATING 0x00000020
#define DLM_LOCK_RES_DROPPING_REF 0x00000040
#define DLM_LOCK_RES_BLOCK_DIRTY 0x00001000
#define DLM_LOCK_RES_SETREF_INPROG 0x00002000
/* max milliseconds to wait to sync up a network failure with a node death */
#define DLM_NODE_DEATH_WAIT_MAX (5 * 1000)
#define DLM_PURGE_INTERVAL_MS (8 * 1000)
struct dlm_lock_resource
{
/* WARNING: Please see the comment in dlm_init_lockres before
* adding fields here. */
struct hlist_node hash_node;
struct qstr lockname;
struct kref refs;
/*
* Please keep granted, converting, and blocked in this order,
* as some funcs want to iterate over all lists.
*
* All four lists are protected by the hash's reference.
*/
struct list_head granted;
struct list_head converting;
struct list_head blocked;
struct list_head purge;
/*
* These two lists require you to hold an additional reference
* while they are on the list.
*/
struct list_head dirty;
struct list_head recovering; // dlm_recovery_ctxt.resources list
/* Added during init and removed during release */
struct list_head tracking; /* dlm->tracking_list */
/* unused lock resources have their last_used stamped and are
* put on a list for the dlm thread to run. */
unsigned long last_used;
struct dlm_ctxt *dlm;
unsigned migration_pending:1;
atomic_t asts_reserved;
spinlock_t spinlock;
wait_queue_head_t wq;
u8 owner; //node which owns the lock resource, or unknown
u16 state;
char lvb[DLM_LVB_LEN];
unsigned int inflight_locks;
unsigned long refmap[BITS_TO_LONGS(O2NM_MAX_NODES)];
};
struct dlm_migratable_lock
{
__be64 cookie;
/* these 3 are just padding for the in-memory structure, but
* list and flags are actually used when sent over the wire */
__be16 pad1;
u8 list; // 0=granted, 1=converting, 2=blocked
u8 flags;
s8 type;
s8 convert_type;
s8 highest_blocked;
u8 node;
}; // 16 bytes
struct dlm_lock
{
struct dlm_migratable_lock ml;
struct list_head list;
struct list_head ast_list;
struct list_head bast_list;
struct dlm_lock_resource *lockres;
spinlock_t spinlock;
struct kref lock_refs;
// ast and bast must be callable while holding a spinlock!
dlm_astlockfunc_t *ast;
dlm_bastlockfunc_t *bast;
void *astdata;
struct dlm_lockstatus *lksb;
unsigned ast_pending:1,
bast_pending:1,
convert_pending:1,
lock_pending:1,
cancel_pending:1,
unlock_pending:1,
lksb_kernel_allocated:1;
};
#define DLM_LKSB_UNUSED1 0x01
#define DLM_LKSB_PUT_LVB 0x02
#define DLM_LKSB_GET_LVB 0x04
#define DLM_LKSB_UNUSED2 0x08
#define DLM_LKSB_UNUSED3 0x10
#define DLM_LKSB_UNUSED4 0x20
#define DLM_LKSB_UNUSED5 0x40
#define DLM_LKSB_UNUSED6 0x80
enum dlm_lockres_list {
DLM_GRANTED_LIST = 0,
DLM_CONVERTING_LIST,
DLM_BLOCKED_LIST
};
static inline int dlm_lvb_is_empty(char *lvb)
{
int i;
for (i=0; i<DLM_LVB_LEN; i++)
if (lvb[i])
return 0;
return 1;
}
static inline struct list_head *
dlm_list_idx_to_ptr(struct dlm_lock_resource *res, enum dlm_lockres_list idx)
{
struct list_head *ret = NULL;
if (idx == DLM_GRANTED_LIST)
ret = &res->granted;
else if (idx == DLM_CONVERTING_LIST)
ret = &res->converting;
else if (idx == DLM_BLOCKED_LIST)
ret = &res->blocked;
else
BUG();
return ret;
}
struct dlm_node_iter
{
unsigned long node_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
int curnode;
};
enum {
DLM_MASTER_REQUEST_MSG = 500,
DLM_UNUSED_MSG1, /* 501 */
DLM_ASSERT_MASTER_MSG, /* 502 */
DLM_CREATE_LOCK_MSG, /* 503 */
DLM_CONVERT_LOCK_MSG, /* 504 */
DLM_PROXY_AST_MSG, /* 505 */
DLM_UNLOCK_LOCK_MSG, /* 506 */
DLM_DEREF_LOCKRES_MSG, /* 507 */
DLM_MIGRATE_REQUEST_MSG, /* 508 */
DLM_MIG_LOCKRES_MSG, /* 509 */
DLM_QUERY_JOIN_MSG, /* 510 */
DLM_ASSERT_JOINED_MSG, /* 511 */
DLM_CANCEL_JOIN_MSG, /* 512 */
DLM_EXIT_DOMAIN_MSG, /* 513 */
DLM_MASTER_REQUERY_MSG, /* 514 */
DLM_LOCK_REQUEST_MSG, /* 515 */
DLM_RECO_DATA_DONE_MSG, /* 516 */
DLM_BEGIN_RECO_MSG, /* 517 */
DLM_FINALIZE_RECO_MSG /* 518 */
};
struct dlm_reco_node_data
{
int state;
u8 node_num;
struct list_head list;
};
enum {
DLM_RECO_NODE_DATA_DEAD = -1,
DLM_RECO_NODE_DATA_INIT = 0,
DLM_RECO_NODE_DATA_REQUESTING,
DLM_RECO_NODE_DATA_REQUESTED,
DLM_RECO_NODE_DATA_RECEIVING,
DLM_RECO_NODE_DATA_DONE,
DLM_RECO_NODE_DATA_FINALIZE_SENT,
};
enum {
DLM_MASTER_RESP_NO = 0,
DLM_MASTER_RESP_YES,
DLM_MASTER_RESP_MAYBE,
DLM_MASTER_RESP_ERROR
};
struct dlm_master_request
{
u8 node_idx;
u8 namelen;
__be16 pad1;
__be32 flags;
u8 name[O2NM_MAX_NAME_LEN];
};
#define DLM_ASSERT_RESPONSE_REASSERT 0x00000001
#define DLM_ASSERT_RESPONSE_MASTERY_REF 0x00000002
#define DLM_ASSERT_MASTER_MLE_CLEANUP 0x00000001
#define DLM_ASSERT_MASTER_REQUERY 0x00000002
#define DLM_ASSERT_MASTER_FINISH_MIGRATION 0x00000004
struct dlm_assert_master
{
u8 node_idx;
u8 namelen;
__be16 pad1;
__be32 flags;
u8 name[O2NM_MAX_NAME_LEN];
};
#define DLM_MIGRATE_RESPONSE_MASTERY_REF 0x00000001
struct dlm_migrate_request
{
u8 master;
u8 new_master;
u8 namelen;
u8 pad1;
__be32 pad2;
u8 name[O2NM_MAX_NAME_LEN];
};
struct dlm_master_requery
{
u8 pad1;
u8 pad2;
u8 node_idx;
u8 namelen;
__be32 pad3;
u8 name[O2NM_MAX_NAME_LEN];
};
#define DLM_MRES_RECOVERY 0x01
#define DLM_MRES_MIGRATION 0x02
#define DLM_MRES_ALL_DONE 0x04
/*
* We would like to get one whole lockres into a single network
* message whenever possible. Generally speaking, there will be
* at most one dlm_lock on a lockres for each node in the cluster,
* plus (infrequently) any additional locks coming in from userdlm.
*
* struct _dlm_lockres_page
* {
* dlm_migratable_lockres mres;
* dlm_migratable_lock ml[DLM_MAX_MIGRATABLE_LOCKS];
* u8 pad[DLM_MIG_LOCKRES_RESERVED];
* };
*
* from ../cluster/tcp.h
* NET_MAX_PAYLOAD_BYTES (4096 - sizeof(net_msg))
* (roughly 4080 bytes)
* and sizeof(dlm_migratable_lockres) = 112 bytes
* and sizeof(dlm_migratable_lock) = 16 bytes
*
* Choosing DLM_MAX_MIGRATABLE_LOCKS=240 and
* DLM_MIG_LOCKRES_RESERVED=128 means we have this:
*
* (DLM_MAX_MIGRATABLE_LOCKS * sizeof(dlm_migratable_lock)) +
* sizeof(dlm_migratable_lockres) + DLM_MIG_LOCKRES_RESERVED =
* NET_MAX_PAYLOAD_BYTES
* (240 * 16) + 112 + 128 = 4080
*
* So a lockres would need more than 240 locks before it would
* use more than one network packet to recover. Not too bad.
*/
#define DLM_MAX_MIGRATABLE_LOCKS 240
struct dlm_migratable_lockres
{
u8 master;
u8 lockname_len;
u8 num_locks; // locks sent in this structure
u8 flags;
__be32 total_locks; // locks to be sent for this migration cookie
__be64 mig_cookie; // cookie for this lockres migration
// or zero if not needed
// 16 bytes
u8 lockname[DLM_LOCKID_NAME_MAX];
// 48 bytes
u8 lvb[DLM_LVB_LEN];
// 112 bytes
struct dlm_migratable_lock ml[0]; // 16 bytes each, begins at byte 112
};
#define DLM_MIG_LOCKRES_MAX_LEN \
(sizeof(struct dlm_migratable_lockres) + \
(sizeof(struct dlm_migratable_lock) * \
DLM_MAX_MIGRATABLE_LOCKS) )
/* from above, 128 bytes
* for some undetermined future use */
#define DLM_MIG_LOCKRES_RESERVED (NET_MAX_PAYLOAD_BYTES - \
DLM_MIG_LOCKRES_MAX_LEN)
struct dlm_create_lock
{
__be64 cookie;
__be32 flags;
u8 pad1;
u8 node_idx;
s8 requested_type;
u8 namelen;
u8 name[O2NM_MAX_NAME_LEN];
};
struct dlm_convert_lock
{
__be64 cookie;
__be32 flags;
u8 pad1;
u8 node_idx;
s8 requested_type;
u8 namelen;
u8 name[O2NM_MAX_NAME_LEN];
s8 lvb[0];
};
#define DLM_CONVERT_LOCK_MAX_LEN (sizeof(struct dlm_convert_lock)+DLM_LVB_LEN)
struct dlm_unlock_lock
{
__be64 cookie;
__be32 flags;
__be16 pad1;
u8 node_idx;
u8 namelen;
u8 name[O2NM_MAX_NAME_LEN];
s8 lvb[0];
};
#define DLM_UNLOCK_LOCK_MAX_LEN (sizeof(struct dlm_unlock_lock)+DLM_LVB_LEN)
struct dlm_proxy_ast
{
__be64 cookie;
__be32 flags;
u8 node_idx;
u8 type;
u8 blocked_type;
u8 namelen;
u8 name[O2NM_MAX_NAME_LEN];
s8 lvb[0];
};
#define DLM_PROXY_AST_MAX_LEN (sizeof(struct dlm_proxy_ast)+DLM_LVB_LEN)
#define DLM_MOD_KEY (0x666c6172)
enum dlm_query_join_response_code {
JOIN_DISALLOW = 0,
JOIN_OK,
JOIN_OK_NO_MAP,
JOIN_PROTOCOL_MISMATCH,
};
struct dlm_query_join_packet {
u8 code; /* Response code. dlm_minor and fs_minor
are only valid if this is JOIN_OK */
u8 dlm_minor; /* The minor version of the protocol the
dlm is speaking. */
u8 fs_minor; /* The minor version of the protocol the
filesystem is speaking. */
u8 reserved;
};
union dlm_query_join_response {
u32 intval;
struct dlm_query_join_packet packet;
};
struct dlm_lock_request
{
u8 node_idx;
u8 dead_node;
__be16 pad1;
__be32 pad2;
};
struct dlm_reco_data_done
{
u8 node_idx;
u8 dead_node;
__be16 pad1;
__be32 pad2;
/* unused for now */
/* eventually we can use this to attempt
* lvb recovery based on each node's info */
u8 reco_lvb[DLM_LVB_LEN];
};
struct dlm_begin_reco
{
u8 node_idx;
u8 dead_node;
__be16 pad1;
__be32 pad2;
};
#define BITS_PER_BYTE 8
#define BITS_TO_BYTES(bits) (((bits)+BITS_PER_BYTE-1)/BITS_PER_BYTE)
struct dlm_query_join_request
{
u8 node_idx;
u8 pad1[2];
u8 name_len;
struct dlm_protocol_version dlm_proto;
struct dlm_protocol_version fs_proto;
u8 domain[O2NM_MAX_NAME_LEN];
u8 node_map[BITS_TO_BYTES(O2NM_MAX_NODES)];
};
struct dlm_assert_joined
{
u8 node_idx;
u8 pad1[2];
u8 name_len;
u8 domain[O2NM_MAX_NAME_LEN];
};
struct dlm_cancel_join
{
u8 node_idx;
u8 pad1[2];
u8 name_len;
u8 domain[O2NM_MAX_NAME_LEN];
};
struct dlm_exit_domain
{
u8 node_idx;
u8 pad1[3];
};
struct dlm_finalize_reco
{
u8 node_idx;
u8 dead_node;
u8 flags;
u8 pad1;
__be32 pad2;
};
struct dlm_deref_lockres
{
u32 pad1;
u16 pad2;
u8 node_idx;
u8 namelen;
u8 name[O2NM_MAX_NAME_LEN];
};
static inline enum dlm_status
__dlm_lockres_state_to_status(struct dlm_lock_resource *res)
{
enum dlm_status status = DLM_NORMAL;
assert_spin_locked(&res->spinlock);
if (res->state & DLM_LOCK_RES_RECOVERING)
status = DLM_RECOVERING;
else if (res->state & DLM_LOCK_RES_MIGRATING)
status = DLM_MIGRATING;
else if (res->state & DLM_LOCK_RES_IN_PROGRESS)
status = DLM_FORWARD;
return status;
}
static inline u8 dlm_get_lock_cookie_node(u64 cookie)
{
u8 ret;
cookie >>= 56;
ret = (u8)(cookie & 0xffULL);
return ret;
}
static inline unsigned long long dlm_get_lock_cookie_seq(u64 cookie)
{
unsigned long long ret;
ret = ((unsigned long long)cookie) & 0x00ffffffffffffffULL;
return ret;
}
struct dlm_lock * dlm_new_lock(int type, u8 node, u64 cookie,
struct dlm_lockstatus *lksb);
void dlm_lock_get(struct dlm_lock *lock);
void dlm_lock_put(struct dlm_lock *lock);
void dlm_lock_attach_lockres(struct dlm_lock *lock,
struct dlm_lock_resource *res);
int dlm_create_lock_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_convert_lock_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_proxy_ast_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
void dlm_revert_pending_convert(struct dlm_lock_resource *res,
struct dlm_lock *lock);
void dlm_revert_pending_lock(struct dlm_lock_resource *res,
struct dlm_lock *lock);
int dlm_unlock_lock_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
void dlm_commit_pending_cancel(struct dlm_lock_resource *res,
struct dlm_lock *lock);
void dlm_commit_pending_unlock(struct dlm_lock_resource *res,
struct dlm_lock *lock);
int dlm_launch_thread(struct dlm_ctxt *dlm);
void dlm_complete_thread(struct dlm_ctxt *dlm);
int dlm_launch_recovery_thread(struct dlm_ctxt *dlm);
void dlm_complete_recovery_thread(struct dlm_ctxt *dlm);
void dlm_wait_for_recovery(struct dlm_ctxt *dlm);
void dlm_kick_recovery_thread(struct dlm_ctxt *dlm);
int dlm_is_node_dead(struct dlm_ctxt *dlm, u8 node);
int dlm_wait_for_node_death(struct dlm_ctxt *dlm, u8 node, int timeout);
int dlm_wait_for_node_recovery(struct dlm_ctxt *dlm, u8 node, int timeout);
void dlm_put(struct dlm_ctxt *dlm);
struct dlm_ctxt *dlm_grab(struct dlm_ctxt *dlm);
int dlm_domain_fully_joined(struct dlm_ctxt *dlm);
void __dlm_lockres_calc_usage(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res);
void dlm_lockres_calc_usage(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res);
static inline void dlm_lockres_get(struct dlm_lock_resource *res)
{
/* This is called on every lookup, so it might be worth
* inlining. */
kref_get(&res->refs);
}
void dlm_lockres_put(struct dlm_lock_resource *res);
void __dlm_unhash_lockres(struct dlm_lock_resource *res);
void __dlm_insert_lockres(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res);
struct dlm_lock_resource * __dlm_lookup_lockres_full(struct dlm_ctxt *dlm,
const char *name,
unsigned int len,
unsigned int hash);
struct dlm_lock_resource * __dlm_lookup_lockres(struct dlm_ctxt *dlm,
const char *name,
unsigned int len,
unsigned int hash);
struct dlm_lock_resource * dlm_lookup_lockres(struct dlm_ctxt *dlm,
const char *name,
unsigned int len);
int dlm_is_host_down(int errno);
struct dlm_lock_resource * dlm_get_lock_resource(struct dlm_ctxt *dlm,
const char *lockid,
int namelen,
int flags);
struct dlm_lock_resource *dlm_new_lockres(struct dlm_ctxt *dlm,
const char *name,
unsigned int namelen);
#define dlm_lockres_set_refmap_bit(bit,res) \
__dlm_lockres_set_refmap_bit(bit,res,__FILE__,__LINE__)
#define dlm_lockres_clear_refmap_bit(bit,res) \
__dlm_lockres_clear_refmap_bit(bit,res,__FILE__,__LINE__)
static inline void __dlm_lockres_set_refmap_bit(int bit,
struct dlm_lock_resource *res,
const char *file,
int line)
{
//printk("%s:%d:%.*s: setting bit %d\n", file, line,
// res->lockname.len, res->lockname.name, bit);
set_bit(bit, res->refmap);
}
static inline void __dlm_lockres_clear_refmap_bit(int bit,
struct dlm_lock_resource *res,
const char *file,
int line)
{
//printk("%s:%d:%.*s: clearing bit %d\n", file, line,
// res->lockname.len, res->lockname.name, bit);
clear_bit(bit, res->refmap);
}
void __dlm_lockres_drop_inflight_ref(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
const char *file,
int line);
void __dlm_lockres_grab_inflight_ref(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
int new_lockres,
const char *file,
int line);
#define dlm_lockres_drop_inflight_ref(d,r) \
__dlm_lockres_drop_inflight_ref(d,r,__FILE__,__LINE__)
#define dlm_lockres_grab_inflight_ref(d,r) \
__dlm_lockres_grab_inflight_ref(d,r,0,__FILE__,__LINE__)
#define dlm_lockres_grab_inflight_ref_new(d,r) \
__dlm_lockres_grab_inflight_ref(d,r,1,__FILE__,__LINE__)
void dlm_queue_ast(struct dlm_ctxt *dlm, struct dlm_lock *lock);
void dlm_queue_bast(struct dlm_ctxt *dlm, struct dlm_lock *lock);
void dlm_do_local_ast(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_lock *lock);
int dlm_do_remote_ast(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_lock *lock);
void dlm_do_local_bast(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_lock *lock,
int blocked_type);
int dlm_send_proxy_ast_msg(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_lock *lock,
int msg_type,
int blocked_type, int flags);
static inline int dlm_send_proxy_bast(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_lock *lock,
int blocked_type)
{
return dlm_send_proxy_ast_msg(dlm, res, lock, DLM_BAST,
blocked_type, 0);
}
static inline int dlm_send_proxy_ast(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_lock *lock,
int flags)
{
return dlm_send_proxy_ast_msg(dlm, res, lock, DLM_AST,
0, flags);
}
void dlm_print_one_lock_resource(struct dlm_lock_resource *res);
void __dlm_print_one_lock_resource(struct dlm_lock_resource *res);
u8 dlm_nm_this_node(struct dlm_ctxt *dlm);
void dlm_kick_thread(struct dlm_ctxt *dlm, struct dlm_lock_resource *res);
void __dlm_dirty_lockres(struct dlm_ctxt *dlm, struct dlm_lock_resource *res);
int dlm_nm_init(struct dlm_ctxt *dlm);
int dlm_heartbeat_init(struct dlm_ctxt *dlm);
void dlm_hb_node_down_cb(struct o2nm_node *node, int idx, void *data);
void dlm_hb_node_up_cb(struct o2nm_node *node, int idx, void *data);
int dlm_empty_lockres(struct dlm_ctxt *dlm, struct dlm_lock_resource *res);
int dlm_finish_migration(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
u8 old_master);
void dlm_lockres_release_ast(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res);
void __dlm_lockres_reserve_ast(struct dlm_lock_resource *res);
int dlm_master_request_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_assert_master_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
void dlm_assert_master_post_handler(int status, void *data, void *ret_data);
int dlm_deref_lockres_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_migrate_request_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_mig_lockres_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_master_requery_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_request_all_locks_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_reco_data_done_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_begin_reco_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_finalize_reco_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data);
int dlm_do_master_requery(struct dlm_ctxt *dlm, struct dlm_lock_resource *res,
u8 nodenum, u8 *real_master);
int dlm_dispatch_assert_master(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
int ignore_higher,
u8 request_from,
u32 flags);
int dlm_send_one_lockres(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_migratable_lockres *mres,
u8 send_to,
u8 flags);
void dlm_move_lockres_to_recovery_list(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res);
/* will exit holding res->spinlock, but may drop in function */
void __dlm_wait_on_lockres_flags(struct dlm_lock_resource *res, int flags);
void __dlm_wait_on_lockres_flags_set(struct dlm_lock_resource *res, int flags);
/* will exit holding res->spinlock, but may drop in function */
static inline void __dlm_wait_on_lockres(struct dlm_lock_resource *res)
{
__dlm_wait_on_lockres_flags(res, (DLM_LOCK_RES_IN_PROGRESS|
DLM_LOCK_RES_RECOVERING|
DLM_LOCK_RES_MIGRATING));
}
void __dlm_unlink_mle(struct dlm_ctxt *dlm, struct dlm_master_list_entry *mle);
void __dlm_insert_mle(struct dlm_ctxt *dlm, struct dlm_master_list_entry *mle);
/* create/destroy slab caches */
int dlm_init_master_caches(void);
void dlm_destroy_master_caches(void);
int dlm_init_lock_cache(void);
void dlm_destroy_lock_cache(void);
int dlm_init_mle_cache(void);
void dlm_destroy_mle_cache(void);
void dlm_hb_event_notify_attached(struct dlm_ctxt *dlm, int idx, int node_up);
int dlm_drop_lockres_ref(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res);
void dlm_clean_master_list(struct dlm_ctxt *dlm,
u8 dead_node);
int dlm_lock_basts_flushed(struct dlm_ctxt *dlm, struct dlm_lock *lock);
int __dlm_lockres_has_locks(struct dlm_lock_resource *res);
int __dlm_lockres_unused(struct dlm_lock_resource *res);
static inline const char * dlm_lock_mode_name(int mode)
{
switch (mode) {
case LKM_EXMODE:
return "EX";
case LKM_PRMODE:
return "PR";
case LKM_NLMODE:
return "NL";
}
return "UNKNOWN";
}
static inline int dlm_lock_compatible(int existing, int request)
{
/* NO_LOCK compatible with all */
if (request == LKM_NLMODE ||
existing == LKM_NLMODE)
return 1;
/* EX incompatible with all non-NO_LOCK */
if (request == LKM_EXMODE)
return 0;
/* request must be PR, which is compatible with PR */
if (existing == LKM_PRMODE)
return 1;
return 0;
}
static inline int dlm_lock_on_list(struct list_head *head,
struct dlm_lock *lock)
{
struct list_head *iter;
struct dlm_lock *tmplock;
list_for_each(iter, head) {
tmplock = list_entry(iter, struct dlm_lock, list);
if (tmplock == lock)
return 1;
}
return 0;
}
static inline enum dlm_status dlm_err_to_dlm_status(int err)
{
enum dlm_status ret;
if (err == -ENOMEM)
ret = DLM_SYSERR;
else if (err == -ETIMEDOUT || o2net_link_down(err, NULL))
ret = DLM_NOLOCKMGR;
else if (err == -EINVAL)
ret = DLM_BADPARAM;
else if (err == -ENAMETOOLONG)
ret = DLM_IVBUFLEN;
else
ret = DLM_BADARGS;
return ret;
}
static inline void dlm_node_iter_init(unsigned long *map,
struct dlm_node_iter *iter)
{
memcpy(iter->node_map, map, sizeof(iter->node_map));
iter->curnode = -1;
}
static inline int dlm_node_iter_next(struct dlm_node_iter *iter)
{
int bit;
bit = find_next_bit(iter->node_map, O2NM_MAX_NODES, iter->curnode+1);
if (bit >= O2NM_MAX_NODES) {
iter->curnode = O2NM_MAX_NODES;
return -ENOENT;
}
iter->curnode = bit;
return bit;
}
static inline void dlm_set_lockres_owner(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
u8 owner)
{
assert_spin_locked(&res->spinlock);
res->owner = owner;
}
static inline void dlm_change_lockres_owner(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
u8 owner)
{
assert_spin_locked(&res->spinlock);
if (owner != res->owner)
dlm_set_lockres_owner(dlm, res, owner);
}
#endif /* DLMCOMMON_H */
| {
"pile_set_name": "Github"
} |
<?pi data?>
<!DOCTYPE doc [
<!ELEMENT doc (#PCDATA)>
]>
<doc></doc>
| {
"pile_set_name": "Github"
} |
{
"name": "sebastian/diff",
"description": "Diff implementation",
"keywords": ["diff"],
"homepage": "http://www.github.com/sebastianbergmann/diff",
"license": "BSD-3-Clause",
"authors": [
{
"name": "Sebastian Bergmann",
"email": "[email protected]"
},
{
"name": "Kore Nordmann",
"email": "[email protected]"
}
],
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"phpunit/phpunit": "~4.2"
},
"autoload": {
"classmap": [
"src/"
]
},
"extra": {
"branch-alias": {
"dev-master": "1.2-dev"
}
}
}
| {
"pile_set_name": "Github"
} |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * auth_signup
#
# Translators:
# ສີສຸວັນ ສັງບົວບຸລົມ <[email protected]>, 2020
# Martin Trigaux, 2020
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server saas~12.5\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-08-26 08:16+0000\n"
"PO-Revision-Date: 2019-08-26 09:09+0000\n"
"Last-Translator: Martin Trigaux, 2020\n"
"Language-Team: Lao (https://www.transifex.com/odoo/teams/41243/lo/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Language: lo\n"
"Plural-Forms: nplurals=1; plural=0;\n"
#. module: auth_signup
#: model:mail.template,subject:auth_signup.set_password_email
msgid ""
"${object.create_uid.name} from ${object.company_id.name} invites you to "
"connect to Odoo"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/models/res_users.py:0
#, python-format
msgid "%s connected"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.res_users_view_form
msgid ""
"<strong>A password reset has been requested for this user. An email "
"containing the following link has been sent:</strong>"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.res_users_view_form
msgid ""
"<strong>An invitation email containing the following subscription link has "
"been sent:</strong>"
msgstr ""
#. module: auth_signup
#: model:mail.template,body_html:auth_signup.mail_template_data_unregistered_users
msgid ""
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"background-color: #F1F1F1; font-family:Verdana, Arial,sans-serif; color: #454748; width: 100%; border-collapse:separate;\"><tr><td align=\"center\">\n"
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"padding: 16px; background-color: white; color: #454748; border-collapse:separate;\">\n"
"<tbody>\n"
" <!-- CONTENT -->\n"
" <tr>\n"
" <td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: white; padding: 0px 8px 0px 8px; border-collapse:separate;\">\n"
" % set invited_users = ctx['invited_users']\n"
" <td style=\"text-align : left\">\n"
" <span style=\"font-size: 20px; font-weight: bold;\">\n"
" Pending Invitations\n"
" </span><br/><br/>\n"
" </td>\n"
" <tr><td valign=\"top\" style=\"font-size: 13px;\">\n"
" <div>\n"
" Dear ${object.name or ''},<br/> <br/>\n"
" You added the following user(s) to your database but they haven't registered yet:\n"
" <ul>\n"
" % for invited_user in invited_users:\n"
" <li>${invited_user}</li>\n"
" % endfor\n"
" </ul>\n"
" Follow up with them so they can access your database and start working with you.\n"
" <br/><br/>\n"
" Have a nice day!<br/>\n"
" --<br/>The ${object.company_id.name} Team\n"
" </div>\n"
" </td></tr>\n"
" <tr><td style=\"text-align:center;\">\n"
" <hr width=\"100%\" style=\"background-color:rgb(204,204,204);border:medium none;clear:both;display:block;font-size:0px;min-height:1px;line-height:0; margin: 16px 0px 16px 0px;\"/>\n"
" </td></tr>\n"
" </table>\n"
" </td>\n"
" </tr>\n"
"</tbody>\n"
"</table>\n"
"</td></tr>\n"
"</table>\n"
" "
msgstr ""
#. module: auth_signup
#: model:mail.template,body_html:auth_signup.set_password_email
msgid ""
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"padding-top: 16px; background-color: #F1F1F1; font-family:Verdana, Arial,sans-serif; color: #454748; width: 100%; border-collapse:separate;\"><tr><td align=\"center\">\n"
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"padding: 16px; background-color: white; color: #454748; border-collapse:separate;\">\n"
"<tbody>\n"
" <!-- HEADER -->\n"
" <tr>\n"
" <td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: white; padding: 0px 8px 0px 8px; border-collapse:separate;\">\n"
" <tr><td valign=\"middle\">\n"
" <span style=\"font-size: 10px;\">Welcome to Odoo</span><br/>\n"
" <span style=\"font-size: 20px; font-weight: bold;\">\n"
" ${object.name}\n"
" </span>\n"
" </td><td valign=\"middle\" align=\"right\">\n"
" <img src=\"/logo.png?company=${object.company_id.id}\" style=\"padding: 0px; margin: 0px; height: auto; width: 80px;\" alt=\"${object.company_id.name}\"/>\n"
" </td></tr>\n"
" <tr><td colspan=\"2\" style=\"text-align:center;\">\n"
" <hr width=\"100%\" style=\"background-color:rgb(204,204,204);border:medium none;clear:both;display:block;font-size:0px;min-height:1px;line-height:0; margin: 16px 0px 16px 0px;\"/>\n"
" </td></tr>\n"
" </table>\n"
" </td>\n"
" </tr>\n"
" <!-- CONTENT -->\n"
" <tr>\n"
" <td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: white; padding: 0px 8px 0px 8px; border-collapse:separate;\">\n"
" <tr><td valign=\"top\" style=\"font-size: 13px;\">\n"
" <div>\n"
" Dear ${object.name},<br/><br/>\n"
" You have been invited by ${object.create_uid.name} of ${object.company_id.name} to connect on Odoo.\n"
" <div style=\"margin: 16px 0px 16px 0px;\">\n"
" <a href=\"${object.signup_url}\" style=\"background-color: #875A7B; padding: 8px 16px 8px 16px; text-decoration: none; color: #fff; border-radius: 5px; font-size:13px;\">\n"
" Accept invitation\n"
" </a>\n"
" </div>\n"
" % set website_url = object.env['ir.config_parameter'].sudo().get_param('web.base.url')\n"
" Your Odoo domain is: <b><a href=\"${website_url}\">${website_url}</a></b><br/>\n"
" Your sign in email is: <b><a href=\"/web/login?login=${object.email}\" target=\"_blank\">${object.email}</a></b><br/><br/>\n"
" Never heard of Odoo? It’s an all-in-one business software loved by 3+ million users. It will considerably improve your experience at work and increase your productivity.\n"
" <br/><br/>\n"
" Have a look at the <a href=\"https://www.odoo.com/page/tour?utm_source=db&utm_medium=auth\" style=\"color: #875A7B;\">Odoo Tour</a> to discover the tool.\n"
" <br/><br/>\n"
" Enjoy Odoo!<br/>\n"
" --<br/>The ${object.company_id.name} Team\n"
" </div>\n"
" </td></tr>\n"
" <tr><td style=\"text-align:center;\">\n"
" <hr width=\"100%\" style=\"background-color:rgb(204,204,204);border:medium none;clear:both;display:block;font-size:0px;min-height:1px;line-height:0; margin: 16px 0px 16px 0px;\"/>\n"
" </td></tr>\n"
" </table>\n"
" </td>\n"
" </tr>\n"
" <!-- FOOTER -->\n"
" <tr>\n"
" <td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: white; font-size: 11px; padding: 0px 8px 0px 8px; border-collapse:separate;\">\n"
" <tr><td valign=\"middle\" align=\"left\">\n"
" ${object.company_id.name}\n"
" </td></tr>\n"
" <tr><td valign=\"middle\" align=\"left\" style=\"opacity: 0.7;\">\n"
" ${object.company_id.phone}\n"
" % if object.company_id.email\n"
" | <a href=\"'mailto:%s' % ${object.company_id.email}\" style=\"text-decoration:none; color: #454748;\">${object.company_id.email}</a>\n"
" % endif\n"
" % if object.company_id.website\n"
" | <a href=\"'%s' % ${object.company_id.website}\" style=\"text-decoration:none; color: #454748;\">\n"
" ${object.company_id.website}\n"
" </a>\n"
" % endif\n"
" </td></tr>\n"
" </table>\n"
" </td>\n"
" </tr>\n"
"</tbody>\n"
"</table>\n"
"</td></tr>\n"
"<!-- POWERED BY -->\n"
"<tr><td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: #F1F1F1; color: #454748; padding: 8px; border-collapse:separate;\">\n"
" <tr><td style=\"text-align: center; font-size: 13px;\">\n"
" Powered by <a target=\"_blank\" href=\"https://www.odoo.com?utm_source=db&utm_medium=auth\" style=\"color: #875A7B;\">Odoo</a>\n"
" </td></tr>\n"
" </table>\n"
"</td></tr>\n"
"</table>"
msgstr ""
#. module: auth_signup
#: model:mail.template,body_html:auth_signup.reset_password_email
msgid ""
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"padding-top: 16px; background-color: #F1F1F1; font-family:Verdana, Arial,sans-serif; color: #454748; width: 100%; border-collapse:separate;\"><tr><td align=\"center\">\n"
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"padding: 16px; background-color: white; color: #454748; border-collapse:separate;\">\n"
"<tbody>\n"
" <!-- HEADER -->\n"
" <tr>\n"
" <td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: white; padding: 0px 8px 0px 8px; border-collapse:separate;\">\n"
" <tr><td valign=\"middle\">\n"
" <span style=\"font-size: 10px;\">Your Account</span><br/>\n"
" <span style=\"font-size: 20px; font-weight: bold;\">\n"
" ${object.name}\n"
" </span>\n"
" </td><td valign=\"middle\" align=\"right\">\n"
" <img src=\"/logo.png?company=${object.company_id.id}\" style=\"padding: 0px; margin: 0px; height: auto; width: 80px;\" alt=\"${object.company_id.name}\"/>\n"
" </td></tr>\n"
" <tr><td colspan=\"2\" style=\"text-align:center;\">\n"
" <hr width=\"100%\" style=\"background-color:rgb(204,204,204);border:medium none;clear:both;display:block;font-size:0px;min-height:1px;line-height:0; margin: 16px 0px 16px 0px;\"/>\n"
" </td></tr>\n"
" </table>\n"
" </td>\n"
" </tr>\n"
" <!-- CONTENT -->\n"
" <tr>\n"
" <td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: white; padding: 0px 8px 0px 8px; border-collapse:separate;\">\n"
" <tr><td valign=\"top\" style=\"font-size: 13px;\">\n"
" <div>\n"
" Dear ${object.name},<br/><br/>\n"
" A password reset was requested for the Odoo account linked to this email.\n"
" You may change your password by following this link which will remain valid during 24 hours:<br/>\n"
" <div style=\"margin: 16px 0px 16px 0px;\">\n"
" <a href=\"${object.signup_url}\" style=\"background-color: #875A7B; padding: 8px 16px 8px 16px; text-decoration: none; color: #fff; border-radius: 5px; font-size:13px;\">\n"
" Change password\n"
" </a>\n"
" </div>\n"
" If you do not expect this, you can safely ignore this email.<br/><br/>\n"
" Thanks,<br/>\n"
" ${user.signature | safe}<br/>\n"
" </div>\n"
" </td></tr>\n"
" <tr><td style=\"text-align:center;\">\n"
" <hr width=\"100%\" style=\"background-color:rgb(204,204,204);border:medium none;clear:both;display:block;font-size:0px;min-height:1px;line-height:0; margin: 16px 0px 16px 0px;\"/>\n"
" </td></tr>\n"
" </table>\n"
" </td>\n"
" </tr>\n"
" <!-- FOOTER -->\n"
" <tr>\n"
" <td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: white; font-size: 11px; padding: 0px 8px 0px 8px; border-collapse:separate;\">\n"
" <tr><td valign=\"middle\" align=\"left\">\n"
" ${object.company_id.name}\n"
" </td></tr>\n"
" <tr><td valign=\"middle\" align=\"left\" style=\"opacity: 0.7;\">\n"
" ${object.company_id.phone}\n"
" % if object.company_id.email\n"
" | <a href=\"'mailto:%s' % ${object.company_id.email}\" style=\"text-decoration:none; color: #454748;\">${object.company_id.email}</a>\n"
" % endif\n"
" % if object.company_id.website\n"
" | <a href=\"'%s' % ${object.company_id.website}\" style=\"text-decoration:none; color: #454748;\">\n"
" ${object.company_id.website}\n"
" </a>\n"
" % endif\n"
" </td></tr>\n"
" </table>\n"
" </td>\n"
" </tr>\n"
"</tbody>\n"
"</table>\n"
"</td></tr>\n"
"<!-- POWERED BY -->\n"
"<tr><td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: #F1F1F1; color: #454748; padding: 8px; border-collapse:separate;\">\n"
" <tr><td style=\"text-align: center; font-size: 13px;\">\n"
" Powered by <a target=\"_blank\" href=\"https://www.odoo.com?utm_source=db&utm_medium=auth\" style=\"color: #875A7B;\">Odoo</a>\n"
" </td></tr>\n"
" </table>\n"
"</td></tr>\n"
"</table>\n"
" "
msgstr ""
#. module: auth_signup
#: model:mail.template,body_html:auth_signup.mail_template_user_signup_account_created
msgid ""
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"padding-top: 16px; background-color: #F1F1F1; font-family:Verdana, Arial,sans-serif; color: #454748; width: 100%; border-collapse:separate;\"><tr><td align=\"center\">\n"
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"padding: 16px; background-color: white; color: #454748; border-collapse:separate;\">\n"
"<tbody>\n"
" <!-- HEADER -->\n"
" <tr>\n"
" <td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: white; padding: 0px 8px 0px 8px; border-collapse:separate;\">\n"
" <tr><td valign=\"middle\">\n"
" <span style=\"font-size: 10px;\">Your Account</span><br/>\n"
" <span style=\"font-size: 20px; font-weight: bold;\">\n"
" ${object.name}\n"
" </span>\n"
" </td><td valign=\"middle\" align=\"right\">\n"
" <img src=\"/logo.png?company=${object.company_id.id}\" style=\"padding: 0px; margin: 0px; height: auto; width: 80px;\" alt=\"${object.company_id.name}\"/>\n"
" </td></tr>\n"
" <tr><td colspan=\"2\" style=\"text-align:center;\">\n"
" <hr width=\"100%\" style=\"background-color:rgb(204,204,204);border:medium none;clear:both;display:block;font-size:0px;min-height:1px;line-height:0; margin: 16px 0px 16px 0px;\"/>\n"
" </td></tr>\n"
" </table>\n"
" </td>\n"
" </tr>\n"
" <!-- CONTENT -->\n"
" <tr>\n"
" <td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: white; padding: 0px 8px 0px 8px; border-collapse:separate;\">\n"
" <tr><td valign=\"top\" style=\"font-size: 13px;\">\n"
" <div>\n"
" Dear ${object.name},<br/><br/>\n"
" Your account has been successfully created!<br/>\n"
" Your login is <strong>${object.email}</strong><br/>\n"
" To gain access to your account, you can use the following link:\n"
" <div style=\"margin: 16px 0px 16px 0px;\">\n"
" <a href=\"/web/login?${ctx['auth_login']}\" style=\"background-color: #875A7B; padding: 8px 16px 8px 16px; text-decoration: none; color: #fff; border-radius: 5px; font-size:13px;\">\n"
" Go to My Account\n"
" </a>\n"
" </div>\n"
" Thanks,<br/><br/>\n"
" ${user.signature | safe}<br/>\n"
" </div>\n"
" </td></tr>\n"
" <tr><td style=\"text-align:center;\">\n"
" <hr width=\"100%\" style=\"background-color:rgb(204,204,204);border:medium none;clear:both;display:block;font-size:0px;min-height:1px;line-height:0; margin: 16px 0px 16px 0px;\"/>\n"
" </td></tr>\n"
" </table>\n"
" </td>\n"
" </tr>\n"
" <!-- FOOTER -->\n"
" <tr>\n"
" <td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: white; font-size: 11px; padding: 0px 8px 0px 8px; border-collapse:separate;\">\n"
" <tr><td valign=\"middle\" align=\"left\">\n"
" ${object.company_id.name}\n"
" </td></tr>\n"
" <tr><td valign=\"middle\" align=\"left\" style=\"opacity: 0.7;\">\n"
" ${object.company_id.phone}\n"
" % if object.company_id.email\n"
" | <a href=\"'mailto:%s' % ${object.company_id.email}\" style=\"text-decoration:none; color: #454748;\">${object.company_id.email}</a>\n"
" % endif\n"
" % if object.company_id.website\n"
" | <a href=\"'%s' % ${object.company_id.website}\" style=\"text-decoration:none; color: #454748;\">\n"
" ${object.company_id.website}\n"
" </a>\n"
" % endif\n"
" </td></tr>\n"
" </table>\n"
" </td>\n"
" </tr>\n"
"</tbody>\n"
"</table>\n"
"</td></tr>\n"
"<!-- POWERED BY -->\n"
"<tr><td align=\"center\" style=\"min-width: 590px;\">\n"
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"590\" style=\"min-width: 590px; background-color: #F1F1F1; color: #454748; padding: 8px; border-collapse:separate;\">\n"
" <tr><td style=\"text-align: center; font-size: 13px;\">\n"
" Powered by <a target=\"_blank\" href=\"https://www.odoo.com?utm_source=db&utm_medium=auth\" style=\"color: #875A7B;\">Odoo</a>\n"
" </td></tr>\n"
" </table>\n"
"</td></tr>\n"
"</table>"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.signup
msgid "Already have an account?"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/controllers/main.py:0
#, python-format
msgid "An email has been sent with credentials to reset your password"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/controllers/main.py:0
#, python-format
msgid "Another user is already registered using this email address."
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/controllers/main.py:0
#, python-format
msgid "Authentication Failed."
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.reset_password
msgid "Back to Login"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/models/res_users.py:0
#, python-format
msgid "Cannot send email: user %s has no email address."
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.res_users_view_form
msgid "Close"
msgstr "ອັດ"
#. module: auth_signup
#: model:ir.model,name:auth_signup.model_res_config_settings
msgid "Config Settings"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.reset_password
msgid "Confirm"
msgstr "ຢືນຢັນ"
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.fields
msgid "Confirm Password"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields.selection,name:auth_signup.selection__res_users__state__active
msgid "Confirmed"
msgstr "ຮັບຮູ້ເເລັວ"
#. module: auth_signup
#: model:ir.model,name:auth_signup.model_res_partner
msgid "Contact"
msgstr "ທີ່ຕິດຕໍ່່"
#. module: auth_signup
#: code:addons/auth_signup/controllers/main.py:0
#, python-format
msgid "Could not create a new account."
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/controllers/main.py:0
#, python-format
msgid "Could not reset your password"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields,field_description:auth_signup.field_res_config_settings__auth_signup_uninvited
msgid "Customer Account"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.res_config_settings_view_form
msgid "Default Access Rights"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.login
msgid "Don't have an account?"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields,field_description:auth_signup.field_res_config_settings__auth_signup_reset_password
#: model_terms:ir.ui.view,arch_db:auth_signup.res_config_settings_view_form
msgid "Enable password reset from Login page"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields.selection,name:auth_signup.selection__res_config_settings__auth_signup_uninvited__b2c
msgid "Free sign up"
msgstr ""
#. module: auth_signup
#: model:ir.model,name:auth_signup.model_ir_http
msgid "HTTP Routing"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/controllers/main.py:0
#, python-format
msgid "Invalid signup token"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.res_config_settings_view_form
msgid "Let your customers log in to see their documents"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields.selection,name:auth_signup.selection__res_users__state__new
msgid "Never Connected"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/controllers/main.py:0
#, python-format
msgid "No login provided."
msgstr ""
#. module: auth_signup
#: model:ir.model.fields.selection,name:auth_signup.selection__res_config_settings__auth_signup_uninvited__b2b
msgid "On invitation"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.fields
msgid "Password"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.res_config_settings_view_form
msgid "Password Reset"
msgstr ""
#. module: auth_signup
#: model:mail.template,subject:auth_signup.reset_password_email
msgid "Password reset"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/controllers/main.py:0
#, python-format
msgid "Passwords do not match; please retype them."
msgstr ""
#. module: auth_signup
#: model:mail.template,subject:auth_signup.mail_template_data_unregistered_users
msgid "Reminder for unregistered users"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.login
msgid "Reset Password"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/models/res_users.py:0
#, python-format
msgid "Reset password: invalid username or email"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.res_users_view_form
msgid "Send Reset Password Instructions"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.res_users_view_form
msgid "Send an Invitation Email"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.signup
msgid "Sign up"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields,field_description:auth_signup.field_res_partner__signup_expiration
#: model:ir.model.fields,field_description:auth_signup.field_res_users__signup_expiration
msgid "Signup Expiration"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields,field_description:auth_signup.field_res_partner__signup_token
#: model:ir.model.fields,field_description:auth_signup.field_res_users__signup_token
msgid "Signup Token"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields,field_description:auth_signup.field_res_partner__signup_type
#: model:ir.model.fields,field_description:auth_signup.field_res_users__signup_type
msgid "Signup Token Type"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields,field_description:auth_signup.field_res_partner__signup_valid
#: model:ir.model.fields,field_description:auth_signup.field_res_users__signup_valid
msgid "Signup Token is Valid"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields,field_description:auth_signup.field_res_partner__signup_url
#: model:ir.model.fields,field_description:auth_signup.field_res_users__signup_url
msgid "Signup URL"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/models/res_users.py:0
#, python-format
msgid "Signup is not allowed for uninvited users"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/models/res_partner.py:0
#, python-format
msgid "Signup token '%s' is no longer valid"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/models/res_partner.py:0
#, python-format
msgid "Signup token '%s' is not valid"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/models/res_users.py:0
#, python-format
msgid "Signup: invalid template user"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/models/res_users.py:0
#, python-format
msgid "Signup: no login given for new user"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/models/res_users.py:0
#, python-format
msgid "Signup: no name or partner given for new user"
msgstr ""
#. module: auth_signup
#: model:ir.model.fields,field_description:auth_signup.field_res_users__state
msgid "Status"
msgstr "ສະພາບ"
#. module: auth_signup
#: model:ir.model.fields,field_description:auth_signup.field_res_config_settings__auth_signup_template_user_id
msgid "Template user for new users created through signup"
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/controllers/main.py:0
#, python-format
msgid "The form was not properly filled in."
msgstr ""
#. module: auth_signup
#: code:addons/auth_signup/models/res_users.py:0
#, python-format
msgid "This is his first connection. Wish him welcome"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.res_config_settings_view_form
msgid ""
"To send invitations in B2B mode, open a contact or select several ones in "
"list view and click on 'Portal Access Management' option in the dropdown "
"menu *Action*."
msgstr ""
#. module: auth_signup
#: model:ir.model,name:auth_signup.model_res_users
msgid "Users"
msgstr "ຜູ້ໃຊ້ງານ"
#. module: auth_signup
#: model:ir.actions.server,name:auth_signup.ir_cron_auth_signup_send_pending_user_reminder_ir_actions_server
#: model:ir.cron,cron_name:auth_signup.ir_cron_auth_signup_send_pending_user_reminder
#: model:ir.cron,name:auth_signup.ir_cron_auth_signup_send_pending_user_reminder
msgid "Users: Notify About Unregistered Users"
msgstr ""
#. module: auth_signup
#: model:mail.template,subject:auth_signup.mail_template_user_signup_account_created
msgid "Welcome to ${object.company_id.name}!"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.fields
#: model_terms:ir.ui.view,arch_db:auth_signup.reset_password
msgid "Your Email"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.fields
msgid "Your Name"
msgstr ""
#. module: auth_signup
#: model_terms:ir.ui.view,arch_db:auth_signup.fields
msgid "e.g. John Doe"
msgstr ""
| {
"pile_set_name": "Github"
} |
.CodeMirror-foldmarker {
color: blue;
text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px;
font-family: arial;
line-height: .3;
cursor: pointer;
}
.CodeMirror-foldgutter {
width: .7em;
}
.CodeMirror-foldgutter-open,
.CodeMirror-foldgutter-folded {
cursor: pointer;
}
.CodeMirror-foldgutter-open:after {
content: "\25BE";
}
.CodeMirror-foldgutter-folded:after {
content: "\25B8";
}
| {
"pile_set_name": "Github"
} |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
using module .\..\..\Common\Common.psm1
using module .\..\UserRightRule.psm1
$exclude = @($MyInvocation.MyCommand.Name,'Template.*.txt')
$supportFileList = Get-ChildItem -Path $PSScriptRoot -Exclude $exclude
foreach ($supportFile in $supportFileList)
{
Write-Verbose "Loading $($supportFile.FullName)"
. $supportFile.FullName
}
# Header
<#
.SYNOPSIS
Convert the contents of an xccdf check-content element into a user right object
.DESCRIPTION
The UserRightRule class is used to extract the {} settings from the
check-content of the xccdf. Once a STIG rule is identified a
user right rule, it is passed to the UserRightRule class for parsing
and validation.
#>
class UserRightRuleConvert : UserRightRule
{
<#
.SYNOPSIS
Empty constructor for SplitFactory
#>
UserRightRuleConvert ()
{
}
<#
.SYNOPSIS
Converts a xccdf STIG rule element into a User Right Rule
.PARAMETER XccdfRule
The STIG rule to convert
#>
UserRightRuleConvert ([xml.xmlelement] $XccdfRule) : base ($XccdfRule, $true)
{
$this.SetDisplayName()
$this.SetConstant()
$this.SetIdentity()
$this.SetForce()
$this.SetDuplicateRule()
if (Test-ExistingRule -RuleCollection $global:stigSettings -NewRule $this)
{
$this.set_id((Get-AvailableId -Id $this.Id))
}
$this.SetDscResource()
}
#region Methods
<#
.SYNOPSIS
Extracts the display name from the check-content and sets the value
.DESCRIPTION
Gets the display name from the xccdf content and sets the value. If
the name that is returned is not valid, the parser status is set to fail.
#>
[void] SetDisplayName ()
{
$thisDisplayName = Get-UserRightDisplayName -CheckContent $this.SplitCheckContent
if (-not $this.SetStatus($thisDisplayName))
{
$this.set_DisplayName($thisDisplayName)
}
}
<#
.SYNOPSIS
Extracts the user right constant from the check-content and sets the value
.DESCRIPTION
Gets the user right constant from the xccdf content and sets the
value. If the constant that is returned is not valid, the parser
status is set to fail.
#>
[void] SetConstant ()
{
$thisConstant = Get-UserRightConstant -UserRightDisplayName $this.DisplayName
if (-not $this.SetStatus($thisConstant))
{
$this.set_Constant($thisConstant)
}
}
<#
.SYNOPSIS
Extracts the user right identity from the check-content and sets the value
.DESCRIPTION
Gets the user right identity from the xccdf content and sets the
value. If the identity that is returned is not valid, the parser
status is set to fail.
#>
[void] SetIdentity ()
{
$thisIdentity = Get-UserRightIdentity -CheckContent $this.SplitCheckContent
$return = $true
if ([String]::IsNullOrEmpty($thisIdentity))
{
$return = $false
}
elseif ($thisIdentity -ne 'NULL')
{
if ($thisIdentity -join "," -match "{Hyper-V}")
{
$this.SetOrganizationValueRequired()
$HyperVIdentity = $thisIdentity -join "," -replace "{Hyper-V}", "NT Virtual Machine\\Virtual Machines"
$NoHyperVIdentity = $thisIdentity.Where( {$PSItem -ne "{Hyper-V}"}) -join ","
$this.set_OrganizationValueTestString("'{0}' -match '^($HyperVIdentity|$NoHyperVIdentity)$'")
}
elseif ($thisIdentity -contains "(Local account and member of Administrators group|Local account)")
{
$this.SetOrganizationValueRequired()
$this.set_OrganizationValueTestString("'{0}' -match '$($thisIdentity -join ",")'")
}
}
if ($this.OrganizationValueRequired -eq $false)
{
$this.Identity = $thisIdentity -Join ","
}
}
<#
.SYNOPSIS
Extracts the force flag from the check-content and sets the value
.DESCRIPTION
Gets the force flag from the xccdf content and sets the value
#>
[void] SetForce ()
{
if (Test-SetForceFlag -CheckContent $this.SplitCheckContent)
{
$this.set_Force($true)
}
else
{
$this.set_Force($false)
}
}
hidden [void] SetDscResource ()
{
if ($null -eq $this.DuplicateOf)
{
$this.DscResource = 'UserRightsAssignment'
}
else
{
$this.DscResource = 'None'
}
}
static [bool] Match ([string] $CheckContent)
{
if
(
$CheckContent -Match 'gpedit\.msc' -and
$CheckContent -Match 'User Rights Assignment' -and
$CheckContent -NotMatch 'unresolved SIDs' -and
$CheckContent -NotMatch 'SQL Server'
)
{
return $true
}
return $false
}
<#
.SYNOPSIS
Tests if a rule contains multiple checks
.DESCRIPTION
Search the rule text to determine if multiple user rights are defined
.PARAMETER CheckContent
The rule text from the check-content element in the xccdf
#>
<#{TODO}#> # HasMultipleRules is implemented inconsistently.
static [bool] HasMultipleRules ([string] $CheckContent)
{
if (Test-MultipleUserRightsAssignment -CheckContent ([UserRightRule]::SplitCheckContent($CheckContent)))
{
return $true
}
return $false
}
<#
.SYNOPSIS
Splits a rule into multiple checks
.DESCRIPTION
Once a rule has been found to have multiple checks, the rule needs
to be split. This method splits a user right into multiple rules. Each
split rule id is appended with a dot and letter to keep reporting
per the ID consistent. An example would be is V-1000 contained 2
checks, then SplitMultipleRules would return 2 objects with rule ids
V-1000.a and V-1000.b
.PARAMETER CheckContent
The rule text from the check-content element in the xccdf
#>
static [string[]] SplitMultipleRules ([string] $CheckContent)
{
return (Split-MultipleUserRightsAssignment -CheckContent ([UserRightRule]::SplitCheckContent($CheckContent)))
}
#endregion
}
| {
"pile_set_name": "Github"
} |
**This airport has been automatically generated**
We have no information about CPC6[*] airport other than its name, ICAO and location (CA).
This airport will have to be done from scratch, which includes adding runways, taxiways, parking locations, boundaries...
Good luck if you decide to do this airport! | {
"pile_set_name": "Github"
} |
///////////////////////////////////////////////////////////////
// Copyright 2012 John Maddock. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_
//
// Comparison operators for cpp_int_backend:
//
#ifndef BOOST_MP_CPP_INT_MUL_HPP
#define BOOST_MP_CPP_INT_MUL_HPP
namespace boost{ namespace multiprecision{ namespace backends{
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4127) // conditional expression is constant
#endif
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>
inline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value >::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,
const limb_type& val) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
if(!val)
{
result = static_cast<limb_type>(0);
return;
}
if((void*)&a != (void*)&result)
result.resize(a.size(), a.size());
double_limb_type carry = 0;
typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_pointer p = result.limbs();
typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_pointer pe = result.limbs() + result.size();
typename cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>::const_limb_pointer pa = a.limbs();
while(p != pe)
{
carry += static_cast<double_limb_type>(*pa) * static_cast<double_limb_type>(val);
#ifdef __MSVC_RUNTIME_CHECKS
*p = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));
#else
*p = static_cast<limb_type>(carry);
#endif
carry >>= cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;
++p, ++pa;
}
if(carry)
{
unsigned i = result.size();
result.resize(i + 1, i + 1);
if(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::variable || (result.size() > i))
result.limbs()[i] = static_cast<limb_type>(carry);
}
result.sign(a.sign());
if(!cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::variable)
result.normalize();
}
//
// resize_for_carry forces a resize of the underlying buffer only if a previous request
// for "required" elements could possibly have failed, *and* we have checking enabled.
// This will cause an overflow error inside resize():
//
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
inline void resize_for_carry(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& /*result*/, unsigned /*required*/){}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
inline void resize_for_carry(cpp_int_backend<MinBits1, MaxBits1, SignType1, checked, void>& result, unsigned required)
{
if(result.size() != required)
result.resize(required, required);
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2, unsigned MinBits3, unsigned MaxBits3, cpp_integer_type SignType3, cpp_int_check_type Checked3, class Allocator3>
inline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3> >::value >::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,
const cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3>& b) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
// Very simple long multiplication, only usable for small numbers of limb_type's
// but that's the typical use case for this type anyway:
//
// Special cases first:
//
unsigned as = a.size();
unsigned bs = b.size();
typename cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>::const_limb_pointer pa = a.limbs();
typename cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3>::const_limb_pointer pb = b.limbs();
if(as == 1)
{
bool s = b.sign() != a.sign();
if(bs == 1)
{
result = static_cast<double_limb_type>(*pa) * static_cast<double_limb_type>(*pb);
}
else
{
limb_type l = *pa;
eval_multiply(result, b, l);
}
result.sign(s);
return;
}
if(bs == 1)
{
bool s = b.sign() != a.sign();
limb_type l = *pb;
eval_multiply(result, a, l);
result.sign(s);
return;
}
if((void*)&result == (void*)&a)
{
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t(a);
eval_multiply(result, t, b);
return;
}
if((void*)&result == (void*)&b)
{
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t(b);
eval_multiply(result, a, t);
return;
}
result.resize(as + bs, as + bs - 1);
typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_pointer pr = result.limbs();
static const double_limb_type limb_max = ~static_cast<limb_type>(0u);
static const double_limb_type double_limb_max = ~static_cast<double_limb_type>(0u);
BOOST_STATIC_ASSERT(double_limb_max - 2 * limb_max >= limb_max * limb_max);
double_limb_type carry = 0;
std::memset(pr, 0, result.size() * sizeof(limb_type));
for(unsigned i = 0; i < as; ++i)
{
unsigned inner_limit = cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::variable ? bs : (std::min)(result.size() - i, bs);
for(unsigned j = 0; j < inner_limit; ++j)
{
BOOST_ASSERT(i+j < result.size());
#if (!defined(__GLIBCXX__) && !defined(__GLIBCPP__)) || !BOOST_WORKAROUND(BOOST_GCC_VERSION, <= 50100)
BOOST_ASSERT(!std::numeric_limits<double_limb_type>::is_specialized
|| ((std::numeric_limits<double_limb_type>::max)() - carry
>
static_cast<double_limb_type>(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::max_limb_value) * static_cast<double_limb_type>(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::max_limb_value)));
#endif
carry += static_cast<double_limb_type>(pa[i]) * static_cast<double_limb_type>(pb[j]);
BOOST_ASSERT(!std::numeric_limits<double_limb_type>::is_specialized || ((std::numeric_limits<double_limb_type>::max)() - carry >= pr[i+j]));
carry += pr[i + j];
#ifdef __MSVC_RUNTIME_CHECKS
pr[i + j] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));
#else
pr[i + j] = static_cast<limb_type>(carry);
#endif
carry >>= cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;
BOOST_ASSERT(carry <= (cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::max_limb_value));
}
resize_for_carry(result, as + bs); // May throw if checking is enabled
if(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::variable || (i + bs < result.size()))
pr[i + bs] = static_cast<limb_type>(carry);
carry = 0;
}
result.normalize();
//
// Set the sign of the result:
//
result.sign(a.sign() != b.sign());
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>
BOOST_MP_FORCEINLINE typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value >::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
eval_multiply(result, result, a);
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
BOOST_MP_FORCEINLINE typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type
eval_multiply(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const limb_type& val) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
eval_multiply(result, result, val);
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>
BOOST_MP_FORCEINLINE typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value >::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,
const double_limb_type& val) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
if(val <= (std::numeric_limits<limb_type>::max)())
{
eval_multiply(result, a, static_cast<limb_type>(val));
}
else
{
#if defined(BOOST_LITTLE_ENDIAN) && !defined(BOOST_MP_TEST_NO_LE)
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t(val);
#else
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t;
t = val;
#endif
eval_multiply(result, a, t);
}
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
BOOST_MP_FORCEINLINE typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type
eval_multiply(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const double_limb_type& val) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
eval_multiply(result, result, val);
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>
BOOST_MP_FORCEINLINE typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value >::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,
const signed_limb_type& val) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
if(val > 0)
eval_multiply(result, a, static_cast<limb_type>(val));
else
{
eval_multiply(result, a, static_cast<limb_type>(boost::multiprecision::detail::unsigned_abs(val)));
result.negate();
}
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
BOOST_MP_FORCEINLINE typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type
eval_multiply(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const signed_limb_type& val) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
eval_multiply(result, result, val);
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>
inline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value >::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,
const signed_double_limb_type& val) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
if(val > 0)
{
if(val <= (std::numeric_limits<limb_type>::max)())
{
eval_multiply(result, a, static_cast<limb_type>(val));
return;
}
}
else if(val >= -static_cast<signed_double_limb_type>((std::numeric_limits<limb_type>::max)()))
{
eval_multiply(result, a, static_cast<limb_type>(boost::multiprecision::detail::unsigned_abs(val)));
result.negate();
return;
}
#if defined(BOOST_LITTLE_ENDIAN) && !defined(BOOST_MP_TEST_NO_LE)
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t(val);
#else
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t;
t = val;
#endif
eval_multiply(result, a, t);
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
BOOST_MP_FORCEINLINE typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type
eval_multiply(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const signed_double_limb_type& val) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
eval_multiply(result, result, val);
}
//
// Now over again for trivial cpp_int's:
//
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
BOOST_MP_FORCEINLINE typename enable_if_c<
is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
&& is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
&& (is_signed_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
|| is_signed_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value)
>::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& o) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
*result.limbs() = detail::checked_multiply(*result.limbs(), *o.limbs(), typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::checked_type());
result.sign(result.sign() != o.sign());
result.normalize();
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
BOOST_MP_FORCEINLINE typename enable_if_c<
is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
&& is_unsigned_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
>::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& o) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
*result.limbs() = detail::checked_multiply(*result.limbs(), *o.limbs(), typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::checked_type());
result.normalize();
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
BOOST_MP_FORCEINLINE typename enable_if_c<
is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
&& is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
&& (is_signed_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
|| is_signed_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value)
>::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a,
const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& b) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
*result.limbs() = detail::checked_multiply(*a.limbs(), *b.limbs(), typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::checked_type());
result.sign(a.sign() != b.sign());
result.normalize();
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
BOOST_MP_FORCEINLINE typename enable_if_c<
is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
&& is_unsigned_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
>::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a,
const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& b) BOOST_MP_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))
{
*result.limbs() = detail::checked_multiply(*a.limbs(), *b.limbs(), typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::checked_type());
result.normalize();
}
//
// Special routines for multiplying two integers to obtain a multiprecision result:
//
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
BOOST_MP_FORCEINLINE typename enable_if_c<
!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
>::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
signed_double_limb_type a, signed_double_limb_type b)
{
static const signed_double_limb_type mask = ~static_cast<limb_type>(0);
static const unsigned limb_bits = sizeof(limb_type) * CHAR_BIT;
bool s = false;
double_limb_type w, x, y, z;
if(a < 0)
{
a = -a;
s = true;
}
if(b < 0)
{
b = -b;
s = !s;
}
w = a & mask;
x = a >> limb_bits;
y = b & mask;
z = b >> limb_bits;
result.resize(4, 4);
limb_type* pr = result.limbs();
double_limb_type carry = w * y;
#ifdef __MSVC_RUNTIME_CHECKS
pr[0] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));
carry >>= limb_bits;
carry += w * z + x * y;
pr[1] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));
carry >>= limb_bits;
carry += x * z;
pr[2] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));
pr[3] = static_cast<limb_type>(carry >> limb_bits);
#else
pr[0] = static_cast<limb_type>(carry);
carry >>= limb_bits;
carry += w * z + x * y;
pr[1] = static_cast<limb_type>(carry);
carry >>= limb_bits;
carry += x * z;
pr[2] = static_cast<limb_type>(carry);
pr[3] = static_cast<limb_type>(carry >> limb_bits);
#endif
result.sign(s);
result.normalize();
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
BOOST_MP_FORCEINLINE typename enable_if_c<
!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
>::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
double_limb_type a, double_limb_type b)
{
static const signed_double_limb_type mask = ~static_cast<limb_type>(0);
static const unsigned limb_bits = sizeof(limb_type) * CHAR_BIT;
double_limb_type w, x, y, z;
w = a & mask;
x = a >> limb_bits;
y = b & mask;
z = b >> limb_bits;
result.resize(4, 4);
limb_type* pr = result.limbs();
double_limb_type carry = w * y;
#ifdef __MSVC_RUNTIME_CHECKS
pr[0] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));
carry >>= limb_bits;
carry += w * z;
pr[1] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));
carry >>= limb_bits;
pr[2] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));
carry = x * y + pr[1];
pr[1] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));
carry >>= limb_bits;
carry += pr[2] + x * z;
pr[2] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));
pr[3] = static_cast<limb_type>(carry >> limb_bits);
#else
pr[0] = static_cast<limb_type>(carry);
carry >>= limb_bits;
carry += w * z;
pr[1] = static_cast<limb_type>(carry);
carry >>= limb_bits;
pr[2] = static_cast<limb_type>(carry);
carry = x * y + pr[1];
pr[1] = static_cast<limb_type>(carry);
carry >>= limb_bits;
carry += pr[2] + x * z;
pr[2] = static_cast<limb_type>(carry);
pr[3] = static_cast<limb_type>(carry >> limb_bits);
#endif
result.sign(false);
result.normalize();
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1,
unsigned MinBits2, unsigned MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>
BOOST_MP_FORCEINLINE typename enable_if_c<
!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value
&& is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value
&& is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value
>::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> const& a,
cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> const& b)
{
typedef typename boost::multiprecision::detail::canonical<typename cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>::local_limb_type, cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::type canonical_type;
eval_multiply(result, static_cast<canonical_type>(*a.limbs()), static_cast<canonical_type>(*b.limbs()));
result.sign(a.sign() != b.sign());
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, class SI>
BOOST_MP_FORCEINLINE typename enable_if_c<is_signed<SI>::value && (sizeof(SI) <= sizeof(signed_double_limb_type) / 2)>::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
SI a, SI b)
{
result = static_cast<signed_double_limb_type>(a) * static_cast<signed_double_limb_type>(b);
}
template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, class UI>
BOOST_MP_FORCEINLINE typename enable_if_c<is_unsigned<UI>::value && (sizeof(UI) <= sizeof(signed_double_limb_type) / 2)>::type
eval_multiply(
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
UI a, UI b)
{
result = static_cast<double_limb_type>(a) * static_cast<double_limb_type>(b);
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}}} // namespaces
#endif
| {
"pile_set_name": "Github"
} |
/*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate licenses this file
* to you under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.operation.projectors;
import io.crate.operation.RowUpstream;
public interface Projector extends RowReceiver, RowUpstream {
void downstream(RowReceiver rowDownstreamHandle);
}
| {
"pile_set_name": "Github"
} |
[
{
"description":
"additionalProperties being false does not allow other properties",
"schema": {
"properties": {"foo": {}, "bar": {}},
"patternProperties": { "^v": {} },
"additionalProperties": false
},
"tests": [
{
"description": "no additional properties is valid",
"data": {"foo": 1},
"valid": true
},
{
"description": "an additional property is invalid",
"data": {"foo" : 1, "bar" : 2, "quux" : "boom"},
"valid": false
},
{
"description": "ignores non-objects",
"data": [1, 2, 3],
"valid": true
},
{
"description": "patternProperties are not additional properties",
"data": {"foo":1, "vroom": 2},
"valid": true
}
]
},
{
"description":
"additionalProperties allows a schema which should validate",
"schema": {
"properties": {"foo": {}, "bar": {}},
"additionalProperties": {"type": "boolean"}
},
"tests": [
{
"description": "no additional properties is valid",
"data": {"foo": 1},
"valid": true
},
{
"description": "an additional valid property is valid",
"data": {"foo" : 1, "bar" : 2, "quux" : true},
"valid": true
},
{
"description": "an additional invalid property is invalid",
"data": {"foo" : 1, "bar" : 2, "quux" : 12},
"valid": false
}
]
},
{
"description":
"additionalProperties can exist by itself",
"schema": {
"additionalProperties": {"type": "boolean"}
},
"tests": [
{
"description": "an additional valid property is valid",
"data": {"foo" : true},
"valid": true
},
{
"description": "an additional invalid property is invalid",
"data": {"foo" : 1},
"valid": false
}
]
},
{
"description": "additionalProperties are allowed by default",
"schema": {"properties": {"foo": {}, "bar": {}}},
"tests": [
{
"description": "additional properties are allowed",
"data": {"foo": 1, "bar": 2, "quux": true},
"valid": true
}
]
}
]
| {
"pile_set_name": "Github"
} |
/*
* @OSF_COPYRIGHT@
*
*/
/*
* HISTORY
* $Log: pthread_test3.c,v $
* Revision 1.1.4.2 1996/10/03 17:53:38 emcmanus
* Changed fprintf(stderr...) to printf(...) to allow building with
* PURE_MACH includes.
* [1996/10/03 16:17:34 emcmanus]
*
* Revision 1.1.4.1 1996/10/01 07:36:02 emcmanus
* Copied from rt3_merge.
* Include <stdlib.h> for malloc() prototype.
* [1996/10/01 07:35:53 emcmanus]
*
* Revision 1.1.2.1 1996/09/27 13:12:15 gdt
* Add support for thread specific data
* [1996/09/27 13:11:17 gdt]
*
* $EndLog$
*/
/*
* Test POSIX Thread Specific Data
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include "darwintest_defaults.h"
static pthread_key_t key;
static void *
thread(void * arg)
{
char * msg;
T_LOG("thread %lx here: %s\n", (uintptr_t)pthread_self(), (char *)arg);
msg = malloc(256);
sprintf(msg, "This is thread specific data for %lx\n", (uintptr_t)pthread_self());
T_ASSERT_POSIX_ZERO(pthread_setspecific(key, msg), NULL);
return (arg);
}
static void
grim_reaper(void * param)
{
T_LOG("grim_reaper - self: %lx, param: %lx value: %s", (uintptr_t)pthread_self(), (uintptr_t)param, (char *)param);
free(param);
}
T_DECL(pthread_setspecific, "pthread_setspecific",
T_META_ALL_VALID_ARCHS(YES))
{
void * thread_res;
pthread_t t1, t2;
T_ASSERT_POSIX_ZERO(pthread_key_create(&key, grim_reaper), NULL);
T_ASSERT_POSIX_ZERO(pthread_create(&t1, (pthread_attr_t *)NULL, thread, "thread #1 arg"), NULL);
T_ASSERT_POSIX_ZERO(pthread_create(&t2, (pthread_attr_t *)NULL, thread, "thread #2 arg"), NULL);
T_ASSERT_POSIX_ZERO(pthread_join(t1, &thread_res), NULL);
T_ASSERT_POSIX_ZERO(pthread_join(t2, &thread_res), NULL);
}
| {
"pile_set_name": "Github"
} |
apiVersion: v1
kind: ServiceAccount
metadata:
name: event-exporter-sa
namespace: kube-system
labels:
k8s-app: event-exporter
kubernetes.io/cluster-service: "true"
addonmanager.kubernetes.io/mode: Reconcile
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: event-exporter-rb
namespace: kube-system
labels:
k8s-app: event-exporter
kubernetes.io/cluster-service: "true"
addonmanager.kubernetes.io/mode: Reconcile
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: view
subjects:
- kind: ServiceAccount
name: event-exporter-sa
namespace: kube-system
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: event-exporter-v0.1.8
namespace: kube-system
labels:
k8s-app: event-exporter
version: v0.1.8
kubernetes.io/cluster-service: "true"
addonmanager.kubernetes.io/mode: Reconcile
spec:
replicas: 1
template:
metadata:
labels:
k8s-app: event-exporter
version: v0.1.8
spec:
serviceAccountName: event-exporter-sa
containers:
- name: event-exporter
image: k8s.gcr.io/event-exporter:v0.1.8
command:
- /event-exporter
- -sink-opts=-location={{ event_exporter_zone }}
# BEGIN_PROMETHEUS_TO_SD
- name: prometheus-to-sd-exporter
image: k8s.gcr.io/prometheus-to-sd:v0.2.4
command:
- /monitor
- --stackdriver-prefix={{ prometheus_to_sd_prefix }}/addons
- --api-override={{ prometheus_to_sd_endpoint }}
- --source=event_exporter:http://localhost:80?whitelisted=stackdriver_sink_received_entry_count,stackdriver_sink_request_count,stackdriver_sink_successfully_sent_entry_count
- --pod-id=$(POD_NAME)
- --namespace-id=$(POD_NAMESPACE)
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
# END_PROMETHEUS_TO_SD
terminationGracePeriodSeconds: 30
volumes:
- name: ssl-certs
hostPath:
path: /etc/ssl/certs
| {
"pile_set_name": "Github"
} |
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
echo $MAVEN_PROJECTBASEDIR
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
| {
"pile_set_name": "Github"
} |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"WD",
"WB"
],
"DAY": [
"Dilbata",
"Wiixata",
"Qibxata",
"Roobii",
"Kamiisa",
"Jimaata",
"Sanbata"
],
"MONTH": [
"Amajjii",
"Guraandhala",
"Bitooteessa",
"Elba",
"Caamsa",
"Waxabajjii",
"Adooleessa",
"Hagayya",
"Fuulbana",
"Onkololeessa",
"Sadaasa",
"Muddee"
],
"SHORTDAY": [
"Dil",
"Wix",
"Qib",
"Rob",
"Kam",
"Jim",
"San"
],
"SHORTMONTH": [
"Ama",
"Gur",
"Bit",
"Elb",
"Cam",
"Wax",
"Ado",
"Hag",
"Ful",
"Onk",
"Sad",
"Mud"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "dd MMMM y",
"medium": "dd-MMM-y h:mm:ss a",
"mediumDate": "dd-MMM-y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/yy h:mm a",
"shortDate": "dd/MM/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "Birr",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "om-et",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| {
"pile_set_name": "Github"
} |
/*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#ifdef GRPC_CFSTREAM
#import <CoreFoundation/CoreFoundation.h>
#import "src/core/lib/iomgr/cfstream_handle.h"
#include <grpc/support/atm.h>
#include <grpc/support/sync.h>
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/error_cfstream.h"
#include "src/core/lib/iomgr/exec_ctx.h"
extern grpc_core::TraceFlag grpc_tcp_trace;
void* CFStreamHandle::Retain(void* info) {
CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);
CFSTREAM_HANDLE_REF(handle, "retain");
return info;
}
void CFStreamHandle::Release(void* info) {
CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);
CFSTREAM_HANDLE_UNREF(handle, "release");
}
CFStreamHandle* CFStreamHandle::CreateStreamHandle(
CFReadStreamRef read_stream, CFWriteStreamRef write_stream) {
return new CFStreamHandle(read_stream, write_stream);
}
void CFStreamHandle::ReadCallback(CFReadStreamRef stream,
CFStreamEventType type,
void* client_callback_info) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
grpc_error* error;
CFErrorRef stream_error;
CFStreamHandle* handle = static_cast<CFStreamHandle*>(client_callback_info);
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_DEBUG, "CFStream ReadCallback (%p, %p, %lu, %p)", handle,
stream, type, client_callback_info);
}
switch (type) {
case kCFStreamEventOpenCompleted:
handle->open_event_.SetReady();
break;
case kCFStreamEventHasBytesAvailable:
case kCFStreamEventEndEncountered:
handle->read_event_.SetReady();
break;
case kCFStreamEventErrorOccurred:
stream_error = CFReadStreamCopyError(stream);
error = grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "read error"),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
CFRelease(stream_error);
handle->open_event_.SetShutdown(GRPC_ERROR_REF(error));
handle->write_event_.SetShutdown(GRPC_ERROR_REF(error));
handle->read_event_.SetShutdown(GRPC_ERROR_REF(error));
GRPC_ERROR_UNREF(error);
break;
default:
GPR_UNREACHABLE_CODE(return );
}
}
void CFStreamHandle::WriteCallback(CFWriteStreamRef stream,
CFStreamEventType type,
void* clientCallBackInfo) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
grpc_error* error;
CFErrorRef stream_error;
CFStreamHandle* handle = static_cast<CFStreamHandle*>(clientCallBackInfo);
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_DEBUG, "CFStream WriteCallback (%p, %p, %lu, %p)", handle,
stream, type, clientCallBackInfo);
}
switch (type) {
case kCFStreamEventOpenCompleted:
handle->open_event_.SetReady();
break;
case kCFStreamEventCanAcceptBytes:
case kCFStreamEventEndEncountered:
handle->write_event_.SetReady();
break;
case kCFStreamEventErrorOccurred:
stream_error = CFWriteStreamCopyError(stream);
error = grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "write error"),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
CFRelease(stream_error);
handle->open_event_.SetShutdown(GRPC_ERROR_REF(error));
handle->write_event_.SetShutdown(GRPC_ERROR_REF(error));
handle->read_event_.SetShutdown(GRPC_ERROR_REF(error));
GRPC_ERROR_UNREF(error);
break;
default:
GPR_UNREACHABLE_CODE(return );
}
}
CFStreamHandle::CFStreamHandle(CFReadStreamRef read_stream,
CFWriteStreamRef write_stream) {
gpr_ref_init(&refcount_, 1);
open_event_.InitEvent();
read_event_.InitEvent();
write_event_.InitEvent();
dispatch_queue_ = dispatch_queue_create(nullptr, DISPATCH_QUEUE_SERIAL);
CFStreamClientContext ctx = {0, static_cast<void*>(this),
CFStreamHandle::Retain, CFStreamHandle::Release,
nil};
CFReadStreamSetClient(
read_stream,
kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable |
kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
CFStreamHandle::ReadCallback, &ctx);
CFWriteStreamSetClient(
write_stream,
kCFStreamEventOpenCompleted | kCFStreamEventCanAcceptBytes |
kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
CFStreamHandle::WriteCallback, &ctx);
CFReadStreamSetDispatchQueue(read_stream, dispatch_queue_);
CFWriteStreamSetDispatchQueue(write_stream, dispatch_queue_);
}
CFStreamHandle::~CFStreamHandle() {
open_event_.DestroyEvent();
read_event_.DestroyEvent();
write_event_.DestroyEvent();
}
void CFStreamHandle::NotifyOnOpen(grpc_closure* closure) {
open_event_.NotifyOn(closure);
}
void CFStreamHandle::NotifyOnRead(grpc_closure* closure) {
read_event_.NotifyOn(closure);
}
void CFStreamHandle::NotifyOnWrite(grpc_closure* closure) {
write_event_.NotifyOn(closure);
}
void CFStreamHandle::Shutdown(grpc_error* error) {
open_event_.SetShutdown(GRPC_ERROR_REF(error));
read_event_.SetShutdown(GRPC_ERROR_REF(error));
write_event_.SetShutdown(GRPC_ERROR_REF(error));
GRPC_ERROR_UNREF(error);
}
void CFStreamHandle::Ref(const char* file, int line, const char* reason) {
if (grpc_tcp_trace.enabled()) {
gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);
gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
"CFStream Handle ref %p : %s %" PRIdPTR " -> %" PRIdPTR, this,
reason, val, val + 1);
}
gpr_ref(&refcount_);
}
void CFStreamHandle::Unref(const char* file, int line, const char* reason) {
if (grpc_tcp_trace.enabled()) {
gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);
gpr_log(GPR_ERROR,
"CFStream Handle unref %p : %s %" PRIdPTR " -> %" PRIdPTR, this,
reason, val, val - 1);
}
if (gpr_unref(&refcount_)) {
delete this;
}
}
#else
/* Creating a dummy function so that the grpc_cfstream library will be
* non-empty.
*/
void CFStreamDummy() {}
#endif
| {
"pile_set_name": "Github"
} |
"abc" * -3 // expect runtime error: Count must be a non-negative integer.
| {
"pile_set_name": "Github"
} |
// +build amd64 amd64p32 arm64 ppc64 ppc64le mips64 mips64le mips64p32 mips64p32le sparc64
package pkg
import "sync/atomic"
type T struct {
A int64
B int32
C int64
}
func fn() {
var v T
atomic.AddInt64(&v.A, 0)
atomic.AddInt64(&v.C, 0)
atomic.LoadInt64(&v.C)
}
| {
"pile_set_name": "Github"
} |
#if !defined Expect_hxx
#define Expect_hxx
#include "tfm/Event.hxx"
#include "tfm/TestEndPoint.hxx"
#include <boost/shared_ptr.hpp>
class EventMatcher
{
public:
virtual bool isMatch(boost::shared_ptr<Event> event)
{
resip_assert(0);
return false;
}
virtual resip::Data getMsgTypeString() const
{
resip_assert(0);
return "";
}
virtual const resip::Data& explainMismatch() const = 0;
virtual ~EventMatcher() {}
};
template<class T>
class EventMatcherSpecific : public EventMatcher
{
public:
EventMatcherSpecific(typename T::Type t) :
mEventType(t)
{
}
virtual bool isMatch(boost::shared_ptr<Event> event)
{
T* specificEvent = dynamic_cast<T*>(event.get());
if (specificEvent)
{
if (specificEvent->getType() == mEventType)
{
return true;
}
else
{
{
resip::DataStream ds(mMessage);
ds << "Expected " << T::getTypeName(mEventType) << ", Received " << *event;
}
return false;
}
}
else
{
{
resip::DataStream ds(mMessage);
ds << "Wrong event type";
}
return false;
}
}
virtual resip::Data getMsgTypeString() const
{
resip::Data d;
{
resip::DataStream ds(d);
ds << T::getName() << ": " << T::getTypeName(mEventType);
}
return d;
}
const resip::Data& explainMismatch() const { return mMessage; }
private:
typename T::Type mEventType;
resip::Data mMessage;
};
class ExpectPredicate
{
public:
virtual ~ExpectPredicate()
{
}
virtual bool passes(boost::shared_ptr<Event>) = 0;
virtual const resip::Data& explainMismatch() const = 0;
};
class Expect : public TestEndPoint::ExpectBase
{
public:
Expect(TestEndPoint& endPoint,
EventMatcher* em,
int timeoutMs,
ActionBase* expectAction);
Expect(TestEndPoint& endPoint,
EventMatcher* em,
ExpectPredicate* pred,
int timeoutMs,
ActionBase* expectAction);
~Expect();
virtual TestEndPoint* getEndPoint() const;
virtual unsigned int getTimeout() const;
virtual bool isMatch(boost::shared_ptr<Event> event) const;
virtual resip::Data explainMismatch(boost::shared_ptr<Event> event) const;
virtual void onEvent(TestEndPoint&, boost::shared_ptr<Event> event);
virtual resip::Data getMsgTypeString() const;
virtual std::ostream& output(std::ostream& s) const;
class Exception : public resip::BaseException
{
public:
Exception(const resip::Data& msg,
const resip::Data& file,
const int line);
virtual resip::Data getName() const ;
virtual const char* name() const ;
};
virtual Box layout() const;
virtual void render(AsciiGraphic::CharRaster &out) const;
private:
TestEndPoint& mEndPoint;
EventMatcher* mEventMatcher;
typedef std::vector<ExpectPredicate*> ExpectPredicates;
ExpectPredicates mExpectPredicates;
unsigned int mTimeoutMs;
ActionBase* mExpectAction;
resip::Data mMessage;
};
#endif
| {
"pile_set_name": "Github"
} |
#pragma once
#include <stdio.h>
#include <stdarg.h>
#define BB_DEBUG 0
#ifdef __cplusplus
// debug
template<int N>
inline
void _dump_symbol ( char* plable, COMPLEX16* input ) {
#if BB_DEBUG > 2
printf ("dump::start(%s)", plable);
for ( size_t i=0; i<N; i++) {
if ( i%4 == 0 ) printf ("\n(%2d) ", i);
printf ( "<%6d, %6d> , ", input[i].re, input[i].im);
}
printf ("\ndump::end\n");
#endif
}
template<int N>
inline
void _dump_symbol32 ( char* plable, COMPLEX32* input ) {
#if BB_DEBUG > 2
printf ("dump::start(%s)", plable);
for ( size_t i=0; i<N; i++) {
if ( i%4 == 0 ) printf ("\n(%2d) ", i);
printf ( "<%6d, %6d> , ", input[i].re, input[i].im);
}
printf ("\ndump::end\n");
#endif
}
inline
void _dump_text (const char *fmt, ...) {
#if BB_DEBUG
va_list args;
va_start (args, fmt);
vprintf (fmt, args);
va_end (args);
#endif
}
#endif | {
"pile_set_name": "Github"
} |
require('../../modules/es6.math.tanh');
module.exports = require('../../modules/_core').Math.tanh; | {
"pile_set_name": "Github"
} |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run ../collate/maketables.go -cldr=23 -unicode=6.2.0 -types=search,searchjl -package=search
// Package search provides language-specific search and string matching.
//
// Natural language matching can be intricate. For example, Danish will insist
// "Århus" and "Aarhus" are the same name and Turkish will match I to ı (note
// the lack of a dot) in a case-insensitive match. This package handles such
// language-specific details.
//
// Text passed to any of the calls in this message does not need to be
// normalized.
package search // import "golang.org/x/text/search"
import (
"strings"
"golang.org/x/text/internal/colltab"
"golang.org/x/text/language"
)
// An Option configures a Matcher.
type Option func(*Matcher)
var (
// WholeWord restricts matches to complete words. The default is to match at
// the character level.
WholeWord Option = nil
// Exact requires that two strings are their exact equivalent. For example
// å would not match aa in Danish. It overrides any of the ignore options.
Exact Option = nil
// Loose causes case, diacritics and width to be ignored.
Loose Option = loose
// IgnoreCase enables case-insensitive search.
IgnoreCase Option = ignoreCase
// IgnoreDiacritics causes diacritics to be ignored ("ö" == "o").
IgnoreDiacritics Option = ignoreDiacritics
// IgnoreWidth equates narrow with wide variants.
IgnoreWidth Option = ignoreWidth
)
func ignoreDiacritics(m *Matcher) { m.ignoreDiacritics = true }
func ignoreCase(m *Matcher) { m.ignoreCase = true }
func ignoreWidth(m *Matcher) { m.ignoreWidth = true }
func loose(m *Matcher) {
ignoreDiacritics(m)
ignoreCase(m)
ignoreWidth(m)
}
var (
// Supported lists the languages for which search differs from its parent.
Supported language.Coverage
tags []language.Tag
)
func init() {
ids := strings.Split(availableLocales, ",")
tags = make([]language.Tag, len(ids))
for i, s := range ids {
tags[i] = language.Raw.MustParse(s)
}
Supported = language.NewCoverage(tags)
}
// New returns a new Matcher for the given language and options.
func New(t language.Tag, opts ...Option) *Matcher {
m := &Matcher{
w: getTable(locales[colltab.MatchLang(t, tags)]),
}
for _, f := range opts {
f(m)
}
return m
}
// A Matcher implements language-specific string matching.
type Matcher struct {
w colltab.Weighter
ignoreCase bool
ignoreWidth bool
ignoreDiacritics bool
}
// An IndexOption specifies how the Index methods of Pattern or Matcher should
// match the input.
type IndexOption byte
const (
// Anchor restricts the search to the start (or end for Backwards) of the
// text.
Anchor IndexOption = 1 << iota
// Backwards starts the search from the end of the text.
Backwards
anchorBackwards = Anchor | Backwards
)
// Index reports the start and end position of the first occurrence of pat in b
// or -1, -1 if pat is not present.
func (m *Matcher) Index(b, pat []byte, opts ...IndexOption) (start, end int) {
// TODO: implement optimized version that does not use a pattern.
return m.Compile(pat).Index(b, opts...)
}
// IndexString reports the start and end position of the first occurrence of pat
// in s or -1, -1 if pat is not present.
func (m *Matcher) IndexString(s, pat string, opts ...IndexOption) (start, end int) {
// TODO: implement optimized version that does not use a pattern.
return m.CompileString(pat).IndexString(s, opts...)
}
// Equal reports whether a and b are equivalent.
func (m *Matcher) Equal(a, b []byte) bool {
_, end := m.Index(a, b, Anchor)
return end == len(a)
}
// EqualString reports whether a and b are equivalent.
func (m *Matcher) EqualString(a, b string) bool {
_, end := m.IndexString(a, b, Anchor)
return end == len(a)
}
// Compile compiles and returns a pattern that can be used for faster searching.
func (m *Matcher) Compile(b []byte) *Pattern {
p := &Pattern{m: m}
iter := colltab.Iter{Weighter: m.w}
for iter.SetInput(b); iter.Next(); {
}
p.ce = iter.Elems
p.deleteEmptyElements()
return p
}
// CompileString compiles and returns a pattern that can be used for faster
// searching.
func (m *Matcher) CompileString(s string) *Pattern {
p := &Pattern{m: m}
iter := colltab.Iter{Weighter: m.w}
for iter.SetInputString(s); iter.Next(); {
}
p.ce = iter.Elems
p.deleteEmptyElements()
return p
}
// A Pattern is a compiled search string. It is safe for concurrent use.
type Pattern struct {
m *Matcher
ce []colltab.Elem
}
// Design note (TODO remove):
// The cost of retrieving collation elements for each rune, which is used for
// search as well, is not trivial. Also, algorithms like Boyer-Moore and
// Sunday require some additional precomputing.
// Index reports the start and end position of the first occurrence of p in b
// or -1, -1 if p is not present.
func (p *Pattern) Index(b []byte, opts ...IndexOption) (start, end int) {
// Pick a large enough buffer such that we likely do not need to allocate
// and small enough to not cause too much overhead initializing.
var buf [8]colltab.Elem
it := &colltab.Iter{
Weighter: p.m.w,
Elems: buf[:0],
}
it.SetInput(b)
var optMask IndexOption
for _, o := range opts {
optMask |= o
}
switch optMask {
case 0:
return p.forwardSearch(it)
case Anchor:
return p.anchoredForwardSearch(it)
case Backwards, anchorBackwards:
panic("TODO: implement")
default:
panic("unrecognized option")
}
}
// IndexString reports the start and end position of the first occurrence of p
// in s or -1, -1 if p is not present.
func (p *Pattern) IndexString(s string, opts ...IndexOption) (start, end int) {
// Pick a large enough buffer such that we likely do not need to allocate
// and small enough to not cause too much overhead initializing.
var buf [8]colltab.Elem
it := &colltab.Iter{
Weighter: p.m.w,
Elems: buf[:0],
}
it.SetInputString(s)
var optMask IndexOption
for _, o := range opts {
optMask |= o
}
switch optMask {
case 0:
return p.forwardSearch(it)
case Anchor:
return p.anchoredForwardSearch(it)
case Backwards, anchorBackwards:
panic("TODO: implement")
default:
panic("unrecognized option")
}
}
// TODO:
// - Maybe IndexAll methods (probably not necessary).
// - Some way to match patterns in a Reader (a bit tricky).
// - Some fold transformer that folds text to comparable text, based on the
// search options. This is a common technique, though very different from the
// collation-based design of this package. It has a somewhat different use
// case, so probably makes sense to support both. Should probably be in a
// different package, though, as it uses completely different kind of tables
// (based on norm, cases, width and range tables.)
| {
"pile_set_name": "Github"
} |
<?php
namespace AppBundle\Service;
use AppBundle\Entity\Decklist;
use AppBundle\Entity\Moderation;
use AppBundle\Entity\Modflag;
use AppBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
/**
* Description of ModerationHelper
*
* @author cedric
*/
class ModerationHelper
{
/** @var EntityManagerInterface $entityManager */
private $entityManager;
/** @var \Swift_Mailer $mailer */
private $mailer;
/** @var \Twig_Environment $twig */
private $twig;
/** @var RouterInterface $router */
private $router;
/** @var LoggerInterface $logger */
private $logger;
public function __construct(EntityManagerInterface $entityManager, \Swift_Mailer $mailer, \Twig_Environment $twig, RouterInterface $router, LoggerInterface $logger)
{
$this->entityManager = $entityManager;
$this->mailer = $mailer;
$this->twig = $twig;
$this->router = $router;
$this->logger = $logger;
}
/**
* @param int $moderationStatus
* @return mixed
*/
public function getLabel(int $moderationStatus)
{
static $labels = [
'Published',
'Restored',
'Trashed',
'Deleted',
];
return $labels[$moderationStatus];
}
/**
* @param User $user
* @param Decklist $decklist
* @param int $status
* @param int|null $modflag_id
*/
public function changeStatus(User $user, Decklist $decklist, int $status, int $modflag_id = null)
{
$previousStatus = $decklist->getModerationStatus();
if (isset($modflag_id)) {
$modflag = $this->entityManager->getRepository('AppBundle:Modflag')->find($modflag_id);
if (!$modflag instanceof Modflag) {
throw new \RuntimeException("Unknown modflag_id");
}
$decklist->setModflag($modflag);
} else {
if ($status != Decklist::MODERATION_PUBLISHED && $status != Decklist::MODERATION_RESTORED) {
throw new \RuntimeException("modflag_id required");
}
}
$decklist->setModerationStatus($status);
$this->sendEmail($decklist);
$moderation = new Moderation();
$moderation->setStatusBefore($previousStatus);
$moderation->setStatusAfter($status);
$moderation->setModerator($user);
$moderation->setDecklist($decklist);
$moderation->setDateCreation(new \DateTime);
$this->entityManager->persist($moderation);
}
/**
* @param Decklist $decklist
* @throws \Twig_Error_Loader
* @throws \Twig_Error_Runtime
* @throws \Twig_Error_Syntax
*/
public function sendEmail(Decklist $decklist)
{
$status = $decklist->getModerationStatus();
if ($status === Decklist::MODERATION_RESTORED) {
return;
}
$name = "/Emails/decklist-moderation-$status.html.twig";
$url = $this->router->generate(
'decklist_detail',
[
'decklist_id' => $decklist->getId(),
'decklist_name' => $decklist->getPrettyname(),
],
UrlGeneratorInterface::ABSOLUTE_URL
);
$body = $this->twig->render(
$name,
[
'username' => $decklist->getUser()->getUsername(),
'decklist_name' => $decklist->getName(),
'url' => $url,
'reason' => $decklist->getModflag() ? $decklist->getModflag()->getReason() : "Unknown",
]
);
$this->logger->debug($body);
$message = \Swift_Message::newInstance()
->setSubject("Your decklist on NetrunnerDB")
->setFrom("[email protected]", "NetrunnerDB Moderation Team")
->setTo($decklist->getUser()->getEmail())
->setBody($body, 'text/html');
$this->mailer->send($message);
}
}
| {
"pile_set_name": "Github"
} |
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2017 Paco Avila & Josep Llort
* <p>
* No bytes were intentionally harmed during the development of this application.
* <p>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.bean;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author pavila
*
*/
@XmlRootElement(name = "folder")
public class Folder extends Node {
private static final long serialVersionUID = 1L;
public static final String TYPE = "okm:folder";
private boolean hasChildren;
public boolean isHasChildren() {
return hasChildren;
}
public void setHasChildren(boolean hasChildren) {
this.hasChildren = hasChildren;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("path=").append(path);
sb.append(", permissions=").append(permissions);
sb.append(", created=").append(created == null ? null : created.getTime());
sb.append(", hasChildren=").append(hasChildren);
sb.append(", subscribed=").append(subscribed);
sb.append(", subscriptors=").append(subscriptors);
sb.append(", uuid=").append(uuid);
sb.append(", keywords=").append(keywords);
sb.append(", categories=").append(categories);
sb.append(", notes=").append(notes);
sb.append("}");
return sb.toString();
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14D136" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
<capability name="Aspect ratio constraints" minToolsVersion="5.1"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="Test15VC">
<connections>
<outlet property="view" destination="iN0-l3-epB" id="MXW-mF-1gZ"/>
<outletCollection property="imgVs" destination="M4h-K1-uyI" id="bv1-Em-uSE"/>
<outletCollection property="imgVs" destination="LJy-iS-iQT" id="ayp-LT-x7C"/>
<outletCollection property="imgVs" destination="c2u-XK-Ulu" id="Nfx-SI-Txy"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="iN0-l3-epB">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="M4h-K1-uyI">
<rect key="frame" x="80" y="80" width="440" height="147"/>
<constraints>
<constraint firstAttribute="width" secondItem="M4h-K1-uyI" secondAttribute="height" multiplier="300:100" id="25y-sp-8xt"/>
</constraints>
</imageView>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="c2u-XK-Ulu">
<rect key="frame" x="80" y="413" width="440" height="147"/>
</imageView>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="vmj-5x-yJz">
<rect key="frame" x="190" y="510" width="60" height="30"/>
<color key="backgroundColor" red="1" green="0.52549019610000003" blue="0.32156862749999998" alpha="1" colorSpace="calibratedRGB"/>
<constraints>
<constraint firstAttribute="width" constant="60" id="UiG-4m-zpT"/>
</constraints>
<state key="normal" title="保存">
<color key="titleColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<connections>
<action selector="saveAction:" destination="-1" eventType="touchUpInside" id="BlW-ZE-ANG"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="kVK-lW-px0">
<rect key="frame" x="350" y="510" width="60" height="30"/>
<color key="backgroundColor" red="1" green="0.52549019610000003" blue="0.32156862749999998" alpha="1" colorSpace="calibratedRGB"/>
<state key="normal" title="读取">
<color key="titleColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<connections>
<action selector="readAction:" destination="-1" eventType="touchUpInside" id="KLm-nw-C1d"/>
</connections>
</button>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="LJy-iS-iQT">
<rect key="frame" x="80" y="247" width="440" height="146"/>
</imageView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="LJy-iS-iQT" firstAttribute="leading" secondItem="c2u-XK-Ulu" secondAttribute="leading" id="2It-t5-P76"/>
<constraint firstItem="LJy-iS-iQT" firstAttribute="top" secondItem="M4h-K1-uyI" secondAttribute="bottom" constant="20" id="K8N-xi-H0X"/>
<constraint firstItem="kVK-lW-px0" firstAttribute="width" secondItem="vmj-5x-yJz" secondAttribute="width" id="Lz8-aU-Ins"/>
<constraint firstAttribute="trailing" secondItem="M4h-K1-uyI" secondAttribute="trailing" constant="80" id="NKG-fm-kMb"/>
<constraint firstAttribute="bottom" secondItem="vmj-5x-yJz" secondAttribute="bottom" constant="60" id="P61-sI-q1L"/>
<constraint firstItem="c2u-XK-Ulu" firstAttribute="top" secondItem="LJy-iS-iQT" secondAttribute="bottom" constant="20" id="PmE-vX-ghL"/>
<constraint firstItem="M4h-K1-uyI" firstAttribute="top" secondItem="iN0-l3-epB" secondAttribute="top" constant="80" id="RWw-3A-Gok"/>
<constraint firstItem="LJy-iS-iQT" firstAttribute="trailing" secondItem="M4h-K1-uyI" secondAttribute="trailing" id="Rkj-1j-A9u"/>
<constraint firstItem="LJy-iS-iQT" firstAttribute="leading" secondItem="M4h-K1-uyI" secondAttribute="leading" id="Vvg-T7-McI"/>
<constraint firstItem="kVK-lW-px0" firstAttribute="bottom" secondItem="vmj-5x-yJz" secondAttribute="bottom" id="Yly-HJ-Qxq"/>
<constraint firstAttribute="centerX" secondItem="kVK-lW-px0" secondAttribute="centerX" constant="-80" id="fbX-Es-HbN"/>
<constraint firstItem="LJy-iS-iQT" firstAttribute="height" secondItem="c2u-XK-Ulu" secondAttribute="height" id="iNJ-cy-aJy"/>
<constraint firstItem="M4h-K1-uyI" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="80" id="mR0-uS-e74"/>
<constraint firstItem="LJy-iS-iQT" firstAttribute="trailing" secondItem="c2u-XK-Ulu" secondAttribute="trailing" id="vRb-e8-j9f"/>
<constraint firstItem="LJy-iS-iQT" firstAttribute="height" secondItem="M4h-K1-uyI" secondAttribute="height" id="wM6-VO-q8D"/>
<constraint firstAttribute="centerX" secondItem="vmj-5x-yJz" secondAttribute="centerX" constant="80" id="yE2-lu-SmG"/>
</constraints>
<point key="canvasLocation" x="440" y="432"/>
</view>
</objects>
</document>
| {
"pile_set_name": "Github"
} |
/* Generated by RuntimeBrowser.
*/
@protocol PHPhotoLibraryChangeObserver <NSObject>
@required
- (void)photoLibraryDidChange:(PHChange *)arg1;
@end
| {
"pile_set_name": "Github"
} |
package com.univocity.trader.simulation;
import org.apache.commons.lang3.*;
import java.util.*;
public class LongParameters extends Parameters {
public long[] params;
public LongParameters(long... params) {
this.params = params;
}
@Override
protected String printParameters() {
return Arrays.toString(params);
}
@Override
public LongParameters fromString(String s) {
if (s.indexOf('[') >= 0) {
s = StringUtils.substringBetween(s, "[", "]");
} else if (s.indexOf('(') >= 0) {
s = StringUtils.substringBetween(s, "(", ")");
} else if (s.indexOf('{') >= 0) {
s = StringUtils.substringBetween(s, "{", "}");
}
if (s.isBlank()) {
return new LongParameters();
}
String[] params = s.split(",");
long[] p = new long[params.length];
for (int i = 0; i < params.length; i++) {
params[i] = params[i].trim();
p[i] = Long.parseLong(params[i]);
}
return new LongParameters(p);
}
} | {
"pile_set_name": "Github"
} |
#!/bin/bash
# symbols set by build host:
#
# export JAVA_JDK=/opt/jdk1.7.0_45/bin
#
# export ANDROID_ADT=/opt/adt-bundle-linux-x86_64
# export ANDROID_ANT=$ANDROID_ADT/eclipse/plugins/org.apache.ant_1.8.3.v20120321-1730/bin/ant
# export ANDROID_SDK=$ANDROID_ADT/sdk
# export ANDROID_NDK=/opt/android-ndk-r9c
#
# export PATH=$JAVA_JDK:$ANDROID_NDK:$ANDROID_ADT:$ANDROID_ANT:$ANDROID_SDK/tools:$PATH
#
# export GRADLE_USER_HOME="$WORKSPACE"
# export SRC_ROOT=$WORKSPACE
# export AUTOMATED_BUILD=1
# export JNI_ROOT=$WORKSPACE/support
#
# export BUILD_NUMBER_PREFIX="alpha-"
# which varies depending on build dev-, alpha-, 17-Apr-2014: <- last is release
set -e
die() {
echo $* >&2
exit 1
}
assert_nonempty_var() {
local var_name="$1"; shift
[[ -n "$(eval echo \$$var_name)" ]] || die "$var_name must not be empty"
}
iso8601_timestamp() {
date -u +'%FT%TZ'
}
set_gradle_properties() {
local build_number="$1"; shift
local build_id="$1"; shift
local build_number_prefix="$1"; shift
cat <<end_set_gradle_properties > gradle.properties
org.gradle.jvmargs=-Xmx3584M
build_environment=silentcircle.com
build_version=$build_number_prefix$build_number
build_version_numeric=$build_number
build_commit=$(git log -n 1 --pretty=format:'%h')
build_date=$build_id
build_debug=true
build_partners=Vertu
## Next is required for gradle plugin 1.3.0 to support the old way to handle
## NDK builds. Maybe we can update/remove it once gradle fully supports NDK
android.useDeprecatedNdk=true
end_set_gradle_properties
}
export SC_BUILD_TYPE="$1"
BUILT_APK_ROOT="silentphone2/build/outputs/apk/"
ARTIFACT_APK="silentphone.apk"
if [[ "$SC_BUILD_TYPE" = "DEVELOP" ]];
then
BUILD_GRADLE_TASK="assembleNormalDevelop"
BUILD_APK_NAME="silentphone2-normal-develop.apk"
echo "*** building develop configuration"
else
export SC_BUILD_TYPE="RELEASE"
BUILD_GRADLE_TASK="assembleRelease"
BUILD_APK_NAME="silentphone2-normal-release.apk"
echo "*** building release configuration"
fi
# Show environment for debug purposes
env
git submodule init
git submodule update --recursive
git submodule status
cat <<END_LOCAL_PROPERTIES > local.properties
sdk.dir=$ANDROID_SDK
ndk.dir=$ANDROID_NDK
END_LOCAL_PROPERTIES
echo "local.properties:"
cat local.properties
# build static and shared libs and dependencies, copy resulting libs to
# correct place (silentphone2/jni/armeabi-v7a), then run top level ndk-build
pushd silentphone2/support/axolotl
chmod +x ./axolotl-build.sh
if ! ./axolotl-build.sh; then
echo "ZINA static library build failed"
exit 1
fi
popd
pushd silentphone2/support/zrtpcpp
chmod +x ./buildNativeAndroidTivi.sh
if ! ./buildNativeAndroidTivi.sh; then
echo "ZRTP static library build failed"
exit 1
fi
popd
pushd silentphone2/support/aec
chmod +x ./aecBuild.sh
if ! ./aecBuild.sh; then
echo "WebRTC AEC shared library build failed"
exit 1
fi
popd
pushd silentphone2/support/silentphone/codecs/vTiVi
chmod +x ./tinaBuild.sh
if ! ./tinaBuild.sh; then
echo "Tina codec shared library build failed"
exit 1
fi
popd
pushd silentphone2
if [ ! -h local.properties ]; then
ln -s ../local.properties
fi
# try to make a clean build for silentphone submodule
ndk-build clean
# ndk jni builds
# ndk-build -d -B V=1 NDK_LOG=1
if ! ndk-build NDK_DEBUG=0; then
echo "Build of native silentphone library failed"
exit 1
fi
popd
## See which build system we are using
## and set env vars accordingly
if [ -n "$AUTOMATED_BUILD" ]; then
if [ -n "$GITLAB_CI" ]; then
# BUILD_NUMBER_PREFIX is (should be) set by gitlab-ci.yml
# It is allowed to be empty.
BUILD_NUMBER="$CI_JOB_ID"
BUILD_ID=$(iso8601_timestamp)
elif [ -n "$JENKINS_HOME" ]; then
# The required build variables should already be set
assert_nonempty_var BUILD_NUMBER
assert_nonempty_var BUILD_ID
else
echo "AUTOMATED_BUILD set but I don't know which CI system this is."
exit 1
fi
else # Manual build
BUILD_NUMBER_PREFIX='manual-'
BUILD_NUMBER=$$ # This should be monotonically increasing, but not worth it
BUILD_ID=$(iso8601_timestamp)
fi
set_gradle_properties "$BUILD_NUMBER" "$BUILD_ID" "$BUILD_NUMBER_PREFIX"
echo "gradle.properties:"
cat gradle.properties
# for more information on what gradlew is doing consider using --info
# ./gradlew --info clean $BUILD_GRADLE_TASK
./gradlew clean $BUILD_GRADLE_TASK
# build-header.txt is sent to the distribution webserver with the apk
# WEB_REPO is a URL prepended to the commit id resulting in a web link to the commit
#
git log -n 1 --pretty=tformat:$"%cD :: <a href=\"$WEB_REPO/%H\">%h</a>%+cn<br />build #$BUILD_NUMBER on $BUILD_ID%+s" > build-header.txt
SymlinkAPK() {
local RELATIVE_DIR=$1
local RELATIVE_APK_PATH=$1"/"$ARTIFACT_APK
local BUILT_APK_NAME=$2
mkdir -p "$RELATIVE_DIR"
if [ -L "$RELATIVE_APK_PATH" ]
then
rm -f "$RELATIVE_APK_PATH"
fi
ln -s "../$BUILT_APK_ROOT$BUILT_APK_NAME" "$RELATIVE_APK_PATH"
echo "linked $BUILT_APK_NAME to $RELATIVE_APK_PATH"
openssl sha1 "$RELATIVE_APK_PATH"
}
SymlinkAPK "bin" $BUILD_APK_NAME
# CI build variable - has format of timestamp
echo $BUILD_ID > ${WORKSPACE}/build-id.txt
| {
"pile_set_name": "Github"
} |
%%-------------------------------------------------------------------
%% @author
%% ChicagoBoss Team and contributors, see AUTHORS file in root directory
%% @end
%% @copyright
%% This file is part of ChicagoBoss project.
%% See AUTHORS file in root directory
%% for license information, see LICENSE file in root directory
%% @end
%% @doc
%%-------------------------------------------------------------------
-module(boss_mq_sup).
-behaviour(supervisor).
-export([start_link/0, start_link/1]).
-export([init/1]).
start_link() ->
start_link([]).
start_link(StartArgs) ->
supervisor:start_link({global, ?MODULE}, ?MODULE, StartArgs).
init(StartArgs) ->
{ok, {{one_for_one, 10, 10}, [
{mq_controller, {boss_mq_controller, start_link, [StartArgs]},
permanent,
2000,
worker,
[boss_mq_controller]}
]}}.
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.