text
stringlengths 2
99.9k
| meta
dict |
---|---|
/*
* Copyright 2014-2016, Björn Ståhl
* License: 3-Clause BSD, see COPYING file in arcan source repository.
* Reference: http://arcan-fe.com
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include <unistd.h>
#include <inttypes.h>
#include "glfun.h"
#include "../video_platform.h"
#include PLATFORM_HEADER
#include "arcan_math.h"
#include "arcan_general.h"
#include "arcan_video.h"
#include "arcan_videoint.h"
static const char* defvprg =
"#version 120\n"
"uniform mat4 modelview;\n"
"uniform mat4 projection;\n"
"attribute vec2 texcoord;\n"
"varying vec2 texco;\n"
"attribute vec4 vertex;\n"
"void main(){\n"
" gl_Position = (projection * modelview) * vertex;\n"
" texco = texcoord;\n"
"}";
const char* deffprg =
"#version 120\n"
"uniform sampler2D map_diffuse;\n"
"varying vec2 texco;\n"
"uniform float obj_opacity;\n"
"void main(){\n"
" vec4 col = texture2D(map_diffuse, texco);\n"
" col.a = col.a * obj_opacity;\n"
" gl_FragColor = col;\n"
"}";
const char* defcfprg =
"#version 120\n"
"uniform vec3 obj_col;\n"
"uniform float obj_opacity;\n"
"void main(){\n"
" gl_FragColor = vec4(obj_col.rgb, obj_opacity);\n"
"}\n";
const char * defcvprg =
"#version 120\n"
"uniform mat4 modelview;\n"
"uniform mat4 projection;\n"
"attribute vec4 vertex;\n"
"void main(){\n"
" gl_Position = (projection * modelview) * vertex;\n"
"}";
#ifdef _DEBUG
#define DEBUG 1
#else
#define DEBUG 0
#endif
#define debug_print(fmt, ...) \
do { if (DEBUG) arcan_warning("%lld:%s:%d:%s(): " fmt "\n",\
arcan_timemillis(), "agp-gl21:", __LINE__, __func__,##__VA_ARGS__); } while (0)
#ifndef verbose_print
#define verbose_print
#endif
agp_shader_id agp_default_shader(enum SHADER_TYPES type)
{
verbose_print("set shader: %s", type == BASIC_2D ? "basic_2d" :
(type == COLOR_2D ? "color_2d" : (type == BASIC_3D ? "basic_3d" : "invalid")));
static agp_shader_id shids[SHADER_TYPE_ENDM];
static bool defshdr_build;
assert(type < SHADER_TYPE_ENDM);
if (!defshdr_build){
shids[BASIC_2D] = agp_shader_build("DEFAULT", NULL, defvprg, deffprg);
shids[COLOR_2D] = agp_shader_build(
"DEFAULT_COLOR", NULL, defcvprg, defcfprg);
shids[BASIC_3D] = shids[BASIC_2D];
defshdr_build = true;
}
return shids[type];
}
const char* agp_ident()
{
return "OPENGL21";
}
void agp_shader_source(enum SHADER_TYPES type,
const char** vert, const char** frag)
{
switch(type){
case BASIC_2D:
case BASIC_3D:
*vert = defvprg;
*frag = deffprg;
break;
case COLOR_2D:
*vert = defcvprg;
*frag = defcfprg;
break;
default:
*vert = NULL;
*frag = NULL;
break;
}
}
const char** agp_envopts()
{
static const char* env[] = {
NULL, NULL
};
return env;
}
const char* agp_shader_language()
{
return "GLSL120";
}
static void pbo_alloc_read(struct agp_vstore* store)
{
GLuint pboid;
struct agp_fenv* env = agp_env();
env->gen_buffers(1, &pboid);
store->vinf.text.rid = pboid;
env->bind_buffer(GL_PIXEL_PACK_BUFFER, pboid);
env->buffer_data(GL_PIXEL_PACK_BUFFER,
store->w * store->h * store->bpp, NULL, GL_STREAM_COPY);
env->bind_buffer(GL_PIXEL_PACK_BUFFER, 0);
verbose_print("allocated %zu*%zu read-pbo",
(size_t) store->w, (size_t) store->h);
}
static void pbo_alloc_write(struct agp_vstore* store)
{
GLuint pboid;
struct agp_fenv* env = agp_env();
env->gen_buffers(1, &pboid);
store->vinf.text.wid = pboid;
env->bind_buffer(GL_PIXEL_UNPACK_BUFFER, pboid);
env->buffer_data(GL_PIXEL_UNPACK_BUFFER,
store->w * store->h * store->bpp, NULL, GL_STREAM_DRAW);
env->bind_buffer(GL_PIXEL_UNPACK_BUFFER, 0);
verbose_print("allocated %zu*%zu write-pbo",
(size_t) store->w, (size_t) store->h);
}
static void rebuild_pbo(struct agp_vstore* s)
{
struct agp_fenv* env = agp_env();
if (s->vinf.text.wid){
env->delete_buffers(1, &s->vinf.text.wid);
pbo_alloc_write(s);
}
if (s->vinf.text.rid){
env->delete_buffers(1, &s->vinf.text.rid);
pbo_alloc_read(s);
}
}
static void set_pixel_store(size_t w, struct stream_meta const meta)
{
struct agp_fenv* env = agp_env();
env->pixel_storei(GL_UNPACK_SKIP_ROWS, meta.y1);
env->pixel_storei(GL_UNPACK_SKIP_PIXELS, meta.x1);
env->pixel_storei(GL_UNPACK_ROW_LENGTH, w);
verbose_print(
"pixel store: skip %zu rows, %zu pixels, len: %zu", meta.x1, meta.y1, w);
}
static void reset_pixel_store()
{
struct agp_fenv* env = agp_env();
env->pixel_storei(GL_UNPACK_SKIP_ROWS, 0);
env->pixel_storei(GL_UNPACK_SKIP_PIXELS, 0);
env->pixel_storei(GL_UNPACK_ROW_LENGTH, 0);
verbose_print("pixel store: reset");
}
void agp_readback_synchronous(struct agp_vstore* dst)
{
if (!(dst->txmapped == TXSTATE_TEX2D) || !dst->vinf.text.raw)
return;
struct agp_fenv* env = agp_env();
verbose_print(
"synchronous readback from id: %u", (unsigned)agp_resolve_texid(dst));
env->bind_texture(GL_TEXTURE_2D, agp_resolve_texid(dst));
env->get_tex_image(GL_TEXTURE_2D, 0,
GL_PIXEL_FORMAT, GL_UNSIGNED_BYTE, dst->vinf.text.raw);
dst->update_ts = arcan_timemillis();
env->bind_texture(GL_TEXTURE_2D, 0);
}
static void pbo_stream(struct agp_vstore* s,
av_pixel* buf, struct stream_meta* meta, bool synch)
{
agp_activate_vstore(s);
struct agp_fenv* env = agp_env();
env->bind_buffer(GL_PIXEL_UNPACK_BUFFER, s->vinf.text.wid);
size_t ntc = s->w * s->h;
av_pixel* ptr = env->map_buffer(GL_PIXEL_UNPACK_BUFFER,GL_WRITE_ONLY);
if (!ptr){
verbose_print("(%"PRIxPTR") failed to map PBO for writing", (uintptr_t) s);
return;
}
av_pixel* obuf = buf;
/* note, explicitly replace with a simd unaligned version */
if ( ((uintptr_t)ptr % 16) == 0 && ((uintptr_t)buf % 16) == 0 )
memcpy(ptr, buf, ntc * sizeof(av_pixel));
else
for (size_t i = 0; i < ntc; i++)
*ptr++ = *buf++;
/* synch :- on-host backing store, one extra copy into local buffer */
if (synch){
buf = obuf;
ptr = s->vinf.text.raw;
s->update_ts = arcan_timemillis();
if ( ((uintptr_t)ptr % 16) == 0 && ((uintptr_t)buf % 16) == 0 )
memcpy(ptr, buf, ntc * sizeof(av_pixel));
else
for (size_t i = 0; i < ntc; i++)
*ptr++ = *buf++;
}
verbose_print(
"(%"PRIxPTR") pbo stream update %zu*%zu", (uintptr_t) s, s->w, s->h);
env->unmap_buffer(GL_PIXEL_UNPACK_BUFFER);
env->tex_subimage_2d(GL_TEXTURE_2D, 0, 0, 0, s->w, s->h,
s->vinf.text.s_fmt ? s->vinf.text.s_fmt : GL_PIXEL_FORMAT,
GL_UNSIGNED_BYTE, 0
);
env->bind_buffer(GL_PIXEL_UNPACK_BUFFER, 0);
agp_deactivate_vstore();
}
/* positions and offsets in meta have been verified in _frameserver */
static void pbo_stream_sub(struct agp_vstore* s,
av_pixel* buf, struct stream_meta* meta, bool synch)
{
struct agp_fenv* env = agp_env();
if ( (float)(meta->w * meta->h) / (s->w * s->h) > 0.5)
return pbo_stream(s, buf, meta, synch);
agp_activate_vstore(s);
size_t row_sz = meta->w * sizeof(av_pixel);
set_pixel_store(s->w, *meta);
verbose_print(
"(%"PRIxPTR") pbo stream sub-update %zu+%zu*%zu+%zu",
(uintptr_t) s, meta->x1, meta->w, meta->y1, meta->h
);
env->tex_subimage_2d(GL_TEXTURE_2D, 0, meta->x1, meta->y1, meta->w, meta->h,
s->vinf.text.s_fmt ? s->vinf.text.s_fmt : GL_PIXEL_FORMAT,
GL_UNSIGNED_BYTE, buf
);
reset_pixel_store();
agp_deactivate_vstore(s);
if (synch){
av_pixel* cpy = s->vinf.text.raw;
for (size_t y = meta->y1; y < meta->y1 + meta->h; y++)
memcpy(&cpy[y * s->w + meta->x1], &buf[y * s->w + meta->x1], row_sz);
s->update_ts = arcan_timemillis();
}
/*
* Currently disabled approach to update subregion using PBO, experienced
* data corruption / driver bugs on several drivers :'(
*/
#if 0
av_pixel* ptr = glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, s->vinf.text.wid);
/* warning, with the normal copy we check alignment in beforehand as we have
* had cases where glMapBuffer intermittently returns unaligned pointers AND
* the compiler has emitted intrinsics that assumed alignment */
for (size_t y = meta->y1; y < meta->y1 + meta->h; y++)
memcpy(&ptr[y * s->w + meta->x1], &buf[y * s->w + meta->x1], row_sz);
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
glTexSubImage2D(GL_TEXTURE_2D, 0, meta->x1, meta->y1, meta->w, meta->h,
GL_PIXEL_FORMAT, GL_UNSIGNED_BYTE, 0);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
#endif
}
static inline void setup_unpack_pbo(struct agp_vstore* s, void* buf)
{
struct agp_fenv* env = agp_env();
agp_activate_vstore(s);
verbose_print("(%"PRIxPTR") build unpack", (uintptr_t) s);
env->gen_buffers(1, &s->vinf.text.wid);
env->bind_buffer(GL_PIXEL_UNPACK_BUFFER, s->vinf.text.wid);
env->buffer_data(GL_PIXEL_UNPACK_BUFFER,
s->w * s->h * sizeof(av_pixel) , buf, GL_STREAM_DRAW);
env->bind_buffer(GL_PIXEL_UNPACK_BUFFER, 0);
agp_deactivate_vstore();
}
static void alloc_buffer(struct agp_vstore* s)
{
if (s->vinf.text.s_raw != s->w * s->h * sizeof(av_pixel)){
arcan_mem_free(s->vinf.text.raw);
s->vinf.text.raw = NULL;
}
if (!s->vinf.text.raw){
verbose_print("(%"PRIxPTR") alloc buffer", (uintptr_t) s);
s->vinf.text.s_raw = s->w * s->h * sizeof(av_pixel);
s->vinf.text.raw = arcan_alloc_mem(s->vinf.text.s_raw,
ARCAN_MEM_VBUFFER, ARCAN_MEM_BZERO, ARCAN_MEMALIGN_PAGE);
}
}
struct stream_meta agp_stream_prepare(struct agp_vstore* s,
struct stream_meta meta, enum stream_type type)
{
struct agp_fenv* env = agp_env();
struct stream_meta res = meta;
res.state = true;
res.type = type;
switch (type){
case STREAM_RAW:
verbose_print("(%"PRIxPTR") prepare upload (raw)", (uintptr_t) s);
if (!s->vinf.text.wid)
setup_unpack_pbo(s, NULL);
alloc_buffer(s);
res.buf = s->vinf.text.raw;
res.state = res.buf != NULL;
break;
case STREAM_RAW_DIRECT_COPY:
alloc_buffer(s);
case STREAM_RAW_DIRECT:
verbose_print("(%"PRIxPTR") prepare upload (raw/direct)", (uintptr_t) s);
if (!s->vinf.text.wid)
setup_unpack_pbo(s, meta.buf);
if (meta.dirty)
pbo_stream_sub(s, meta.buf, &meta, type == STREAM_RAW_DIRECT_COPY);
else
pbo_stream(s, meta.buf, &meta, type == STREAM_RAW_DIRECT_COPY);
break;
/* resynch: drop PBOs and GLid, alloc / upload and rebuild possible PBOs */
case STREAM_EXT_RESYNCH:
verbose_print("(%"PRIxPTR") resynch stream", (uintptr_t) s);
agp_null_vstore(s);
agp_update_vstore(s, true);
rebuild_pbo(s);
break;
case STREAM_RAW_DIRECT_SYNCHRONOUS:
agp_activate_vstore(s);
if (meta.dirty){
verbose_print("(%"PRIxPTR") raw synch sub (%zu+%zu*%zu+%zu)",
(uintptr_t) s, meta.x1, meta.w, meta.y1, meta.h);
set_pixel_store(s->w, meta);
env->tex_subimage_2d(GL_TEXTURE_2D, 0, meta.x1, meta.y1, meta.w, meta.h,
s->vinf.text.s_fmt ? s->vinf.text.s_fmt : GL_PIXEL_FORMAT,
GL_UNSIGNED_BYTE, meta.buf
);
reset_pixel_store();
}
else
verbose_print(
"(%"PRIxPTR") raw synch (%zu*%zu)", (uintptr_t) s, meta.w, meta.h);
env->tex_subimage_2d(GL_TEXTURE_2D, 0, 0, 0, s->w, s->h,
s->vinf.text.s_fmt ? s->vinf.text.s_fmt : GL_PIXEL_FORMAT,
GL_UNSIGNED_BYTE, meta.buf
);
agp_deactivate_vstore();
break;
case STREAM_HANDLE:
/* if platform_video_map_handle fails here, prepare an empty vstore and attempt
* again, if that succeeds it means that we had to go through a RTT
* indirection, if that fails we should convey back to the client that
we can't accept this kind of transfer */
res.state = platform_video_map_handle(s, meta.handle);
break;
}
return res;
}
void agp_stream_release(struct agp_vstore* s, struct stream_meta meta)
{
struct agp_fenv* env = agp_env();
if (meta.dirty)
pbo_stream_sub(s, s->vinf.text.raw, &meta, false);
else
pbo_stream(s, s->vinf.text.raw, &meta, false);
verbose_print("(%"PRIxPTR") release", (uintptr_t) s);
env->unmap_buffer(GL_PIXEL_UNPACK_BUFFER);
env->bind_buffer(GL_PIXEL_UNPACK_BUFFER, GL_NONE);
}
void agp_stream_commit(struct agp_vstore* s, struct stream_meta meta)
{
}
static void default_release(void* tag)
{
if (!tag)
return;
struct agp_fenv* env = agp_env();
env->unmap_buffer(GL_PIXEL_PACK_BUFFER);
env->bind_buffer(GL_PIXEL_PACK_BUFFER, 0);
}
void agp_resize_vstore(struct agp_vstore* s, size_t w, size_t h)
{
struct agp_fenv* env = agp_env();
s->w = w;
s->h = h;
s->bpp = sizeof(av_pixel);
verbose_print("(%"PRIxPTR") resize to %zu * %zu", (uintptr_t) s, w, h);
alloc_buffer(s);
rebuild_pbo(s);
agp_update_vstore(s, true);
}
void agp_request_readback(struct agp_vstore* store)
{
if (!store || store->txmapped != TXSTATE_TEX2D)
return;
struct agp_fenv* env = agp_env();
if (!store->vinf.text.rid)
pbo_alloc_read(store);
verbose_print("(%"PRIxPTR":glid %u) getTexImage2D => PBO",
(uintptr_t) store, (unsigned) store->vinf.text.glid);
env->bind_texture(GL_TEXTURE_2D, agp_resolve_texid(store));
env->bind_buffer(GL_PIXEL_PACK_BUFFER, store->vinf.text.rid);
env->get_tex_image(GL_TEXTURE_2D, 0, GL_PIXEL_FORMAT, GL_UNSIGNED_BYTE, NULL);
env->bind_buffer(GL_PIXEL_PACK_BUFFER, 0);
env->bind_texture(GL_TEXTURE_2D, 0);
}
struct asynch_readback_meta agp_poll_readback(struct agp_vstore* store)
{
struct agp_fenv* env = agp_env();
struct asynch_readback_meta res = {
.release = default_release
};
if (!store || store->txmapped != TXSTATE_TEX2D ||
store->vinf.text.rid == GL_NONE)
return res;
env->bind_buffer(GL_PIXEL_PACK_BUFFER, store->vinf.text.rid);
res.w = store->w;
res.h = store->h;
res.tag = (void*) 0xdeadbeef;
res.ptr = (av_pixel*) env->map_buffer(GL_PIXEL_PACK_BUFFER, GL_READ_WRITE);
return res;
}
| {
"pile_set_name": "Github"
} |
<?php
namespace CssCrush\UnitTest;
use CssCrush\Regex;
class RegexTest extends \PHPUnit_Framework_TestCase
{
public function testMake()
{
$this->assertEquals('~(?<parens>\(\s*(?<parens_content>(?:(?>[^()]+)|(?&parens))*)\))~S',
Regex::make('~{{ parens }}~S'));
$this->assertEquals('~ #[[:xdigit:]]{3} ~xS', Regex::make('~ #{{hex}}{3} ~xS'));
}
public function testMatchAll()
{
$expected = [
[['foo', 0]],
[['foo', 12]],
];
$matches = Regex::matchAll('~foo~', 'foo bar baz foo bar baz');
$this->assertEquals($expected, $matches);
}
}
| {
"pile_set_name": "Github"
} |
var baseDifference = require('../internal/baseDifference'),
baseFlatten = require('../internal/baseFlatten'),
isArrayLike = require('../internal/isArrayLike'),
isObjectLike = require('../internal/isObjectLike'),
restParam = require('../function/restParam');
/**
* Creates an array of unique `array` values not included in the other
* provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The arrays of values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.difference([1, 2, 3], [4, 2]);
* // => [1, 3]
*/
var difference = restParam(function(array, values) {
return (isObjectLike(array) && isArrayLike(array))
? baseDifference(array, baseFlatten(values, false, true))
: [];
});
module.exports = difference;
| {
"pile_set_name": "Github"
} |
EESchema-DOCLIB Version 2.0
#
$CMP CAP1188-1-CP-TR
D IC TOUCH SENSOR/LED DRVR 24VQFN
K CAP1188-1-CP-TRCT-ND
F http://www.microchip.com/mymicrochip/filehandler.aspx?ddocname=en561990
$ENDCMP
#
#End Doc Library | {
"pile_set_name": "Github"
} |
import {
BaseRequestPolicy,
HttpOperationResponse,
RequestPolicy,
RequestPolicyOptions,
WebResource,
RestError
} from "../../src";
export interface NextInjectErrorHolder {
nextInjectError?: RestError;
}
export type Injector = () => RestError | undefined;
/**
* InjectorPolicy will inject a customized error before next HTTP request.
*
* @class InjectorPolicy
* @extends {BaseRequestPolicy}
*/
export class InjectorPolicy extends BaseRequestPolicy {
/**
* Creates an instance of InjectorPolicy.
*
* @param {RequestPolicy} nextPolicy
* @param {RequestPolicyOptions} options
* @memberof InjectorPolicy
*/
public constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, injector: Injector) {
super(nextPolicy, options);
this.injector = injector;
}
/**
* Sends request.
*
* @param {WebResource} request
* @returns {Promise<HttpOperationResponse>}
* @memberof InjectorPolicy
*/
public async sendRequest(request: WebResource): Promise<HttpOperationResponse> {
const error = this.injector();
if (error) {
throw error;
}
return this._nextPolicy.sendRequest(request);
}
private injector: Injector;
}
| {
"pile_set_name": "Github"
} |
#include "sx/allocator.h"
#include "sx/io.h"
#include "sx/string.h"
#include <stdio.h>
static const uint8_t dummy_data[473] =
{
0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x73, 0x22, 0x3a,
0x20, 0x5b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x74, 0x68, 0x22, 0x3a,
0x20, 0x22, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x5f, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64,
0x65, 0x5f, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x5b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x62, 0x75, 0x69, 0x6c, 0x64, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x2e, 0x76, 0x73, 0x63, 0x6f, 0x64, 0x65,
0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x2e, 0x63, 0x6c, 0x61, 0x6e, 0x67, 0x64, 0x22, 0x2c, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62,
0x69, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x2d, 0x2a, 0x22, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5d, 0x2c, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x69, 0x6c, 0x65, 0x5f,
0x65, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x5f, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x73,
0x22, 0x3a, 0x20, 0x5b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x2e, 0x67, 0x69, 0x74, 0x69, 0x67, 0x6e, 0x6f, 0x72, 0x65,
0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x2e, 0x74, 0x72, 0x61, 0x76, 0x69, 0x73, 0x2e, 0x79, 0x6d, 0x6c, 0x22,
0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x2e, 0x67, 0x69, 0x74, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x73, 0x22, 0x2c,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x22, 0x2e, 0x63, 0x6c, 0x61, 0x6e, 0x67, 0x2d, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x22,
0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x63, 0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x65, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x61,
0x6e, 0x64, 0x73, 0x2e, 0x6a, 0x73, 0x6f, 0x6e, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x5d, 0x0a, 0x7d,
};
#define LEVEL1_FOURCC sx_makefourcc('L', 'V', 'L', '1')
#define LEVEL2_FOURCC sx_makefourcc('L', 'V', 'L', '2')
static void test_write_iff(const char* filename)
{
sx_file f;
if (sx_file_open(&f, filename, SX_FILE_WRITE)) {
sx_iff_file iff;
sx_iff_init_from_file_writer(&iff, &f, 0, sx_alloc_malloc());
int level1 = sx_iff_put_chunk(&iff, 0, LEVEL1_FOURCC, dummy_data, sizeof(dummy_data), 0, 0);
sx_iff_put_chunk(&iff, level1, LEVEL2_FOURCC, dummy_data, sizeof(dummy_data), 0, 0);
sx_iff_put_chunk(&iff, level1, LEVEL2_FOURCC, dummy_data, sizeof(dummy_data), 0, 0);
sx_iff_put_chunk(&iff, 0, LEVEL1_FOURCC, dummy_data, sizeof(dummy_data), 0, 0);
sx_iff_release(&iff);
sx_file_close(&f);
}
}
static void test_append_iff(const char* filename)
{
sx_file f;
if (sx_file_open(&f, filename, SX_FILE_WRITE|SX_FILE_APPEND)) {
sx_iff_file iff;
sx_iff_init_from_file_writer(&iff, &f, SX_IFFFLAG_APPEND|SX_IFFFLAG_READ_ALL_CHUNKS, sx_alloc_malloc());
int level1 = sx_iff_put_chunk(&iff, 0, LEVEL1_FOURCC, dummy_data, sizeof(dummy_data), 0, 0);
sx_iff_put_chunk(&iff, level1, LEVEL2_FOURCC, dummy_data, sizeof(dummy_data), 0, 0);
sx_iff_put_chunk(&iff, level1, LEVEL2_FOURCC, dummy_data, sizeof(dummy_data), 0, 0);
sx_iff_put_chunk(&iff, 0, LEVEL1_FOURCC, dummy_data, sizeof(dummy_data), 0, 0);
sx_iff_release(&iff);
sx_file_close(&f);
}
}
static const char* get_tabs(int depth)
{
static char depth_str[256];
for (int i = 0; i < depth; i++) {
depth_str[i] = '\t';
}
depth_str[depth] = '\0';
return depth_str;
}
static void test_load_iff(const char* filename)
{
sx_file f;
if (sx_file_open(&f, filename, SX_FILE_READ)) {
sx_iff_file iff;
sx_iff_init_from_file_reader(&iff, &f, 0, sx_alloc_malloc());
int depth = 0;
int level1 = sx_iff_get_chunk(&iff, LEVEL1_FOURCC, 0);
while (level1 != -1) {
printf("%sChunk [Level%d] - size: %u (parent: %d)\n",
get_tabs(depth), depth+1, (uint32_t)iff.chunks[level1].size, iff.chunks[level1].parent_id);
depth++;
int level2 = sx_iff_get_chunk(&iff, LEVEL2_FOURCC, level1);
while (level2 != -1) {
printf("%sChunk [level%d] - size: %u (parent: %d)\n",
get_tabs(depth), depth+1, (uint32_t)iff.chunks[level2].size, iff.chunks[level2].parent_id);
level2 = sx_iff_get_next_chunk(&iff, level2);
}
depth--;
level1 = sx_iff_get_next_chunk(&iff, level1);
}
}
}
int main(int argc, char* argv[])
{
if (argc != 2) {
puts("You must provide a command and a file:");
puts(" test-iff load");
puts(" test-iff save");
return -1;
}
const char* command = argv[1];
if (strcmp(command, "save") == 0) {
test_write_iff("test.bin");
} else if (strcmp(command, "load") == 0) {
test_load_iff("test.bin");
} else if (strcmp(command, "append") == 0) {
test_append_iff("test.bin");
}
return 0;
} | {
"pile_set_name": "Github"
} |
#! gmake
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
CORE_DEPTH = ..
DEPTH = ..
include manifest.mn
include $(CORE_DEPTH)/coreconf/config.mk
ifdef BUILD_LIBPKIX_TESTS
DIRS += libpkix
endif
ifeq ($(NSS_BUILD_WITHOUT_SOFTOKEN),1)
BLTEST_SRCDIR =
ECPERF_SRCDIR =
FREEBL_ECTEST_SRCDIR =
FIPSTEST_SRCDIR =
SHLIBSIGN_SRCDIR =
else
BLTEST_SRCDIR = bltest
ECPERF_SRCDIR = ecperf
FREEBL_ECTEST_SRCDIR = fbectest
FIPSTEST_SRCDIR = fipstest
SHLIBSIGN_SRCDIR = shlibsign
endif
LOWHASHTEST_SRCDIR=
ifeq ($(FREEBL_LOWHASH),1)
LOWHASHTEST_SRCDIR = lowhashtest # Add the lowhashtest directory to DIRS.
endif
INCLUDES += \
-I$(DIST)/../public/security \
-I./include \
$(NULL)
include $(CORE_DEPTH)/coreconf/rules.mk
symbols::
@echo "TARGETS = $(TARGETS)"
| {
"pile_set_name": "Github"
} |
<?php
/**
* @package Joomla.Component.Builder
*
* @created 30th April, 2015
* @author Llewellyn van der Merwe <http://www.joomlacomponentbuilder.com>
* @github Joomla Component Builder <https://github.com/vdm-io/Joomla-Component-Builder>
* @copyright Copyright (C) 2015 - 2020 Vast Development Method. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
use Joomla\Utilities\ArrayHelper;
/**
* Library_files_folders_urls Controller
*/
class ComponentbuilderControllerLibrary_files_folders_urls extends JControllerForm
{
/**
* Current or most recently performed task.
*
* @var string
* @since 12.2
* @note Replaces _task.
*/
protected $task;
/**
* Class constructor.
*
* @param array $config A named array of configuration variables.
*
* @since 1.6
*/
public function __construct($config = array())
{
$this->view_list = 'Libraries_files_folders_urls'; // safeguard for setting the return view listing to the main view.
parent::__construct($config);
}
/**
* Method override to check if you can add a new record.
*
* @param array $data An array of input data.
*
* @return boolean
*
* @since 1.6
*/
protected function allowAdd($data = array())
{
// Get user object.
$user = JFactory::getUser();
// Access check.
$access = $user->authorise('library_files_folders_urls.access', 'com_componentbuilder');
if (!$access)
{
return false;
}
// In the absense of better information, revert to the component permissions.
return $user->authorise('library_files_folders_urls.create', $this->option);
}
/**
* Method override to check if you can edit an existing record.
*
* @param array $data An array of input data.
* @param string $key The name of the key for the primary key.
*
* @return boolean
*
* @since 1.6
*/
protected function allowEdit($data = array(), $key = 'id')
{
// get user object.
$user = JFactory::getUser();
// get record id.
$recordId = (int) isset($data[$key]) ? $data[$key] : 0;
// Access check.
$access = ($user->authorise('library_files_folders_urls.access', 'com_componentbuilder.library_files_folders_urls.' . (int) $recordId) && $user->authorise('library_files_folders_urls.access', 'com_componentbuilder'));
if (!$access)
{
return false;
}
if ($recordId)
{
// The record has been set. Check the record permissions.
$permission = $user->authorise('library_files_folders_urls.edit', 'com_componentbuilder.library_files_folders_urls.' . (int) $recordId);
if (!$permission)
{
if ($user->authorise('library_files_folders_urls.edit.own', 'com_componentbuilder.library_files_folders_urls.' . $recordId))
{
// Now test the owner is the user.
$ownerId = (int) isset($data['created_by']) ? $data['created_by'] : 0;
if (empty($ownerId))
{
// Need to do a lookup from the model.
$record = $this->getModel()->getItem($recordId);
if (empty($record))
{
return false;
}
$ownerId = $record->created_by;
}
// If the owner matches 'me' then allow.
if ($ownerId == $user->id)
{
if ($user->authorise('library_files_folders_urls.edit.own', 'com_componentbuilder'))
{
return true;
}
}
}
return false;
}
}
// Since there is no permission, revert to the component permissions.
return $user->authorise('library_files_folders_urls.edit', $this->option);
}
/**
* Gets the URL arguments to append to an item redirect.
*
* @param integer $recordId The primary key id for the item.
* @param string $urlVar The name of the URL variable for the id.
*
* @return string The arguments to append to the redirect URL.
*
* @since 1.6
*/
protected function getRedirectToItemAppend($recordId = null, $urlVar = 'id')
{
// get the referral options (old method use return instead see parent)
$ref = $this->input->get('ref', 0, 'string');
$refid = $this->input->get('refid', 0, 'int');
// get redirect info.
$append = parent::getRedirectToItemAppend($recordId, $urlVar);
// set the referral options
if ($refid && $ref)
{
$append = '&ref=' . (string)$ref . '&refid='. (int)$refid . $append;
}
elseif ($ref)
{
$append = '&ref='. (string)$ref . $append;
}
return $append;
}
/**
* Method to run batch operations.
*
* @param object $model The model.
*
* @return boolean True if successful, false otherwise and internal error is set.
*
* @since 2.5
*/
public function batch($model = null)
{
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Set the model
$model = $this->getModel('Library_files_folders_urls', '', array());
// Preset the redirect
$this->setRedirect(JRoute::_('index.php?option=com_componentbuilder&view=libraries_files_folders_urls' . $this->getRedirectToListAppend(), false));
return parent::batch($model);
}
/**
* Method to cancel an edit.
*
* @param string $key The name of the primary key of the URL variable.
*
* @return boolean True if access level checks pass, false otherwise.
*
* @since 12.2
*/
public function cancel($key = null)
{
// get the referral options
$this->ref = $this->input->get('ref', 0, 'word');
$this->refid = $this->input->get('refid', 0, 'int');
// Check if there is a return value
$return = $this->input->get('return', null, 'base64');
$cancel = parent::cancel($key);
if (!is_null($return) && JUri::isInternal(base64_decode($return)))
{
$redirect = base64_decode($return);
// Redirect to the return value.
$this->setRedirect(
JRoute::_(
$redirect, false
)
);
}
elseif ($this->refid && $this->ref)
{
$redirect = '&view=' . (string)$this->ref . '&layout=edit&id=' . (int)$this->refid;
// Redirect to the item screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . $redirect, false
)
);
}
elseif ($this->ref)
{
$redirect = '&view='.(string)$this->ref;
// Redirect to the list screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . $redirect, false
)
);
}
return $cancel;
}
/**
* Method to save a record.
*
* @param string $key The name of the primary key of the URL variable.
* @param string $urlVar The name of the URL variable if different from the primary key (sometimes required to avoid router collisions).
*
* @return boolean True if successful, false otherwise.
*
* @since 12.2
*/
public function save($key = null, $urlVar = null)
{
// get the referral options
$this->ref = $this->input->get('ref', 0, 'word');
$this->refid = $this->input->get('refid', 0, 'int');
// Check if there is a return value
$return = $this->input->get('return', null, 'base64');
$canReturn = (!is_null($return) && JUri::isInternal(base64_decode($return)));
if ($this->ref || $this->refid || $canReturn)
{
// to make sure the item is checkedin on redirect
$this->task = 'save';
}
$saved = parent::save($key, $urlVar);
// This is not needed since parent save already does this
// Due to the ref and refid implementation we need to add this
if ($canReturn)
{
$redirect = base64_decode($return);
// Redirect to the return value.
$this->setRedirect(
JRoute::_(
$redirect, false
)
);
}
elseif ($this->refid && $this->ref)
{
$redirect = '&view=' . (string)$this->ref . '&layout=edit&id=' . (int)$this->refid;
// Redirect to the item screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . $redirect, false
)
);
}
elseif ($this->ref)
{
$redirect = '&view=' . (string)$this->ref;
// Redirect to the list screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . $redirect, false
)
);
}
return $saved;
}
/**
* Function that allows child controller access to model data
* after the data has been saved.
*
* @param JModel &$model The data model object.
* @param array $validData The validated data.
*
* @return void
*
* @since 11.1
*/
protected function postSaveHook(JModelLegacy $model, $validData = array())
{
return;
}
}
| {
"pile_set_name": "Github"
} |
#
# OpenSSL example configuration file.
# This is mostly being used for generation of certificate requests.
#
# This definition stops the following lines choking if HOME isn't
# defined.
HOME = .
RANDFILE = $ENV::HOME/.rnd
####################################################################
[ ca ]
default_ca = CA_default # The default ca section
####################################################################
[ CA_default ]
dir = .ca # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
#unique_subject = no # Set to 'no' to allow creation of
# several certs with same subject.
new_certs_dir = $dir/newcerts # default place for new certs.
certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crlnumber = $dir/crlnumber # the current crl number
# must be commented out to leave a V1 CRL
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/cakey.pem# The private key
RANDFILE = $dir/private/.rand # private random number file
x509_extensions = usr_cert # The extensions to add to the cert
# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options
# Extension copying option: use with caution.
# copy_extensions = copy
# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crlnumber must also be commented out to leave a V1 CRL.
# crl_extensions = crl_ext
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = sm3 # use public key default MD
preserve = no # keep passed DN ordering
# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy = policy_match
# For the CA policy
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
####################################################################
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca # The extensions to add to the self signed cert
# Passwords for private keys if not present they will be prompted for
# input_password = secret
# output_password = secret
# This sets a mask for permitted string types. There are several options.
# default: PrintableString, T61String, BMPString.
# pkix : PrintableString, BMPString (PKIX recommendation before 2004)
# utf8only: only UTF8Strings (PKIX recommendation after 2004).
# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
# MASK:XXXX a literal mask value.
# WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings.
string_mask = utf8only
# req_extensions = v3_req # The extensions to add to a certificate request
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = CN
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = BJ
localityName = Locality Name (eg, city)
localityName_default = BJ
0.organizationName = Organization Name (eg, company)
0.organizationName_default = PKU
# we can do this but it is not needed normally :-)
#1.organizationName = Second Organization Name (eg, company)
#1.organizationName_default = World Wide Web Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
organizationalUnitName_default = CS
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 64
# SET-ex3 = SET extension number 3
[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20
unstructuredName = An optional company name
[ usr_cert ]
# These extensions are added when 'ca' signs a request.
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints=CA:FALSE
# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.
# This is OK for an SSL server.
# nsCertType = server
# For an object signing certificate this would be used.
# nsCertType = objsign
# For normal client use this is typical
# nsCertType = client, email
# and for everything including object signing:
# nsCertType = client, email, objsign
# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
#keyUsage = digitalSignature
keyUsage = keyEncipherment
# This will be displayed in Netscape's comment listbox.
nsComment = "OpenSSL Generated Certificate"
# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move
# Copy subject details
# issuerAltName=issuer:copy
#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName
# This is required for TSA certificates.
# extendedKeyUsage = critical,timeStamping
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
[ v3_ca ]
# Extensions for a typical CA
# PKIX recommendation.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
basicConstraints = critical,CA:true
# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
# keyUsage = cRLSign, keyCertSign
# Some might want this also
# nsCertType = sslCA, emailCA
# Include email address in subject alt name: another PKIX recommendation
# subjectAltName=email:copy
# Copy issuer details
# issuerAltName=issuer:copy
# DER hex encoding of an extension: beware experts only!
# obj=DER:02:03
# Where 'obj' is a standard or added object
# You can even override a supported extension:
# basicConstraints= critical, DER:30:03:01:01:FF
[ crl_ext ]
# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
# issuerAltName=issuer:copy
authorityKeyIdentifier=keyid:always
[ proxy_cert_ext ]
# These extensions should be added when creating a proxy certificate
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints=CA:FALSE
# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.
# This is OK for an SSL server.
# nsCertType = server
# For an object signing certificate this would be used.
# nsCertType = objsign
# For normal client use this is typical
# nsCertType = client, email
# and for everything including object signing:
# nsCertType = client, email, objsign
# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
# This will be displayed in Netscape's comment listbox.
nsComment = "OpenSSL Generated Certificate"
# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move
# Copy subject details
# issuerAltName=issuer:copy
#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName
# This really needs to be in place for it to be a proxy certificate.
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2009-2017 ARM Limited. All rights reserved.
SPDX-License-Identifier: Apache-2.0
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
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.
NOTICE: This file has been modified by Nordic Semiconductor ASA.
*/
/* NOTE: Template files (including this one) are application specific and therefore expected to
be copied into the application project folder prior to its use! */
#include <stdint.h>
#include <stdbool.h>
#include "nrf.h"
#include "system_nrf52810.h"
/*lint ++flb "Enter library region" */
#define __SYSTEM_CLOCK_64M (64000000UL)
static bool errata_31(void);
static bool errata_36(void);
static bool errata_66(void);
static bool errata_103(void);
static bool errata_136(void);
/* Helper functions for Errata workarounds in nRF52832 */
#if defined (DEVELOP_IN_NRF52832)
static bool errata_12(void);
static bool errata_16(void);
static bool errata_32(void);
static bool errata_37(void);
static bool errata_57(void);
static bool errata_108(void);
#endif
#if defined ( __CC_ARM )
uint32_t SystemCoreClock __attribute__((used)) = __SYSTEM_CLOCK_64M;
#elif defined ( __ICCARM__ )
__root uint32_t SystemCoreClock = __SYSTEM_CLOCK_64M;
#elif defined ( __GNUC__ )
uint32_t SystemCoreClock __attribute__((used)) = __SYSTEM_CLOCK_64M;
#endif
void SystemCoreClockUpdate(void)
{
SystemCoreClock = __SYSTEM_CLOCK_64M;
}
void SystemInit(void)
{
/* Enable SWO trace functionality. If ENABLE_SWO is not defined, SWO pin will be used as GPIO (see Product
Specification to see which one). Only available if the developing environment is an nRF52832 device. */
#if defined (DEVELOP_IN_NRF52832) && defined (ENABLE_SWO)
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
NRF_CLOCK->TRACECONFIG |= CLOCK_TRACECONFIG_TRACEMUX_Serial << CLOCK_TRACECONFIG_TRACEMUX_Pos;
NRF_P0->PIN_CNF[18] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos);
#endif
/* Enable Trace functionality. If ENABLE_TRACE is not defined, TRACE pins will be used as GPIOs (see Product
Specification to see which ones). Only available if the developing environment is an nRF52832 device. */
#if defined (DEVELOP_IN_NRF52832) && defined (ENABLE_TRACE)
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
NRF_CLOCK->TRACECONFIG |= CLOCK_TRACECONFIG_TRACEMUX_Parallel << CLOCK_TRACECONFIG_TRACEMUX_Pos;
NRF_P0->PIN_CNF[14] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos);
NRF_P0->PIN_CNF[15] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos);
NRF_P0->PIN_CNF[16] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos);
NRF_P0->PIN_CNF[18] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos);
NRF_P0->PIN_CNF[20] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos);
#endif
#if defined (DEVELOP_IN_NRF52832)
/* Workaround for Errata 12 "COMP: Reference ladder not correctly calibrated" found at the Errata document
for nRF52832 device located at https://infocenter.nordicsemi.com/ */
if (errata_12()){
*(volatile uint32_t *)0x40013540 = (*(uint32_t *)0x10000324 & 0x00001F00) >> 8;
}
#endif
#if defined (DEVELOP_IN_NRF52832)
/* Workaround for Errata 16 "System: RAM may be corrupt on wakeup from CPU IDLE" found at the Errata document
for nRF52832 device located at https://infocenter.nordicsemi.com/ */
if (errata_16()){
*(volatile uint32_t *)0x4007C074 = 3131961357ul;
}
#endif
/* Workaround for Errata 31 "CLOCK: Calibration values are not correctly loaded from FICR at reset" found at the Errata document
for your device located at https://infocenter.nordicsemi.com/ */
if (errata_31()){
*(volatile uint32_t *)0x4000053C = ((*(volatile uint32_t *)0x10000244) & 0x0000E000) >> 13;
}
#if defined (DEVELOP_IN_NRF52832)
/* Workaround for Errata 32 "DIF: Debug session automatically enables TracePort pins" found at the Errata document
for nRF52832 device located at https://infocenter.nordicsemi.com/ */
if (errata_32()){
CoreDebug->DEMCR &= ~CoreDebug_DEMCR_TRCENA_Msk;
}
#endif
/* Workaround for Errata 36 "CLOCK: Some registers are not reset when expected" found at the Errata document
for your device located at https://infocenter.nordicsemi.com/ */
if (errata_36()){
NRF_CLOCK->EVENTS_DONE = 0;
NRF_CLOCK->EVENTS_CTTO = 0;
NRF_CLOCK->CTIV = 0;
}
#if defined (DEVELOP_IN_NRF52832)
/* Workaround for Errata 37 "RADIO: Encryption engine is slow by default" found at the Errata document
for your device located at https://infocenter.nordicsemi.com/ */
if (errata_37()){
*(volatile uint32_t *)0x400005A0 = 0x3;
}
#endif
#if defined (DEVELOP_IN_NRF52832)
/* Workaround for Errata 57 "NFCT: NFC Modulation amplitude" found at the Errata document
for your device located at https://infocenter.nordicsemi.com/ */
if (errata_57()){
*(volatile uint32_t *)0x40005610 = 0x00000005;
*(volatile uint32_t *)0x40005688 = 0x00000001;
*(volatile uint32_t *)0x40005618 = 0x00000000;
*(volatile uint32_t *)0x40005614 = 0x0000003F;
}
#endif
/* Workaround for Errata 66 "TEMP: Linearity specification not met with default settings" found at the Errata document
for your device located at https://infocenter.nordicsemi.com/ */
if (errata_66()){
NRF_TEMP->A0 = NRF_FICR->TEMP.A0;
NRF_TEMP->A1 = NRF_FICR->TEMP.A1;
NRF_TEMP->A2 = NRF_FICR->TEMP.A2;
NRF_TEMP->A3 = NRF_FICR->TEMP.A3;
NRF_TEMP->A4 = NRF_FICR->TEMP.A4;
NRF_TEMP->A5 = NRF_FICR->TEMP.A5;
NRF_TEMP->B0 = NRF_FICR->TEMP.B0;
NRF_TEMP->B1 = NRF_FICR->TEMP.B1;
NRF_TEMP->B2 = NRF_FICR->TEMP.B2;
NRF_TEMP->B3 = NRF_FICR->TEMP.B3;
NRF_TEMP->B4 = NRF_FICR->TEMP.B4;
NRF_TEMP->B5 = NRF_FICR->TEMP.B5;
NRF_TEMP->T0 = NRF_FICR->TEMP.T0;
NRF_TEMP->T1 = NRF_FICR->TEMP.T1;
NRF_TEMP->T2 = NRF_FICR->TEMP.T2;
NRF_TEMP->T3 = NRF_FICR->TEMP.T3;
NRF_TEMP->T4 = NRF_FICR->TEMP.T4;
}
/* Workaround for Errata 103 "CCM: Wrong reset value of CCM MAXPACKETSIZE" found at the Errata document
for your device located at https://infocenter.nordicsemi.com/ */
if (errata_103()){
NRF_CCM->MAXPACKETSIZE = 0xFBul;
}
#if defined (DEVELOP_IN_NRF52832)
/* Workaround for Errata 108 "RAM: RAM content cannot be trusted upon waking up from System ON Idle or System OFF mode" found at the Errata document
for your device located at https://infocenter.nordicsemi.com/ */
if (errata_108()){
*(volatile uint32_t *)0x40000EE4 = *(volatile uint32_t *)0x10000258 & 0x0000004F;
}
#endif
/* Workaround for Errata 136 "System: Bits in RESETREAS are set when they should not be" found at the Errata document
for your device located at https://infocenter.nordicsemi.com/ */
if (errata_136()){
if (NRF_POWER->RESETREAS & POWER_RESETREAS_RESETPIN_Msk){
NRF_POWER->RESETREAS = ~POWER_RESETREAS_RESETPIN_Msk;
}
}
/* Configure GPIO pads as pPin Reset pin if Pin Reset capabilities desired. If CONFIG_GPIO_AS_PINRESET is not
defined, pin reset will not be available. One GPIO (see Product Specification to see which one) will then be
reserved for PinReset and not available as normal GPIO. */
#if defined (CONFIG_GPIO_AS_PINRESET)
if (((NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) != (UICR_PSELRESET_CONNECT_Connected << UICR_PSELRESET_CONNECT_Pos)) ||
((NRF_UICR->PSELRESET[1] & UICR_PSELRESET_CONNECT_Msk) != (UICR_PSELRESET_CONNECT_Connected << UICR_PSELRESET_CONNECT_Pos))){
NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos;
while (NRF_NVMC->READY == NVMC_READY_READY_Busy){}
NRF_UICR->PSELRESET[0] = 21;
while (NRF_NVMC->READY == NVMC_READY_READY_Busy){}
NRF_UICR->PSELRESET[1] = 21;
while (NRF_NVMC->READY == NVMC_READY_READY_Busy){}
NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos;
while (NRF_NVMC->READY == NVMC_READY_READY_Busy){}
NVIC_SystemReset();
}
#endif
SystemCoreClockUpdate();
}
#if defined (DEVELOP_IN_NRF52832)
static bool errata_12(void)
{
if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x6) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0)){
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x30){
return true;
}
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x40){
return true;
}
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x50){
return true;
}
}
return false;
}
#endif
#if defined (DEVELOP_IN_NRF52832)
static bool errata_16(void)
{
if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x6) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0)){
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x30){
return true;
}
}
return false;
}
#endif
static bool errata_31(void)
{
if ((*(uint32_t *)0x10000130ul == 0xAul) && (*(uint32_t *)0x10000134ul == 0x0ul)){
return true;
}
#if defined (DEVELOP_IN_NRF52832)
if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x6) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0)){
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x30){
return true;
}
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x40){
return true;
}
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x50){
return true;
}
}
#endif
return true;
}
#if defined (DEVELOP_IN_NRF52832)
static bool errata_32(void)
{
if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x6) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0)){
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x30){
return true;
}
}
return false;
}
#endif
static bool errata_36(void)
{
if ((*(uint32_t *)0x10000130ul == 0xAul) && (*(uint32_t *)0x10000134ul == 0x0ul)){
return true;
}
#if defined (DEVELOP_IN_NRF52832)
if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x6) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0)){
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x30){
return true;
}
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x40){
return true;
}
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x50){
return true;
}
}
#endif
return true;
}
#if defined (DEVELOP_IN_NRF52832)
static bool errata_37(void)
{
if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x6) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0)){
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x30){
return true;
}
}
return false;
}
#endif
#if defined (DEVELOP_IN_NRF52832)
static bool errata_57(void)
{
if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x6) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0)){
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x30){
return true;
}
}
return false;
}
#endif
static bool errata_66(void)
{
if ((*(uint32_t *)0x10000130ul == 0xAul) && (*(uint32_t *)0x10000134ul == 0x0ul)){
return true;
}
#if defined (DEVELOP_IN_NRF52832)
if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x6) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0)){
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x50){
return true;
}
}
#endif
return true;
}
static bool errata_103(void)
{
if ((*(uint32_t *)0x10000130ul == 0xAul) && (*(uint32_t *)0x10000134ul == 0x0ul)){
return true;
}
return true;
}
#if defined (DEVELOP_IN_NRF52832)
static bool errata_108(void)
{
if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x6) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0)){
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x30){
return true;
}
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x40){
return true;
}
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x50){
return true;
}
}
return false;
}
#endif
static bool errata_136(void)
{
if ((*(uint32_t *)0x10000130ul == 0xAul) && (*(uint32_t *)0x10000134ul == 0x0ul)){
return true;
}
#if defined (DEVELOP_IN_NRF52832)
if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x6) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0)){
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x30){
return true;
}
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x40){
return true;
}
if (((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x50){
return true;
}
}
#endif
return true;
}
/*lint --flb "Leave library region" */
| {
"pile_set_name": "Github"
} |
$pkg_name="python"
$pkg_version="3.7.3"
$pkg_origin="core"
$pkg_maintainer="The Habitat Maintainers <[email protected]>"
$pkg_license=@('Python-2.0')
$pkg_description="Python is a programming language that lets you work quickly and integrate systems more effectively."
$pkg_upstream_url="https://www.python.org"
$pkg_build_deps=@("core/nuget")
$pkg_bin_dirs=@("bin", "bin/Scripts")
function Invoke-Build {
nuget install python -version $pkg_version -ExcludeVersion -OutputDirectory "$HAB_CACHE_SRC_PATH/$pkg_dirname"
}
function Invoke-Install {
Remove-Item "$pkg_prefix/bin/Scripts"
Copy-Item "$HAB_CACHE_SRC_PATH/$pkg_dirname/python/tools/*" "$pkg_prefix/bin" -Recurse
}
function Invoke-Check {
& "$HAB_CACHE_SRC_PATH/$pkg_dirname/python/tools/python" -m pip --version
if($LASTEXITCODE -ne 0) { Write-Error "Invoke check failed with error code $LASTEXITCODE" }
}
| {
"pile_set_name": "Github"
} |
package test.unit.gov.nist.javax.sip.stack;
import gov.nist.javax.sip.SipStackImpl;
import java.util.ArrayList;
import java.util.EventObject;
import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.DialogTerminatedEvent;
import javax.sip.IOExceptionEvent;
import javax.sip.ListeningPoint;
import javax.sip.RequestEvent;
import javax.sip.ResponseEvent;
import javax.sip.ServerTransaction;
import javax.sip.SipListener;
import javax.sip.SipProvider;
import javax.sip.TimeoutEvent;
import javax.sip.Transaction;
import javax.sip.TransactionTerminatedEvent;
import javax.sip.address.Address;
import javax.sip.address.SipURI;
import javax.sip.header.CSeqHeader;
import javax.sip.header.CallIdHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.ContentTypeHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.Header;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.RouteHeader;
import javax.sip.header.ToHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import test.tck.msgflow.callflows.ProtocolObjects;
import test.tck.msgflow.callflows.ScenarioHarness;
public class SelfroutingTest extends ScenarioHarness {
protected Shootist shootist;
private static Logger logger = Logger.getLogger("test.tck");
static {
if (!logger.isAttached(console))
logger.addAppender(console);
}
class Shootist implements SipListener {
private SipProvider provider;
private ContactHeader contactHeader;
private ListeningPoint listeningPoint;
// To run on two machines change these to suit.
public static final String myAddress = "127.0.0.1";
private static final int myPort = 5060;
protected ClientTransaction inviteTid;
private ProtocolObjects protocolObjects;
private Dialog dialog;
public Shootist(ProtocolObjects protocolObjects) {
super();
this.protocolObjects = protocolObjects;
}
public void processRequest(RequestEvent requestReceivedEvent) {
Request request = requestReceivedEvent.getRequest();
ServerTransaction serverTransactionId = requestReceivedEvent
.getServerTransaction();
logger.info("\n\nRequest " + request.getMethod() + " received at "
+ protocolObjects.sipStack.getStackName()
+ " with server transaction id " + serverTransactionId);
if (request.getMethod().equals(Request.BYE))
processBye(request, serverTransactionId);
else if (request.getMethod().equals(Request.ACK))
processAck(request, serverTransactionId);
else if (request.getMethod().equals(Request.INVITE))
processInvite(request, serverTransactionId);
}
public void processBye(Request request,
ServerTransaction serverTransactionId) {
try {
logger.info("shootist: got a bye .");
if (serverTransactionId == null) {
logger.info("shootist: null TID.");
return;
}
Response response = protocolObjects.messageFactory.createResponse(
200, request);
serverTransactionId.sendResponse(response);
} catch (Exception ex) {
logger.error("unexpected exception",ex);
fail("unexpected exception");
}
}
public void processInvite(Request request,
ServerTransaction serverTransactionId) {
try {
Response response = protocolObjects.messageFactory.createResponse(
200, request);
provider.sendResponse(response);
} catch (Exception ex) {
logger.error("unexpected exception",ex);
fail("unexpected exception");
}
}
public void processAck(Request request,
ServerTransaction serverTransactionId) {
try {
logger.info("shootist: got ACK .");
if (serverTransactionId == null) {
logger.info("shootist: null TID.");
return;
}
Request bye = dialog.createRequest(Request.BYE);
ClientTransaction ctx = provider.getNewClientTransaction(bye);
ctx.sendRequest();
} catch (Exception ex) {
logger.error("unexpected exception",ex);
fail("unexpected exception");
}
}
public boolean okToInviteReceived;
public void processResponse(ResponseEvent responseReceivedEvent) {
logger.info("Got a response");
Response response = (Response) responseReceivedEvent.getResponse();
Transaction tid = responseReceivedEvent.getClientTransaction();
logger.info("Response received with client transaction id " + tid
+ ":\n" + response.getStatusCode());
if (tid != null) {
logger.info("Dialog = " + responseReceivedEvent.getDialog());
logger.info("Dialog State is "
+ responseReceivedEvent.getDialog().getState());
}
SipProvider provider = (SipProvider) responseReceivedEvent.getSource();
try {
if (response.getStatusCode() == Response.OK) {
if(((CSeqHeader) response.getHeader(CSeqHeader.NAME))
.getMethod().equals(Request.INVITE)) {
okToInviteReceived = true;
}
}
} catch (Exception ex) {
logger.error(ex);
ex.printStackTrace();
fail("unexpected exception");
}
}
public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) {
logger.info("Transaction Time out");
logger.info("TimeoutEvent " + timeoutEvent.getTimeout());
}
public SipProvider createSipProvider() {
try {
listeningPoint = protocolObjects.sipStack.createListeningPoint(
myAddress, myPort, protocolObjects.transport);
provider = protocolObjects.sipStack
.createSipProvider(listeningPoint);
return provider;
} catch (Exception ex) {
logger.error(ex);
fail("unable to create provider");
return null;
}
}
public void sendInvite() {
try {
// Note that a provider has multiple listening points.
// all the listening points must have the same IP address
// and port but differ in their transport parameters.
String fromName = "BigGuy";
String fromSipAddress = "here.com";
String fromDisplayName = "The Master Blaster";
String toSipAddress = "there.com";
String toUser = "LittleGuy";
String toDisplayName = "The Little Blister";
// create >From Header
SipURI fromAddress = protocolObjects.addressFactory.createSipURI(
fromName, fromSipAddress);
Address fromNameAddress = protocolObjects.addressFactory
.createAddress(fromAddress);
fromNameAddress.setDisplayName(fromDisplayName);
FromHeader fromHeader = protocolObjects.headerFactory
.createFromHeader(fromNameAddress, new Integer((int) (Math
.random() * Integer.MAX_VALUE)).toString());
// create To Header
SipURI toAddress = protocolObjects.addressFactory.createSipURI(
toUser, toSipAddress);
Address toNameAddress = protocolObjects.addressFactory
.createAddress(toAddress);
toNameAddress.setDisplayName(toDisplayName);
ToHeader toHeader = protocolObjects.headerFactory.createToHeader(
toNameAddress, null);
// create Request URI addressed to me
SipURI requestURI = protocolObjects.addressFactory.createSipURI(
toUser, myAddress + ":" + myPort);
// Create ViaHeaders
ArrayList viaHeaders = new ArrayList();
int port = provider.getListeningPoint(protocolObjects.transport)
.getPort();
ViaHeader viaHeader = protocolObjects.headerFactory
.createViaHeader(myAddress, port,
protocolObjects.transport, null);
// add via headers
viaHeaders.add(viaHeader);
// Create ContentTypeHeader
ContentTypeHeader contentTypeHeader = protocolObjects.headerFactory
.createContentTypeHeader("application", "sdp");
// Create a new CallId header
CallIdHeader callIdHeader = provider.getNewCallId();
// JvB: Make sure that the implementation matches the messagefactory
callIdHeader = protocolObjects.headerFactory.createCallIdHeader( callIdHeader.getCallId() );
// Create a new Cseq header
CSeqHeader cSeqHeader = protocolObjects.headerFactory
.createCSeqHeader(1L, Request.INVITE);
// Create a new MaxForwardsHeader
MaxForwardsHeader maxForwards = protocolObjects.headerFactory
.createMaxForwardsHeader(70);
// Create the request.
Request request = protocolObjects.messageFactory.createRequest(
requestURI, Request.INVITE, callIdHeader, cSeqHeader,
fromHeader, toHeader, viaHeaders, maxForwards);
// Create contact headers
// Create the contact name address.
SipURI contactURI = protocolObjects.addressFactory.createSipURI(
fromName, myAddress);
contactURI.setPort(provider.getListeningPoint(
protocolObjects.transport).getPort());
Address contactAddress = protocolObjects.addressFactory
.createAddress(contactURI);
// Add the contact address.
contactAddress.setDisplayName(fromName);
contactHeader = protocolObjects.headerFactory
.createContactHeader(contactAddress);
request.addHeader(contactHeader);
// Add the extension header.
Header extensionHeader = protocolObjects.headerFactory
.createHeader("My-Header", "my header value");
request.addHeader(extensionHeader);
String sdpData = "v=0\r\n"
+ "o=4855 13760799956958020 13760799956958020"
+ " IN IP4 129.6.55.78\r\n" + "s=mysession session\r\n"
+ "p=+46 8 52018010\r\n" + "c=IN IP4 129.6.55.78\r\n"
+ "t=0 0\r\n" + "m=audio 6022 RTP/AVP 0 4 18\r\n"
+ "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n"
+ "a=rtpmap:18 G729A/8000\r\n" + "a=ptime:20\r\n";
request.setContent(sdpData, contentTypeHeader);
// The following is the preferred method to route requests
// to the peer. Create a route header and set the "lr"
// parameter for the router header.
Address address = protocolObjects.addressFactory
.createAddress("<sip:" + myAddress + ":" + myPort
+ ">");
// SipUri sipUri = (SipUri) address.getURI();
// sipUri.setPort(PEER_PORT);
RouteHeader routeHeader = protocolObjects.headerFactory
.createRouteHeader(address);
((SipURI)address.getURI()).setLrParam();
request.addHeader(routeHeader);
extensionHeader = protocolObjects.headerFactory.createHeader(
"My-Other-Header", "my new header value ");
request.addHeader(extensionHeader);
Header callInfoHeader = protocolObjects.headerFactory.createHeader(
"Call-Info", "<http://www.antd.nist.gov>");
request.addHeader(callInfoHeader);
// Create the client transaction.
this.inviteTid = provider.getNewClientTransaction(request);
this.dialog = this.inviteTid.getDialog();
// Note that the response may have arrived right away so
// we cannot check after the message is sent.
assertTrue(this.dialog.getState() == null);
// send the request out.
this.inviteTid.sendRequest();
} catch (Exception ex) {
logger.error("Unexpected exception", ex);
fail("unexpected exception");
}
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipListener#processIOException(javax.sip.IOExceptionEvent)
*/
public void processIOException(IOExceptionEvent exceptionEvent) {
logger.error("IO Exception!");
fail("Unexpected exception");
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipListener#processTransactionTerminated(javax.sip.TransactionTerminatedEvent)
*/
public void processTransactionTerminated(
TransactionTerminatedEvent transactionTerminatedEvent) {
logger.info("Transaction Terminated Event!");
}
/*
* (non-Javadoc)
*
* @see javax.sip.SipListener#processDialogTerminated(javax.sip.DialogTerminatedEvent)
*/
public void processDialogTerminated(
DialogTerminatedEvent dialogTerminatedEvent) {
logger.info("Dialog Terminated Event!");
}
}
public SelfroutingTest()
{
super("Selfrouting", true);
}
public void setUp() {
}
public void testSelfroutingUDP() {
try {
this.transport = "udp";
super.setUp();
shootist = new Shootist(getRiProtocolObjects());
SipProvider shootistProvider = shootist.createSipProvider();
shootistProvider.addSipListener(shootist);
SipStackImpl ss = (SipStackImpl) shootistProvider.getSipStack();
getRiProtocolObjects().start();
if (getTiProtocolObjects() != getRiProtocolObjects())
getTiProtocolObjects().start();
} catch (Exception ex) {
ex.printStackTrace();
fail("unexpected exception ");
}
new Thread() {
@Override
public void run() {
shootist.sendInvite();
super.run();
}
}.start();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
assertTrue(this.shootist.okToInviteReceived);
}
public void testSelfroutingTCP() {
try {
this.transport = "tcp";
super.setUp();
shootist = new Shootist(getRiProtocolObjects());
SipProvider shootistProvider = shootist.createSipProvider();
shootistProvider.addSipListener(shootist);
getRiProtocolObjects().start();
if (getTiProtocolObjects() != getRiProtocolObjects())
getTiProtocolObjects().start();
} catch (Exception ex) {
ex.printStackTrace();
fail("unexpected exception ");
}
new Thread() {
@Override
public void run() {
shootist.sendInvite();
super.run();
}
}.start();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
assertTrue(this.shootist.okToInviteReceived);
}
public void tearDown() {
try {
Thread.sleep(1000);
getTiProtocolObjects().destroy();
if (getTiProtocolObjects() != getRiProtocolObjects())
getRiProtocolObjects().destroy();
Thread.sleep(1000);
this.providerTable.clear();
logTestCompleted();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| {
"pile_set_name": "Github"
} |
user nobody nobody;
worker_processes 4;
worker_rlimit_nofile 51200;
error_log logs/error.log notice;
pid /var/run/nginx.pid;
events {
use epoll;
worker_connections 51200;
}
http {
server_tokens off;
include mime.types;
include proxy.conf;
default_type application/octet-stream;
charset utf-8;
client_body_temp_path /usr/local/nginx/tmpdir/client_body_temp 1 2;
proxy_temp_path /usr/local/nginx/tmpdir/proxy_temp 1 2;
fastcgi_temp_path /usr/local/nginx/tmpdir/fastcgi_temp 1 2;
uwsgi_temp_path /usr/local/nginx/tmpdir/uwsgi_temp 1 2;
scgi_temp_path /usr/local/nginx/tmpdir/scgi_temp 1 2;
ignore_invalid_headers on;
server_names_hash_max_size 256;
server_names_hash_bucket_size 256;
client_header_buffer_size 8k;
large_client_header_buffers 4 32k;
connection_pool_size 256;
request_pool_size 64k;
output_buffers 2 128k;
postpone_output 1460;
client_header_timeout 1m;
client_body_timeout 3m;
send_timeout 3m;
sendfile on;
tcp_nodelay on;
tcp_nopush off;
reset_timedout_connection on;
keepalive_timeout 20 5;
keepalive_requests 100;
gzip on;
gzip_http_version 1.1;
gzip_vary on;
gzip_proxied any;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_proxied expired no-cache no-store private auth no_last_modified no_etag;
gzip_types text/plain application/x-javascript text/css application/xml application/json;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
include nginx_app.conf;
include nginx_status.conf;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_162) on Tue Nov 05 19:39:12 PST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.fasterxml.jackson.databind.ext.Java7SupportImpl (jackson-databind 2.10.0 API)</title>
<meta name="date" content="2019-11-05">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.fasterxml.jackson.databind.ext.Java7SupportImpl (jackson-databind 2.10.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/fasterxml/jackson/databind/ext/Java7SupportImpl.html" title="class in com.fasterxml.jackson.databind.ext">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/fasterxml/jackson/databind/ext/class-use/Java7SupportImpl.html" target="_top">Frames</a></li>
<li><a href="Java7SupportImpl.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.fasterxml.jackson.databind.ext.Java7SupportImpl" class="title">Uses of Class<br>com.fasterxml.jackson.databind.ext.Java7SupportImpl</h2>
</div>
<div class="classUseContainer">No usage of com.fasterxml.jackson.databind.ext.Java7SupportImpl</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/fasterxml/jackson/databind/ext/Java7SupportImpl.html" title="class in com.fasterxml.jackson.databind.ext">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/fasterxml/jackson/databind/ext/class-use/Java7SupportImpl.html" target="_top">Frames</a></li>
<li><a href="Java7SupportImpl.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2008–2019 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<html>
<head>
<title>
</title>
<meta charset="UTF-8" />
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js">
</script>
<script type="text/javascript" src="jquery.jplayer.min.js">
</script>
<style type="text/css">
body {
margin: 0;
padding: 0
}
div.openyy {
cursor: pointer;
text-decoration: none;
font: 12px/1.2 "Helvetica Neue",Helvetica,Arial,sans-serif;
overflow: hidden;
display: block;
width: 250px;
height: 30px;
line-height: 30px;
white-space: nowrap;
background-color: #FF6503;
color: #fff;
border-bottom: #C4753D 1px solid;
text-align: center;
border-radius: 3px;
text-shadow: 0-1px 0 rgba(0, 0, 0, .2);
font-size: 14px
}
.openyy span {
float: left;
margin-left: 10px;
width: 210px;
overflow: hidden;
text-align: left
}
#play {
width: 0;
height: 0;
border:10px solid transparent;
border-left: 15px solid #FFF;
float: right;
margin-top: 5px
}
#pause {
width: 5px;
height: 20px;
border-left: 5px solid #FFF;
border-right: 5px solid #FFF;
float: right;
margin-top: 5px;
margin-right: 10px
}
#progress {
height: 30px;
background: #FF8F00;
position: absolute;
opacity: 0.5;-moz-opacity: 0.5;
filter: alpha(opacity = 50)
}
</style>
<script type="text/javascript">
$(function() {
var hash = location.hash.split('|');
if (hash.length == 3) {
var background = '#' + hash[1],
border = '#' + hash[2]
} else {
var background = '#' + hash[2],
border = '#' + hash[3]
}
$('.openyy').css({
'background': background,
'border-bottom-color': border
});
$('#progress').css({
'background': border
});
var song = hash[0].substr(1);
if (song.substring(0, 7) == "http://") {
var songs = new Array(hash[0].substr(1), hash[1]),
format = songs[0].split('.').pop();
$('#jplayer').jPlayer({
ready: function() {
switch (format) {
case 'wma':
$(this).jPlayer('setMedia', {
wma: songs[0]
});
break;
case 'ogg':
$(this).jPlayer('setMedia', {
ogg: songs[0]
});
break;
case 'ape':
$(this).jPlayer('setMedia', {
ape: songs[0]
});
break;
default:
$(this).jPlayer('setMedia', {
mp3: songs[0]
});
break
}
$('title').html(songs[1]);
$('.openyy span').html(songs[1])
},
preload: 'none',
ended: function() {
$('#pause').click();
$('#progress').width('0px')
},
swfPath: './',
supplied: 'mp3,wma,ogg,ape'
})
} else {
$.ajax({
url: 'http://imnerd.org/lab/player/apiv2.php?id=' + song,
type: 'GET',
dataType: 'jsonp',
async: false,
success: function(d) {
$('#jplayer').jPlayer({
ready: function() {
$(this).jPlayer('setMedia', {
mp3: d.location
});
$('title').html(d.title);
$('.openyy span').html(d.title);
$.ajax({
url: 'http://imnerd.org/lab/search/lyric.php?url=' + d.lyric,
type: 'GET',
dataType: 'jsonp',
async: false,
success: function(lrc) {
var m = 0;
$('#jplayer').bind($.jPlayer.event.timeupdate,
function(e) {
if (e.jPlayer.status.currentTime > lrc[m][0]) $('.openyy span').html(lrc[m][1]),
m++
})
}
})
},
ended: function() {
$('#pause').click();
$('#progress').width('0px')
},
preload: 'none',
swfPath: './',
supplied: 'mp3'
})
}
})
}
$('#jplayer').bind($.jPlayer.event.timeupdate,
function(e) {
$('#progress').width(Math.round(e.jPlayer.status.currentPercentAbsolute / 100 * $('.openyy span').width()))
});
$('body').on('click', '#play',
function() {
$('#jplayer').jPlayer('play');
$(this).attr('id', 'pause')
});
$('body').on('click', '#pause',
function() {
$('#jplayer').jPlayer('pause');
$(this).attr('id', 'play')
})
});
</script>
</head>
<body>
<div class="openyy">
<div id="progress">
</div>
<div id="jplayer">
</div>
<span>
</span>
<div id="play"></div>
</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
#include "dense-reconstruction/stereo-matcher.h"
#include <memory>
#include <Eigen/Dense>
#include <aslam/cameras/camera.h>
#include <aslam/common/pose-types.h>
#include <gflags/gflags.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include "dense-reconstruction/aslam-cv-interface.h"
#include "dense-reconstruction/disparity-conversion-utils.h"
#include "dense-reconstruction/stereo-camera-utils.h"
DEFINE_double(
dense_stereo_downscaling_factor, 1.0,
"Downscaling factor applied to the images prior to stereo matching.");
DEFINE_bool(dense_stereo_use_sgbm, true, "Use SGBM if enabled, BM otherwise.");
DEFINE_int32(dense_stereo_sgbm_min_disparity, 0, "");
DEFINE_int32(dense_stereo_sgbm_num_disparities, 128, "");
DEFINE_int32(dense_stereo_sgbm_sad_window_size, 3, "");
DEFINE_int32(dense_stereo_sgbm_p1, 72, "");
DEFINE_int32(dense_stereo_sgbm_p2, 288, "");
DEFINE_int32(dense_stereo_sgbm_disp12_max_diff, 1, "");
DEFINE_int32(dense_stereo_sgbm_pre_filter_cap, 31, "");
DEFINE_int32(dense_stereo_sgbm_uniqueness_ratio, 10, "");
DEFINE_int32(dense_stereo_sgbm_speckle_window_size, 500, "");
DEFINE_int32(dense_stereo_sgbm_speckle_range, 3, "");
DEFINE_int32(
dense_stereo_sgbm_mode, cv::StereoSGBM::MODE_SGBM,
"MODE_SGBM = 0, MODE_HH = 1, MODE_SGBM_3WAY = 2, MODE_HH4 = 3");
DEFINE_int32(dense_stereo_bm_pre_filter_size, 9, "");
DEFINE_int32(dense_stereo_bm_pre_filter_cap, 31, "");
DEFINE_string(dense_stereo_bm_prefilter_type, "xsobel", "");
DEFINE_int32(dense_stereo_bm_texture_threshold, 10, "");
DEFINE_int32(dense_stereo_bm_uniqueness_ratio, 15, "");
DEFINE_int32(dense_stereo_bm_sad_window_size, 9, "");
DEFINE_int32(dense_stereo_bm_min_disparity, 0, "");
DEFINE_int32(dense_stereo_bm_num_disparities, 128, "");
DEFINE_int32(dense_stereo_bm_speckle_window_size, 500, "");
DEFINE_int32(dense_stereo_bm_speckle_range, 3, "");
DEFINE_int32(dense_stereo_bm_disp12_max_diff, 1, "");
namespace dense_reconstruction {
namespace stereo {
void StereoMatcherConfig::adaptParamsBasedOnImageSize(
const size_t image_width) {
// Source:
// https://github.com/opencv/opencv/blob/master/samples/cpp/stereo_match.cpp
const int sgbm_old_num_disparities = sgbm_num_disparities;
const int bm_old_num_disparities = bm_num_disparities;
sgbm_num_disparities = ((image_width / 8) + 15) & -16;
bm_num_disparities = sgbm_num_disparities;
LOG(INFO)
<< "Adapted the number of disparities based on the image width from "
<< sgbm_old_num_disparities << "/" << bm_old_num_disparities << " to "
<< sgbm_num_disparities;
const int old_p1 = sgbm_p1;
const int old_p2 = sgbm_p2;
sgbm_p1 = 8 * sgbm_sad_window_size * sgbm_sad_window_size;
sgbm_p2 = 32 * sgbm_sad_window_size * sgbm_sad_window_size;
LOG(INFO) << "Adapted the SGBM params p1/p2 based on sad window size from "
<< old_p1 << "/" << old_p2 << " to " << sgbm_p1 << "/" << sgbm_p2;
}
StereoMatcherConfig StereoMatcherConfig::getFromGflags() {
StereoMatcherConfig config;
// General config:
config.downscaling_factor = FLAGS_dense_stereo_downscaling_factor;
config.use_sgbm = FLAGS_dense_stereo_use_sgbm;
// SGBM config:
config.sgbm_min_disparity = FLAGS_dense_stereo_sgbm_min_disparity;
config.sgbm_num_disparities = FLAGS_dense_stereo_sgbm_num_disparities;
config.sgbm_sad_window_size = FLAGS_dense_stereo_sgbm_sad_window_size;
config.sgbm_p1 = FLAGS_dense_stereo_sgbm_p1;
config.sgbm_p2 = FLAGS_dense_stereo_sgbm_p2;
config.sgbm_disp12_max_diff = FLAGS_dense_stereo_sgbm_disp12_max_diff;
config.sgbm_pre_filter_cap = FLAGS_dense_stereo_sgbm_pre_filter_cap;
config.sgbm_uniqueness_ratio = FLAGS_dense_stereo_sgbm_uniqueness_ratio;
config.sgbm_speckle_window_size = FLAGS_dense_stereo_sgbm_speckle_window_size;
config.sgbm_speckle_range = FLAGS_dense_stereo_sgbm_speckle_range;
config.sgbm_mode = FLAGS_dense_stereo_sgbm_mode;
// BM config:
config.bm_pre_filter_size = FLAGS_dense_stereo_bm_pre_filter_size;
config.bm_pre_filter_cap = FLAGS_dense_stereo_bm_pre_filter_cap;
config.bm_prefilter_type = FLAGS_dense_stereo_bm_prefilter_type;
config.bm_texture_threshold = FLAGS_dense_stereo_bm_texture_threshold;
config.bm_uniqueness_ratio = FLAGS_dense_stereo_bm_uniqueness_ratio;
config.bm_sad_window_size = FLAGS_dense_stereo_bm_sad_window_size;
config.bm_min_disparity = FLAGS_dense_stereo_bm_min_disparity;
config.bm_num_disparities = FLAGS_dense_stereo_bm_num_disparities;
config.bm_speckle_window_size = FLAGS_dense_stereo_bm_speckle_window_size;
config.bm_speckle_range = FLAGS_dense_stereo_bm_speckle_range;
config.bm_disp12_max_diff = FLAGS_dense_stereo_bm_disp12_max_diff;
return config;
}
StereoMatcher::StereoMatcher(
const aslam::Camera& first_camera, const aslam::Camera& second_camera,
const aslam::Transformation& T_C2_C1, const StereoMatcherConfig& config)
: config_(config),
first_camera_(first_camera),
second_camera_(second_camera),
T_C2_C1_(T_C2_C1),
stereo_camera_params_(config_.downscaling_factor),
undistorter_first_(nullptr),
undistorter_second_(nullptr) {
getStereoPairFromAslamCvCameras(
first_camera_, second_camera_, T_C2_C1_, config_.downscaling_factor,
&stereo_camera_params_);
undistorter_first_.reset(new Undistorter(stereo_camera_params_.getFirst()));
undistorter_second_.reset(new Undistorter(stereo_camera_params_.getSecond()));
if (config_.use_sgbm) {
VLOG(1) << "Stereo matching algorithm used: SGBM";
stereo_matcher_ = cv::StereoSGBM::create(
config_.sgbm_min_disparity, config_.sgbm_num_disparities,
config_.sgbm_sad_window_size, config_.sgbm_p1, config_.sgbm_p2,
config_.sgbm_disp12_max_diff, config_.sgbm_pre_filter_cap,
config_.sgbm_uniqueness_ratio, config_.sgbm_speckle_window_size,
config_.sgbm_speckle_range, config_.sgbm_mode);
min_disparity_ = config_.sgbm_min_disparity;
num_disparities_ = config_.sgbm_num_disparities;
sad_window_size_ = config_.sgbm_sad_window_size;
} else {
VLOG(1) << "Stereo matching algorithm used: BM";
stereo_matcher_ = cv::StereoBM::create(
config_.bm_num_disparities, config_.bm_sad_window_size);
cv::StereoBM* bm_ptr = static_cast<cv::StereoBM*>(stereo_matcher_.get());
bm_ptr->setPreFilterCap(config_.bm_pre_filter_cap);
bm_ptr->setPreFilterSize(config_.bm_pre_filter_size);
bm_ptr->setMinDisparity(config_.bm_min_disparity);
bm_ptr->setTextureThreshold(config_.bm_texture_threshold);
bm_ptr->setUniquenessRatio(config_.bm_uniqueness_ratio);
bm_ptr->setSpeckleRange(config_.bm_speckle_range);
bm_ptr->setSpeckleWindowSize(config_.bm_speckle_window_size);
bm_ptr->setDisp12MaxDiff(config_.bm_disp12_max_diff);
min_disparity_ = config_.bm_min_disparity;
num_disparities_ = config_.bm_num_disparities;
sad_window_size_ = config_.bm_sad_window_size;
}
// Cache some intrinsics values:
const std::shared_ptr<OutputCameraParameters> left_params =
undistorter_first_->getCameraParametersPair().getOutputPtr();
const std::shared_ptr<OutputCameraParameters> right_params =
undistorter_second_->getCameraParametersPair().getOutputPtr();
focal_length_ = left_params->P()(0, 0);
baseline_ = (right_params->P()(0, 3) - left_params->P()(0, 3)) /
left_params->P()(0, 0);
cx_ = left_params->P()(0, 2);
const double cx_right = right_params->P()(0, 2);
CHECK_EQ(cx_, cx_right)
<< "The undistortion should have made cx_left and cx_right identical!";
cy_ = left_params->P()(1, 2);
CHECK_GT(std::abs(baseline_), 1e-6);
}
void StereoMatcher::computeDisparityMap(
const cv::Mat& first_image, const cv::Mat& second_image,
cv::Mat* disparity_map, cv::Mat* first_image_undistorted,
cv::Mat* second_image_undistorted) const {
CHECK_NOTNULL(disparity_map);
CHECK_NOTNULL(first_image_undistorted);
CHECK_NOTNULL(second_image_undistorted);
CHECK(undistorter_first_);
CHECK(undistorter_second_);
CHECK(stereo_matcher_);
VLOG(5) << "Undistorting and rectifying images...";
undistorter_first_->undistortImage(first_image, first_image_undistorted);
undistorter_second_->undistortImage(second_image, second_image_undistorted);
VLOG(5) << "Computing disparity map...";
stereo_matcher_->compute(
*first_image_undistorted, *second_image_undistorted, *disparity_map);
VLOG(5) << "Done.";
}
void StereoMatcher::computePointCloud(
const cv::Mat& first_image, const cv::Mat& second_image,
resources::PointCloud* point_cloud) const {
CHECK_NOTNULL(point_cloud);
cv::Mat disparity_map, first_image_undistorted, second_image_undistorted;
computeDisparityMap(
first_image, second_image, &disparity_map, &first_image_undistorted,
&second_image_undistorted);
convertDisparityMapToPointCloud(
disparity_map, first_image_undistorted, baseline_, focal_length_, cx_,
cy_, sad_window_size_, min_disparity_, num_disparities_, point_cloud);
}
void StereoMatcher::computeDepthMapForOriginalCamera(
const cv::Mat& first_image, const cv::Mat& second_image,
cv::Mat* depth_map) const {
CHECK_NOTNULL(depth_map);
cv::Mat disparity_map, first_image_undistorted, second_image_undistorted;
computeDisparityMap(
first_image, second_image, &disparity_map, &first_image_undistorted,
&second_image_undistorted);
convertDisparityMapToDepthMap(
disparity_map, first_image_undistorted, baseline_, focal_length_, cx_,
cy_, sad_window_size_, min_disparity_, num_disparities_, first_camera_,
depth_map);
}
} // namespace stereo
} // namespace dense_reconstruction
| {
"pile_set_name": "Github"
} |
in this film , we meet the new poké ; mon , celebi , who has the power to travel through time .
| {
"pile_set_name": "Github"
} |
..
This file is part of Logtalk <https://logtalk.org/>
Copyright 1998-2020 Paulo Moura <[email protected]>
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.
.. index:: pair: abolish_events/5; Built-in predicate
.. _predicates_abolish_events_5:
abolish_events/5
================
Description
-----------
::
abolish_events(Event, Object, Message, Sender, Monitor)
Abolishes all matching events. The two types of events are represented
by the atoms ``before`` and ``after``. When the predicate is called with
the first argument unbound, both types of events are abolished.
Modes and number of proofs
--------------------------
::
abolish_events(@term, @term, @term, @term, @term) - one
Errors
------
| ``Event`` is neither a variable nor a valid event identifier:
| ``type_error(event, Event)``
| ``Object`` is neither a variable nor a valid object identifier:
| ``type_error(object_identifier, Object)``
| ``Message`` is neither a variable nor a callable term:
| ``type_error(callable, Message)``
| ``Sender`` is neither a variable nor a valid object identifier:
| ``type_error(object_identifier, Sender)``
| ``Monitor`` is neither a variable nor a valid object identifier:
| ``type_error(object_identifier, Monitor)``
Examples
--------
::
% abolish all events for messages sent to the "list"
% object being monitored by the "debugger" object:
| ?- abolish_events(_, list, _, _, debugger).
.. seealso::
:ref:`predicates_current_event_5`,
:ref:`predicates_define_events_5`,
:ref:`methods_before_3`,
:ref:`methods_after_3`
| {
"pile_set_name": "Github"
} |
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Xml;
using Dynamo.Graph;
using Dynamo.Graph.Nodes;
using Dynamo.Migration;
using Dynamo.Selection;
using NUnit.Framework;
using Revit.Elements;
namespace Dynamo.Tests
{
/// <summary>
/// Class containing tests for the NodeModel class
/// </summary>
[TestFixture]
public class NodeModelTests : DynamoModelTestBase
{
NodeModel testNodeModel;
[SetUp]
public void Init()
{
CurrentDynamoModel.NodeFactory.CreateNodeFromTypeName("CoreNodeModels.Input.DoubleInput", out testNodeModel);
}
[Test]
[Category("UnitTests")]
public void CreationNameTest()
{
testNodeModel.Category = "Category";
var result = testNodeModel.ConstructDictionaryLinkFromLibrary(CurrentDynamoModel.LibraryServices);
Assert.AreEqual("http://dictionary.dynamobim.com/2/#/Category/Action/Number", result);
}
[Test]
[Category("UnitTests")]
public void CategoryTest()
{
testNodeModel.Category = null; //Set Category to null so that GetCategoryStringFromAttributes() gets called in the property getter
var category = testNodeModel.Category;
Assert.AreEqual("Core.Input", category);
}
[Test]
[Category("UnitTests")]
public void DictionaryLinkTest()
{
testNodeModel.DictionaryLink = null; //Set DictionaryLink to null to cover the setter and to test the Configuration property
var dictLink = testNodeModel.DictionaryLink;
Assert.AreEqual("http://dictionary.dynamobim.com/2/", dictLink);
}
[Test]
[Category("UnitTests")]
public void SelectNeighborsTest()
{
//Open and run the workspace
string listTestFolder = Path.Combine(TestDirectory, "core");
string testFilePath = Path.Combine(listTestFolder, "Angle.dyn");
RunModel(testFilePath);
//Select the node with neighbors
NodeModel node = CurrentDynamoModel.CurrentWorkspace.NodeFromWorkspace("dcd9c6c6-6350-4292-a553-c57a764504b4");
var countBefore = DynamoSelection.Instance.Selection.Count;
Assert.AreEqual(0, countBefore);
//Run the method and assert whether more nodes were selected
node.SelectNeighbors();
var countAfter = DynamoSelection.Instance.Selection.Count;
Assert.AreEqual(2, countAfter);
}
[Test]
[Category("UnitTests")]
public void UpdateValueCoreTest()
{
var nodeModel = new NodeModelTestingClass();
nodeModel.InPorts = new ObservableCollection<PortModel>
{
new PortModel("Port1", "Tooltip1"),
new PortModel("Port2", "Tooltip2"),
new PortModel("Port3", "Tooltip3")
};
//case "UsingDefaultValue"
var param = new UpdateValueParams("UsingDefaultValue", "true;true;false");
Assert.IsTrue(nodeModel.UpdateValueCoreBool(param));
param = new UpdateValueParams("UsingDefaultValue", null);
Assert.IsTrue(nodeModel.UpdateValueCoreBool(param));
//case "KeepListStructure"
param = new UpdateValueParams("KeepListStructure", "1:true");
nodeModel.InPorts[0].KeepListStructure = true;
Assert.IsTrue(nodeModel.UpdateValueCoreBool(param));
}
}
/// <summary>
/// Class containing tests for some of the migration methods of the NodeModel class
/// </summary>
[TestFixture]
public class NodeModelMigrationTests : DynamoModelTestBase
{
private NodeModelTestingClass nodeModel;
private NodeMigrationData migrationDataTest;
[SetUp]
public void Init()
{
string documentDynPath = Path.Combine(TestDirectory, @"core\Angle.dyn");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(documentDynPath);
migrationDataTest = new NodeMigrationData(xmlDoc);
XmlElement dsFunctionNode = (XmlElement)xmlDoc.SelectSingleNode("//Dynamo.Graph.Nodes.ZeroTouch.DSFunction");
migrationDataTest.AppendNode(dsFunctionNode);
nodeModel = new NodeModelTestingClass();
}
[Test]
[Category("UnitTests")]
public void MigrateToDsFunctionNoAssemblyTest()
{
var result = nodeModel.MigrateToDsFunctionNoAssembly(migrationDataTest, "nickname", "function");
var assembly = result.MigratedNodes.First().Attributes["assembly"].Value;
var nickname = result.MigratedNodes.First().Attributes["nickname"].Value;
var function = result.MigratedNodes.First().Attributes["function"].Value;
Assert.AreEqual(assembly, "");
Assert.AreEqual(nickname, "nickname");
Assert.AreEqual(function, "function");
}
[Test]
[Category("UnitTests")]
public void MigrateToDsFunctionWithAssemblyTest()
{
var result = nodeModel.MigrateToDsFunctionAssembly(migrationDataTest, "assembly", "nickname", "function");
var assembly = result.MigratedNodes.First().Attributes["assembly"].Value;
var nickname = result.MigratedNodes.First().Attributes["nickname"].Value;
var function = result.MigratedNodes.First().Attributes["function"].Value;
Assert.AreEqual(assembly, "assembly");
Assert.AreEqual(nickname, "nickname");
Assert.AreEqual(function, "function");
}
[Test]
[Category("UnitTests")]
public void MigrateToDsVarArgFunctionTest()
{
var result = nodeModel.MigrateToDsVarArgFunctionNMData(migrationDataTest, "assembly", "nickname", "function");
var assembly = result.MigratedNodes.First().Attributes["assembly"].Value;
var nickname = result.MigratedNodes.First().Attributes["nickname"].Value;
var function = result.MigratedNodes.First().Attributes["function"].Value;
Assert.AreEqual(assembly, "assembly");
Assert.AreEqual(nickname, "nickname");
Assert.AreEqual(function, "function");
}
}
/// <summary>
/// Class created in order to test protected methods in the NodeModel parent
/// </summary>
internal class NodeModelTestingClass : NodeModel
{
public bool UpdateValueCoreBool(UpdateValueParams uvParams) =>
UpdateValueCore(uvParams);
public NodeMigrationData MigrateToDsFunctionNoAssembly(NodeMigrationData nmData, string name, string funcName) =>
MigrateToDsFunction(nmData, name, funcName);
public NodeMigrationData MigrateToDsFunctionAssembly(NodeMigrationData nmData, string assembly, string name, string funcName) =>
MigrateToDsFunction(nmData, assembly, name, funcName);
public NodeMigrationData MigrateToDsVarArgFunctionNMData(NodeMigrationData data, string assembly, string name, string funcName) =>
MigrateToDsVarArgFunction(data, assembly, name, funcName);
}
} | {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _LIBLOCKDEP_LOCKDEP_H_
#define _LIBLOCKDEP_LOCKDEP_H_
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <string.h>
#include <limits.h>
#include <linux/utsname.h>
#include <linux/compiler.h>
#include <linux/export.h>
#include <linux/kern_levels.h>
#include <linux/err.h>
#include <linux/rcu.h>
#include <linux/list.h>
#include <linux/hardirq.h>
#include <unistd.h>
#define MAX_LOCK_DEPTH 63UL
#define asmlinkage
#define __visible
#include "../../../include/linux/lockdep.h"
struct task_struct {
u64 curr_chain_key;
int lockdep_depth;
unsigned int lockdep_recursion;
struct held_lock held_locks[MAX_LOCK_DEPTH];
gfp_t lockdep_reclaim_gfp;
int pid;
int state;
char comm[17];
};
#define TASK_RUNNING 0
extern struct task_struct *__curr(void);
#define current (__curr())
static inline int debug_locks_off(void)
{
return 1;
}
#define task_pid_nr(tsk) ((tsk)->pid)
#define KSYM_NAME_LEN 128
#define printk(...) dprintf(STDOUT_FILENO, __VA_ARGS__)
#define pr_err(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
#define pr_warn pr_err
#define pr_cont pr_err
#define list_del_rcu list_del
#define atomic_t unsigned long
#define atomic_inc(x) ((*(x))++)
#define print_tainted() ""
#define static_obj(x) 1
#define debug_show_all_locks()
extern void debug_check_no_locks_held(void);
static __used bool __is_kernel_percpu_address(unsigned long addr, void *can_addr)
{
return false;
}
#endif
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: ae9405f95b96f4b88bee16d433034a52
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 0
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2014-2019, MyMonero.com
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder 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.
"use strict"
//
const HostedMoneroAPIClient_Base = require('./HostedMoneroAPIClient_Base')
//
class HostedMoneroAPIClient extends HostedMoneroAPIClient_Base
{
//
// Lifecycle - Init
constructor(options, context)
{
super(options, context)
}
//
// Runtime - Accessors - Private - Requests - Overrides
_new_apiAddress_authority() // authority means [subdomain.]host.…[:…]
{
const self = this
const settingsController = self.context.settingsController
if (settingsController.hasBooted != true) {
throw "Expected SettingsController to have been booted"
}
const specificAPIAddressURLAuthority = self.context.settingsController.specificAPIAddressURLAuthority || ""
if (specificAPIAddressURLAuthority != "") {
return specificAPIAddressURLAuthority
}
// fall back to mymonero server
return super._new_apiAddress_authority()
}
}
module.exports = HostedMoneroAPIClient | {
"pile_set_name": "Github"
} |
Import( 'env_testing buildJSONTests' )
buildJSONTests( env_testing, Split( """
main.cpp
""" ),
'jsontestrunner' )
# For 'check' to work, 'libs' must be built first.
env_testing.Depends('jsontestrunner', '#libs')
| {
"pile_set_name": "Github"
} |
#
# PvP Game Manager Sample Configuration
#
# This file describes some high-level configuration about the server as a
# whole. Map-specific configuration should be specified in the map folder.
#
# # # # # # # # # # # # # # # #
# OPTION: server #
# # # # # # # # # # # # # # # #
#
# Sets the server mode.
#
# Available options:
# - pickup
# - communityday
# - development
#
# # # # # # # # # # # # # # # #
# OPTION: maps #
# # # # # # # # # # # # # # # #
#
# Directory where maps are stored. See example map.yml for more information
# about the structure of this folder.
#
# # # # # # # # # # # # # # # #
# OPTION: archive #
# # # # # # # # # # # # # # # #
#
# Directory where completed matches will be stored. World files will be stored
# in the form of 'match-{id}'. If this is not specified, the plugin will
# automatically delete the world files.
#
# For example:
# archive/
# match-1/
# match-2/
# etc
#
# # # # # # # # # # # # # # # #
# OPTION: rotationfile #
# # # # # # # # # # # # # # # #
#
# File where the rotation will be stored and consists of a series of map names
# that may include comments prefixed with '#'.
#
# # # # # # # # # # # # # # # #
# OPTION: broadcastfrequency #
# # # # # # # # # # # # # # # #
#
# Frequency in seconds that information should be broadcasted to everyone.
#
# # # # # # # # # # # # # #
# OPTION: howto-book-file #
# # # # # # # # # # # # # #
#
# XML file containing a <book> definition that will be given to observers.
#
# If false, PGM will load its classes but not enable itself
enabled: true
# Public PGM listing service
# --------------------------
# If announce is enabled, and this server is running the PGM plugin,
# the listing service will be notified whenever this server starts up
# or shuts down. If the server is reachable at the announced address,
# it will be included in the public list.
#
# WARNING: Enabling this will publish your IP address to the world,
# unless you set server-host to something else.
announce:
enabled: false # Announce this server?
# server-port: 25565 # Public port - defaults to whatever port is bound at startup
# server-host: myserver.com # Public hostname or IP - if not set, the listing service will use
# the IP address that the announcement originates from
# Variables accessible by the XML pre-processor
environment:
ranked: false
rotation:
default-name: default
initial-wait: 20000
providers: {}
map:
sources: {}
# public:
# priority: 0
# path: /minecraft/repo/maps
# only:
# - CTW
# - CTF
# - DTC
# url: https://maps.oc.tc/
# depth: 99
# global-includes: true
include-path: []
autoreload:
enabled: true
reload-when-error: false
map-ratings:
enabled: true
autorestart:
enabled: true
time: 30
match-limit: 30
memory-limit: -1
start:
auto: true # Start the match automatically when ready
countdown: 30s # Default match start countdown
huddle: 0s # Team huddle duration
# timeout: 30s # Cycle if match takes longer than this to start
cycle:
countdown: 15s # Default countdown for cycle commands
running-match: false # Allow cycle commands during a running match without the -f flag
match-empty: # Cycle if a running match empties out
enabled: false
countdown: 5s
match-end: # Cycle when a match ends
enabled: true
countdown: 30s
join:
priority-kick: true # Kick non-privileged players to make room for privileged ones
mid-match: true # Allow players to join after the match has started (does not override Blitz rule)
commit-players: false # Do various things to keep players in the match once committed
capacity:
enabled: true
overfill: true # Enable overfill (false disables overfill, regardless of XML)
overfill-ratio: 1.25 # Default value, XML overrides this
requirements:
minimum-kills: 0
minimum-players: 1
teams:
minimum-players: 0
autobalance: true
allow-choose: true # Allow privileged players to choose their team
allow-switch: true # Allow players to be on multiple teams in the same match
even: false # Force evenly sized teams when using queued joins
broadcast:
title: true
periodic: true
frequency: 600
fireworks:
post-match:
enabled: true
number: 5
delay: 40 # ticks
frequency: 40 # ticks
iterations: 15
power: 2
goals:
enabled: true
antigrief:
diffuse:
enabled: false
craft-protect:
enabled: false
vechicle-protect:
enabled: false
anvil-protect:
enabled: false
arrowremoval:
enabled: true
delay: 10
fishing:
disable-treasure: true
scoreboard:
show-proximity: false
precise-progress: false
wool:
auto-refill: true
# howto-book-file:
stats:
deaths: true
engagements:
enabled: false
max-continuous-absence: oo
max-cumulative-absence: oo
min-participation-percent: 0
match-quotas:
# premium:
# permission: pgm.join.full
# priority: 10
# premium: true
# interval: 24h
# max: 4
# default:
# priority: 100
# premium: false
# interval: 20h
# max: 1
mutations:
enabled: true
license:
control-access: true
auto-grant: true
auto-revoke: true
freeze:
enabled: true
remove-tnt:
victim-radius: 10
sender-radius: 10
| {
"pile_set_name": "Github"
} |
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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.
"""Test class for PXE driver."""
import os
import tempfile
from unittest import mock
from oslo_config import cfg
from oslo_serialization import jsonutils as json
from oslo_utils import timeutils
from oslo_utils import uuidutils
from ironic.common import boot_devices
from ironic.common import boot_modes
from ironic.common import dhcp_factory
from ironic.common import exception
from ironic.common.glance_service import image_service
from ironic.common import pxe_utils
from ironic.common import states
from ironic.conductor import task_manager
from ironic.conductor import utils as manager_utils
from ironic.drivers import base as drivers_base
from ironic.drivers.modules import agent_base
from ironic.drivers.modules import deploy_utils
from ironic.drivers.modules import fake
from ironic.drivers.modules import ipxe
from ironic.drivers.modules import pxe
from ironic.drivers.modules import pxe_base
from ironic.drivers.modules.storage import noop as noop_storage
from ironic.tests.unit.db import base as db_base
from ironic.tests.unit.db import utils as db_utils
from ironic.tests.unit.objects import utils as obj_utils
CONF = cfg.CONF
INST_INFO_DICT = db_utils.get_test_pxe_instance_info()
DRV_INFO_DICT = db_utils.get_test_pxe_driver_info()
DRV_INTERNAL_INFO_DICT = db_utils.get_test_pxe_driver_internal_info()
# NOTE(TheJulia): Mark pxe interface loading as None in order
# to prent false counts for individual method tests.
@mock.patch.object(ipxe.iPXEBoot, '__init__', lambda self: None)
@mock.patch.object(pxe.PXEBoot, '__init__', lambda self: None)
class PXEBootTestCase(db_base.DbTestCase):
driver = 'fake-hardware'
boot_interface = 'pxe'
driver_info = DRV_INFO_DICT
driver_internal_info = DRV_INTERNAL_INFO_DICT
def setUp(self):
super(PXEBootTestCase, self).setUp()
self.context.auth_token = 'fake'
self.config_temp_dir('tftp_root', group='pxe')
self.config_temp_dir('images_path', group='pxe')
self.config_temp_dir('http_root', group='deploy')
instance_info = INST_INFO_DICT
instance_info['deploy_key'] = 'fake-56789'
self.config(enabled_boot_interfaces=[self.boot_interface,
'ipxe', 'fake'])
self.node = obj_utils.create_test_node(
self.context,
driver=self.driver,
boot_interface=self.boot_interface,
# Avoid fake properties in get_properties() output
vendor_interface='no-vendor',
instance_info=instance_info,
driver_info=self.driver_info,
driver_internal_info=self.driver_internal_info)
self.port = obj_utils.create_test_port(self.context,
node_id=self.node.id)
self.config(my_ipv6='2001:db8::1')
def test_get_properties(self):
expected = pxe_base.COMMON_PROPERTIES
expected.update(agent_base.VENDOR_PROPERTIES)
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
self.assertEqual(expected, task.driver.get_properties())
@mock.patch.object(image_service.GlanceImageService, 'show', autospec=True)
def test_validate_good(self, mock_glance):
mock_glance.return_value = {'properties': {'kernel_id': 'fake-kernel',
'ramdisk_id': 'fake-initr'}}
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.driver.boot.validate(task)
@mock.patch.object(image_service.GlanceImageService, 'show', autospec=True)
def test_validate_good_whole_disk_image(self, mock_glance):
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.node.driver_internal_info['is_whole_disk_image'] = True
task.driver.boot.validate(task)
@mock.patch.object(image_service.GlanceImageService, 'show', autospec=True)
@mock.patch.object(noop_storage.NoopStorage, 'should_write_image',
autospec=True)
def test_validate_skip_check_write_image_false(self, mock_write,
mock_glance):
mock_write.return_value = False
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.driver.boot.validate(task)
self.assertFalse(mock_glance.called)
def test_validate_fail_missing_deploy_kernel(self):
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
del task.node.driver_info['deploy_kernel']
self.assertRaises(exception.MissingParameterValue,
task.driver.boot.validate, task)
def test_validate_fail_missing_deploy_ramdisk(self):
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
del task.node.driver_info['deploy_ramdisk']
self.assertRaises(exception.MissingParameterValue,
task.driver.boot.validate, task)
def test_validate_fail_missing_image_source(self):
info = dict(INST_INFO_DICT)
del info['image_source']
self.node.instance_info = json.dumps(info)
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.node['instance_info'] = json.dumps(info)
self.assertRaises(exception.MissingParameterValue,
task.driver.boot.validate, task)
def test_validate_fail_no_port(self):
new_node = obj_utils.create_test_node(
self.context,
uuid='aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
driver=self.driver, boot_interface=self.boot_interface,
instance_info=INST_INFO_DICT, driver_info=DRV_INFO_DICT)
with task_manager.acquire(self.context, new_node.uuid,
shared=True) as task:
self.assertRaises(exception.MissingParameterValue,
task.driver.boot.validate, task)
def test_validate_fail_trusted_boot_with_secure_boot(self):
instance_info = {"boot_option": "netboot",
"secure_boot": "true",
"trusted_boot": "true"}
properties = {'capabilities': 'trusted_boot:true'}
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.node.instance_info['capabilities'] = instance_info
task.node.properties = properties
task.node.driver_internal_info['is_whole_disk_image'] = False
self.assertRaises(exception.InvalidParameterValue,
task.driver.boot.validate, task)
def test_validate_fail_invalid_trusted_boot_value(self):
properties = {'capabilities': 'trusted_boot:value'}
instance_info = {"trusted_boot": "value"}
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.node.properties = properties
task.node.instance_info['capabilities'] = instance_info
self.assertRaises(exception.InvalidParameterValue,
task.driver.boot.validate, task)
@mock.patch.object(image_service.GlanceImageService, 'show', autospec=True)
def test_validate_fail_no_image_kernel_ramdisk_props(self, mock_glance):
instance_info = {"boot_option": "netboot"}
mock_glance.return_value = {'properties': {}}
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.node.instance_info['capabilities'] = instance_info
self.assertRaises(exception.MissingParameterValue,
task.driver.boot.validate,
task)
@mock.patch.object(image_service.GlanceImageService, 'show', autospec=True)
def test_validate_fail_glance_image_doesnt_exists(self, mock_glance):
mock_glance.side_effect = exception.ImageNotFound('not found')
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
self.assertRaises(exception.InvalidParameterValue,
task.driver.boot.validate, task)
@mock.patch.object(image_service.GlanceImageService, 'show', autospec=True)
def test_validate_fail_glance_conn_problem(self, mock_glance):
exceptions = (exception.GlanceConnectionFailed('connection fail'),
exception.ImageNotAuthorized('not authorized'),
exception.Invalid('invalid'))
mock_glance.side_effect = exceptions
for exc in exceptions:
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
self.assertRaises(exception.InvalidParameterValue,
task.driver.boot.validate, task)
def test_validate_inspection(self):
with task_manager.acquire(self.context, self.node.uuid) as task:
task.driver.boot.validate_inspection(task)
def test_validate_inspection_no_inspection_ramdisk(self):
driver_info = self.node.driver_info
del driver_info['deploy_ramdisk']
self.node.driver_info = driver_info
self.node.save()
with task_manager.acquire(self.context, self.node.uuid) as task:
self.assertRaises(exception.UnsupportedDriverExtension,
task.driver.boot.validate_inspection, task)
@mock.patch.object(manager_utils, 'node_get_boot_mode', autospec=True)
@mock.patch.object(manager_utils, 'node_set_boot_device', autospec=True)
@mock.patch.object(dhcp_factory, 'DHCPFactory', autospec=True)
@mock.patch.object(pxe_utils, 'get_instance_image_info', autospec=True)
@mock.patch.object(pxe_utils, 'get_image_info', autospec=True)
@mock.patch.object(pxe_utils, 'cache_ramdisk_kernel', autospec=True)
@mock.patch.object(pxe_utils, 'build_pxe_config_options', autospec=True)
@mock.patch.object(pxe_utils, 'create_pxe_config', autospec=True)
def _test_prepare_ramdisk(self, mock_pxe_config,
mock_build_pxe, mock_cache_r_k,
mock_deploy_img_info,
mock_instance_img_info,
dhcp_factory_mock,
set_boot_device_mock,
get_boot_mode_mock,
uefi=False,
cleaning=False,
ipxe_use_swift=False,
whole_disk_image=False,
mode='deploy',
node_boot_mode=None,
persistent=False):
mock_build_pxe.return_value = {}
kernel_label = '%s_kernel' % mode
ramdisk_label = '%s_ramdisk' % mode
mock_deploy_img_info.return_value = {kernel_label: 'a',
ramdisk_label: 'r'}
if whole_disk_image:
mock_instance_img_info.return_value = {}
else:
mock_instance_img_info.return_value = {'kernel': 'b'}
mock_pxe_config.return_value = None
mock_cache_r_k.return_value = None
provider_mock = mock.MagicMock()
dhcp_factory_mock.return_value = provider_mock
get_boot_mode_mock.return_value = node_boot_mode
driver_internal_info = self.node.driver_internal_info
driver_internal_info['is_whole_disk_image'] = whole_disk_image
self.node.driver_internal_info = driver_internal_info
if mode == 'rescue':
mock_deploy_img_info.return_value = {
'rescue_kernel': 'a',
'rescue_ramdisk': 'r'}
self.node.save()
with task_manager.acquire(self.context, self.node.uuid) as task:
dhcp_opts = pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False)
dhcp_opts += pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False, ip_version=6)
task.driver.boot.prepare_ramdisk(task, {'foo': 'bar'})
mock_deploy_img_info.assert_called_once_with(task.node,
mode=mode,
ipxe_enabled=False)
provider_mock.update_dhcp.assert_called_once_with(task, dhcp_opts)
get_boot_mode_mock.assert_called_once_with(task)
set_boot_device_mock.assert_called_once_with(task,
boot_devices.PXE,
persistent=persistent)
if ipxe_use_swift:
if whole_disk_image:
self.assertFalse(mock_cache_r_k.called)
else:
mock_cache_r_k.assert_called_once_with(
task,
{'kernel': 'b'},
ipxe_enabled=False)
mock_instance_img_info.assert_called_once_with(
task, ipxe_enabled=False)
elif not cleaning and mode == 'deploy':
mock_cache_r_k.assert_called_once_with(
task,
{'deploy_kernel': 'a', 'deploy_ramdisk': 'r',
'kernel': 'b'},
ipxe_enabled=False)
mock_instance_img_info.assert_called_once_with(
task, ipxe_enabled=False)
elif mode == 'deploy':
mock_cache_r_k.assert_called_once_with(
task,
{'deploy_kernel': 'a', 'deploy_ramdisk': 'r'},
ipxe_enabled=False)
elif mode == 'rescue':
mock_cache_r_k.assert_called_once_with(
task,
{'rescue_kernel': 'a', 'rescue_ramdisk': 'r'},
ipxe_enabled=False)
if uefi:
mock_pxe_config.assert_called_once_with(
task, {}, CONF.pxe.uefi_pxe_config_template,
ipxe_enabled=False)
else:
mock_pxe_config.assert_called_once_with(
task, {}, CONF.pxe.pxe_config_template,
ipxe_enabled=False)
def test_prepare_ramdisk(self):
self.node.provision_state = states.DEPLOYING
self.node.save()
self._test_prepare_ramdisk()
def test_prepare_ramdisk_force_persistent_boot_device_true(self):
self.node.provision_state = states.DEPLOYING
driver_info = self.node.driver_info
driver_info['force_persistent_boot_device'] = 'True'
self.node.driver_info = driver_info
self.node.save()
self._test_prepare_ramdisk(persistent=True)
def test_prepare_ramdisk_force_persistent_boot_device_bool_true(self):
self.node.provision_state = states.DEPLOYING
driver_info = self.node.driver_info
driver_info['force_persistent_boot_device'] = True
self.node.driver_info = driver_info
self.node.save()
self._test_prepare_ramdisk(persistent=True)
def test_prepare_ramdisk_force_persistent_boot_device_sloppy_true(self):
for value in ['true', 't', '1', 'on', 'y', 'YES']:
self.node.provision_state = states.DEPLOYING
driver_info = self.node.driver_info
driver_info['force_persistent_boot_device'] = value
self.node.driver_info = driver_info
self.node.save()
self._test_prepare_ramdisk(persistent=True)
def test_prepare_ramdisk_force_persistent_boot_device_false(self):
self.node.provision_state = states.DEPLOYING
driver_info = self.node.driver_info
driver_info['force_persistent_boot_device'] = 'False'
self.node.driver_info = driver_info
self.node.save()
self._test_prepare_ramdisk()
def test_prepare_ramdisk_force_persistent_boot_device_bool_false(self):
self.node.provision_state = states.DEPLOYING
driver_info = self.node.driver_info
driver_info['force_persistent_boot_device'] = False
self.node.driver_info = driver_info
self.node.save()
self._test_prepare_ramdisk(persistent=False)
def test_prepare_ramdisk_force_persistent_boot_device_sloppy_false(self):
for value in ['false', 'f', '0', 'off', 'n', 'NO', 'yxz']:
self.node.provision_state = states.DEPLOYING
driver_info = self.node.driver_info
driver_info['force_persistent_boot_device'] = value
self.node.driver_info = driver_info
self.node.save()
self._test_prepare_ramdisk()
def test_prepare_ramdisk_force_persistent_boot_device_default(self):
self.node.provision_state = states.DEPLOYING
driver_info = self.node.driver_info
driver_info['force_persistent_boot_device'] = 'Default'
self.node.driver_info = driver_info
self.node.save()
self._test_prepare_ramdisk(persistent=False)
def test_prepare_ramdisk_force_persistent_boot_device_always(self):
self.node.provision_state = states.DEPLOYING
driver_info = self.node.driver_info
driver_info['force_persistent_boot_device'] = 'Always'
self.node.driver_info = driver_info
self.node.save()
self._test_prepare_ramdisk(persistent=True)
def test_prepare_ramdisk_force_persistent_boot_device_never(self):
self.node.provision_state = states.DEPLOYING
driver_info = self.node.driver_info
driver_info['force_persistent_boot_device'] = 'Never'
self.node.driver_info = driver_info
self.node.save()
self._test_prepare_ramdisk(persistent=False)
def test_prepare_ramdisk_rescue(self):
self.node.provision_state = states.RESCUING
self.node.save()
self._test_prepare_ramdisk(mode='rescue')
def test_prepare_ramdisk_uefi(self):
self.node.provision_state = states.DEPLOYING
self.node.save()
properties = self.node.properties
properties['capabilities'] = 'boot_mode:uefi'
self.node.properties = properties
self.node.save()
self._test_prepare_ramdisk(uefi=True)
def test_prepare_ramdisk_cleaning(self):
self.node.provision_state = states.CLEANING
self.node.save()
self._test_prepare_ramdisk(cleaning=True)
@mock.patch.object(manager_utils, 'node_set_boot_mode', autospec=True)
def test_prepare_ramdisk_set_boot_mode_on_bm(
self, set_boot_mode_mock):
self.node.provision_state = states.DEPLOYING
properties = self.node.properties
properties['capabilities'] = 'boot_mode:uefi'
self.node.properties = properties
self.node.save()
self._test_prepare_ramdisk(uefi=True)
set_boot_mode_mock.assert_called_once_with(mock.ANY, boot_modes.UEFI)
@mock.patch.object(manager_utils, 'node_set_boot_mode', autospec=True)
def test_prepare_ramdisk_set_boot_mode_on_ironic(
self, set_boot_mode_mock):
self.node.provision_state = states.DEPLOYING
self.node.save()
self._test_prepare_ramdisk(node_boot_mode=boot_modes.LEGACY_BIOS)
with task_manager.acquire(self.context, self.node.uuid) as task:
driver_internal_info = task.node.driver_internal_info
self.assertIn('deploy_boot_mode', driver_internal_info)
self.assertEqual(boot_modes.LEGACY_BIOS,
driver_internal_info['deploy_boot_mode'])
self.assertEqual(set_boot_mode_mock.call_count, 0)
@mock.patch.object(manager_utils, 'node_set_boot_mode', autospec=True)
def test_prepare_ramdisk_set_default_boot_mode_on_ironic_bios(
self, set_boot_mode_mock):
self.node.provision_state = states.DEPLOYING
self.node.save()
self.config(default_boot_mode=boot_modes.LEGACY_BIOS, group='deploy')
self._test_prepare_ramdisk()
with task_manager.acquire(self.context, self.node.uuid) as task:
driver_internal_info = task.node.driver_internal_info
self.assertIn('deploy_boot_mode', driver_internal_info)
self.assertEqual(boot_modes.LEGACY_BIOS,
driver_internal_info['deploy_boot_mode'])
self.assertEqual(set_boot_mode_mock.call_count, 1)
@mock.patch.object(manager_utils, 'node_set_boot_mode', autospec=True)
def test_prepare_ramdisk_set_default_boot_mode_on_ironic_uefi(
self, set_boot_mode_mock):
self.node.provision_state = states.DEPLOYING
self.node.save()
self.config(default_boot_mode=boot_modes.UEFI, group='deploy')
self._test_prepare_ramdisk(uefi=True)
with task_manager.acquire(self.context, self.node.uuid) as task:
driver_internal_info = task.node.driver_internal_info
self.assertIn('deploy_boot_mode', driver_internal_info)
self.assertEqual(boot_modes.UEFI,
driver_internal_info['deploy_boot_mode'])
self.assertEqual(set_boot_mode_mock.call_count, 1)
@mock.patch.object(manager_utils, 'node_set_boot_mode', autospec=True)
def test_prepare_ramdisk_conflicting_boot_modes(
self, set_boot_mode_mock):
self.node.provision_state = states.DEPLOYING
properties = self.node.properties
properties['capabilities'] = 'boot_mode:uefi'
self.node.properties = properties
self.node.save()
self._test_prepare_ramdisk(uefi=True,
node_boot_mode=boot_modes.LEGACY_BIOS)
set_boot_mode_mock.assert_called_once_with(mock.ANY, boot_modes.UEFI)
@mock.patch.object(manager_utils, 'node_set_boot_mode', autospec=True)
def test_prepare_ramdisk_conflicting_boot_modes_set_unsupported(
self, set_boot_mode_mock):
self.node.provision_state = states.DEPLOYING
properties = self.node.properties
properties['capabilities'] = 'boot_mode:uefi'
self.node.properties = properties
self.node.save()
set_boot_mode_mock.side_effect = exception.UnsupportedDriverExtension(
extension='management', driver='test-driver'
)
self.assertRaises(exception.UnsupportedDriverExtension,
self._test_prepare_ramdisk,
uefi=True, node_boot_mode=boot_modes.LEGACY_BIOS)
@mock.patch.object(manager_utils, 'node_set_boot_mode', autospec=True)
def test_prepare_ramdisk_set_boot_mode_not_called(
self, set_boot_mode_mock):
self.node.provision_state = states.DEPLOYING
self.node.save()
properties = self.node.properties
properties['capabilities'] = 'boot_mode:uefi'
self.node.properties = properties
self.node.save()
self._test_prepare_ramdisk(uefi=True, node_boot_mode=boot_modes.UEFI)
self.assertEqual(set_boot_mode_mock.call_count, 0)
@mock.patch.object(pxe_utils, 'clean_up_pxe_env', autospec=True)
@mock.patch.object(pxe_utils, 'get_image_info', autospec=True)
def _test_clean_up_ramdisk(self, get_image_info_mock,
clean_up_pxe_env_mock, mode='deploy'):
with task_manager.acquire(self.context, self.node.uuid) as task:
kernel_label = '%s_kernel' % mode
ramdisk_label = '%s_ramdisk' % mode
image_info = {kernel_label: ['', '/path/to/' + kernel_label],
ramdisk_label: ['', '/path/to/' + ramdisk_label]}
get_image_info_mock.return_value = image_info
task.driver.boot.clean_up_ramdisk(task)
clean_up_pxe_env_mock.assert_called_once_with(
task, image_info, ipxe_enabled=False)
get_image_info_mock.assert_called_once_with(
task.node, mode=mode, ipxe_enabled=False)
def test_clean_up_ramdisk(self):
self.node.provision_state = states.DEPLOYING
self.node.save()
self._test_clean_up_ramdisk()
def test_clean_up_ramdisk_rescue(self):
self.node.provision_state = states.RESCUING
self.node.save()
self._test_clean_up_ramdisk(mode='rescue')
@mock.patch.object(manager_utils, 'node_set_boot_device', autospec=True)
@mock.patch.object(deploy_utils, 'switch_pxe_config', autospec=True)
@mock.patch.object(dhcp_factory, 'DHCPFactory', autospec=True)
@mock.patch.object(pxe_utils, 'cache_ramdisk_kernel', autospec=True)
@mock.patch.object(pxe_utils, 'get_instance_image_info', autospec=True)
def test_prepare_instance_netboot(
self, get_image_info_mock, cache_mock,
dhcp_factory_mock, switch_pxe_config_mock,
set_boot_device_mock):
provider_mock = mock.MagicMock()
dhcp_factory_mock.return_value = provider_mock
image_info = {'kernel': ('', '/path/to/kernel'),
'ramdisk': ('', '/path/to/ramdisk')}
get_image_info_mock.return_value = image_info
with task_manager.acquire(self.context, self.node.uuid) as task:
dhcp_opts = pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False, ip_version=4)
dhcp_opts += pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False, ip_version=6)
pxe_config_path = pxe_utils.get_pxe_config_file_path(
task.node.uuid)
task.node.properties['capabilities'] = 'boot_mode:bios'
task.node.driver_internal_info['root_uuid_or_disk_id'] = (
"30212642-09d3-467f-8e09-21685826ab50")
task.node.driver_internal_info['is_whole_disk_image'] = False
task.node.instance_info = {
'capabilities': {'boot_option': 'netboot'}}
task.driver.boot.prepare_instance(task)
get_image_info_mock.assert_called_once_with(
task, ipxe_enabled=False)
cache_mock.assert_called_once_with(
task, image_info, ipxe_enabled=False)
provider_mock.update_dhcp.assert_called_once_with(task, dhcp_opts)
switch_pxe_config_mock.assert_called_once_with(
pxe_config_path, "30212642-09d3-467f-8e09-21685826ab50",
'bios', False, False, False, False, ipxe_enabled=False)
set_boot_device_mock.assert_called_once_with(task,
boot_devices.PXE,
persistent=True)
@mock.patch('os.path.isfile', return_value=False, autospec=True)
@mock.patch.object(pxe_utils, 'create_pxe_config', autospec=True)
@mock.patch.object(manager_utils, 'node_set_boot_device', autospec=True)
@mock.patch.object(deploy_utils, 'switch_pxe_config', autospec=True)
@mock.patch.object(dhcp_factory, 'DHCPFactory', autospec=True)
@mock.patch.object(pxe_utils, 'cache_ramdisk_kernel', autospec=True)
@mock.patch.object(pxe_utils, 'get_instance_image_info', autospec=True)
def test_prepare_instance_netboot_active(
self, get_image_info_mock, cache_mock,
dhcp_factory_mock, switch_pxe_config_mock,
set_boot_device_mock, create_pxe_config_mock, isfile_mock):
provider_mock = mock.MagicMock()
dhcp_factory_mock.return_value = provider_mock
image_info = {'kernel': ('', '/path/to/kernel'),
'ramdisk': ('', '/path/to/ramdisk')}
instance_info = {"boot_option": "netboot"}
get_image_info_mock.return_value = image_info
self.node.provision_state = states.ACTIVE
self.node.save()
with task_manager.acquire(self.context, self.node.uuid) as task:
dhcp_opts = pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False)
dhcp_opts += pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False, ip_version=6)
pxe_config_path = pxe_utils.get_pxe_config_file_path(
task.node.uuid)
task.node.properties['capabilities'] = 'boot_mode:bios'
task.node.driver_internal_info['root_uuid_or_disk_id'] = (
"30212642-09d3-467f-8e09-21685826ab50")
task.node.driver_internal_info['is_whole_disk_image'] = False
task.node.instance_info['capabilities'] = instance_info
task.driver.boot.prepare_instance(task)
get_image_info_mock.assert_called_once_with(
task, ipxe_enabled=False)
cache_mock.assert_called_once_with(
task, image_info, ipxe_enabled=False)
provider_mock.update_dhcp.assert_called_once_with(task, dhcp_opts)
create_pxe_config_mock.assert_called_once_with(
task, mock.ANY, CONF.pxe.pxe_config_template,
ipxe_enabled=False)
switch_pxe_config_mock.assert_called_once_with(
pxe_config_path, "30212642-09d3-467f-8e09-21685826ab50",
'bios', False, False, False, False, ipxe_enabled=False)
self.assertFalse(set_boot_device_mock.called)
@mock.patch.object(manager_utils, 'node_set_boot_device', autospec=True)
@mock.patch.object(deploy_utils, 'switch_pxe_config', autospec=True)
@mock.patch.object(dhcp_factory, 'DHCPFactory', autospec=True)
@mock.patch.object(pxe_utils, 'cache_ramdisk_kernel', autospec=True)
@mock.patch.object(pxe_utils, 'get_instance_image_info', autospec=True)
def test_prepare_instance_netboot_missing_root_uuid(
self, get_image_info_mock, cache_mock,
dhcp_factory_mock, switch_pxe_config_mock,
set_boot_device_mock):
provider_mock = mock.MagicMock()
dhcp_factory_mock.return_value = provider_mock
image_info = {'kernel': ('', '/path/to/kernel'),
'ramdisk': ('', '/path/to/ramdisk')}
instance_info = {"boot_option": "netboot"}
get_image_info_mock.return_value = image_info
with task_manager.acquire(self.context, self.node.uuid) as task:
dhcp_opts = pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False)
dhcp_opts += pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False, ip_version=6)
task.node.properties['capabilities'] = 'boot_mode:bios'
task.node.instance_info['capabilities'] = instance_info
task.node.driver_internal_info['is_whole_disk_image'] = False
task.driver.boot.prepare_instance(task)
get_image_info_mock.assert_called_once_with(task,
ipxe_enabled=False)
cache_mock.assert_called_once_with(
task, image_info, ipxe_enabled=False)
provider_mock.update_dhcp.assert_called_once_with(task, dhcp_opts)
self.assertFalse(switch_pxe_config_mock.called)
self.assertFalse(set_boot_device_mock.called)
@mock.patch.object(pxe_base.LOG, 'warning', autospec=True)
@mock.patch.object(pxe_utils, 'clean_up_pxe_config', autospec=True)
@mock.patch.object(manager_utils, 'node_set_boot_device', autospec=True)
@mock.patch.object(dhcp_factory, 'DHCPFactory', autospec=True)
@mock.patch.object(pxe_utils, 'cache_ramdisk_kernel', autospec=True)
@mock.patch.object(pxe_utils, 'get_instance_image_info', autospec=True)
def test_prepare_instance_whole_disk_image_missing_root_uuid(
self, get_image_info_mock, cache_mock,
dhcp_factory_mock, set_boot_device_mock,
clean_up_pxe_mock, log_mock):
provider_mock = mock.MagicMock()
dhcp_factory_mock.return_value = provider_mock
get_image_info_mock.return_value = {}
instance_info = {"boot_option": "netboot"}
with task_manager.acquire(self.context, self.node.uuid) as task:
dhcp_opts = pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False)
dhcp_opts += pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False, ip_version=6)
task.node.properties['capabilities'] = 'boot_mode:bios'
task.node.instance_info['capabilities'] = instance_info
task.node.driver_internal_info['is_whole_disk_image'] = True
task.driver.boot.prepare_instance(task)
get_image_info_mock.assert_called_once_with(task,
ipxe_enabled=False)
cache_mock.assert_called_once_with(
task, {}, ipxe_enabled=False)
provider_mock.update_dhcp.assert_called_once_with(task, dhcp_opts)
self.assertTrue(log_mock.called)
clean_up_pxe_mock.assert_called_once_with(
task, ipxe_enabled=False)
set_boot_device_mock.assert_called_once_with(
task, boot_devices.DISK, persistent=True)
@mock.patch.object(manager_utils, 'node_set_boot_device', autospec=True)
@mock.patch.object(pxe_utils, 'clean_up_pxe_config', autospec=True)
def test_prepare_instance_localboot(self, clean_up_pxe_config_mock,
set_boot_device_mock):
with task_manager.acquire(self.context, self.node.uuid) as task:
instance_info = task.node.instance_info
instance_info['capabilities'] = {'boot_option': 'local'}
task.node.instance_info = instance_info
task.node.save()
task.driver.boot.prepare_instance(task)
clean_up_pxe_config_mock.assert_called_once_with(
task, ipxe_enabled=False)
set_boot_device_mock.assert_called_once_with(task,
boot_devices.DISK,
persistent=True)
@mock.patch.object(manager_utils, 'node_set_boot_device', autospec=True)
@mock.patch.object(pxe_utils, 'clean_up_pxe_config', autospec=True)
def test_prepare_instance_localboot_active(self, clean_up_pxe_config_mock,
set_boot_device_mock):
self.node.provision_state = states.ACTIVE
self.node.save()
with task_manager.acquire(self.context, self.node.uuid) as task:
instance_info = task.node.instance_info
instance_info['capabilities'] = {'boot_option': 'local'}
task.node.instance_info = instance_info
task.node.save()
task.driver.boot.prepare_instance(task)
clean_up_pxe_config_mock.assert_called_once_with(
task, ipxe_enabled=False)
self.assertFalse(set_boot_device_mock.called)
@mock.patch.object(manager_utils, 'node_set_boot_device', autospec=True)
@mock.patch.object(deploy_utils, 'switch_pxe_config', autospec=True)
@mock.patch.object(pxe_utils, 'create_pxe_config', autospec=True)
@mock.patch.object(dhcp_factory, 'DHCPFactory', autospec=True)
@mock.patch.object(pxe_utils, 'cache_ramdisk_kernel', autospec=True)
@mock.patch.object(pxe_utils, 'get_instance_image_info', autospec=True)
def _test_prepare_instance_ramdisk(
self, get_image_info_mock, cache_mock,
dhcp_factory_mock, create_pxe_config_mock,
switch_pxe_config_mock,
set_boot_device_mock, config_file_exits=False):
image_info = {'kernel': ['', '/path/to/kernel'],
'ramdisk': ['', '/path/to/ramdisk']}
get_image_info_mock.return_value = image_info
provider_mock = mock.MagicMock()
dhcp_factory_mock.return_value = provider_mock
self.node.provision_state = states.DEPLOYING
get_image_info_mock.return_value = image_info
with task_manager.acquire(self.context, self.node.uuid) as task:
instance_info = task.node.instance_info
instance_info['capabilities'] = {'boot_option': 'ramdisk'}
task.node.instance_info = instance_info
task.node.save()
dhcp_opts = pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False)
dhcp_opts += pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False, ip_version=6)
pxe_config_path = pxe_utils.get_pxe_config_file_path(
task.node.uuid)
task.driver.boot.prepare_instance(task)
get_image_info_mock.assert_called_once_with(task,
ipxe_enabled=False)
cache_mock.assert_called_once_with(
task, image_info, False)
provider_mock.update_dhcp.assert_called_once_with(task, dhcp_opts)
if config_file_exits:
self.assertFalse(create_pxe_config_mock.called)
else:
create_pxe_config_mock.assert_called_once_with(
task, mock.ANY, CONF.pxe.pxe_config_template,
ipxe_enabled=False)
switch_pxe_config_mock.assert_called_once_with(
pxe_config_path, None,
'bios', False, ipxe_enabled=False, iscsi_boot=False,
ramdisk_boot=True)
set_boot_device_mock.assert_called_once_with(task,
boot_devices.PXE,
persistent=True)
@mock.patch.object(os.path, 'isfile', lambda path: True)
def test_prepare_instance_ramdisk_pxe_conf_missing(self):
self._test_prepare_instance_ramdisk(config_file_exits=True)
@mock.patch.object(os.path, 'isfile', lambda path: False)
def test_prepare_instance_ramdisk_pxe_conf_exists(self):
self._test_prepare_instance_ramdisk(config_file_exits=False)
@mock.patch.object(pxe_utils, 'clean_up_pxe_env', autospec=True)
@mock.patch.object(pxe_utils, 'get_instance_image_info', autospec=True)
def test_clean_up_instance(self, get_image_info_mock,
clean_up_pxe_env_mock):
with task_manager.acquire(self.context, self.node.uuid) as task:
image_info = {'kernel': ['', '/path/to/kernel'],
'ramdisk': ['', '/path/to/ramdisk']}
get_image_info_mock.return_value = image_info
task.driver.boot.clean_up_instance(task)
clean_up_pxe_env_mock.assert_called_once_with(task, image_info,
ipxe_enabled=False)
get_image_info_mock.assert_called_once_with(task,
ipxe_enabled=False)
class PXERamdiskDeployTestCase(db_base.DbTestCase):
def setUp(self):
super(PXERamdiskDeployTestCase, self).setUp()
self.temp_dir = tempfile.mkdtemp()
self.config(tftp_root=self.temp_dir, group='pxe')
self.temp_dir = tempfile.mkdtemp()
self.config(images_path=self.temp_dir, group='pxe')
self.config(enabled_deploy_interfaces=['ramdisk'])
self.config(enabled_boot_interfaces=['pxe'])
for iface in drivers_base.ALL_INTERFACES:
impl = 'fake'
if iface == 'network':
impl = 'noop'
if iface == 'deploy':
impl = 'ramdisk'
if iface == 'boot':
impl = 'pxe'
config_kwarg = {'enabled_%s_interfaces' % iface: [impl],
'default_%s_interface' % iface: impl}
self.config(**config_kwarg)
self.config(enabled_hardware_types=['fake-hardware'])
instance_info = INST_INFO_DICT
self.node = obj_utils.create_test_node(
self.context,
driver='fake-hardware',
instance_info=instance_info,
driver_info=DRV_INFO_DICT,
driver_internal_info=DRV_INTERNAL_INFO_DICT)
self.port = obj_utils.create_test_port(self.context,
node_id=self.node.id)
@mock.patch.object(manager_utils, 'node_set_boot_device', autospec=True)
@mock.patch.object(deploy_utils, 'switch_pxe_config', autospec=True)
@mock.patch.object(dhcp_factory, 'DHCPFactory', autospec=True)
@mock.patch.object(pxe_utils, 'cache_ramdisk_kernel', autospec=True)
@mock.patch.object(pxe_utils, 'get_instance_image_info', autospec=True)
def test_prepare_instance_ramdisk(
self, get_image_info_mock, cache_mock,
dhcp_factory_mock, switch_pxe_config_mock,
set_boot_device_mock):
provider_mock = mock.MagicMock()
dhcp_factory_mock.return_value = provider_mock
self.node.provision_state = states.DEPLOYING
image_info = {'kernel': ('', '/path/to/kernel'),
'ramdisk': ('', '/path/to/ramdisk')}
get_image_info_mock.return_value = image_info
with task_manager.acquire(self.context, self.node.uuid) as task:
dhcp_opts = pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False)
dhcp_opts += pxe_utils.dhcp_options_for_instance(
task, ipxe_enabled=False, ip_version=6)
pxe_config_path = pxe_utils.get_pxe_config_file_path(
task.node.uuid)
task.node.properties['capabilities'] = 'boot_option:netboot'
task.node.driver_internal_info['is_whole_disk_image'] = False
task.driver.deploy.prepare(task)
task.driver.deploy.deploy(task)
get_image_info_mock.assert_called_once_with(task,
ipxe_enabled=False)
cache_mock.assert_called_once_with(
task, image_info, ipxe_enabled=False)
provider_mock.update_dhcp.assert_called_once_with(task, dhcp_opts)
switch_pxe_config_mock.assert_called_once_with(
pxe_config_path, None,
'bios', False, ipxe_enabled=False, iscsi_boot=False,
ramdisk_boot=True)
set_boot_device_mock.assert_called_once_with(task,
boot_devices.PXE,
persistent=True)
@mock.patch.object(pxe.LOG, 'warning', autospec=True)
@mock.patch.object(deploy_utils, 'switch_pxe_config', autospec=True)
@mock.patch.object(dhcp_factory, 'DHCPFactory', autospec=True)
@mock.patch.object(pxe_utils, 'cache_ramdisk_kernel', autospec=True)
@mock.patch.object(pxe_utils, 'get_instance_image_info', autospec=True)
def test_deploy(self, mock_image_info, mock_cache,
mock_dhcp_factory, mock_switch_config, mock_warning):
image_info = {'kernel': ('', '/path/to/kernel'),
'ramdisk': ('', '/path/to/ramdisk')}
mock_image_info.return_value = image_info
i_info = self.node.instance_info
i_info.update({'capabilities': {'boot_option': 'ramdisk'}})
self.node.instance_info = i_info
self.node.save()
with task_manager.acquire(self.context, self.node.uuid) as task:
self.assertIsNone(task.driver.deploy.deploy(task))
mock_image_info.assert_called_once_with(task, ipxe_enabled=False)
mock_cache.assert_called_once_with(
task, image_info, ipxe_enabled=False)
self.assertFalse(mock_warning.called)
i_info['configdrive'] = 'meow'
self.node.instance_info = i_info
self.node.save()
mock_warning.reset_mock()
with task_manager.acquire(self.context, self.node.uuid) as task:
self.assertIsNone(task.driver.deploy.deploy(task))
self.assertTrue(mock_warning.called)
@mock.patch.object(pxe.PXEBoot, 'prepare_instance', autospec=True)
def test_prepare(self, mock_prepare_instance):
node = self.node
node.provision_state = states.DEPLOYING
node.instance_info = {}
node.save()
with task_manager.acquire(self.context, node.uuid) as task:
task.driver.deploy.prepare(task)
self.assertFalse(mock_prepare_instance.called)
self.assertEqual({'boot_option': 'ramdisk'},
task.node.instance_info['capabilities'])
@mock.patch.object(pxe.PXEBoot, 'prepare_instance', autospec=True)
def test_prepare_active(self, mock_prepare_instance):
node = self.node
node.provision_state = states.ACTIVE
node.save()
with task_manager.acquire(self.context, node.uuid) as task:
task.driver.deploy.prepare(task)
mock_prepare_instance.assert_called_once_with(mock.ANY, task)
@mock.patch.object(pxe.PXEBoot, 'prepare_instance', autospec=True)
def test_prepare_unrescuing(self, mock_prepare_instance):
node = self.node
node.provision_state = states.UNRESCUING
node.save()
with task_manager.acquire(self.context, node.uuid) as task:
task.driver.deploy.prepare(task)
mock_prepare_instance.assert_called_once_with(mock.ANY, task)
@mock.patch.object(pxe.LOG, 'warning', autospec=True)
@mock.patch.object(pxe.PXEBoot, 'prepare_instance', autospec=True)
def test_prepare_fixes_and_logs_boot_option_warning(
self, mock_prepare_instance, mock_warning):
node = self.node
node.properties['capabilities'] = 'boot_option:ramdisk'
node.provision_state = states.DEPLOYING
node.instance_info = {}
node.save()
with task_manager.acquire(self.context, node.uuid) as task:
task.driver.deploy.prepare(task)
self.assertFalse(mock_prepare_instance.called)
self.assertEqual({'boot_option': 'ramdisk'},
task.node.instance_info['capabilities'])
self.assertTrue(mock_warning.called)
@mock.patch.object(deploy_utils, 'validate_image_properties',
autospec=True)
def test_validate(self, mock_validate_img):
node = self.node
node.properties['capabilities'] = 'boot_option:netboot'
node.save()
with task_manager.acquire(self.context, node.uuid) as task:
task.driver.deploy.validate(task)
self.assertTrue(mock_validate_img.called)
@mock.patch.object(fake.FakeBoot, 'validate', autospec=True)
@mock.patch.object(deploy_utils, 'validate_image_properties',
autospec=True)
def test_validate_interface_mismatch(self, mock_validate_image,
mock_boot_validate):
node = self.node
node.boot_interface = 'fake'
node.save()
self.config(enabled_boot_interfaces=['fake'],
default_boot_interface='fake')
with task_manager.acquire(self.context, node.uuid) as task:
error = self.assertRaises(exception.InvalidParameterValue,
task.driver.deploy.validate, task)
error_message = ('Invalid configuration: The boot interface must '
'have the `ramdisk_boot` capability. You are '
'using an incompatible boot interface.')
self.assertEqual(error_message, str(error))
self.assertFalse(mock_boot_validate.called)
self.assertFalse(mock_validate_image.called)
@mock.patch.object(pxe.PXEBoot, 'validate', autospec=True)
def test_validate_calls_boot_validate(self, mock_validate):
with task_manager.acquire(self.context, self.node.uuid) as task:
task.driver.deploy.validate(task)
mock_validate.assert_called_once_with(mock.ANY, task)
@mock.patch.object(manager_utils, 'restore_power_state_if_needed',
autospec=True)
@mock.patch.object(manager_utils, 'power_on_node_if_needed',
autospec=True)
@mock.patch.object(pxe.LOG, 'warning', autospec=True)
@mock.patch.object(deploy_utils, 'switch_pxe_config', autospec=True)
@mock.patch.object(dhcp_factory, 'DHCPFactory', autospec=True)
@mock.patch.object(pxe_utils, 'cache_ramdisk_kernel', autospec=True)
@mock.patch.object(pxe_utils, 'get_instance_image_info', autospec=True)
def test_deploy_with_smartnic_port(
self, mock_image_info, mock_cache,
mock_dhcp_factory, mock_switch_config, mock_warning,
power_on_node_if_needed_mock, restore_power_state_mock):
image_info = {'kernel': ('', '/path/to/kernel'),
'ramdisk': ('', '/path/to/ramdisk')}
mock_image_info.return_value = image_info
i_info = self.node.instance_info
i_info.update({'capabilities': {'boot_option': 'ramdisk'}})
self.node.instance_info = i_info
self.node.save()
with task_manager.acquire(self.context, self.node.uuid) as task:
power_on_node_if_needed_mock.return_value = states.POWER_OFF
self.assertIsNone(task.driver.deploy.deploy(task))
mock_image_info.assert_called_once_with(task, ipxe_enabled=False)
mock_cache.assert_called_once_with(
task, image_info, ipxe_enabled=False)
self.assertFalse(mock_warning.called)
power_on_node_if_needed_mock.assert_called_once_with(task)
restore_power_state_mock.assert_called_once_with(
task, states.POWER_OFF)
i_info['configdrive'] = 'meow'
self.node.instance_info = i_info
self.node.save()
mock_warning.reset_mock()
with task_manager.acquire(self.context, self.node.uuid) as task:
self.assertIsNone(task.driver.deploy.deploy(task))
self.assertTrue(mock_warning.called)
class PXEValidateRescueTestCase(db_base.DbTestCase):
def setUp(self):
super(PXEValidateRescueTestCase, self).setUp()
for iface in drivers_base.ALL_INTERFACES:
impl = 'fake'
if iface == 'network':
impl = 'flat'
if iface == 'rescue':
impl = 'agent'
if iface == 'boot':
impl = 'pxe'
config_kwarg = {'enabled_%s_interfaces' % iface: [impl],
'default_%s_interface' % iface: impl}
self.config(**config_kwarg)
self.config(enabled_hardware_types=['fake-hardware'])
driver_info = DRV_INFO_DICT
driver_info.update({'rescue_ramdisk': 'my_ramdisk',
'rescue_kernel': 'my_kernel'})
instance_info = INST_INFO_DICT
instance_info.update({'rescue_password': 'password'})
n = {
'driver': 'fake-hardware',
'instance_info': instance_info,
'driver_info': driver_info,
'driver_internal_info': DRV_INTERNAL_INFO_DICT,
}
self.node = obj_utils.create_test_node(self.context, **n)
def test_validate_rescue(self):
with task_manager.acquire(self.context, self.node.uuid) as task:
task.driver.boot.validate_rescue(task)
def test_validate_rescue_no_rescue_ramdisk(self):
driver_info = self.node.driver_info
del driver_info['rescue_ramdisk']
self.node.driver_info = driver_info
self.node.save()
with task_manager.acquire(self.context, self.node.uuid) as task:
self.assertRaisesRegex(exception.MissingParameterValue,
'Missing.*rescue_ramdisk',
task.driver.boot.validate_rescue, task)
def test_validate_rescue_fails_no_rescue_kernel(self):
driver_info = self.node.driver_info
del driver_info['rescue_kernel']
self.node.driver_info = driver_info
self.node.save()
with task_manager.acquire(self.context, self.node.uuid) as task:
self.assertRaisesRegex(exception.MissingParameterValue,
'Missing.*rescue_kernel',
task.driver.boot.validate_rescue, task)
@mock.patch.object(ipxe.iPXEBoot, '__init__', lambda self: None)
@mock.patch.object(pxe.PXEBoot, '__init__', lambda self: None)
@mock.patch.object(manager_utils, 'node_set_boot_device', autospec=True)
@mock.patch.object(manager_utils, 'node_power_action', autospec=True)
class PXEBootRetryTestCase(db_base.DbTestCase):
boot_interface = 'pxe'
def setUp(self):
super(PXEBootRetryTestCase, self).setUp()
self.config(enabled_boot_interfaces=['pxe', 'ipxe', 'fake'])
self.config(boot_retry_timeout=300, group='pxe')
self.node = obj_utils.create_test_node(
self.context,
driver='fake-hardware',
boot_interface=self.boot_interface,
provision_state=states.DEPLOYWAIT)
@mock.patch.object(pxe.PXEBoot, '_check_boot_status', autospec=True)
def test_check_boot_timeouts(self, mock_check_status, mock_power,
mock_boot_dev):
def _side_effect(iface, task):
self.assertEqual(self.node.uuid, task.node.uuid)
mock_check_status.side_effect = _side_effect
manager = mock.Mock(spec=['iter_nodes'])
manager.iter_nodes.return_value = [
(uuidutils.generate_uuid(), 'fake-hardware', ''),
(self.node.uuid, self.node.driver, self.node.conductor_group)
]
iface = pxe.PXEBoot()
iface._check_boot_timeouts(manager, self.context)
mock_check_status.assert_called_once_with(iface, mock.ANY)
def test_check_boot_status_another_boot_interface(self, mock_power,
mock_boot_dev):
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.driver.boot = fake.FakeBoot()
pxe.PXEBoot()._check_boot_status(task)
self.assertTrue(task.shared)
self.assertFalse(mock_power.called)
self.assertFalse(mock_boot_dev.called)
def test_check_boot_status_recent_power_change(self, mock_power,
mock_boot_dev):
for field in ('agent_last_heartbeat', 'last_power_state_change'):
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.node.driver_internal_info = {
field: str(timeutils.utcnow().isoformat())
}
task.driver.boot._check_boot_status(task)
self.assertTrue(task.shared)
self.assertFalse(mock_power.called)
self.assertFalse(mock_boot_dev.called)
def test_check_boot_status_maintenance(self, mock_power, mock_boot_dev):
self.node.maintenance = True
self.node.save()
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.driver.boot._check_boot_status(task)
self.assertFalse(task.shared)
self.assertFalse(mock_power.called)
self.assertFalse(mock_boot_dev.called)
def test_check_boot_status_wrong_state(self, mock_power, mock_boot_dev):
self.node.provision_state = states.DEPLOYING
self.node.save()
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.driver.boot._check_boot_status(task)
self.assertFalse(task.shared)
self.assertFalse(mock_power.called)
self.assertFalse(mock_boot_dev.called)
def test_check_boot_status_retry(self, mock_power, mock_boot_dev):
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.driver.boot._check_boot_status(task)
self.assertFalse(task.shared)
mock_power.assert_has_calls([
mock.call(task, states.POWER_OFF),
mock.call(task, states.POWER_ON)
])
mock_boot_dev.assert_called_once_with(task, 'pxe',
persistent=False)
class iPXEBootRetryTestCase(PXEBootRetryTestCase):
boot_interface = 'ipxe'
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?><module moduleId="4244TPM6MM">
<version replacedby="4244TPM6MMPotentiometerModuleID">4</version>
<author>Brendan Howell</author>
<title>Trimmer Potentiometer</title>
<label>R</label>
<date>2009-05-20</date>
<tags>
<tag>potentiometer</tag>
<tag>poti</tag>
<tag>adjustable</tag>
<tag>resistor</tag>
<tag>fritzing core</tag>
</tags>
<properties>
<property name="family">//obsolete//Potentiometer</property>
<property name="type">Trimmer Potentiometer</property>
<property name="Maximum Resistance" showInLabel="yes">10kΩ</property>
<property name="Track">Linear</property>
<property name="Size">Trimmer - 6mm</property>
<property name="package">THT</property></properties>
<taxonomy>discreteParts.resistors.adjustable.potentiometer</taxonomy>
<description>A standard 6mm trimmer potentiometer.</description>
<views>
<iconView>
<layers image="icon/basic_poti_icon.svg">
<layer layerId="icon"/>
</layers>
</iconView>
<breadboardView>
<layers image="breadboard/potentiometer_trimmer.svg">
<layer layerId="breadboard"/>
</layers>
</breadboardView>
<schematicView fliphorizontal="true" flipvertical="true">
<layers image="schematic/basic_poti.svg">
<layer layerId="schematic"/>
</layers>
</schematicView>
<pcbView>
<layers image="pcb/trimpot_meggitt_pih.svg">
<layer layerId="silkscreen"/>
<layer layerId="copper0"/>
<layer layerId="copper1"/></layers>
</pcbView>
</views>
<connectors>
<connector id="connector0" name="leg1" type="male">
<description>leg1</description>
<views>
<breadboardView>
<p layer="breadboard" svgId="connector0pin" terminalId="connector0terminal"/>
</breadboardView>
<schematicView>
<p layer="schematic" svgId="connector0pin" terminalId="connector0terminal"/>
</schematicView>
<pcbView>
<p layer="copper0" svgId="connector0pad"/>
<p layer="copper1" svgId="connector0pad"/></pcbView>
</views>
</connector>
<connector id="connector1" name="wiper" type="male">
<description>wiper</description>
<views>
<breadboardView>
<p layer="breadboard" svgId="connector1pin" terminalId="connector1terminal"/>
</breadboardView>
<schematicView>
<p layer="schematic" svgId="connector1pin" terminalId="connector1terminal"/>
</schematicView>
<pcbView>
<p layer="copper0" svgId="connector1pad"/>
<p layer="copper1" svgId="connector1pad"/></pcbView>
</views>
</connector>
<connector id="connector2" name="leg2" type="male">
<description>leg2</description>
<views>
<breadboardView>
<p layer="breadboard" svgId="connector2pin" terminalId="connector2terminal"/>
</breadboardView>
<schematicView>
<p layer="schematic" svgId="connector2pin" terminalId="connector2terminal"/>
</schematicView>
<pcbView>
<p layer="copper0" svgId="connector2pad"/>
<p layer="copper1" svgId="connector2pad"/></pcbView>
</views>
</connector>
</connectors>
</module> | {
"pile_set_name": "Github"
} |
TIMESTAMP = 1559777557
SHA256 (azure-mgmt-search-2.1.0.zip) = 92a40a1a7a9e3a82b6fa302042799e8d5a67d3996c20835af72afc14f1610501
SIZE (azure-mgmt-search-2.1.0.zip) = 56140
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2014 Freescale Semiconductor, Inc.
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <fsl_ddr_sdram.h>
#include <fsl_ddr_dimm_params.h>
#include <asm/io.h>
#include <asm/arch/clock.h>
#include "ddr.h"
DECLARE_GLOBAL_DATA_PTR;
void fsl_ddr_board_options(memctl_options_t *popts,
dimm_params_t *pdimm,
unsigned int ctrl_num)
{
const struct board_specific_parameters *pbsp, *pbsp_highest = NULL;
ulong ddr_freq;
if (ctrl_num > 3) {
printf("Not supported controller number %d\n", ctrl_num);
return;
}
if (!pdimm->n_ranks)
return;
pbsp = udimms[0];
/* Get clk_adjust, wrlvl_start, wrlvl_ctl, according to the board ddr
* freqency and n_banks specified in board_specific_parameters table.
*/
ddr_freq = get_ddr_freq(0) / 1000000;
while (pbsp->datarate_mhz_high) {
if (pbsp->n_ranks == pdimm->n_ranks) {
if (ddr_freq <= pbsp->datarate_mhz_high) {
popts->clk_adjust = pbsp->clk_adjust;
popts->wrlvl_start = pbsp->wrlvl_start;
popts->wrlvl_ctl_2 = pbsp->wrlvl_ctl_2;
popts->wrlvl_ctl_3 = pbsp->wrlvl_ctl_3;
popts->cpo_override = pbsp->cpo_override;
popts->write_data_delay =
pbsp->write_data_delay;
goto found;
}
pbsp_highest = pbsp;
}
pbsp++;
}
if (pbsp_highest) {
printf("Error: board specific timing not found for %lu MT/s\n",
ddr_freq);
printf("Trying to use the highest speed (%u) parameters\n",
pbsp_highest->datarate_mhz_high);
popts->clk_adjust = pbsp_highest->clk_adjust;
popts->wrlvl_start = pbsp_highest->wrlvl_start;
popts->wrlvl_ctl_2 = pbsp->wrlvl_ctl_2;
popts->wrlvl_ctl_3 = pbsp->wrlvl_ctl_3;
} else {
panic("DIMM is not supported by this board");
}
found:
debug("Found timing match: n_ranks %d, data rate %d, rank_gb %d\n",
pbsp->n_ranks, pbsp->datarate_mhz_high, pbsp->rank_gb);
/* force DDR bus width to 32 bits */
popts->data_bus_width = 1;
popts->otf_burst_chop_en = 0;
popts->burst_length = DDR_BL8;
/*
* Factors to consider for half-strength driver enable:
* - number of DIMMs installed
*/
popts->half_strength_driver_enable = 1;
/*
* Write leveling override
*/
popts->wrlvl_override = 1;
popts->wrlvl_sample = 0xf;
/*
* Rtt and Rtt_WR override
*/
popts->rtt_override = 0;
/* Enable ZQ calibration */
popts->zq_en = 1;
#ifdef CONFIG_SYS_FSL_DDR4
popts->ddr_cdr1 = DDR_CDR1_DHC_EN | DDR_CDR1_ODT(DDR_CDR_ODT_80ohm);
popts->ddr_cdr2 = DDR_CDR2_ODT(DDR_CDR_ODT_80ohm) |
DDR_CDR2_VREF_OVRD(70); /* Vref = 70% */
#else
popts->cswl_override = DDR_CSWL_CS0;
/* optimize cpo for erratum A-009942 */
popts->cpo_sample = 0x58;
/* DHC_EN =1, ODT = 75 Ohm */
popts->ddr_cdr1 = DDR_CDR1_DHC_EN | DDR_CDR1_ODT(DDR_CDR_ODT_75ohm);
popts->ddr_cdr2 = DDR_CDR2_ODT(DDR_CDR_ODT_75ohm);
#endif
}
#ifdef CONFIG_SYS_DDR_RAW_TIMING
dimm_params_t ddr_raw_timing = {
.n_ranks = 1,
.rank_density = 1073741824u,
.capacity = 1073741824u,
.primary_sdram_width = 32,
.ec_sdram_width = 0,
.registered_dimm = 0,
.mirrored_dimm = 0,
.n_row_addr = 15,
.n_col_addr = 10,
.n_banks_per_sdram_device = 8,
.edc_config = 0,
.burst_lengths_bitmask = 0x0c,
.tckmin_x_ps = 1071,
.caslat_x = 0xfe << 4, /* 5,6,7,8 */
.taa_ps = 13125,
.twr_ps = 15000,
.trcd_ps = 13125,
.trrd_ps = 7500,
.trp_ps = 13125,
.tras_ps = 37500,
.trc_ps = 50625,
.trfc_ps = 160000,
.twtr_ps = 7500,
.trtp_ps = 7500,
.refresh_rate_ps = 7800000,
.tfaw_ps = 37500,
};
int fsl_ddr_get_dimm_params(dimm_params_t *pdimm,
unsigned int controller_number,
unsigned int dimm_number)
{
static const char dimm_model[] = "Fixed DDR on board";
if (((controller_number == 0) && (dimm_number == 0)) ||
((controller_number == 1) && (dimm_number == 0))) {
memcpy(pdimm, &ddr_raw_timing, sizeof(dimm_params_t));
memset(pdimm->mpart, 0, sizeof(pdimm->mpart));
memcpy(pdimm->mpart, dimm_model, sizeof(dimm_model) - 1);
}
return 0;
}
#endif
#if defined(CONFIG_DEEP_SLEEP)
void board_mem_sleep_setup(void)
{
void __iomem *qixis_base = (void *)QIXIS_BASE;
/* does not provide HW signals for power management */
clrbits_8(qixis_base + 0x21, 0x2);
udelay(1);
}
#endif
int fsl_initdram(void)
{
phys_size_t dram_size;
#if defined(CONFIG_SPL_BUILD) || !defined(CONFIG_SPL)
puts("Initializing DDR....using SPD\n");
dram_size = fsl_ddr_sdram();
#else
dram_size = fsl_ddr_sdram_size();
#endif
#if defined(CONFIG_DEEP_SLEEP) && !defined(CONFIG_SPL_BUILD)
fsl_dp_resume();
#endif
gd->ram_size = dram_size;
return 0;
}
int dram_init_banksize(void)
{
gd->bd->bi_dram[0].start = CONFIG_SYS_SDRAM_BASE;
gd->bd->bi_dram[0].size = gd->ram_size;
return 0;
}
| {
"pile_set_name": "Github"
} |
{
"quicksand" : {
"index" : 10,
"targetType" : "NO_TARGET",
"sounds": {
"cast": "QUIKSAND"
},
"levels" : {
"base":{
"range" : "X",
"battleEffects" : {
"obstacle" : {
"type":"core:obstacle",
"hidden" : true,
"passable" : true,
"trap" : true,
"trigger" : false,
"patchCount" : 4,
"turnsRemaining" : -1,
"attacker" :{
"animation" : "C17SPE1",
"appearAnimation" : "C17SPE0",
"offsetY" : -42
},
"defender" :{
"animation" : "C17SPE1",
"appearAnimation" : "C17SPE0",
"offsetY" : -42
}
}
}
},
"advanced":{
"battleEffects":{
"obstacle":{
"patchCount" : 6
}
}
},
"expert":{
"battleEffects":{
"obstacle":{
"patchCount" : 8
}
}
}
},
"flags" : {
"indifferent": true
}
},
"landMine" : {
"index" : 11,
"targetType" : "NO_TARGET",
"sounds": {
"cast": ""
},
"levels" : {
"base":{
"range" : "X",
"battleEffects" : {
"obstacle" : {
"type":"core:obstacle",
"hidden" : true,
"passable" : true,
"trap" : false,
"trigger" : true,
"removeOnTrigger" : true,
"patchCount" : 4,
"turnsRemaining" : -1,
"attacker" :{
"animation" : "C09SPF1",
"appearAnimation" : "C09SPF0"
},
"defender" :{
"animation" : "C09SPF1",
"appearAnimation" : "C09SPF0"
}
},
"damage":{
"type":"core:damage",
"optional":false,
"indirect":true,
"customEffectId" : 82
}
}
},
"advanced":{
"battleEffects":{
"obstacle":{
"patchCount" : 6
}
}
},
"expert":{
"battleEffects":{
"obstacle":{
"patchCount" : 8
}
}
}
},
"flags" : {
"damage": true,
"indifferent": true
},
"targetCondition" : {
"noneOf" : {
"bonus.DIRECT_DAMAGE_IMMUNITY" : "normal"
}
}
},
"forceField" : {
"index" : 12,
"targetType" : "LOCATION",
"sounds": {
"cast": "FORCEFLD"
},
"levels" : {
"base":{
"range" : "0",
"targetModifier":{
"clearAffected": true
},
"battleEffects":{
"obstacle":{
"type":"core:obstacle",
"hidden" : false,
"passable" : false,
"trap" : false,
"trigger" : false,
"patchCount" : 1,
"turnsRemaining" : 2,
"attacker" :{
"range" : [[""]],
"shape" : [[""], ["TR"]],
"animation" : "C15SPE1",
"appearAnimation" : "C15SPE0"
},
"defender" :{
"range" : [[""]],
"shape" : [[""], ["TL"]],
"animation" : "C15SPE4",
"appearAnimation" : "C15SPE0"
}
}
}
},
"advanced":{
"battleEffects":{
"obstacle":{
"attacker" :{
"shape" : [[""], ["TR"], ["TR", "TL"]],
"animation" : "C15SPE10",
"appearAnimation" : "C15SPE9"
},
"defender" :{
"shape" : [[""], ["TL"], ["TL", "TR"]],
"animation" : "C15SPE7",
"appearAnimation" : "C15SPE6"
}
}
}
},
"expert":{
"battleEffects":{
"obstacle":{
"attacker" :{
"shape" : [[""], ["TR"], ["TR", "TL"]],
"animation" : "C15SPE10",
"appearAnimation" : "C15SPE9"
},
"defender" :{
"shape" : [[""], ["TL"], ["TL", "TR"]],
"animation" : "C15SPE7",
"appearAnimation" : "C15SPE6"
}
}
}
}
},
"flags" : {
"indifferent": true
}
},
"fireWall" : {
"index" : 13,
"targetType" : "LOCATION",
"sounds": {
"cast": "FIREWALL"
},
"levels" : {
"base":{
"range" : "0",
"targetModifier":{
"clearAffected": true
},
"battleEffects":{
"obstacle":{
"type":"core:obstacle",
"hidden" : false,
"passable" : true,
"trap" : false,
"trigger" : true,
"patchCount" : 1,
"turnsRemaining" : 2,
"attacker" :{
"shape" : [[""]],
"range" : [[""], ["TR"]],
"animation" : "C07SPF61",
"appearAnimation" : "C07SPF60"
},
"defender" :{
"shape" : [[""]],
"range" : [[""], ["TL"]],
"animation" : "C07SPF61",
"appearAnimation" : "C07SPF60"
}
},
"damage":{
"type":"core:damage",
"optional":false,
"indirect":true
}
}
},
"advanced":{
"battleEffects":{
"obstacle":{
"attacker" :{
"range" : [[""], ["TR"], ["TR", "TL"]]
},
"defender" :{
"range" : [[""], ["TL"], ["TL", "TR"]]
}
}
}
},
"expert":{
"battleEffects":{
"obstacle":{
"attacker" :{
"range" : [[""], ["TR"], ["TR", "TL"]]
},
"defender" :{
"range" : [[""], ["TL"], ["TL", "TR"]]
}
}
}
}
},
"flags" : {
"damage": true,
"indifferent": true
},
"targetCondition" : {
"noneOf" : {
"bonus.DIRECT_DAMAGE_IMMUNITY" : "normal"
}
}
},
"earthquake" : {
"index" : 14,
"targetType" : "NO_TARGET",
"sounds": {
"cast": "ERTHQUAK"
},
"levels" : {
"base":{
"targetModifier":{"smart":true},
"battleEffects":{
"catapult":{
"type":"core:catapult",
"targetsToAttack": 2
}
},
"range" : "X"
},
"advanced":{
"battleEffects":{
"catapult":{
"targetsToAttack": 3
}
}
},
"expert":{
"battleEffects":{
"catapult":{
"targetsToAttack": 4
}
}
}
},
"flags" : {
"indifferent": true
}
},
"dispel" : {
"index" : 35,
"targetType" : "CREATURE",
"animation":{
"affect":["C05SPW"] //C05SPW0
},
"sounds": {
"cast": "DISPELL"
},
"levels" : {
"base":{
"targetModifier":{
"smart":true
},
"battleEffects":{
"dispel":{
"type":"core:dispel",
"optional":false,
"ignoreImmunity" : true,
"dispelNegative":true,
"dispelNeutral":true,
"dispelPositive":true
}
},
"range" : "0"
},
"advanced":{
"targetModifier":{"smart":false}
},
"expert":{
"targetModifier":{"smart":false},
"battleEffects":{
"dispel":{
"optional":true
},
"removeObstacle":{
"optional":true,
"type":"core:removeObstacle",
"removeAllSpells" : true
}
},
"range" : "X"
}
},
"flags" : {
"positive": true
}
},
"cure" : {
"index" : 37,
"targetType" : "CREATURE",
"animation":{
"affect":["C03SPW"]//C03SPW0
},
"sounds": {
"cast": "CURE"
},
"levels" : {
"base":{
"targetModifier":{"smart":true},
"battleEffects":{
"heal":{
"type":"core:heal",
"healLevel":"heal",
"healPower":"permanent",
"optional":true
},
"cure":{
"type":"core:dispel",
"optional":true,
"dispelNegative":true,
"dispelNeutral":false,
"dispelPositive":false
}
},
"range" : "0"
},
"expert":{
"range" : "X"
}
},
"flags" : {
"positive": true
}
},
"resurrection" : {
"index" : 38,
"targetType" : "CREATURE",
"animation":{
"affect":["C01SPE0"]
},
"sounds": {
"cast": "RESURECT"
},
"levels" : {
"base":{
"range" : "0",
"battleEffects":{
"heal":{
"type":"core:heal",
"healLevel":"resurrect",
"healPower":"oneBattle",
"minFullUnits" : 1
},
"cure":{
"type":"core:dispel",
"indirect": true,
"optional":true,
"dispelNegative":true,
"dispelNeutral":false,
"dispelPositive":false
}
},
"targetModifier":{"smart":true}
},
"advanced":{
"battleEffects":{
"heal":{
"healPower":"permanent"
}
}
},
"expert":{
"battleEffects":{
"heal":{
"healPower":"permanent"
}
}
}
},
"flags" : {
"rising": true,
"positive": true
},
"targetCondition" : {
"noneOf" : {
"bonus.NON_LIVING" : "absolute",
"bonus.SIEGE_WEAPON" : "absolute",
"bonus.UNDEAD" : "absolute",
"bonus.GARGOYLE" : "absolute"
}
}
},
"animateDead" : {
"index" : 39,
"targetType" : "CREATURE",
"animation":{
"affect":["C01SPE0"]
},
"sounds": {
"cast": "ANIMDEAD"
},
"levels" : {
"base":{
"range" : "0",
"battleEffects":{
"heal":{
"type":"core:heal",
"healLevel":"resurrect",
"healPower":"permanent",
"minFullUnits" : 1
}
},
"targetModifier":{"smart":true}
}
},
"flags" : {
"rising": true,
"positive": true
},
"targetCondition" : {
"allOf" : {
"bonus.UNDEAD" : "absolute"
}
}
},
"sacrifice" : {
"index" : 40,
"targetType" : "CREATURE",
"animation":{
"affect":["C01SPE0"]
},
"sounds": {
"cast": "SACRIF1"
},
"levels" : {
"base":{
"range" : "0",
"battleEffects":{
"sacrifice":{
"type":"core:sacrifice",
"healLevel":"resurrect",
"healPower":"permanent",
"minFullUnits" : 0
}
},
"targetModifier":{"smart":true}
}
},
"flags" : {
"rising": true,
"positive": true
},
"targetCondition" : {
"noneOf" : {
"bonus.NON_LIVING" : "absolute",
"bonus.SIEGE_WEAPON" : "absolute",
"bonus.UNDEAD" : "absolute",
"bonus.GARGOYLE" : "absolute"
}
}
},
"teleport" : {
"index" : 63,
"targetType" : "CREATURE",
"sounds": {
"cast": "TELPTOUT"
},
"levels" : {
"base":{
"range" : "0",
"battleEffects":{
"teleport":{
"type":"core:teleport"
}
},
"targetModifier":{"smart":true}
}
},
"flags" : {
"positive": true
},
"targetCondition" : {
"noneOf" : {
"bonus.SIEGE_WEAPON" : "absolute"
}
}
},
"removeObstacle" : {
"index" : 64,
"targetType" : "OBSTACLE",
"animation":{
"cast":[2]
},
"sounds": {
"cast": "REMOVEOB"
},
"levels" : {
"base":{
"range" : "0",
"battleEffects": {
"removeObstacle" : {
"optional":false,
"type":"core:removeObstacle",
"removeUsual" : true
}
}
},
"advanced" : {
"battleEffects": {
"removeObstacle" : {
"removeSpells" : ["fireWall"]
}
}
},
"expert" : {
"battleEffects": {
"removeObstacle" : {
"removeAllSpells" : true
}
}
}
},
"flags" : {
"indifferent": true
}
},
"clone" : {
"index" : 65,
"targetType" : "CREATURE",
"animation":{
"cast":[2]
},
"sounds": {
"cast": "CLONE"
},
"levels" : {
"base":{
"range" : "0",
"battleEffects":{
"clone":{
"maxTier":5,
"type":"core:clone"
}
},
"targetModifier":{"smart":true}
},
"advanced":{
"battleEffects":{
"clone":{
"maxTier":6
}
}
},
"expert":{
"battleEffects":{
"clone":{
"maxTier":1000
}
}
}
},
"flags" : {
"positive": true
},
"targetCondition" : {
"noneOf" : {
"bonus.SIEGE_WEAPON" : "absolute"
}
}
},
"fireElemental" : {
"index" : 66,
"targetType" : "NO_TARGET",
"animation":{
"cast":[2]
},
"sounds": {
"cast": "SUMNELM"
},
"levels" : {
"base":{
"range" : "X",
"battleEffects":{
"summon":{
"exclusive":true,
"id":"fireElemental",
"permanent":false,
"type":"core:summon"
}
}
}
},
"flags" : {
"indifferent": true
}
},
"earthElemental" : {
"index" : 67,
"targetType" : "NO_TARGET",
"animation":{
"cast":[2]
},
"sounds": {
"cast": "SUMNELM"
},
"levels" : {
"base":{
"range" : "X",
"battleEffects":{
"summon":{
"exclusive":true,
"id":"earthElemental",
"permanent":false,
"type":"core:summon"
}
}
}
},
"flags" : {
"indifferent": true
}
},
"waterElemental" : {
"index" : 68,
"targetType" : "NO_TARGET",
"animation":{
"cast":[2]
},
"sounds": {
"cast": "SUMNELM"
},
"levels" : {
"base":{
"range" : "X",
"battleEffects":{
"summon":{
"exclusive":true,
"id":"waterElemental",
"permanent":false,
"type":"core:summon"
}
}
}
},
"flags" : {
"indifferent": true
}
},
"airElemental" : {
"index" : 69,
"targetType" : "NO_TARGET",
"animation":{
"cast":[2]
},
"sounds": {
"cast": "SUMNELM"
},
"levels" : {
"base":{
"range" : "X",
"battleEffects":{
"summon":{
"exclusive":true,
"id":"airElemental",
"permanent":false,
"type":"core:summon"
}
}
}
},
"flags" : {
"indifferent": true
}
}
}
| {
"pile_set_name": "Github"
} |
FROM balenalib/armv7hf-fedora:29-run
LABEL io.balena.device-type="beaglebone-black"
RUN dnf install -y \
less \
nano \
net-tools \
usbutils \
gnupg \
i2c-tools \
&& dnf clean all
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Fedora 29 \nVariant: run variant \nDefault variable(s): UDEV=off \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"pile_set_name": "Github"
} |
.\" Copyright (c) 1983, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)truncate.2 8.1 (Berkeley) 6/4/93
.\" $FreeBSD: src/lib/libc/sys/truncate.2,v 1.7.2.6 2001/12/14 18:34:02 ru Exp $
.\" $DragonFly: src/lib/libc/sys/truncate.2,v 1.3 2006/02/17 19:35:06 swildner Exp $
.\"
.Dd June 4, 1993
.Dt TRUNCATE 2
.Os
.Sh NAME
.Nm truncate ,
.Nm ftruncate
.Nd truncate or extend a file to a specified length
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In unistd.h
.Ft int
.Fn truncate "const char *path" "off_t length"
.Ft int
.Fn ftruncate "int fd" "off_t length"
.Sh DESCRIPTION
.Fn Truncate
causes the file named by
.Fa path
or referenced by
.Fa fd
to be truncated or extended to
.Fa length
bytes in size. If the file
was larger than this size, the extra data
is lost.
If the file was smaller than this size,
it will be extended as if by writing bytes
with the value zero.
With
.Fn ftruncate ,
the file must be open for writing.
.Sh RETURN VALUES
.Rv -std
.Sh ERRORS
.Fn Truncate
succeeds unless:
.Bl -tag -width Er
.It Bq Er ENOTDIR
A component of the path prefix is not a directory.
.It Bq Er ENAMETOOLONG
A component of a pathname exceeded 255 characters,
or an entire path name exceeded 1023 characters.
.It Bq Er ENOENT
The named file does not exist.
.It Bq Er EACCES
Search permission is denied for a component of the path prefix.
.It Bq Er EACCES
The named file is not writable by the user.
.It Bq Er ELOOP
Too many symbolic links were encountered in translating the pathname.
.It Bq Er EISDIR
The named file is a directory.
.It Bq Er EROFS
The named file resides on a read-only file system.
.It Bq Er ETXTBSY
The file is a pure procedure (shared text) file that is being executed.
.It Bq Er EIO
An I/O error occurred updating the inode.
.It Bq Er EFAULT
.Fa Path
points outside the process's allocated address space.
.El
.Pp
.Fn Ftruncate
succeeds unless:
.Bl -tag -width Er
.It Bq Er EBADF
The
.Fa fd
is not a valid descriptor.
.It Bq Er EINVAL
The
.Fa fd
references a socket, not a file.
.It Bq Er EINVAL
The
.Fa fd
is not open for writing.
.El
.Sh SEE ALSO
.Xr open 2
.Sh HISTORY
The
.Fn truncate
function call appeared in
.Bx 4.2 .
.Sh BUGS
These calls should be generalized to allow ranges
of bytes in a file to be discarded.
.Pp
Use of
.Fn truncate
to extend a file is not portable.
| {
"pile_set_name": "Github"
} |
# -*- encoding: utf-8 -*-
require 'test_helper'
require 'hexapdf/font_loader'
require 'hexapdf/document'
describe HexaPDF::FontLoader::FromFile do
before do
@doc = HexaPDF::Document.new
@font_file = File.join(TEST_DATA_DIR, "fonts", "Ubuntu-Title.ttf")
@klass = HexaPDF::FontLoader::FromFile
end
it "loads the specified font file" do
wrapper = @klass.call(@doc, @font_file)
assert_equal("Ubuntu-Title", wrapper.wrapped_font.font_name)
end
it "passes the subset value to the wrapper" do
wrapper = @klass.call(@doc, @font_file)
assert(wrapper.subset?)
wrapper = @klass.call(@doc, @font_file, subset: false)
refute(wrapper.subset?)
end
it "returns nil if the given name doesn't represent a file" do
assert_nil(@klass.call(@doc, "Unknown"))
end
end
| {
"pile_set_name": "Github"
} |
import { BR_BOUNDING_VOLUME_TREE } from '../../../constants';
import { BroadPhase } from '../BroadPhase';
import { DBVT } from './DBVT';
import { DBVTProxy } from './DBVTProxy';
/**
* A broad-phase algorithm using dynamic bounding volume tree.
*
* @author saharan
* @author lo-th
*/
function DBVTBroadPhase(){
BroadPhase.call( this );
this.types = BR_BOUNDING_VOLUME_TREE;
this.tree = new DBVT();
this.stack = [];
this.leaves = [];
this.numLeaves = 0;
};
DBVTBroadPhase.prototype = Object.assign( Object.create( BroadPhase.prototype ), {
constructor: DBVTBroadPhase,
createProxy: function ( shape ) {
return new DBVTProxy( shape );
},
addProxy: function ( proxy ) {
this.tree.insertLeaf( proxy.leaf );
this.leaves.push( proxy.leaf );
this.numLeaves++;
},
removeProxy: function ( proxy ) {
this.tree.deleteLeaf( proxy.leaf );
var n = this.leaves.indexOf( proxy.leaf );
if ( n > -1 ) {
this.leaves.splice(n,1);
this.numLeaves--;
}
},
collectPairs: function () {
if ( this.numLeaves < 2 ) return;
var leaf, margin = 0.1, i = this.numLeaves;
while(i--){
leaf = this.leaves[i];
if ( leaf.proxy.aabb.intersectTestTwo( leaf.aabb ) ){
leaf.aabb.copy( leaf.proxy.aabb, margin );
this.tree.deleteLeaf( leaf );
this.tree.insertLeaf( leaf );
this.collide( leaf, this.tree.root );
}
}
},
collide: function ( node1, node2 ) {
var stackCount = 2;
var s1, s2, n1, n2, l1, l2;
this.stack[0] = node1;
this.stack[1] = node2;
while( stackCount > 0 ){
n1 = this.stack[--stackCount];
n2 = this.stack[--stackCount];
l1 = n1.proxy != null;
l2 = n2.proxy != null;
this.numPairChecks++;
if( l1 && l2 ){
s1 = n1.proxy.shape;
s2 = n2.proxy.shape;
if ( s1 == s2 || s1.aabb.intersectTest( s2.aabb ) || !this.isAvailablePair( s1, s2 ) ) continue;
this.addPair(s1,s2);
}else{
if ( n1.aabb.intersectTest( n2.aabb ) ) continue;
/*if(stackCount+4>=this.maxStack){// expand the stack
//this.maxStack<<=1;
this.maxStack*=2;
var newStack = [];// vector
newStack.length = this.maxStack;
for(var i=0;i<stackCount;i++){
newStack[i] = this.stack[i];
}
this.stack = newStack;
}*/
if( l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea()) ){
this.stack[stackCount++] = n1.child1;
this.stack[stackCount++] = n2;
this.stack[stackCount++] = n1.child2;
this.stack[stackCount++] = n2;
}else{
this.stack[stackCount++] = n1;
this.stack[stackCount++] = n2.child1;
this.stack[stackCount++] = n1;
this.stack[stackCount++] = n2.child2;
}
}
}
}
});
export { DBVTBroadPhase }; | {
"pile_set_name": "Github"
} |
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"doc.go",
"generated.pb.go",
"register.go",
"types.go",
"types_swagger_doc_generated.go",
"zz_generated.deepcopy.go",
],
deps = [
"//vendor/github.com/gogo/protobuf/proto:go_default_library",
"//vendor/k8s.io/api/core/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
filegroup(
name = "go_default_library_protos",
srcs = ["generated.proto"],
visibility = ["//visibility:public"],
)
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_TYPE_TRAITS_IS_MEMBER_FUNCTION_POINTER_HPP
#define SPROUT_TYPE_TRAITS_IS_MEMBER_FUNCTION_POINTER_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/type_traits/detail/type_traits_wrapper.hpp>
namespace sprout {
//
// is_member_function_pointer
//
template<typename T>
struct is_member_function_pointer
: public sprout::detail::type_traits_wrapper<std::is_member_function_pointer<T> >
{};
#if SPROUT_USE_VARIABLE_TEMPLATES
template<typename T>
SPROUT_STATIC_CONSTEXPR bool is_member_function_pointer_v = sprout::is_member_function_pointer<T>::value;
#endif // #if SPROUT_USE_VARIABLE_TEMPLATES
} // namespace sprout
#endif // #ifndef SPROUT_TYPE_TRAITS_IS_MEMBER_FUNCTION_POINTER_HPP
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_35) on Tue Oct 16 22:49:49 ICT 2012 -->
<TITLE>
Uses of Package org.apache.fop.render.intermediate.extensions (Apache FOP 1.1 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-16">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.apache.fop.render.intermediate.extensions (Apache FOP 1.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/render/intermediate/extensions/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Package<br>org.apache.fop.render.intermediate.extensions</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/package-summary.html">org.apache.fop.render.intermediate.extensions</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.intermediate"><B>org.apache.fop.render.intermediate</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.intermediate.extensions"><B>org.apache.fop.render.intermediate.extensions</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.pdf"><B>org.apache.fop.render.pdf</B></A></TD>
<TD>PDF Renderer </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.intermediate"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/package-summary.html">org.apache.fop.render.intermediate.extensions</A> used by <A HREF="../../../../../../org/apache/fop/render/intermediate/package-summary.html">org.apache.fop.render.intermediate</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/AbstractAction.html#org.apache.fop.render.intermediate"><B>AbstractAction</B></A></B>
<BR>
Abstract base class for document actions, like "go-to" actions with absolute page coordinates.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/BookmarkTree.html#org.apache.fop.render.intermediate"><B>BookmarkTree</B></A></B>
<BR>
This class is the root of the bookmark tree for use in the intermediate format.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/Link.html#org.apache.fop.render.intermediate"><B>Link</B></A></B>
<BR>
This class is a link element for use in the intermediate format.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/NamedDestination.html#org.apache.fop.render.intermediate"><B>NamedDestination</B></A></B>
<BR>
This class is a named destination element for use in the intermediate format.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.intermediate.extensions"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/package-summary.html">org.apache.fop.render.intermediate.extensions</A> used by <A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/package-summary.html">org.apache.fop.render.intermediate.extensions</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/AbstractAction.html#org.apache.fop.render.intermediate.extensions"><B>AbstractAction</B></A></B>
<BR>
Abstract base class for document actions, like "go-to" actions with absolute page coordinates.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/Bookmark.html#org.apache.fop.render.intermediate.extensions"><B>Bookmark</B></A></B>
<BR>
This class is a bookmark element for use in the intermediate format.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/DocumentNavigationExtensionConstants.html#org.apache.fop.render.intermediate.extensions"><B>DocumentNavigationExtensionConstants</B></A></B>
<BR>
Constants for the IF document-level navigation extension.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.pdf"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/package-summary.html">org.apache.fop.render.intermediate.extensions</A> used by <A HREF="../../../../../../org/apache/fop/render/pdf/package-summary.html">org.apache.fop.render.pdf</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/AbstractAction.html#org.apache.fop.render.pdf"><B>AbstractAction</B></A></B>
<BR>
Abstract base class for document actions, like "go-to" actions with absolute page coordinates.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/BookmarkTree.html#org.apache.fop.render.pdf"><B>BookmarkTree</B></A></B>
<BR>
This class is the root of the bookmark tree for use in the intermediate format.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/Link.html#org.apache.fop.render.pdf"><B>Link</B></A></B>
<BR>
This class is a link element for use in the intermediate format.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/fop/render/intermediate/extensions/class-use/NamedDestination.html#org.apache.fop.render.pdf"><B>NamedDestination</B></A></B>
<BR>
This class is a named destination element for use in the intermediate format.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/render/intermediate/extensions/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
// indices/update-settings.asciidoc:120
[source, php]
----
$params = [
'index' => 'twitter',
'body' => [
'index' => [
'refresh_interval' => '1s',
],
],
];
$response = $client->indices()->putSettings($params);
----
| {
"pile_set_name": "Github"
} |
import React from "react";
import * as SSMActions from "../actions/SSMActions";
import SSMStore from "../stores/SSMStore";
import Instance from "../components/Instance";
import { Dropdown, Input, Form, Message, Button } from "semantic-ui-react";
export default class Instances extends React.Component {
constructor(){
super();
this.state = {
instances: SSMStore.getInstances(),
regions: [],
selectedRegion: "",
viewOptionsValue: "byInstanceName",
instanceSearchValue: "",
refreshInstancesLoading: false,
};
this.handleViewOptionsChange = this.handleViewOptionsChange.bind(this);
this.handleSearchChange = this.handleSearchChange.bind(this);
this.handleRefreshButton = this.handleRefreshButton.bind(this);
}
componentWillMount() {
SSMStore.on("instances_changed", () => {
this.setState(
{
instances: SSMStore.getInstances(),
refreshInstancesLoading:false,
}
);
});
SSMStore.on("selected_region_changed", () => {
this.setState(
{
selectedRegion: SSMStore.getSelectedRegion(),
}
);
});
SSMStore.on("regions_updated", () => {
this.setState({regions: SSMStore.getRegions()});
});
SSMStore.on("clear_search", () => {
this.setState({instanceSearchValue:""});
});
SSMStore.on("refresh_instances_loading",() => {
this.setState({refreshInstancesLoading:true});
});
}
loadRegions() {
SSMActions.loadRegions();
}
loadInstances() {
SSMActions.loadInstances(this.state.selectedRegion);
}
selectRegion(event, data){
const region = data.value;
SSMActions.selectRegion(region);
}
handleViewOptionsChange(e, { value }){
this.setState({viewOptionsValue: value});
}
handleSearchChange(e, { value }){
this.setState({instanceSearchValue:value});
}
handleRefreshButton(){
SSMActions.refreshInstances();
}
render() {
if (!SSMStore.isAuthenticated){
return (
<Message warning>
<Message.Header> Not Authenticated </Message.Header>
<p>Enter authentication details to load instances ...</p>
</Message>
);
}
else {
const { instances, selectedRegion, viewOptionsValue, instanceSearchValue, refreshInstancesLoading } = this.state;
const instancesList = [];
Object.keys(instances).map(function(key, index) {
const instanceId = key;
const commandStatus = (instances[instanceId]['commandStatus']) ? commandStatus : "";
const iconInfo = {
loading: (instances[instanceId]['commandStatus'] == "loading") ? true : false,
color: (instances[instanceId]['commandStatus'] == "success") ? "blue" : "black",
};
if (instances[instanceId]['commandStatus'] == "success") iconInfo['icon'] = 'check';
else if (instances[instanceId]['commandStatus'] == "loading") iconInfo['icon'] = 'spinner';
else if (instances[instanceId]['commandStatus'] == "error") {
iconInfo['icon'] = 'remove';
iconInfo['color'] = 'red';
}
instancesList.push(
<Instance key={instanceId} instanceId={instanceId} {...instances[instanceId]} iconInfo={iconInfo} viewOptionsValue={viewOptionsValue} instanceSearchValue={instanceSearchValue}/>
);
});
const regionsList = [];
this.state.regions.map( (region) => {regionsList.push({key:region, value:region, text:region});});
const viewOptionsForm = <Form>
<Form.Group inline>
<label>Show</label>
<Form.Radio label='Name' value='byInstanceName' checked={viewOptionsValue === "byInstanceName"} onChange={this.handleViewOptionsChange} />
<Form.Radio label='Instance Id' value='byInstanceId' checked={viewOptionsValue === "byInstanceId"} onChange={this.handleViewOptionsChange} />
</Form.Group>
</Form>;
return (
<div>
<h1> Select Instances </h1>
<Dropdown search placeholder='Choose region...'
options={regionsList} onChange={this.selectRegion} value={selectedRegion}/>
<Button size='small' loading={refreshInstancesLoading} icon='refresh' style={{'position':'absolute','right':'0','backgroundColor':'Transparent'}} onClick={this.handleRefreshButton} />
<hr></hr>
{instancesList.length > 0
? <Input size='mini' icon='search' fluid value={this.state.instanceSearchValue} placeholder='Search instances by name, details, tags, ...' onChange={this.handleSearchChange} />
: null
}
<br />
{instancesList.length > 0 ? instancesList: "No instances in selected region"}
<br />
{instancesList.length > 0 ? viewOptionsForm: null }
</div>
);
}
}
} | {
"pile_set_name": "Github"
} |
###
# Makefile.basic lists the most basic programs used during the build process.
# The programs listed herein are what are needed to do the basic stuff,
# such as fix file dependencies.
# This initial step is needed to avoid files to be recompiled
# when kernel configuration changes (which is what happens when
# .config is included by main Makefile.
# ---------------------------------------------------------------------------
# fixdep: Used to generate dependency information during build process
hostprogs-y := fixdep
always := $(hostprogs-y)
# fixdep is needed to compile other host programs
$(addprefix $(obj)/,$(filter-out fixdep,$(always))): $(obj)/fixdep
| {
"pile_set_name": "Github"
} |
import styled from 'styled-components/native';
import { red } from '../../utils/colors';
export const Container = styled.ScrollView`
flex: 1;
background: #fff;
`;
export const BackButton = styled.TouchableOpacity``;
export const Panel = styled.View`
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
padding: 0 20px;
margin: 40px 0;
`;
export const Balance = styled.View``;
export const Money = styled.View`
display: flex;
flex-direction: row;
align-items: baseline;
`;
export const Title = styled.Text`
font-size: 18px;
color: #999999;
`;
export const Value = styled.Text`
margin-top: 10px;
font-size: 25px;
`;
export const QrCode = styled.View`
align-items: center;
`;
export const Options = styled.ScrollView.attrs({
showsHorizontalScrollIndicator: false,
})`
background: #eee;
padding: 20px 5px;
`;
export const Option = styled.TouchableOpacity`
background: #fff;
margin: 5px;
width: 120px;
height: 110px;
padding: 5px;
border-radius: 4px;
justify-content: space-around;
`;
export const Message = styled.Text`
margin: 5px 0;
font-size: 18px;
color: #999;
`; | {
"pile_set_name": "Github"
} |
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cache
import (
"errors"
"fmt"
"sync"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/klog"
)
// NewDeltaFIFO returns a Store which can be used process changes to items.
//
// keyFunc is used to figure out what key an object should have. (It's
// exposed in the returned DeltaFIFO's KeyOf() method, with bonus features.)
//
// 'keyLister' is expected to return a list of keys that the consumer of
// this queue "knows about". It is used to decide which items are missing
// when Replace() is called; 'Deleted' deltas are produced for these items.
// It may be nil if you don't need to detect all deletions.
// TODO: consider merging keyLister with this object, tracking a list of
// "known" keys when Pop() is called. Have to think about how that
// affects error retrying.
// NOTE: It is possible to misuse this and cause a race when using an
// external known object source.
// Whether there is a potential race depends on how the comsumer
// modifies knownObjects. In Pop(), process function is called under
// lock, so it is safe to update data structures in it that need to be
// in sync with the queue (e.g. knownObjects).
//
// Example:
// In case of sharedIndexInformer being a consumer
// (https://github.com/kubernetes/kubernetes/blob/0cdd940f/staging/
// src/k8s.io/client-go/tools/cache/shared_informer.go#L192),
// there is no race as knownObjects (s.indexer) is modified safely
// under DeltaFIFO's lock. The only exceptions are GetStore() and
// GetIndexer() methods, which expose ways to modify the underlying
// storage. Currently these two methods are used for creating Lister
// and internal tests.
//
// Also see the comment on DeltaFIFO.
func NewDeltaFIFO(keyFunc KeyFunc, knownObjects KeyListerGetter) *DeltaFIFO {
f := &DeltaFIFO{
items: map[string]Deltas{},
queue: []string{},
keyFunc: keyFunc,
knownObjects: knownObjects,
}
f.cond.L = &f.lock
return f
}
// DeltaFIFO is like FIFO, but allows you to process deletes.
//
// DeltaFIFO is a producer-consumer queue, where a Reflector is
// intended to be the producer, and the consumer is whatever calls
// the Pop() method.
//
// DeltaFIFO solves this use case:
// * You want to process every object change (delta) at most once.
// * When you process an object, you want to see everything
// that's happened to it since you last processed it.
// * You want to process the deletion of objects.
// * You might want to periodically reprocess objects.
//
// DeltaFIFO's Pop(), Get(), and GetByKey() methods return
// interface{} to satisfy the Store/Queue interfaces, but it
// will always return an object of type Deltas.
//
// A note on threading: If you call Pop() in parallel from multiple
// threads, you could end up with multiple threads processing slightly
// different versions of the same object.
//
// A note on the KeyLister used by the DeltaFIFO: It's main purpose is
// to list keys that are "known", for the purpose of figuring out which
// items have been deleted when Replace() or Delete() are called. The deleted
// object will be included in the DeleteFinalStateUnknown markers. These objects
// could be stale.
type DeltaFIFO struct {
// lock/cond protects access to 'items' and 'queue'.
lock sync.RWMutex
cond sync.Cond
// We depend on the property that items in the set are in
// the queue and vice versa, and that all Deltas in this
// map have at least one Delta.
items map[string]Deltas
queue []string
// populated is true if the first batch of items inserted by Replace() has been populated
// or Delete/Add/Update was called first.
populated bool
// initialPopulationCount is the number of items inserted by the first call of Replace()
initialPopulationCount int
// keyFunc is used to make the key used for queued item
// insertion and retrieval, and should be deterministic.
keyFunc KeyFunc
// knownObjects list keys that are "known", for the
// purpose of figuring out which items have been deleted
// when Replace() or Delete() is called.
knownObjects KeyListerGetter
// Indication the queue is closed.
// Used to indicate a queue is closed so a control loop can exit when a queue is empty.
// Currently, not used to gate any of CRED operations.
closed bool
closedLock sync.Mutex
}
var (
_ = Queue(&DeltaFIFO{}) // DeltaFIFO is a Queue
)
var (
// ErrZeroLengthDeltasObject is returned in a KeyError if a Deltas
// object with zero length is encountered (should be impossible,
// but included for completeness).
ErrZeroLengthDeltasObject = errors.New("0 length Deltas object; can't get key")
)
// Close the queue.
func (f *DeltaFIFO) Close() {
f.closedLock.Lock()
defer f.closedLock.Unlock()
f.closed = true
f.cond.Broadcast()
}
// KeyOf exposes f's keyFunc, but also detects the key of a Deltas object or
// DeletedFinalStateUnknown objects.
func (f *DeltaFIFO) KeyOf(obj interface{}) (string, error) {
if d, ok := obj.(Deltas); ok {
if len(d) == 0 {
return "", KeyError{obj, ErrZeroLengthDeltasObject}
}
obj = d.Newest().Object
}
if d, ok := obj.(DeletedFinalStateUnknown); ok {
return d.Key, nil
}
return f.keyFunc(obj)
}
// Return true if an Add/Update/Delete/AddIfNotPresent are called first,
// or an Update called first but the first batch of items inserted by Replace() has been popped
func (f *DeltaFIFO) HasSynced() bool {
f.lock.Lock()
defer f.lock.Unlock()
return f.populated && f.initialPopulationCount == 0
}
// Add inserts an item, and puts it in the queue. The item is only enqueued
// if it doesn't already exist in the set.
func (f *DeltaFIFO) Add(obj interface{}) error {
f.lock.Lock()
defer f.lock.Unlock()
f.populated = true
return f.queueActionLocked(Added, obj)
}
// Update is just like Add, but makes an Updated Delta.
func (f *DeltaFIFO) Update(obj interface{}) error {
f.lock.Lock()
defer f.lock.Unlock()
f.populated = true
return f.queueActionLocked(Updated, obj)
}
// Delete is just like Add, but makes an Deleted Delta. If the item does not
// already exist, it will be ignored. (It may have already been deleted by a
// Replace (re-list), for example.
func (f *DeltaFIFO) Delete(obj interface{}) error {
id, err := f.KeyOf(obj)
if err != nil {
return KeyError{obj, err}
}
f.lock.Lock()
defer f.lock.Unlock()
f.populated = true
if f.knownObjects == nil {
if _, exists := f.items[id]; !exists {
// Presumably, this was deleted when a relist happened.
// Don't provide a second report of the same deletion.
return nil
}
} else {
// We only want to skip the "deletion" action if the object doesn't
// exist in knownObjects and it doesn't have corresponding item in items.
// Note that even if there is a "deletion" action in items, we can ignore it,
// because it will be deduped automatically in "queueActionLocked"
_, exists, err := f.knownObjects.GetByKey(id)
_, itemsExist := f.items[id]
if err == nil && !exists && !itemsExist {
// Presumably, this was deleted when a relist happened.
// Don't provide a second report of the same deletion.
return nil
}
}
return f.queueActionLocked(Deleted, obj)
}
// AddIfNotPresent inserts an item, and puts it in the queue. If the item is already
// present in the set, it is neither enqueued nor added to the set.
//
// This is useful in a single producer/consumer scenario so that the consumer can
// safely retry items without contending with the producer and potentially enqueueing
// stale items.
//
// Important: obj must be a Deltas (the output of the Pop() function). Yes, this is
// different from the Add/Update/Delete functions.
func (f *DeltaFIFO) AddIfNotPresent(obj interface{}) error {
deltas, ok := obj.(Deltas)
if !ok {
return fmt.Errorf("object must be of type deltas, but got: %#v", obj)
}
id, err := f.KeyOf(deltas.Newest().Object)
if err != nil {
return KeyError{obj, err}
}
f.lock.Lock()
defer f.lock.Unlock()
f.addIfNotPresent(id, deltas)
return nil
}
// addIfNotPresent inserts deltas under id if it does not exist, and assumes the caller
// already holds the fifo lock.
func (f *DeltaFIFO) addIfNotPresent(id string, deltas Deltas) {
f.populated = true
if _, exists := f.items[id]; exists {
return
}
f.queue = append(f.queue, id)
f.items[id] = deltas
f.cond.Broadcast()
}
// re-listing and watching can deliver the same update multiple times in any
// order. This will combine the most recent two deltas if they are the same.
func dedupDeltas(deltas Deltas) Deltas {
n := len(deltas)
if n < 2 {
return deltas
}
a := &deltas[n-1]
b := &deltas[n-2]
if out := isDup(a, b); out != nil {
d := append(Deltas{}, deltas[:n-2]...)
return append(d, *out)
}
return deltas
}
// If a & b represent the same event, returns the delta that ought to be kept.
// Otherwise, returns nil.
// TODO: is there anything other than deletions that need deduping?
func isDup(a, b *Delta) *Delta {
if out := isDeletionDup(a, b); out != nil {
return out
}
// TODO: Detect other duplicate situations? Are there any?
return nil
}
// keep the one with the most information if both are deletions.
func isDeletionDup(a, b *Delta) *Delta {
if b.Type != Deleted || a.Type != Deleted {
return nil
}
// Do more sophisticated checks, or is this sufficient?
if _, ok := b.Object.(DeletedFinalStateUnknown); ok {
return a
}
return b
}
// willObjectBeDeletedLocked returns true only if the last delta for the
// given object is Delete. Caller must lock first.
func (f *DeltaFIFO) willObjectBeDeletedLocked(id string) bool {
deltas := f.items[id]
return len(deltas) > 0 && deltas[len(deltas)-1].Type == Deleted
}
// queueActionLocked appends to the delta list for the object.
// Caller must lock first.
func (f *DeltaFIFO) queueActionLocked(actionType DeltaType, obj interface{}) error {
id, err := f.KeyOf(obj)
if err != nil {
return KeyError{obj, err}
}
// If object is supposed to be deleted (last event is Deleted),
// then we should ignore Sync events, because it would result in
// recreation of this object.
if actionType == Sync && f.willObjectBeDeletedLocked(id) {
return nil
}
newDeltas := append(f.items[id], Delta{actionType, obj})
newDeltas = dedupDeltas(newDeltas)
if len(newDeltas) > 0 {
if _, exists := f.items[id]; !exists {
f.queue = append(f.queue, id)
}
f.items[id] = newDeltas
f.cond.Broadcast()
} else {
// We need to remove this from our map (extra items in the queue are
// ignored if they are not in the map).
delete(f.items, id)
}
return nil
}
// List returns a list of all the items; it returns the object
// from the most recent Delta.
// You should treat the items returned inside the deltas as immutable.
func (f *DeltaFIFO) List() []interface{} {
f.lock.RLock()
defer f.lock.RUnlock()
return f.listLocked()
}
func (f *DeltaFIFO) listLocked() []interface{} {
list := make([]interface{}, 0, len(f.items))
for _, item := range f.items {
list = append(list, item.Newest().Object)
}
return list
}
// ListKeys returns a list of all the keys of the objects currently
// in the FIFO.
func (f *DeltaFIFO) ListKeys() []string {
f.lock.RLock()
defer f.lock.RUnlock()
list := make([]string, 0, len(f.items))
for key := range f.items {
list = append(list, key)
}
return list
}
// Get returns the complete list of deltas for the requested item,
// or sets exists=false.
// You should treat the items returned inside the deltas as immutable.
func (f *DeltaFIFO) Get(obj interface{}) (item interface{}, exists bool, err error) {
key, err := f.KeyOf(obj)
if err != nil {
return nil, false, KeyError{obj, err}
}
return f.GetByKey(key)
}
// GetByKey returns the complete list of deltas for the requested item,
// setting exists=false if that list is empty.
// You should treat the items returned inside the deltas as immutable.
func (f *DeltaFIFO) GetByKey(key string) (item interface{}, exists bool, err error) {
f.lock.RLock()
defer f.lock.RUnlock()
d, exists := f.items[key]
if exists {
// Copy item's slice so operations on this slice
// won't interfere with the object we return.
d = copyDeltas(d)
}
return d, exists, nil
}
// Checks if the queue is closed
func (f *DeltaFIFO) IsClosed() bool {
f.closedLock.Lock()
defer f.closedLock.Unlock()
return f.closed
}
// Pop blocks until an item is added to the queue, and then returns it. If
// multiple items are ready, they are returned in the order in which they were
// added/updated. The item is removed from the queue (and the store) before it
// is returned, so if you don't successfully process it, you need to add it back
// with AddIfNotPresent().
// process function is called under lock, so it is safe update data structures
// in it that need to be in sync with the queue (e.g. knownKeys). The PopProcessFunc
// may return an instance of ErrRequeue with a nested error to indicate the current
// item should be requeued (equivalent to calling AddIfNotPresent under the lock).
//
// Pop returns a 'Deltas', which has a complete list of all the things
// that happened to the object (deltas) while it was sitting in the queue.
func (f *DeltaFIFO) Pop(process PopProcessFunc) (interface{}, error) {
f.lock.Lock()
defer f.lock.Unlock()
for {
for len(f.queue) == 0 {
// When the queue is empty, invocation of Pop() is blocked until new item is enqueued.
// When Close() is called, the f.closed is set and the condition is broadcasted.
// Which causes this loop to continue and return from the Pop().
if f.IsClosed() {
return nil, FIFOClosedError
}
f.cond.Wait()
}
id := f.queue[0]
f.queue = f.queue[1:]
if f.initialPopulationCount > 0 {
f.initialPopulationCount--
}
item, ok := f.items[id]
if !ok {
// Item may have been deleted subsequently.
continue
}
delete(f.items, id)
err := process(item)
if e, ok := err.(ErrRequeue); ok {
f.addIfNotPresent(id, item)
err = e.Err
}
// Don't need to copyDeltas here, because we're transferring
// ownership to the caller.
return item, err
}
}
// Replace will delete the contents of 'f', using instead the given map.
// 'f' takes ownership of the map, you should not reference the map again
// after calling this function. f's queue is reset, too; upon return, it
// will contain the items in the map, in no particular order.
func (f *DeltaFIFO) Replace(list []interface{}, resourceVersion string) error {
f.lock.Lock()
defer f.lock.Unlock()
keys := make(sets.String, len(list))
for _, item := range list {
key, err := f.KeyOf(item)
if err != nil {
return KeyError{item, err}
}
keys.Insert(key)
if err := f.queueActionLocked(Sync, item); err != nil {
return fmt.Errorf("couldn't enqueue object: %v", err)
}
}
if f.knownObjects == nil {
// Do deletion detection against our own list.
queuedDeletions := 0
for k, oldItem := range f.items {
if keys.Has(k) {
continue
}
var deletedObj interface{}
if n := oldItem.Newest(); n != nil {
deletedObj = n.Object
}
queuedDeletions++
if err := f.queueActionLocked(Deleted, DeletedFinalStateUnknown{k, deletedObj}); err != nil {
return err
}
}
if !f.populated {
f.populated = true
// While there shouldn't be any queued deletions in the initial
// population of the queue, it's better to be on the safe side.
f.initialPopulationCount = len(list) + queuedDeletions
}
return nil
}
// Detect deletions not already in the queue.
knownKeys := f.knownObjects.ListKeys()
queuedDeletions := 0
for _, k := range knownKeys {
if keys.Has(k) {
continue
}
deletedObj, exists, err := f.knownObjects.GetByKey(k)
if err != nil {
deletedObj = nil
klog.Errorf("Unexpected error %v during lookup of key %v, placing DeleteFinalStateUnknown marker without object", err, k)
} else if !exists {
deletedObj = nil
klog.Infof("Key %v does not exist in known objects store, placing DeleteFinalStateUnknown marker without object", k)
}
queuedDeletions++
if err := f.queueActionLocked(Deleted, DeletedFinalStateUnknown{k, deletedObj}); err != nil {
return err
}
}
if !f.populated {
f.populated = true
f.initialPopulationCount = len(list) + queuedDeletions
}
return nil
}
// Resync will send a sync event for each item
func (f *DeltaFIFO) Resync() error {
f.lock.Lock()
defer f.lock.Unlock()
if f.knownObjects == nil {
return nil
}
keys := f.knownObjects.ListKeys()
for _, k := range keys {
if err := f.syncKeyLocked(k); err != nil {
return err
}
}
return nil
}
func (f *DeltaFIFO) syncKey(key string) error {
f.lock.Lock()
defer f.lock.Unlock()
return f.syncKeyLocked(key)
}
func (f *DeltaFIFO) syncKeyLocked(key string) error {
obj, exists, err := f.knownObjects.GetByKey(key)
if err != nil {
klog.Errorf("Unexpected error %v during lookup of key %v, unable to queue object for sync", err, key)
return nil
} else if !exists {
klog.Infof("Key %v does not exist in known objects store, unable to queue object for sync", key)
return nil
}
// If we are doing Resync() and there is already an event queued for that object,
// we ignore the Resync for it. This is to avoid the race, in which the resync
// comes with the previous value of object (since queueing an event for the object
// doesn't trigger changing the underlying store <knownObjects>.
id, err := f.KeyOf(obj)
if err != nil {
return KeyError{obj, err}
}
if len(f.items[id]) > 0 {
return nil
}
if err := f.queueActionLocked(Sync, obj); err != nil {
return fmt.Errorf("couldn't queue object: %v", err)
}
return nil
}
// A KeyListerGetter is anything that knows how to list its keys and look up by key.
type KeyListerGetter interface {
KeyLister
KeyGetter
}
// A KeyLister is anything that knows how to list its keys.
type KeyLister interface {
ListKeys() []string
}
// A KeyGetter is anything that knows how to get the value stored under a given key.
type KeyGetter interface {
GetByKey(key string) (interface{}, bool, error)
}
// DeltaType is the type of a change (addition, deletion, etc)
type DeltaType string
const (
Added DeltaType = "Added"
Updated DeltaType = "Updated"
Deleted DeltaType = "Deleted"
// The other types are obvious. You'll get Sync deltas when:
// * A watch expires/errors out and a new list/watch cycle is started.
// * You've turned on periodic syncs.
// (Anything that trigger's DeltaFIFO's Replace() method.)
Sync DeltaType = "Sync"
)
// Delta is the type stored by a DeltaFIFO. It tells you what change
// happened, and the object's state after* that change.
//
// [*] Unless the change is a deletion, and then you'll get the final
// state of the object before it was deleted.
type Delta struct {
Type DeltaType
Object interface{}
}
// Deltas is a list of one or more 'Delta's to an individual object.
// The oldest delta is at index 0, the newest delta is the last one.
type Deltas []Delta
// Oldest is a convenience function that returns the oldest delta, or
// nil if there are no deltas.
func (d Deltas) Oldest() *Delta {
if len(d) > 0 {
return &d[0]
}
return nil
}
// Newest is a convenience function that returns the newest delta, or
// nil if there are no deltas.
func (d Deltas) Newest() *Delta {
if n := len(d); n > 0 {
return &d[n-1]
}
return nil
}
// copyDeltas returns a shallow copy of d; that is, it copies the slice but not
// the objects in the slice. This allows Get/List to return an object that we
// know won't be clobbered by a subsequent modifications.
func copyDeltas(d Deltas) Deltas {
d2 := make(Deltas, len(d))
copy(d2, d)
return d2
}
// DeletedFinalStateUnknown is placed into a DeltaFIFO in the case where
// an object was deleted but the watch deletion event was missed. In this
// case we don't know the final "resting" state of the object, so there's
// a chance the included `Obj` is stale.
type DeletedFinalStateUnknown struct {
Key string
Obj interface{}
}
| {
"pile_set_name": "Github"
} |
#= require active_admin/base
| {
"pile_set_name": "Github"
} |
// Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE.md file in the project root for more information.
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.ProjectSystem;
using Microsoft.VisualStudio.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.SolutionRestoreManager;
using NuGet.VisualStudio;
[assembly: ProjectSystemContract(ProjectSystemContractScope.Global, ProjectSystemContractProvider.Private, Cardinality = ImportCardinality.ExactlyOne, ContractType = typeof(SVsServiceProvider))]
[assembly: ProjectSystemContract(ProjectSystemContractScope.Global, ProjectSystemContractProvider.Private, Cardinality = ImportCardinality.ExactlyOne, ContractType = typeof(SAsyncServiceProvider))]
[assembly: ProjectSystemContract(ProjectSystemContractScope.Global, ProjectSystemContractProvider.Private, Cardinality = ImportCardinality.ExactlyOne, ContractType = typeof(VisualStudioWorkspace))]
[assembly: ProjectSystemContract(ProjectSystemContractScope.Global, ProjectSystemContractProvider.Private, Cardinality = ImportCardinality.ExactlyOne, ContractType = typeof(ICodeModelFactory))]
[assembly: ProjectSystemContract(ProjectSystemContractScope.Global, ProjectSystemContractProvider.Private, Cardinality = ImportCardinality.ExactlyOne, ContractType = typeof(IVsSolutionRestoreService3))]
[assembly: ProjectSystemContract(ProjectSystemContractScope.Global, ProjectSystemContractProvider.Private, Cardinality = ImportCardinality.ExactlyOne, ContractType = typeof(IVsFrameworkParser))]
[assembly: ProjectSystemContract(ProjectSystemContractScope.Global, ProjectSystemContractProvider.Private, Cardinality = ImportCardinality.ExactlyOne, ContractType = typeof(IVsFrameworkCompatibility))]
| {
"pile_set_name": "Github"
} |
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{juggernaut}
s.version = "2.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = [%q{Alex MacCaw}]
s.date = %q{2012-01-03}
s.description = %q{Use Juggernaut to easily implement realtime chat, collaboration, gaming and much more!}
s.email = %q{[email protected]}
s.files = [
".document",
".gitignore",
"README",
"Rakefile",
"VERSION",
"examples/juggernaut_observer.js",
"examples/juggernaut_observer.rb",
"examples/roster.rb",
"juggernaut.gemspec",
"lib/juggernaut.rb",
"lib/juggernaut/rails/engine.rb",
"vendor/assets/javascripts/json.js",
"vendor/assets/javascripts/juggernaut.js",
"vendor/assets/javascripts/socket_io.js"
]
s.homepage = %q{http://github.com/maccman/juggernaut}
s.require_paths = [%q{lib}]
s.rubygems_version = %q{1.8.6}
s.summary = %q{Simple realtime push}
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<redis>, [">= 0"])
else
s.add_dependency(%q<redis>, [">= 0"])
end
else
s.add_dependency(%q<redis>, [">= 0"])
end
end
| {
"pile_set_name": "Github"
} |
import { Module } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { UserModule } from './user/user.module'
import { BackofficeModule } from './backoffice/backoffice.module'
@Module({
imports: [TypeOrmModule.forRoot(), UserModule, BackofficeModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
| {
"pile_set_name": "Github"
} |
#include <string>
#include <functional>
#include <iostream>
bool check_size(const std::string &s, std::string::size_type sz)
{
return s.size() >= sz;
}
std::ostream &print(std::ostream &os, const std::string &s, char c)
{
return os << s << c;
}
int main()
{
using namespace std::placeholders;
auto check6 = std::bind(check_size, _1, 6);
std::cout << check6("check") << std::endl;
std::cout << check6("check6") << std::endl;
std::bind(print, ref(std::cout), _1, ' ');
return 0;
}
| {
"pile_set_name": "Github"
} |
<?php
/*************************************************
Snoopy - the PHP net client
Author: Monte Ohrt <[email protected]>
Copyright (c): 1999-2000 ispi, all rights reserved
Version: 1.01
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
You may contact the author of Snoopy by e-mail at:
[email protected]
Or, write to:
Monte Ohrt
CTO, ispi
237 S. 70th suite 220
Lincoln, NE 68510
The latest version of Snoopy can be obtained from:
http://snoopy.sourceforge.net/
*************************************************/
class Snoopy
{
/**** Public variables ****/
/* user definable vars */
var $host = "www.php.net"; // host name we are connecting to
var $port = 80; // port we are connecting to
var $proxy_host = ""; // proxy host to use
var $proxy_port = ""; // proxy port to use
var $proxy_user = ""; // proxy user to use
var $proxy_pass = ""; // proxy password to use
var $agent = "Snoopy v1.2.3"; // agent we masquerade as
var $referer = ""; // referer info to pass
var $cookies = array(); // array of cookies to pass
// $cookies["username"]="joe";
var $rawheaders = array(); // array of raw headers to send
// $rawheaders["Content-type"]="text/html";
var $maxredirs = 5; // http redirection depth maximum. 0 = disallow
var $lastredirectaddr = ""; // contains address of last redirected address
var $offsiteok = true; // allows redirection off-site
var $maxframes = 0; // frame content depth maximum. 0 = disallow
var $expandlinks = true; // expand links to fully qualified URLs.
// this only applies to fetchlinks()
// submitlinks(), and submittext()
var $passcookies = true; // pass set cookies back through redirects
// NOTE: this currently does not respect
// dates, domains or paths.
var $user = ""; // user for http authentication
var $pass = ""; // password for http authentication
// http accept types
var $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*";
var $results = ""; // where the content is put
var $error = ""; // error messages sent here
var $response_code = ""; // response code returned from server
var $headers = array(); // headers returned from server sent here
var $maxlength = 500000; // max return data length (body)
var $read_timeout = 0; // timeout on read operations, in seconds
// supported only since PHP 4 Beta 4
// set to 0 to disallow timeouts
var $timed_out = false; // if a read operation timed out
var $status = 0; // http request status
var $temp_dir = "/tmp"; // temporary directory that the webserver
// has permission to write to.
// under Windows, this should be C:\temp
var $curl_path = "/usr/local/bin/curl";
// Snoopy will use cURL for fetching
// SSL content if a full system path to
// the cURL binary is supplied here.
// set to false if you do not have
// cURL installed. See http://curl.haxx.se
// for details on installing cURL.
// Snoopy does *not* use the cURL
// library functions built into php,
// as these functions are not stable
// as of this Snoopy release.
/**** Private variables ****/
var $_maxlinelen = 4096; // max line length (headers)
var $_httpmethod = "GET"; // default http request method
var $_httpversion = "HTTP/1.0"; // default http request version
var $_submit_method = "POST"; // default submit method
var $_submit_type = "application/x-www-form-urlencoded"; // default submit type
var $_mime_boundary = ""; // MIME boundary for multipart/form-data submit type
var $_redirectaddr = false; // will be set if page fetched is a redirect
var $_redirectdepth = 0; // increments on an http redirect
var $_frameurls = array(); // frame src urls
var $_framedepth = 0; // increments on frame depth
var $_isproxy = false; // set if using a proxy server
var $_fp_timeout = 30; // timeout for socket connection
/*======================================================================*\
Function: fetch
Purpose: fetch the contents of a web page
(and possibly other protocols in the
future like ftp, nntp, gopher, etc.)
Input: $URI the location of the page to fetch
Output: $this->results the output text from the fetch
\*======================================================================*/
function fetch($URI)
{
//preg_match("|^([^:]+)://([^:/]+)(:[\d]+)*(.*)|",$URI,$URI_PARTS);
$URI_PARTS = parse_url($URI);
if (!empty($URI_PARTS["user"]))
$this->user = $URI_PARTS["user"];
if (!empty($URI_PARTS["pass"]))
$this->pass = $URI_PARTS["pass"];
if (empty($URI_PARTS["query"]))
$URI_PARTS["query"] = '';
if (empty($URI_PARTS["path"]))
$URI_PARTS["path"] = '';
switch(strtolower($URI_PARTS["scheme"]))
{
case "http":
$this->host = $URI_PARTS["host"];
if(!empty($URI_PARTS["port"]))
$this->port = $URI_PARTS["port"];
if($this->_connect($fp))
{
if($this->_isproxy)
{
// using proxy, send entire URI
$this->_httprequest($URI,$fp,$URI,$this->_httpmethod);
}
else
{
$path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : "");
// no proxy, send only the path
$this->_httprequest($path, $fp, $URI, $this->_httpmethod);
}
$this->_disconnect($fp);
if($this->_redirectaddr)
{
/* url was redirected, check if we've hit the max depth */
if($this->maxredirs > $this->_redirectdepth)
{
// only follow redirect if it's on this site, or offsiteok is true
if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok)
{
/* follow the redirect */
$this->_redirectdepth++;
$this->lastredirectaddr=$this->_redirectaddr;
$this->fetch($this->_redirectaddr);
}
}
}
if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0)
{
$frameurls = $this->_frameurls;
$this->_frameurls = array();
while(list(,$frameurl) = each($frameurls))
{
if($this->_framedepth < $this->maxframes)
{
$this->fetch($frameurl);
$this->_framedepth++;
}
else
break;
}
}
}
else
{
return false;
}
return true;
break;
case "https":
if(!$this->curl_path)
return false;
if(function_exists("is_executable"))
if (!is_executable($this->curl_path))
return false;
$this->host = $URI_PARTS["host"];
if(!empty($URI_PARTS["port"]))
$this->port = $URI_PARTS["port"];
if($this->_isproxy)
{
// using proxy, send entire URI
$this->_httpsrequest($URI,$URI,$this->_httpmethod);
}
else
{
$path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : "");
// no proxy, send only the path
$this->_httpsrequest($path, $URI, $this->_httpmethod);
}
if($this->_redirectaddr)
{
/* url was redirected, check if we've hit the max depth */
if($this->maxredirs > $this->_redirectdepth)
{
// only follow redirect if it's on this site, or offsiteok is true
if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok)
{
/* follow the redirect */
$this->_redirectdepth++;
$this->lastredirectaddr=$this->_redirectaddr;
$this->fetch($this->_redirectaddr);
}
}
}
if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0)
{
$frameurls = $this->_frameurls;
$this->_frameurls = array();
while(list(,$frameurl) = each($frameurls))
{
if($this->_framedepth < $this->maxframes)
{
$this->fetch($frameurl);
$this->_framedepth++;
}
else
break;
}
}
return true;
break;
default:
// not a valid protocol
$this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n';
return false;
break;
}
return true;
}
/*======================================================================*\
Function: submit
Purpose: submit an http form
Input: $URI the location to post the data
$formvars the formvars to use.
format: $formvars["var"] = "val";
$formfiles an array of files to submit
format: $formfiles["var"] = "/dir/filename.ext";
Output: $this->results the text output from the post
\*======================================================================*/
function submit($URI, $formvars="", $formfiles="")
{
unset($postdata);
$postdata = $this->_prepare_post_body($formvars, $formfiles);
$URI_PARTS = parse_url($URI);
if (!empty($URI_PARTS["user"]))
$this->user = $URI_PARTS["user"];
if (!empty($URI_PARTS["pass"]))
$this->pass = $URI_PARTS["pass"];
if (empty($URI_PARTS["query"]))
$URI_PARTS["query"] = '';
if (empty($URI_PARTS["path"]))
$URI_PARTS["path"] = '';
switch(strtolower($URI_PARTS["scheme"]))
{
case "http":
$this->host = $URI_PARTS["host"];
if(!empty($URI_PARTS["port"]))
$this->port = $URI_PARTS["port"];
if($this->_connect($fp))
{
if($this->_isproxy)
{
// using proxy, send entire URI
$this->_httprequest($URI,$fp,$URI,$this->_submit_method,$this->_submit_type,$postdata);
}
else
{
$path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : "");
// no proxy, send only the path
$this->_httprequest($path, $fp, $URI, $this->_submit_method, $this->_submit_type, $postdata);
}
$this->_disconnect($fp);
if($this->_redirectaddr)
{
/* url was redirected, check if we've hit the max depth */
if($this->maxredirs > $this->_redirectdepth)
{
if(!preg_match("|^".$URI_PARTS["scheme"]."://|", $this->_redirectaddr))
$this->_redirectaddr = $this->_expandlinks($this->_redirectaddr,$URI_PARTS["scheme"]."://".$URI_PARTS["host"]);
// only follow redirect if it's on this site, or offsiteok is true
if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok)
{
/* follow the redirect */
$this->_redirectdepth++;
$this->lastredirectaddr=$this->_redirectaddr;
if( strpos( $this->_redirectaddr, "?" ) > 0 )
$this->fetch($this->_redirectaddr); // the redirect has changed the request method from post to get
else
$this->submit($this->_redirectaddr,$formvars, $formfiles);
}
}
}
if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0)
{
$frameurls = $this->_frameurls;
$this->_frameurls = array();
while(list(,$frameurl) = each($frameurls))
{
if($this->_framedepth < $this->maxframes)
{
$this->fetch($frameurl);
$this->_framedepth++;
}
else
break;
}
}
}
else
{
return false;
}
return true;
break;
case "https":
if(!$this->curl_path)
return false;
if(function_exists("is_executable"))
if (!is_executable($this->curl_path))
return false;
$this->host = $URI_PARTS["host"];
if(!empty($URI_PARTS["port"]))
$this->port = $URI_PARTS["port"];
if($this->_isproxy)
{
// using proxy, send entire URI
$this->_httpsrequest($URI, $URI, $this->_submit_method, $this->_submit_type, $postdata);
}
else
{
$path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : "");
// no proxy, send only the path
$this->_httpsrequest($path, $URI, $this->_submit_method, $this->_submit_type, $postdata);
}
if($this->_redirectaddr)
{
/* url was redirected, check if we've hit the max depth */
if($this->maxredirs > $this->_redirectdepth)
{
if(!preg_match("|^".$URI_PARTS["scheme"]."://|", $this->_redirectaddr))
$this->_redirectaddr = $this->_expandlinks($this->_redirectaddr,$URI_PARTS["scheme"]."://".$URI_PARTS["host"]);
// only follow redirect if it's on this site, or offsiteok is true
if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok)
{
/* follow the redirect */
$this->_redirectdepth++;
$this->lastredirectaddr=$this->_redirectaddr;
if( strpos( $this->_redirectaddr, "?" ) > 0 )
$this->fetch($this->_redirectaddr); // the redirect has changed the request method from post to get
else
$this->submit($this->_redirectaddr,$formvars, $formfiles);
}
}
}
if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0)
{
$frameurls = $this->_frameurls;
$this->_frameurls = array();
while(list(,$frameurl) = each($frameurls))
{
if($this->_framedepth < $this->maxframes)
{
$this->fetch($frameurl);
$this->_framedepth++;
}
else
break;
}
}
return true;
break;
default:
// not a valid protocol
$this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n';
return false;
break;
}
return true;
}
/*======================================================================*\
Function: fetchlinks
Purpose: fetch the links from a web page
Input: $URI where you are fetching from
Output: $this->results an array of the URLs
\*======================================================================*/
function fetchlinks($URI)
{
if ($this->fetch($URI))
{
if($this->lastredirectaddr)
$URI = $this->lastredirectaddr;
if(is_array($this->results))
{
for($x=0;$x<count($this->results);$x++)
$this->results[$x] = $this->_striplinks($this->results[$x]);
}
else
$this->results = $this->_striplinks($this->results);
if($this->expandlinks)
$this->results = $this->_expandlinks($this->results, $URI);
return true;
}
else
return false;
}
/*======================================================================*\
Function: fetchform
Purpose: fetch the form elements from a web page
Input: $URI where you are fetching from
Output: $this->results the resulting html form
\*======================================================================*/
function fetchform($URI)
{
if ($this->fetch($URI))
{
if(is_array($this->results))
{
for($x=0;$x<count($this->results);$x++)
$this->results[$x] = $this->_stripform($this->results[$x]);
}
else
$this->results = $this->_stripform($this->results);
return true;
}
else
return false;
}
/*======================================================================*\
Function: fetchtext
Purpose: fetch the text from a web page, stripping the links
Input: $URI where you are fetching from
Output: $this->results the text from the web page
\*======================================================================*/
function fetchtext($URI)
{
if($this->fetch($URI))
{
if(is_array($this->results))
{
for($x=0;$x<count($this->results);$x++)
$this->results[$x] = $this->_striptext($this->results[$x]);
}
else
$this->results = $this->_striptext($this->results);
return true;
}
else
return false;
}
/*======================================================================*\
Function: submitlinks
Purpose: grab links from a form submission
Input: $URI where you are submitting from
Output: $this->results an array of the links from the post
\*======================================================================*/
function submitlinks($URI, $formvars="", $formfiles="")
{
if($this->submit($URI,$formvars, $formfiles))
{
if($this->lastredirectaddr)
$URI = $this->lastredirectaddr;
if(is_array($this->results))
{
for($x=0;$x<count($this->results);$x++)
{
$this->results[$x] = $this->_striplinks($this->results[$x]);
if($this->expandlinks)
$this->results[$x] = $this->_expandlinks($this->results[$x],$URI);
}
}
else
{
$this->results = $this->_striplinks($this->results);
if($this->expandlinks)
$this->results = $this->_expandlinks($this->results,$URI);
}
return true;
}
else
return false;
}
/*======================================================================*\
Function: submittext
Purpose: grab text from a form submission
Input: $URI where you are submitting from
Output: $this->results the text from the web page
\*======================================================================*/
function submittext($URI, $formvars = "", $formfiles = "")
{
if($this->submit($URI,$formvars, $formfiles))
{
if($this->lastredirectaddr)
$URI = $this->lastredirectaddr;
if(is_array($this->results))
{
for($x=0;$x<count($this->results);$x++)
{
$this->results[$x] = $this->_striptext($this->results[$x]);
if($this->expandlinks)
$this->results[$x] = $this->_expandlinks($this->results[$x],$URI);
}
}
else
{
$this->results = $this->_striptext($this->results);
if($this->expandlinks)
$this->results = $this->_expandlinks($this->results,$URI);
}
return true;
}
else
return false;
}
/*======================================================================*\
Function: set_submit_multipart
Purpose: Set the form submission content type to
multipart/form-data
\*======================================================================*/
function set_submit_multipart()
{
$this->_submit_type = "multipart/form-data";
}
/*======================================================================*\
Function: set_submit_normal
Purpose: Set the form submission content type to
application/x-www-form-urlencoded
\*======================================================================*/
function set_submit_normal()
{
$this->_submit_type = "application/x-www-form-urlencoded";
}
/*======================================================================*\
Private functions
\*======================================================================*/
/*======================================================================*\
Function: _striplinks
Purpose: strip the hyperlinks from an html document
Input: $document document to strip.
Output: $match an array of the links
\*======================================================================*/
function _striplinks($document)
{
preg_match_all("'<\s*a\s.*?href\s*=\s* # find <a href=
([\"\'])? # find single or double quote
(?(1) (.*?)\\1 | ([^\s\>]+)) # if quote found, match up to next matching
# quote, otherwise match up to next space
'isx",$document,$links);
// catenate the non-empty matches from the conditional subpattern
while(list($key,$val) = each($links[2]))
{
if(!empty($val))
$match[] = $val;
}
while(list($key,$val) = each($links[3]))
{
if(!empty($val))
$match[] = $val;
}
// return the links
return $match;
}
/*======================================================================*\
Function: _stripform
Purpose: strip the form elements from an html document
Input: $document document to strip.
Output: $match an array of the links
\*======================================================================*/
function _stripform($document)
{
preg_match_all("'<\/?(FORM|INPUT|SELECT|TEXTAREA|(OPTION))[^<>]*>(?(2)(.*(?=<\/?(option|select)[^<>]*>[\r\n]*)|(?=[\r\n]*))|(?=[\r\n]*))'Usi",$document,$elements);
// catenate the matches
$match = implode("\r\n",$elements[0]);
// return the links
return $match;
}
/*======================================================================*\
Function: _striptext
Purpose: strip the text from an html document
Input: $document document to strip.
Output: $text the resulting text
\*======================================================================*/
function _striptext($document)
{
// I didn't use preg eval (//e) since that is only available in PHP 4.0.
// so, list your entities one by one here. I included some of the
// more common ones.
$search = array("'<script[^>]*?>.*?</script>'si", // strip out javascript
"'<[\/\!]*?[^<>]*?>'si", // strip out html tags
"'([\r\n])[\s]+'", // strip out white space
"'&(quot|#34|#034|#x22);'i", // replace html entities
"'&(amp|#38|#038|#x26);'i", // added hexadecimal values
"'&(lt|#60|#060|#x3c);'i",
"'&(gt|#62|#062|#x3e);'i",
"'&(nbsp|#160|#xa0);'i",
"'&(iexcl|#161);'i",
"'&(cent|#162);'i",
"'&(pound|#163);'i",
"'&(copy|#169);'i",
"'&(reg|#174);'i",
"'&(deg|#176);'i",
"'&(#39|#039|#x27);'",
"'&(euro|#8364);'i", // europe
"'&a(uml|UML);'", // german
"'&o(uml|UML);'",
"'&u(uml|UML);'",
"'&A(uml|UML);'",
"'&O(uml|UML);'",
"'&U(uml|UML);'",
"'ß'i",
);
$replace = array( "",
"",
"\\1",
"\"",
"&",
"<",
">",
" ",
chr(161),
chr(162),
chr(163),
chr(169),
chr(174),
chr(176),
chr(39),
chr(128),
"ä",
"ö",
"ü",
"Ä",
"Ö",
"Ü",
"ß",
);
$text = preg_replace($search,$replace,$document);
return $text;
}
/*======================================================================*\
Function: _expandlinks
Purpose: expand each link into a fully qualified URL
Input: $links the links to qualify
$URI the full URI to get the base from
Output: $expandedLinks the expanded links
\*======================================================================*/
function _expandlinks($links,$URI)
{
preg_match("/^[^\?]+/",$URI,$match);
$match = preg_replace("|/[^\/\.]+\.[^\/\.]+$|","",$match[0]);
$match = preg_replace("|/$|","",$match);
$match_part = parse_url($match);
$match_root =
$match_part["scheme"]."://".$match_part["host"];
$search = array( "|^http://".preg_quote($this->host)."|i",
"|^(\/)|i",
"|^(?!http://)(?!mailto:)|i",
"|/\./|",
"|/[^\/]+/\.\./|"
);
$replace = array( "",
$match_root."/",
$match."/",
"/",
"/"
);
$expandedLinks = preg_replace($search,$replace,$links);
return $expandedLinks;
}
/*======================================================================*\
Function: _httprequest
Purpose: go get the http data from the server
Input: $url the url to fetch
$fp the current open file pointer
$URI the full URI
$body body contents to send if any (POST)
Output:
\*======================================================================*/
function _httprequest($url,$fp,$URI,$http_method,$content_type="",$body="")
{
$cookie_headers = '';
if($this->passcookies && $this->_redirectaddr)
$this->setcookies();
$URI_PARTS = parse_url($URI);
if(empty($url))
$url = "/";
$headers = $http_method." ".$url." ".$this->_httpversion."\r\n";
if(!empty($this->agent))
$headers .= "User-Agent: ".$this->agent."\r\n";
if(!empty($this->host) && !isset($this->rawheaders['Host'])) {
$headers .= "Host: ".$this->host;
if(!empty($this->port))
$headers .= ":".$this->port;
$headers .= "\r\n";
}
if(!empty($this->accept))
$headers .= "Accept: ".$this->accept."\r\n";
if(!empty($this->referer))
$headers .= "Referer: ".$this->referer."\r\n";
if(!empty($this->cookies))
{
if(!is_array($this->cookies))
$this->cookies = (array)$this->cookies;
reset($this->cookies);
if ( count($this->cookies) > 0 ) {
$cookie_headers .= 'Cookie: ';
foreach ( $this->cookies as $cookieKey => $cookieVal ) {
$cookie_headers .= $cookieKey."=".urlencode($cookieVal)."; ";
}
$headers .= substr($cookie_headers,0,-2) . "\r\n";
}
}
if(!empty($this->rawheaders))
{
if(!is_array($this->rawheaders))
$this->rawheaders = (array)$this->rawheaders;
while(list($headerKey,$headerVal) = each($this->rawheaders))
$headers .= $headerKey.": ".$headerVal."\r\n";
}
if(!empty($content_type)) {
$headers .= "Content-type: $content_type";
if ($content_type == "multipart/form-data")
$headers .= "; boundary=".$this->_mime_boundary;
$headers .= "\r\n";
}
if(!empty($body))
$headers .= "Content-length: ".strlen($body)."\r\n";
if(!empty($this->user) || !empty($this->pass))
$headers .= "Authorization: Basic ".base64_encode($this->user.":".$this->pass)."\r\n";
//add proxy auth headers
if(!empty($this->proxy_user))
$headers .= 'Proxy-Authorization: ' . 'Basic ' . base64_encode($this->proxy_user . ':' . $this->proxy_pass)."\r\n";
$headers .= "\r\n";
// set the read timeout if needed
if ($this->read_timeout > 0)
socket_set_timeout($fp, $this->read_timeout);
$this->timed_out = false;
fwrite($fp,$headers.$body,strlen($headers.$body));
$this->_redirectaddr = false;
unset($this->headers);
while($currentHeader = fgets($fp,$this->_maxlinelen))
{
if ($this->read_timeout > 0 && $this->_check_timeout($fp))
{
$this->status=-100;
return false;
}
if($currentHeader == "\r\n")
break;
// if a header begins with Location: or URI:, set the redirect
if(preg_match("/^(Location:|URI:)/i",$currentHeader))
{
// get URL portion of the redirect
preg_match("/^(Location:|URI:)[ ]+(.*)/i",chop($currentHeader),$matches);
// look for :// in the Location header to see if hostname is included
if(!preg_match("|\:\/\/|",$matches[2]))
{
// no host in the path, so prepend
$this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port;
// eliminate double slash
if(!preg_match("|^/|",$matches[2]))
$this->_redirectaddr .= "/".$matches[2];
else
$this->_redirectaddr .= $matches[2];
}
else
$this->_redirectaddr = $matches[2];
}
if(preg_match("|^HTTP/|",$currentHeader))
{
if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$currentHeader, $status))
{
$this->status= $status[1];
}
$this->response_code = $currentHeader;
}
$this->headers[] = $currentHeader;
}
$results = '';
do {
$_data = fread($fp, $this->maxlength);
if (strlen($_data) == 0) {
break;
}
$results .= $_data;
} while(true);
if ($this->read_timeout > 0 && $this->_check_timeout($fp))
{
$this->status=-100;
return false;
}
// check if there is a a redirect meta tag
if(preg_match("'<meta[\s]*http-equiv[^>]*?content[\s]*=[\s]*[\"\']?\d+;[\s]*URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match))
{
$this->_redirectaddr = $this->_expandlinks($match[1],$URI);
}
// have we hit our frame depth and is there frame src to fetch?
if(($this->_framedepth < $this->maxframes) && preg_match_all("'<frame\s+.*src[\s]*=[\'\"]?([^\'\"\>]+)'i",$results,$match))
{
$this->results[] = $results;
for($x=0; $x<count($match[1]); $x++)
$this->_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host);
}
// have we already fetched framed content?
elseif(is_array($this->results))
$this->results[] = $results;
// no framed content
else
$this->results = $results;
return true;
}
/*======================================================================*\
Function: _httpsrequest
Purpose: go get the https data from the server using curl
Input: $url the url to fetch
$URI the full URI
$body body contents to send if any (POST)
Output:
\*======================================================================*/
function _httpsrequest($url,$URI,$http_method,$content_type="",$body="")
{
if($this->passcookies && $this->_redirectaddr)
$this->setcookies();
$headers = array();
$URI_PARTS = parse_url($URI);
if(empty($url))
$url = "/";
// GET ... header not needed for curl
//$headers[] = $http_method." ".$url." ".$this->_httpversion;
if(!empty($this->agent))
$headers[] = "User-Agent: ".$this->agent;
if(!empty($this->host))
if(!empty($this->port))
$headers[] = "Host: ".$this->host.":".$this->port;
else
$headers[] = "Host: ".$this->host;
if(!empty($this->accept))
$headers[] = "Accept: ".$this->accept;
if(!empty($this->referer))
$headers[] = "Referer: ".$this->referer;
if(!empty($this->cookies))
{
if(!is_array($this->cookies))
$this->cookies = (array)$this->cookies;
reset($this->cookies);
if ( count($this->cookies) > 0 ) {
$cookie_str = 'Cookie: ';
foreach ( $this->cookies as $cookieKey => $cookieVal ) {
$cookie_str .= $cookieKey."=".urlencode($cookieVal)."; ";
}
$headers[] = substr($cookie_str,0,-2);
}
}
if(!empty($this->rawheaders))
{
if(!is_array($this->rawheaders))
$this->rawheaders = (array)$this->rawheaders;
while(list($headerKey,$headerVal) = each($this->rawheaders))
$headers[] = $headerKey.": ".$headerVal;
}
if(!empty($content_type)) {
if ($content_type == "multipart/form-data")
$headers[] = "Content-type: $content_type; boundary=".$this->_mime_boundary;
else
$headers[] = "Content-type: $content_type";
}
if(!empty($body))
$headers[] = "Content-length: ".strlen($body);
if(!empty($this->user) || !empty($this->pass))
$headers[] = "Authorization: BASIC ".base64_encode($this->user.":".$this->pass);
for($curr_header = 0; $curr_header < count($headers); $curr_header++) {
$safer_header = strtr( $headers[$curr_header], "\"", " " );
$cmdline_params .= " -H \"".$safer_header."\"";
}
if(!empty($body))
$cmdline_params .= " -d \"$body\"";
if($this->read_timeout > 0)
$cmdline_params .= " -m ".$this->read_timeout;
$headerfile = tempnam($temp_dir, "sno");
$safer_URI = strtr( $URI, "\"", " " ); // strip quotes from the URI to avoid shell access
exec($this->curl_path." -D \"$headerfile\"".$cmdline_params." \"".$safer_URI."\"",$results,$return);
if($return)
{
$this->error = "Error: cURL could not retrieve the document, error $return.";
return false;
}
$results = implode("\r\n",$results);
$result_headers = file("$headerfile");
$this->_redirectaddr = false;
unset($this->headers);
for($currentHeader = 0; $currentHeader < count($result_headers); $currentHeader++)
{
// if a header begins with Location: or URI:, set the redirect
if(preg_match("/^(Location: |URI: )/i",$result_headers[$currentHeader]))
{
// get URL portion of the redirect
preg_match("/^(Location: |URI:)\s+(.*)/",chop($result_headers[$currentHeader]),$matches);
// look for :// in the Location header to see if hostname is included
if(!preg_match("|\:\/\/|",$matches[2]))
{
// no host in the path, so prepend
$this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port;
// eliminate double slash
if(!preg_match("|^/|",$matches[2]))
$this->_redirectaddr .= "/".$matches[2];
else
$this->_redirectaddr .= $matches[2];
}
else
$this->_redirectaddr = $matches[2];
}
if(preg_match("|^HTTP/|",$result_headers[$currentHeader]))
$this->response_code = $result_headers[$currentHeader];
$this->headers[] = $result_headers[$currentHeader];
}
// check if there is a a redirect meta tag
if(preg_match("'<meta[\s]*http-equiv[^>]*?content[\s]*=[\s]*[\"\']?\d+;[\s]*URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match))
{
$this->_redirectaddr = $this->_expandlinks($match[1],$URI);
}
// have we hit our frame depth and is there frame src to fetch?
if(($this->_framedepth < $this->maxframes) && preg_match_all("'<frame\s+.*src[\s]*=[\'\"]?([^\'\"\>]+)'i",$results,$match))
{
$this->results[] = $results;
for($x=0; $x<count($match[1]); $x++)
$this->_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host);
}
// have we already fetched framed content?
elseif(is_array($this->results))
$this->results[] = $results;
// no framed content
else
$this->results = $results;
unlink("$headerfile");
return true;
}
/*======================================================================*\
Function: setcookies()
Purpose: set cookies for a redirection
\*======================================================================*/
function setcookies()
{
for($x=0; $x<count($this->headers); $x++)
{
if(preg_match('/^set-cookie:[\s]+([^=]+)=([^;]+)/i', $this->headers[$x],$match))
$this->cookies[$match[1]] = urldecode($match[2]);
}
}
/*======================================================================*\
Function: _check_timeout
Purpose: checks whether timeout has occurred
Input: $fp file pointer
\*======================================================================*/
function _check_timeout($fp)
{
if ($this->read_timeout > 0) {
$fp_status = socket_get_status($fp);
if ($fp_status["timed_out"]) {
$this->timed_out = true;
return true;
}
}
return false;
}
/*======================================================================*\
Function: _connect
Purpose: make a socket connection
Input: $fp file pointer
\*======================================================================*/
function _connect(&$fp)
{
if(!empty($this->proxy_host) && !empty($this->proxy_port))
{
$this->_isproxy = true;
$host = $this->proxy_host;
$port = $this->proxy_port;
}
else
{
$host = $this->host;
$port = $this->port;
}
$this->status = 0;
if($fp = fsockopen(
$host,
$port,
$errno,
$errstr,
$this->_fp_timeout
))
{
// socket connection succeeded
return true;
}
else
{
// socket connection failed
$this->status = $errno;
switch($errno)
{
case -3:
$this->error="socket creation failed (-3)";
case -4:
$this->error="dns lookup failure (-4)";
case -5:
$this->error="connection refused or timed out (-5)";
default:
$this->error="connection failed (".$errno.")";
}
return false;
}
}
/*======================================================================*\
Function: _disconnect
Purpose: disconnect a socket connection
Input: $fp file pointer
\*======================================================================*/
function _disconnect($fp)
{
return(fclose($fp));
}
/*======================================================================*\
Function: _prepare_post_body
Purpose: Prepare post body according to encoding type
Input: $formvars - form variables
$formfiles - form upload files
Output: post body
\*======================================================================*/
function _prepare_post_body($formvars, $formfiles)
{
settype($formvars, "array");
settype($formfiles, "array");
$postdata = '';
if (count($formvars) == 0 && count($formfiles) == 0)
return;
switch ($this->_submit_type) {
case "application/x-www-form-urlencoded":
reset($formvars);
while(list($key,$val) = each($formvars)) {
if (is_array($val) || is_object($val)) {
while (list($cur_key, $cur_val) = each($val)) {
$postdata .= urlencode($key)."[]=".urlencode($cur_val)."&";
}
} else
$postdata .= urlencode($key)."=".urlencode($val)."&";
}
break;
case "multipart/form-data":
$this->_mime_boundary = "Snoopy".md5(uniqid(microtime()));
reset($formvars);
while(list($key,$val) = each($formvars)) {
if (is_array($val) || is_object($val)) {
while (list($cur_key, $cur_val) = each($val)) {
$postdata .= "--".$this->_mime_boundary."\r\n";
$postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n";
$postdata .= "$cur_val\r\n";
}
} else {
$postdata .= "--".$this->_mime_boundary."\r\n";
$postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n";
$postdata .= "$val\r\n";
}
}
reset($formfiles);
while (list($field_name, $file_names) = each($formfiles)) {
settype($file_names, "array");
while (list(, $file_name) = each($file_names)) {
if (!is_readable($file_name)) continue;
$fp = fopen($file_name, "r");
$file_content = fread($fp, filesize($file_name));
fclose($fp);
$base_name = basename($file_name);
$postdata .= "--".$this->_mime_boundary."\r\n";
$postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\n\r\n";
$postdata .= "$file_content\r\n";
}
}
$postdata .= "--".$this->_mime_boundary."--\r\n";
break;
}
return $postdata;
}
}
?>
| {
"pile_set_name": "Github"
} |
{
"name": "reveal.js",
"version": "2.6.2",
"description": "The HTML Presentation Framework",
"homepage": "http://lab.hakim.se/reveal-js",
"subdomain": "revealjs",
"scripts": {
"test": "grunt test",
"start": ""
},
"author": {
"name": "Hakim El Hattab",
"email": "[email protected]",
"web": "http://hakim.se"
},
"repository": {
"type": "git",
"url": "git://github.com/hakimel/reveal.js.git"
},
"engines": {
"node": "~0.8.0"
},
"dependencies": {
"underscore": "~1.5.1",
"express": "~2.5.9",
"mustache": "~0.7.2",
"socket.io": "~0.9.13"
},
"devDependencies": {
"grunt-contrib-qunit": "~0.2.2",
"grunt-contrib-jshint": "~0.6.4",
"grunt-contrib-cssmin": "~0.4.1",
"grunt-contrib-uglify": "~0.2.4",
"grunt-contrib-watch": "~0.5.3",
"grunt-contrib-sass": "~0.5.0",
"grunt-contrib-connect": "~0.4.1",
"grunt-zip": "~0.7.0",
"grunt": "~0.4.0"
},
"licenses": [
{
"type": "MIT",
"url": "https://github.com/hakimel/reveal.js/blob/master/LICENSE"
}
]
}
| {
"pile_set_name": "Github"
} |
/* Formatted output to strings.
Copyright (C) 1999, 2002, 2005-2007, 2009-2020 Free Software Foundation,
Inc.
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
#include <config.h>
/* Specification. */
#include "unistdio.h"
#include <stdarg.h>
#define SNPRINTF u8_snprintf
#define VSNPRINTF u8_vsnprintf
#define FCHAR_T char
#define DCHAR_T uint8_t
#include "u-snprintf.h"
| {
"pile_set_name": "Github"
} |
# Analytics
Parse provides a number of hooks for you to get a glimpse into the ticking heart of your app. We understand that it's important to understand what your app is doing, how frequently, and when.
While this section will cover different ways to instrument your app to best take advantage of Parse's analytics backend, developers using Parse to store and retrieve data can already take advantage of metrics on Parse.
Without having to implement any client-side logic, you can view real-time graphs and breakdowns (by device type, Parse class name, or REST verb) of your API Requests in your app's dashboard and save these graph filters to quickly access just the data you're interested in.
The current server time will be used for all analytics requests. To explicitly set the time associated with a given event, an optional `at` parameter can be provided in ISO 8601 format.
```bash
-d '{
"at": {
"__type": "Date",
"iso": "2015-03-01T15:59:11-07:00"
}
}'
```
## App-Open Analytics
Our analytics hook allows you to track your application being launched. By making a POST request to our REST API, you'll begin to collect data on when and how often your application is opened.
In the example below, the `at` parameter is optional. If omitted, the current server time will be used instead.
<div class="language-toggle">
<pre><code class="bash">
curl -X POST \
-H "X-Parse-Application-Id: <span class="custom-parse-server-appid">${APPLICATION_ID}</span>" \
-H "X-Parse-REST-API-Key: <span class="custom-parse-server-restapikey">${REST_API_KEY}</span>" \
-H "Content-Type: application/json" \
-d '{
}' \
<span class="custom-parse-server-protocol">https</span>://<span class="custom-parse-server-url">YOUR.PARSE-SERVER.HERE</span><span class="custom-parse-server-mount">/parse/</span>events/AppOpened
</code></pre>
<pre><code class="python">
import json,httplib
connection = httplib.HTTPSConnection('<span class="custom-parse-server-url">YOUR.PARSE-SERVER.HERE</span>', 443)
connection.connect()
connection.request('POST', '<span class="custom-parse-server-mount">/parse/</span>events/AppOpened', json.dumps({
}), {
"X-Parse-Application-Id": "<span class="custom-parse-server-appid">${APPLICATION_ID}</span>",
"X-Parse-REST-API-Key": "<span class="custom-parse-server-restapikey">${REST_API_KEY}</span>",
"Content-Type": "application/json"
})
result = json.loads(connection.getresponse().read())
print result
</code></pre>
</div>
Graphs and breakdowns of your statistics are accessible from your app's Dashboard.
## Custom Analytics
Parse Analytics also allows you to track free-form events, with a handful of string keys and values. These extra dimensions allow segmentation of your custom events via your app's Dashboard.
Say your app offers search functionality for apartment listings, and you want to track how often the feature is used, with some additional metadata.
<div class="language-toggle">
<pre><code class="bash">
curl -X POST \
-H "X-Parse-Application-Id: <span class="custom-parse-server-appid">${APPLICATION_ID}</span>" \
-H "X-Parse-REST-API-Key: <span class="custom-parse-server-restapikey">${REST_API_KEY}</span>" \
-H "Content-Type: application/json" \
-d '{
"dimensions": {
"priceRange": "1000-1500",
"source": "craigslist",
"dayType": "weekday"
}
}' \
<span class="custom-parse-server-protocol">https</span>://<span class="custom-parse-server-url">YOUR.PARSE-SERVER.HERE</span><span class="custom-parse-server-mount">/parse/</span>events/Search
</code></pre>
<pre><code class="python">
import json,httplib
connection = httplib.HTTPSConnection('<span class="custom-parse-server-url">YOUR.PARSE-SERVER.HERE</span>', 443)
connection.connect()
connection.request('POST', '<span class="custom-parse-server-mount">/parse/</span>events/Search', json.dumps({
"dimensions": {
"priceRange": "1000-1500",
"source": "craigslist",
"dayType": "weekday"
}
}), {
"X-Parse-Application-Id": "<span class="custom-parse-server-appid">${APPLICATION_ID}</span>",
"X-Parse-REST-API-Key": "<span class="custom-parse-server-restapikey">${REST_API_KEY}</span>",
"Content-Type": "application/json"
})
result = json.loads(connection.getresponse().read())
print result
</code></pre>
</div>
Parse Analytics can even be used as a lightweight error tracker — simply invoke the following and you'll have access to an overview of the rate and frequency of errors, broken down by error code, in your application:
<div class="language-toggle">
<pre><code class="bash">
curl -X POST \
-H "X-Parse-Application-Id: <span class="custom-parse-server-appid">${APPLICATION_ID}</span>" \
-H "X-Parse-REST-API-Key: <span class="custom-parse-server-restapikey">${REST_API_KEY}</span>" \
-H "Content-Type: application/json" \
-d '{
"dimensions": {
"code": "404"
}
}' \
<span class="custom-parse-server-protocol">https</span>://<span class="custom-parse-server-url">YOUR.PARSE-SERVER.HERE</span><span class="custom-parse-server-mount">/parse/</span>events/Error
</code></pre>
<pre><code class="python">
import json,httplib
connection = httplib.HTTPSConnection('<span class="custom-parse-server-url">YOUR.PARSE-SERVER.HERE</span>', 443)
connection.connect()
connection.request('POST', '<span class="custom-parse-server-mount">/parse/</span>events/Error', json.dumps({
"dimensions": {
"code": "404"
}
}), {
"X-Parse-Application-Id": "<span class="custom-parse-server-appid">${APPLICATION_ID}</span>",
"X-Parse-REST-API-Key": "<span class="custom-parse-server-restapikey">${REST_API_KEY}</span>",
"Content-Type": "application/json"
})
result = json.loads(connection.getresponse().read())
print result
</code></pre>
</div>
Note that Parse currently only stores the first eight dimension pairs per call to <code class="highlighter-rouge"><span class="custom-parse-server-mount">/parse/</span>events/<eventName></code>.
| {
"pile_set_name": "Github"
} |
<div class="refentry" lang="en" xml:lang="en"><a id="glDeleteBuffers"></a><div class="titlepage"></div><div class="refnamediv"><h2>Name</h2><p>glDeleteBuffers — delete named buffer objects</p></div><div class="refsynopsisdiv"><h2>C Specification</h2><div class="funcsynopsis"><table><tr><td><code class="funcdef">void <b class="fsfunc">glDeleteBuffers</b>(</code></td><td>GLsizei </td><td><var class="pdparam">n</var>, </td></tr><tr><td> </td><td>const GLuint * </td><td><var class="pdparam">buffers</var><code>)</code>;</td></tr></table></div></div><div class="refsect1" lang="en" xml:lang="en"><a id="parameters"></a><h2>Parameters</h2><div class="variablelist"><dl><dt><span class="term"><em class="parameter"><code>n</code></em></span></dt><dd><p>
Specifies the number of buffer objects to be deleted.
</p></dd><dt><span class="term"><em class="parameter"><code>buffers</code></em></span></dt><dd><p>
Specifies an array of buffer objects to be deleted.
</p></dd></dl></div></div><div class="refsect1" lang="en" xml:lang="en"><a id="description"></a><h2>Description</h2><p>
<code class="function">glDeleteBuffers</code> deletes <em class="parameter"><code>n</code></em> buffer objects named by the elements of the array <em class="parameter"><code>buffers</code></em>.
After a buffer object is deleted, it has no contents,
and its name is free for reuse (for example by <a class="citerefentry" href="glGenBuffers"><span class="citerefentry"><span class="refentrytitle">glGenBuffers</span></span></a>).
If a buffer object that is currently bound is deleted, the binding reverts
to 0 (the absence of any buffer object, which reverts to client memory usage).
</p><p>
<code class="function">glDeleteBuffers</code> silently ignores 0's and names that do not correspond to
existing buffer objects.
</p></div><div class="refsect1" lang="en" xml:lang="en"><a id="notes"></a><h2>Notes</h2><p>
<code class="function">glDeleteBuffers</code> is available only if the GL version is 1.5 or greater.
</p></div><div class="refsect1" lang="en" xml:lang="en"><a id="errors"></a><h2>Errors</h2><p>
<code class="constant">GL_INVALID_VALUE</code> is generated if <em class="parameter"><code>n</code></em> is negative.
</p><p>
<code class="constant">GL_INVALID_OPERATION</code> is generated if <code class="function">glDeleteBuffers</code> is executed
between the execution of <a class="citerefentry" href="glBegin"><span class="citerefentry"><span class="refentrytitle">glBegin</span></span></a> and the corresponding
execution of <a class="citerefentry" href="glEnd"><span class="citerefentry"><span class="refentrytitle">glEnd</span></span></a>.
</p></div><div class="refsect1" lang="en" xml:lang="en"><a id="associatedgets"></a><h2>Associated Gets</h2><p>
<a class="citerefentry" href="glIsBuffer"><span class="citerefentry"><span class="refentrytitle">glIsBuffer</span></span></a>
</p></div>
{$pipelinestall}{$examples}
<div class="refsect1" lang="en" xml:lang="en"><a id="seealso"></a><h2>See Also</h2><p>
<a class="citerefentry" href="glBindBuffer"><span class="citerefentry"><span class="refentrytitle">glBindBuffer</span></span></a>,
<a class="citerefentry" href="glGenBuffers"><span class="citerefentry"><span class="refentrytitle">glGenBuffers</span></span></a>,
<a class="citerefentry" href="glGet"><span class="citerefentry"><span class="refentrytitle">glGet</span></span></a>
</p></div><div class="refsect1" lang="en" xml:lang="en"><div id="Copyright"><h2>Copyright</h2><p>
Copyright © 2005 Addison-Wesley.
This material may be distributed subject to the terms and conditions set forth in
the Open Publication License, v 1.0, 8 June 1999.
<a class="ulink" href="https://opencontent.org/openpub/" target="_top">https://opencontent.org/openpub/</a>.
</p></div></div></div>
| {
"pile_set_name": "Github"
} |
// Code generated by protoc-gen-validate. DO NOT EDIT.
// source: github.com/solo-io/gloo/projects/gloo/api/external/envoy/extensions/waf/waf.proto
package waf
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"hash"
"hash/fnv"
"net"
"net/mail"
"net/url"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/golang/protobuf/ptypes"
"github.com/mitchellh/hashstructure"
)
// ensure the imports are used
var (
_ = bytes.MinRead
_ = errors.New("")
_ = fmt.Print
_ = utf8.UTFMax
_ = (*regexp.Regexp)(nil)
_ = (*strings.Reader)(nil)
_ = net.IPv4len
_ = time.Duration(0)
_ = (*url.URL)(nil)
_ = (*mail.Address)(nil)
_ = ptypes.DynamicAny{}
)
// Hash function
func (m *ModSecurity) Hash(hasher hash.Hash64) (uint64, error) {
if m == nil {
return 0, nil
}
if hasher == nil {
hasher = fnv.New64()
}
var err error
err = binary.Write(hasher, binary.LittleEndian, m.GetDisabled())
if err != nil {
return 0, err
}
for _, v := range m.GetRuleSets() {
if h, ok := interface{}(v).(interface {
Hash(hasher hash.Hash64) (uint64, error)
}); ok {
if _, err = h.Hash(hasher); err != nil {
return 0, err
}
} else {
if val, err := hashstructure.Hash(v, nil); err != nil {
return 0, err
} else {
if err := binary.Write(hasher, binary.LittleEndian, val); err != nil {
return 0, err
}
}
}
}
if _, err = hasher.Write([]byte(m.GetCustomInterventionMessage())); err != nil {
return 0, err
}
return hasher.Sum64(), nil
}
// Hash function
func (m *RuleSet) Hash(hasher hash.Hash64) (uint64, error) {
if m == nil {
return 0, nil
}
if hasher == nil {
hasher = fnv.New64()
}
var err error
if _, err = hasher.Write([]byte(m.GetRuleStr())); err != nil {
return 0, err
}
for _, v := range m.GetFiles() {
if _, err = hasher.Write([]byte(v)); err != nil {
return 0, err
}
}
return hasher.Sum64(), nil
}
// Hash function
func (m *ModSecurityPerRoute) Hash(hasher hash.Hash64) (uint64, error) {
if m == nil {
return 0, nil
}
if hasher == nil {
hasher = fnv.New64()
}
var err error
err = binary.Write(hasher, binary.LittleEndian, m.GetDisabled())
if err != nil {
return 0, err
}
for _, v := range m.GetRuleSets() {
if h, ok := interface{}(v).(interface {
Hash(hasher hash.Hash64) (uint64, error)
}); ok {
if _, err = h.Hash(hasher); err != nil {
return 0, err
}
} else {
if val, err := hashstructure.Hash(v, nil); err != nil {
return 0, err
} else {
if err := binary.Write(hasher, binary.LittleEndian, val); err != nil {
return 0, err
}
}
}
}
if _, err = hasher.Write([]byte(m.GetCustomInterventionMessage())); err != nil {
return 0, err
}
return hasher.Sum64(), nil
}
| {
"pile_set_name": "Github"
} |
const fs = require("fs");
module.exports = ({}, pluginOptions) => {
const notesDirectory = pluginOptions.notesDirectory || "content/brain/";
if (!fs.existsSync(notesDirectory)) {
fs.mkdirSync(notesDirectory, { recursive: true });
}
};
| {
"pile_set_name": "Github"
} |
'use strict';
const AggregationCursor = require('../aggregation_cursor');
const applyWriteConcern = require('../utils').applyWriteConcern;
const decorateWithCollation = require('../utils').decorateWithCollation;
const decorateWithReadConcern = require('../utils').decorateWithReadConcern;
const handleCallback = require('../utils').handleCallback;
const MongoError = require('mongodb-core').MongoError;
const resolveReadPreference = require('../utils').resolveReadPreference;
const toError = require('../utils').toError;
const DB_AGGREGATE_COLLECTION = 1;
/**
* Perform an aggregate operation. See Collection.prototype.aggregate or Db.prototype.aggregate for more information.
*
* @method
* @param {Db} db A Db instance.
* @param {Collection|string} coll A collection instance or the string '1', used for db.aggregate.
* @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution.
* @param {object} [options] Optional settings. See Collection.prototype.aggregate or Db.prototype.aggregate for a list of options.
* @param {Db~aggregationCallback|Collection~aggregationCallback} callback The command result callback
*/
function aggregate(db, coll, pipeline, options, callback) {
const isDbAggregate = typeof coll === 'string';
const target = isDbAggregate ? db : coll;
const topology = target.s.topology;
let hasOutStage = false;
if (typeof options.out === 'string') {
pipeline = pipeline.concat({ $out: options.out });
hasOutStage = true;
} else if (pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) {
hasOutStage = true;
}
let command;
let namespace;
let optionSources;
if (isDbAggregate) {
command = { aggregate: DB_AGGREGATE_COLLECTION, pipeline: pipeline };
namespace = `${db.s.databaseName}.${DB_AGGREGATE_COLLECTION}`;
optionSources = { db };
} else {
command = { aggregate: coll.s.name, pipeline: pipeline };
namespace = coll.s.namespace;
optionSources = { db: coll.s.db, collection: coll };
}
const takesWriteConcern = topology.capabilities().commandsTakeWriteConcern;
if (!hasOutStage) {
decorateWithReadConcern(command, target, options);
}
if (pipeline.length > 0 && pipeline[pipeline.length - 1]['$out'] && takesWriteConcern) {
applyWriteConcern(command, optionSources, options);
}
try {
decorateWithCollation(command, target, options);
} catch (err) {
if (typeof callback === 'function') return callback(err, null);
throw err;
}
if (options.bypassDocumentValidation === true) {
command.bypassDocumentValidation = options.bypassDocumentValidation;
}
if (typeof options.allowDiskUse === 'boolean') command.allowDiskUse = options.allowDiskUse;
if (typeof options.maxTimeMS === 'number') command.maxTimeMS = options.maxTimeMS;
if (options.hint) command.hint = options.hint;
options = Object.assign({}, options);
// Ensure we have the right read preference inheritance
options.readPreference = resolveReadPreference(options, optionSources);
if (options.explain) {
if (command.readConcern || command.writeConcern) {
throw toError('"explain" cannot be used on an aggregate call with readConcern/writeConcern');
}
command.explain = options.explain;
}
if (typeof options.comment === 'string') command.comment = options.comment;
// Validate that cursor options is valid
if (options.cursor != null && typeof options.cursor !== 'object') {
throw toError('cursor options must be an object');
}
options.cursor = options.cursor || {};
if (options.batchSize && !hasOutStage) options.cursor.batchSize = options.batchSize;
command.cursor = options.cursor;
// promiseLibrary
options.promiseLibrary = target.s.promiseLibrary;
// Set the AggregationCursor constructor
options.cursorFactory = AggregationCursor;
if (typeof callback !== 'function') {
if (!topology.capabilities()) {
throw new MongoError('cannot connect to server');
}
return topology.cursor(namespace, command, options);
}
return handleCallback(callback, null, topology.cursor(namespace, command, options));
}
module.exports = {
aggregate
};
| {
"pile_set_name": "Github"
} |
import { useContext, useEffect } from 'react';
import { ChatContext } from '../../../../context';
export const useChannelUpdated = ({ onChannelUpdated, setChannels }) => {
const { client } = useContext(ChatContext);
useEffect(() => {
const handleEvent = (e) => {
if (typeof onChannelUpdated === 'function') {
onChannelUpdated(setChannels, e);
} else {
setChannels((channels) => {
const index = channels.findIndex(
(c) => c.cid === (e.cid || e.channel?.cid),
);
if (index >= 0 && e.channel) {
channels[index].data = e.channel;
}
return [...channels];
});
}
};
client.on('channel.updated', handleEvent);
return () => client.off('channel.updated', handleEvent);
}, []);
};
| {
"pile_set_name": "Github"
} |
/*------------------------------------------------------------------------
*
* Derivative of the OpenVG 1.0.1 Reference Implementation
* -------------------------------------
*
* Copyright (c) 2007 The Khronos Group Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and /or associated documentation files
* (the "Materials "), to deal in the Materials without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Materials,
* and to permit persons to whom the Materials are 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 Materials.
*
* THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR
* THE USE OR OTHER DEALINGS IN THE MATERIALS.
*
*-------------------------------------------------------------------*/
#import <Onyx2D/O2Paint_color.h>
#import <Onyx2D/O2Surface.h>
@implementation O2Paint_color
ONYX2D_STATIC int color_largb8u_PRE(O2Paint *selfX,int x,int y,O2argb8u *span,int length){
O2Paint_color *self=(O2Paint_color *)selfX;
O2argb8u rgba=self->_argb8u_PRE;
int i;
for(i=0;i<length;i++)
span[i]=rgba;
return length;
}
ONYX2D_STATIC int color_largb32f_PRE(O2Paint *selfX,int x,int y,O2argb32f *span,int length){
O2Paint_color *self=(O2Paint_color *)selfX;
O2argb32f rgba=self->_argb32f_PRE;
int i;
for(i=0;i<length;i++)
span[i]=rgba;
return length;
}
-initWithGray:(O2Float)gray alpha:(O2Float)alpha surfaceToPaintTransform:(O2AffineTransform)transform {
O2PaintInitWithTransform(self,transform);
if(alpha==1.0f)
isOpaque=TRUE;
_paint_largb8u_PRE=color_largb8u_PRE;
_paint_largb32f_PRE=color_largb32f_PRE;
_argb32f_PRE=O2argb32fInit(gray,gray,gray,alpha);
_argb32f_PRE=O2argb32fClamp(_argb32f_PRE);
_argb32f_PRE=O2argb32fPremultiply(_argb32f_PRE);
_argb8u_PRE=O2argb8uFromO2argb32f(_argb32f_PRE);
return self;
}
-initWithRed:(O2Float)red green:(O2Float)green blue:(O2Float)blue alpha:(O2Float)alpha surfaceToPaintTransform:(O2AffineTransform)transform {
O2PaintInitWithTransform(self,transform);
if(alpha==1.0f)
isOpaque=TRUE;
_paint_largb8u_PRE=color_largb8u_PRE;
_paint_largb32f_PRE=color_largb32f_PRE;
_argb32f_PRE=O2argb32fInit(red,green,blue,alpha);
_argb32f_PRE=O2argb32fClamp(_argb32f_PRE);
_argb32f_PRE=O2argb32fPremultiply(_argb32f_PRE);
_argb8u_PRE=O2argb8uFromO2argb32f(_argb32f_PRE);
return self;
}
@end
| {
"pile_set_name": "Github"
} |
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
/////////////////////////////////////////////////////////////////////////////
// Basic Help support (for backward compatibility to MFC 2.0)
void CWinApp::OnHelp() // use context to derive help context
{
if (m_dwPromptContext != 0)
{
// do not call WinHelp when the error is failing to lauch help
if (m_dwPromptContext != HID_BASE_PROMPT+AFX_IDP_FAILED_TO_LAUNCH_HELP)
WinHelpInternal(m_dwPromptContext);
return;
}
// otherwise, use CWnd::OnHelp implementation
CWnd* pWnd = AfxGetMainWnd();
ENSURE_VALID(pWnd);
if (!pWnd->IsFrameWnd())
pWnd->OnHelp();
else
((CFrameWnd*)pWnd)->OnHelp();
}
void CWinApp::OnHelpIndex()
{
WinHelpInternal(0L, HELP_INDEX);
}
void CWinApp::OnHelpFinder()
{
WinHelpInternal(0L, HELP_FINDER);
}
void CWinApp::OnHelpUsing()
{
WinHelpInternal(0L, HELP_HELPONHELP);
}
/////////////////////////////////////////////////////////////////////////////
// Context Help Mode support (backward compatibility to MFC 2.0)
void CWinApp::OnContextHelp()
{
// just use CFrameWnd::OnContextHelp implementation
m_bHelpMode = HELP_ACTIVE;
CFrameWnd* pMainWnd = (CFrameWnd*)AfxGetMainWnd();
ENSURE_VALID(pMainWnd);
ENSURE(pMainWnd->IsFrameWnd());
pMainWnd->OnContextHelp();
m_bHelpMode = pMainWnd->m_bHelpMode;
pMainWnd->PostMessage(WM_KICKIDLE); // trigger idle update
}
/////////////////////////////////////////////////////////////////////////////
| {
"pile_set_name": "Github"
} |
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
2367A45C187104EA00378542 /* IconPickerViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 2367A45B187104EA00378542 /* IconPickerViewController.m */; };
23F99E94186962EC00657813 /* DataModel.m in Sources */ = {isa = PBXBuildFile; fileRef = 23F99E93186962EC00657813 /* DataModel.m */; };
7B6CA3C717F967DD00E68B4B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7B6CA3C617F967DD00E68B4B /* Foundation.framework */; };
7B6CA3C917F967DD00E68B4B /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7B6CA3C817F967DD00E68B4B /* CoreGraphics.framework */; };
7B6CA3CB17F967DD00E68B4B /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7B6CA3CA17F967DD00E68B4B /* UIKit.framework */; };
7B6CA3D117F967DD00E68B4B /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 7B6CA3CF17F967DD00E68B4B /* InfoPlist.strings */; };
7B6CA3D317F967DD00E68B4B /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B6CA3D217F967DD00E68B4B /* main.m */; };
7B6CA3D717F967DD00E68B4B /* ChecklistsAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B6CA3D617F967DD00E68B4B /* ChecklistsAppDelegate.m */; };
7B6CA3DA17F967DD00E68B4B /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 7B6CA3D817F967DD00E68B4B /* Main.storyboard */; };
7B6CA3DD17F967DD00E68B4B /* ChecklistViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B6CA3DC17F967DD00E68B4B /* ChecklistViewController.m */; };
7B6CA3DF17F967DD00E68B4B /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 7B6CA3DE17F967DD00E68B4B /* Images.xcassets */; };
7B6CA3E617F967DD00E68B4B /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7B6CA3E517F967DD00E68B4B /* XCTest.framework */; };
7B6CA3E717F967DD00E68B4B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7B6CA3C617F967DD00E68B4B /* Foundation.framework */; };
7B6CA3E817F967DD00E68B4B /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7B6CA3CA17F967DD00E68B4B /* UIKit.framework */; };
7B6CA3F017F967DD00E68B4B /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 7B6CA3EE17F967DD00E68B4B /* InfoPlist.strings */; };
7B6CA3F217F967DD00E68B4B /* ChecklistsTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B6CA3F117F967DD00E68B4B /* ChecklistsTests.m */; };
7B6CA3FD17F99B6400E68B4B /* ChecklistItem.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B6CA3FC17F99B6400E68B4B /* ChecklistItem.m */; };
7B6CA40017F9D7C900E68B4B /* ItemDetailViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B6CA3FF17F9D7C900E68B4B /* ItemDetailViewController.m */; };
7B6CA4C617FC1F7900E68B4B /* AllListsViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B6CA4C517FC1F7900E68B4B /* AllListsViewController.m */; };
7B6CA4C917FC301B00E68B4B /* Checklist.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B6CA4C817FC301B00E68B4B /* Checklist.m */; };
7B6CA4CC17FC3EAE00E68B4B /* ListDetailViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B6CA4CB17FC3EAE00E68B4B /* ListDetailViewController.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
7B6CA3E917F967DD00E68B4B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 7B6CA3BB17F967DD00E68B4B /* Project object */;
proxyType = 1;
remoteGlobalIDString = 7B6CA3C217F967DD00E68B4B;
remoteInfo = Checklists;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
2367A45A187104EA00378542 /* IconPickerViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IconPickerViewController.h; sourceTree = "<group>"; };
2367A45B187104EA00378542 /* IconPickerViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = IconPickerViewController.m; sourceTree = "<group>"; };
23F99E92186962EC00657813 /* DataModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DataModel.h; sourceTree = "<group>"; };
23F99E93186962EC00657813 /* DataModel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DataModel.m; sourceTree = "<group>"; };
7B6CA3C317F967DD00E68B4B /* Checklists.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Checklists.app; sourceTree = BUILT_PRODUCTS_DIR; };
7B6CA3C617F967DD00E68B4B /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
7B6CA3C817F967DD00E68B4B /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
7B6CA3CA17F967DD00E68B4B /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
7B6CA3CE17F967DD00E68B4B /* Checklists-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Checklists-Info.plist"; sourceTree = "<group>"; };
7B6CA3D017F967DD00E68B4B /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
7B6CA3D217F967DD00E68B4B /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
7B6CA3D417F967DD00E68B4B /* Checklists-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Checklists-Prefix.pch"; sourceTree = "<group>"; };
7B6CA3D517F967DD00E68B4B /* ChecklistsAppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ChecklistsAppDelegate.h; sourceTree = "<group>"; };
7B6CA3D617F967DD00E68B4B /* ChecklistsAppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ChecklistsAppDelegate.m; sourceTree = "<group>"; };
7B6CA3D917F967DD00E68B4B /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
7B6CA3DB17F967DD00E68B4B /* ChecklistViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ChecklistViewController.h; sourceTree = "<group>"; };
7B6CA3DC17F967DD00E68B4B /* ChecklistViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ChecklistViewController.m; sourceTree = "<group>"; };
7B6CA3DE17F967DD00E68B4B /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = "<group>"; };
7B6CA3E417F967DD00E68B4B /* ChecklistsTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = ChecklistsTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
7B6CA3E517F967DD00E68B4B /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; };
7B6CA3ED17F967DD00E68B4B /* ChecklistsTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "ChecklistsTests-Info.plist"; sourceTree = "<group>"; };
7B6CA3EF17F967DD00E68B4B /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
7B6CA3F117F967DD00E68B4B /* ChecklistsTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ChecklistsTests.m; sourceTree = "<group>"; };
7B6CA3FB17F99B6400E68B4B /* ChecklistItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ChecklistItem.h; sourceTree = "<group>"; };
7B6CA3FC17F99B6400E68B4B /* ChecklistItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ChecklistItem.m; sourceTree = "<group>"; };
7B6CA3FE17F9D7C900E68B4B /* ItemDetailViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ItemDetailViewController.h; sourceTree = "<group>"; };
7B6CA3FF17F9D7C900E68B4B /* ItemDetailViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ItemDetailViewController.m; sourceTree = "<group>"; };
7B6CA4C417FC1F7900E68B4B /* AllListsViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AllListsViewController.h; sourceTree = "<group>"; };
7B6CA4C517FC1F7900E68B4B /* AllListsViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AllListsViewController.m; sourceTree = "<group>"; };
7B6CA4C717FC301B00E68B4B /* Checklist.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Checklist.h; sourceTree = "<group>"; };
7B6CA4C817FC301B00E68B4B /* Checklist.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Checklist.m; sourceTree = "<group>"; };
7B6CA4CA17FC3EAE00E68B4B /* ListDetailViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ListDetailViewController.h; sourceTree = "<group>"; };
7B6CA4CB17FC3EAE00E68B4B /* ListDetailViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ListDetailViewController.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
7B6CA3C017F967DD00E68B4B /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
7B6CA3C917F967DD00E68B4B /* CoreGraphics.framework in Frameworks */,
7B6CA3CB17F967DD00E68B4B /* UIKit.framework in Frameworks */,
7B6CA3C717F967DD00E68B4B /* Foundation.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
7B6CA3E117F967DD00E68B4B /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
7B6CA3E617F967DD00E68B4B /* XCTest.framework in Frameworks */,
7B6CA3E817F967DD00E68B4B /* UIKit.framework in Frameworks */,
7B6CA3E717F967DD00E68B4B /* Foundation.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
7B6CA3BA17F967DD00E68B4B = {
isa = PBXGroup;
children = (
7B6CA3CC17F967DD00E68B4B /* Checklists */,
7B6CA3EB17F967DD00E68B4B /* ChecklistsTests */,
7B6CA3C517F967DD00E68B4B /* Frameworks */,
7B6CA3C417F967DD00E68B4B /* Products */,
);
sourceTree = "<group>";
};
7B6CA3C417F967DD00E68B4B /* Products */ = {
isa = PBXGroup;
children = (
7B6CA3C317F967DD00E68B4B /* Checklists.app */,
7B6CA3E417F967DD00E68B4B /* ChecklistsTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
7B6CA3C517F967DD00E68B4B /* Frameworks */ = {
isa = PBXGroup;
children = (
7B6CA3C617F967DD00E68B4B /* Foundation.framework */,
7B6CA3C817F967DD00E68B4B /* CoreGraphics.framework */,
7B6CA3CA17F967DD00E68B4B /* UIKit.framework */,
7B6CA3E517F967DD00E68B4B /* XCTest.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
7B6CA3CC17F967DD00E68B4B /* Checklists */ = {
isa = PBXGroup;
children = (
7B6CA3D517F967DD00E68B4B /* ChecklistsAppDelegate.h */,
7B6CA3D617F967DD00E68B4B /* ChecklistsAppDelegate.m */,
7B6CA3D817F967DD00E68B4B /* Main.storyboard */,
7B6CA3DB17F967DD00E68B4B /* ChecklistViewController.h */,
7B6CA3DC17F967DD00E68B4B /* ChecklistViewController.m */,
7B6CA3DE17F967DD00E68B4B /* Images.xcassets */,
7B6CA3CD17F967DD00E68B4B /* Supporting Files */,
7B6CA3FB17F99B6400E68B4B /* ChecklistItem.h */,
7B6CA3FC17F99B6400E68B4B /* ChecklistItem.m */,
7B6CA3FE17F9D7C900E68B4B /* ItemDetailViewController.h */,
7B6CA3FF17F9D7C900E68B4B /* ItemDetailViewController.m */,
7B6CA4C417FC1F7900E68B4B /* AllListsViewController.h */,
7B6CA4C517FC1F7900E68B4B /* AllListsViewController.m */,
7B6CA4C717FC301B00E68B4B /* Checklist.h */,
7B6CA4C817FC301B00E68B4B /* Checklist.m */,
7B6CA4CA17FC3EAE00E68B4B /* ListDetailViewController.h */,
7B6CA4CB17FC3EAE00E68B4B /* ListDetailViewController.m */,
23F99E92186962EC00657813 /* DataModel.h */,
23F99E93186962EC00657813 /* DataModel.m */,
2367A45A187104EA00378542 /* IconPickerViewController.h */,
2367A45B187104EA00378542 /* IconPickerViewController.m */,
);
path = Checklists;
sourceTree = "<group>";
};
7B6CA3CD17F967DD00E68B4B /* Supporting Files */ = {
isa = PBXGroup;
children = (
7B6CA3CE17F967DD00E68B4B /* Checklists-Info.plist */,
7B6CA3CF17F967DD00E68B4B /* InfoPlist.strings */,
7B6CA3D217F967DD00E68B4B /* main.m */,
7B6CA3D417F967DD00E68B4B /* Checklists-Prefix.pch */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
7B6CA3EB17F967DD00E68B4B /* ChecklistsTests */ = {
isa = PBXGroup;
children = (
7B6CA3F117F967DD00E68B4B /* ChecklistsTests.m */,
7B6CA3EC17F967DD00E68B4B /* Supporting Files */,
);
path = ChecklistsTests;
sourceTree = "<group>";
};
7B6CA3EC17F967DD00E68B4B /* Supporting Files */ = {
isa = PBXGroup;
children = (
7B6CA3ED17F967DD00E68B4B /* ChecklistsTests-Info.plist */,
7B6CA3EE17F967DD00E68B4B /* InfoPlist.strings */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
7B6CA3C217F967DD00E68B4B /* Checklists */ = {
isa = PBXNativeTarget;
buildConfigurationList = 7B6CA3F517F967DD00E68B4B /* Build configuration list for PBXNativeTarget "Checklists" */;
buildPhases = (
7B6CA3BF17F967DD00E68B4B /* Sources */,
7B6CA3C017F967DD00E68B4B /* Frameworks */,
7B6CA3C117F967DD00E68B4B /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = Checklists;
productName = Checklists;
productReference = 7B6CA3C317F967DD00E68B4B /* Checklists.app */;
productType = "com.apple.product-type.application";
};
7B6CA3E317F967DD00E68B4B /* ChecklistsTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 7B6CA3F817F967DD00E68B4B /* Build configuration list for PBXNativeTarget "ChecklistsTests" */;
buildPhases = (
7B6CA3E017F967DD00E68B4B /* Sources */,
7B6CA3E117F967DD00E68B4B /* Frameworks */,
7B6CA3E217F967DD00E68B4B /* Resources */,
);
buildRules = (
);
dependencies = (
7B6CA3EA17F967DD00E68B4B /* PBXTargetDependency */,
);
name = ChecklistsTests;
productName = ChecklistsTests;
productReference = 7B6CA3E417F967DD00E68B4B /* ChecklistsTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
7B6CA3BB17F967DD00E68B4B /* Project object */ = {
isa = PBXProject;
attributes = {
CLASSPREFIX = Checklists;
LastUpgradeCheck = 0500;
ORGANIZATIONNAME = "Razeware LLC";
TargetAttributes = {
7B6CA3E317F967DD00E68B4B = {
TestTargetID = 7B6CA3C217F967DD00E68B4B;
};
};
};
buildConfigurationList = 7B6CA3BE17F967DD00E68B4B /* Build configuration list for PBXProject "Checklists" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 7B6CA3BA17F967DD00E68B4B;
productRefGroup = 7B6CA3C417F967DD00E68B4B /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
7B6CA3C217F967DD00E68B4B /* Checklists */,
7B6CA3E317F967DD00E68B4B /* ChecklistsTests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
7B6CA3C117F967DD00E68B4B /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
7B6CA3DF17F967DD00E68B4B /* Images.xcassets in Resources */,
7B6CA3D117F967DD00E68B4B /* InfoPlist.strings in Resources */,
7B6CA3DA17F967DD00E68B4B /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
7B6CA3E217F967DD00E68B4B /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
7B6CA3F017F967DD00E68B4B /* InfoPlist.strings in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
7B6CA3BF17F967DD00E68B4B /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
7B6CA3D317F967DD00E68B4B /* main.m in Sources */,
2367A45C187104EA00378542 /* IconPickerViewController.m in Sources */,
7B6CA3D717F967DD00E68B4B /* ChecklistsAppDelegate.m in Sources */,
23F99E94186962EC00657813 /* DataModel.m in Sources */,
7B6CA4C617FC1F7900E68B4B /* AllListsViewController.m in Sources */,
7B6CA4CC17FC3EAE00E68B4B /* ListDetailViewController.m in Sources */,
7B6CA3DD17F967DD00E68B4B /* ChecklistViewController.m in Sources */,
7B6CA40017F9D7C900E68B4B /* ItemDetailViewController.m in Sources */,
7B6CA3FD17F99B6400E68B4B /* ChecklistItem.m in Sources */,
7B6CA4C917FC301B00E68B4B /* Checklist.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
7B6CA3E017F967DD00E68B4B /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
7B6CA3F217F967DD00E68B4B /* ChecklistsTests.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
7B6CA3EA17F967DD00E68B4B /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 7B6CA3C217F967DD00E68B4B /* Checklists */;
targetProxy = 7B6CA3E917F967DD00E68B4B /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
7B6CA3CF17F967DD00E68B4B /* InfoPlist.strings */ = {
isa = PBXVariantGroup;
children = (
7B6CA3D017F967DD00E68B4B /* en */,
);
name = InfoPlist.strings;
sourceTree = "<group>";
};
7B6CA3D817F967DD00E68B4B /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
7B6CA3D917F967DD00E68B4B /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
7B6CA3EE17F967DD00E68B4B /* InfoPlist.strings */ = {
isa = PBXVariantGroup;
children = (
7B6CA3EF17F967DD00E68B4B /* en */,
);
name = InfoPlist.strings;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
7B6CA3F317F967DD00E68B4B /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)";
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 7.0;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
};
name = Debug;
};
7B6CA3F417F967DD00E68B4B /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)";
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
ENABLE_NS_ASSERTIONS = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 7.0;
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
7B6CA3F617F967DD00E68B4B /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Checklists/Checklists-Prefix.pch";
INFOPLIST_FILE = "Checklists/Checklists-Info.plist";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = app;
};
name = Debug;
};
7B6CA3F717F967DD00E68B4B /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Checklists/Checklists-Prefix.pch";
INFOPLIST_FILE = "Checklists/Checklists-Info.plist";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = app;
};
name = Release;
};
7B6CA3F917F967DD00E68B4B /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)";
BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/Checklists.app/Checklists";
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
"$(DEVELOPER_FRAMEWORKS_DIR)",
);
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Checklists/Checklists-Prefix.pch";
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = "ChecklistsTests/ChecklistsTests-Info.plist";
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUNDLE_LOADER)";
WRAPPER_EXTENSION = xctest;
};
name = Debug;
};
7B6CA3FA17F967DD00E68B4B /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)";
BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/Checklists.app/Checklists";
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
"$(DEVELOPER_FRAMEWORKS_DIR)",
);
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Checklists/Checklists-Prefix.pch";
INFOPLIST_FILE = "ChecklistsTests/ChecklistsTests-Info.plist";
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUNDLE_LOADER)";
WRAPPER_EXTENSION = xctest;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
7B6CA3BE17F967DD00E68B4B /* Build configuration list for PBXProject "Checklists" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7B6CA3F317F967DD00E68B4B /* Debug */,
7B6CA3F417F967DD00E68B4B /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
7B6CA3F517F967DD00E68B4B /* Build configuration list for PBXNativeTarget "Checklists" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7B6CA3F617F967DD00E68B4B /* Debug */,
7B6CA3F717F967DD00E68B4B /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
7B6CA3F817F967DD00E68B4B /* Build configuration list for PBXNativeTarget "ChecklistsTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7B6CA3F917F967DD00E68B4B /* Debug */,
7B6CA3FA17F967DD00E68B4B /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 7B6CA3BB17F967DD00E68B4B /* Project object */;
}
| {
"pile_set_name": "Github"
} |
# coding=utf-8
# Copyright 2020 The Tensor2Robot 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.
# Lint as python3
"""Tests for tensor2robot.layers.resnet."""
import functools
from absl.testing import parameterized
from six.moves import range
from tensor2robot.layers import resnet
import tensorflow.compat.v1 as tf
class ResnetTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.parameters(('',), ('fubar',), ('dummy/scope'))
def test_intermediate_values(self, scope):
with tf.variable_scope(scope):
image = tf.zeros((2, 224, 224, 3), dtype=tf.float32)
end_points = resnet.resnet_model(image,
is_training=True,
num_classes=1001,
return_intermediate_values=True)
tensors = ['initial_conv', 'initial_max_pool', 'pre_final_pool',
'final_reduce_mean', 'final_dense']
tensors += [
'block_layer{}'.format(i + 1) for i in range(4)]
self.assertEqual(set(tensors), set(end_points.keys()))
@parameterized.parameters(
(18, [True, True, True, True]),
(50, [True, False, True, False]))
def test_film(self, resnet_size, enabled_blocks):
image = tf.zeros((2, 224, 224, 3), dtype=tf.float32)
embedding = tf.zeros((2, 100), dtype=tf.float32)
film_generator_fn = functools.partial(
resnet.linear_film_generator, enabled_block_layers=enabled_blocks)
_ = resnet.resnet_model(image,
is_training=True,
num_classes=1001,
resnet_size=resnet_size,
return_intermediate_values=True,
film_generator_fn=film_generator_fn,
film_generator_input=embedding)
def test_malformed_film_raises(self):
image = tf.zeros((2, 224, 224, 3), dtype=tf.float32)
embedding = tf.zeros((2, 100), dtype=tf.float32)
film_generator_fn = functools.partial(
resnet.linear_film_generator, enabled_block_layers=[True]*5)
with self.assertRaises(ValueError):
_ = resnet.resnet_model(image,
is_training=True,
num_classes=1001,
resnet_size=18,
return_intermediate_values=True,
film_generator_fn=film_generator_fn,
film_generator_input=embedding)
if __name__ == '__main__':
tf.test.main()
| {
"pile_set_name": "Github"
} |
procedural_city_generation.additional_stuff package
===================================================
Submodules
----------
procedural_city_generation.additional_stuff.LinalgTools module
--------------------------------------------------------------
.. automodule:: procedural_city_generation.additional_stuff.LinalgTools
:members:
:undoc-members:
:show-inheritance:
procedural_city_generation.additional_stuff.Param module
--------------------------------------------------------
.. automodule:: procedural_city_generation.additional_stuff.Param
:members:
:undoc-members:
:show-inheritance:
procedural_city_generation.additional_stuff.Singleton module
------------------------------------------------------------
.. automodule:: procedural_city_generation.additional_stuff.Singleton
:members:
:undoc-members:
:show-inheritance:
procedural_city_generation.additional_stuff.Wavefront module
------------------------------------------------------------
.. automodule:: procedural_city_generation.additional_stuff.Wavefront
:members:
:undoc-members:
:show-inheritance:
procedural_city_generation.additional_stuff.clean_tools module
--------------------------------------------------------------
.. automodule:: procedural_city_generation.additional_stuff.clean_tools
:members:
:undoc-members:
:show-inheritance:
procedural_city_generation.additional_stuff.pickletools module
--------------------------------------------------------------
.. automodule:: procedural_city_generation.additional_stuff.pickletools
:members:
:undoc-members:
:show-inheritance:
procedural_city_generation.additional_stuff.randommap module
------------------------------------------------------------
.. automodule:: procedural_city_generation.additional_stuff.randommap
:members:
:undoc-members:
:show-inheritance:
procedural_city_generation.additional_stuff.readimages module
-------------------------------------------------------------
.. automodule:: procedural_city_generation.additional_stuff.readimages
:members:
:undoc-members:
:show-inheritance:
procedural_city_generation.additional_stuff.rotate module
---------------------------------------------------------
.. automodule:: procedural_city_generation.additional_stuff.rotate
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: procedural_city_generation.additional_stuff
:members:
:undoc-members:
:show-inheritance:
| {
"pile_set_name": "Github"
} |
---
layout: page
title: Upgrade Astronomer
permalink: /guides/upgrade/
hide: true
---
## Upgrade Astronomer
Once the Astronomer umbrella chart is installed, you may want to make config changes, or upgrade to a newer release.
Helm makes it easy to update a Kubernetes cluster.
Most updates can be installed by running:
```bash
cd astronomer-ee
helm upgrade -f config.yaml --namespace astronomer <release name> .
```
There are some cases where Helm cannot do an automatic upgrade which can be resolved by doing a fresh install.
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.core.security;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import org.apache.accumulo.core.util.ByteArraySet;
import org.junit.Test;
public class AuthorizationsTest {
@Test
public void testSetOfByteArrays() {
assertTrue(ByteArraySet.fromStrings("a", "b", "c").contains("a".getBytes()));
}
@Test
public void testEncodeDecode() {
Authorizations a = new Authorizations("a", "abcdefg", "hijklmno", ",");
byte[] array = a.getAuthorizationsArray();
Authorizations b = new Authorizations(array);
assertEquals(a, b);
// test encoding empty auths
a = new Authorizations();
array = a.getAuthorizationsArray();
b = new Authorizations(array);
assertEquals(a, b);
// test encoding multi-byte auths
a = new Authorizations("五", "b", "c", "九");
array = a.getAuthorizationsArray();
b = new Authorizations(array);
assertEquals(a, b);
}
@Test
public void testSerialization() {
Authorizations a1 = new Authorizations("a", "b");
Authorizations a2 = new Authorizations("b", "a");
assertEquals(a1, a2);
assertEquals(a1.serialize(), a2.serialize());
}
@Test
public void testDefensiveAccess() {
Authorizations expected = new Authorizations("foo", "a");
Authorizations actual = new Authorizations("foo", "a");
// foo to goo; test defensive iterator
for (byte[] bytes : actual) {
bytes[0]++;
}
assertArrayEquals(expected.getAuthorizationsArray(), actual.getAuthorizationsArray());
// test defensive getter and serializer
actual.getAuthorizations().get(0)[0]++;
assertArrayEquals(expected.getAuthorizationsArray(), actual.getAuthorizationsArray());
assertEquals(expected.serialize(), actual.serialize());
}
// This should throw ReadOnlyBufferException, but THRIFT-883 requires that the ByteBuffers
// themselves not be read-only
// @Test(expected = ReadOnlyBufferException.class)
@Test
public void testReadOnlyByteBuffer() {
Authorizations expected = new Authorizations("foo");
Authorizations actual = new Authorizations("foo");
assertArrayEquals(expected.getAuthorizationsArray(), actual.getAuthorizationsArray());
actual.getAuthorizationsBB().get(0).array()[0]++;
assertArrayEquals(expected.getAuthorizationsArray(), actual.getAuthorizationsArray());
}
@Test(expected = UnsupportedOperationException.class)
public void testUnmodifiableList() {
Authorizations expected = new Authorizations("foo");
Authorizations actual = new Authorizations("foo");
assertArrayEquals(expected.getAuthorizationsArray(), actual.getAuthorizationsArray());
actual.getAuthorizationsBB().add(ByteBuffer.wrap(new byte[] {'a'}));
}
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2011-2013, dafei 李飞 (myaniu AT gmail DOT com)
*
* 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.jfinal.ext.plugin.shiro;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
public class ShiroInterceptor implements Interceptor {
@Override
public void intercept(ActionInvocation ai) {
AuthzHandler ah = ShiroKit.getAuthzHandler(ai.getActionKey());
// 存在访问控制处理器。
if (ah != null) {
try {
// 执行权限检查。
ah.assertAuthorized();
} catch (UnauthenticatedException lae) {
// RequiresGuest,RequiresAuthentication,RequiresUser,未满足时,抛出未经授权的异常。
// 如果没有进行身份验证,返回HTTP401状态码
ai.getController().renderError(401);
return;
} catch (AuthorizationException ae) {
// RequiresRoles,RequiresPermissions授权异常
// 如果没有权限访问对应的资源,返回HTTP状态码403。
ai.getController().renderError(403);
return;
} catch (Exception e) {
// 出现了异常,应该是没有登录。
ai.getController().renderError(401);
return;
}
}
// 执行正常逻辑
ai.invoke();
}
}
| {
"pile_set_name": "Github"
} |
# Darwin/XNU
`Darwin/XNU` is not supported at the moment.
[panicall](https://twitter.com/panicaII) has ported
([[1]](https://i.blackhat.com/eu-18/Wed-Dec-5/eu-18-Juwei_Lin-Drill-The-Apple-Core.pdf)
([video](https://www.youtube.com/watch?v=zDXyH8HxTwg)),
[[2]](https://conference.hitb.org/hitbsecconf2019ams/materials/D2T2%20-%20PanicXNU%203.0%20-%20Juwei%20Lin%20&%20Junzhi%20Lu.pdf))
syzkaller to `Darwin/XNU` and that has found more than
[50 bugs](https://twitter.com/panicaII/status/1070696972326133760) including
`CVE-2018-4447` and `CVE-2018-4435` mentioned in
[Apple security updates](https://support.apple.com/en-us/HT209341).
`Darwin/XNU` is [open-source](https://github.com/opensource-apple/xnu) and has
[KASAN](https://github.com/apple/darwin-xnu/blob/master/san/kasan.c).
Latest versions also contain KCOV-like support for coverage;
it's not uploaded to github mirror yet, but this
[tarball](https://opensource.apple.com/tarballs/xnu/xnu-6153.11.26.tar.gz)
contains `san/ksancov.{h,c}`.
[PureDarwin](http://www.puredarwin.org/) may be used to create VM images suitable for fuzzing.
| {
"pile_set_name": "Github"
} |
//{{BLOCK(start_border0)
//======================================================================
//
// start_border0, 32x256@4,
// Transparent color : FF,00,FF
// + palette 16 entries, not compressed
// + bitmap not compressed
// Total size: 32 + 4096 = 4128
//
// Time-stamp: 2018-06-20, 11:35:44
// Exported by Cearn's GBA Image Transmogrifier, v0.8.14
// ( http://www.coranac.com/projects/#grit )
//
//======================================================================
#ifndef CURSOR_PAL_H
#define CURSOR_PAL_H
const unsigned short cursorPals[16*16]
{
0x7C1F,0x3D88,0x7FFF,0x0000,0x0000,0x0000,0x0000,0x0000, // 0: gray
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x00D1,0x6B9F,0x0000,0x0000,0x0000,0x0000,0x0000, // 1: brown
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x0019,0x6B3F,0x0000,0x0000,0x0000,0x0000,0x0000, // 2: red
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x413B,0x7FBF,0x0000,0x0000,0x0000,0x0000,0x0000, // 3: pink
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x015B,0x73DF,0x0000,0x0000,0x0000,0x0000,0x0000, // 4: orange
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x0238,0x6FFF,0x0000,0x0000,0x0000,0x0000,0x0000, // 5: yellow
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x02ED,0x7FFF,0x0000,0x0000,0x0000,0x0000,0x0000, // 6: yellow-green
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x02C0,0x7FFF,0x0000,0x0000,0x0000,0x0000,0x0000, // 7: lively green
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x0260,0x7FFF,0x0000,0x0000,0x0000,0x0000,0x0000, // 8: green
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x2203,0x7BFD,0x0000,0x0000,0x0000,0x0000,0x0000, // 9: light green
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x51C3,0x7FFF,0x0000,0x0000,0x0000,0x0000,0x0000, // 10: sky blue
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x60E0,0x7FBB,0x0000,0x0000,0x0000,0x0000,0x0000, // 11: light blue
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x5400,0x7FBD,0x0000,0x0000,0x0000,0x0000,0x0000, // 12: blue
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x480E,0x7F7E,0x0000,0x0000,0x0000,0x0000,0x0000, // 13: violet
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x4CD7,0x7FFF,0x0000,0x0000,0x0000,0x0000,0x0000, // 14: purple
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x7C1F,0x401B,0x7B9F,0x0000,0x0000,0x0000,0x0000,0x0000, // 15: fuschia
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
};
#endif // CURSOR_PAL_H
//}}BLOCK(start_border0)
| {
"pile_set_name": "Github"
} |
/* intprefix.c - generate an unprefixed internal symbol list
*
* Last changed in libpng version 1.6.16 [December 22, 2014]
* Copyright (c) 2013-2014 Glenn Randers-Pehrson
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*/
#define PNG_INTERNAL_DATA(type, name, array)\
PNG_DFN "@" name "@"
#define PNG_INTERNAL_FUNCTION(type, name, args, attributes)\
PNG_DFN "@" name "@"
#define PNG_INTERNAL_CALLBACK(type, name, args, attributes)\
PNG_DFN "@" name "@"
#define PNGPREFIX_H /* self generation */
#include "../pngpriv.h"
| {
"pile_set_name": "Github"
} |
<div id="password" class="field form-group has-feedback formio-component formio-component-password formio-component-password " ref="component">
<label class="" for="password-password">
Password
</label>
<div ref="element">
<div class="ui input fluid ">
<input ref="input" name="data[password]" type="password" class="form-control" lang="en" spellcheck="true" value="" id="password-password"></input>
</div>
</div>
<div ref="messageContainer"></div>
</div> | {
"pile_set_name": "Github"
} |
package com.apollographql.apollo.internal;
import com.apollographql.apollo.ApolloCall;
import com.apollographql.apollo.ApolloQueryWatcher;
import com.apollographql.apollo.api.OperationName;
import com.apollographql.apollo.api.Query;
import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.api.ScalarTypeAdapters;
import com.apollographql.apollo.api.cache.http.HttpCachePolicy;
import com.apollographql.apollo.api.internal.ApolloLogger;
import com.apollographql.apollo.cache.CacheHeaders;
import com.apollographql.apollo.cache.normalized.ApolloStore;
import com.apollographql.apollo.exception.ApolloException;
import com.apollographql.apollo.fetcher.ApolloResponseFetchers;
import com.apollographql.apollo.interceptor.ApolloInterceptor;
import com.apollographql.apollo.interceptor.ApolloInterceptorFactory;
import okhttp3.Call;
import okhttp3.HttpUrl;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
final class QueryReFetcher {
final ApolloLogger logger;
private final List<RealApolloCall> calls;
private List<OperationName> queryWatchers;
private ApolloCallTracker callTracker;
private final AtomicBoolean executed = new AtomicBoolean();
OnCompleteCallback onCompleteCallback;
static Builder builder() {
return new Builder();
}
QueryReFetcher(Builder builder) {
logger = builder.logger;
calls = new ArrayList<>(builder.queries.size());
for (Query query : builder.queries) {
calls.add(RealApolloCall.builder()
.operation(query)
.serverUrl(builder.serverUrl)
.httpCallFactory(builder.httpCallFactory)
.responseFieldMapperFactory(builder.responseFieldMapperFactory)
.scalarTypeAdapters(builder.scalarTypeAdapters)
.apolloStore(builder.apolloStore)
.httpCachePolicy(HttpCachePolicy.NETWORK_ONLY)
.responseFetcher(ApolloResponseFetchers.NETWORK_ONLY)
.cacheHeaders(CacheHeaders.NONE)
.logger(builder.logger)
.applicationInterceptors(builder.applicationInterceptors)
.applicationInterceptorFactories(builder.applicationInterceptorFactories)
.autoPersistedOperationsInterceptorFactory(builder.autoPersistedOperationsInterceptorFactory)
.tracker(builder.callTracker)
.dispatcher(builder.dispatcher)
.build());
}
queryWatchers = builder.queryWatchers;
callTracker = builder.callTracker;
}
void refetch() {
if (!executed.compareAndSet(false, true)) {
throw new IllegalStateException("Already Executed");
}
refetchQueryWatchers();
refetchQueries();
}
void cancel() {
for (RealApolloCall call : calls) {
call.cancel();
}
}
private void refetchQueryWatchers() {
try {
for (OperationName operationName : queryWatchers) {
for (ApolloQueryWatcher queryWatcher : callTracker.activeQueryWatchers(operationName)) {
queryWatcher.refetch();
}
}
} catch (Exception e) {
logger.e(e, "Failed to re-fetch query watcher");
}
}
private void refetchQueries() {
final OnCompleteCallback completeCallback = onCompleteCallback;
final AtomicInteger callsLeft = new AtomicInteger(calls.size());
for (final RealApolloCall call : calls) {
//noinspection unchecked
call.enqueue(new ApolloCall.Callback() {
@Override public void onResponse(@NotNull Response response) {
if (callsLeft.decrementAndGet() == 0 && completeCallback != null) {
completeCallback.onFetchComplete();
}
}
@Override public void onFailure(@NotNull ApolloException e) {
if (logger != null) {
logger.e(e, "Failed to fetch query: %s", call.operation);
}
if (callsLeft.decrementAndGet() == 0 && completeCallback != null) {
completeCallback.onFetchComplete();
}
}
});
}
}
static final class Builder {
List<Query> queries = Collections.emptyList();
List<OperationName> queryWatchers = Collections.emptyList();
HttpUrl serverUrl;
Call.Factory httpCallFactory;
ResponseFieldMapperFactory responseFieldMapperFactory;
ScalarTypeAdapters scalarTypeAdapters;
ApolloStore apolloStore;
Executor dispatcher;
ApolloLogger logger;
List<ApolloInterceptor> applicationInterceptors;
List<ApolloInterceptorFactory> applicationInterceptorFactories;
ApolloInterceptorFactory autoPersistedOperationsInterceptorFactory;
ApolloCallTracker callTracker;
Builder queries(List<Query> queries) {
this.queries = queries != null ? queries : Collections.<Query>emptyList();
return this;
}
public Builder queryWatchers(List<OperationName> queryWatchers) {
this.queryWatchers = queryWatchers != null ? queryWatchers : Collections.<OperationName>emptyList();
return this;
}
Builder serverUrl(HttpUrl serverUrl) {
this.serverUrl = serverUrl;
return this;
}
Builder httpCallFactory(Call.Factory httpCallFactory) {
this.httpCallFactory = httpCallFactory;
return this;
}
Builder responseFieldMapperFactory(ResponseFieldMapperFactory responseFieldMapperFactory) {
this.responseFieldMapperFactory = responseFieldMapperFactory;
return this;
}
Builder scalarTypeAdapters(ScalarTypeAdapters scalarTypeAdapters) {
this.scalarTypeAdapters = scalarTypeAdapters;
return this;
}
Builder apolloStore(ApolloStore apolloStore) {
this.apolloStore = apolloStore;
return this;
}
Builder dispatcher(Executor dispatcher) {
this.dispatcher = dispatcher;
return this;
}
Builder logger(ApolloLogger logger) {
this.logger = logger;
return this;
}
Builder applicationInterceptors(List<ApolloInterceptor> applicationInterceptors) {
this.applicationInterceptors = applicationInterceptors;
return this;
}
Builder applicationInterceptorFactories(List<ApolloInterceptorFactory> applicationInterceptorFactories) {
this.applicationInterceptorFactories = applicationInterceptorFactories;
return this;
}
Builder autoPersistedOperationsInterceptorFactory(ApolloInterceptorFactory interceptorFactories) {
this.autoPersistedOperationsInterceptorFactory = interceptorFactories;
return this;
}
Builder callTracker(ApolloCallTracker callTracker) {
this.callTracker = callTracker;
return this;
}
QueryReFetcher build() {
return new QueryReFetcher(this);
}
Builder() {
}
}
interface OnCompleteCallback {
void onFetchComplete();
}
}
| {
"pile_set_name": "Github"
} |
#!/bin/cat
$Id: FAQ.ISP.txt,v 1.9 2018/05/24 11:34:30 gilles Exp gilles $
This document is also available online at
https://imapsync.lamiral.info/FAQ.d/
https://imapsync.lamiral.info/FAQ.d/FAQ.ISP.txt
=======================================================================
Imapsync tips for ISP. Specific issues and solutions.
=======================================================================
* IMAPSync - usage scenario with ISP - by Flávio Zarur Lucarelli.
I thought Id write a quick step by step on my attempts to learn the
imapsync features that matter the most, so it works as we expected in
the cenario in which we use it, which is to migrate customers from
their old ISP to our ISP/email hosting. Thanks to the master Gilles
Lamiral for all his help and hard work.
First of all, remember to use --dry to test things first always and
check the log file to see what would actually happen.
Initially, I used a method where I'd do an exact sync of source to
destination, deleting messages which were in destination, but not
source. I call this "Method 2", below. In this cenario, customer
shouldn't be using the destination account yet. Then, after I switch MX,
I'd do a final sync based on date. The big advantage of this is, you
get an exact sync.
Easier, however, is method 1, where I sync based on message ID, this
way, I can use the same syntax before and after MX change, with no
worries. Only disadvantage, you might not get an exact sync, there
might be some difference in terms of total emails in folders, due to
duplicates, emails that had same message ID in source server.
* Method 1 - sync based on message ID, can use same syntax before and
after MX change
imapsync --host1 imap.myisp.com --user1 [email protected] --password1 pwd \
--host2 imap.myisp.com --user2 [email protected] --password2 pwd \
--addheader
Note: add header adds message ID when it doesn't exist.
This syntax can also be used to sync different source accounts to one
same destination account, simply execute it as many times as desired,
switching source user (user1).
* Method 2 - exact sync source do destination, then sync based on date
after MX change
My first goal is to have an exact sync of an account from
current/source host to the new/destination host and be able to sync
several times. The --useuid parameter is very important for that
purpose. This is what I use:
imapsync --host1 imap.gmail.com --user1 [email protected] --password1 pwd --ssl1 \
--host2 imap.myisp.com --user2 [email protected] --password2 pwd --ssl2 \
--useuid --delete2 --delete2folders
This makes it so imap.myisp.com (destination) is an exact copy of the
account at imap.gmail.com (source). This is not a problem, since the
user is not using the new host yet. ]You can check Imapsync log files
and surely you will see the final difference should be 0. Check also
for any possible errors in the log (search for "error").
The second goal is to lower the TTL (ex: 5 min) for the host
associated with the MX record, in the domain's DNS server. Let's say
customer has a host mail which his MX points to, with a high TTL
(usually 1 hour). Lower it to 5 min so that, when you change the MX,
it propagates faster.
When comes time to switch over to the new host, do a final sync with
above syntax, before changing the MX. Then, change the MX and tell
your users to start using exclusively the new host.
A few hours after the MX change, we will run Imapsync again. We have
to start preserving emails users move or flag in the new host, which
they started using, so we can't do an exact sync anymore.
The best solution for me was to Sync any new emails (maxage:1) from
source (that could arrive in source even after MX change, due to
cache) and delete such emails from source server. This way, customer's
mailbox is still intact on the source server, except new emails, which
get synced to new server and deleted from source.
imapsync --host1 imap.gmail.com --user1 [email protected] --password1 pwd --ssl1 \
--host2 imap.myisp.com --user2 [email protected] --password2 pwd --ssl2 \
--folder INBOX --useuid --noexpungeaftereach --skipemptyfolders --maxage 1 --delete1
I personally prefer to keep a copy of users box intact in source, but
if that's not an issue for you, you can remove --folder INBOX and even
--maxage, but then, all emails in source will be deleted. You can use
--maxage 1 with --delete1, however, for all folder (without specifying
--folder INBOX), so only any new email that arrives at source is
copied to destination and deleted from source.
My next goal was to automate the process, so I followed this advice:
http://imapsync.lamiral.info/examples/sync_loop_unix.sh
I also ended up requiring a regex to translate folder names. On the
old server (Gmail), Sent items were in a folder called [Gmail]/E-mails
enviados and on the new server, its simply called SENT. Same with
lixeira (trash) and rascunhos (drafts).
So this was added:
--regextrans2 "s,\[Gmail\].,," \
--regextrans2 "s,E-mails enviados,Sent," \
--regextrans2 "s,Lixeira,Trash," \
--regextrans2 "s,Rascunhos,Drafts,"
*** Other cenarios
- Sync entire account into 1 folder of another account
imapsync --host1 xxx --user1 [email protected] --password1 secret1 --ssl1 \
--host2 yyy --user2 [email protected] --password2 secret2 --ssl2 \
--useuid --subfolder2 otheraccountfolder --delete2 --delete2foldersonly /otheraccountfolder/
Above is based on message UID, advantage of no dupes, however, user
must not be using such destination folder in destination account until
you finish syncing.
=======================================================================
=======================================================================
| {
"pile_set_name": "Github"
} |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#ifndef _CV_MODEL_EST_H_
#define _CV_MODEL_EST_H_
#include "precomp.hpp"
class CvModelEstimator2
{
public:
CvModelEstimator2(int _modelPoints, CvSize _modelSize, int _maxBasicSolutions);
virtual ~CvModelEstimator2();
virtual int runKernel( const CvMat* m1, const CvMat* m2, CvMat* model )=0;
virtual bool runLMeDS( const CvMat* m1, const CvMat* m2, CvMat* model,
CvMat* mask, double confidence=0.99, int maxIters=2000 );
virtual bool runRANSAC( const CvMat* m1, const CvMat* m2, CvMat* model,
CvMat* mask, double threshold,
double confidence=0.99, int maxIters=2000 );
virtual bool refine( const CvMat*, const CvMat*, CvMat*, int ) { return true; }
virtual void setSeed( int64 seed );
protected:
virtual void computeReprojError( const CvMat* m1, const CvMat* m2,
const CvMat* model, CvMat* error ) = 0;
virtual int findInliers( const CvMat* m1, const CvMat* m2,
const CvMat* model, CvMat* error,
CvMat* mask, double threshold );
virtual bool getSubset( const CvMat* m1, const CvMat* m2,
CvMat* ms1, CvMat* ms2, int maxAttempts=1000 );
virtual bool checkSubset( const CvMat* ms1, int count );
CvRNG rng;
int modelPoints;
CvSize modelSize;
int maxBasicSolutions;
bool checkPartialSubsets;
};
#endif // _CV_MODEL_EST_H_
| {
"pile_set_name": "Github"
} |
# Copyright 2018 Spotify AB
#
# 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 cstar.job
import cstar.jobreader
import cstar.exceptions
import os
import shutil
from cstar.output import msg
def cleanup(max_days, listdir=os.listdir, jobread=cstar.jobreader.read, delete=shutil.rmtree):
job_dir = os.path.expanduser('~/.cstar/jobs')
for job_id in listdir(job_dir):
try:
jobread(cstar.job.Job(), job_id, stop_after=None, max_days=max_days, endpoint_mapper=lambda x: None)
except Exception:
msg("Removing job", job_id)
full_name = os.path.join(job_dir, job_id)
delete(full_name)
| {
"pile_set_name": "Github"
} |
{
"acno": "D26298",
"acquisitionYear": 1856,
"additionalImages": [
{
"copyright": null,
"creativeCommons": null,
"filenameBase": "D26298",
"sizes": [
{
"caption": "Enhanced image",
"cleared": true,
"file": "enhanced_images/D262/D26298_E.jpg",
"height": 512,
"resolution": 512,
"size": "large",
"width": 334
}
]
}
],
"all_artists": "Joseph Mallord William Turner",
"catTextResId": 1136228,
"catalogueGroup": {
"accessionRanges": "D26259-D26435; D41047-D41049",
"completeStatus": "COMPLETE",
"finbergNumber": "CCLXIX",
"groupType": "Turner Sketchbook",
"id": 65894,
"shortTitle": "Stirling and Edinburgh Sketchbook"
},
"classification": "on paper, unique",
"contributorCount": 1,
"contributors": [
{
"birthYear": 1775,
"date": "1775\u20131851",
"displayOrder": 1,
"fc": "Joseph Mallord William Turner",
"gender": "Male",
"id": 558,
"mda": "Turner, Joseph Mallord William",
"role": "artist",
"startLetter": "T"
}
],
"creditLine": "Accepted by the nation as part of the Turner Bequest 1856",
"dateRange": {
"endYear": 1834,
"startYear": 1834,
"text": "1834"
},
"dateText": "1834",
"depth": "",
"dimensions": "support: 190 x 113 mm",
"finberg": "CCLXIX 20 a",
"foreignTitle": null,
"groupTitle": "Stirling and Edinburgh Sketchbook",
"height": "113",
"id": 53635,
"inscription": null,
"medium": "Graphite on paper",
"movementCount": 0,
"pageNumber": 42,
"subjectCount": 4,
"subjects": {
"children": [
{
"children": [
{
"children": [
{
"id": 1138,
"name": "castle"
}
],
"id": 20,
"name": "military"
},
{
"children": [
{
"id": 5212,
"name": "military"
}
],
"id": 27,
"name": "ruins"
}
],
"id": 13,
"name": "architecture"
},
{
"children": [
{
"children": [
{
"id": 636,
"name": "hill"
},
{
"id": 496,
"name": "wooded"
}
],
"id": 71,
"name": "landscape"
}
],
"id": 60,
"name": "nature"
}
],
"id": 1,
"name": "subject"
},
"thumbnailCopyright": null,
"thumbnailUrl": "http://www.tate.org.uk/art/images/work/D/D26/D26298_8.jpg",
"title": "Ruined Castle on Hill, ?Craignethan Castle",
"units": "mm",
"url": "http://www.tate.org.uk/art/artworks/turner-ruined-castle-on-hill-craignethan-castle-d26298",
"width": "190"
} | {
"pile_set_name": "Github"
} |
{
"author": {
"name": "Sindre Sorhus",
"email": "[email protected]",
"url": "sindresorhus.com"
},
"dependencies": {
"pump": "^3.0.0"
},
"description": "Get a stream as a string, buffer, or array",
"devDependencies": {
"ava": "*",
"into-stream": "^3.0.0",
"xo": "*"
},
"engines": {
"node": ">=6"
},
"files": [
"index.js",
"buffer-stream.js"
],
"homepage": "https://github.com/sindresorhus/get-stream#readme",
"license": "MIT",
"name": "get-stream",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/get-stream.git"
},
"version": "4.1.0"
} | {
"pile_set_name": "Github"
} |
/**
*
*/
package com.juxtapose.example.ch09.listener;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import com.juxtapose.example.ch09.Constant;
/**
* @author bruce.liu(mailto:[email protected])
* 2013-10-7下午03:33:22
*/
public class VerifyStepExecutionListener implements StepExecutionListener {
/* (non-Javadoc)
* @see org.springframework.batch.core.StepExecutionListener#beforeStep(org.springframework.batch.core.StepExecution)
*/
@Override
public void beforeStep(StepExecution stepExecution) { }
/* (non-Javadoc)
* @see org.springframework.batch.core.StepExecutionListener#afterStep(org.springframework.batch.core.StepExecution)
*/
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
String status = stepExecution.getExecutionContext().getString(Constant.VERITY_STATUS);
if(null != status){
return new ExitStatus(status);
}
return stepExecution.getExitStatus();
}
}
| {
"pile_set_name": "Github"
} |
<?php
__FUNCTION__[0];
__dir__[0];
?> | {
"pile_set_name": "Github"
} |
define([
'../Variable',
'../extensions/dstore',
'dstore/Memory',
'intern!object',
'intern/chai!assert'
], function (VariableExports, dstore, Memory, registerSuite, assert) {
var Variable = VariableExports.Variable
var DstoreVariable = dstore.DstoreVariable
function MockStore() {
this.handlers = []
this.on = function(events, f) {
this.handlers.push(f)
var that = this
return {
remove: function() {
that.handlers = that.handlers.filter(function(h) { return h !== f })
}
}
}
}
suite('dstore', function() {
test('dstoreUpdates', function() {
var store = new Memory({
data: [
{id: 1, name: 'one'},
{id: 2, name: 'two'},
{id: 3, name: 'three'}
]
})
// wrap an existing variable just to make sure we get flow through
var array = new DstoreVariable(new Variable(store))
var count = array.to(function(){
return store.fetchSync().length
})
var lastCountUpdate
count.notifies({
updated: function(updateEvent) {
lastCountUpdate = updateEvent
}
})
assert.strictEqual(count.valueOf(), 3)
store.add({id: 4, name: 'four'})
assert.strictEqual(count.valueOf(), 4)
assert.strictEqual(lastCountUpdate.type, 'refresh')
lastCountUpdate = null
store.remove(2)
assert.strictEqual(count.valueOf(), 3)
assert.strictEqual(lastCountUpdate.type, 'refresh')
lastCountUpdate = null
store.put({id: 4, name: 'FOUR'})
assert.strictEqual(count.valueOf(), 3)
assert.strictEqual(lastCountUpdate.type, 'refresh')
})
test('resolveDStoreAsyncPromise', function() {
var store = new Memory({
data: [
{id: 1, name: 'one'},
{id: 2, name: 'two'},
{id: 3, name: 'three'}
]
})
//var storeVar = new DstoreVariable(store)
var storeVar = new Variable(store)
var result = []
storeVar.forEach(function(item){
result.push({i: item.id, n: item.name})
})
assert.deepEqual(result, [{i:1,n:'one'},{i:2,n:'two'},{i:3,n:'three'}])
})
test('listenerRemovedWhenVariableChanged', function() {
var m1 = new MockStore()
var m2 = new MockStore()
assert.equal(m1.handlers.length, 0)
assert.equal(m2.handlers.length, 0)
var storeVar = new DstoreVariable()
storeVar.put(m1)
storeVar.valueOf()
assert.equal(m1.handlers.length, 1)
assert.equal(m2.handlers.length, 0)
storeVar.put(m2)
storeVar.valueOf()
assert.equal(m1.handlers.length, 0)
assert.equal(m2.handlers.length, 1)
})
test('listenerRegistrationIdempotent', function() {
var m1 = new MockStore()
var m2 = new MockStore()
assert.equal(m1.handlers.length, 0)
assert.equal(m2.handlers.length, 0)
var storeVar = new DstoreVariable()
storeVar.put(m1)
storeVar.valueOf()
assert.equal(m1.handlers.length, 1)
storeVar.valueOf()
assert.equal(m1.handlers.length, 1)
storeVar.put(m1)
storeVar.valueOf()
assert.equal(m1.handlers.length, 1)
storeVar.put(m2)
storeVar.valueOf()
assert.equal(m1.handlers.length, 0)
assert.equal(m2.handlers.length, 1)
// put seen m1 again
storeVar.put(m1)
storeVar.valueOf()
assert.equal(m1.handlers.length, 1)
assert.equal(m2.handlers.length, 0)
}
})
})
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
#ifndef ROCKSDB_LITE
#include "utilities/persistent_cache/volatile_tier_impl.h"
#include <string>
namespace rocksdb {
void VolatileCacheTier::DeleteCacheData(VolatileCacheTier::CacheData* data) {
assert(data);
delete data;
}
VolatileCacheTier::~VolatileCacheTier() { index_.Clear(&DeleteCacheData); }
PersistentCache::StatsType VolatileCacheTier::Stats() {
std::map<std::string, double> stat;
stat.insert({"persistent_cache.volatile_cache.hits",
static_cast<double>(stats_.cache_hits_)});
stat.insert({"persistent_cache.volatile_cache.misses",
static_cast<double>(stats_.cache_misses_)});
stat.insert({"persistent_cache.volatile_cache.inserts",
static_cast<double>(stats_.cache_inserts_)});
stat.insert({"persistent_cache.volatile_cache.evicts",
static_cast<double>(stats_.cache_evicts_)});
stat.insert({"persistent_cache.volatile_cache.hit_pct",
static_cast<double>(stats_.CacheHitPct())});
stat.insert({"persistent_cache.volatile_cache.miss_pct",
static_cast<double>(stats_.CacheMissPct())});
auto out = PersistentCacheTier::Stats();
out.push_back(stat);
return out;
}
Status VolatileCacheTier::Insert(const Slice& page_key, const char* data,
const size_t size) {
// precondition
assert(data);
assert(size);
// increment the size
size_ += size;
// check if we have overshot the limit, if so evict some space
while (size_ > max_size_) {
if (!Evict()) {
// unable to evict data, we give up so we don't spike read
// latency
assert(size_ >= size);
size_ -= size;
return Status::TryAgain("Unable to evict any data");
}
}
assert(size_ >= size);
// insert order: LRU, followed by index
std::string key(page_key.data(), page_key.size());
std::string value(data, size);
std::unique_ptr<CacheData> cache_data(
new CacheData(std::move(key), std::move(value)));
bool ok = index_.Insert(cache_data.get());
if (!ok) {
// decrement the size that we incremented ahead of time
assert(size_ >= size);
size_ -= size;
// failed to insert to cache, block already in cache
return Status::TryAgain("key already exists in volatile cache");
}
cache_data.release();
stats_.cache_inserts_++;
return Status::OK();
}
Status VolatileCacheTier::Lookup(const Slice& page_key,
std::unique_ptr<char[]>* result,
size_t* size) {
CacheData key(std::move(page_key.ToString()));
CacheData* kv;
bool ok = index_.Find(&key, &kv);
if (ok) {
// set return data
result->reset(new char[kv->value.size()]);
memcpy(result->get(), kv->value.c_str(), kv->value.size());
*size = kv->value.size();
// drop the reference on cache data
kv->refs_--;
// update stats
stats_.cache_hits_++;
return Status::OK();
}
stats_.cache_misses_++;
if (next_tier()) {
return next_tier()->Lookup(page_key, result, size);
}
return Status::NotFound("key not found in volatile cache");
}
bool VolatileCacheTier::Erase(const Slice& key) {
assert(!"not supported");
return true;
}
bool VolatileCacheTier::Evict() {
CacheData* edata = index_.Evict();
if (!edata) {
// not able to evict any object
return false;
}
stats_.cache_evicts_++;
// push the evicted object to the next level
if (next_tier()) {
next_tier()->Insert(Slice(edata->key), edata->value.c_str(),
edata->value.size());
}
// adjust size and destroy data
size_ -= edata->value.size();
delete edata;
return true;
}
} // namespace rocksdb
#endif
| {
"pile_set_name": "Github"
} |
/*
Open Source Initiative OSI - The MIT License (MIT):Licensing
The MIT License (MIT)
Copyright (c) 2013 Ralph Caraveo ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Package mapset implements a simple and generic set collection.
// Items stored within it are unordered and unique. It supports
// typical set operations: membership testing, intersection, union,
// difference, symmetric difference and cloning.
//
// Package mapset provides two implementations. The default
// implementation is safe for concurrent access. There is a non-threadsafe
// implementation which is slightly more performant.
package mapset
type Set interface {
// Adds an element to the set. Returns whether
// the item was added.
Add(i interface{}) bool
// Returns the number of elements in the set.
Cardinality() int
// Removes all elements from the set, leaving
// the emtpy set.
Clear()
// Returns a clone of the set using the same
// implementation, duplicating all keys.
Clone() Set
// Returns whether the given items
// are all in the set.
Contains(i ...interface{}) bool
// Returns the difference between this set
// and other. The returned set will contain
// all elements of this set that are not also
// elements of other.
//
// Note that the argument to Difference
// must be of the same type as the receiver
// of the method. Otherwise, Difference will
// panic.
Difference(other Set) Set
// Determines if two sets are equal to each
// other. If they have the same cardinality
// and contain the same elements, they are
// considered equal. The order in which
// the elements were added is irrelevant.
//
// Note that the argument to Equal must be
// of the same type as the receiver of the
// method. Otherwise, Equal will panic.
Equal(other Set) bool
// Returns a new set containing only the elements
// that exist only in both sets.
//
// Note that the argument to Intersect
// must be of the same type as the receiver
// of the method. Otherwise, Intersect will
// panic.
Intersect(other Set) Set
// Determines if every element in the other set
// is in this set.
//
// Note that the argument to IsSubset
// must be of the same type as the receiver
// of the method. Otherwise, IsSubset will
// panic.
IsSubset(other Set) bool
// Determines if every element in this set is in
// the other set.
//
// Note that the argument to IsSuperset
// must be of the same type as the receiver
// of the method. Otherwise, IsSuperset will
// panic.
IsSuperset(other Set) bool
// Returns a channel of elements that you can
// range over.
Iter() <-chan interface{}
// Remove a single element from the set.
Remove(i interface{})
// Provides a convenient string representation
// of the current state of the set.
String() string
// Returns a new set with all elements which are
// in either this set or the other set but not in both.
//
// Note that the argument to SymmetricDifference
// must be of the same type as the receiver
// of the method. Otherwise, SymmetricDifference
// will panic.
SymmetricDifference(other Set) Set
// Returns a new set with all elements in both sets.
//
// Note that the argument to Union must be of the
// same type as the receiver of the method.
// Otherwise, IsSuperset will panic.
Union(other Set) Set
// Returns all subsets of a given set (Power Set).
PowerSet() Set
// Returns the Cartesian Product of two sets.
CartesianProduct(other Set) Set
// Returns the members of the set as a slice.
ToSlice() []interface{}
}
// Creates and returns a reference to an empty set.
func NewSet() Set {
set := newThreadSafeSet()
return &set
}
// Creates and returns a reference to a set from an existing slice
func NewSetFromSlice(s []interface{}) Set {
a := NewSet()
for _, item := range s {
a.Add(item)
}
return a
}
func NewThreadUnsafeSet() Set {
set := newThreadUnsafeSet()
return &set
}
func NewThreadUnsafeSetFromSlice(s []interface{}) Set {
a := NewThreadUnsafeSet()
for _, item := range s {
a.Add(item)
}
return a
}
| {
"pile_set_name": "Github"
} |
import Vue from 'vue'
describe('Directive v-model dynamic input type', () => {
it('should work', done => {
const vm = new Vue({
data: {
inputType: null,
test: 'b'
},
template: `<input :type="inputType" v-model="test">`
}).$mount()
document.body.appendChild(vm.$el)
// test text
assertInputWorks(vm, 'inputType').then(done)
})
it('with v-if', done => {
const vm = new Vue({
data: {
ok: true,
type: null,
test: 'b'
},
template: `<input v-if="ok" :type="type" v-model="test"><div v-else>haha</div>`
}).$mount()
document.body.appendChild(vm.$el)
const chain = assertInputWorks(vm).then(() => {
vm.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('haha')
}).then(() => {
// reset
vm.ok = true
vm.type = null
vm.test = 'b'
})
assertInputWorks(vm, chain).then(done)
})
it('with v-else', done => {
const data = {
ok: true,
type: null,
test: 'b'
}
const vm = new Vue({
data,
template: `<div v-if="ok">haha</div><input v-else :type="type" v-model="test">`
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.textContent).toBe('haha')
vm.ok = false
assertInputWorks(vm).then(done)
})
it('with v-else-if', done => {
const vm = new Vue({
data: {
foo: true,
bar: false,
type: null,
test: 'b'
},
template: `<div v-if="foo">text</div><input v-else-if="bar" :type="type" v-model="test">`
}).$mount()
document.body.appendChild(vm.$el)
const chain = waitForUpdate(() => {
expect(vm.$el.textContent).toBe('text')
}).then(() => {
vm.foo = false
}).then(() => {
expect(vm._vnode.isComment).toBe(true)
}).then(() => {
vm.bar = true
})
assertInputWorks(vm, chain).then(done)
})
it('with v-for', done => {
const vm = new Vue({
data: {
data: {
text: 'foo',
checkbox: true
},
types: ['text', 'checkbox']
},
template: `<div>
<input v-for="type in types" :type="type" v-model="data[type]">
</div>`
}).$mount()
document.body.appendChild(vm.$el)
let el1 = vm.$el.children[0]
expect(el1.type).toBe('text')
expect(el1.value).toBe('foo')
el1.value = 'bar'
triggerEvent(el1, 'input')
expect(vm.data.text).toBe('bar')
let el2 = vm.$el.children[1]
expect(el2.type).toBe('checkbox')
expect(el2.checked).toBe(true)
el2.click()
expect(vm.data.checkbox).toBe(false)
// now in reverse!
vm.types.reverse()
waitForUpdate(() => {
el1 = vm.$el.children[0]
expect(el1.type).toBe('checkbox')
expect(el1.checked).toBe(false)
el1.click()
expect(vm.data.checkbox).toBe(true)
el2 = vm.$el.children[1]
expect(el2.type).toBe('text')
expect(el2.value).toBe('bar')
el2.value = 'foo'
triggerEvent(el2, 'input')
expect(vm.data.text).toBe('foo')
}).then(done)
})
it('with v-bind', done => {
const vm = new Vue({
data: {
data: {
text: 'foo',
checkbox: true
},
inputs: [{ id: 'one', type: 'text' }, { id: 'two', type: 'checkbox' }]
},
template: `<div>
<input v-for="i in inputs" v-bind="i" v-model="data[i.type]">
</div>`
}).$mount()
document.body.appendChild(vm.$el)
let el1 = vm.$el.children[0]
expect(el1.id).toBe('one')
expect(el1.type).toBe('text')
expect(el1.value).toBe('foo')
el1.value = 'bar'
triggerEvent(el1, 'input')
expect(vm.data.text).toBe('bar')
let el2 = vm.$el.children[1]
expect(el2.id).toBe('two')
expect(el2.type).toBe('checkbox')
expect(el2.checked).toBe(true)
el2.click()
expect(vm.data.checkbox).toBe(false)
// now in reverse!
vm.inputs.reverse()
waitForUpdate(() => {
el1 = vm.$el.children[0]
expect(el1.id).toBe('two')
expect(el1.type).toBe('checkbox')
expect(el1.checked).toBe(false)
el1.click()
expect(vm.data.checkbox).toBe(true)
el2 = vm.$el.children[1]
expect(el2.id).toBe('one')
expect(el2.type).toBe('text')
expect(el2.value).toBe('bar')
el2.value = 'foo'
triggerEvent(el2, 'input')
expect(vm.data.text).toBe('foo')
}).then(done)
})
})
function assertInputWorks (vm, type, chain) {
if (typeof type !== 'string') {
if (!chain) chain = type
type = 'type'
}
if (!chain) chain = waitForUpdate()
chain.then(() => {
expect(vm.$el.value).toBe('b')
vm.test = 'a'
}).then(() => {
expect(vm.$el.value).toBe('a')
vm.$el.value = 'c'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('c')
}).then(() => {
// change it to password
vm[type] = 'password'
vm.test = 'b'
}).then(() => {
expect(vm.$el.type).toBe('password')
expect(vm.$el.value).toBe('b')
vm.$el.value = 'c'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('c')
}).then(() => {
// change it to checkbox...
vm[type] = 'checkbox'
}).then(() => {
expect(vm.$el.type).toBe('checkbox')
expect(vm.$el.checked).toBe(true)
}).then(() => {
vm.$el.click()
expect(vm.$el.checked).toBe(false)
expect(vm.test).toBe(false)
})
return chain
}
| {
"pile_set_name": "Github"
} |
---
name: Free form
about: For everything that is NOT a bug report.
title: ''
labels: ''
assignees: ''
---
<!--
DO NOT USE THIS TEMPLATE FOR BUG REPORTS!
IF YOU DO, THEY WILL BE CLOSED AND MARKED AS INVALID!
-->
| {
"pile_set_name": "Github"
} |
# Dolibarr language file - Source file is en_US - contracts
ContractsArea=Área contratos
ListOfContracts=Listaxe de contratos
AllContracts=Todos os contratos
ContractCard=Ficha contrato
ContractStatusNotRunning=Fora de servizo
ContractStatusDraft=Borrador
ContractStatusValidated=Validado
ContractStatusClosed=Pechado
ServiceStatusInitial=Inactivo
ServiceStatusRunning=En servizo
ServiceStatusNotLate=En servizo, non expirado
ServiceStatusNotLateShort=Non expirado
ServiceStatusLate=En servizo, expirado
ServiceStatusLateShort=Expirado
ServiceStatusClosed=Pechado
ShowContractOfService=Amosar contrato de servizos
Contracts=Contratos
ContractsSubscriptions=Contratos/Suscricións
ContractsAndLine=Contratos e liñas de contratos
Contract=Contrato
ContractLine=Liña de contrato
Closing=Pechando
NoContracts=Sen contratos
MenuServices=Servizos
MenuInactiveServices=Servizos inactivos
MenuRunningServices=Servizos activos
MenuExpiredServices=Servizos expirados
MenuClosedServices=Servizos pechados
NewContract=Novo contrato
NewContractSubscription=New contract or subscription
AddContract=Crear contrato
DeleteAContract=Eliminar un contrato
ActivateAllOnContract=Activar todos os servizos
CloseAContract=Pechar un contrato
ConfirmDeleteAContract=¿Está certo de querer eliminar este contrato?
ConfirmValidateContract=¿Está certo de querer validar este contrato baixo a referencia <b>%s</b>?
ConfirmActivateAllOnContract=Esto abrirá todos os servizos (aínda non activos). ¿Está certo de que quere abrir todos os servizos?
ConfirmCloseContract=Esto pechará todos os servizos (activos ou non) ¿Está certo de querer pechar este contrato?
ConfirmCloseService=¿Está certo de querer pechar este servizo en data <b>%s</b>?
ValidateAContract=Validar un contrato
ActivateService=Activar o servizo
ConfirmActivateService=¿Está certo de querer activar este servizo en data <b>%s</b>?
RefContract=Ref. contrato
DateContract=Data contrato
DateServiceActivate=Data activación do servizo
ListOfServices=Listaxe dos servizos
ListOfInactiveServices=Listaxe dos servizos inactivos
ListOfExpiredServices=Listaxe dos servizos activos expirados
ListOfClosedServices=Listaxe dos servizos pechados
ListOfRunningServices=Listaxe de servizos activos
NotActivatedServices=Inactive services (among validated contracts)
BoardNotActivatedServices=Servizos a activar entre os contratos validados
BoardNotActivatedServicesShort=Servizos a activar
LastContracts=Últimos %s contratos
LastModifiedServices=Últimos %s servizos modificados
ContractStartDate=Data de inicio
ContractEndDate=Data de fin
DateStartPlanned=Data prevista posta en servizo
DateStartPlannedShort=Data inicio prevista
DateEndPlanned=Data prevista fin do servizo
DateEndPlannedShort=Data fin prevista
DateStartReal=Data real posta en servizo
DateStartRealShort=Data inicio
DateEndReal=Data real fin do servizo
DateEndRealShort=Data real finalización
CloseService=Finalizar servizo
BoardRunningServices=Servizos activos expirados
BoardRunningServicesShort=Servizos activos
BoardExpiredServices=Servicios expirados
BoardExpiredServicesShort=Servizos expirados
ServiceStatus=Estado do servizo
DraftContracts=Contratos borrador
CloseRefusedBecauseOneServiceActive=Contract can't be closed as there is at least one open service on it
ActivateAllContracts=Activar todas as liñas do contrato
CloseAllContracts=Pechar todos as liñas do contrato
DeleteContractLine=Eliminar liña de contrato
ConfirmDeleteContractLine=¿Está certo de querer eliminar esta líña do contrato de servizo?
MoveToAnotherContract=Mover o servizo a outro contrato deste tercero.
ConfirmMoveToAnotherContract=He elegido el contrato y confirmo el cambio de servizo en el presente contrato.
ConfirmMoveToAnotherContractQuestion=Elija cualquier otro contrato del mismo tercero, ¿desea mover este servizo?
PaymentRenewContractId=Renovación servizo (número %s)
ExpiredSince=Expirado dende o
NoExpiredServices=Sen servizos activos expirados
ListOfServicesToExpireWithDuration=Listaxe de servizos activos a expirar en %s días
ListOfServicesToExpireWithDurationNeg=Listaxe de servizos expirados mais de %s días
ListOfServicesToExpire=Listaxe de servizos activos a expirar
NoteListOfYourExpiredServices=Esta listaxe só contén os servizos de contratos de terceiros dos que vostede é comercial
StandardContractsTemplate=Modelo de contrato estandar
ContactNameAndSignature=Para %s, nome e sinatura:
OnlyLinesWithTypeServiceAreUsed=Solo serán clonadas as liñas dotipo "Servizo"
ConfirmCloneContract=¿Está certo de querer copiar o contrato <b>%s</b>?
LowerDateEndPlannedShort=A data de finalización planificada é anterior aos servizos activos
SendContractRef=Información do contrato __REF__
OtherContracts=Outros contratos
##### Types de contacts #####
TypeContact_contrat_internal_SALESREPSIGN=Comercial asinante do contrato
TypeContact_contrat_internal_SALESREPFOLL=Comercial de rastrexo do contrato
TypeContact_contrat_external_BILLING=Contacto cliente de facturación do contrato
TypeContact_contrat_external_CUSTOMER=Contacto cliente rastrexo do contrato
TypeContact_contrat_external_SALESREPSIGN=Contacto cliente asinante do contrato
HideClosedServiceByDefault=Ocultar servizos pechados por defecto
ShowClosedServices=Amosar servizos pechados
HideClosedServices=Ocultar servizos pechados
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//
#import <Assistant/AFAssistantPane.h>
@class CALearnMoreSheetWindowController, NSBox, NSButton, NSImageView, NSObjectController, NSTextField;
@interface CAExtendedKUExtPane : AFAssistantPane
{
NSObjectController *_panelObjectController;
NSTextField *_caExtKeyUsageExtMessage;
NSImageView *_caLackOfUsageWarningIcon;
NSButton *_SWDevCodeSigningDevCheckBox;
NSButton *_SWDevCodeSigningCheckBox;
NSBox *_caSettingsBox;
CALearnMoreSheetWindowController *_learnMoreWindowController;
}
- (void)_doSheet:(id)arg1;
- (void)_errorSheetDidEnd:(id)arg1 returnCode:(int)arg2 contextInfo:(void *)arg3;
- (void)_learnMoreClicked:(id)arg1;
- (id)nextPane;
- (BOOL)shouldExitPane:(unsigned int)arg1;
- (void)didEnterPane:(unsigned int)arg1;
- (id)title;
- (void)didExitPane:(unsigned int)arg1;
- (void)willEnterPane:(unsigned int)arg1;
@end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="Cpp Wrapper"
RootNamespace="Cpp Wrapper"
SccProjectName=""
SccLocalPath="">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\include"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="2"
WarningLevel="1"
SuppressStartupBanner="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="$(OutDir)/$(ProjectName)_DBG.lib"
SuppressStartupBanner="TRUE"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"
CommandLine="copy "$(TargetPath)" "$(SolutionDir)\..\..\lib""/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="1033"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="2"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
StringPooling="TRUE"
RuntimeLibrary="2"
BufferSecurityCheck="FALSE"
PrecompiledHeaderFile=".\obj/Cpp Wrapper.pch"
WarningLevel="3"
SuppressStartupBanner="TRUE"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="../lib\il_wrap.lib"
SuppressStartupBanner="TRUE"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"
CommandLine="copy "$(TargetPath)" "$(SolutionDir)\..\..\lib""/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="1033"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Dynamic|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="2"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="2"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
StringPooling="TRUE"
RuntimeLibrary="2"
BufferSecurityCheck="FALSE"
WarningLevel="3"
SuppressStartupBanner="TRUE"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"
CommandLine="copy "$(TargetPath)" "$(SolutionDir)\..\..\lib""/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="1033"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
<File
RelativePath="il_wrap.cpp">
<FileConfiguration
Name="Release|Win32">
<Tool
Name="VCCLCompilerTool"
Optimization="2"
PreprocessorDefinitions=""/>
</FileConfiguration>
<FileConfiguration
Name="Dynamic|Win32">
<Tool
Name="VCCLCompilerTool"
Optimization="2"
PreprocessorDefinitions=""/>
</FileConfiguration>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl">
<File
RelativePath="..\include\il\il_wrap.h">
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
| {
"pile_set_name": "Github"
} |
# Addons
Addons are dynamically linked shared objects. They can provide glue to C and
C++ libraries. The API (at the moment) is rather complex, involving
knowledge of several libraries:
- V8 JavaScript, a C++ library. Used for interfacing with JavaScript:
creating objects, calling functions, etc. Documented mostly in the
`v8.h` header file (`deps/v8/include/v8.h` in the Node source
tree), which is also available
[online](http://izs.me/v8-docs/main.html).
- [libuv](https://github.com/joyent/libuv), C event loop library.
Anytime one needs to wait for a file descriptor to become readable,
wait for a timer, or wait for a signal to be received one will need
to interface with libuv. That is, if you perform any I/O, libuv will
need to be used.
- Internal Node libraries. Most importantly is the `node::ObjectWrap`
class which you will likely want to derive from.
- Others. Look in `deps/` for what else is available.
Node statically compiles all its dependencies into the executable.
When compiling your module, you don't need to worry about linking to
any of these libraries.
All of the following examples are available for
[download](https://github.com/rvagg/node-addon-examples) and may be
used as a starting-point for your own Addon.
## Hello world
To get started let's make a small Addon which is the C++ equivalent of
the following JavaScript code:
module.exports.hello = function() { return 'world'; };
First we create a file `hello.cc`:
// hello.cc
#include <node.h>
using namespace v8;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}
void init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "hello", Method);
}
NODE_MODULE(addon, init)
Note that all Node addons must export an initialization function:
void Initialize (Handle<Object> exports);
NODE_MODULE(module_name, Initialize)
There is no semi-colon after `NODE_MODULE` as it's not a function (see
`node.h`).
The `module_name` needs to match the filename of the final binary (minus the
.node suffix).
The source code needs to be built into `addon.node`, the binary Addon. To
do this we create a file called `binding.gyp` which describes the configuration
to build your module in a JSON-like format. This file gets compiled by
[node-gyp](https://github.com/TooTallNate/node-gyp).
{
"targets": [
{
"target_name": "addon",
"sources": [ "hello.cc" ]
}
]
}
The next step is to generate the appropriate project build files for the
current platform. Use `node-gyp configure` for that.
Now you will have either a `Makefile` (on Unix platforms) or a `vcxproj` file
(on Windows) in the `build/` directory. Next invoke the `node-gyp build`
command.
Now you have your compiled `.node` bindings file! The compiled bindings end up
in `build/Release/`.
You can now use the binary addon in a Node project `hello.js` by pointing
`require` to the recently built `hello.node` module:
// hello.js
var addon = require('./build/Release/addon');
console.log(addon.hello()); // 'world'
Please see patterns below for further information or
<https://github.com/arturadib/node-qt> for an example in production.
## Addon patterns
Below are some addon patterns to help you get started. Consult the online
[v8 reference](http://izs.me/v8-docs/main.html) for help with the various v8
calls, and v8's [Embedder's Guide](http://code.google.com/apis/v8/embed.html)
for an explanation of several concepts used such as handles, scopes,
function templates, etc.
In order to use these examples you need to compile them using `node-gyp`.
Create the following `binding.gyp` file:
{
"targets": [
{
"target_name": "addon",
"sources": [ "addon.cc" ]
}
]
}
In cases where there is more than one `.cc` file, simply add the file name to
the `sources` array, e.g.:
"sources": ["addon.cc", "myexample.cc"]
Now that you have your `binding.gyp` ready, you can configure and build the
addon:
$ node-gyp configure build
### Function arguments
The following pattern illustrates how to read arguments from JavaScript
function calls and return a result. This is the main and only needed source
`addon.cc`:
// addon.cc
#include <node.h>
using namespace v8;
void Add(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 2) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong number of arguments")));
return;
}
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
double value = args[0]->NumberValue() + args[1]->NumberValue();
Local<Number> num = Number::New(isolate, value);
args.GetReturnValue().Set(num);
}
void Init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "add", Add);
}
NODE_MODULE(addon, Init)
You can test it with the following JavaScript snippet:
// test.js
var addon = require('./build/Release/addon');
console.log( 'This should be eight:', addon.add(3,5) );
### Callbacks
You can pass JavaScript functions to a C++ function and execute them from
there. Here's `addon.cc`:
// addon.cc
#include <node.h>
using namespace v8;
void RunCallback(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<Function> cb = Local<Function>::Cast(args[0]);
const unsigned argc = 1;
Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") };
cb->Call(isolate->GetCurrentContext()->Global(), argc, argv);
}
void Init(Handle<Object> exports, Handle<Object> module) {
NODE_SET_METHOD(module, "exports", RunCallback);
}
NODE_MODULE(addon, Init)
Note that this example uses a two-argument form of `Init()` that receives
the full `module` object as the second argument. This allows the addon
to completely overwrite `exports` with a single function instead of
adding the function as a property of `exports`.
To test it run the following JavaScript snippet:
// test.js
var addon = require('./build/Release/addon');
addon(function(msg){
console.log(msg); // 'hello world'
});
### Object factory
You can create and return new objects from within a C++ function with this
`addon.cc` pattern, which returns an object with property `msg` that echoes
the string passed to `createObject()`:
// addon.cc
#include <node.h>
using namespace v8;
void CreateObject(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<Object> obj = Object::New(isolate);
obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString());
args.GetReturnValue().Set(obj);
}
void Init(Handle<Object> exports, Handle<Object> module) {
NODE_SET_METHOD(module, "exports", CreateObject);
}
NODE_MODULE(addon, Init)
To test it in JavaScript:
// test.js
var addon = require('./build/Release/addon');
var obj1 = addon('hello');
var obj2 = addon('world');
console.log(obj1.msg+' '+obj2.msg); // 'hello world'
### Function factory
This pattern illustrates how to create and return a JavaScript function that
wraps a C++ function:
// addon.cc
#include <node.h>
using namespace v8;
void MyFunction(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
}
void CreateFunction(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
Local<Function> fn = tpl->GetFunction();
// omit this to make it anonymous
fn->SetName(String::NewFromUtf8(isolate, "theFunction"));
args.GetReturnValue().Set(fn);
}
void Init(Handle<Object> exports, Handle<Object> module) {
NODE_SET_METHOD(module, "exports", CreateFunction);
}
NODE_MODULE(addon, Init)
To test:
// test.js
var addon = require('./build/Release/addon');
var fn = addon();
console.log(fn()); // 'hello world'
### Wrapping C++ objects
Here we will create a wrapper for a C++ object/class `MyObject` that can be
instantiated in JavaScript through the `new` operator. First prepare the main
module `addon.cc`:
// addon.cc
#include <node.h>
#include "myobject.h"
using namespace v8;
void InitAll(Handle<Object> exports) {
MyObject::Init(exports);
}
NODE_MODULE(addon, InitAll)
Then in `myobject.h` make your wrapper inherit from `node::ObjectWrap`:
// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <node.h>
#include <node_object_wrap.h>
class MyObject : public node::ObjectWrap {
public:
static void Init(v8::Handle<v8::Object> exports);
private:
explicit MyObject(double value = 0);
~MyObject();
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Persistent<v8::Function> constructor;
double value_;
};
#endif
And in `myobject.cc` implement the various methods that you want to expose.
Here we expose the method `plusOne` by adding it to the constructor's
prototype:
// myobject.cc
#include "myobject.h"
using namespace v8;
Persistent<Function> MyObject::constructor;
MyObject::MyObject(double value) : value_(value) {
}
MyObject::~MyObject() {
}
void MyObject::Init(Handle<Object> exports) {
Isolate* isolate = Isolate::GetCurrent();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "MyObject"),
tpl->GetFunction());
}
void MyObject::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
MyObject* obj = new MyObject(value);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
}
void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
obj->value_ += 1;
args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}
Test it with:
// test.js
var addon = require('./build/Release/addon');
var obj = new addon.MyObject(10);
console.log( obj.plusOne() ); // 11
console.log( obj.plusOne() ); // 12
console.log( obj.plusOne() ); // 13
### Factory of wrapped objects
This is useful when you want to be able to create native objects without
explicitly instantiating them with the `new` operator in JavaScript, e.g.
var obj = addon.createObject();
// instead of:
// var obj = new addon.Object();
Let's register our `createObject` method in `addon.cc`:
// addon.cc
#include <node.h>
#include "myobject.h"
using namespace v8;
void CreateObject(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
MyObject::NewInstance(args);
}
void InitAll(Handle<Object> exports, Handle<Object> module) {
MyObject::Init();
NODE_SET_METHOD(module, "exports", CreateObject);
}
NODE_MODULE(addon, InitAll)
In `myobject.h` we now introduce the static method `NewInstance` that takes
care of instantiating the object (i.e. it does the job of `new` in JavaScript):
// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <node.h>
#include <node_object_wrap.h>
class MyObject : public node::ObjectWrap {
public:
static void Init();
static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
private:
explicit MyObject(double value = 0);
~MyObject();
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Persistent<v8::Function> constructor;
double value_;
};
#endif
The implementation is similar to the above in `myobject.cc`:
// myobject.cc
#include <node.h>
#include "myobject.h"
using namespace v8;
Persistent<Function> MyObject::constructor;
MyObject::MyObject(double value) : value_(value) {
}
MyObject::~MyObject() {
}
void MyObject::Init() {
Isolate* isolate = Isolate::GetCurrent();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
constructor.Reset(isolate, tpl->GetFunction());
}
void MyObject::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
MyObject* obj = new MyObject(value);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
}
void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
const unsigned argc = 1;
Handle<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
Local<Object> instance = cons->NewInstance(argc, argv);
args.GetReturnValue().Set(instance);
}
void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
obj->value_ += 1;
args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}
Test it with:
// test.js
var createObject = require('./build/Release/addon');
var obj = createObject(10);
console.log( obj.plusOne() ); // 11
console.log( obj.plusOne() ); // 12
console.log( obj.plusOne() ); // 13
var obj2 = createObject(20);
console.log( obj2.plusOne() ); // 21
console.log( obj2.plusOne() ); // 22
console.log( obj2.plusOne() ); // 23
### Passing wrapped objects around
In addition to wrapping and returning C++ objects, you can pass them around
by unwrapping them with Node's `node::ObjectWrap::Unwrap` helper function.
In the following `addon.cc` we introduce a function `add()` that can take on two
`MyObject` objects:
// addon.cc
#include <node.h>
#include <node_object_wrap.h>
#include "myobject.h"
using namespace v8;
void CreateObject(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
MyObject::NewInstance(args);
}
void Add(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
args[0]->ToObject());
MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
args[1]->ToObject());
double sum = obj1->value() + obj2->value();
args.GetReturnValue().Set(Number::New(isolate, sum));
}
void InitAll(Handle<Object> exports) {
MyObject::Init();
NODE_SET_METHOD(exports, "createObject", CreateObject);
NODE_SET_METHOD(exports, "add", Add);
}
NODE_MODULE(addon, InitAll)
To make things interesting we introduce a public method in `myobject.h` so we
can probe private values after unwrapping the object:
// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <node.h>
#include <node_object_wrap.h>
class MyObject : public node::ObjectWrap {
public:
static void Init();
static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
inline double value() const { return value_; }
private:
explicit MyObject(double value = 0);
~MyObject();
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Persistent<v8::Function> constructor;
double value_;
};
#endif
The implementation of `myobject.cc` is similar as before:
// myobject.cc
#include <node.h>
#include "myobject.h"
using namespace v8;
Persistent<Function> MyObject::constructor;
MyObject::MyObject(double value) : value_(value) {
}
MyObject::~MyObject() {
}
void MyObject::Init() {
Isolate* isolate = Isolate::GetCurrent();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
constructor.Reset(isolate, tpl->GetFunction());
}
void MyObject::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
MyObject* obj = new MyObject(value);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
}
void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
const unsigned argc = 1;
Handle<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
Local<Object> instance = cons->NewInstance(argc, argv);
args.GetReturnValue().Set(instance);
}
Test it with:
// test.js
var addon = require('./build/Release/addon');
var obj1 = addon.createObject(10);
var obj2 = addon.createObject(20);
var result = addon.add(obj1, obj2);
console.log(result); // 30
| {
"pile_set_name": "Github"
} |
/**
* MUI Angular Container Component
* @module angular/container
*/
import angular from 'angular';
const moduleName = 'mui.container';
angular.module(moduleName, [])
.directive('muiContainer', function() {
return {
restrict: 'AE',
template: '<div class="mui-container"></div>',
transclude: true,
scope: true,
replace: true,
link: function(scope, element, attrs, controller, transcludeFn) {
// use transcludeFn to pass ng-controller on parent element
transcludeFn(scope, function(clone) {
element.append(clone);
});
// handle fluid containers
if (!angular.isUndefined(attrs.fluid)){
element.removeClass('mui-container').addClass('mui-container-fluid');
}
}
};
});
/** Define module API */
export default moduleName;
| {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package v1beta1
import (
"context"
time "time"
rbacv1beta1 "k8s.io/api/rbac/v1beta1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
watch "k8s.io/apimachinery/pkg/watch"
internalinterfaces "k8s.io/client-go/informers/internalinterfaces"
kubernetes "k8s.io/client-go/kubernetes"
v1beta1 "k8s.io/client-go/listers/rbac/v1beta1"
cache "k8s.io/client-go/tools/cache"
)
// RoleBindingInformer provides access to a shared informer and lister for
// RoleBindings.
type RoleBindingInformer interface {
Informer() cache.SharedIndexInformer
Lister() v1beta1.RoleBindingLister
}
type roleBindingInformer struct {
factory internalinterfaces.SharedInformerFactory
tweakListOptions internalinterfaces.TweakListOptionsFunc
namespace string
}
// NewRoleBindingInformer constructs a new informer for RoleBinding type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredRoleBindingInformer(client, namespace, resyncPeriod, indexers, nil)
}
// NewFilteredRoleBindingInformer constructs a new informer for RoleBinding type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.RbacV1beta1().RoleBindings(namespace).List(context.TODO(), options)
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.RbacV1beta1().RoleBindings(namespace).Watch(context.TODO(), options)
},
},
&rbacv1beta1.RoleBinding{},
resyncPeriod,
indexers,
)
}
func (f *roleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
return NewFilteredRoleBindingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}
func (f *roleBindingInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&rbacv1beta1.RoleBinding{}, f.defaultInformer)
}
func (f *roleBindingInformer) Lister() v1beta1.RoleBindingLister {
return v1beta1.NewRoleBindingLister(f.Informer().GetIndexer())
}
| {
"pile_set_name": "Github"
} |
/// Copyright (C) 2012-2014 Soomla 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.
using UnityEngine;
using System.Collections;
namespace Soomla.Store {
/// <summary>
/// A <c>SingleUsePackVG</c> is just a bundle of <c>SingleUseVG</c>s.
/// This kind of virtual good can be used to let your users buy more than one <c>SingleUseVG</c> at once.
///
/// The <c>SingleUsePackVG</c>'s characteristics are:
/// 1. Can be purchased an unlimited number of times.
/// 2. Doesn't have a balance in the database. The <c>SingleUseVG</c> that's associated with this pack
/// has its own balance. When your users buy a <c>SingleUsePackVG</c>, the balance of the associated
/// <c>SingleUseVG</c> goes up in the amount that this pack represents.
///
/// Real Game Examples: 'Box Of Chocolates', '10 Swords'
///
/// NOTE: In case you want this item to be available for purchase in the market (PurchaseWithMarket),
/// you will need to define the item in the market (Apple App Store, Google Play, Amazon App Store, etc...).
///
/// Inheritance: SingleUsePackVG >
/// <see cref="com.soomla.store.domain.virtualGoods.VirtualGood"/> >
/// <see cref="com.soomla.store.domain.PurchasableVirtualItem"/> >
/// <see cref="com.soomla.store.domain.VirtualItem"/>
/// </summary>
public class SingleUsePackVG : VirtualGood {
private static string TAG = "SOOMLA SingleUsePackVG";
/// <summary>
/// The itemId of the <c>VirtualGood</c> associated with the pack.
/// </summary>
public string GoodItemId;
/// <summary>
/// The amount of instances of the associated virtual good.
/// </summary>
public int GoodAmount;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="goodItemId">The itemId of the <c>SingleUseVG</c> associated with this pack.</param>
/// <param name="amount">The number of <c>SingleUseVG</c>S in the pack.</param>
/// <param name="name">Name.</param>
/// <param name="description">Description.</param>
/// <param name="itemId">Item id.</param>
/// <param name="purchaseType">Purchase type.</param>
public SingleUsePackVG(string goodItemId, int amount, string name, string description, string itemId, PurchaseType purchaseType)
: base(name, description, itemId, purchaseType)
{
this.GoodItemId = goodItemId;
this.GoodAmount = amount;
}
#if UNITY_WP8 && !UNITY_EDITOR
public SingleUsePackVG(SoomlaWpStore.domain.virtualGoods.SingleUsePackVG wpSingleUsePackVG)
: base(wpSingleUsePackVG)
{
GoodItemId = wpSingleUsePackVG.getGoodItemId();
GoodAmount = wpSingleUsePackVG.getGoodAmount();
}
#endif
/// <summary>
/// see parent.
/// </summary>
public SingleUsePackVG(JSONObject jsonItem)
: base(jsonItem)
{
GoodItemId = jsonItem[StoreJSONConsts.VGP_GOOD_ITEMID].str;
this.GoodAmount = System.Convert.ToInt32(((JSONObject)jsonItem[StoreJSONConsts.VGP_GOOD_AMOUNT]).n);
}
/// <summary>
/// see parent.
/// </summary>
public override JSONObject toJSONObject()
{
JSONObject jsonObject = base.toJSONObject();
jsonObject.AddField(StoreJSONConsts.VGP_GOOD_ITEMID, GoodItemId);
jsonObject.AddField(StoreJSONConsts.VGP_GOOD_AMOUNT, GoodAmount);
return jsonObject;
}
/// <summary>
/// This function gives a curtain amout of <c>VirtualGood</c>s according to the given amount and the amount in the pack.
/// </summary>
/// <param name="amount">amount the amount of the specific item to be given.</param>
/// <param name="notify">notify of change in user's balance of current virtual item.</param>
public override int Give(int amount, bool notify) {
SingleUseVG good = null;
try {
good = (SingleUseVG) StoreInfo.GetItemByItemId(GoodItemId);
} catch (VirtualItemNotFoundException) {
SoomlaUtils.LogError(TAG, "SingleUseVG with itemId: " + GoodItemId + " doesn't exist! Can't give this pack.");
return 0;
}
return VirtualGoodsStorage.Add(good, GoodAmount*amount, notify);
}
/// <summary>
/// This function takes a curtain amout of <c>VirtualGood</c>s according to the given amount and the amount in the pack.
/// </summary>
/// <param name="amount">the amount of the specific item to be taken.</param>
/// <param name="notify">notify of change in user's balance of current virtual item.</param>
public override int Take(int amount, bool notify) {
SingleUseVG good = null;
try {
good = (SingleUseVG) StoreInfo.GetItemByItemId(GoodItemId);
} catch (VirtualItemNotFoundException) {
SoomlaUtils.LogError(TAG, "SingleUseVG with itemId: " + GoodItemId + " doesn't exist! Can't give this pack.");
return 0;
}
return VirtualGoodsStorage.Remove(good, GoodAmount*amount, notify);
}
/// <summary>
/// DON't APPLY FOR A PACK
/// </summary>
public override int ResetBalance(int balance, bool notify) {
// Not supported for SingleUsePackVGs !
SoomlaUtils.LogError(TAG, "Someone tried to reset balance of GoodPack. "
+ "That's not right.");
return 0;
}
/// <summary>
/// DON'T APPLY FOR A PACK
/// </summary>
public override int GetBalance() {
// Not supported for SingleUsePackVGs !
SoomlaUtils.LogError(TAG, "Someone tried to check balance of GoodPack. "
+ "That's not right.");
return 0;
}
protected override bool canBuy() {
return true;
}
}
}
| {
"pile_set_name": "Github"
} |
//Copyright (c) 2006, Adobe Systems Incorporated
//All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. All advertising materials mentioning features or use of this software
// must display the following acknowledgement:
// This product includes software developed by the Adobe Systems Incorporated.
// 4. Neither the name of the Adobe Systems Incorporated 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 ADOBE SYSTEMS INCORPORATED ''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 ADOBE SYSTEMS INCORPORATED 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.
//
// http://www.adobe.com/devnet/xmp/library/eula-xmp-library-java.html
package com.itextpdf.xmp.options;
import com.itextpdf.xmp.XMPError;
import com.itextpdf.xmp.XMPException;
/**
* The property flags are used when properties are fetched from the <code>XMPMeta</code>-object
* and provide more detailed information about the property.
*
* @since 03.07.2006
*/
public final class PropertyOptions extends Options
{
/** */
public static final int NO_OPTIONS = 0x00000000;
/** */
public static final int URI = 0x00000002;
/** */
public static final int HAS_QUALIFIERS = 0x00000010;
/** */
public static final int QUALIFIER = 0x00000020;
/** */
public static final int HAS_LANGUAGE = 0x00000040;
/** */
public static final int HAS_TYPE = 0x00000080;
/** */
public static final int STRUCT = 0x00000100;
/** */
public static final int ARRAY = 0x00000200;
/** */
public static final int ARRAY_ORDERED = 0x00000400;
/** */
public static final int ARRAY_ALTERNATE = 0x00000800;
/** */
public static final int ARRAY_ALT_TEXT = 0x00001000;
/** */
public static final int SCHEMA_NODE = 0x80000000;
/** may be used in the future */
public static final int DELETE_EXISTING = 0x20000000;
/** Updated by iText. Indicates if the property should be writted as a separate node */
public static final int SEPARATE_NODE = 0x40000000;
/**
* Default constructor
*/
public PropertyOptions()
{
// reveal default constructor
}
/**
* Intialization constructor
*
* @param options the initialization options
* @throws XMPException If the options are not valid
*/
public PropertyOptions(int options) throws XMPException
{
super(options);
}
/**
* @return Return whether the property value is a URI. It is serialized to RDF using the
* <tt>rdf:resource</tt> attribute. Not mandatory for URIs, but considered RDF-savvy.
*/
public boolean isURI()
{
return getOption(URI);
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setURI(boolean value)
{
setOption(URI, value);
return this;
}
/**
* @return Return whether the property has qualifiers. These could be an <tt>xml:lang</tt>
* attribute, an <tt>rdf:type</tt> property, or a general qualifier. See the
* introductory discussion of qualified properties for more information.
*/
public boolean getHasQualifiers()
{
return getOption(HAS_QUALIFIERS);
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setHasQualifiers(boolean value)
{
setOption(HAS_QUALIFIERS, value);
return this;
}
/**
* @return Return whether this property is a qualifier for some other property. Note that if the
* qualifier itself has a structured value, this flag is only set for the top node of
* the qualifier's subtree. Qualifiers may have arbitrary structure, and may even have
* qualifiers.
*/
public boolean isQualifier()
{
return getOption(QUALIFIER);
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setQualifier(boolean value)
{
setOption(QUALIFIER, value);
return this;
}
/** @return Return whether this property has an <tt>xml:lang</tt> qualifier. */
public boolean getHasLanguage()
{
return getOption(HAS_LANGUAGE);
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setHasLanguage(boolean value)
{
setOption(HAS_LANGUAGE, value);
return this;
}
/** @return Return whether this property has an <tt>rdf:type</tt> qualifier. */
public boolean getHasType()
{
return getOption(HAS_TYPE);
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setHasType(boolean value)
{
setOption(HAS_TYPE, value);
return this;
}
/** @return Return whether this property contains nested fields. */
public boolean isStruct()
{
return getOption(STRUCT);
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setStruct(boolean value)
{
setOption(STRUCT, value);
return this;
}
/**
* @return Return whether this property is an array. By itself this indicates a general
* unordered array. It is serialized using an <tt>rdf:Bag</tt> container.
*/
public boolean isArray()
{
return getOption(ARRAY);
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setArray(boolean value)
{
setOption(ARRAY, value);
return this;
}
/**
* @return Return whether this property is an ordered array. Appears in conjunction with
* getPropValueIsArray(). It is serialized using an <tt>rdf:Seq</tt> container.
*/
public boolean isArrayOrdered()
{
return getOption(ARRAY_ORDERED);
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setArrayOrdered(boolean value)
{
setOption(ARRAY_ORDERED, value);
return this;
}
/**
* @return Return whether this property is an alternative array. Appears in conjunction with
* getPropValueIsArray(). It is serialized using an <tt>rdf:Alt</tt> container.
*/
public boolean isArrayAlternate()
{
return getOption(ARRAY_ALTERNATE);
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setArrayAlternate(boolean value)
{
setOption(ARRAY_ALTERNATE, value);
return this;
}
/**
* @return Return whether this property is an alt-text array. Appears in conjunction with
* getPropArrayIsAlternate(). It is serialized using an <tt>rdf:Alt</tt> container.
* Each array element is a simple property with an <tt>xml:lang</tt> attribute.
*/
public boolean isArrayAltText()
{
return getOption(ARRAY_ALT_TEXT);
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setArrayAltText(boolean value)
{
setOption(ARRAY_ALT_TEXT, value);
return this;
}
/**
* @param value the value to set
* @return Returns this to enable cascaded options.
*/
/**
* @return Returns whether the SCHEMA_NODE option is set.
*/
public boolean isSchemaNode()
{
return getOption(SCHEMA_NODE);
}
/**
* @param value the option DELETE_EXISTING to set
* @return Returns this to enable cascaded options.
*/
public PropertyOptions setSchemaNode(boolean value)
{
setOption(SCHEMA_NODE, value);
return this;
}
//-------------------------------------------------------------------------- convenience methods
/**
* @return Returns whether the property is of composite type - an array or a struct.
*/
public boolean isCompositeProperty()
{
return (getOptions() & (ARRAY | STRUCT)) > 0;
}
/**
* @return Returns whether the property is of composite type - an array or a struct.
*/
public boolean isSimple()
{
return (getOptions() & (ARRAY | STRUCT)) == 0;
}
/**
* Compares two options set for array compatibility.
*
* @param options other options
* @return Returns true if the array options of the sets are equal.
*/
public boolean equalArrayTypes(PropertyOptions options)
{
return
isArray() == options.isArray() &&
isArrayOrdered() == options.isArrayOrdered() &&
isArrayAlternate() == options.isArrayAlternate() &&
isArrayAltText() == options.isArrayAltText();
}
/**
* Merges the set options of a another options object with this.
* If the other options set is null, this objects stays the same.
* @param options other options
* @throws XMPException If illegal options are provided
*/
public void mergeWith(PropertyOptions options) throws XMPException
{
if (options != null)
{
setOptions(getOptions() | options.getOptions());
}
}
/**
* @return Returns true if only array options are set.
*/
public boolean isOnlyArrayOptions()
{
return (getOptions() &
~(ARRAY | ARRAY_ORDERED | ARRAY_ALTERNATE | ARRAY_ALT_TEXT)) == 0;
}
/**
* @see Options#getValidOptions()
*/
protected int getValidOptions()
{
return
URI |
HAS_QUALIFIERS |
QUALIFIER |
HAS_LANGUAGE |
HAS_TYPE |
STRUCT |
ARRAY |
ARRAY_ORDERED |
ARRAY_ALTERNATE |
ARRAY_ALT_TEXT |
SCHEMA_NODE |
SEPARATE_NODE;
}
/**
* @see Options#defineOptionName(int)
*/
protected String defineOptionName(int option)
{
switch (option)
{
case URI : return "URI";
case HAS_QUALIFIERS : return "HAS_QUALIFIER";
case QUALIFIER : return "QUALIFIER";
case HAS_LANGUAGE : return "HAS_LANGUAGE";
case HAS_TYPE: return "HAS_TYPE";
case STRUCT : return "STRUCT";
case ARRAY : return "ARRAY";
case ARRAY_ORDERED : return "ARRAY_ORDERED";
case ARRAY_ALTERNATE : return "ARRAY_ALTERNATE";
case ARRAY_ALT_TEXT : return "ARRAY_ALT_TEXT";
case SCHEMA_NODE : return "SCHEMA_NODE";
default: return null;
}
}
/**
* Checks that a node not a struct and array at the same time;
* and URI cannot be a struct.
*
* @param options the bitmask to check.
* @throws XMPException Thrown if the options are not consistent.
*/
public void assertConsistency(int options) throws XMPException
{
if ((options & STRUCT) > 0 && (options & ARRAY) > 0)
{
throw new XMPException("IsStruct and IsArray options are mutually exclusive",
XMPError.BADOPTIONS);
}
else if ((options & URI) > 0 && (options & (ARRAY | STRUCT)) > 0)
{
throw new XMPException("Structs and arrays can't have \"value\" options",
XMPError.BADOPTIONS);
}
}
} | {
"pile_set_name": "Github"
} |
#
# Jitsi, the OpenSource Java VoIP and Instant Messaging client.
#
# Copyright @ 2015 Atlassian Pty 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.
#
MINGW_HOME ?= C:/mingw
PRODUCTNAME ?= Jitsi
TARGET_BASENAME ?= cleansweep
TARGET_DIR ?= ../../../../../release/windows/tmp
ifeq ($(wildcard /bin/cygpath.*),/bin/cygpath.exe)
target.dir := $(shell cygpath --mixed "$(TARGET_DIR)")
cygwin.target.dir := $(shell cygpath --unix "$(TARGET_DIR)")
else
target.dir := "$(TARGET_DIR)"
cygwin.target.dir := "$(TARGET_DIR)"
endif
CC = $(MINGW_HOME)/bin/gcc.exe
CPPFLAGS = \
-O2 \
-Wall -Wreturn-type \
-DWINVER=0x0502 -D_WIN32_WINNT=0x0502 \
-I$(target.dir)
LDFLAGS = -mwindows
LIBS = -lshell32
MACHINE = $(shell $(CC) -dumpmachine)
WINDRES = $(MINGW_HOME)/bin/windres.exe
ifneq ("x$(MACHINE)","x")
ifeq ($(wildcard $(MINGW_HOME)/bin/$(MACHINE)-windres.*),$(MINGW_HOME)/bin/$(MACHINE)-windres.exe)
WINDRES = $(MINGW_HOME)/bin/$(MACHINE)-windres.exe
endif
endif
ifdef PACKAGECODE
DEFINE_PACKAGECODE = define PACKAGECODE "$(strip $(PACKAGECODE))"
else
DEFINE_PACKAGECODE = undef PACKAGECODE
endif
$(cygwin.target.dir)/$(TARGET_BASENAME).exe: cleansweep.c $(cygwin.target.dir)/config.h $(cygwin.target.dir)/cleansweep.res
$(CC) $(CPPFLAGS) cleansweep.c $(target.dir)/cleansweep.res $(LDFLAGS) -o $(target.dir)/$(TARGET_BASENAME).exe $(LIBS)
-$(MINGW_HOME)/$(MACHINE)/bin/strip.exe $(target.dir)/$(TARGET_BASENAME).exe
.PHONY: $(cygwin.target.dir)/config.h
$(cygwin.target.dir)/config.h:
-rm.exe -f ../../../../../resources/install/windows/config.h
echo.exe -e '#define PRODUCTNAME "$(PRODUCTNAME)"\n#$(DEFINE_PACKAGECODE)' > $(cygwin.target.dir)/config.h
$(cygwin.target.dir)/cleansweep.res: cleansweep.rc $(cygwin.target.dir)/config.h
$(WINDRES) -I../../../../../resources/install/windows -I$(target.dir) cleansweep.rc -O coff -o $(target.dir)/cleansweep.res
| {
"pile_set_name": "Github"
} |
//
// kvassert.c
// kvdb
//
// Created by DINH Viêt Hoà on 6/1/13.
// Copyright (c) 2013 etpan. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
void assertInternal(const char * filename, unsigned int line, int cond, const char * condString)
{
if (cond) {
return;
}
fprintf(stderr, "%s:%i: assert %s\n", filename, line, condString);
abort();
}
| {
"pile_set_name": "Github"
} |
You've gotten hungry from all the dancing, so you decided to bake a cake.
You tasted the cake. Yummy!
After eating a slice, you start to feel sleepy.
Were all of those ingredients what you thought they were...
Do you:
[Sleep?](../../sleep/marshmallow.md)
[Sing a song?](../../sing-song/sing.md)
[Drink some coffee?](../../coffee/coffee.md)
[Sing a Queen Song about cake and champagne?](../../music/add_music.md)
| {
"pile_set_name": "Github"
} |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using ClearCanvas.Common;
using ClearCanvas.Enterprise.Common;
using ClearCanvas.Enterprise.Core.Imex;
using System.Runtime.Serialization;
using ClearCanvas.Enterprise.Core;
using ClearCanvas.Common.Utilities;
using ClearCanvas.Enterprise.Authentication.Brokers;
namespace ClearCanvas.Enterprise.Authentication.Imex
{
[ExtensionOf(typeof(XmlDataImexExtensionPoint))]
[ImexDataClass("User")]
public class UserImex : XmlEntityImex<User, UserImex.UserData>
{
[DataContract]
public class UserData
{
[DataMember]
public string AccountType;
[DataMember]
public string UserName;
[DataMember]
public string DisplayName;
[DataMember]
public string EmailAddress;
[DataMember]
public DateTime? ValidFrom;
[DataMember]
public DateTime? ValidUntil;
[DataMember]
public bool Enabled;
[DataMember]
public List<string> AuthorityGroups;
}
private readonly AuthenticationSettings _settings = new AuthenticationSettings();
#region Overrides
protected override IList<User> GetItemsForExport(IReadContext context, int firstRow, int maxRows)
{
var where = new UserSearchCriteria();
where.UserName.SortAsc(0);
return context.GetBroker<IUserBroker>().Find(where, new SearchResultPage(firstRow, maxRows));
}
protected override UserData Export(User user, IReadContext context)
{
var data = new UserData();
data.AccountType = user.AccountType.ToString();
data.UserName = user.UserName;
data.DisplayName = user.DisplayName;
data.ValidFrom = user.ValidFrom;
data.ValidUntil = user.ValidUntil;
data.Enabled = user.Enabled;
data.AuthorityGroups = CollectionUtils.Map<AuthorityGroup, string>(
user.AuthorityGroups,
group => group.Name);
return data;
}
protected override void Import(UserData data, IUpdateContext context)
{
var accountType = string.IsNullOrEmpty(data.AccountType)
? UserAccountType.U
: (UserAccountType)Enum.Parse(typeof(UserAccountType), data.AccountType, true);
var info = new UserInfo(accountType, data.UserName, data.DisplayName, data.EmailAddress, data.ValidFrom, data.ValidUntil);
var user = LoadOrCreateUser(info, context);
user.Enabled = data.Enabled;
if (data.AuthorityGroups != null)
{
foreach (var group in data.AuthorityGroups)
{
var where = new AuthorityGroupSearchCriteria();
where.Name.EqualTo(group);
var authGroup = CollectionUtils.FirstElement(context.GetBroker<IAuthorityGroupBroker>().Find(where));
if (authGroup != null)
user.AuthorityGroups.Add(authGroup);
}
}
}
#endregion
private User LoadOrCreateUser(UserInfo info, IPersistenceContext context)
{
User user;
try
{
var criteria = new UserSearchCriteria();
criteria.UserName.EqualTo(info.UserName);
var broker = context.GetBroker<IUserBroker>();
user = broker.FindOne(criteria);
}
catch (EntityNotFoundException)
{
user = User.CreateNewUser(info, _settings.DefaultTemporaryPassword);
context.Lock(user, DirtyState.New);
}
return user;
}
}
}
| {
"pile_set_name": "Github"
} |
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <fstream>
#include <streambuf>
#include <utils.h>
#include <base64.h>
#include "SitesConfig.h"
static std::string ObtainObfuscationKey()
{
std::string out;
try {
std::ifstream f("/etc/machine-id");
out = std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
} catch(std::exception &) {
}
if (out.empty()) {
out = "DummyObfuscationKey";
}
return out;
}
static const std::string &ObfuscationKey()
{
static std::string s_out = ObtainObfuscationKey();
return s_out;
}
static void StringObfuscate(std::string &s)
{
const std::string &key = ObfuscationKey();
std::vector<unsigned char> data;
unsigned char salt_len = (unsigned char)(rand() & 0x7);
data.emplace_back(salt_len ^ ((unsigned char)key[key.size() - 1]));
for (unsigned char i = 0; i < salt_len; ++i) {
data.emplace_back((unsigned char)(rand()&0xff));
}
for (size_t i = 0; i < s.size(); ++i) {
data.emplace_back(((unsigned char)s[i]) ^ ((unsigned char)key[i % key.size()]));
}
s.clear();
if (!data.empty()) {
base64_encode(s, &data[0], data.size());
}
}
static void StringDeobfuscate(std::string &s)
{
const std::string &key = ObfuscationKey();
std::vector<unsigned char> data;
base64_decode(data, s);
s.clear();
if (!data.empty()) {
unsigned char salt_len = ((unsigned char)data[0]) ^ ((unsigned char)key[key.size() - 1]);
if (salt_len <= 7) {
for (size_t i = 0; i + 1 + salt_len < data.size(); ++i) {
s+= (char)(((unsigned char)data[i + 1 + salt_len]) ^ ((unsigned char)key[i % key.size()]));
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool SitesConfig_AppendSubParts(std::vector<std::string> &parts, const std::string &sub)
{
StrExplode(parts, sub, "/");
for (auto it = parts.begin(); it != parts.end(); ) {
if (*it == ".") {
it = parts.erase(it);
} else if (*it == "..") {
if (it == parts.begin()) {
return false;
}
--it;
it = parts.erase(parts.erase(it));
} else {
++it;
}
}
return true;
}
static std::string SitesConfig_TranslateToDir(const std::vector<std::string> &parts)
{
std::string out = InMyConfig("NetRocks/");
for (const auto &part : parts) {
out+= part;
out+= ".sites/";
}
return out;
}
void SitesConfigLocation::Reset()
{
_parts.clear();
}
bool SitesConfigLocation::Change(const std::string &sub)
{
std::vector<std::string> parts = _parts;
if (!SitesConfig_AppendSubParts(parts, sub)) {
return false;
}
struct stat s{};
if (stat(SitesConfig_TranslateToDir(parts).c_str(), &s) != 0) {
return false;
}
_parts.swap(parts);
return true;
}
bool SitesConfigLocation::Make(const std::string &sub)
{
std::vector<std::string> parts = _parts;
if (!SitesConfig_AppendSubParts(parts, sub)) {
return false;
}
const std::string &dir = SitesConfig_TranslateToDir(parts);
struct stat s{};
if (stat(dir.c_str(), &s) != 0) {
if (mkdir(dir.c_str(), 0700) != 0) {
return false;
}
}
return true;
}
bool SitesConfigLocation::Remove(const std::string &sub)
{
SitesConfigLocation tmp = *this;
if (!SitesConfig_AppendSubParts(tmp._parts, sub) || tmp._parts.empty()) {
return false;
}
if (!SitesConfig(tmp).EnumSites().empty()) {
return false;
}
unlink(tmp.TranslateToSitesConfigPath().c_str());
return rmdir(SitesConfig_TranslateToDir(tmp._parts).c_str()) == 0;
}
void SitesConfigLocation::Enum(std::vector<std::string> &children) const
{
DIR *d = opendir(SitesConfig_TranslateToDir(_parts).c_str());
if (d) {
for (;;) {
struct dirent *de = readdir(d);
if (!de) break;
const size_t l = strlen(de->d_name);
if (l > 6 && memcmp(de->d_name + l - 6, ".sites", 6) == 0) {
children.emplace_back(de->d_name, l - 6);
}
}
closedir(d);
}
}
std::string SitesConfigLocation::TranslateToPath(bool ending_slash) const
{
std::string out;
for (const auto &part : _parts) {
out+= part;
out+= '/';
}
if (!ending_slash && !out.empty()) {
out.resize(out.size() - 1);
}
return out;
}
std::string SitesConfigLocation::TranslateToSitesConfigPath() const
{
std::string out = SitesConfig_TranslateToDir(_parts);
out+= "sites.cfg";
return out;
}
bool SitesConfigLocation::Transfer(SitesConfigLocation &dst, const std::string &sub, bool mv)
{
std::vector<std::string> parts = _parts;
if (!SitesConfig_AppendSubParts(parts, sub) || parts.empty()) {
return false;
}
std::string src_arg = SitesConfig_TranslateToDir(parts);
src_arg.resize(src_arg.size() - 1); // remove slash
src_arg = EscapeCmdStr(src_arg);
const std::string &dst_arg = EscapeCmdStr(SitesConfig_TranslateToDir(dst._parts));
std::string cmd;
if (mv) {
cmd = StrPrintf("mv -f \"%s\" \"%s\" >/dev/null 2>&1", src_arg.c_str(), dst_arg.c_str());
} else {
cmd = StrPrintf("cp -R -f \"%s\" \"%s\" >/dev/null 2>&1", src_arg.c_str(), dst_arg.c_str());
}
fprintf(stderr, "SitesConfigLocation::Transfer: %s\n", cmd.c_str());
return system(cmd.c_str()) == 0;
}
///
SiteSpecification::SiteSpecification(const std::string &s)
{
size_t p = s.rfind('/');
if (p == std::string::npos) {
site = s;
} else if (!sites_cfg_location.Change(s.substr(0, p))) {
fprintf(stderr, "SiteSpecification('%s') - bad config location\n", s.c_str());
site.clear();
} else {
site = s.substr(p + 1, s.size() - p - 1);
}
}
std::string SiteSpecification::ToString() const
{
if (!IsValid()) {
return std::string();
}
std::string out = sites_cfg_location.TranslateToPath(true);
out+= site;
return out;
}
///
SitesConfig::SitesConfig(const SitesConfigLocation &sites_cfg_location)
: KeyFileHelper(sites_cfg_location.TranslateToSitesConfigPath().c_str())
{
}
std::string SitesConfig::GetProtocol(const std::string &site)
{
return GetString(site.c_str(), "Protocol");
}
void SitesConfig::PutProtocol(const std::string &site, const std::string &value)
{
PutString(site.c_str(), "Protocol", value.c_str());
}
std::string SitesConfig::GetHost(const std::string &site)
{
return GetString(site.c_str(), "Host");
}
void SitesConfig::PutHost(const std::string &site, const std::string &value)
{
PutString(site.c_str(), "Host", value.c_str());
}
std::string SitesConfig::GetDirectory(const std::string &site)
{
return GetString(site.c_str(), "Directory");
}
void SitesConfig::PutDirectory(const std::string &site, const std::string &value)
{
PutString(site.c_str(), "Directory", value.c_str());
}
unsigned int SitesConfig::GetPort(const std::string &site, unsigned int def)
{
return (unsigned int)GetInt(site.c_str(), "Port", def);
}
void SitesConfig::PutPort(const std::string &site, unsigned int value)
{
PutInt(site.c_str(), "Port", value);
}
unsigned int SitesConfig::GetLoginMode(const std::string &site, unsigned int def)
{
return (unsigned int)GetInt(site.c_str(), "LoginMode", def);
}
void SitesConfig::PutLoginMode(const std::string &site, unsigned int value)
{
PutInt(site.c_str(), "LoginMode", value);
}
std::string SitesConfig::GetUsername(const std::string &site)
{
return GetString(site.c_str(), "Username");
}
void SitesConfig::PutUsername(const std::string &site, const std::string &value)
{
PutString(site.c_str(), "Username", value.c_str());
}
std::string SitesConfig::GetPassword(const std::string &site)
{
std::string s = GetString(site.c_str(), "Password");
StringDeobfuscate(s);
return s;
}
void SitesConfig::PutPassword(const std::string &site, const std::string &value)
{
std::string s(value);
StringObfuscate(s);
PutString(site.c_str(), "Password", s.c_str());
}
std::string SitesConfig::GetProtocolOptions(const std::string &site, const std::string &protocol)
{
return GetString(site.c_str(), std::string("Options_").append(protocol).c_str());
}
void SitesConfig::PutProtocolOptions(const std::string &site, const std::string &protocol, const std::string &options)
{
PutString(site.c_str(), std::string("Options_").append(protocol).c_str(), options.c_str());
}
bool SitesConfig::Transfer(SitesConfig &dst, const std::string &site, bool mv)
{
const auto keys = KeyFileHelper::EnumKeys(site.c_str());
dst.RemoveSection(site.c_str());
for (const auto &key : keys) {
const std::string &value = GetString(site.c_str(), key.c_str());
dst.PutString(site.c_str(), key.c_str(), value.c_str());
}
if (mv) {
RemoveSection(site.c_str());
}
return true;
}
| {
"pile_set_name": "Github"
} |
package volumes
import (
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/pagination"
)
// CreateOptsBuilder allows extensions to add additional parameters to the
// Create request.
type CreateOptsBuilder interface {
ToVolumeCreateMap() (map[string]interface{}, error)
}
// CreateOpts contains options for creating a Volume. This object is passed to
// the volumes.Create function. For more information about these parameters,
// see the Volume object.
type CreateOpts struct {
// The size of the volume, in GB
Size int `json:"size" required:"true"`
// The availability zone
AvailabilityZone string `json:"availability_zone,omitempty"`
// ConsistencyGroupID is the ID of a consistency group
ConsistencyGroupID string `json:"consistencygroup_id,omitempty"`
// The volume description
Description string `json:"description,omitempty"`
// One or more metadata key and value pairs to associate with the volume
Metadata map[string]string `json:"metadata,omitempty"`
// The volume name
Name string `json:"name,omitempty"`
// the ID of the existing volume snapshot
SnapshotID string `json:"snapshot_id,omitempty"`
// SourceReplica is a UUID of an existing volume to replicate with
SourceReplica string `json:"source_replica,omitempty"`
// the ID of the existing volume
SourceVolID string `json:"source_volid,omitempty"`
// The ID of the image from which you want to create the volume.
// Required to create a bootable volume.
ImageID string `json:"imageRef,omitempty"`
// The associated volume type
VolumeType string `json:"volume_type,omitempty"`
}
// ToVolumeCreateMap assembles a request body based on the contents of a
// CreateOpts.
func (opts CreateOpts) ToVolumeCreateMap() (map[string]interface{}, error) {
return gophercloud.BuildRequestBody(opts, "volume")
}
// Create will create a new Volume based on the values in CreateOpts. To extract
// the Volume object from the response, call the Extract method on the
// CreateResult.
func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {
b, err := opts.ToVolumeCreateMap()
if err != nil {
r.Err = err
return
}
_, r.Err = client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{
OkCodes: []int{202},
})
return
}
// DeleteOptsBuilder allows extensions to add additional parameters to the
// Delete request.
type DeleteOptsBuilder interface {
ToVolumeDeleteQuery() (string, error)
}
// DeleteOpts contains options for deleting a Volume. This object is passed to
// the volumes.Delete function.
type DeleteOpts struct {
// Delete all snapshots of this volume as well.
Cascade bool `q:"cascade"`
}
// ToLoadBalancerDeleteQuery formats a DeleteOpts into a query string.
func (opts DeleteOpts) ToVolumeDeleteQuery() (string, error) {
q, err := gophercloud.BuildQueryString(opts)
return q.String(), err
}
// Delete will delete the existing Volume with the provided ID.
func Delete(client *gophercloud.ServiceClient, id string, opts DeleteOptsBuilder) (r DeleteResult) {
url := deleteURL(client, id)
if opts != nil {
query, err := opts.ToVolumeDeleteQuery()
if err != nil {
r.Err = err
return
}
url += query
}
_, r.Err = client.Delete(url, nil)
return
}
// Get retrieves the Volume with the provided ID. To extract the Volume object
// from the response, call the Extract method on the GetResult.
func Get(client *gophercloud.ServiceClient, id string) (r GetResult) {
_, r.Err = client.Get(getURL(client, id), &r.Body, nil)
return
}
// ListOptsBuilder allows extensions to add additional parameters to the List
// request.
type ListOptsBuilder interface {
ToVolumeListQuery() (string, error)
}
// ListOpts holds options for listing Volumes. It is passed to the volumes.List
// function.
type ListOpts struct {
// AllTenants will retrieve volumes of all tenants/projects.
AllTenants bool `q:"all_tenants"`
// Metadata will filter results based on specified metadata.
Metadata map[string]string `q:"metadata"`
// Name will filter by the specified volume name.
Name string `q:"name"`
// Status will filter by the specified status.
Status string `q:"status"`
// TenantID will filter by a specific tenant/project ID.
// Setting AllTenants is required for this.
TenantID string `q:"project_id"`
// Comma-separated list of sort keys and optional sort directions in the
// form of <key>[:<direction>].
Sort string `q:"sort"`
// Requests a page size of items.
Limit int `q:"limit"`
// Used in conjunction with limit to return a slice of items.
Offset int `q:"offset"`
// The ID of the last-seen item.
Marker string `q:"marker"`
}
// ToVolumeListQuery formats a ListOpts into a query string.
func (opts ListOpts) ToVolumeListQuery() (string, error) {
q, err := gophercloud.BuildQueryString(opts)
return q.String(), err
}
// List returns Volumes optionally limited by the conditions provided in ListOpts.
func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
url := listURL(client)
if opts != nil {
query, err := opts.ToVolumeListQuery()
if err != nil {
return pagination.Pager{Err: err}
}
url += query
}
return pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {
return VolumePage{pagination.LinkedPageBase{PageResult: r}}
})
}
// UpdateOptsBuilder allows extensions to add additional parameters to the
// Update request.
type UpdateOptsBuilder interface {
ToVolumeUpdateMap() (map[string]interface{}, error)
}
// UpdateOpts contain options for updating an existing Volume. This object is passed
// to the volumes.Update function. For more information about the parameters, see
// the Volume object.
type UpdateOpts struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
// ToVolumeUpdateMap assembles a request body based on the contents of an
// UpdateOpts.
func (opts UpdateOpts) ToVolumeUpdateMap() (map[string]interface{}, error) {
return gophercloud.BuildRequestBody(opts, "volume")
}
// Update will update the Volume with provided information. To extract the updated
// Volume from the response, call the Extract method on the UpdateResult.
func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) (r UpdateResult) {
b, err := opts.ToVolumeUpdateMap()
if err != nil {
r.Err = err
return
}
_, r.Err = client.Put(updateURL(client, id), b, &r.Body, &gophercloud.RequestOpts{
OkCodes: []int{200},
})
return
}
// IDFromName is a convienience function that returns a server's ID given its name.
func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) {
count := 0
id := ""
listOpts := ListOpts{
Name: name,
}
pages, err := List(client, listOpts).AllPages()
if err != nil {
return "", err
}
all, err := ExtractVolumes(pages)
if err != nil {
return "", err
}
for _, s := range all {
if s.Name == name {
count++
id = s.ID
}
}
switch count {
case 0:
return "", gophercloud.ErrResourceNotFound{Name: name, ResourceType: "volume"}
case 1:
return id, nil
default:
return "", gophercloud.ErrMultipleResourcesFound{Name: name, Count: count, ResourceType: "volume"}
}
}
| {
"pile_set_name": "Github"
} |
# unpipe
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-image]][node-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Unpipe a stream from all destinations.
## Installation
```sh
$ npm install unpipe
```
## API
```js
var unpipe = require('unpipe')
```
### unpipe(stream)
Unpipes all destinations from a given stream. With stream 2+, this is
equivalent to `stream.unpipe()`. When used with streams 1 style streams
(typically Node.js 0.8 and below), this module attempts to undo the
actions done in `stream.pipe(dest)`.
## License
[MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/unpipe.svg
[npm-url]: https://npmjs.org/package/unpipe
[node-image]: https://img.shields.io/node/v/unpipe.svg
[node-url]: http://nodejs.org/download/
[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg
[travis-url]: https://travis-ci.org/stream-utils/unpipe
[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg
[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master
[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg
[downloads-url]: https://npmjs.org/package/unpipe
| {
"pile_set_name": "Github"
} |
BOARDNAME:=Generic
DEFAULT_PACKAGES+= wpad-mini
define Target/Description
Build firmware images for ixp4xx based boards that boot from internal flash
(e.g : Linksys NSLU2, ...)
endef
| {
"pile_set_name": "Github"
} |
<?php
/**
* This file was generated by phpSPO model generator 2019-10-12T19:39:07+00:00 16.0.19402.12016
*/
namespace Office365\SharePoint\Microfeed;
use Office365\Runtime\ClientValue;
class MicrofeedThread extends ClientValue
{
/**
* @var bool
*/
public $CanFollowUp;
/**
* @var bool
*/
public $CanHaveAttachments;
/**
* @var bool
*/
public $CanLike;
/**
* @var bool
*/
public $CanReply;
/**
* @var array
*/
public $DataLinks;
/**
* @var integer
*/
public $DefinitionId;
/**
* @var string
*/
public $DefinitionName;
/**
* @var string
*/
public $Identifier;
/**
* @var bool
*/
public $Locked;
/**
* @var array
*/
public $MicrofeedEntities;
/**
* @var integer
*/
public $OwnerIndex;
public $RefReply;
public $RefRoot;
/**
* @var bool
*/
public $RenderPostAuthorImage;
public $Replies;
/**
* @var integer
*/
public $ReplyCount;
public $RootPost;
/**
* @var bool
*/
public $SmallImageSizePreferred;
/**
* @var integer
*/
public $Status;
} | {
"pile_set_name": "Github"
} |
#include "evlist.h"
#include "evsel.h"
#include "parse-events.h"
#include "tests.h"
static int perf_evsel__roundtrip_cache_name_test(void)
{
char name[128];
int type, op, err = 0, ret = 0, i, idx;
struct perf_evsel *evsel;
struct perf_evlist *evlist = perf_evlist__new();
if (evlist == NULL)
return -ENOMEM;
for (type = 0; type < PERF_COUNT_HW_CACHE_MAX; type++) {
for (op = 0; op < PERF_COUNT_HW_CACHE_OP_MAX; op++) {
/* skip invalid cache type */
if (!perf_evsel__is_cache_op_valid(type, op))
continue;
for (i = 0; i < PERF_COUNT_HW_CACHE_RESULT_MAX; i++) {
__perf_evsel__hw_cache_type_op_res_name(type, op, i,
name, sizeof(name));
err = parse_events(evlist, name);
if (err)
ret = err;
}
}
}
idx = 0;
evsel = perf_evlist__first(evlist);
for (type = 0; type < PERF_COUNT_HW_CACHE_MAX; type++) {
for (op = 0; op < PERF_COUNT_HW_CACHE_OP_MAX; op++) {
/* skip invalid cache type */
if (!perf_evsel__is_cache_op_valid(type, op))
continue;
for (i = 0; i < PERF_COUNT_HW_CACHE_RESULT_MAX; i++) {
__perf_evsel__hw_cache_type_op_res_name(type, op, i,
name, sizeof(name));
if (evsel->idx != idx)
continue;
++idx;
if (strcmp(perf_evsel__name(evsel), name)) {
pr_debug("%s != %s\n", perf_evsel__name(evsel), name);
ret = -1;
}
evsel = perf_evsel__next(evsel);
}
}
}
perf_evlist__delete(evlist);
return ret;
}
static int __perf_evsel__name_array_test(const char *names[], int nr_names)
{
int i, err;
struct perf_evsel *evsel;
struct perf_evlist *evlist = perf_evlist__new();
if (evlist == NULL)
return -ENOMEM;
for (i = 0; i < nr_names; ++i) {
err = parse_events(evlist, names[i]);
if (err) {
pr_debug("failed to parse event '%s', err %d\n",
names[i], err);
goto out_delete_evlist;
}
}
err = 0;
list_for_each_entry(evsel, &evlist->entries, node) {
if (strcmp(perf_evsel__name(evsel), names[evsel->idx])) {
--err;
pr_debug("%s != %s\n", perf_evsel__name(evsel), names[evsel->idx]);
}
}
out_delete_evlist:
perf_evlist__delete(evlist);
return err;
}
#define perf_evsel__name_array_test(names) \
__perf_evsel__name_array_test(names, ARRAY_SIZE(names))
int test__perf_evsel__roundtrip_name_test(void)
{
int err = 0, ret = 0;
err = perf_evsel__name_array_test(perf_evsel__hw_names);
if (err)
ret = err;
err = perf_evsel__name_array_test(perf_evsel__sw_names);
if (err)
ret = err;
err = perf_evsel__roundtrip_cache_name_test();
if (err)
ret = err;
return ret;
}
| {
"pile_set_name": "Github"
} |
namespace CSharpGL
{
/// <summary>
/// uniform mat4 variable;
/// </summary>
public class UniformMat4 : UniformSingleVariable<mat4>
{
/// <summary>
/// uniform mat4 variable;
/// </summary>
/// <param name="varName"></param>
public UniformMat4(string varName) : base(varName) { }
/// <summary>
/// uniform mat4 variable;
/// </summary>
/// <param name="varName"></param>
/// <param name="value"></param>
public UniformMat4(string varName, mat4 value) : base(varName, value) { }
/// <summary>
///
/// </summary>
/// <param name="program"></param>
protected override void DoSetUniform(ShaderProgram program)
{
this.Location = program.glUniformMatrix4(VarName, this.value.ToArray());
this.Updated = false;
}
}
} | {
"pile_set_name": "Github"
} |
namespace Server.Items
{
public class QuiverOfLightning : ElvenQuiver
{
public override bool IsArtifact => true;
[Constructable]
public QuiverOfLightning()
: base()
{
Hue = 0x4F9;
}
public QuiverOfLightning(Serial serial)
: base(serial)
{
}
public override int LabelNumber => 1073112;// Quiver of Lightning
public override void AlterBowDamage(ref int phys, ref int fire, ref int cold, ref int pois, ref int nrgy, ref int chaos, ref int direct)
{
fire = cold = pois = chaos = direct = 0;
phys = nrgy = 50;
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.WriteEncodedInt(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadEncodedInt();
}
}
} | {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.