answer
stringlengths
15
1.25M
// This file is part of the deal.II library. // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // the top level of the deal.II distribution. // test the PETSc CG solver #include "../tests.h" #include "../testmatrix.h" #include <cmath> #include <fstream> #include <iostream> #include <iomanip> #include <deal.II/base/logstream.h> #include <deal.II/lac/petsc_sparse_matrix.h> #include <deal.II/lac/petsc_vector.h> #include <deal.II/lac/petsc_solver.h> #include <deal.II/lac/petsc_precondition.h> #include <deal.II/lac/vector_memory.h> #include <typeinfo> template<typename SolverType, typename MatrixType, typename VectorType, class PRECONDITION> void check_solve(SolverType &solver, const SolverControl &solver_control, const MatrixType &A, VectorType &u, VectorType &f, const PRECONDITION &P) { deallog << "Solver type: " << typeid(solver).name() << std::endl; u = 0.; f = 1.; try { solver.solve(A,u,f,P); } catch (std::exception &e) { deallog << e.what() << std::endl; abort (); } deallog << "Solver stopped after " << solver_control.last_step() << " iterations" << std::endl; } int main(int argc, char **argv) { std::ofstream logfile("output"); deallog.attach(logfile); deallog << std::setprecision(4); deallog.threshold_double(1.e-10); Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1); { SolverControl control(100, 1.e-3); const unsigned int size = 32; unsigned int dim = (size-1)*(size-1); deallog << "Size " << size << " Unknowns " << dim << std::endl; // Make matrix FDMatrix testproblem(size, size); PETScWrappers::SparseMatrix A(dim, dim, 5); testproblem.five_point(A); PETScWrappers::Vector f(dim); PETScWrappers::Vector u(dim); f = 1.; A.compress (VectorOperation::insert); PETScWrappers::SolverCG solver(control); PETScWrappers::PreconditionSOR preconditioner(A); check_solve (solver, control, A,u,f, preconditioner); } }
package org.herac.tuxguitar.gui.util; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.player.base.<API key>; import org.herac.tuxguitar.song.managers.TGSongManager; import org.herac.tuxguitar.song.models.TGMeasureHeader; public class MidiTickUtil { public static long getStart(long tick){ long startPoint = getStartPoint(); long start = startPoint; long length = 0; TGSongManager manager = TuxGuitar.instance().getSongManager(); <API key> controller = new <API key>(manager.getSong(), getSHeader() , getEHeader() ); while(!controller.finished()){ TGMeasureHeader header = manager.getSong().getMeasureHeader(controller.getIndex()); controller.process(); if(controller.shouldPlay()){ start += length; length = header.getLength(); //verifico si es el compas correcto if(tick >= start && tick < (start + length )){ return header.getStart() + (tick - start); } } } return ( tick < startPoint ? startPoint : start ); } public static long getTick(long start){ long startPoint = getStartPoint(); long tick = startPoint; long length = 0; TGSongManager manager = TuxGuitar.instance().getSongManager(); <API key> controller = new <API key>(manager.getSong(), getSHeader() , getEHeader() ); while(!controller.finished()){ TGMeasureHeader header = manager.getSong().getMeasureHeader(controller.getIndex()); controller.process(); if(controller.shouldPlay()){ tick += length; length = header.getLength(); //verifico si es el compas correcto if(start >= header.getStart() && start < (header.getStart() + length )){ return tick; } } } return ( start < startPoint ? startPoint : tick ); } private static long getStartPoint(){ TuxGuitar.instance().getPlayer().updateLoop( false ); return TuxGuitar.instance().getPlayer().getLoopSPosition(); } public static int getSHeader() { return TuxGuitar.instance().getPlayer().getLoopSHeader(); } public static int getEHeader() { return TuxGuitar.instance().getPlayer().getLoopEHeader(); } }
#include <windows.h> #include <tchar.h> #define _MAKE_DLL 1 #undef _export #include "console.h" #include "console_i.h" #include "common.h" #include <memory.h> #include <string.h> #include <ctype.h> #ifndef EOF #define EOF -1 #endif typedef void (*function)(Line ln, int chr); /* edit-function */ static function dispatch_table[256]; /* general dispatch-table */ static function dispatch_meta[256]; /* ESC-char dispatch */ static RlcCompleteFunc <API key> = <API key>; static void init_line_package(RlcData b); static void bind_actions(void); #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #define max(a, b) ((a) > (b) ? (a) : (b)) #endif #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif #ifndef EOS #define EOS 0 #endif #ifndef ESC #define ESC 27 #endif #define COMPLETE_NEWLINE 1 #define COMPLETE_EOF 2 #define ctrl(c) ((c) - '@') #define META_OFFSET 128 #define meta(c) ((c) + META_OFFSET) /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - make_room(Line, int room) Make n-characters space after the point. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ static void make_room(Line ln, size_t room) { while ( ln->size + room + 1 > ln->allocated ) { if ( !ln->data ) { ln->data = rlc_malloc(256 * sizeof(TCHAR)); ln->allocated = 256; } else { ln->allocated *= 2; ln->data = rlc_realloc(ln->data, ln->allocated * sizeof(TCHAR)); } } memmove(&ln->data[ln->point + room], &ln->data[ln->point], (ln->size - ln->point)*sizeof(TCHAR)); ln->size += room; if ( room > 0 ) ln->change_start = min(ln->change_start, ln->point); } static void set_line(Line ln, const TCHAR *s) { size_t len = _tcslen(s); ln->size = ln->point = 0; make_room(ln, len); _tcsncpy(ln->data, s, len); } static void terminate(Line ln) { if ( !ln->data ) { ln->data = rlc_malloc(sizeof(TCHAR)); ln->allocated = 1; } ln->data[ln->size] = EOS; } static void delete(Line ln, size_t from, size_t len) { if ( from < 0 || from > ln->size || len < 0 || from + len > ln->size ) return; _tcsncpy(&ln->data[from], &ln->data[from+len], ln->size - (from+len)); ln->size -= len; } static size_t back_word(Line ln, size_t from) { from = min(from, ln->size); from = max(0, from); if ( ln->data ) { while(!rlc_is_word_char(ln->data[from-1]) && from > 0 ) from while(rlc_is_word_char(ln->data[from-1]) && from > 0 ) from } return from; } static size_t forw_word(Line ln, size_t from) { from = min(from, ln->size); from = max(0, from); if ( ln->data ) { while(!rlc_is_word_char(ln->data[from]) && from < ln->size ) from++; while(rlc_is_word_char(ln->data[from]) && from < ln->size ) from++; } return from; } static __inline void changed(Line ln, size_t from) { ln->change_start = min(ln->change_start, from); } static void insert_self(Line ln, int chr) { make_room(ln, 1); ln->data[ln->point++] = chr; } static void <API key>(Line ln, int chr) { if ( ln->point > 0 ) { memmove(&ln->data[ln->point-1], &ln->data[ln->point], (ln->size - ln->point)*sizeof(TCHAR)); ln->size ln->point } changed(ln, ln->point); } static void delete_character(Line ln, int chr) { if ( ln->point < ln->size ) { ln->point++; <API key>(ln, chr); } } static void backward_character(Line ln, int chr) { if ( ln->point > 0 ) ln->point } static void forward_character(Line ln, int chr) { if ( ln->point < ln->size ) ln->point++; } static void backward_word(Line ln, int chr) { ln->point = back_word(ln, ln->point); } static void forward_word(Line ln, int chr) { ln->point = forw_word(ln, ln->point); } static void <API key>(Line ln, int chr) { size_t from = back_word(ln, ln->point); memmove(&ln->data[from], &ln->data[ln->point], (ln->size - ln->point)*sizeof(TCHAR)); ln->size -= ln->point - from; ln->point = from; changed(ln, from); } static void forward_delete_word(Line ln, int chr) { size_t to = forw_word(ln, ln->point); memmove(&ln->data[ln->point], &ln->data[to], (ln->size - to)*sizeof(TCHAR)); ln->size -= to - ln->point; changed(ln, ln->point); } static void transpose_chars(Line ln, int chr) { if ( ln->point > 0 && ln->point < ln->size ) { int c0 = ln->data[ln->point-1]; ln->data[ln->point-1] = ln->data[ln->point]; ln->data[ln->point] = c0; changed(ln, ln->point-1); } } static void start_of_line(Line ln, int chr) { ln->point = 0; } static void end_of_line(Line ln, int chr) { ln->point = ln->size; } static void kill_line(Line ln, int chr) { ln->size = ln->point; changed(ln, ln->size); } static void empty_line(Line ln, int chr) { ln->size = ln->point = 0; changed(ln, 0); } static void enter(Line ln, int chr) { ln->point = ln->size; #ifdef DOS_CRNL make_room(ln, 2); ln->data[ln->point++] = '\r'; ln->data[ln->point++] = '\n'; #else make_room(ln, 1); ln->data[ln->point++] = '\n'; #endif terminate(ln); ln->complete = COMPLETE_NEWLINE; } static void eof(Line ln, int chr) { ln->point = ln->size; terminate(ln); ln->complete = COMPLETE_EOF; } static void <API key>(Line ln, int chr) { if ( ln->size == 0 ) { ln->point = ln->size; terminate(ln); ln->complete = COMPLETE_EOF; } else delete_character(ln, chr); } static void undefined(Line ln, int chr) { } static void interrupt(Line ln, int chr) { raise(SIGINT); } static void add_history(rlc_console c, const TCHAR *data) { const TCHAR *s = data; while(*s && *s <= ' ') s++; if ( *s ) rlc_add_history(c, s); } static void backward_history(Line ln, int chr) { const TCHAR *h; if ( rlc_at_head_history(ln->console) && ln->size > 0 ) { terminate(ln); add_history(ln->console, ln->data); } if ( (h = rlc_bwd_history(ln->console)) ) { set_line(ln, h); ln->point = ln->size; } } static void forward_history(Line ln, int chr) { if ( !rlc_at_head_history(ln->console) ) { const TCHAR *h = rlc_fwd_history(ln->console); if ( h ) { set_line(ln, h); ln->point = ln->size; } } else empty_line(ln, chr); } RlcCompleteFunc rlc_complete_hook(RlcCompleteFunc new) { RlcCompleteFunc old = <API key>; <API key> = new; return old; } static int common(const TCHAR *s1, const TCHAR *s2, int insensitive) { int n = 0; if ( !insensitive ) { while(*s1 && *s1 == *s2) { s1++, s2++; n++; } return n; } else { while(*s1) { if ( _totlower(*s1) == _totlower(*s2) ) { s1++, s2++; n++; } else break; } return n; } } static void complete(Line ln, int chr) { if ( <API key> ) { rlc_complete_data dbuf; RlcCompleteData data = &dbuf; memset(data, 0, sizeof(dbuf)); data->line = ln; data->call_type = COMPLETE_INIT; if ( (*<API key>)(data) ) { TCHAR match[<API key>]; int nmatches = 1; size_t ncommon = _tcslen(data->candidate); size_t patlen = ln->point - data->replace_from; _tcscpy(match, data->candidate); data->call_type = COMPLETE_ENUMERATE; while( (*data->function)(data) ) { ncommon = common(match, data->candidate, data->case_insensitive); match[ncommon] = EOS; nmatches++; } data->call_type = COMPLETE_CLOSE; (*data->function)(data); delete(ln, data->replace_from, patlen); ln->point = data->replace_from; make_room(ln, ncommon); _tcsncpy(&ln->data[data->replace_from], match, ncommon); ln->point += ncommon; if ( nmatches == 1 && data->quote ) insert_self(ln, data->quote); } } } #define <API key> 256 static void list_completions(Line ln, int chr) { if ( <API key> ) { rlc_complete_data dbuf; RlcCompleteData data = &dbuf; memset(data, 0, sizeof(dbuf)); data->line = ln; data->call_type = COMPLETE_INIT; if ( (*<API key>)(data) ) { TCHAR *buf[<API key>]; int n, nmatches = 0; size_t len = _tcslen(data->candidate) + 1; size_t longest = len; size_t cols; buf[nmatches] = rlc_malloc(len*sizeof(TCHAR)); _tcsncpy(buf[nmatches], data->candidate, len); nmatches++; data->call_type = COMPLETE_ENUMERATE; while( (*data->function)(data) ) { len = _tcslen(data->candidate) + 1; buf[nmatches] = rlc_malloc(len*sizeof(TCHAR)); _tcsncpy(buf[nmatches], data->candidate, len); nmatches++; longest = max(longest, len); if ( nmatches > <API key> ) { TCHAR *msg = _T("\r\n! Too many matches\r\n"); while(*msg) rlc_putchar(ln->console, *msg++); ln->reprompt = TRUE; data->call_type = COMPLETE_CLOSE; (*data->function)(data); return; } } data->call_type = COMPLETE_CLOSE; (*data->function)(data); cols = ScreenCols(ln->console) / longest; rlc_putchar(ln->console, '\r'); rlc_putchar(ln->console, '\n'); for(n=0; n<nmatches; ) { TCHAR *s = buf[n]; len = 0; while(*s) { len++; rlc_putchar(ln->console, *s++); } rlc_free(buf[n++]); if ( n % cols == 0 ) { rlc_putchar(ln->console, '\r'); rlc_putchar(ln->console, '\n'); } else { while( len++ < longest ) rlc_putchar(ln->console, ' '); } } if ( nmatches % cols != 0 ) { rlc_putchar(ln->console, '\r'); rlc_putchar(ln->console, '\n'); } ln->reprompt = TRUE; } } } static void output(rlc_console b, TCHAR *s, size_t len) { while(len { if ( *s == '\n' ) rlc_putchar(b, '\r'); rlc_putchar(b, *s++); } } static void update_display(Line ln) { if ( ln->reprompt ) { const TCHAR *prompt = rlc_prompt(ln->console, NULL); const TCHAR *s = prompt; rlc_putchar(ln->console, '\r'); while(*s) rlc_putchar(ln->console, *s++); rlc_get_mark(ln->console, &ln->origin); ln->change_start = 0; ln->reprompt = FALSE; } rlc_goto_mark(ln->console, &ln->origin, ln->data, ln->change_start); output(ln->console, &ln->data[ln->change_start], ln->size - ln->change_start); <API key>(ln->console); rlc_goto_mark(ln->console, &ln->origin, ln->data, ln->point); rlc_update(ln->console); ln->change_start = ln->size; } TCHAR * read_line(rlc_console b) { line ln; init_line_package(b); memset(&ln, 0, sizeof(line)); ln.console = b; rlc_get_mark(b, &ln.origin); while(!ln.complete) { int c; rlc_mark m0, m1; function func; rlc_get_mark(b, &m0); if ( (c = getch(b)) == IMODE_SWITCH_CHAR ) return RL_CANCELED_CHARP; if ( c == EOF ) { eof(&ln, c); update_display(&ln); break; } else if ( c == ESC ) { if ( (c = getch(b)) == IMODE_SWITCH_CHAR ) return RL_CANCELED_CHARP; if ( c > 256 ) func = undefined; else func = dispatch_meta[c&0xff]; } else { if ( c >= 256 ) func = insert_self; else func = dispatch_table[c&0xff]; } rlc_get_mark(b, &m1); (*func)(&ln, c); if ( m0.mark_x != m1.mark_x || m0.mark_y != m1.mark_y ) ln.reprompt = TRUE; update_display(&ln); } rlc_clearprompt(b); add_history(b, ln.data); return ln.data; } static void init_dispatch_table() { static int done; if ( !done ) { int n; for(n=0; n<32; n++) dispatch_table[n] = undefined; for(n=32; n<256; n++) dispatch_table[n] = insert_self; for(n=0; n<256; n++) dispatch_meta[n] = undefined; bind_actions(); done = TRUE; } } static void init_line_package(RlcData b) { init_dispatch_table(); rlc_init_history(b, 50); } typedef struct _action { char *name; function function; unsigned char keys[4]; } action, *Action; #define ACTION(n, f, k) { n, f, k } static action actions[] = { ACTION("insert_self", insert_self, ""), ACTION("<API key>", <API key>, "\b"), ACTION("complete", complete, "\t"), ACTION("enter", enter, "\r\n"), ACTION("start_of_line", start_of_line, {ctrl('A')}), ACTION("backward_character", backward_character, {ctrl('B')}), ACTION("interrupt", interrupt, {ctrl('C')}), ACTION("end_of_line", end_of_line, {ctrl('E')}), ACTION("forward_character", forward_character, {ctrl('F')}), ACTION("transpose_chars", transpose_chars, {ctrl('T')}), ACTION("kill_line", kill_line, {ctrl('K')}), ACTION("backward_history", backward_history, {ctrl('P')}), ACTION("forward_history", forward_history, {ctrl('N')}), ACTION("empty_line", empty_line, {ctrl('U')}), ACTION("eof", eof, {ctrl('Z')}), ACTION("<API key>", <API key>, {ctrl('D')}), ACTION("delete_character", delete_character, {127}), { "forward_word", forward_word, {meta(ctrl('F')), meta('f')}}, { "backward_word", backward_word, {meta(ctrl('B')), meta('b')}}, { "forward_delete_word", forward_delete_word, {meta(127), meta('d')}}, ACTION("list_completions", list_completions, {meta('?')}), ACTION("<API key>", <API key>, {meta('\b')}), ACTION(NULL, NULL, "") }; int rlc_bind(int chr, const char *fname) { if ( chr >= 0 && chr <= 256 ) { Action a = actions; for( ; a->name; a++ ) { if ( strcmp(a->name, fname) == 0 ) { if ( chr > META_OFFSET ) dispatch_meta[chr-META_OFFSET] = a->function; else dispatch_table[chr] = a->function; return TRUE; } } } return FALSE; } static void bind_actions() { Action a = actions; for( ; a->name; a++ ) { unsigned char *k = a->keys; for( ; *k; k++ ) { int chr = *k & 0xff; if ( chr > META_OFFSET ) dispatch_meta[chr-META_OFFSET] = a->function; else dispatch_table[chr] = a->function; } } }
/* OCaml */ /* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ /* en Automatique. */ #define CAML_INTERNALS /* Registration of global memory roots */ #include "caml/mlvalues.h" #include "caml/roots.h" #include "caml/globroots.h" #include "caml/skiplist.h" /* The three global root lists. Each is represented by a skip list with the key being the address of the root. (The associated data field is unused.) */ struct skiplist caml_global_roots = <API key>; /* mutable roots, don't know whether old or young */ struct skiplist <API key> = <API key>; /* generational roots pointing to minor or major heap */ struct skiplist <API key> = <API key>; /* generational roots pointing to major heap */ /* The invariant of the generational roots is the following: - If the global root contains a pointer to the minor heap, then the root is in [<API key>]; - If the global root contains a pointer to the major heap, then the root is in [<API key>] or in [<API key>]; - Otherwise (the root contains a pointer outside of the heap or an integer), then neither [<API key>] nor [<API key>] contain it. */ /* Insertion and deletion */ Caml_inline void <API key>(struct skiplist * list, value * r) { <API key>(list, (uintnat) r, 0); } Caml_inline void <API key>(struct skiplist * list, value * r) { <API key>(list, (uintnat) r); } /* Iterate a GC scanning action over a global root list */ static void <API key>(scanning_action f, struct skiplist * rootlist) { <API key>(e, rootlist, { value * r = (value *) (e->key); f(*r, r); }) } /* Register a global C root of the mutable kind */ CAMLexport void <API key>(value *r) { CAMLassert (((intnat) r & 3) == 0); /* compact.c demands this (for now) */ <API key>(&caml_global_roots, r); } /* Un-register a global C root of the mutable kind */ CAMLexport void <API key>(value *r) { <API key>(&caml_global_roots, r); } enum gc_root_class { YOUNG, OLD, UNTRACKED }; static enum gc_root_class classify_gc_root(value v) { if(!Is_block(v)) return UNTRACKED; if(Is_young(v)) return YOUNG; #ifndef NO_NAKED_POINTERS if(!Is_in_heap(v)) return UNTRACKED; #endif return OLD; } /* Register a global C root of the generational kind */ CAMLexport void <API key>(value *r) { CAMLassert (((intnat) r & 3) == 0); /* compact.c demands this (for now) */ switch(classify_gc_root(*r)) { case YOUNG: <API key>(&<API key>, r); break; case OLD: <API key>(&<API key>, r); break; case UNTRACKED: break; } } /* Un-register a global C root of the generational kind */ CAMLexport void <API key>(value *r) { switch(classify_gc_root(*r)) { case OLD: <API key>(&<API key>, r); /* Fallthrough: the root can be in the young list while actually being in the major heap. */ case YOUNG: <API key>(&<API key>, r); break; case UNTRACKED: break; } } /* Modify the value of a global C root of the generational kind */ CAMLexport void <API key>(value *r, value newval) { enum gc_root_class c; /* See PRs #4704, #607 and #8656 */ switch(classify_gc_root(newval)) { case YOUNG: c = classify_gc_root(*r); if(c == OLD) <API key>(&<API key>, r); if(c != YOUNG) <API key>(&<API key>, r); break; case OLD: /* If the old class is YOUNG, then we do not need to do anything: It is OK to have a root in roots_young that suddenly points to the old generation -- the next minor GC will take care of that. */ if(classify_gc_root(*r) == UNTRACKED) <API key>(&<API key>, r); break; case UNTRACKED: <API key>(r); break; } *r = newval; } /* Scan all global roots */ void <API key>(scanning_action f) { <API key>(f, &caml_global_roots); <API key>(f, &<API key>); <API key>(f, &<API key>); } /* Scan global roots for a minor collection */ void <API key>(scanning_action f) { <API key>(f, &caml_global_roots); <API key>(f, &<API key>); /* Move young roots to old roots */ <API key>(e, &<API key>, { value * r = (value *) (e->key); <API key>(&<API key>, r); }); caml_skiplist_empty(&<API key>); }
<?php /** * @package tikiwiki */ // $Id: categorize.php 44444 2013-01-05 21:24:24Z changi67 $ require_once('tiki-setup.php'); $access = TikiLib::lib('access'); $access->check_script($_SERVER["SCRIPT_NAME"], basename(__FILE__)); $smarty = TikiLib::lib('smarty'); global $prefs; $catobjperms = Perms::get(array( 'type' => $cat_type, 'object' => $cat_objid )); if ($prefs['feature_categories'] == 'y' && $catobjperms-><API key> ) { $categlib = TikiLib::lib('categ'); if (isset($_REQUEST['import']) and isset($_REQUEST['categories'])) { $_REQUEST["cat_categories"] = explode(',', $_REQUEST['categories']); $_REQUEST["cat_categorize"] = 'on'; } if ( !isset($_REQUEST["cat_categorize"]) || $_REQUEST["cat_categorize"] != 'on' ) { $_REQUEST['cat_categories'] = NULL; } $categlib-><API key>(isset($_REQUEST['cat_categories'])?$_REQUEST['cat_categories']:'', $cat_objid, $cat_type, $cat_desc, $cat_name, $cat_href, $_REQUEST['cat_managed']); }
package org.jboss.narayana.txframework.api.exception; /** * @deprecated The TXFramework API will be removed. The org.jboss.narayana.compensations API should be used instead. * The new API is superior for these reasons: * <p/> * i) offers a higher level API; * ii) The API very closely matches that of JTA, making it easier for developers to learn, * iii) It works for non-distributed transactions as well as distributed transactions. * iv) It is CDI based so only needs a CDI container to run, rather than a full Java EE server. * <p/> */ @Deprecated public class <API key> extends Exception { public <API key>(String message) { super(message); } public <API key>(String message, Throwable cause) { super(message, cause); } }
var <API key> = [ [ "Deserialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a5e8aa7ae1372033da215d02b79947b20.html#<API key>", null ], [ "Serialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a4aec60f5df74f482b576f4e0dad0d5f6.html#<API key>", null ], [ "Serialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a2362ae784859054bf5b9281dafeb37cd.html#<API key>", null ], [ "ValueType", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_af5d06e2fe995f816c840a8ceefd22991.html#<API key>", null ] ];
// Arjuna Technologies Ltd., // Newcastle upon Tyne, // Tyne and Wear, package org.jboss.jbossts.qa.<API key>; /* * Try to get around the differences between Ansi CPP and * K&R cpp with concatenation. */ import org.jboss.jbossts.qa.RawResources02.*; import org.jboss.jbossts.qa.Utils.OAInterface; import org.jboss.jbossts.qa.Utils.ORBInterface; import org.jboss.jbossts.qa.Utils.OTS; import org.jboss.jbossts.qa.Utils.ServerIORStore; import org.omg.CORBA.<API key>; public class Client085 { public static void main(String[] args) { try { ORBInterface.initORB(args, null); OAInterface.initOA(); String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]); Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1)); String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]); Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2)); ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1]; resourceBehaviors1[0] = new ResourceBehavior(); resourceBehaviors1[0].prepare_behavior = PrepareBehavior.<API key>; resourceBehaviors1[0].rollback_behavior = RollbackBehavior.<API key>; resourceBehaviors1[0].commit_behavior = CommitBehavior.<API key>; resourceBehaviors1[0].<API key> = <API key>.<API key>; ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1]; resourceBehaviors2[0] = new ResourceBehavior(); resourceBehaviors2[0].prepare_behavior = PrepareBehavior.<API key>; resourceBehaviors2[0].rollback_behavior = RollbackBehavior.<API key>; resourceBehaviors2[0].commit_behavior = CommitBehavior.<API key>; resourceBehaviors2[0].<API key> = <API key>.<API key>; boolean correct = true; OTS.current().begin(); service1.oper(resourceBehaviors1, OTS.current().get_control()); service2.oper(resourceBehaviors2, OTS.current().get_control()); try { OTS.current().commit(true); System.err.println("Commit succeeded when it shouldn't"); correct = false; } catch (<API key> <API key>) { } correct = correct && service1.is_correct() && service2.is_correct(); if (!correct) { System.err.println("service1.is_correct() or service2.is_correct() returned false"); } ResourceTrace resourceTrace1 = service1.get_resource_trace(0); ResourceTrace resourceTrace2 = service2.get_resource_trace(0); correct = correct && (resourceTrace1 == ResourceTrace.<API key>); correct = correct && ((resourceTrace2 == ResourceTrace.<API key>) || (resourceTrace2 == ResourceTrace.<API key>)); if (correct) { System.out.println("Passed"); } else { System.out.println("Failed"); } } catch (Exception exception) { System.err.println("Client085.main: " + exception); exception.printStackTrace(System.err); System.out.println("Failed"); } try { OAInterface.shutdownOA(); ORBInterface.shutdownORB(); } catch (Exception exception) { System.err.println("Client085.main: " + exception); exception.printStackTrace(System.err); } } }
package com.pi4j.io.gpio; @SuppressWarnings("unused") public interface GpioPinPwm extends GpioPin { int getPwm(); }
# This is a fix for InnoDB in MySQL >= 4.1.x # It "suspends judgement" for fkey relationships until are tables are set. SET FOREIGN_KEY_CHECKS = 0; UPDATE `config` SET `value`='2.0.1' WHERE `name`='thelia_version'; UPDATE `config` SET `value`='1' WHERE `name`='<API key>'; UPDATE `config` SET `value`='' WHERE `name`='<API key>'; INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('<API key>','fcccn', 1, 1, NOW(), NOW()); INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('<API key>','2592000', 1, 1, NOW(), NOW()); INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('sitemap_ttl','7200', 1, 1, NOW(), NOW()); INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('feed_ttl','7200', 1, 1, NOW(), NOW()); ALTER TABLE `module` ADD INDEX `idx_module_activate` (`activate`); SELECT @max := MAX(`id`) FROM `resource`; SET @max := @max+1; INSERT INTO resource (`id`, `code`, `created_at`, `updated_at`) VALUES (@max, 'admin.configuration.store', NOW(), NOW()), (@max+1, 'admin.configuration.variable', NOW(), NOW()), (@max+2, 'admin.configuration.admin-logs', NOW(), NOW()), (@max+3, 'admin.configuration.system-logs', NOW(), NOW()), (@max+4, 'admin.configuration.advanced', NOW(), NOW()), (@max+5, 'admin.configuration.translations', NOW(), NOW()), (@max+6, 'admin.tools', NOW(), NOW()), (@max+7, 'admin.export', NOW(), NOW()), (@max+8, 'admin.export.customer.newsletter', NOW(), NOW()) ; INSERT INTO resource_i18n (`id`, `locale`, `title`) VALUES (@max, 'en_US', 'Store information configuration'), (@max+1, 'en_US', 'Configuration variables'), (@max+2, 'en_US', 'View administration logs'), (@max+3, 'en_US', 'Logging system configuration'), (@max+4, 'en_US', 'Advanced configuration'), (@max+5, 'en_US', 'Translations'), (@max+6, 'en_US', 'Tools panel'), (@max+7, 'en_US', 'Back-office export management'), (@max+8, 'en_US', 'export of newsletter subscribers'), (@max, 'es_ES', NULL), (@max+1, 'es_ES', NULL), (@max+2, 'es_ES', NULL), (@max+3, 'es_ES', NULL), (@max+4, 'es_ES', NULL), (@max+5, 'es_ES', NULL), (@max+6, 'es_ES', NULL), (@max+7, 'es_ES', NULL), (@max+8, 'es_ES', NULL), (@max, 'fr_FR', 'Configuration des informations sur la boutique'), (@max+1, 'fr_FR', 'Variables de configuration'), (@max+2, 'fr_FR', 'Consulter les logs d\'administration'), (@max+3, 'fr_FR', 'Configuration du système de log'), (@max+4, 'fr_FR', 'Configuration avancée'), (@max+5, 'fr_FR', 'Traductions'), (@max+6, 'fr_FR', 'Outils'), (@max+7, 'fr_FR', 'gestion des exports'), (@max+8, 'fr_FR', 'Export des inscrits à la newsletter') ; SELECT @max := MAX(`id`) FROM `lang`; SET @max := @max+1; INSERT INTO `lang`(`id`,`title`,`code`,`locale`,`url`,`date_format`,`time_format`,`datetime_format`,`decimal_separator`,`thousands_separator`,`decimals`,`by_default`,`created_at`,`updated_at`)VALUES (@max, 'Russian', 'ru', 'ru_RU', '', 'j.n.Y', 'H:i:s', 'j.n.Y H:i:s', ',', ' ', '2', 0, NOW(), NOW()); SET @max := @max+1; INSERT INTO `lang`(`id`,`title`,`code`,`locale`,`url`,`date_format`,`time_format`,`datetime_format`,`decimal_separator`,`thousands_separator`,`decimals`,`by_default`,`created_at`,`updated_at`)VALUES (@max, 'Czech', 'cs', 'cs_CZ', '', 'j.n.Y', 'H:i:s', 'j.n.Y H:i:s', ',', ' ', '2', 0, NOW(), NOW()); SET FOREIGN_KEY_CHECKS = 1;
package ca import ( "bytes" cryptorand "crypto/rand" "crypto/tls" "crypto/x509" "encoding/hex" "encoding/json" "encoding/pem" "io" "io/ioutil" "net/http" "sync" "time" "github.com/cloudflare/cfssl/api" "github.com/cloudflare/cfssl/config" "github.com/cloudflare/cfssl/csr" "github.com/cloudflare/cfssl/signer" "github.com/docker/swarmkit/log" "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/net/context" "golang.org/x/net/context/ctxhttp" ) const ( // <API key> is the profile that we will be sending cross-signing CSR sign requests with <API key> = "CA" // CertificateMaxSize is the maximum expected size of a certificate. // While there is no specced upper limit to the size of an x509 certificate in PEM format, // one with a ridiculous RSA key size (16384) and 26 256-character DNS SAN fields is about 14k. // While there is no upper limit on the length of certificate chains, long chains are impractical. // To be conservative, and to also account for external CA certificate responses in JSON format // from CFSSL, we'll set the max to be 256KiB. CertificateMaxSize int64 = 256 << 10 ) // ErrNoExternalCAURLs is an error used it indicate that an ExternalCA is // configured with no URLs to which it can proxy certificate signing requests. var ErrNoExternalCAURLs = errors.New("no external CA URLs") // ExternalCA is able to make certificate signing requests to one of a list // remote CFSSL API endpoints. type ExternalCA struct { <API key> time.Duration mu sync.Mutex rootCA *RootCA urls []string client *http.Client } // NewExternalCA creates a new ExternalCA which uses the given tlsConfig to // authenticate to any of the given URLS of CFSSL API endpoints. func NewExternalCA(rootCA *RootCA, tlsConfig *tls.Config, urls ...string) *ExternalCA { return &ExternalCA{ <API key>: 5 * time.Second, rootCA: rootCA, urls: urls, client: &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, }, } } // Copy returns a copy of the external CA that can be updated independently func (eca *ExternalCA) Copy() *ExternalCA { eca.mu.Lock() defer eca.mu.Unlock() return &ExternalCA{ <API key>: eca.<API key>, rootCA: eca.rootCA, urls: eca.urls, client: eca.client, } } // UpdateTLSConfig updates the HTTP Client for this ExternalCA by creating // a new client which uses the given tlsConfig. func (eca *ExternalCA) UpdateTLSConfig(tlsConfig *tls.Config) { eca.mu.Lock() defer eca.mu.Unlock() eca.client = &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, } } // UpdateURLs updates the list of CSR API endpoints by setting it to the given urls. func (eca *ExternalCA) UpdateURLs(urls ...string) { eca.mu.Lock() defer eca.mu.Unlock() eca.urls = urls } // UpdateRootCA changes the root CA used to append intermediates func (eca *ExternalCA) UpdateRootCA(rca *RootCA) { eca.mu.Lock() eca.rootCA = rca eca.mu.Unlock() } // Sign signs a new certificate by proxying the given certificate signing // request to an external CFSSL API server. func (eca *ExternalCA) Sign(ctx context.Context, req signer.SignRequest) (cert []byte, err error) { // Get the current HTTP client and list of URLs in a small critical // section. We will use these to make certificate signing requests. eca.mu.Lock() urls := eca.urls client := eca.client intermediates := eca.rootCA.Intermediates eca.mu.Unlock() if len(urls) == 0 { return nil, ErrNoExternalCAURLs } csrJSON, err := json.Marshal(req) if err != nil { return nil, errors.Wrap(err, "unable to JSON-encode CFSSL signing request") } // Try each configured proxy URL. Return after the first success. If // all fail then the last error will be returned. for _, url := range urls { requestCtx, cancel := context.WithTimeout(ctx, eca.<API key>) cert, err = <API key>(requestCtx, client, url, csrJSON) cancel() if err == nil { return append(cert, intermediates...), err } log.G(ctx).Debugf("unable to proxy certificate signing request to %s: %s", url, err) } return nil, err } // CrossSignRootCA takes a RootCA object, generates a CA CSR, sends a signing request with the CA CSR to the external // CFSSL API server in order to obtain a cross-signed root func (eca *ExternalCA) CrossSignRootCA(ctx context.Context, rca RootCA) ([]byte, error) { // <API key> generates a new key request, and we want to continue to use the old // key. However, <API key> will also convert the pkix.Name to csr.Name, which we // need in order to generate a signing request rcaSigner, err := rca.Signer() if err != nil { return nil, err } rootCert := rcaSigner.parsedCert cfCSRObj := csr.<API key>(rootCert) der, err := x509.<API key>(cryptorand.Reader, &x509.CertificateRequest{ <API key>: rootCert.<API key>, RawSubject: rootCert.RawSubject, PublicKeyAlgorithm: rootCert.PublicKeyAlgorithm, Subject: rootCert.Subject, Extensions: rootCert.Extensions, DNSNames: rootCert.DNSNames, EmailAddresses: rootCert.EmailAddresses, IPAddresses: rootCert.IPAddresses, }, rcaSigner.cryptoSigner) if err != nil { return nil, err } req := signer.SignRequest{ Request: string(pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE REQUEST", Bytes: der, })), Subject: &signer.Subject{ CN: rootCert.Subject.CommonName, Names: cfCSRObj.Names, }, Profile: <API key>, } // cfssl actually ignores non subject alt name extensions in the CSR, so we have to add the CA extension in the signing // request as well for _, ext := range rootCert.Extensions { if ext.Id.Equal(BasicConstraintsOID) { req.Extensions = append(req.Extensions, signer.Extension{ ID: config.OID(ext.Id), Critical: ext.Critical, Value: hex.EncodeToString(ext.Value), }) } } return eca.Sign(ctx, req) } func <API key>(ctx context.Context, client *http.Client, url string, csrJSON []byte) (cert []byte, err error) { resp, err := ctxhttp.Post(ctx, client, url, "application/json", bytes.NewReader(csrJSON)) if err != nil { return nil, recoverableErr{err: errors.Wrap(err, "unable to perform certificate signing request")} } defer resp.Body.Close() b := io.LimitReader(resp.Body, CertificateMaxSize) body, err := ioutil.ReadAll(b) if err != nil { return nil, recoverableErr{err: errors.Wrap(err, "unable to read CSR response body")} } if resp.StatusCode != http.StatusOK { return nil, recoverableErr{err: errors.Errorf("unexpected status code in CSR response: %d - %s", resp.StatusCode, string(body))} } var apiResponse api.Response if err := json.Unmarshal(body, &apiResponse); err != nil { logrus.Debugf("unable to JSON-parse CFSSL API response body: %s", string(body)) return nil, recoverableErr{err: errors.Wrap(err, "unable to parse JSON response")} } if !apiResponse.Success || apiResponse.Result == nil { if len(apiResponse.Errors) > 0 { return nil, errors.Errorf("response errors: %v", apiResponse.Errors) } return nil, errors.New("certificate signing request failed") } result, ok := apiResponse.Result.(map[string]interface{}) if !ok { return nil, errors.Errorf("invalid result type: %T", apiResponse.Result) } certPEM, ok := result["certificate"].(string) if !ok { return nil, errors.Errorf("invalid result certificate field type: %T", result["certificate"]) } return []byte(certPEM), nil }
package com.arjuna.wsas.tests; import com.arjuna.mw.wsas.context.Context; import com.arjuna.mw.wsas.UserActivityFactory; import com.arjuna.mw.wsas.common.GlobalId; import com.arjuna.mw.wsas.activity.Outcome; import com.arjuna.mw.wsas.activity.HLS; import com.arjuna.mw.wsas.completionstatus.CompletionStatus; import com.arjuna.mw.wsas.exceptions.*; import java.util.*; /** * @author Mark Little (mark.little@arjuna.com) * @version $Id: DemoHLS.java,v 1.2 2005/05/19 12:13:19 nmcl Exp $ * @since 1.0. */ public class DemoHLS implements HLS { private Stack<GlobalId> _id; public DemoHLS() { _id = new Stack<GlobalId>(); } /** * An activity has begun and is active on the current thread. */ public void begun () throws SystemException { try { GlobalId activityId = UserActivityFactory.userActivity().activityId(); _id.push(activityId); System.out.println("DemoHLS.begun "+activityId); } catch (Exception ex) { ex.printStackTrace(); } } /** * The current activity is completing with the specified completion status. * * @return The result of terminating the relationship of this HLS and * the current activity. */ public Outcome complete (CompletionStatus cs) throws SystemException { try { System.out.println("DemoHLS.complete ( "+cs+" ) " + UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * The activity has been suspended. How does the HLS know which activity * has been suspended? It must remember what its notion of current is. */ public void suspended () throws SystemException { System.out.println("DemoHLS.suspended"); } /** * The activity has been resumed on the current thread. */ public void resumed () throws SystemException { System.out.println("DemoHLS.resumed"); } /** * The activity has completed and is no longer active on the current * thread. */ public void completed () throws SystemException { try { System.out.println("DemoHLS.completed "+ UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } if (!_id.isEmpty()) { _id.pop(); } } /** * The HLS name. */ public String identity () throws SystemException { return "DemoHLS"; } /** * The activity service maintains a priority ordered list of HLS * implementations. If an HLS wishes to be ordered based on priority * then it can return a non-negative value: the higher the value, * the higher the priority and hence the earlier in the list of HLSes * it will appear (and be used in). * * @return a positive value for the priority for this HLS, or zero/negative * if the order is not important. */ public int priority () throws SystemException { return 0; } /** * Return the context augmentation for this HLS, if any on the current * activity. * * @return a context object or null if no augmentation is necessary. */ public Context context () throws SystemException { if (_id.isEmpty()) { throw new SystemException("request for context when inactive"); } try { System.out.println("DemoHLS.context "+ UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } return new <API key>(identity() + "_" + _id.size()); } }
/ [<API key>.1.ts] class A { a?: A #b?: A; getA(): A { return new A(); } constructor() { this?.#b; // Error this?.a.#b; // Error this?.getA().#b; // Error } } / [<API key>.1.js] "use strict"; class A { constructor() { this?.#b; // Error this?.a.#b; // Error this?.getA().#b; // Error } getA() { return new A(); } }
/*! * \~chinese * @header EMOptions+PrivateDeploy.h * @abstract SDK * @author Hyphenate * @version 3.0 * * \~english * @header EMOptions+PrivateDeploy.h * @abstract SDK setting options of private deployment * @author Hyphenate * @version 3.0 */ #import "EMOptions.h" @interface EMOptions (PrivateDeploy) /*! * \~chinese * DNS, YES * * [EMClient <API key>:] * * \~english * Whether allow to use DNS, default is YES * * Can only set when initialize SDK [EMClient <API key>:], can't change it in runtime */ @property (nonatomic, assign) BOOL enableDnsConfig; /*! * \~chinese * IM * * enableDnsConfigNO[EMClient <API key>:] * * \~english * IM server port * * It's effective only when enableDnsConfig is NO. Can only set when initialize SDK [EMClient <API key>:], can't change it in runtime */ @property (nonatomic, assign) int chatPort; /*! * \~chinese * IM * * enableDnsConfigNO[EMClient <API key>:] * * \~english * IM server * * It's effective only when enableDnsConfig is NO. Can only set when initialize SDK [EMClient <API key>:], can't change it in runtime */ @property (nonatomic, strong) NSString *chatServer; /*! * \~chinese * REST * * enableDnsConfigNO[EMClient <API key>:] * * \~english * REST server * * It's effective only when enableDnsConfig is NO. Can only set when initialize SDK [EMClient <API key>:], can't change it in runtime */ @property (nonatomic, strong) NSString *restServer; @end
// @allowjs: true // @checkjs: true // @noemit: true // @strict: true // @filename: <API key>.js this["a" + "b"] = 0
// RUN: %clang_cc1 -fsyntax-only -fshow-overloads=best -std=c++11 -verify %s template <class T> struct X { operator T() const {return T();} }; void test_char16t(X<char16_t> x) { bool b = x == char16_t(); }
package org.axonframework.test.saga; public class <API key> { }
// @declaration: true // @noImplicitThis: true function createObj() { return { func1() { return this; }, func2() { return this; }, func3() { return this; } }; } function createObjNoCrash() { return { func1() { return this; }, func2() { return this; }, func3() { return this; }, func4() { return this; }, func5() { return this; }, func6() { return this; }, func7() { return this; }, func8() { return this; }, func9() { return this; } }; }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_31) on Mon Jul 22 15:25:23 PDT 2013 --> <TITLE> Uses of Class org.apache.hadoop.mapred.join.ResetableIterator.EMPTY (Hadoop 1.2.1 API) </TITLE> <META NAME="date" CONTENT="2013-07-22"> <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 Class org.apache.hadoop.mapred.join.ResetableIterator.EMPTY (Hadoop 1.2.1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <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>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/mapred/join/ResetableIterator.EMPTY.html" title="class in org.apache.hadoop.mapred.join"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/mapred/join//<API key>.EMPTY.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ResetableIterator.EMPTY.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<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> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.mapred.join.ResetableIterator.EMPTY</B></H2> </CENTER> No usage of org.apache.hadoop.mapred.join.ResetableIterator.EMPTY <P> <HR> <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="<API key>"></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>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/mapred/join/ResetableIterator.EMPTY.html" title="class in org.apache.hadoop.mapred.join"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/mapred/join//<API key>.EMPTY.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ResetableIterator.EMPTY.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<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> <HR> Copyright &copy; 2009 The Apache Software Foundation </BODY> </HTML>
package strategy import ( "reflect" "strings" "testing" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation" kapi "k8s.io/kubernetes/pkg/api" buildapi "github.com/openshift/origin/pkg/build/api" _ "github.com/openshift/origin/pkg/build/api/install" ) func <API key>(t *testing.T) { strategy := DockerBuildStrategy{ Image: "docker-test-image", Codec: kapi.Codecs.LegacyCodec(buildapi.<API key>), } build := mockDockerBuild() actual, err := strategy.CreateBuildPod(build) if err != nil { t.Errorf("Unexpected error: %v", err) } if expected, actual := buildapi.GetBuildPodName(build), actual.ObjectMeta.Name; expected != actual { t.Errorf("Expected %s, but got %s!", expected, actual) } if !reflect.DeepEqual(map[string]string{buildapi.BuildLabel: buildapi.LabelValue(build.Name)}, actual.Labels) { t.Errorf("Pod Labels does not match Build Labels!") } if !reflect.DeepEqual(nodeSelector, actual.Spec.NodeSelector) { t.Errorf("Pod NodeSelector does not match Build NodeSelector. Expected: %v, got: %v", nodeSelector, actual.Spec.NodeSelector) } container := actual.Spec.Containers[0] if container.Name != "docker-build" { t.Errorf("Expected docker-build, but got %s!", container.Name) } if container.Image != strategy.Image { t.Errorf("Expected %s image, got %s!", container.Image, strategy.Image) } if container.ImagePullPolicy != kapi.PullIfNotPresent { t.Errorf("Expected %v, got %v", kapi.PullIfNotPresent, container.ImagePullPolicy) } if actual.Spec.RestartPolicy != kapi.RestartPolicyNever { t.Errorf("Expected never, got %#v", actual.Spec.RestartPolicy) } if len(container.Env) != 10 { var keys []string for _, env := range container.Env { keys = append(keys, env.Name) } t.Fatalf("Expected 10 elements in Env table, got %d:\n%s", len(container.Env), strings.Join(keys, ", ")) } if len(container.VolumeMounts) != 4 { t.Fatalf("Expected 4 volumes in container, got %d", len(container.VolumeMounts)) } if *actual.Spec.<API key> != 60 { t.Errorf("Expected <API key> 60, got %d", *actual.Spec.<API key>) } for i, expected := range []string{dockerSocketPath, <API key>, <API key>, <API key>} { if container.VolumeMounts[i].MountPath != expected { t.Fatalf("Expected %s in VolumeMount[%d], got %s", expected, i, container.VolumeMounts[i].MountPath) } } if len(actual.Spec.Volumes) != 4 { t.Fatalf("Expected 4 volumes in Build pod, got %d", len(actual.Spec.Volumes)) } if !kapi.Semantic.DeepEqual(container.Resources, build.Spec.Resources) { t.Fatalf("Expected actual=expected, %v != %v", container.Resources, build.Spec.Resources) } found := false foundIllegal := false for _, v := range container.Env { if v.Name == "BUILD_LOGLEVEL" && v.Value == "bar" { found = true } if v.Name == "ILLEGAL" { foundIllegal = true } } if !found { t.Fatalf("Expected variable BUILD_LOGLEVEL be defined for the container") } if foundIllegal { t.Fatalf("Found illegal environment variable 'ILLEGAL' defined on container") } buildJSON, _ := runtime.Encode(kapi.Codecs.LegacyCodec(buildapi.<API key>), build) errorCases := map[int][]string{ 0: {"BUILD", string(buildJSON)}, } for index, exp := range errorCases { if e := container.Env[index]; e.Name != exp[0] || e.Value != exp[1] { t.Errorf("Expected %s:%s, got %s:%s!\n", exp[0], exp[1], e.Name, e.Value) } } } func <API key>(t *testing.T) { strategy := DockerBuildStrategy{ Image: "docker-test-image", Codec: kapi.Codecs.LegacyCodec(buildapi.<API key>), } build := mockDockerBuild() build.Name = strings.Repeat("a", validation.<API key>*2) pod, err := strategy.CreateBuildPod(build) if err != nil { t.Fatalf("unexpected: %v", err) } if pod.Labels[buildapi.BuildLabel] != build.Name[:validation.<API key>] { t.Errorf("Unexpected build label value: %s", pod.Labels[buildapi.BuildLabel]) } } func mockDockerBuild() *buildapi.Build { timeout := int64(60) return &buildapi.Build{ ObjectMeta: metav1.ObjectMeta{ Name: "dockerBuild", Labels: map[string]string{ "name": "dockerBuild", }, }, Spec: buildapi.BuildSpec{ CommonSpec: buildapi.CommonSpec{ Revision: &buildapi.SourceRevision{ Git: &buildapi.GitSourceRevision{}, }, Source: buildapi.BuildSource{ Git: &buildapi.GitBuildSource{ URI: "http://my.build.com/the/dockerbuild/Dockerfile", Ref: "master", }, ContextDir: "my/test/dir", SourceSecret: &kapi.<API key>{Name: "secretFoo"}, }, Strategy: buildapi.BuildStrategy{ DockerStrategy: &buildapi.DockerBuildStrategy{ PullSecret: &kapi.<API key>{Name: "bar"}, Env: []kapi.EnvVar{ {Name: "ILLEGAL", Value: "foo"}, {Name: "BUILD_LOGLEVEL", Value: "bar"}, }, }, }, Output: buildapi.BuildOutput{ To: &kapi.ObjectReference{ Kind: "DockerImage", Name: "docker-registry/repository/dockerBuild", }, PushSecret: &kapi.<API key>{Name: "foo"}, }, Resources: kapi.<API key>{ Limits: kapi.ResourceList{ kapi.ResourceName(kapi.ResourceCPU): resource.MustParse("10"), kapi.ResourceName(kapi.ResourceMemory): resource.MustParse("10G"), }, }, <API key>: &timeout, NodeSelector: nodeSelector, }, }, Status: buildapi.BuildStatus{ Phase: buildapi.BuildPhaseNew, }, } }
#!/bin/bash # Linux on Hyper-V and Azure Test Code, ver. 1.0.0 # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION # ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR # PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. # performance_zk.sh # Description: # This tool uses the ZooKeeper (zk) python binding to test various operation latencies # In general the script does the following: # 1.create a root znode for the test, i.e. /zk-latencies # 2.attach a zk session to each server in the ensemble (the --servers list) # 3.run various (create/get/set/delete) operations against each server, note the latencies of operations # 4.client then cleans up, removing /zk-latencies znode # Parameters: # ZK_VERSION zookeeper-server version # ZK_SERVERS: comma separated list of host:port (default localhost:2181) # ZK_TIMEOUT; session timeout in milliseconds (default 5000) # ZK_ZNODE_SIZE; data size when creating/setting znodes (default 25) # ZK_ZNODE_COUNT; the number of znodes to operate on in each performance section (default 10000) # ZK_FORCE; (optional) force the test to run, even if root_znode exists -WARNING! don't run this on a real znode or you'll lose it !!! # ZK_SYNCHRONOUS; by default asynchronous ZK api is used, this forces synchronous calls # ZK_VERBOSE; verbose output, include more detail ICA_TESTRUNNING="TestRunning" ICA_TESTCOMPLETED="TestCompleted" ICA_TESTABORTED="TestAborted" ICA_TESTFAILED="TestFailed" # Function definitions LogMsg() { echo `date "+%a %b %d %T %Y"` ": ${1}" } UpdateTestState() { echo $1 > ~/state.txt } # LinuxRelease() LinuxRelease() { DISTRO=`grep -ihs "buntu\|Suse\|Fedora\|Debian\|CentOS\|Red Hat Enterprise Linux" /etc/{issue,*release,*version}` case $DISTRO in *buntu*) echo "UBUNTU";; Fedora*) echo "FEDORA";; CentOS*) echo "CENTOS";; *SUSE*) echo "SLES";; Red*Hat*) echo "RHEL";; Debian*) echo "DEBIAN";; esac } # DoSlesAB() # Description: # Perform distro specific Apache and tool installation steps for SLES # and then run the benchmark tool ConfigSlesZK() { # Note: A number of steps will use SSH to issue commands to the # APACHE_SERVER. This requires that the SSH keys be provisioned # in advanced, and strict mode be disabled for both the SSH # server and client. LogMsg "Info: Running SLES" arr=$(echo $ZK_SERVERS | tr "," "\n") for ZK_SERVER in $arr do #echo "${ZK_SERVER}" SERVER=(`echo "${ZK_SERVER}" | awk -F':' '{print $1}'`) #echo "${SERVER}" #ssh root@${SERVER} "mkdir /root/kk" #exit 1 LogMsg "Info: LogMsg "Info: Zookeeper-Server installation on server ${SERVER}" LogMsg "Info: Installing required packages first" ssh root@${SERVER} "zypper --non-interactive install wget" if [ $? -ne 0 ]; then msg="Error: Unable to install package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi # Install Java LogMsg "Check if Java is installed" javaInstalled=`which java` if [ ! $javaInstalled ]; then LogMsg "Installing Java" ssh root@${SERVER} "zypper --non-interactive install jre-1.7.0" if [ $? -ne 0 ]; then LogMsg "Error: Unable to install java" UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Download ZK package" pkg=(`ssh root@${SERVER} "ls /root/ | grep ${ZK_ARCHIVE}"`) echo $pkg if [ -z "$pkg" ]; then LogMsg "Downloading ZK package ${ZK_ARCHIVE}" #exit 1 ssh root@${SERVER} "wget ${ZK_URL}" if [ $? -ne 0 ]; then msg="Error: Unable to download ZK package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Untar and Config ZK server" ssh root@${SERVER} "tar -xzf ./${ZK_ARCHIVE}" ssh root@${SERVER} "cp zookeeper-${ZK_VERSION}/conf/zoo_sample.cfg zookeeper-${ZK_VERSION}/conf/zoo.cfg" LogMsg "Info: Starting Zookeeper-Server ${SERVER}" ssh root@${SERVER} "zookeeper-${ZK_VERSION}/bin/zkServer.sh start" if [ $? -ne 0 ]; then msg="Error: Unable to start Zookeeper-Server on ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi LogMsg "Info: Server started successfully" done } ConfigUbuntuZK() { # Note: A number of steps will use SSH to issue commands to the # ZK_SERVER. This requires that the SSH keys be provisioned # in advanced, and strict mode be disabled for both the SSH # server and client. LogMsg "Info: Running Ubuntu" arr=$(echo $ZK_SERVERS | tr "," "\n") for ZK_SERVER in $arr do SERVER=(`echo "${ZK_SERVER}" | awk -F':' '{print $1}'`) LogMsg "Info: LogMsg "Info: Zookeeper-Server installation on server ${SERVER}" LogMsg "Info: Installing required packages first" ssh root@${SERVER} "apt-get install -y wget" if [ $? -ne 0 ]; then msg="Error: Unable to install package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi # Install Java LogMsg "Check if Java is installed" javaInstalled=`which java` if [ ! $javaInstalled ]; then LogMsg "Installing Java" ssh root@${SERVER} "apt-get -y install default-jdk" if [ $? -ne 0 ]; then LogMsg "Error: Unable to install java" UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Download ZK package" pkg=(`ssh root@${SERVER} "ls /root/ | grep ${ZK_ARCHIVE}"`) echo $pkg if [ -z "$pkg" ]; then LogMsg "Downloading ZK package ${ZK_ARCHIVE}" #exit 1 ssh root@${SERVER} "wget ${ZK_URL}" if [ $? -ne 0 ]; then msg="Error: Unable to download ZK package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Untar and Config ZK server" ssh root@${SERVER} "tar -xzf ./${ZK_ARCHIVE}" ssh root@${SERVER} "cp zookeeper-${ZK_VERSION}/conf/zoo_sample.cfg zookeeper-${ZK_VERSION}/conf/zoo.cfg" LogMsg "Info: Starting Zookeeper-Server ${SERVER}" ssh root@${SERVER} "zookeeper-${ZK_VERSION}/bin/zkServer.sh start" if [ $? -ne 0 ]; then msg="Error: Unable to start Zookeeper-Server on ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi LogMsg "Info: Server started successfully" done } ConfigRHELZK() { # Note: A number of steps will use SSH to issue commands to the # ZK_SERVER. This requires that the SSH keys be provisioned # in advanced, and strict mode be disabled for both the SSH # server and client. LogMsg "Info: Running RHEL" arr=$(echo $ZK_SERVERS | tr "," "\n") for ZK_SERVER in $arr do SERVER=(`echo "${ZK_SERVER}" | awk -F':' '{print $1}'`) LogMsg "Info: LogMsg "Info: Zookeeper-Server installation on server ${SERVER}" LogMsg "Info: Installing required packages first" ssh root@${SERVER} "yum install -y wget" if [ $? -ne 0 ]; then msg="Error: Unable to install package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi # Install Java LogMsg "Check if Java is installed" javaInstalled=`which java` if [ ! $javaInstalled ]; then LogMsg "Installing Java" ssh root@${SERVER} "yum -y install java-1.7.0-openjdk" if [ $? -ne 0 ]; then LogMsg "Error: Unable to install Java" UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Download ZK package" pkg=(`ssh root@${SERVER} "ls /root/ | grep ${ZK_ARCHIVE}"`) echo $pkg if [ -z "$pkg" ]; then LogMsg "Downloading ZK package ${ZK_ARCHIVE}" #exit 1 ssh root@${SERVER} "wget ${ZK_URL}" if [ $? -ne 0 ]; then msg="Error: Unable to download ZK package to server ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi fi LogMsg "Info: Untar and Config ZK server" ssh root@${SERVER} "tar -xzf ./${ZK_ARCHIVE}" ssh root@${SERVER} "cp zookeeper-${ZK_VERSION}/conf/zoo_sample.cfg zookeeper-${ZK_VERSION}/conf/zoo.cfg" LogMsg "Info: Starting Zookeeper-Server ${SERVER}" ssh root@${SERVER} "zookeeper-${ZK_VERSION}/bin/zkServer.sh start" if [ $? -ne 0 ]; then msg="Error: Unable to start Zookeeper-Server on ${SERVER}" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi LogMsg "Info: Server started successfully" done } # Main script body cd ~ UpdateTestState $ICA_TESTRUNNING LogMsg "Starting test" # Delete any old summary.log file LogMsg "Cleaning up old summary.log" if [ -e ~/summary.log ]; then rm -f ~/summary.log fi touch ~/summary.log # Source the constants.sh file LogMsg "Sourcing constants.sh" if [ -e ~/constants.sh ]; then . ~/constants.sh else msg="Error: ~/constants.sh does not exist" LogMsg "${msg}" echo "${msg}" >> ~/summary.log UpdateTestState $ICA_TESTABORTED exit 10 fi # Make sure the required test parameters are defined if [ "${ZK_VERSION:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_VERSION test parameter is missing" LogMsg "${msg}" echo "${msg}" >> ~/summary.log UpdateTestState $ICA_TESTFAILED exit 20 fi if [ "${ZK_SERVERS:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_SERVER test parameter is missing" LogMsg "${msg}" echo "${msg}" >> ~/summary.log UpdateTestState $ICA_TESTFAILED exit 20 fi if [ "${ZK_TIMEOUT:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_TIMEOUT test parameter is missing" LogMsg "${msg}" echo "${msg}" >> ~/summary.log ZK_TIMEOUT=100000 fi if [ "${ZK_ZNODE_SIZE:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_ZNODE_SIZE test parameter is missing" LogMsg "${msg}" echo "${msg}" >> ~/summary.log ZK_ZNODE_SIZE=100 fi if [ "${ZK_ZNODE_COUNT:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_ZNODE_COUNT test parameter is missing" LogMsg "${msg}" echo "${msg}" >> ~/summary.log ZK_ZNODE_SIZE=100 fi if [ "${ZK_FORCE:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_FORCE test parameter is missing" LogMsg "${msg}" ZK_FORCE=$false fi if [ "${ZK_VERBOSE:="UNDEFINED"}" = "UNDEFINED" ]; then msg="Error: the ZK_VERBOSE test parameter is missing" LogMsg "${msg}" ZK_VERBOSE=$false fi LogMsg "Info: Test run parameters" echo "ZK_VERSION = ${ZK_VERSION}" echo "ZK_SERVERS = ${ZK_SERVERS}" echo "ZK_TIMEOUT = ${ZK_TIMEOUT}" echo "ZK_ZNODE_SIZE = ${ZK_ZNODE_SIZE}" echo "ZK_ZNODE_COUNT = ${ZK_ZNODE_COUNT}" echo "ZK_FORCE = ${ZK_FORCE}" echo "ZK_SYNCHRONOUS = ${ZK_SYNCHRONOUS}" echo "ZK_VERBOSE = ${ZK_VERBOSE}" LogMsg "Info : ZK_VERSION = ${ZK_VERSION}" ZK_ARCHIVE="zookeeper-${ZK_VERSION}.tar.gz" ZK_URL=http://apache.spinellicreations.com/zookeeper/zookeeper-${ZK_VERSION}/${ZK_ARCHIVE} # Configure ZK server - this has distro specific behaviour distro=`LinuxRelease` case $distro in "CENTOS" | "RHEL") ConfigRHELZK ;; "UBUNTU") ConfigUbuntuZK ;; "DEBIAN") ConfigDebianZK ;; "SLES") ConfigSlesZK ;; *) msg="Error: Distro '${distro}' not supported" LogMsg "${msg}" echo "${msg}" >> ~/summary.log UpdateTestState "TestAborted" exit 1 ;; esac IFS=',' read -ra ADDR <<< "$ZK_SERVERS" for zk_server in "${ADDR[@]}"; do LogMsg "Prepare ZK test cmd for ${zk_server}" testBaseString='PYTHONPATH="lib.linux-x86_64-2.6" LD_LIBRARY_PATH="lib.linux-x86_64-2.6" python ./zk-latencies.py ' #testBaseString='./zk-latencies.py PYTHONPATH=lib.linux-x86_64-2.6 LD_LIBRARY_PATH=lib.linux-x86_64-2.6 ' testString="${testBaseString}""--servers=${zk_server} --timeout=${ZK_TIMEOUT} --znode_count=${ZK_ZNODE_COUNT} --znode_size=${ZK_ZNODE_SIZE}" if [ "${ZK_FORCE}" = true ]; then testString="${testString}"" --force" fi if [ "${ZK_SYNCHRONOUS}" = true ]; then testString="${testString}"" --synchronous" fi if [ "${ZK_VERBOSE}" = true ]; then testString="${testString}"" --verbose" fi LogMsg "Running zookeeper tests with cmd: ${testString}" eval $testString if [ $? -ne 0 ]; then msg="Error: Unable to run test" LogMsg "${msg}" echo "${msg}" >> ./summary.log UpdateTestState $ICA_TESTFAILED exit 1 fi done # If we made it here, everything worked. # Indicate success LogMsg "Test completed successfully" UpdateTestState $ICA_TESTCOMPLETED exit 0
.picture-background{ background-image:linear-gradient(rgba(0, 0, 0, 0.6),rgba(0, 0, 0, 0.6)),url("../Fz-imgs/fact-img/technology3.jpeg"); background-position:center center; background-size:cover; } .main-home-nav{ background-color:#2c3e50; } .main-home-nav:after, .main-home-nav:before{ background-color:#2c3e50; }
<?php class IPPIdType { /** * Initializes this object, optionally with pre-defined property values * * Initializes this object and it's property members, using the dictionary * of key/value pairs passed as an optional argument. * * @param dictionary $keyValInitializers key/value pairs to be populated into object's properties * @param boolean $verbose specifies whether object should echo warnings */ public function __construct($keyValInitializers=array(), $verbose=FALSE) { foreach($keyValInitializers as $initPropName => $initPropVal) { if (property_exists('IPPIdType',$initPropName)) { $this->{$initPropName} = $initPropVal; } else { if ($verbose) echo "Property does not exist ($initPropName) in class (".get_class($this).")"; } } } /** * @xmlType value * @var string */ public $value; } // end class IPPIdType
<reference path='fourslash.ts' /> //@Filename: file.tsx / declare module JSX { / interface Element { } / interface IntrinsicElements { / } / interface <API key> { props } / } / class MyClass { / props: { / [|[|{| "contextRangeIndex": 0 |}name|]?: string;|] / size?: number; / } / / / var x = <MyClass [|[|{| "contextRangeIndex": 2 |}name|]='hello'|]/>; verify.<API key>("name");
package de.j4velin.pedometer.util; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class ColorPreview extends View { private Paint paint = new Paint(); private int color; public ColorPreview(Context context) { super(context); } public ColorPreview(Context context, AttributeSet attrs) { super(context, attrs); } public ColorPreview(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setColor(final int c) { color = c; invalidate(); } @Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); paint.setColor(color); paint.setStyle(Paint.Style.FILL); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2, paint); paint.setColor(Color.BLACK); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(2); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2 - 1, paint); } }
package javaguide.xml; import org.w3c.dom.Document; import play.libs.XPath; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Result; public class JavaXmlRequests extends Controller { //#xml-hello public Result sayHello() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("Missing parameter [name]"); } else { return ok("Hello " + name); } } } //#xml-hello //#<API key> @BodyParser.Of(BodyParser.Xml.class) public Result sayHelloBP() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("Missing parameter [name]"); } else { return ok("Hello " + name); } } } //#<API key> //#xml-reply @BodyParser.Of(BodyParser.Xml.class) public Result replyHello() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("<message \"status\"=\"KO\">Missing parameter [name]</message>").as("application/xml"); } else { return ok("<message \"status\"=\"OK\">Hello " + name + "</message>").as("application/xml"); } } } //#xml-reply }
<div style="width: 600px"> <div class="delayed-image-load" data-src="base/test/fixtures/interpolated/B-{width}.jpg"></div> </div> <div style="width: 600px"> <div class="delayed-image-load" data-src="base/test/fixtures/{width}/{width}.jpg" data-width="1024"></div> </div>
from click_plugins import with_plugins from pkg_resources import iter_entry_points import click @with_plugins(iter_entry_points('girder.cli_plugins')) @click.group(help='Girder: data management platform for the web.', context_settings=dict(help_option_names=['-h', '--help'])) @click.version_option(message='%(version)s') def main(): pass
## Pinpoint JBoss plugin configuration Known Issue There is a bug in our ASM engine in 1.6.0. In order to trace jboss in 1.6.0, **you must set `profiler.instrument.engine=JAVASSIST` in pinpoint.config**. (The issue has been fixed in 1.6.1) **You must set jboss log manager starting from pinpoint 1.6.1+** - issue : #2612 Standalone mode <br/> Add following configuration in __standalone.conf__ :- <br/> bash JAVA_OPTS="$JAVA_OPTS -Djboss.modules.system.pkgs=org.jboss.byteman,org.jboss.logmanager,com.navercorp.pinpoint.bootstrap, com.navercorp.pinpoint.common,com.navercorp.pinpoint.exception" JAVA_OPTS="$JAVA_OPTS -Djava.util.logging.manager=org.jboss.logmanager.LogManager" JAVA_OPTS="$JAVA_OPTS -Xbootclasspath/p:$JBOSS_HOME/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-$<API key>.jar" JAVA_OPTS="$JAVA_OPTS -javaagent:$PINPOINT_AGENT_HOME/pinpoint-bootstrap-$PINPOINT_VERSION.jar" JAVA_OPTS="$JAVA_OPTS -Dpinpoint.applicationName=<API key>" JAVA_OPTS="$JAVA_OPTS -Dpinpoint.agentId=APP-AGENTID" Domain mode <br/> * Add below configuration in __domain.xml__ :- <br/> xml <system-properties> <property name="jboss.modules.system.pkgs" value="org.jboss.logmanager,com.navercorp.pinpoint.bootstrap, com.navercorp.pinpoint.common,com.navercorp.pinpoint.exception" boot-time="true"/> <property name="java.util.logging.manager" value="org.jboss.logmanager.LogManager"/> </system-properties> * Add below configuration in __host.xml__ :- <br/> xml <servers> <server name="server-one" group="main-server-group"> <jvm name="default"> <jvm-options> <option value="-Xbootclasspath/p:$JBOSS_HOME/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-$<API key>.jar"/> <option value="-javaagent:$PINPOINT_AGENT_HOME/pinpoint-bootstrap-$PINPOINT_VERSION.jar"/> <option value="-Dpinpoint.applicationName=<API key>"/> <option value="-Dpinpoint.agentId=APP-AGENT-1"/> </jvm-options> </jvm> </server> <server name="server-two" group="main-server-group" auto-start="true"> <jvm name="default"> <jvm-options> <option value="-Xbootclasspath/p:$JBOSS_HOME/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-$<API key>.jar"/> <option value="-javaagent:$PINPOINT_AGENT_HOME/pinpoint-bootstrap-$PINPOINT_VERSION.jar"/> <option value="-Dpinpoint.applicationName=<API key>"/> <option value="-Dpinpoint.agentId=APP-AGENT-2"/> </jvm-options> </jvm> </server> </servers> # Set ```profiler.jboss.traceEjb=true``` for remote ejb based application in *pinpoint.config* file # Set ```profiler.jboss.traceEjb=false``` for non-ejb based application in *pinpoint.config* file If your application shows up as *STAND_ALONE* Pinpoint agent throws an exception if multiple class file transformers are registered for a class. Since multiple plugins register class file transformers for `org.apache.catalina.core.StandardHostValve`, the agent will throw an exception on start up if they all blindly add class file transformers. To cirvumvent this issue, JBoss plugin will only register it's class file transformers if the application is detected or configured to be a *JBOSS* application. As a result, if your application is not identified as a *JBOSS* application, JBoss class file transformers will not be registered and your application will not be traced. When this happens, please manually set `profiler.<API key>=JBOSS` in *pinpoint.config*.
#ifndef vl_decoder_h #define vl_decoder_h #include "pipe/p_video_codec.h" /** * check if a given profile is supported with shader based decoding */ bool <API key>(struct pipe_screen *screen, enum pipe_video_profile profile, enum <API key> entrypoint); /** * get the maximum supported level for the given profile with shader based decoding */ int vl_level_supported(struct pipe_screen *screen, enum pipe_video_profile profile); /** * standard implementation of pipe->create_video_codec */ struct pipe_video_codec * vl_create_decoder(struct pipe_context *pipe, const struct pipe_video_codec *templat); #endif /* vl_decoder_h */
param($installPath, $toolsPath, $package, $project) # Need to load MSBuild assembly if it's not loaded yet. Add-Type -AssemblyName 'Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKey<API key> # Grab the loaded MSBuild project for the project $msbuild = [Microsoft.Build.Evaluation.ProjectCollection]::<API key>.GetLoadedProjects($project.FullName) | Select-Object -First 1 $importToRemove = $msbuild.Xml.Imports | Where-Object { $_.Project.Endswith($package.Id + '.targets') } if ($importToRemove) { # Remove the import and save the project $msbuild.Xml.RemoveChild($importToRemove) | out-null $project.Save() }
// This source file is part of the Swift.org open source project \file This file contains wrappes / helpers to import libcurl into Swift. It is used to implement the NSURLSession API. In most cases each `curl_…` API is mapped 1-to-1 to a corresponding `CFURLSession_…` API. This approach lets us keep most of the logic inside Swift code as opposed to more C code. - SeeAlso: https://curl.haxx.se/libcurl/c/ #if !defined(<API key>) #define <API key> 1 #include <stdio.h> <API key> CF_EXTERN_C_BEGIN CURL typedef void * <API key>; CURLM typedef void * <API key>; // This must match libcurl's curl_socket_t typedef int <API key>; typedef struct <API key> { int value; } <API key>; CF_EXPORT CFStringRef _Nonnull <API key>(int value); CF_EXPORT int const <API key>; CURLcode CF_EXPORT <API key> const <API key>; // CURLE_OK CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_FAILED_INIT CF_EXPORT <API key> const <API key>; // CURLE_URL_MALFORMAT CF_EXPORT <API key> const <API key>; // CURLE_NOT_BUILT_IN CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> //CF_EXPORT <API key> const <API key>; // CURLE_HTTP2 CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_PARTIAL_FILE CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_OBSOLETE20 CF_EXPORT <API key> const <API key>; // CURLE_QUOTE_ERROR CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_WRITE_ERROR CF_EXPORT <API key> const <API key>; // CURLE_OBSOLETE24 CF_EXPORT <API key> const <API key>; // CURLE_UPLOAD_FAILED CF_EXPORT <API key> const <API key>; // CURLE_READ_ERROR CF_EXPORT <API key> const <API key>; // CURLE_OUT_OF_MEMORY CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_OBSOLETE29 CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_OBSOLETE32 CF_EXPORT <API key> const <API key>; // CURLE_RANGE_ERROR CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> //CF_EXPORT <API key> const <API key>; // CURLE_OBSOLETE40 CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_OBSOLETE44 CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_OBSOLETE46 CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_OBSOLETE50 CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_GOT_NOTHING CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_SEND_ERROR CF_EXPORT <API key> const <API key>; // CURLE_RECV_ERROR CF_EXPORT <API key> const <API key>; // CURLE_OBSOLETE57 CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_SSL_CIPHER CF_EXPORT <API key> const <API key>; // CURLE_SSL_CACERT CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_LOGIN_DENIED CF_EXPORT <API key> const <API key>; // CURLE_TFTP_NOTFOUND CF_EXPORT <API key> const <API key>; // CURLE_TFTP_PERM CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_CONV_FAILED CF_EXPORT <API key> const <API key>; // CURLE_CONV_REQD CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_SSH CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_AGAIN CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLE_CHUNK_FAILED CF_EXPORT <API key> const <API key>; // <API key> //CF_EXPORT <API key> const <API key>; // <API key> //CF_EXPORT <API key> const <API key>; // <API key> CURLOPTTYPE typedef enum { <API key> = 0, // CURLOPTTYPE_LONG <API key> = 10000, // <API key> <API key> = 20000, // <API key> <API key> = 30000, // CURLOPTTYPE_OFF_T } CFURLSessionOptType; typedef struct CFURLSessionOption { int value; } CFURLSessionOption; CURLoption CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_WRITEDATA CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_URL CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PORT CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PROXY CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_USERPWD CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_RANGE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_READDATA CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_ERRORBUFFER CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_TIMEOUT CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_INFILESIZE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_POSTFIELDS CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_REFERER CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_FTPPORT CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_USERAGENT CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_RESUME_FROM CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_COOKIE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_HTTPHEADER CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_HTTPPOST CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SSLCERT CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_KEYPASSWD CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_CRLF CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_QUOTE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_HEADERDATA CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_COOKIEFILE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SSLVERSION CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_TIMEVALUE CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_STDERR CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_POSTQUOTE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_OBSOLETE40 CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_VERBOSE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_HEADER CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_NOPROGRESS CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_NOBODY CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_FAILONERROR CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_UPLOAD CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_POST CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_DIRLISTONLY CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_APPEND CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_NETRC CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PUT CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_AUTOREFERER CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PROXYPORT CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_INTERFACE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_KRBLEVEL CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_CAINFO CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_MAXREDIRS CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_FILETIME CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_MAXCONNECTS //CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_OBSOLETE72 CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_RANDOM_FILE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_EGDSOCKET CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_HTTPGET //CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_COOKIEJAR CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SSLCERTTYPE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SSLKEY CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SSLKEYTYPE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SSLENGINE CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PREQUOTE CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_DEBUGDATA CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_CAPATH CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_BUFFERSIZE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_NOSIGNAL CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SHARE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PROXYTYPE CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PRIVATE CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_HTTPAUTH CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PROXYAUTH CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_IPRESOLVE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_MAXFILESIZE CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_NETRC_FILE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_USE_SSL CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_TCP_NODELAY CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_FTPSSLAUTH CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_IOCTLDATA CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_FTP_ACCOUNT CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_COOKIELIST CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_LOCALPORT CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SOCKOPTDATA CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_FTP_SSL_CCC CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_TIMEOUT_MS CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_POSTREDIR CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SEEKDATA CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_CRLFILE CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_ISSUERCERT CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_CERTINFO CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_USERNAME CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PASSWORD CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_NOPROXY CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PROTOCOLS CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SSH_KEYDATA CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_MAIL_FROM CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_MAIL_RCPT CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_CHUNK_DATA CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_RESOLVE CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_DNS_SERVERS CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SSL_OPTIONS CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_MAIL_AUTH CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_SASL_IR CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> CF_EXPORT CFURLSessionOption const <API key>; // <API key> //CF_EXPORT CFURLSessionOption const <API key>; // <API key> //CF_EXPORT CFURLSessionOption const <API key>; // <API key> //CF_EXPORT CFURLSessionOption const <API key>; // <API key> //CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PROXYHEADER //CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_HEADEROPT //CF_EXPORT CFURLSessionOption const <API key>; // <API key> //CF_EXPORT CFURLSessionOption const <API key>; // <API key> //CF_EXPORT CFURLSessionOption const <API key>; // <API key> //CF_EXPORT CFURLSessionOption const <API key>; // <API key> //CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PATH_AS_IS //CF_EXPORT CFURLSessionOption const <API key>; // <API key> //CF_EXPORT CFURLSessionOption const <API key>; // <API key> //CF_EXPORT CFURLSessionOption const <API key>; // CURLOPT_PIPEWAIT This is a mash-up of these two types: curl_infotype & CURLoption typedef struct CFURLSessionInfo { int value; } CFURLSessionInfo; CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_TEXT CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_HEADER_IN CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_HEADER_OUT CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_DATA_IN CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_DATA_OUT CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const CFURLSessionInfoEND; // CURLINFO_END CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_NONE CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_TOTAL_TIME CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_FILETIME CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_PRIVATE CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_OS_ERRNO CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_COOKIELIST CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_LASTSOCKET CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_PRIMARY_IP CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_CERTINFO CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_LOCAL_IP CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_LOCAL_PORT CF_EXPORT CFURLSessionInfo const <API key>; // <API key> CF_EXPORT CFURLSessionInfo const <API key>; // CURLINFO_LASTONE typedef struct <API key> { int value; } <API key>; CURLMoption CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLMOPT_SOCKETDATA CF_EXPORT <API key> const <API key>; // CURLMOPT_PIPELINING CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLMOPT_TIMERDATA CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // <API key> typedef struct <API key> { int value; } <API key>; CURLMcode CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLM_OK CF_EXPORT <API key> const <API key>; // CURLM_BAD_HANDLE CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLM_OUT_OF_MEMORY CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLM_BAD_SOCKET CF_EXPORT <API key> const <API key>; // <API key> CF_EXPORT <API key> const <API key>; // CURLM_ADDED_ALREADY CF_EXPORT <API key> const <API key>; // CURLM_LAST typedef struct CFURLSessionPoll { int value; } CFURLSessionPoll; CF_EXPORT CFURLSessionPoll const <API key>; // CURL_POLL_NONE CF_EXPORT CFURLSessionPoll const CFURLSessionPollIn; // CURL_POLL_IN CF_EXPORT CFURLSessionPoll const CFURLSessionPollOut; // CURL_POLL_OUT CF_EXPORT CFURLSessionPoll const <API key>; // CURL_POLL_INOUT CF_EXPORT CFURLSessionPoll const <API key>; // CURL_POLL_REMOVE typedef long <API key>; CF_EXPORT <API key> const <API key>; // CURLPROTO_HTTP CF_EXPORT <API key> const <API key>; // CURLPROTO_HTTPS CF_EXPORT <API key> const <API key>; // CURLPROTO_FTP CF_EXPORT <API key> const <API key>; // CURLPROTO_FTPS CF_EXPORT <API key> const <API key>; // CURLPROTO_SCP CF_EXPORT <API key> const <API key>; // CURLPROTO_SFTP CF_EXPORT <API key> const <API key>; // CURLPROTO_TELNET CF_EXPORT <API key> const <API key>; // CURLPROTO_LDAP CF_EXPORT <API key> const <API key>; // CURLPROTO_LDAPS CF_EXPORT <API key> const <API key>; // CURLPROTO_DICT CF_EXPORT <API key> const <API key>; // CURLPROTO_FILE CF_EXPORT <API key> const <API key>; // CURLPROTO_TFTP CF_EXPORT <API key> const <API key>; // CURLPROTO_IMAP CF_EXPORT <API key> const <API key>; // CURLPROTO_IMAPS CF_EXPORT <API key> const <API key>; // CURLPROTO_POP3 CF_EXPORT <API key> const <API key>; // CURLPROTO_POP3S CF_EXPORT <API key> const <API key>; // CURLPROTO_SMTP CF_EXPORT <API key> const <API key>; // CURLPROTO_SMTPS CF_EXPORT <API key> const <API key>; // CURLPROTO_RTSP CF_EXPORT <API key> const <API key>; // CURLPROTO_RTMP CF_EXPORT <API key> const <API key>; // CURLPROTO_RTMPT CF_EXPORT <API key> const <API key>; // CURLPROTO_RTMPE CF_EXPORT <API key> const <API key>; // CURLPROTO_RTMPTE CF_EXPORT <API key> const <API key>; // CURLPROTO_RTMPS CF_EXPORT <API key> const <API key>; // CURLPROTO_RTMPTS CF_EXPORT <API key> const <API key>; // CURLPROTO_GOPHER //CF_EXPORT <API key> const <API key>; // CURLPROTO_SMB //CF_EXPORT <API key> const <API key>; // CURLPROTO_SMBS CF_EXPORT <API key> const <API key>; // CURLPROTO_ALL CF_EXPORT size_t const <API key>; // CURL_MAX_WRITE_SIZE CF_EXPORT char * _Nonnull <API key>(void); typedef struct <API key> { int major; int minor; int patch; } <API key>; CF_EXPORT <API key> <API key>(void); CF_EXPORT int const <API key>; CF_EXPORT int const <API key>; CF_EXPORT int const <API key>; CF_EXPORT int const <API key>; CF_EXPORT int const CFURLSessionSeekOk; CF_EXPORT int const <API key>; CF_EXPORT int const <API key>; CF_EXPORT <API key> _Nonnull <API key>(void); CF_EXPORT void <API key>(<API key> _Nonnull handle); CF_EXPORT <API key> <API key>(<API key> _Nonnull handle, int send, int receive); CF_EXPORT <API key> _Nonnull <API key>(void); CF_EXPORT <API key> <API key>(<API key> _Nonnull handle); CF_EXPORT <API key> <API key>(<API key> _Nonnull handle, <API key> _Nonnull curl); CF_EXPORT <API key> <API key>(<API key> _Nonnull handle, <API key> _Nonnull curl); CF_EXPORT <API key> <API key>(<API key> _Nonnull handle, <API key> socket, void * _Nullable sockp); CF_EXPORT <API key> <API key>(<API key> _Nonnull handle, <API key> socket, int bitmask, int * _Nonnull running_handles); typedef struct <API key> { <API key> _Nullable easyHandle; <API key> resultCode; } <API key>; CF_EXPORT <API key> <API key>(<API key> _Nonnull handle, int * _Nonnull msgs_in_queue); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, void *_Nullable a); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, void *_Nullable a); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, int a); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, long a); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, int64_t a); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, size_t(*_Nonnull a)(char *_Nonnull, size_t, size_t, void *_Nullable)); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, size_t(*_Nonnull a)(char *_Nonnull, size_t, size_t, void *_Nullable)); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, int(*_Nonnull a)(<API key> _Nonnull handle, int type, char *_Nonnull data, size_t size, void *_Nullable userptr)); typedef enum { <API key>, // socket created for a specific IP connection <API key>, } <API key>; typedef int (<API key>)(void *_Nullable clientp, int fd, <API key> purpose); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, <API key> * _Nullable a); typedef int (<API key>)(void *_Nullable userp, int64_t offset, int origin); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, <API key> * _Nullable a); typedef int (<API key>)(void *_Nullable userp, int64_t dltotal, int64_t dlnow, int64_t ultotal, int64_t ulnow); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionOption option, <API key> * _Nullable a); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionInfo info, long *_Nonnull a); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionInfo info, double *_Nonnull a); CF_EXPORT <API key> <API key>(<API key> _Nonnull curl, CFURLSessionInfo info, char *_Nullable*_Nonnull a); CF_EXPORT <API key> <API key>(<API key> _Nonnull multi_handle, <API key> option, void *_Nullable a); CF_EXPORT <API key> <API key>(<API key> _Nonnull multi_handle, <API key> option, long a); CF_EXPORT <API key> <API key>(<API key> _Nonnull multi_handle, <API key> option, int (*_Nonnull a)(<API key> _Nonnull, <API key>, int, void *_Nullable, void *_Nullable)); CF_EXPORT <API key> <API key>(<API key> _Nonnull multi_handle, <API key> option, int (*_Nonnull a)(<API key> _Nonnull, long, void *_Nullable)); CF_EXPORT <API key> CFURLSessionInit(void); typedef struct CFURLSessionSList CFURLSessionSList; CF_EXPORT CFURLSessionSList *_Nullable <API key>(CFURLSessionSList *_Nullable list, const char * _Nullable string); CF_EXPORT void <API key>(CFURLSessionSList *_Nullable list); CF_EXTERN_C_END <API key> #endif /* <API key> */
/* Uncaught exception * Output: <API key> */ function throwsException() { throw new Error(); } function doSomething() { try { throwsException(); } catch (e) { } } function doSomethingElse() { throwsException(); } doSomething(); doSomethingElse();
abstract class AbstractClass { constructor(str: string, other: AbstractClass) { this.method(parseInt(str)); let val = this.prop.toLowerCase(); if (!str) { this.prop = "Hello World"; } this.cb(str); // OK, reference is inside function const innerFunction = () => { return this.prop; } // OK, references are to another instance other.cb(other.prop); } abstract prop: string; abstract cb: (s: string) => void; abstract method(num: number): void; other = this.prop; fn = () => this.prop; method2() { this.prop = this.prop + "!"; } } abstract class <API key> extends AbstractClass { cb = (s: string) => {}; constructor(str: string, other: AbstractClass, yetAnother: <API key>) { super(str, other); // there is no implementation of 'prop' in any base class this.cb(this.prop.toLowerCase()); this.method(1); // OK, references are to another instance other.cb(other.prop); yetAnother.cb(yetAnother.prop); } } class Implementation extends <API key> { prop = ""; cb = (s: string) => {}; constructor(str: string, other: AbstractClass, yetAnother: <API key>) { super(str, other, yetAnother); this.cb(this.prop); } method(n: number) { this.cb(this.prop + n); } } class User { constructor(a: AbstractClass) { a.prop; a.cb("hi"); a.method(12); a.method2(); } }
#!/usr/bin/env python3 class <API key>: <API key> = """ select table_oid, index_name, table_name, array_agg(attname) as column_names from pg_attribute, ( select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index from pg_index, pg_class index_class, pg_class table_class where pg_index.indisunique='t' and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog') and index_class.relkind = 'i' and index_class.oid = pg_index.indexrelid and table_class.oid = pg_index.indrelid ) as <API key> where attnum = column_index and attrelid = table_oid group by table_oid, index_name, table_name; """ def __init__(self): self.<API key> = """ select distinct(gp_segment_id) from ( (select gp_segment_id, %s from gp_dist_random('%s') where (%s) is not null group by gp_segment_id, %s having count(*) > 1) union (select gp_segment_id, %s from %s where (%s) is not null group by gp_segment_id, %s having count(*) > 1) ) as violations """ def runCheck(self, db_connection): unique_indexes = db_connection.query(self.<API key>).getresult() violations = [] for (table_oid, index_name, table_name, column_names) in unique_indexes: column_names = ",".join(column_names) sql = self.<API key>(table_name, column_names) violated_segments = db_connection.query(sql).getresult() if violated_segments: violations.append(dict(table_oid=table_oid, table_name=table_name, index_name=index_name, column_names=column_names, violated_segments=[row[0] for row in violated_segments])) return violations def <API key>(self, table_name, column_names): return self.<API key> % ( column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names )
-- @Description Tests the behavior while compacting is disabled CREATE TABLE uao_eof_truncate (a INT, b INT, c CHAR(128)) WITH (appendonly=true); CREATE INDEX <API key> ON uao_eof_truncate(b); BEGIN; INSERT INTO uao_eof_truncate SELECT i as a, 1 as b, 'hello world' as c FROM generate_series(1,1000) AS i; ANALYZE uao_eof_truncate; COMMIT; BEGIN; INSERT INTO uao_eof_truncate SELECT i as a, 1 as b, 'hello world' as c FROM generate_series(1000,2000) AS i; ROLLBACK; SET <API key>=false; SELECT COUNT(*) FROM uao_eof_truncate; VACUUM uao_eof_truncate; SELECT COUNT(*) FROM uao_eof_truncate; -- Insert afterwards INSERT INTO uao_eof_truncate SELECT i as a, 1 as b, 'hello world' as c FROM generate_series(1,10) AS i; SELECT COUNT(*) FROM uao_eof_truncate;
package org.postgresql.test.jdbc4.jdbc41; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.postgresql.test.TestUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.Properties; public class SchemaTest { private Connection _conn; private boolean dropUserSchema; @Before public void setUp() throws Exception { _conn = TestUtil.openDB(); Statement stmt = _conn.createStatement(); try { stmt.execute("CREATE SCHEMA " + TestUtil.getUser()); dropUserSchema = true; } catch (SQLException e) { /* assume schema existed */ } stmt.execute("CREATE SCHEMA schema1"); stmt.execute("CREATE SCHEMA schema2"); stmt.execute("CREATE SCHEMA \"schema 3\""); stmt.execute("CREATE SCHEMA \"schema \"\"4\""); stmt.execute("CREATE SCHEMA \"schema '5\""); stmt.execute("CREATE SCHEMA \"schema ,6\""); stmt.execute("CREATE SCHEMA \"UpperCase\""); TestUtil.createTable(_conn, "schema1.table1", "id integer"); TestUtil.createTable(_conn, "schema2.table2", "id integer"); TestUtil.createTable(_conn, "\"UpperCase\".table3", "id integer"); TestUtil.createTable(_conn, "schema1.sptest", "id integer"); TestUtil.createTable(_conn, "schema2.sptest", "id varchar"); } @After public void tearDown() throws SQLException { _conn.setAutoCommit(true); _conn.setSchema(null); Statement stmt = _conn.createStatement(); if (dropUserSchema) { stmt.execute("DROP SCHEMA " + TestUtil.getUser() + " CASCADE"); } stmt.execute("DROP SCHEMA schema1 CASCADE"); stmt.execute("DROP SCHEMA schema2 CASCADE"); stmt.execute("DROP SCHEMA \"schema 3\" CASCADE"); stmt.execute("DROP SCHEMA \"schema \"\"4\" CASCADE"); stmt.execute("DROP SCHEMA \"schema '5\" CASCADE"); stmt.execute("DROP SCHEMA \"schema ,6\""); stmt.execute("DROP SCHEMA \"UpperCase\" CASCADE"); TestUtil.closeDB(_conn); } /** * Test that what you set is what you get */ @Test public void testGetSetSchema() throws SQLException { _conn.setSchema("schema1"); assertEquals("schema1", _conn.getSchema()); _conn.setSchema("schema2"); assertEquals("schema2", _conn.getSchema()); _conn.setSchema("schema 3"); assertEquals("schema 3", _conn.getSchema()); _conn.setSchema("schema \"4"); assertEquals("schema \"4", _conn.getSchema()); _conn.setSchema("schema '5"); assertEquals("schema '5", _conn.getSchema()); _conn.setSchema("UpperCase"); assertEquals("UpperCase", _conn.getSchema()); } /** * Test that setting the schema allows to access objects of this schema without prefix, hide * objects from other schemas but doesn't prevent to prefix-access to them. */ @Test public void testUsingSchema() throws SQLException { Statement stmt = _conn.createStatement(); try { try { _conn.setSchema("schema1"); stmt.executeQuery(TestUtil.selectSQL("table1", "*")); stmt.executeQuery(TestUtil.selectSQL("schema2.table2", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table2", "*")); fail("Objects of schema2 should not be visible without prefix"); } catch (SQLException e) { // expected } _conn.setSchema("schema2"); stmt.executeQuery(TestUtil.selectSQL("table2", "*")); stmt.executeQuery(TestUtil.selectSQL("schema1.table1", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table1", "*")); fail("Objects of schema1 should not be visible without prefix"); } catch (SQLException e) { // expected } _conn.setSchema("UpperCase"); stmt.executeQuery(TestUtil.selectSQL("table3", "*")); stmt.executeQuery(TestUtil.selectSQL("schema1.table1", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table1", "*")); fail("Objects of schema1 should not be visible without prefix"); } catch (SQLException e) { // expected } } catch (SQLException e) { fail("Could not find expected schema elements: " + e.getMessage()); } } finally { try { stmt.close(); } catch (SQLException e) { } } } /** * Test that get schema returns the schema with the highest priority in the search path */ @Test public void <API key>() throws SQLException { execute("SET search_path TO schema1,schema2"); assertEquals("schema1", _conn.getSchema()); execute("SET search_path TO \"schema ,6\",schema2"); assertEquals("schema ,6", _conn.getSchema()); } @Test public void <API key>() throws Exception { Properties properties = new Properties(); properties.setProperty("currentSchema", "schema1"); Connection conn = TestUtil.openDB(properties); try { assertEquals("schema1", conn.getSchema()); Statement stmt = conn.createStatement(); stmt.executeQuery(TestUtil.selectSQL("table1", "*")); stmt.executeQuery(TestUtil.selectSQL("schema2.table2", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table2", "*")); fail("Objects of schema2 should not be visible without prefix"); } catch (SQLException e) { // expected } } finally { TestUtil.closeDB(conn); } } @Test public void testSchemaPath$User() throws Exception { execute("SET search_path TO \"$user\",public,schema2"); assertEquals(TestUtil.getUser(), _conn.getSchema()); } private void execute(String sql) throws SQLException { Statement stmt = _conn.createStatement(); try { stmt.execute(sql); } finally { try { stmt.close(); } catch (SQLException e) { } } } @Test public void <API key>() throws SQLException { _conn.setAutoCommit(false); <API key>(); } @Test public void <API key>() throws SQLException { <API key>(); } @Test public void <API key>() throws SQLException { execute("set search_path to schema1,public"); PreparedStatement ps = _conn.prepareStatement("select * from sptest"); for (int i = 0; i < 10; i++) { ps.execute(); } assertColType(ps, "sptest should point to schema1.sptest, thus column type should be INT", Types.INTEGER); ps.close(); execute("set search_path to schema2,public"); ps = _conn.prepareStatement("select * from sptest"); assertColType(ps, "sptest should point to schema2.sptest, thus column type should be VARCHAR", Types.VARCHAR); ps.close(); } private void assertColType(PreparedStatement ps, String message, int expected) throws SQLException { ResultSet rs = ps.executeQuery(); ResultSetMetaData md = rs.getMetaData(); int columnType = md.getColumnType(1); assertEquals(message, expected, columnType); rs.close(); } }
#ifndef <API key> #define <API key> #include "simd_t.h" namespace bx { BX_ALIGN_DECL_16(struct) float4x4_t { simd128_t col[4]; }; <API key> simd128_t simd_mul_xyz1(simd128_t _a, const float4x4_t* _b) { const simd128_t xxxx = simd_swiz_xxxx(_a); const simd128_t yyyy = simd_swiz_yyyy(_a); const simd128_t zzzz = simd_swiz_zzzz(_a); const simd128_t col0 = simd_mul(_b->col[0], xxxx); const simd128_t col1 = simd_mul(_b->col[1], yyyy); const simd128_t col2 = simd_madd(_b->col[2], zzzz, col0); const simd128_t col3 = simd_add(_b->col[3], col1); const simd128_t result = simd_add(col2, col3); return result; } <API key> simd128_t simd_mul(simd128_t _a, const float4x4_t* _b) { const simd128_t xxxx = simd_swiz_xxxx(_a); const simd128_t yyyy = simd_swiz_yyyy(_a); const simd128_t zzzz = simd_swiz_zzzz(_a); const simd128_t wwww = simd_swiz_wwww(_a); const simd128_t col0 = simd_mul(_b->col[0], xxxx); const simd128_t col1 = simd_mul(_b->col[1], yyyy); const simd128_t col2 = simd_madd(_b->col[2], zzzz, col0); const simd128_t col3 = simd_madd(_b->col[3], wwww, col1); const simd128_t result = simd_add(col2, col3); return result; } BX_SIMD_INLINE void float4x4_mul(float4x4_t* __restrict _result, const float4x4_t* __restrict _a, const float4x4_t* __restrict _b) { _result->col[0] = simd_mul(_a->col[0], _b); _result->col[1] = simd_mul(_a->col[1], _b); _result->col[2] = simd_mul(_a->col[2], _b); _result->col[3] = simd_mul(_a->col[3], _b); } <API key> void float4x4_transpose(float4x4_t* __restrict _result, const float4x4_t* __restrict _mtx) { const simd128_t aibj = simd_shuf_xAyB(_mtx->col[0], _mtx->col[2]); // aibj const simd128_t emfn = simd_shuf_xAyB(_mtx->col[1], _mtx->col[3]); // emfn const simd128_t ckdl = simd_shuf_zCwD(_mtx->col[0], _mtx->col[2]); // ckdl const simd128_t gohp = simd_shuf_zCwD(_mtx->col[1], _mtx->col[3]); // gohp _result->col[0] = simd_shuf_xAyB(aibj, emfn); // aeim _result->col[1] = simd_shuf_zCwD(aibj, emfn); // bfjn _result->col[2] = simd_shuf_xAyB(ckdl, gohp); // cgko _result->col[3] = simd_shuf_zCwD(ckdl, gohp); // dhlp } BX_SIMD_INLINE void float4x4_inverse(float4x4_t* __restrict _result, const float4x4_t* __restrict _a) { const simd128_t tmp0 = simd_shuf_xAzC(_a->col[0], _a->col[1]); const simd128_t tmp1 = simd_shuf_xAzC(_a->col[2], _a->col[3]); const simd128_t tmp2 = simd_shuf_yBwD(_a->col[0], _a->col[1]); const simd128_t tmp3 = simd_shuf_yBwD(_a->col[2], _a->col[3]); const simd128_t t0 = simd_shuf_xyAB(tmp0, tmp1); const simd128_t t1 = simd_shuf_xyAB(tmp3, tmp2); const simd128_t t2 = simd_shuf_zwCD(tmp0, tmp1); const simd128_t t3 = simd_shuf_zwCD(tmp3, tmp2); const simd128_t t23 = simd_mul(t2, t3); const simd128_t t23_yxwz = simd_swiz_yxwz(t23); const simd128_t t23_wzyx = simd_swiz_wzyx(t23); simd128_t cof0, cof1, cof2, cof3; const simd128_t zero = simd_zero(); cof0 = simd_nmsub(t1, t23_yxwz, zero); cof0 = simd_madd(t1, t23_wzyx, cof0); cof1 = simd_nmsub(t0, t23_yxwz, zero); cof1 = simd_madd(t0, t23_wzyx, cof1); cof1 = simd_swiz_zwxy(cof1); const simd128_t t12 = simd_mul(t1, t2); const simd128_t t12_yxwz = simd_swiz_yxwz(t12); const simd128_t t12_wzyx = simd_swiz_wzyx(t12); cof0 = simd_madd(t3, t12_yxwz, cof0); cof0 = simd_nmsub(t3, t12_wzyx, cof0); cof3 = simd_mul(t0, t12_yxwz); cof3 = simd_nmsub(t0, t12_wzyx, cof3); cof3 = simd_swiz_zwxy(cof3); const simd128_t t1_zwxy = simd_swiz_zwxy(t1); const simd128_t t2_zwxy = simd_swiz_zwxy(t2); const simd128_t t13 = simd_mul(t1_zwxy, t3); const simd128_t t13_yxwz = simd_swiz_yxwz(t13); const simd128_t t13_wzyx = simd_swiz_wzyx(t13); cof0 = simd_madd(t2_zwxy, t13_yxwz, cof0); cof0 = simd_nmsub(t2_zwxy, t13_wzyx, cof0); cof2 = simd_mul(t0, t13_yxwz); cof2 = simd_nmsub(t0, t13_wzyx, cof2); cof2 = simd_swiz_zwxy(cof2); const simd128_t t01 = simd_mul(t0, t1); const simd128_t t01_yxwz = simd_swiz_yxwz(t01); const simd128_t t01_wzyx = simd_swiz_wzyx(t01); cof2 = simd_nmsub(t3, t01_yxwz, cof2); cof2 = simd_madd(t3, t01_wzyx, cof2); cof3 = simd_madd(t2_zwxy, t01_yxwz, cof3); cof3 = simd_nmsub(t2_zwxy, t01_wzyx, cof3); const simd128_t t03 = simd_mul(t0, t3); const simd128_t t03_yxwz = simd_swiz_yxwz(t03); const simd128_t t03_wzyx = simd_swiz_wzyx(t03); cof1 = simd_nmsub(t2_zwxy, t03_yxwz, cof1); cof1 = simd_madd(t2_zwxy, t03_wzyx, cof1); cof2 = simd_madd(t1, t03_yxwz, cof2); cof2 = simd_nmsub(t1, t03_wzyx, cof2); const simd128_t t02 = simd_mul(t0, t2_zwxy); const simd128_t t02_yxwz = simd_swiz_yxwz(t02); const simd128_t t02_wzyx = simd_swiz_wzyx(t02); cof1 = simd_madd(t3, t02_yxwz, cof1); cof1 = simd_nmsub(t3, t02_wzyx, cof1); cof3 = simd_nmsub(t1, t02_yxwz, cof3); cof3 = simd_madd(t1, t02_wzyx, cof3); const simd128_t det = simd_dot(t0, cof0); const simd128_t invdet = simd_rcp(det); _result->col[0] = simd_mul(cof0, invdet); _result->col[1] = simd_mul(cof1, invdet); _result->col[2] = simd_mul(cof2, invdet); _result->col[3] = simd_mul(cof3, invdet); } } // namespace bx #endif // <API key>
# Tests for XlsxWriter. import unittest from ...compatibility import StringIO from ...worksheet import Worksheet class TestWriteWorksheet(unittest.TestCase): """ Test the Worksheet _write_worksheet() method. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def <API key>(self): """Test the _write_worksheet() method""" self.worksheet._write_worksheet() exp = got = self.fh.getvalue() self.assertEqual(got, exp)
class Jellyfish < Formula desc "Fast, memory-efficient counting of DNA k-mers" homepage "http: url "https://github.com/gmarcais/Jellyfish/releases/download/v2.3.0/jellyfish-2.3.0.tar.gz" sha256 "<SHA256-like>" license any_of: ["BSD-3-Clause", "GPL-3.0-or-later"] bottle do sha256 cellar: :any, arm64_monterey: "<SHA256-like>" sha256 cellar: :any, arm64_big_sur: "<SHA256-like>" sha256 cellar: :any, monterey: "<SHA256-like>" sha256 cellar: :any, big_sur: "<SHA256-like>" sha256 cellar: :any, catalina: "<SHA256-like>" sha256 cellar: :any, mojave: "<SHA256-like>" sha256 cellar: :any_skip_relocation, x86_64_linux: "<SHA256-like>" end depends_on "autoconf@2.69" => :build depends_on "automake" => :build depends_on "gettext" => :build depends_on "libtool" => :build depends_on "pkg-config" => :build depends_on "htslib" def install # autoreconf to fix flat namespace detection bug. system "autoreconf", "-fvi" system "./configure", *std_configure_args system "make" system "make", "install" end test do (testpath/"test.fa").write <<~EOS >Homebrew <API key> EOS system "#{bin}/jellyfish", "count", "-m17", "-s100M", "-t2", "-C", "test.fa" assert_match "1 54", shell_output("#{bin}/jellyfish histo mer_counts.jf") assert_match(/Unique:\s+54/, shell_output("#{bin}/jellyfish stats mer_counts.jf")) end end
package org.atmosphere.cpr import java.net.URI import org.scalatra.atmosphere.{ <API key>, ScalatraBroadcaster } trait BroadcasterConf { def broadcasterClass: Class[_ <: ScalatraBroadcaster] def uri: URI def extraSetup: Broadcaster => Unit // To perform optional plugin-specific Broadcaster setup } sealed case class <API key>(broadcasterClass: Class[_ <: ScalatraBroadcaster], uri: URI = URI.create("http://127.0.0.1"), extraSetup: Broadcaster => Unit = { b => }) extends BroadcasterConf /** * Convenient configuration class for RedisBroadcaster * * Using this class will automatically take care of setting Redis auth on the underlying * RedisBroadcaster if the auth parameter is given an argument * * @param uri [[URI]] for the Redis Server. Defaults to redis://127.0.0.1:6379 * @param auth An Option[String] if the Redis Server requires a password. Defaults to None */ sealed case class <API key>(uri: URI = URI.create("redis://127.0.0.1:6379"), auth: Option[String] = None) extends BroadcasterConf { final def broadcasterClass = classOf[<API key>] final def extraSetup = { b: Broadcaster => auth.foreach(b.asInstanceOf[<API key>].setAuth(_)) } }
// SeqAn - The Library for Sequence Analysis // modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // 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 KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. #ifndef <API key> #define <API key> namespace <API key> { // AhoCorasick /** .Spec.AhoCorasick: ..summary: Multiple exact string matching using Aho-Corasick. ..general:Class.Pattern ..cat:Searching ..signature:Pattern<TNeedle, AhoCorasick> ..param.TNeedle:The needle type, a string of keywords. type:Class.String ..remarks.text:The types of the keywords in the needle container and the haystack have to match. ..remarks.text:Matching positions do not come in order because we report beginning positions of matches. ..remarks.text:Likewise, if multiple keywords match at a given position no pre-specified order is guaranteed. ..include:seqan/find.h */ .Class.Pattern.param.TSpec.type:Spec.AhoCorasick struct AhoCorasick_; typedef Tag<AhoCorasick_> AhoCorasick; template <typename TNeedle> class Pattern<TNeedle, AhoCorasick> { //<API key> private: Pattern(Pattern const& other); Pattern const& operator=(Pattern const & other); //<API key> public: typedef typename Size<TNeedle>::Type TSize; typedef typename Value<TNeedle>::Type TKeyword; typedef typename Value<TKeyword>::Type TAlphabet; typedef Graph<Automaton<TAlphabet> > TGraph; typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor; Holder<TNeedle> data_host; String<TVertexDescriptor> data_supplyMap; String<String<TSize> > <API key>; TGraph data_graph; // To restore the automaton after a hit String<TSize> data_endPositions; // All remaining keyword indices TSize data_keywordIndex; // Current keyword that produced a hit TSize data_needleLength; // Last length of needle to reposition finder TVertexDescriptor data_lastState; // Last state in the trie //<API key> Pattern() { } template <typename TNeedle2> Pattern(TNeedle2 const & ndl) { SEQAN_CHECKPOINT setHost(*this, ndl); } ~Pattern() { SEQAN_CHECKPOINT } //<API key> }; // Host Metafunctions template <typename TNeedle> struct Host< Pattern<TNeedle, AhoCorasick> > { typedef TNeedle Type; }; template <typename TNeedle> struct Host< Pattern<TNeedle, AhoCorasick> const> { typedef TNeedle const Type; }; // Functions template <typename TNeedle> inline void _createAcTrie(Pattern<TNeedle, AhoCorasick> & me) { typedef typename Position<TNeedle>::Type TPosition; typedef typename Value<TNeedle>::Type TKeyword; typedef typename Value<TKeyword>::Type TAlphabet; typedef Graph<Automaton<TAlphabet> > TGraph; typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor; TVertexDescriptor nilVal = getNil<TVertexDescriptor>(); // Create regular trie createTrie(me.data_graph,me.<API key>, host(me)); // Create parent map String<TVertexDescriptor> parentMap; String<TAlphabet> parentCharMap; resizeVertexMap(me.data_graph,parentMap); resizeVertexMap(me.data_graph,parentCharMap); for(TPosition i = 0;i<length(parentMap);++i) { assignProperty(parentMap, i, nilVal); } typedef typename Iterator<TGraph, EdgeIterator>::Type TEdgeIterator; TEdgeIterator itEd(me.data_graph); for(;!atEnd(itEd);goNext(itEd)) { assignProperty(parentMap, targetVertex(itEd), sourceVertex(itEd)); assignProperty(parentCharMap, targetVertex(itEd), label(itEd)); } // Build AC TVertexDescriptor root = getRoot(me.data_graph); resizeVertexMap(me.data_graph,me.data_supplyMap); assignProperty(me.data_supplyMap, root, nilVal); // Bfs Traversal typedef typename Iterator<TGraph, BfsIterator>::Type TBfsIterator; TBfsIterator it(me.data_graph,root); for(;!atEnd(it);goNext(it)) { if (atBegin(it)) continue; TVertexDescriptor parent = getProperty(parentMap, *it); TAlphabet sigma = getProperty(parentCharMap, *it); TVertexDescriptor down = getProperty(me.data_supplyMap, parent); while ((down != nilVal) && (getSuccessor(me.data_graph, down, sigma) == nilVal)) { down = getProperty(me.data_supplyMap, down); } if (down != nilVal) { assignProperty(me.data_supplyMap, *it, getSuccessor(me.data_graph, down, sigma)); String<TPosition> endPositions = getProperty(me.<API key>, getProperty(me.data_supplyMap, *it)); if (!empty(endPositions)) { String<TPosition> endPositionsCurrent = getProperty(me.<API key>, *it); typedef typename Iterator<String<TPosition>, Rooted >::Type TStringIterator; TStringIterator sit = begin(endPositions); for(;!atEnd(sit);goNext(sit)) { appendValue(endPositionsCurrent, *sit); } assignProperty(me.<API key>, *it, endPositionsCurrent); } } else { assignProperty(me.data_supplyMap, *it, root); } } } template <typename TNeedle, typename TNeedle2> void setHost (Pattern<TNeedle, AhoCorasick> & me, TNeedle2 const & needle) { SEQAN_CHECKPOINT; SEQAN_ASSERT_NOT(empty(needle)); setValue(me.data_host, needle); clear(me.data_graph); clear(me.data_supplyMap); clear(me.data_endPositions); clear(me.<API key>); _createAcTrie(me); me.data_needleLength = 0; //fstream strm; //strm.open(TEST_PATH "my_trie.dot", ios_base::out | ios_base::trunc); //String<String<char> > nodeMap; //<API key>(me.data_graph, me.<API key>, nodeMap); //String<String<char> > edgeMap; //<API key>(me.data_graph,edgeMap); //write(strm,me.data_graph,nodeMap,edgeMap,DotDrawing()); //strm.close(); // Supply links //for(unsigned int i=0;i<length(me.data_supplyMap);++i) { // std::cout << i << "->" << getProperty(me.data_supplyMap,i) << ::std::endl; } template <typename TNeedle, typename TNeedle2> inline void setHost (Pattern<TNeedle, AhoCorasick> & me, TNeedle2 & needle) { setHost(me, reinterpret_cast<TNeedle2 const &>(needle)); } //<API key> template <typename TNeedle> inline void _patternInit (Pattern<TNeedle, AhoCorasick> & me) { SEQAN_CHECKPOINT clear(me.data_endPositions); me.data_keywordIndex = 0; me.data_lastState = getRoot(me.data_graph); } //<API key> template <typename TNeedle> inline typename Size<TNeedle>::Type position(Pattern<TNeedle, AhoCorasick> & me) { return me.data_keywordIndex; } template <typename TFinder, typename TNeedle> inline bool find(TFinder & finder, Pattern<TNeedle, AhoCorasick> & me) { typedef typename Value<TNeedle>::Type TKeyword; typedef typename Value<TKeyword>::Type TAlphabet; typedef Graph<Automaton<TAlphabet> > TGraph; typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor; if (empty(finder)) { _patternInit(me); _finderSetNonEmpty(finder); } else { finder += me.data_needleLength; ++finder; // Set forward the finder } // Process left-over hits if (!empty(me.data_endPositions)) { --finder; // Set back the finder me.data_keywordIndex = me.data_endPositions[length(me.data_endPositions)-1]; me.data_needleLength = length(value(host(me), me.data_keywordIndex))-1; if (length(me.data_endPositions) > 1) resize(me.data_endPositions, (length(me.data_endPositions)-1)); else clear(me.data_endPositions); finder -= me.data_needleLength; _setFinderLength(finder, me.data_needleLength+1); _setFinderEnd(finder, position(finder)+length(finder)); return true; } TVertexDescriptor current = me.data_lastState; TVertexDescriptor nilVal = getNil<TVertexDescriptor>(); while (!atEnd(finder)) { while ((getSuccessor(me.data_graph, current, *finder) == nilVal) && (getProperty(me.data_supplyMap, current) != nilVal)) { current = getProperty(me.data_supplyMap,current); } if (getSuccessor(me.data_graph, current, *finder) != nilVal) { current = getSuccessor(me.data_graph, current, *finder); } else { current = getRoot(me.data_graph); } me.data_endPositions = getProperty(me.<API key>,current); if (!empty(me.data_endPositions)) { me.data_keywordIndex = me.data_endPositions[length(me.data_endPositions)-1]; me.data_needleLength = length(value(host(me), me.data_keywordIndex))-1; if (length(me.data_endPositions) > 1) resize(me.data_endPositions, length(me.data_endPositions)-1); else clear(me.data_endPositions); me.data_lastState = current; finder -= me.data_needleLength; _setFinderLength(finder, me.data_needleLength+1); _setFinderEnd(finder, position(finder)+length(finder)); return true; } ++finder; } return false; } }// namespace <API key> #endif //#ifndef <API key>
<?php class <API key> implements <API key> { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array( T_CLASS, T_INTERFACE, ); }//end register() /** * Processes this test, when one of its tokens is encountered. * * @param <API key> $phpcsFile The current file being processed. * @param int $stackPtr The position of the current token in the * stack passed in $tokens. * * @return void */ public function process(<API key> $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if (isset($tokens[$stackPtr]['scope_opener']) === false) { $error = 'Possible parse error: %s missing opening or closing brace'; $data = array($tokens[$stackPtr]['content']); $phpcsFile->addWarning($error, $stackPtr, 'MissingBrace', $data); return; } // Determine the name of the class or interface. Note that we cannot // simply look for the first T_STRING because a class name // starting with the number will be multiple tokens. $opener = $tokens[$stackPtr]['scope_opener']; $nameStart = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), $opener, true); $nameEnd = $phpcsFile->findNext(T_WHITESPACE, $nameStart, $opener); $name = trim($phpcsFile->getTokensAsString($nameStart, ($nameEnd - $nameStart))); // Check for camel caps format. $valid = PHP_CodeSniffer::isCamelCaps($name, true, true, false); if ($valid === false) { $type = ucfirst($tokens[$stackPtr]['content']); $error = '%s name "%s" is not in camel caps format'; $data = array( $type, $name, ); $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $data); } }//end process() }//end class ?>
#include <nuttx/config.h> #include <unistd.h> #include <pthread.h> #include <sched.h> #include <errno.h> #include <debug.h> #include "pthread_internal.h" int pthread_cond_wait(FAR pthread_cond_t *cond, FAR pthread_mutex_t *mutex) { int ret; sdbg("cond=0x%p mutex=0x%p\n", cond, mutex); /* Make sure that non-NULL references were provided. */ if (!cond || !mutex) { ret = EINVAL; } /* Make sure that the caller holds the mutex */ else if (mutex->pid != (int)getpid()) { ret = EPERM; } else { /* Give up the mutex */ sdbg("Give up mutex / take cond\n"); sched_lock(); mutex->pid = 0; ret = <API key>((sem_t*)&mutex->sem); /* Take the semaphore */ ret |= <API key>((sem_t*)&cond->sem); sched_unlock(); /* Reacquire the mutex */ sdbg("Reacquire mutex...\n"); ret |= <API key>((sem_t*)&mutex->sem); if (!ret) { mutex->pid = getpid();; } } sdbg("Returning %d\n", ret); return ret; }
<?php namespace yii\helpers; /** * Console helper provides useful methods for command line related tasks such as getting input or formatting and coloring * output. * * @author Carsten Brandt <mail@cebe.cc> * @since 2.0 */ class Console extends BaseConsole { }
'use strict'; const {<API key>} = require('../Utilities/PolyfillFunctions'); let navigator = global.navigator; if (navigator === undefined) { global.navigator = navigator = {}; } <API key>(navigator, 'product', () => 'ReactNative');
#include <assert.h> #include <stdint.h> #include <string.h> #include <lib/mmio.h> #include <lib/fconf/fconf.h> #include <plat/arm/common/plat_arm.h> #include <plat/arm/common/<API key>.h> #include <plat/common/platform.h> #include <platform_def.h> #include <tools_share/tbbr_oid.h> /* * Return the ROTPK hash in the following ASN.1 structure in DER format: * * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL * } * * DigestInfo ::= SEQUENCE { * digestAlgorithm AlgorithmIdentifier, * digest OCTET STRING * } */ int plat_get_rotpk_info(void *cookie, void **key_ptr, unsigned int *key_len, unsigned int *flags) { return arm_get_rotpk_info(cookie, key_ptr, key_len, flags); } /* * Store a new non-volatile counter value. * * On some FVP versions, the non-volatile counters are read-only so this * function will always fail. * * Return: 0 = success, Otherwise = error */ int plat_set_nv_ctr(void *cookie, unsigned int nv_ctr) { const char *oid; uintptr_t nv_ctr_addr; assert(cookie != NULL); oid = (const char *)cookie; if (strcmp(oid, <API key>) == 0) { nv_ctr_addr = FCONF_GET_PROPERTY(cot, nv_cntr_addr, TRUSTED_NV_CTR_ID); } else if (strcmp(oid, <API key>) == 0) { nv_ctr_addr = FCONF_GET_PROPERTY(cot, nv_cntr_addr, <API key>); } else { return 1; } mmio_write_32(nv_ctr_addr, nv_ctr); /* * If the FVP models a locked counter then its value cannot be updated * and the above write operation has been silently ignored. */ return (mmio_read_32(nv_ctr_addr) == nv_ctr) ? 0 : 1; }
require 'nn' local <API key>, parent = torch.class('nn.<API key>', 'nn.Module') function <API key>:__init(inputFrameSize, outputFrameSize, kW, dW) parent.__init(self) dW = dW or 1 self.inputFrameSize = inputFrameSize self.outputFrameSize = outputFrameSize self.kW = kW self.dW = dW self.weight = torch.Tensor(outputFrameSize, kW, inputFrameSize) self.bias = torch.Tensor(outputFrameSize) self.gradWeight = torch.Tensor(outputFrameSize, kW, inputFrameSize) self.gradBias = torch.Tensor(outputFrameSize) self:reset() end function <API key>:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.inputFrameSize) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function <API key>:updateOutput(input) input.nn.<API key>(self, input) return self.output end function <API key>:updateGradInput(input, gradOutput) if self.gradInput then return input.nn.<API key>( self, input, gradOutput) end end function <API key>:accGradParameters(input, gradOutput, scale) scale = scale or 1 input.nn.<API key>( self, input, gradOutput, scale) end -- we do not need to accumulate parameters when sharing <API key>.<API key> = <API key>.<API key>
#include <iostream> #include <seqan/file.h> #include <seqan/sequence.h> #include <seqan/score.h> using namespace seqan; template <typename TText, typename TPattern> int computeLocalScore(TText const & subText, TPattern const & pattern) { int localScore = 0; for (unsigned i = 0; i < length(pattern); ++i) if (subText[i] == pattern[i]) ++localScore; return localScore; } template <typename TText, typename TPattern> String<int> computeScore(TText const & text, TPattern const & pattern) { String<int> score; resize(score, length(text) - length(pattern) + 1, 0); for (unsigned i = 0; i < length(text) - length(pattern) + 1; ++i) score[i] = computeLocalScore(infix(text, i, i + length(pattern)), pattern); return score; } void print(String<int> const & text) { for (unsigned i = 0; i < length(text); ++i) std::cout << text[i] << " "; std::cout << std::endl; } int main() { String<char> text = "This is an awesome tutorial to get to know SeqAn!"; String<char> pattern = "tutorial"; String<int> score = computeScore(text, pattern); print(score); return 0; }
module Stupidedi module Versions module FunctionalGroups module ThirtyForty module SegmentDefs s = Schema e = ElementDefs r = ElementReqs MS1 = s::SegmentDef.build(:MS1, "Equipment, Shipment, or Real Property Location", "To specify the location of a piece of equipment, a shipment, or real property in terms of city and state for the stop location that relates to the AT7 shipment status details.", e::E19 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E156 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E26 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E1654.simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E1655.simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E1280.simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E1280.simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E116 .simple_use(r::Optional, s::RepeatCount.bounded(1)), SyntaxNotes::L.build(1, 2, 3), SyntaxNotes::E.build(1, 4), SyntaxNotes::C.build(2, 1), SyntaxNotes::C.build(3, 1), SyntaxNotes::P.build(4, 5), SyntaxNotes::C.build(6, 4), SyntaxNotes::C.build(7, 4), SyntaxNotes::C.build(8, 1)) end end end end end
#include "chrome/browser/extensions/convert_web_app.h" #include <cmath> #include <limits> #include <string> #include <vector> #include "base/base64.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/json/<API key>.h" #include "base/logging.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/stringprintf.h" #include "base/time.h" #include "base/<API key>.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/<API key>.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/web_apps.h" #include "crypto/sha2.h" #include "googleurl/src/gurl.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" namespace keys = <API key>; using base::Time; namespace { const char kIconsDirName[] = "icons"; // Create the public key for the converted web app. // Web apps are not signed, but the public key for an extension doubles as // its unique identity, and we need one of those. A web app's unique identity // is its manifest URL, so we hash that to create a public key. There will be // no corresponding private key, which means that these extensions cannot be // auto-updated using ExtensionUpdater. But Chrome does notice updates to the // manifest and regenerates these extensions. std::string GenerateKey(const GURL& manifest_url) { char raw[crypto::kSHA256Length] = {0}; std::string key; crypto::SHA256HashString(manifest_url.spec().c_str(), raw, crypto::kSHA256Length); base::Base64Encode(std::string(raw, crypto::kSHA256Length), &key); return key; } } // Generates a version for the converted app using the current date. This isn't // really needed, but it seems like useful information. std::string <API key>(const Time& create_time) { Time::Exploded <API key>; create_time.UTCExplode(&<API key>); double micros = static_cast<double>( (<API key>.millisecond * Time::<API key>) + (<API key>.second * Time::<API key>) + (<API key>.minute * Time::<API key>) + (<API key>.hour * Time::<API key>)); double day_fraction = micros / Time::kMicrosecondsPerDay; double stamp = day_fraction * std::numeric_limits<uint16>::max(); // Ghetto-round, since VC++ doesn't have round(). stamp = stamp >= (floor(stamp) + 0.5) ? (stamp + 1) : stamp; return base::StringPrintf("%i.%i.%i.%i", <API key>.year, <API key>.month, <API key>.day_of_month, static_cast<uint16>(stamp)); } scoped_refptr<Extension> <API key>( const WebApplicationInfo& web_app, const Time& create_time) { FilePath user_data_temp_dir = extension_file_util::GetUserDataTempDir(); if (user_data_temp_dir.empty()) { LOG(ERROR) << "Could not get path to profile temporary directory."; return NULL; } ScopedTempDir temp_dir; if (!temp_dir.<API key>(user_data_temp_dir)) { LOG(ERROR) << "Could not create temporary directory."; return NULL; } // Create the manifest scoped_ptr<DictionaryValue> root(new DictionaryValue); if (!web_app.is_bookmark_app) root->SetString(keys::kPublicKey, GenerateKey(web_app.manifest_url)); else root->SetString(keys::kPublicKey, GenerateKey(web_app.app_url)); root->SetString(keys::kName, UTF16ToUTF8(web_app.title)); root->SetString(keys::kVersion, <API key>(create_time)); root->SetString(keys::kDescription, UTF16ToUTF8(web_app.description)); root->SetString(keys::kLaunchWebURL, web_app.app_url.spec()); if (!web_app.launch_container.empty()) root->SetString(keys::kLaunchContainer, web_app.launch_container); // Add the icons. DictionaryValue* icons = new DictionaryValue(); root->Set(keys::kIcons, icons); for (size_t i = 0; i < web_app.icons.size(); ++i) { std::string size = StringPrintf("%i", web_app.icons[i].width); std::string icon_path = StringPrintf("%s/%s.png", kIconsDirName, size.c_str()); icons->SetString(size, icon_path); } ListValue* permissions = new ListValue(); root->Set(keys::kPermissions, permissions); for (size_t i = 0; i < web_app.permissions.size(); ++i) { permissions->Append(Value::CreateStringValue(web_app.permissions[i])); } // Add the URLs. ListValue* urls = new ListValue(); root->Set(keys::kWebURLs, urls); for (size_t i = 0; i < web_app.urls.size(); ++i) { urls->Append(Value::CreateStringValue(web_app.urls[i].spec())); } // Write the manifest. FilePath manifest_path = temp_dir.path().Append( Extension::kManifestFilename); <API key> serializer(manifest_path); if (!serializer.Serialize(*root)) { LOG(ERROR) << "Could not serialize manifest."; return NULL; } // Write the icon files. FilePath icons_dir = temp_dir.path().AppendASCII(kIconsDirName); if (!file_util::CreateDirectory(icons_dir)) { LOG(ERROR) << "Could not create icons directory."; return NULL; } for (size_t i = 0; i < web_app.icons.size(); ++i) { // Skip unfetched bitmaps. if (web_app.icons[i].data.config() == SkBitmap::kNo_Config) continue; FilePath icon_file = icons_dir.AppendASCII( StringPrintf("%i.png", web_app.icons[i].width)); std::vector<unsigned char> image_data; if (!gfx::PNGCodec::EncodeBGRASkBitmap(web_app.icons[i].data, false, &image_data)) { LOG(ERROR) << "Could not create icon file."; return NULL; } const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(icon_file, image_data_ptr, image_data.size())) { LOG(ERROR) << "Could not write icon file."; return NULL; } } // Finally, create the extension object to represent the unpacked directory. std::string error; int extension_flags = Extension::STRICT_ERROR_CHECKS; if (web_app.is_bookmark_app) extension_flags |= Extension::FROM_BOOKMARK; scoped_refptr<Extension> extension = Extension::Create( temp_dir.path(), Extension::INTERNAL, *root, extension_flags, &error); if (!extension) { LOG(ERROR) << error; return NULL; } temp_dir.Take(); // The caller takes ownership of the directory. return extension; }
<!DOCTYPE html> <html> <body> <script src="../../resources/js-test.js"></script> <a id="id1" name="name1"></a> <a id="id2" name="name1"></a> <a id="id3"></a> <a id="id4" name="name4"></a> <a name="name5"></a> <a id="id4" name="name6"></a> <script> description("This tests verifies the enumerated properties on HTMLCollection and their order."); var testLink = document.getElementById("testLink"); var htmlCollection = document.<API key>("a"); shouldBe("htmlCollection.__proto__", "HTMLCollection.prototype"); shouldBe("htmlCollection.length", "6"); // As per http://dom.spec.whatwg.org/#htmlcollection: // - The object's supported property indices are the numbers in the range zero to one less than the // number of nodes represented by the collection. If there are no such elements, then there are no // supported property indices. // - The supported property names are the values from the list returned by these steps: // 1. Let result be an empty list. // 2. For each element represented by the collection, in tree order, run these substeps: // 1. If element has an ID which is neither the empty string nor is in result, append element's ID to result. // 2. If element is in the HTML namespace and has a name attribute whose value is neither the empty string // nor is in result, append element's name attribute value to result. // 3. Return result. var <API key> = ["0", "1" , "2", "3", "4", "5", "length", "id1", "name1", "id2", "id3", "id4", "name4", "name5", "name6", "item", "namedItem"]; var <API key> = []; for (var property in htmlCollection) { <API key>[<API key>.length] = property; } shouldBe("<API key>", "<API key>"); </script> </body> </html>
#if 0 // Disabled until updated to use current API. #include "tools/fiddle/examples.h" // HASH=<API key> REG_FIDDLE(Paint_setTextScaleX, 256, 256, true, 0) { void draw(SkCanvas* canvas) { SkPaint paint; paint.setTextScaleX(0.f / 0.f); SkDebugf("text scale %s-a-number\n", SkScalarIsNaN(paint.getTextScaleX()) ? "not" : "is"); } } // END FIDDLE #endif // Disabled until updated to use current API.
#include "chrome/browser/ash/<API key>/operations/execute_action.h" #include <algorithm> #include <string> #include "chrome/common/extensions/api/<API key>.h" #include "chrome/common/extensions/api/<API key>.h" namespace ash { namespace <API key> { namespace operations { ExecuteAction::ExecuteAction(extensions::EventRouter* event_router, const <API key>& file_system_info, const std::vector<base::FilePath>& entry_paths, const std::string& action_id, storage::AsyncFileUtil::StatusCallback callback) : Operation(event_router, file_system_info), entry_paths_(entry_paths), action_id_(action_id), callback_(std::move(callback)) {} ExecuteAction::~ExecuteAction() { } bool ExecuteAction::Execute(int request_id) { using extensions::api::<API key>::<API key>; <API key> options; options.file_system_id = file_system_info_.file_system_id(); options.request_id = request_id; for (const auto& entry_path : entry_paths_) options.entry_paths.push_back(entry_path.AsUTF8Unsafe()); options.action_id = action_id_; return SendEvent( request_id, extensions::events::<API key>, extensions::api::<API key>::<API key>:: kEventName, extensions::api::<API key>::<API key>::Create( options)); } void ExecuteAction::OnSuccess(int /* request_id */, std::unique_ptr<RequestValue> result, bool has_more) { DCHECK(callback_); std::move(callback_).Run(base::File::FILE_OK); } void ExecuteAction::OnError(int /* request_id */, std::unique_ptr<RequestValue> /* result */, base::File::Error error) { DCHECK(callback_); std::move(callback_).Run(error); } } // namespace operations } // namespace <API key> } // namespace ash
// This software is provided 'as-is', without any express or implied // arising from the use of this software. // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // 3. This notice may not be removed or altered from any source // distribution. #define OSMESA_RGBA 0x1908 #define OSMESA_FORMAT 0x22 #define OSMESA_DEPTH_BITS 0x30 #define OSMESA_STENCIL_BITS 0x31 #define OSMESA_ACCUM_BITS 0x32 #define OSMESA_PROFILE 0x33 #define OSMESA_CORE_PROFILE 0x34 #define <API key> 0x35 #define <API key> 0x36 #define <API key> 0x37 typedef void* OSMesaContext; typedef void (*OSMESAproc)(void); typedef OSMesaContext (GLAPIENTRY * <API key>)(GLenum,GLint,GLint,GLint,OSMesaContext); typedef OSMesaContext (GLAPIENTRY * <API key>)(const int*,OSMesaContext); typedef void (GLAPIENTRY * <API key>)(OSMesaContext); typedef int (GLAPIENTRY * <API key>)(OSMesaContext,void*,int,int,int); typedef int (GLAPIENTRY * <API key>)(OSMesaContext,int*,int*,int*,void**); typedef int (GLAPIENTRY * <API key>)(OSMesaContext,int*,int*,int*,void**); typedef GLFWglproc (GLAPIENTRY * <API key>)(const char*); #define <API key> _glfw.osmesa.CreateContextExt #define <API key> _glfw.osmesa.<API key> #define <API key> _glfw.osmesa.DestroyContext #define OSMesaMakeCurrent _glfw.osmesa.MakeCurrent #define <API key> _glfw.osmesa.GetColorBuffer #define <API key> _glfw.osmesa.GetDepthBuffer #define <API key> _glfw.osmesa.GetProcAddress #define <API key> _GLFWcontextOSMesa osmesa #define <API key> _GLFWlibraryOSMesa osmesa // OSMesa-specific per-context data typedef struct _GLFWcontextOSMesa { OSMesaContext handle; int width; int height; void* buffer; } _GLFWcontextOSMesa; // OSMesa-specific global data typedef struct _GLFWlibraryOSMesa { void* handle; <API key> CreateContextExt; <API key> <API key>; <API key> DestroyContext; <API key> MakeCurrent; <API key> GetColorBuffer; <API key> GetDepthBuffer; <API key> GetProcAddress; } _GLFWlibraryOSMesa; GLFWbool _glfwInitOSMesa(void); void <API key>(void); GLFWbool <API key>(_GLFWwindow* window, const _GLFWctxconfig* ctxconfig, const _GLFWfbconfig* fbconfig);
<html> <body> <select aria-label="selection_list" size="10" id="listbox"> <optgroup label="Enabled" id="<API key>"> <option value="listbox_e1" id="<API key>">One</option> <option value="listbox_e2">Two</option> <option value="listbox_e3">Three</option> <option value="listbox_e4">Four</option> </optgroup> </select> </body> </html>
package org.chromium.chrome.browser.browserservices.ui.splashscreen.trustedwebactivity; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static androidx.browser.trusted.<API key>.<API key>; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.browser.customtabs.TrustedWebUtils; import androidx.browser.trusted.<API key>; import androidx.browser.trusted.splashscreens.<API key>; import org.chromium.base.IntentUtils; import org.chromium.chrome.browser.browserservices.intents.<API key>; import org.chromium.chrome.browser.browserservices.ui.splashscreen.SplashController; import org.chromium.chrome.browser.browserservices.ui.splashscreen.SplashDelegate; import org.chromium.chrome.browser.customtabs.<API key>; import org.chromium.chrome.browser.tab.Tab; import org.chromium.ui.base.<API key>; import org.chromium.ui.util.ColorUtils; import javax.inject.Inject; /** * Orchestrates the flow of showing and removing splash screens for apps based on Trusted Web * Activities. * * The flow is as follows: * - TWA client app verifies conditions for showing splash screen. If the checks pass, it shows the * splash screen immediately. * - The client passes the URI to a file with the splash image to * {@link androidx.browser.customtabs.CustomTabsService}. The image is decoded and put into * {@link SplashImageHolder}. * - The client then launches a TWA, at which point the Bitmap is already available. * - <API key> calls {@link #handleIntent}, which starts * {@link <API key>} - a CustomTabActivity with translucent style. The * translucency is necessary in order to avoid a flash that might be seen when starting the activity * before the splash screen is attached. * - {@link <API key>} creates an instance of {@link TwaSplashController} which * immediately displays the splash screen in an ImageView on top of the rest of view hierarchy. * - It also immediately removes the translucency. See comment in {@link SplashController} for more * details. * - It waits for the page to load, and removes the splash image once first paint (or a failure) * occurs. * * Lifecycle: this class is resolved only once when CustomTabActivity is launched, and is * gc-ed when it finishes its job. * If these lifecycle assumptions change, consider whether @ActivityScope needs to be added. */ public class TwaSplashController implements SplashDelegate { // TODO(pshmakov): move this to AndroidX. private static final String KEY_SHOWN_IN_CLIENT = "androidx.browser.trusted.<API key>"; private final SplashController mSplashController; private final Activity mActivity; private final SplashImageHolder mSplashImageCache; private final <API key> mIntentDataProvider; @Inject public TwaSplashController(SplashController splashController, Activity activity, <API key> <API key>, SplashImageHolder splashImageCache, <API key> intentDataProvider) { mSplashController = splashController; mActivity = activity; mSplashImageCache = splashImageCache; mIntentDataProvider = intentDataProvider; long <API key> = IntentUtils.safeGetInt(<API key>(), <API key>.<API key>, 0); mSplashController.setConfig(this, <API key>); } @Override public View buildSplashView() { Bitmap bitmap = mSplashImageCache.takeImage(mIntentDataProvider.getSession()); if (bitmap == null) { return null; } ImageView splashView = new ImageView(mActivity); splashView.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); splashView.setImageBitmap(bitmap); <API key>(splashView); return splashView; } @Override public void onSplashHidden(Tab tab, long startTimestamp, long endTimestamp) {} @Override public boolean <API key>() { return false; } private void <API key>(ImageView imageView) { Bundle params = <API key>(); int backgroundColor = IntentUtils.safeGetInt( params, <API key>.<API key>, Color.WHITE); imageView.setBackgroundColor(ColorUtils.getOpaqueColor(backgroundColor)); int scaleTypeOrdinal = IntentUtils.safeGetInt(params, <API key>.KEY_SCALE_TYPE, -1); ImageView.ScaleType[] scaleTypes = ImageView.ScaleType.values(); ImageView.ScaleType scaleType; if (scaleTypeOrdinal < 0 || scaleTypeOrdinal >= scaleTypes.length) { scaleType = ImageView.ScaleType.CENTER; } else { scaleType = scaleTypes[scaleTypeOrdinal]; } imageView.setScaleType(scaleType); if (scaleType != ImageView.ScaleType.MATRIX) return; float[] matrixValues = IntentUtils.safeGetFloatArray( params, <API key>.<API key>); if (matrixValues == null || matrixValues.length != 9) return; Matrix matrix = new Matrix(); matrix.setValues(matrixValues); imageView.setImageMatrix(matrix); } private Bundle <API key>() { return mIntentDataProvider.getIntent().getBundleExtra(<API key>); } /** * Returns true if the intent corresponds to a TWA with a splash screen. */ public static boolean <API key>(Intent intent) { boolean <API key> = IntentUtils.safeGetBooleanExtra( intent, TrustedWebUtils.<API key>, false); boolean <API key> = IntentUtils.<API key>(intent, <API key>) != null; return <API key> && <API key>; } /** * Handles the intent if it should launch a TWA with splash screen. * @param activity Activity, from which to start the next one. * @param intent Incoming intent. * @return Whether the intent was handled. */ public static boolean handleIntent(Activity activity, Intent intent) { if (!<API key>(intent)) return false; Bundle params = IntentUtils.safeGetBundleExtra( intent, <API key>.<API key>); boolean shownInClient = IntentUtils.safeGetBoolean(params, KEY_SHOWN_IN_CLIENT, true); // shownInClient is "true" by default for the following reasons: // - For compatibility with older clients which don't use this bundle key. // - Because getting "false" when it should be "true" leads to more severe visual glitches, // than vice versa. if (shownInClient) { // If splash screen was shown in client, we must launch a translucent activity to // ensure smooth transition. intent.setClassName(activity, <API key>.class.getName()); } intent.addFlags(Intent.<API key>); activity.startActivity(intent); activity.<API key>(0, 0); return true; } }
using System; using System.Collections.Generic; namespace SharpCompress { internal class <API key><T> : ICollection<T> { private readonly List<T> backing = new List<T>(); private readonly IEnumerator<T> source; private bool fullyLoaded; public <API key>(IEnumerable<T> source) { this.source = source.GetEnumerator(); } private class LazyLoader : IEnumerator<T> { private readonly <API key><T> <API key>; private bool disposed; private int index = -1; internal LazyLoader(<API key><T> <API key>) { this.<API key> = <API key>; } #region IEnumerator<T> Members public T Current { get { return <API key>.backing[index]; } } #endregion #region IDisposable Members public void Dispose() { if (!disposed) { disposed = true; } } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { if (index + 1 < <API key>.backing.Count) { index++; return true; } if (!<API key>.fullyLoaded && <API key>.source.MoveNext()) { <API key>.backing.Add(<API key>.source.Current); index++; return true; } <API key>.fullyLoaded = true; return false; } public void Reset() { throw new <API key>(); } #endregion } internal void EnsureFullyLoaded() { if (!fullyLoaded) { this.ForEach(x => { }); fullyLoaded = true; } } internal IEnumerable<T> GetLoaded() { return backing; } #region ICollection<T> Members public void Add(T item) { throw new <API key>(); } public void Clear() { throw new <API key>(); } public bool Contains(T item) { EnsureFullyLoaded(); return backing.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { EnsureFullyLoaded(); backing.CopyTo(array, arrayIndex); } public int Count { get { EnsureFullyLoaded(); return backing.Count; } } public bool IsReadOnly { get { return true; } } public bool Remove(T item) { throw new <API key>(); } #endregion #region IEnumerable<T> Members //TODO check for concurrent access public IEnumerator<T> GetEnumerator() { return new LazyLoader(this); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
VERSION = (1, 3, 0, 'alpha', 1) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) from django.utils.version import get_svn_revision svn_rev = get_svn_revision() if svn_rev != u'SVN-unknown': version = "%s %s" % (version, svn_rev) return version
package com.greenlemonmobile.app.ebook.books.parser; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; public interface ZipWrapper { ZipEntry getEntry(String entryName); InputStream getInputStream(ZipEntry entry) throws IOException; Enumeration<? extends ZipEntry> entries(); void close() throws IOException; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace AutoTest.TestRunners.XUnit.Tests.TestResource { public class Class2 { [Fact] public void <API key>() { Assert.Equal(1, 1); } } }
function example(name, deps) { console.log('This is where fpscounter plugin code would execute in the node process.'); } module.exports = example;
<?php namespace Concrete\Controller\Element\Express\Search; use Concrete\Core\Controller\ElementController; use Concrete\Core\Entity\Express\Entity; use Concrete\Core\Entity\Search\Query; use Concrete\Core\File\Search\SearchProvider; use Concrete\Core\Foundation\Serializer\JsonSerializer; class Search extends ElementController { /** * This is where the header search bar in the page should point. This search bar allows keyword searching in * different contexts. * * @var string */ protected $headerSearchAction; /** * @var Entity */ protected $entity; /** * @var Query */ protected $query; public function getElement() { return 'express/search/search'; } /** * @param Query $query */ public function setQuery(Query $query = null): void { $this->query = $query; } /** * @param string $headerSearchAction */ public function <API key>(string $headerSearchAction): void { $this->headerSearchAction = $headerSearchAction; } /** * @param Entity $entity */ public function setEntity(Entity $entity): void { $this->entity = $entity; } public function view() { $this->set('entity', $this->entity); $this->set('form', $this->app->make('helper/form')); $this->set('token', $this->app->make('token')); if (isset($this->headerSearchAction)) { $this->set('headerSearchAction', $this->headerSearchAction); } else { $this->set( 'headerSearchAction', $this->app->make('url')->to('/dashboard/express/entries/', 'view', $this->entity->getId()) ); } if (isset($this->query)) { $this->set('query', $this->app->make(JsonSerializer::class)->serialize($this->query, 'json')); } } }
// Node if (typeof module !== 'undefined' && module.exports) { var numeral = require('../../numeral'); var expect = require('chai').expect; var language = require('../../languages/th'); } describe('Language: th', function() { before(function() { numeral.language('th', language); numeral.language('th'); }); after(function() { numeral.reset(); }); describe('Number', function() { it('should format a number', function() { var tests = [ [10000,'0,0.0000','10,000.0000'], [10000.23,'0,0','10,000'], [-10000,'0,0.0','-10,000.0'], [10000.1234,'0.000','10000.123'], [-10000,'(0,0.0000)','(10,000.0000)'], [-0.23,'.00','-.23'], [-0.23,'(.00)','(.23)'], [0.23,'0.00000','0.23000'], [1230974,'0.0a','1.2ล้าน'], [1460,'0a','1พัน'], [-104000,'0a','-104พัน'], [1,'0o','1.'], [52,'0o','52.'], [23,'0o','23.'], [100,'0o','100.'], [1,'0[.]0','1'] ]; for (var i = 0; i < tests.length; i++) { expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]); } }); }); describe('Currency', function() { it('should format a currency', function() { var tests = [ [1000.234,'$0,0.00','฿1,000.23'], [-1000.234,'($0,0)','(฿1,000)'], [-1000.234,'$0.00','-฿1000.23'], [1230974,'($0.00a)','฿1.23ล้าน'] ]; for (var i = 0; i < tests.length; i++) { expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]); } }); }); describe('Percentages', function() { it('should format a percentages', function() { var tests = [ [1,'0%','100%'], [0.974878234,'0.000%','97.488%'], [-0.43,'0%','-43%'], [0.43,'(0.000%)','43.000%'] ]; for (var i = 0; i < tests.length; i++) { expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]); } }); }); describe('Unformat', function() { it('should unformat', function() { var tests = [ ['10,000.123',10000.123], ['(0.12345)',-0.12345], ['(฿1.23ล้าน)',-1230000], ['10พัน',10000], ['-10พัน',-10000], ['23.',23], ['฿10,000.00',10000], ['-76%',-0.76], ['2:23:57',8637] ]; for (var i = 0; i < tests.length; i++) { expect(numeral().unformat(tests[i][0])).to.equal(tests[i][1]); } }); }); });
#include <boost/chrono/config.hpp> #include <boost/detail/lightweight_test.hpp> #if defined(<API key>) || defined(__CYGWIN__) #include <boost/chrono/detail/static_assert.hpp> #if !defined(<API key>) #define NOTHING "" #endif #include <boost/type_traits.hpp> #include <boost/typeof/typeof.hpp> #undef BOOST_USE_WINDOWS_H #include <boost/detail/win/basic_types.hpp> #include <boost/detail/win/time.hpp> #include <windows.h> void test() { { boost::detail::win32::LARGE_INTEGER_ a; LARGE_INTEGER b; <API key>(( sizeof(boost::detail::win32::LARGE_INTEGER_)==sizeof(LARGE_INTEGER) ), NOTHING, (boost::detail::win32::LARGE_INTEGER_, LARGE_INTEGER)); BOOST_TEST(( sizeof(a.QuadPart)==sizeof(b.QuadPart) )); <API key>(( offsetof(boost::detail::win32::LARGE_INTEGER_, QuadPart)==offsetof(LARGE_INTEGER, QuadPart) ), NOTHING, (boost::detail::win32::LARGE_INTEGER_, LARGE_INTEGER)); <API key>(( boost::is_same< BOOST_TYPEOF(a.QuadPart), BOOST_TYPEOF(b.QuadPart) >::value ), NOTHING, (boost::detail::win32::LARGE_INTEGER_, LARGE_INTEGER)); } <API key>(( sizeof(boost::detail::win32::BOOL_)==sizeof(BOOL) ), NOTHING, (boost::detail::win32::BOOL_, BOOL)); <API key>(( boost::is_same<boost::detail::win32::BOOL_,BOOL>::value ), NOTHING, (boost::detail::win32::BOOL_, BOOL)); <API key>(( sizeof(boost::detail::win32::DWORD_)==sizeof(DWORD) ), NOTHING, (boost::detail::win32::DWORD_, DWORD)); <API key>(( boost::is_same<boost::detail::win32::DWORD_,DWORD>::value ), NOTHING, (boost::detail::win32::DWORD_, DWORD)); <API key>(( sizeof(boost::detail::win32::HANDLE_)==sizeof(HANDLE) ), NOTHING, (boost::detail::win32::HANDLE_, HANDLE)); <API key>(( boost::is_same<boost::detail::win32::HANDLE_,HANDLE>::value ), NOTHING, (boost::detail::win32::HANDLE_, HANDLE)); <API key>(( sizeof(boost::detail::win32::LONG_)==sizeof(LONG) ), NOTHING, (boost::detail::win32::LONG_, LONG)); <API key>(( boost::is_same<boost::detail::win32::LONG_,LONG>::value ), NOTHING, (boost::detail::win32::LONG_, LONG)); <API key>(( sizeof(boost::detail::win32::LONGLONG_)==sizeof(LONGLONG) ), NOTHING, (boost::detail::win32::LONGLONG_, LONGLONG)); <API key>(( boost::is_same<boost::detail::win32::LONGLONG_,LONGLONG>::value ), NOTHING, (boost::detail::win32::LONGLONG_, LONGLONG)); <API key>(( sizeof(boost::detail::win32::ULONG_PTR_)==sizeof(ULONG_PTR) ), NOTHING, (boost::detail::win32::ULONG_PTR_, ULONG_PTR)); <API key>(( boost::is_same<boost::detail::win32::ULONG_PTR_,ULONG_PTR>::value ), NOTHING, (boost::detail::win32::ULONG_PTR_, ULONG_PTR)); <API key>(( sizeof(boost::detail::win32::PLARGE_INTEGER_)==sizeof(PLARGE_INTEGER) ), NOTHING, (boost::detail::win32::PLARGE_INTEGER_, PLARGE_INTEGER)); //~ <API key>(( //~ boost::is_same<boost::detail::win32::PLARGE_INTEGER_,PLARGE_INTEGER>::value //~ ), NOTHING, (boost::detail::win32::PLARGE_INTEGER_, PLARGE_INTEGER)); { <API key>(( sizeof(boost::detail::win32::FILETIME_)==sizeof(FILETIME) ), NOTHING, (boost::detail::win32::FILETIME_, FILETIME)); <API key>(( sizeof(boost::detail::win32::PFILETIME_)==sizeof(PFILETIME) ), NOTHING, (boost::detail::win32::PFILETIME_, PFILETIME)); boost::detail::win32::FILETIME_ a; FILETIME b; BOOST_TEST(( sizeof(a.dwLowDateTime)==sizeof(b.dwLowDateTime) )); BOOST_TEST(( sizeof(a.dwHighDateTime)==sizeof(b.dwHighDateTime) )); <API key>(( offsetof(boost::detail::win32::FILETIME_, dwLowDateTime)==offsetof(FILETIME, dwLowDateTime) ), NOTHING, (boost::detail::win32::FILETIME_, FILETIME)); <API key>(( offsetof(boost::detail::win32::FILETIME_, dwHighDateTime)==offsetof(FILETIME, dwHighDateTime) ), NOTHING, (boost::detail::win32::FILETIME_, FILETIME)); <API key>(( boost::is_same< BOOST_TYPEOF(a.dwLowDateTime), BOOST_TYPEOF(b.dwLowDateTime) >::value ), NOTHING, (boost::detail::win32::FILETIME_, FILETIME)); <API key>(( boost::is_same< BOOST_TYPEOF(a.dwHighDateTime), BOOST_TYPEOF(b.dwHighDateTime) >::value ), NOTHING, (boost::detail::win32::FILETIME_, FILETIME)); } // <API key>(( // GetLastError==boost::detail::win32::::GetLastError // ), NOTHING, ()); } #else void test() { } #endif int main( ) { test(); return boost::report_errors(); }
#ifndef YR_MUTEX_H #define YR_MUTEX_H #if defined(_WIN32) || defined(__CYGWIN__) #include <windows.h> typedef DWORD YR_THREAD_ID; typedef DWORD <API key>; typedef HANDLE YR_MUTEX; #else #include <pthread.h> typedef pthread_t YR_THREAD_ID; typedef pthread_key_t <API key>; typedef pthread_mutex_t YR_MUTEX; #endif YR_THREAD_ID <API key>(void); int yr_mutex_create(YR_MUTEX*); int yr_mutex_destroy(YR_MUTEX*); int yr_mutex_lock(YR_MUTEX*); int yr_mutex_unlock(YR_MUTEX*); int <API key>(<API key>*); int <API key>(<API key>*); int <API key>(<API key>*, void*); void* <API key>(<API key>*); #endif
<?php declare(strict_types=1); namespace Sylius\Bundle\ApiBundle\Command; /** @experimental */ interface <API key> extends <API key> { public function getChannelCode(): ?string; public function setChannelCode(?string $channelCode): void; }
#ifndef BLE_CONN_H__ #define BLE_CONN_H__ /** * @addtogroup ser_codecs Serialization codecs * @ingroup <API key> */ /** * @addtogroup <API key> Connectivity s120 codecs * @ingroup ser_codecs */ /**@file * * @defgroup ble_conn Connectivity command request decoders and command response encoders * @{ * @ingroup <API key> * * @brief Connectivity command request decoders and command response encoders. */ #include "ble.h" /**@brief Decodes @ref <API key> command request. * * @sa @ref <API key> for packet format, * @ref <API key> for response encoding. * * @param[in] p_buf Pointer to beginning of command request packet. * @param[in] packet_len Length (in bytes) of response packet. * @param[out] pp_count Pointer to pointer to location for count. * * @retval NRF_SUCCESS Decoding success. * @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied. * @retval <API key> Decoding failure. Incorrect buffer length. * @retval <API key> Decoding failure. Invalid operation type. */ uint32_t <API key>(uint8_t const * const p_buf, uint16_t packet_len, uint8_t * * const pp_count); /**@brief Encodes @ref <API key> command response. * * @sa @ref <API key> for packet format. * @ref <API key> for request decoding. * * @param[in] return_code Return code indicating if command was successful or not. * @param[out] p_buf Pointer to buffer where encoded data command response will be * returned. * @param[in,out] p_buf_len \c in: size of \p p_buf buffer. * \c out: Length of encoded command response packet. * @param[in] p_count Pointer to count value. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. */ uint32_t <API key>(uint32_t return_code, uint8_t * const p_buf, uint32_t * const p_buf_len, uint8_t const * const p_count); /**@brief Event encoding dispatcher. * * The event encoding dispatcher will route the event packet to the correct encoder which in turn * encodes the contents of the event and updates the \p p_buf buffer. * * @param[in] p_event Pointer to the \ref ble_evt_t buffer that shall be encoded. * @param[in] event_len Size (in bytes) of \p p_event buffer. * @param[out] p_buf Pointer to the beginning of a buffer for encoded event packet. * @param[in,out] p_buf_len \c in: Size (in bytes) of \p p_buf buffer. * \c out: Length of encoded contents in \p p_buf. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. * @retval <API key> Event encoder is not implemented. */ uint32_t ble_event_enc(ble_evt_t const * const p_event, uint32_t event_len, uint8_t * const p_buf, uint32_t * const p_buf_len); /**@brief Decodes @ref sd_ble_version_get command request. * * @sa @ref <API key> for packet format, * @ref <API key> for response encoding. * * @param[in] p_buf Pointer to beginning of command request packet. * @param[in] packet_len Length (in bytes) of response packet. * @param[out] pp_version Pointer to pointer to @ref ble_version_t address. * * @retval NRF_SUCCESS Decoding success. * @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied. * @retval <API key> Decoding failure. Incorrect buffer length. * @retval <API key> Decoding failure. Invalid operation type. */ uint32_t <API key>(uint8_t const * const p_buf, uint16_t packet_len, ble_version_t * * const pp_version); /**@brief Encodes @ref sd_ble_version_get command response. * * @sa @ref <API key> for packet format. * @ref <API key> for request decoding. * * @param[in] return_code Return code indicating if command was successful or not. * @param[out] p_buf Pointer to buffer where encoded data command response will be * returned. * @param[in,out] p_buf_len \c in: size of \p p_buf buffer. * \c out: Length of encoded command response packet. * @param[in] p_version Pointer to @ref ble_version_t address. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. */ uint32_t <API key>(uint32_t return_code, uint8_t * const p_buf, uint32_t * const p_buf_len, ble_version_t const * const p_version); /**@brief Decodes @ref sd_ble_opt_get command request. * * @sa @ref <API key> for packet format, * @ref ble_opt_get_rsp_enc for response encoding. * * @param[in] p_buf Pointer to beginning of command request packet. * @param[in] packet_len Length (in bytes) of response packet. * @param[out] p_opt_id Pointer to pointer to @ref ble_version_t address. * @param[out] pp_opt Pointer to pointer to @ref ble_opt_t address. * * @retval NRF_SUCCESS Decoding success. * @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied. * @retval <API key> Decoding failure. Incorrect buffer length. * @retval <API key> Decoding failure. Invalid operation type. */ uint32_t ble_opt_get_req_dec(uint8_t const * const p_buf, uint16_t packet_len, uint32_t * const p_opt_id, ble_opt_t **const pp_opt ); /**@brief Encodes @ref sd_ble_opt_get command response. * * @sa @ref <API key> for packet format. * @ref ble_opt_get_req_dec for request decoding. * * @param[in] return_code Return code indicating if command was successful or not. * @param[out] p_buf Pointer to buffer where encoded data command response will be * returned. * @param[in,out] p_buf_len \c in: size of \p p_buf buffer. * \c out: Length of encoded command response packet. * @param[in] opt_id identifies type of ble_opt_t union * @param[in] p_opt Pointer to @ref ble_opt_t union. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. */ uint32_t ble_opt_get_rsp_enc(uint32_t return_code, uint8_t * const p_buf, uint32_t * const p_buf_len, uint32_t opt_id, ble_opt_t const * const p_opt); /**@brief Decodes @ref sd_ble_opt_set command request. * * @sa @ref <API key> for packet format, * @ref ble_opt_set_rsp_enc for response encoding. * * @param[in] p_buf Pointer to beginning of command request packet. * @param[in] packet_len Length (in bytes) of response packet. * @param[out] p_opt_id Pointer to @ref ble_opt_t union type identifier. * @param[out] pp_opt Pointer to pointer to @ref ble_opt_t union. * * @retval NRF_SUCCESS Decoding success. * @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied. * @retval <API key> Decoding failure. Incorrect buffer length. * @retval <API key> Decoding failure. Invalid operation type. */ uint32_t ble_opt_set_req_dec(uint8_t const * const p_buf, uint16_t packet_len, uint32_t * const p_opt_id, ble_opt_t **const pp_opt ); /**@brief Encodes @ref sd_ble_opt_set command response. * * @sa @ref <API key> for packet format. * @ref ble_opt_set_req_dec for request decoding. * * @param[in] return_code Return code indicating if command was successful or not. * @param[out] p_buf Pointer to buffer where encoded data command response will be * returned. * @param[in,out] p_buf_len \c in: size of \p p_buf buffer. * \c out: Length of encoded command response packet. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. */ uint32_t ble_opt_set_rsp_enc(uint32_t return_code, uint8_t * const p_buf, uint32_t * const p_buf_len); /**@brief Decodes @ref sd_ble_uuid_encode command request. * * @sa @ref <API key> for packet format, * @ref <API key> for response encoding. * * @param[in] p_buf Pointer to beginning of command request packet. * @param[in] packet_len Length (in bytes) of response packet. * @param[out] pp_uuid Pointer to pointer to @ref ble_uuid_t structure. * @param[out] pp_uuid_le_len Pointer to pointer to the length of encoded UUID. * @param[out] pp_uuid_le Pointer to pointer to buffer where encoded UUID will be stored. * * @retval NRF_SUCCESS Decoding success. * @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied. * @retval <API key> Decoding failure. Incorrect buffer length. * @retval <API key> Decoding failure. Invalid operation type. */ uint32_t <API key>(uint8_t const * const p_buf, uint16_t packet_len, ble_uuid_t * * const pp_uuid, uint8_t * * const pp_uuid_le_len, uint8_t * * const pp_uuid_le); /**@brief Encodes @ref sd_ble_uuid_encode command response. * * @sa @ref <API key> for packet format. * @ref <API key> for request decoding. * * @param[in] return_code Return code indicating if command was successful or not. * @param[out] p_buf Pointer to buffer where encoded data command response will be * returned. * @param[in,out] p_buf_len \c in: size of \p p_buf buffer. * \c out: Length of encoded command response packet. * @param[in] uuid_le_len Length of the encoded UUID. * @param[in] p_uuid_le Pointer to the buffer with encoded UUID. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. */ uint32_t <API key>(uint32_t return_code, uint8_t * const p_buf, uint32_t * const p_buf_len, uint8_t uuid_le_len, uint8_t const * const p_uuid_le); /**@brief Decodes @ref sd_ble_uuid_decode command request. * * @sa @ref <API key> for packet format, * @ref <API key> for response encoding. * * @param[in] p_buf Pointer to beginning of command request packet. * @param[in] buf_len Length (in bytes) of response packet. * @param[out] p_uuid_le_len Pointer to the length of encoded UUID. * @param[out] pp_uuid_le Pointer to pointer to buffer where encoded UUID will be stored. * @param[out] pp_uuid Pointer to pointer to @ref ble_uuid_t structure. * \c It will be set to NULL if p_uuid is not present in the packet. * * @retval NRF_SUCCESS Decoding success. * @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied. * @retval <API key> Decoding failure. Incorrect buffer length. */ uint32_t <API key>(uint8_t const * const p_buf, uint32_t const buf_len, uint8_t * p_uuid_le_len, uint8_t * * const pp_uuid_le, ble_uuid_t * * const pp_uuid); /**@brief Encodes @ref sd_ble_uuid_decode command response. * * @sa @ref <API key> for packet format. * @ref <API key> for request decoding. * * @param[in] return_code Return code indicating if command was successful or not. * @param[out] p_buf Pointer to buffer where encoded data command response will be * returned. * @param[in,out] p_buf_len \c in: size of \p p_buf buffer. * \c out: Length of encoded command response packet. * @param[in] p_uuid Pointer to the buffer with encoded UUID. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. */ uint32_t <API key>(uint32_t return_code, uint8_t * const p_buf, uint32_t * const p_buf_len, ble_uuid_t const * const p_uuid); /**@brief Decodes @ref sd_ble_uuid_vs_add command request. * * @sa @ref <API key> for packet format, * @ref <API key> for response encoding. * * @param[in] p_buf Pointer to beginning of command request packet. * @param[in] buf_len Length (in bytes) of response packet. * @param[out] pp_uuid Pointer to pointer to UUID. * \c It will be set to NULL if p_uuid is not present in the packet. * @param[out] pp_uuid_type Pointer to pointer to UUID type. * \c It will be set to NULL if p_uuid_type is not present in the packet. * * @retval NRF_SUCCESS Decoding success. * @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied. * @retval <API key> Decoding failure. Incorrect buffer length. */ uint32_t <API key>(uint8_t const * const p_buf, uint16_t buf_len, ble_uuid128_t * * const pp_uuid, uint8_t * * const pp_uuid_type); /**@brief Encodes @ref sd_ble_uuid_vs_add command response. * * @sa @ref <API key> for packet format. * @ref <API key> for request decoding. * * @param[in] return_code Return code indicating if command was successful or not. * @param[out] p_buf Pointer to buffer where encoded data command response will be * returned. * @param[in,out] p_buf_len \c in: size of \p p_buf buffer. * \c out: Length of encoded command response packet. * @param[in] p_uuid_type Pointer to the UUID type. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. */ uint32_t <API key>(uint32_t return_code, uint8_t * const p_buf, uint32_t * const p_buf_len, uint8_t const * const p_uuid_type); /**@brief Decodes @ref sd_ble_enable command request. * * @sa @ref <API key> for packet format, * @ref ble_enable_rsp_enc for response encoding. * * @param[in] p_buf Pointer to beginning of command request packet. * @param[in] packet_len Length (in bytes) of response packet. * @param[out] <API key> Pointer to pointer to ble_enable_params_t. * \c It will be set to NULL if p_ble_enable_params is not present in the packet. * * @retval NRF_SUCCESS Decoding success. * @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied. * @retval <API key> Decoding failure. Incorrect buffer length. */ uint32_t ble_enable_req_dec(uint8_t const * const p_buf, uint32_t packet_len, ble_enable_params_t * * const <API key>); /**@brief Encodes @ref sd_ble_enable command response. * * @sa @ref <API key> for packet format. * @ref ble_enable_req_dec for request decoding. * * @param[in] return_code Return code indicating if command was successful or not. * @param[out] p_buf Pointer to buffer where encoded data command response will be * returned. * @param[in,out] p_buf_len \c in: size of \p p_buf buffer. * \c out: Length of encoded command response packet. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. */ uint32_t ble_enable_rsp_enc(uint32_t return_code, uint8_t * const p_buf, uint32_t * const p_buf_len); /**@brief Pre-decodes opt_id of @ref ble_opt_t for middleware. * * @param[out] p_buf Pointer to buffer where encoded data command response will be * returned. * @param[in,out] packet_len \c in: size of \p p_buf buffer. * \c out: Length of encoded command response packet. * @param[in,out] p_opt_id Pointer to opt_id which identifies type of @ref ble_opt_t union. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. */ uint32_t ble_opt_id_pre_dec(uint8_t const * const p_buf, uint16_t packet_len, uint32_t * const p_opt_id); /**@brief Decodes @ref <API key> command request. * * @sa @ref <API key> for packet format, * @ref <API key> for response encoding. * * @param[in] p_buf Pointer to beginning of command request packet. * @param[in] packet_len Length (in bytes) of response packet. * @param[in] p_conn_handle Pointer to Connection Handle. * @param[in,out] pp_block Pointer to pointer to <API key>. * \c It will be set to NULL if p_block is not present in the packet. * * @retval NRF_SUCCESS Decoding success. * @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied. * @retval <API key> Decoding failure. Incorrect buffer length. */ uint32_t <API key>(uint8_t const * const p_buf, uint32_t packet_len, uint16_t * const p_conn_handle, <API key> * * const pp_block); /**@brief Encodes @ref <API key> command response. * * @sa @ref <API key> for packet format. * @ref <API key> for request decoding. * * @param[in] return_code Return code indicating if command was successful or not. * @param[out] p_buf Pointer to buffer where encoded data command response will be * returned. * @param[in,out] p_buf_len \c in: size of \p p_buf buffer. * \c out: Length of encoded command response packet. * * @retval NRF_SUCCESS Encoding success. * @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied. * @retval <API key> Encoding failure. Incorrect buffer length. */ uint32_t <API key>(uint32_t return_code, uint8_t * const p_buf, uint32_t * const p_buf_len); #endif
/** * @file * lwIP network interface abstraction * * @defgroup netif Network interface (NETIF) * @ingroup callbackstyle_api * * @defgroup netif_ip4 IPv4 address handling * @ingroup netif * * @defgroup netif_ip6 IPv6 address handling * @ingroup netif * * @defgroup netif_cd Client data handling * Store data (void*) on a netif for application usage. * @see @ref <API key> * @ingroup netif */ #include "lwip/opt.h" #include <string.h> #include "lwip/def.h" #include "lwip/ip_addr.h" #include "lwip/ip6_addr.h" #include "lwip/netif.h" #include "lwip/priv/tcp_priv.h" #include "lwip/udp.h" #include "lwip/raw.h" #include "lwip/snmp.h" #include "lwip/igmp.h" #include "lwip/etharp.h" #include "lwip/stats.h" #include "lwip/sys.h" #include "lwip/ip.h" #if ENABLE_LOOPBACK #if <API key> #include "lwip/tcpip.h" #endif /* <API key> */ #endif /* ENABLE_LOOPBACK */ #include "netif/ethernet.h" #if LWIP_AUTOIP #include "lwip/autoip.h" #endif /* LWIP_AUTOIP */ #if LWIP_DHCP #include "lwip/dhcp.h" #endif /* LWIP_DHCP */ #if LWIP_IPV6_DHCP6 #include "lwip/dhcp6.h" #endif /* LWIP_IPV6_DHCP6 */ #if LWIP_IPV6_MLD #include "lwip/mld6.h" #endif /* LWIP_IPV6_MLD */ #if LWIP_IPV6 #include "lwip/nd6.h" #endif #if <API key> #define <API key>(n) do{ if (n->status_callback) { (n->status_callback)(n); }}while(0) #else #define <API key>(n) #endif /* <API key> */ #if <API key> #define NETIF_LINK_CALLBACK(n) do{ if (n->link_callback) { (n->link_callback)(n); }}while(0) #else #define NETIF_LINK_CALLBACK(n) #endif /* <API key> */ struct netif *netif_list; struct netif *netif_default; static u8_t netif_num; #if <API key> > 0 static u8_t netif_client_id; #endif #define <API key> 0x01 #define <API key> 0x02 static void netif_issue_reports(struct netif* netif, u8_t report_type); #if LWIP_IPV6 static err_t <API key>(struct netif *netif, struct pbuf *p, const ip6_addr_t *ipaddr); #endif /* LWIP_IPV6 */ #if LWIP_HAVE_LOOPIF #if LWIP_IPV4 static err_t <API key>(struct netif *netif, struct pbuf *p, const ip4_addr_t* addr); #endif #if LWIP_IPV6 static err_t <API key>(struct netif *netif, struct pbuf *p, const ip6_addr_t* addr); #endif static struct netif loop_netif; /** * Initialize a lwip network interface structure for a loopback interface * * @param netif the lwip network interface structure for this loopif * @return ERR_OK if the loopif is initialized * ERR_MEM if private data couldn't be allocated */ static err_t netif_loopif_init(struct netif *netif) { /* initialize the snmp variables and counters inside the struct netif * ifSpeed: no assumption can be made! */ MIB2_INIT_NETIF(netif, <API key>, 0); netif->name[0] = 'l'; netif->name[1] = 'o'; #if LWIP_IPV4 netif->output = <API key>; #endif #if LWIP_IPV6 netif->output_ip6 = <API key>; #endif #if <API key> netif->flags |= NETIF_FLAG_IGMP; #endif return ERR_OK; } #endif /* LWIP_HAVE_LOOPIF */ void netif_init(void) { #if LWIP_HAVE_LOOPIF #if LWIP_IPV4 #define LOOPIF_ADDRINIT &loop_ipaddr, &loop_netmask, &loop_gw, ip4_addr_t loop_ipaddr, loop_netmask, loop_gw; IP4_ADDR(&loop_gw, 127,0,0,1); IP4_ADDR(&loop_ipaddr, 127,0,0,1); IP4_ADDR(&loop_netmask, 255,0,0,0); #else /* LWIP_IPV4 */ #define LOOPIF_ADDRINIT #endif /* LWIP_IPV4 */ #if NO_SYS netif_add(&loop_netif, LOOPIF_ADDRINIT NULL, netif_loopif_init, ip_input); #else /* NO_SYS */ netif_add(&loop_netif, LOOPIF_ADDRINIT NULL, netif_loopif_init, tcpip_input); #endif /* NO_SYS */ #if LWIP_IPV6 IP_ADDR6(loop_netif.ip6_addr, 0, 0, 0, PP_HTONL(0x00000001UL)); loop_netif.ip6_addr_state[0] = IP6_ADDR_VALID; #endif /* LWIP_IPV6 */ netif_set_link_up(&loop_netif); netif_set_up(&loop_netif); #endif /* LWIP_HAVE_LOOPIF */ } /** * @ingroup lwip_nosys * Forwards a received packet for input processing with * ethernet_input() or ip_input() depending on netif flags. * Don't call directly, pass to netif_add() and call * netif->input(). * Only works if the netif driver correctly sets * NETIF_FLAG_ETHARP and/or NETIF_FLAG_ETHERNET flag! */ err_t netif_input(struct pbuf *p, struct netif *inp) { #if LWIP_ETHERNET if (inp->flags & (NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET)) { return ethernet_input(p, inp); } else #endif /* LWIP_ETHERNET */ return ip_input(p, inp); } /** * @ingroup netif * Add a network interface to the list of lwIP netifs. * * @param netif a pre-allocated netif structure * @param ipaddr IP address for the new netif * @param netmask network mask for the new netif * @param gw default gateway IP address for the new netif * @param state opaque data passed to the new netif * @param init callback function that initializes the interface * @param input callback function that is called to pass * ingress packets up in the protocol layer stack.\n * It is recommended to use a function that passes the input directly * to the stack (netif_input(), NO_SYS=1 mode) or via sending a * message to TCPIP thread (tcpip_input(), NO_SYS=0 mode).\n * These functions use netif flags NETIF_FLAG_ETHARP and NETIF_FLAG_ETHERNET * to decide whether to forward to ethernet_input() or ip_input(). * In other words, the functions only work when the netif * driver is implemented correctly!\n * Most members of struct netif should be be initialized by the * netif init function = netif driver (init parameter of this function).\n * IPv6: Don't forget to call <API key>() after * setting the MAC address in struct netif.hwaddr * (IPv6 requires a link-local address). * * @return netif, or NULL if failed. */ struct netif * netif_add(struct netif *netif, #if LWIP_IPV4 const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw, #endif /* LWIP_IPV4 */ void *state, netif_init_fn init, netif_input_fn input) { #if LWIP_IPV6 s8_t i; #endif LWIP_ASSERT("No init function given", init != NULL); /* reset new interface configuration state */ #if LWIP_IPV4 <API key>(&netif->ip_addr); <API key>(&netif->netmask); <API key>(&netif->gw); #endif /* LWIP_IPV4 */ #if LWIP_IPV6 for (i = 0; i < <API key>; i++) { <API key>(&netif->ip6_addr[i]); netif->ip6_addr_state[i] = IP6_ADDR_INVALID; } netif->output_ip6 = <API key>; #endif /* LWIP_IPV6 */ <API key>(netif, <API key>); netif->flags = 0; #ifdef <API key> memset(netif->client_data, 0, sizeof(netif->client_data)); #endif /* <API key> */ #if <API key> /* IPv6 address autoconfiguration not enabled by default */ netif-><API key> = 0; #endif /* <API key> */ #if <API key> netif->rs_count = <API key>; #endif /* <API key> */ #if <API key> netif->status_callback = NULL; #endif /* <API key> */ #if <API key> netif->link_callback = NULL; #endif /* <API key> */ #if LWIP_IGMP netif->igmp_mac_filter = NULL; #endif /* LWIP_IGMP */ #if LWIP_IPV6 && LWIP_IPV6_MLD netif->mld_mac_filter = NULL; #endif /* LWIP_IPV6 && LWIP_IPV6_MLD */ #if ENABLE_LOOPBACK netif->loop_first = NULL; netif->loop_last = NULL; #endif /* ENABLE_LOOPBACK */ /* remember netif specific state information data */ netif->state = state; netif->num = netif_num++; netif->input = input; <API key>(netif, NULL); #if ENABLE_LOOPBACK && <API key> netif->loop_cnt_current = 0; #endif /* ENABLE_LOOPBACK && <API key> */ #if LWIP_IPV4 netif_set_addr(netif, ipaddr, netmask, gw); #endif /* LWIP_IPV4 */ /* call user specified initialization function for netif */ if (init(netif) != ERR_OK) { return NULL; } /* add this netif to the list */ netif->next = netif_list; netif_list = netif; mib2_netif_added(netif); #if LWIP_IGMP /* start IGMP processing */ if (netif->flags & NETIF_FLAG_IGMP) { igmp_start(netif); } #endif /* LWIP_IGMP */ LWIP_DEBUGF(NETIF_DEBUG, ("netif: added interface %c%c IP", netif->name[0], netif->name[1])); #if LWIP_IPV4 LWIP_DEBUGF(NETIF_DEBUG, (" addr ")); <API key>(NETIF_DEBUG, ipaddr); LWIP_DEBUGF(NETIF_DEBUG, (" netmask ")); <API key>(NETIF_DEBUG, netmask); LWIP_DEBUGF(NETIF_DEBUG, (" gw ")); <API key>(NETIF_DEBUG, gw); #endif /* LWIP_IPV4 */ LWIP_DEBUGF(NETIF_DEBUG, ("\n")); return netif; } #if LWIP_IPV4 /** * @ingroup netif_ip4 * Change IP address configuration for a network interface (including netmask * and default gateway). * * @param netif the network interface to change * @param ipaddr the new IP address * @param netmask the new netmask * @param gw the new default gateway */ void netif_set_addr(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw) { if (ip4_addr_isany(ipaddr)) { /* when removing an address, we have to remove it *before* changing netmask/gw to ensure that tcp RST segment can be sent correctly */ netif_set_ipaddr(netif, ipaddr); netif_set_netmask(netif, netmask); netif_set_gw(netif, gw); } else { netif_set_netmask(netif, netmask); netif_set_gw(netif, gw); /* set ipaddr last to ensure netmask/gw have been set when status callback is called */ netif_set_ipaddr(netif, ipaddr); } } #endif /* LWIP_IPV4*/ /** * @ingroup netif * Remove a network interface from the list of lwIP netifs. * * @param netif the network interface to remove */ void netif_remove(struct netif *netif) { #if LWIP_IPV6 int i; #endif if (netif == NULL) { return; } #if LWIP_IPV4 if (!ip4_addr_isany_val(*netif_ip4_addr(netif))) { #if LWIP_TCP <API key>(netif_ip_addr4(netif), NULL); #endif /* LWIP_TCP */ #if LWIP_UDP <API key>(netif_ip_addr4(netif), NULL); #endif /* LWIP_UDP */ #if LWIP_RAW <API key>(netif_ip_addr4(netif), NULL); #endif /* LWIP_RAW */ } #if LWIP_IGMP /* stop IGMP processing */ if (netif->flags & NETIF_FLAG_IGMP) { igmp_stop(netif); } #endif /* LWIP_IGMP */ #endif /* LWIP_IPV4*/ #if LWIP_IPV6 for (i = 0; i < <API key>; i++) { if (ip6_addr_isvalid(<API key>(netif, i))) { #if LWIP_TCP <API key>(netif_ip_addr6(netif, i), NULL); #endif /* LWIP_TCP */ #if LWIP_UDP <API key>(netif_ip_addr6(netif, i), NULL); #endif /* LWIP_UDP */ #if LWIP_RAW <API key>(netif_ip_addr6(netif, i), NULL); #endif /* LWIP_RAW */ } } #if LWIP_IPV6_MLD /* stop MLD processing */ mld6_stop(netif); #endif /* LWIP_IPV6_MLD */ #endif /* LWIP_IPV6 */ if (netif_is_up(netif)) { /* set netif down before removing (call callback function) */ netif_set_down(netif); } mib2_remove_ip4(netif); /* this netif is default? */ if (netif_default == netif) { /* reset default netif */ netif_set_default(NULL); } /* is it the first netif? */ if (netif_list == netif) { netif_list = netif->next; } else { /* look for netif further down the list */ struct netif * tmp_netif; for (tmp_netif = netif_list; tmp_netif != NULL; tmp_netif = tmp_netif->next) { if (tmp_netif->next == netif) { tmp_netif->next = netif->next; break; } } if (tmp_netif == NULL) { return; /* netif is not on the list */ } } mib2_netif_removed(netif); #if <API key> if (netif->remove_callback) { netif->remove_callback(netif); } #endif /* <API key> */ LWIP_DEBUGF( NETIF_DEBUG, ("netif_remove: removed netif\n") ); } /** * @ingroup netif * Find a network interface by searching for its name * * @param name the name of the netif (like netif->name) plus concatenated number * in ascii representation (e.g. 'en0') */ struct netif * netif_find(const char *name) { struct netif *netif; u8_t num; if (name == NULL) { return NULL; } num = name[2] - '0'; for (netif = netif_list; netif != NULL; netif = netif->next) { if (num == netif->num && name[0] == netif->name[0] && name[1] == netif->name[1]) { LWIP_DEBUGF(NETIF_DEBUG, ("netif_find: found %c%c\n", name[0], name[1])); return netif; } } LWIP_DEBUGF(NETIF_DEBUG, ("netif_find: didn't find %c%c\n", name[0], name[1])); return NULL; } #if LWIP_IPV4 /** * @ingroup netif_ip4 * Change the IP address of a network interface * * @param netif the network interface to change * @param ipaddr the new IP address * * @note call netif_set_addr() if you also want to change netmask and * default gateway */ void netif_set_ipaddr(struct netif *netif, const ip4_addr_t *ipaddr) { ip_addr_t new_addr; *ip_2_ip4(&new_addr) = (ipaddr ? *ipaddr : *IP4_ADDR_ANY4); IP_SET_TYPE_VAL(new_addr, IPADDR_TYPE_V4); /* address is actually being changed? */ if (ip4_addr_cmp(ip_2_ip4(&new_addr), netif_ip4_addr(netif)) == 0) { LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: netif address being changed\n")); #if LWIP_TCP <API key>(netif_ip_addr4(netif), &new_addr); #endif /* LWIP_TCP */ #if LWIP_UDP <API key>(netif_ip_addr4(netif), &new_addr); #endif /* LWIP_UDP */ #if LWIP_RAW <API key>(netif_ip_addr4(netif), &new_addr); #endif /* LWIP_RAW */ mib2_remove_ip4(netif); <API key>(0, netif); /* set new IP address to netif */ ip4_addr_set(ip_2_ip4(&netif->ip_addr), ipaddr); IP_SET_TYPE_VAL(netif->ip_addr, IPADDR_TYPE_V4); mib2_add_ip4(netif); mib2_add_route_ip4(0, netif); netif_issue_reports(netif, <API key>); <API key>(netif); } LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: IP address of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", netif->name[0], netif->name[1], ip4_addr1_16(netif_ip4_addr(netif)), ip4_addr2_16(netif_ip4_addr(netif)), ip4_addr3_16(netif_ip4_addr(netif)), ip4_addr4_16(netif_ip4_addr(netif)))); } /** * @ingroup netif_ip4 * Change the default gateway for a network interface * * @param netif the network interface to change * @param gw the new default gateway * * @note call netif_set_addr() if you also want to change ip address and netmask */ void netif_set_gw(struct netif *netif, const ip4_addr_t *gw) { ip4_addr_set(ip_2_ip4(&netif->gw), gw); IP_SET_TYPE_VAL(netif->gw, IPADDR_TYPE_V4); LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: GW address of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", netif->name[0], netif->name[1], ip4_addr1_16(netif_ip4_gw(netif)), ip4_addr2_16(netif_ip4_gw(netif)), ip4_addr3_16(netif_ip4_gw(netif)), ip4_addr4_16(netif_ip4_gw(netif)))); } /** * @ingroup netif_ip4 * Change the netmask of a network interface * * @param netif the network interface to change * @param netmask the new netmask * * @note call netif_set_addr() if you also want to change ip address and * default gateway */ void netif_set_netmask(struct netif *netif, const ip4_addr_t *netmask) { <API key>(0, netif); /* set new netmask to netif */ ip4_addr_set(ip_2_ip4(&netif->netmask), netmask); IP_SET_TYPE_VAL(netif->netmask, IPADDR_TYPE_V4); mib2_add_route_ip4(0, netif); LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: netmask of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", netif->name[0], netif->name[1], ip4_addr1_16(netif_ip4_netmask(netif)), ip4_addr2_16(netif_ip4_netmask(netif)), ip4_addr3_16(netif_ip4_netmask(netif)), ip4_addr4_16(netif_ip4_netmask(netif)))); } #endif /* LWIP_IPV4 */ /** * @ingroup netif * Set a network interface as the default network interface * (used to output all packets for which no specific route is found) * * @param netif the default network interface */ void netif_set_default(struct netif *netif) { if (netif == NULL) { /* remove default route */ <API key>(1, netif); } else { /* install default route */ mib2_add_route_ip4(1, netif); } netif_default = netif; LWIP_DEBUGF(NETIF_DEBUG, ("netif: setting default interface %c%c\n", netif ? netif->name[0] : '\'', netif ? netif->name[1] : '\'')); } /** * @ingroup netif * Bring an interface up, available for processing * traffic. */ void netif_set_up(struct netif *netif) { if (!(netif->flags & NETIF_FLAG_UP)) { netif->flags |= NETIF_FLAG_UP; <API key>(&netif->ts); <API key>(netif); if (netif->flags & NETIF_FLAG_LINK_UP) { netif_issue_reports(netif, <API key>|<API key>); } } } /** Send ARP/IGMP/MLD/RS events, e.g. on link-up/netif-up or addr-change */ static void netif_issue_reports(struct netif* netif, u8_t report_type) { #if LWIP_IPV4 if ((report_type & <API key>) && !ip4_addr_isany_val(*netif_ip4_addr(netif))) { #if LWIP_ARP /* For Ethernet network interfaces, we would like to send a "gratuitous ARP" */ if (netif->flags & (NETIF_FLAG_ETHARP)) { etharp_gratuitous(netif); } #endif /* LWIP_ARP */ #if LWIP_IGMP /* resend IGMP memberships */ if (netif->flags & NETIF_FLAG_IGMP) { igmp_report_groups(netif); } #endif /* LWIP_IGMP */ } #endif /* LWIP_IPV4 */ #if LWIP_IPV6 if (report_type & <API key>) { #if LWIP_IPV6_MLD /* send mld memberships */ mld6_report_groups(netif); #endif /* LWIP_IPV6_MLD */ #if <API key> /* Send Router Solicitation messages. */ netif->rs_count = <API key>; #endif /* <API key> */ } #endif /* LWIP_IPV6 */ } /** * @ingroup netif * Bring an interface down, disabling any traffic processing. */ void netif_set_down(struct netif *netif) { if (netif->flags & NETIF_FLAG_UP) { netif->flags &= ~NETIF_FLAG_UP; <API key>(&netif->ts); #if LWIP_IPV4 && LWIP_ARP if (netif->flags & NETIF_FLAG_ETHARP) { <API key>(netif); } #endif /* LWIP_IPV4 && LWIP_ARP */ #if LWIP_IPV6 nd6_cleanup_netif(netif); #endif /* LWIP_IPV6 */ <API key>(netif); } } #if <API key> /** * @ingroup netif * Set callback to be called when interface is brought up/down or address is changed while up */ void <API key>(struct netif *netif, <API key> status_callback) { if (netif) { netif->status_callback = status_callback; } } #endif /* <API key> */ #if <API key> /** * @ingroup netif * Set callback to be called when the interface has been removed */ void <API key>(struct netif *netif, <API key> remove_callback) { if (netif) { netif->remove_callback = remove_callback; } } #endif /* <API key> */ /** * @ingroup netif * Called by a driver when its link goes up */ void netif_set_link_up(struct netif *netif) { if (!(netif->flags & NETIF_FLAG_LINK_UP)) { netif->flags |= NETIF_FLAG_LINK_UP; #if LWIP_DHCP <API key>(netif); #endif /* LWIP_DHCP */ #if LWIP_AUTOIP <API key>(netif); #endif /* LWIP_AUTOIP */ if (netif->flags & NETIF_FLAG_UP) { netif_issue_reports(netif, <API key>|<API key>); } NETIF_LINK_CALLBACK(netif); } } /** * @ingroup netif * Called by a driver when its link goes down */ void netif_set_link_down(struct netif *netif ) { if (netif->flags & NETIF_FLAG_LINK_UP) { netif->flags &= ~NETIF_FLAG_LINK_UP; NETIF_LINK_CALLBACK(netif); } } #if <API key> /** * @ingroup netif * Set callback to be called when link is brought up/down */ void <API key>(struct netif *netif, <API key> link_callback) { if (netif) { netif->link_callback = link_callback; } } #endif /* <API key> */ #if ENABLE_LOOPBACK /** * @ingroup netif * Send an IP packet to be received on the same netif (loopif-like). * The pbuf is simply copied and handed back to netif->input. * In multithreaded mode, this is done directly since netif->input must put * the packet on a queue. * In callback mode, the packet is put on an internal queue and is fed to * netif->input by netif_poll(). * * @param netif the lwip network interface structure * @param p the (IP) packet to 'send' * @return ERR_OK if the packet has been sent * ERR_MEM if the pbuf used to copy the packet couldn't be allocated */ err_t netif_loop_output(struct netif *netif, struct pbuf *p) { struct pbuf *r; err_t err; struct pbuf *last; #if <API key> u16_t clen = 0; #endif /* <API key> */ /* If we have a loopif, SNMP counters are adjusted for it, * if not they are adjusted for 'netif'. */ #if MIB2_STATS #if LWIP_HAVE_LOOPIF struct netif *stats_if = &loop_netif; #else /* LWIP_HAVE_LOOPIF */ struct netif *stats_if = netif; #endif /* LWIP_HAVE_LOOPIF */ #endif /* MIB2_STATS */ <API key>(lev); /* Allocate a new pbuf */ r = pbuf_alloc(PBUF_LINK, p->tot_len, PBUF_RAM); if (r == NULL) { LINK_STATS_INC(link.memerr); LINK_STATS_INC(link.drop); <API key>(stats_if, ifoutdiscards); return ERR_MEM; } #if <API key> clen = pbuf_clen(r); /* check for overflow or too many pbuf on queue */ if (((netif->loop_cnt_current + clen) < netif->loop_cnt_current) || ((netif->loop_cnt_current + clen) > <API key>)) { pbuf_free(r); LINK_STATS_INC(link.memerr); LINK_STATS_INC(link.drop); <API key>(stats_if, ifoutdiscards); return ERR_MEM; } netif->loop_cnt_current += clen; #endif /* <API key> */ /* Copy the whole pbuf queue p into the single pbuf r */ if ((err = pbuf_copy(r, p)) != ERR_OK) { pbuf_free(r); LINK_STATS_INC(link.memerr); LINK_STATS_INC(link.drop); <API key>(stats_if, ifoutdiscards); return err; } /* Put the packet on a linked list which gets emptied through calling netif_poll(). */ /* let last point to the last pbuf in chain r */ for (last = r; last->next != NULL; last = last->next); SYS_ARCH_PROTECT(lev); if (netif->loop_first != NULL) { LWIP_ASSERT("if first != NULL, last must also be != NULL", netif->loop_last != NULL); netif->loop_last->next = r; netif->loop_last = last; } else { netif->loop_first = r; netif->loop_last = last; } SYS_ARCH_UNPROTECT(lev); LINK_STATS_INC(link.xmit); <API key>(stats_if, ifoutoctets, p->tot_len); <API key>(stats_if, ifoutucastpkts); #if <API key> /* For multithreading environment, schedule a call to netif_poll */ <API key>((tcpip_callback_fn)netif_poll, netif, 0); #endif /* <API key> */ return ERR_OK; } #if LWIP_HAVE_LOOPIF #if LWIP_IPV4 static err_t <API key>(struct netif *netif, struct pbuf *p, const ip4_addr_t* addr) { LWIP_UNUSED_ARG(addr); return netif_loop_output(netif, p); } #endif /* LWIP_IPV4 */ #if LWIP_IPV6 static err_t <API key>(struct netif *netif, struct pbuf *p, const ip6_addr_t* addr) { LWIP_UNUSED_ARG(addr); return netif_loop_output(netif, p); } #endif /* LWIP_IPV6 */ #endif /* LWIP_HAVE_LOOPIF */ /** * Call netif_poll() in the main loop of your application. This is to prevent * reentering non-reentrant functions like tcp_input(). Packets passed to * netif_loop_output() are put on a list that is passed to netif->input() by * netif_poll(). */ void netif_poll(struct netif *netif) { struct pbuf *in; /* If we have a loopif, SNMP counters are adjusted for it, * if not they are adjusted for 'netif'. */ #if MIB2_STATS #if LWIP_HAVE_LOOPIF struct netif *stats_if = &loop_netif; #else /* LWIP_HAVE_LOOPIF */ struct netif *stats_if = netif; #endif /* LWIP_HAVE_LOOPIF */ #endif /* MIB2_STATS */ <API key>(lev); do { /* Get a packet from the list. With <API key>=1, this is protected */ SYS_ARCH_PROTECT(lev); in = netif->loop_first; if (in != NULL) { struct pbuf *in_end = in; #if <API key> u8_t clen = 1; #endif /* <API key> */ while (in_end->len != in_end->tot_len) { LWIP_ASSERT("bogus pbuf: len != tot_len but next == NULL!", in_end->next != NULL); in_end = in_end->next; #if <API key> clen++; #endif /* <API key> */ } #if <API key> /* adjust the number of pbufs on queue */ LWIP_ASSERT("netif->loop_cnt_current underflow", ((netif->loop_cnt_current - clen) < netif->loop_cnt_current)); netif->loop_cnt_current -= clen; #endif /* <API key> */ /* 'in_end' now points to the last pbuf from 'in' */ if (in_end == netif->loop_last) { /* this was the last pbuf in the list */ netif->loop_first = netif->loop_last = NULL; } else { /* pop the pbuf off the list */ netif->loop_first = in_end->next; LWIP_ASSERT("should not be null since first != last!", netif->loop_first != NULL); } /* De-queue the pbuf from its successors on the 'loop_' list. */ in_end->next = NULL; } SYS_ARCH_UNPROTECT(lev); if (in != NULL) { LINK_STATS_INC(link.recv); <API key>(stats_if, ifinoctets, in->tot_len); <API key>(stats_if, ifinucastpkts); /* loopback packets are always IP packets! */ if (ip_input(in, netif) != ERR_OK) { pbuf_free(in); } /* Don't reference the packet any more! */ in = NULL; } /* go on while there is a packet on the list */ } while (netif->loop_first != NULL); } #if !<API key> /** * Calls netif_poll() for every netif on the netif_list. */ void netif_poll_all(void) { struct netif *netif = netif_list; /* loop through netifs */ while (netif != NULL) { netif_poll(netif); /* proceed to next network interface */ netif = netif->next; } } #endif /* !<API key> */ #endif /* ENABLE_LOOPBACK */ #if <API key> > 0 /** * @ingroup netif_cd * Allocate an index to store data in client_data member of struct netif. * Returned value is an index in mentioned array. * @see <API key> */ u8_t <API key>(void) { u8_t result = netif_client_id; netif_client_id++; LWIP_ASSERT("Increase <API key> in lwipopts.h", result < <API key>); return result + <API key>; } #endif #if LWIP_IPV6 /** * @ingroup netif_ip6 * Change an IPv6 address of a network interface * * @param netif the network interface to change * @param addr_idx index of the IPv6 address * @param addr6 the new IPv6 address * * @note call <API key>() to set the address valid/temptative */ void netif_ip6_addr_set(struct netif *netif, s8_t addr_idx, const ip6_addr_t *addr6) { LWIP_ASSERT("addr6 != NULL", addr6 != NULL); <API key>(netif, addr_idx, addr6->addr[0], addr6->addr[1], addr6->addr[2], addr6->addr[3]); } /* * Change an IPv6 address of a network interface (internal version taking 4 * u32_t) * * @param netif the network interface to change * @param addr_idx index of the IPv6 address * @param i0 word0 of the new IPv6 address * @param i1 word1 of the new IPv6 address * @param i2 word2 of the new IPv6 address * @param i3 word3 of the new IPv6 address */ void <API key>(struct netif *netif, s8_t addr_idx, u32_t i0, u32_t i1, u32_t i2, u32_t i3) { const ip6_addr_t *old_addr; LWIP_ASSERT("netif != NULL", netif != NULL); LWIP_ASSERT("invalid index", addr_idx < <API key>); old_addr = netif_ip6_addr(netif, addr_idx); /* address is actually being changed? */ if ((old_addr->addr[0] != i0) || (old_addr->addr[1] != i1) || (old_addr->addr[2] != i2) || (old_addr->addr[3] != i3)) { LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_ip6_addr_set: netif address being changed\n")); if (<API key>(netif, addr_idx) & IP6_ADDR_VALID) { #if LWIP_TCP || LWIP_UDP ip_addr_t new_ipaddr; IP_ADDR6(&new_ipaddr, i0, i1, i2, i3); #endif /* LWIP_TCP || LWIP_UDP */ #if LWIP_TCP <API key>(netif_ip_addr6(netif, addr_idx), &new_ipaddr); #endif /* LWIP_TCP */ #if LWIP_UDP <API key>(netif_ip_addr6(netif, addr_idx), &new_ipaddr); #endif /* LWIP_UDP */ #if LWIP_RAW <API key>(netif_ip_addr6(netif, addr_idx), &new_ipaddr); #endif /* LWIP_RAW */ } /* @todo: remove/readd mib2 ip6 entries? */ IP6_ADDR(ip_2_ip6(&(netif->ip6_addr[addr_idx])), i0, i1, i2, i3); IP_SET_TYPE_VAL(netif->ip6_addr[addr_idx], IPADDR_TYPE_V6); if (<API key>(netif, addr_idx) & IP6_ADDR_VALID) { netif_issue_reports(netif, <API key>); <API key>(netif); } } LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: IPv6 address %d of interface %c%c set to %s/0x%"X8_F"\n", addr_idx, netif->name[0], netif->name[1], ip6addr_ntoa(netif_ip6_addr(netif, addr_idx)), <API key>(netif, addr_idx))); } /** * @ingroup netif_ip6 * Change the state of an IPv6 address of a network interface * (INVALID, TEMPTATIVE, PREFERRED, DEPRECATED, where TEMPTATIVE * includes the number of checks done, see ip6_addr.h) * * @param netif the network interface to change * @param addr_idx index of the IPv6 address * @param state the new IPv6 address state */ void <API key>(struct netif* netif, s8_t addr_idx, u8_t state) { u8_t old_state; LWIP_ASSERT("netif != NULL", netif != NULL); LWIP_ASSERT("invalid index", addr_idx < <API key>); old_state = <API key>(netif, addr_idx); /* state is actually being changed? */ if (old_state != state) { u8_t old_valid = old_state & IP6_ADDR_VALID; u8_t new_valid = state & IP6_ADDR_VALID; LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("<API key>: netif address state being changed\n")); if (old_valid && !new_valid) { /* address about to be removed by setting invalid */ #if LWIP_TCP <API key>(netif_ip_addr6(netif, addr_idx), NULL); #endif /* LWIP_TCP */ #if LWIP_UDP <API key>(netif_ip_addr6(netif, addr_idx), NULL); #endif /* LWIP_UDP */ #if LWIP_RAW <API key>(netif_ip_addr6(netif, addr_idx), NULL); #endif /* LWIP_RAW */ /* @todo: remove mib2 ip6 entries? */ } netif->ip6_addr_state[addr_idx] = state; if (!old_valid && new_valid) { /* address added by setting valid */ /* @todo: add mib2 ip6 entries? */ netif_issue_reports(netif, <API key>); } if ((old_state & IP6_ADDR_PREFERRED) != (state & IP6_ADDR_PREFERRED)) { /* address state has changed (valid flag changed or switched between preferred and deprecated) -> call the callback function */ <API key>(netif); } } LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: IPv6 address %d of interface %c%c set to %s/0x%"X8_F"\n", addr_idx, netif->name[0], netif->name[1], ip6addr_ntoa(netif_ip6_addr(netif, addr_idx)), <API key>(netif, addr_idx))); } /** * Checks if a specific address is assigned to the netif and returns its * index. * * @param netif the netif to check * @param ip6addr the IPv6 address to find * @return >= 0: address found, this is its index * -1: address not found on this netif */ s8_t <API key>(struct netif *netif, const ip6_addr_t *ip6addr) { s8_t i; for (i = 0; i < <API key>; i++) { if (!ip6_addr_isinvalid(<API key>(netif, i)) && ip6_addr_cmp(netif_ip6_addr(netif, i), ip6addr)) { return i; } } return -1; } /** * @ingroup netif_ip6 * Create a link-local IPv6 address on a netif (stored in slot 0) * * @param netif the netif to create the address on * @param from_mac_48bit if != 0, assume hwadr is a 48-bit MAC address (std conversion) * if == 0, use hwaddr directly as interface ID */ void <API key>(struct netif *netif, u8_t from_mac_48bit) { u8_t i, addr_index; /* Link-local prefix. */ ip_2_ip6(&netif->ip6_addr[0])->addr[0] = PP_HTONL(0xfe800000ul); ip_2_ip6(&netif->ip6_addr[0])->addr[1] = 0; /* Generate interface ID. */ if (from_mac_48bit) { /* Assume hwaddr is a 48-bit IEEE 802 MAC. Convert to EUI-64 address. Complement Group bit. */ ip_2_ip6(&netif->ip6_addr[0])->addr[2] = lwip_htonl((((u32_t)(netif->hwaddr[0] ^ 0x02)) << 24) | ((u32_t)(netif->hwaddr[1]) << 16) | ((u32_t)(netif->hwaddr[2]) << 8) | (0xff)); ip_2_ip6(&netif->ip6_addr[0])->addr[3] = lwip_htonl((0xfeul << 24) | ((u32_t)(netif->hwaddr[3]) << 16) | ((u32_t)(netif->hwaddr[4]) << 8) | (netif->hwaddr[5])); } else { /* Use hwaddr directly as interface ID. */ ip_2_ip6(&netif->ip6_addr[0])->addr[2] = 0; ip_2_ip6(&netif->ip6_addr[0])->addr[3] = 0; addr_index = 3; for (i = 0; (i < 8) && (i < netif->hwaddr_len); i++) { if (i == 4) { addr_index } ip_2_ip6(&netif->ip6_addr[0])->addr[addr_index] |= ((u32_t)(netif->hwaddr[netif->hwaddr_len - i - 1])) << (8 * (i & 0x03)); } } /* Set address state. */ #if <API key> /* Will perform duplicate address detection (DAD). */ netif->ip6_addr_state[0] = IP6_ADDR_TENTATIVE; #else /* Consider address valid. */ netif->ip6_addr_state[0] = IP6_ADDR_PREFERRED; #endif /* <API key> */ } /** * @ingroup netif_ip6 * This function allows for the easy addition of a new IPv6 address to an interface. * It takes care of finding an empty slot and then sets the address tentative * (to make sure that all the subsequent processing happens). * * @param netif netif to add the address on * @param ip6addr address to add * @param chosen_idx if != NULL, the chosen IPv6 address index will be stored here */ err_t <API key>(struct netif *netif, const ip6_addr_t *ip6addr, s8_t *chosen_idx) { s8_t i; i = <API key>(netif, ip6addr); if (i >= 0) { /* Address already added */ if (chosen_idx != NULL) { *chosen_idx = i; } return ERR_OK; } /* Find a free slot -- musn't be the first one (reserved for link local) */ for (i = 1; i < <API key>; i++) { if (!ip6_addr_isvalid(netif->ip6_addr_state[i])) { <API key>(netif->ip6_addr[i], *ip6addr); <API key>(netif, i, IP6_ADDR_TENTATIVE); if (chosen_idx != NULL) { *chosen_idx = i; } return ERR_OK; } } if (chosen_idx != NULL) { *chosen_idx = -1; } return ERR_VAL; } /** Dummy IPv6 output function for netifs not supporting IPv6 */ static err_t <API key>(struct netif *netif, struct pbuf *p, const ip6_addr_t *ipaddr) { LWIP_UNUSED_ARG(netif); LWIP_UNUSED_ARG(p); LWIP_UNUSED_ARG(ipaddr); return ERR_IF; } #endif /* LWIP_IPV6 */
#define NOMINMAX #include "harness_defs.h" #include "tbb/concurrent_queue.h" #include "tbb/tick_count.h" #include "harness.h" #include "harness_allocator.h" #include <vector> static tbb::atomic<long> FooConstructed; static tbb::atomic<long> FooDestroyed; enum state_t{ LIVE=0x1234, DEAD=0xDEAD }; class Foo { state_t state; public: int thread_id; int serial; Foo() : state(LIVE), thread_id(0), serial(0) { ++FooConstructed; } Foo( const Foo& item ) : state(LIVE) { ASSERT( item.state==LIVE, NULL ); ++FooConstructed; thread_id = item.thread_id; serial = item.serial; } ~Foo() { ASSERT( state==LIVE, NULL ); ++FooDestroyed; state=DEAD; thread_id=DEAD; serial=DEAD; } void operator=( const Foo& item ) { ASSERT( item.state==LIVE, NULL ); ASSERT( state==LIVE, NULL ); thread_id = item.thread_id; serial = item.serial; } bool is_const() {return false;} bool is_const() const {return true;} static void clear_counters() { FooConstructed = 0; FooDestroyed = 0; } static long get_n_constructed() { return FooConstructed; } static long get_n_destroyed() { return FooDestroyed; } }; // problem size static const int N = 50000; // # of bytes #if TBB_USE_EXCEPTIONS //! Exception for concurrent_queue class Foo_exception : public std::bad_alloc { public: virtual const char *what() const throw() { return "out of Foo limit"; } virtual ~Foo_exception() throw() {} }; static tbb::atomic<long> FooExConstructed; static tbb::atomic<long> FooExDestroyed; static tbb::atomic<long> serial_source; static long MaxFooCount = 0; static const long Threshold = 400; class FooEx { state_t state; public: int serial; FooEx() : state(LIVE) { ++FooExConstructed; serial = serial_source++; } FooEx( const FooEx& item ) : state(LIVE) { ASSERT( item.state == LIVE, NULL ); ++FooExConstructed; if( MaxFooCount && (<API key>) >= MaxFooCount ) // in push() throw Foo_exception(); serial = item.serial; } ~FooEx() { ASSERT( state==LIVE, NULL ); ++FooExDestroyed; state=DEAD; serial=DEAD; } void operator=( FooEx& item ) { ASSERT( item.state==LIVE, NULL ); ASSERT( state==LIVE, NULL ); serial = item.serial; if( MaxFooCount==2*Threshold && (<API key>) <= MaxFooCount/4 ) // in pop() throw Foo_exception(); } #if <API key> void operator=( FooEx&& item ) { operator=( item ); item.serial = 0; } #endif /* <API key> */ } ; #endif /* TBB_USE_EXCEPTIONS */ const size_t MAXTHREAD = 256; static int Sum[MAXTHREAD]; //! Count of various pop operations /** [0] = pop_if_present that failed [1] = pop_if_present that succeeded [2] = pop */ static tbb::atomic<long> PopKind[3]; const int M = 10000; #if <API key> && <API key> const size_t <API key> = 3; #elif <API key> const size_t <API key> = 2; #else const size_t <API key> = 1; #endif template<typename CQ, typename ValueType, typename CounterType> void push( CQ& q, ValueType v, CounterType i ) { switch( i % <API key> ) { case 0: q.push( v ); break; #if <API key> case 1: q.push( std::move(v) ); break; #if <API key> case 2: q.emplace( v ); break; #endif #endif default: ASSERT( false, NULL ); break; } } template<typename CQ,typename T> struct Body: NoAssign { CQ* queue; const int nthread; Body( int nthread_ ) : nthread(nthread_) {} void operator()( int thread_id ) const { long pop_kind[3] = {0,0,0}; int serial[MAXTHREAD+1]; memset( serial, 0, nthread*sizeof(int) ); ASSERT( thread_id<nthread, NULL ); long sum = 0; for( long j=0; j<M; ++j ) { T f; f.thread_id = DEAD; f.serial = DEAD; bool prepopped = false; if( j&1 ) { prepopped = queue->try_pop( f ); ++pop_kind[prepopped]; } T g; g.thread_id = thread_id; g.serial = j+1; push( *queue, g, j ); if( !prepopped ) { while( !(queue)->try_pop(f) ) __TBB_Yield(); ++pop_kind[2]; } ASSERT( f.thread_id<=nthread, NULL ); ASSERT( f.thread_id==nthread || serial[f.thread_id]<f.serial, "partial order violation" ); serial[f.thread_id] = f.serial; sum += f.serial-1; } Sum[thread_id] = sum; for( int k=0; k<3; ++k ) PopKind[k] += pop_kind[k]; } }; // Define wrapper classes to test tbb::concurrent_queue<T> template<typename T, typename A = tbb::<API key><T> > class <API key> : public tbb::concurrent_queue<T, A> { public: <API key>() {} <API key>( const <API key>& q ) : tbb::concurrent_queue<T, A>( q ) {} <API key>(const A& a) : tbb::concurrent_queue<T, A>( a ) {} #if <API key> <API key>(<API key>&& q) : tbb::concurrent_queue<T>( std::move(q) ) {} <API key>(<API key>&& q, const A& a) : tbb::concurrent_queue<T, A>( std::move(q), a ) { } #endif /* <API key> */ template<typename InputIterator> <API key>( InputIterator begin, InputIterator end, const A& a = A()) : tbb::concurrent_queue<T, A>(begin,end,a) {} size_t size() const { return this->unsafe_size(); } }; template<typename T> class ConcQPushPopWrapper : public tbb::concurrent_queue<T> { public: ConcQPushPopWrapper() : my_capacity( size_t(-1)/(sizeof(void*)+sizeof(T)) ) {} size_t size() const { return this->unsafe_size(); } void set_capacity( const ptrdiff_t n ) { my_capacity = n; } bool try_push( const T& source ) { return this->push( source ); } bool try_pop( T& dest ) { return this->tbb::concurrent_queue<T>::try_pop( dest ); } size_t my_capacity; }; template<typename T> class ConcQWithCapacity : public tbb::concurrent_queue<T> { public: ConcQWithCapacity() : my_capacity( size_t(-1)/(sizeof(void*)+sizeof(T)) ) {} size_t size() const { return this->unsafe_size(); } size_t capacity() const { return my_capacity; } void set_capacity( const int n ) { my_capacity = n; } bool try_push( const T& source ) { this->push( source ); return (size_t)source.serial<my_capacity; } bool try_pop( T& dest ) { this->tbb::concurrent_queue<T>::try_pop( dest ); return (size_t)dest.serial<my_capacity; } size_t my_capacity; }; template <typename Queue> void AssertEquality(Queue &q, const std::vector<typename Queue::value_type> &vec) { ASSERT(q.size() == typename Queue::size_type(vec.size()), NULL); ASSERT(std::equal(q.unsafe_begin(), q.unsafe_end(), vec.begin(), Harness::IsEqual()), NULL); } template <typename Queue> void AssertEmptiness(Queue &q) { ASSERT(q.empty(), NULL); ASSERT(!q.size(), NULL); typename Queue::value_type elem; ASSERT(!q.try_pop(elem), NULL); } enum push_t { push_op, try_push_op }; template<push_t push_op> struct pusher { #if <API key> template<typename CQ, typename VType> static bool push( CQ& queue, VType&& val ) { queue.push( std::forward<VType>( val ) ); return true; } #else template<typename CQ, typename VType> static bool push( CQ& queue, const VType& val ) { queue.push( val ); return true; } #endif /* <API key> */ }; template<> struct pusher< try_push_op > { #if <API key> template<typename CQ, typename VType> static bool push( CQ& queue, VType&& val ) { return queue.try_push( std::forward<VType>( val ) ); } #else template<typename CQ, typename VType> static bool push( CQ& queue, const VType& val ) { return queue.try_push( val ); } #endif /* <API key> */ }; enum pop_t { pop_op, try_pop_op }; template<pop_t pop_op> struct popper { #if <API key> template<typename CQ, typename VType> static bool pop( CQ& queue, VType&& val ) { if( queue.empty() ) return false; queue.pop( std::forward<VType>( val ) ); return true; } #else template<typename CQ, typename VType> static bool pop( CQ& queue, VType& val ) { if( queue.empty() ) return false; queue.pop( val ); return true; } #endif /* <API key> */ }; template<> struct popper< try_pop_op > { #if <API key> template<typename CQ, typename VType> static bool pop( CQ& queue, VType&& val ) { return queue.try_pop( std::forward<VType>( val ) ); } #else template<typename CQ, typename VType> static bool pop( CQ& queue, VType& val ) { return queue.try_pop( val ); } #endif /* <API key> */ }; template <push_t push_op, typename Queue> void FillTest(Queue &q, const std::vector<typename Queue::value_type> &vec) { for (typename std::vector<typename Queue::value_type>::const_iterator it = vec.begin(); it != vec.end(); ++it) ASSERT(pusher<push_op>::push(q, *it), NULL); AssertEquality(q, vec); } template <pop_t pop_op, typename Queue> void EmptyTest(Queue &q, const std::vector<typename Queue::value_type> &vec) { typedef typename Queue::value_type value_type; value_type elem; typename std::vector<value_type>::const_iterator it = vec.begin(); while (popper<pop_op>::pop(q, elem)) { ASSERT(Harness::IsEqual()(elem, *it), NULL); ++it; } ASSERT(it == vec.end(), NULL); AssertEmptiness(q); } template <typename T, typename A> void <API key>(tbb::concurrent_queue<T, A> &, const std::vector<T> &) { /* do nothing */ } template <typename T, typename A> void <API key>(tbb::<API key><T, A> &q, const std::vector<T> &vec) { typedef typename tbb::<API key><T, A>::size_type size_type; FillTest<try_push_op>(q, vec); tbb::<API key><T, A> q2 = q; EmptyTest<pop_op>(q, vec); // capacity q2.set_capacity(size_type(vec.size())); ASSERT(q2.capacity() == size_type(vec.size()), NULL); ASSERT(q2.size() == size_type(vec.size()), NULL); ASSERT(!q2.try_push(vec[0]), NULL); #if TBB_USE_EXCEPTIONS q.abort(); #endif } template<typename CQ, typename T> void TestPushPop( size_t prefill, ptrdiff_t capacity, int nthread ) { ASSERT( nthread>0, "nthread must be positive" ); ptrdiff_t signed_prefill = ptrdiff_t(prefill); if( signed_prefill+1>=capacity ) return; bool success = false; for( int k=0; k<3; ++k ) PopKind[k] = 0; for( int trial=0; !success; ++trial ) { T::clear_counters(); Body<CQ,T> body(nthread); CQ queue; queue.set_capacity( capacity ); body.queue = &queue; for( size_t i=0; i<prefill; ++i ) { T f; f.thread_id = nthread; f.serial = 1+int(i); push(queue, f, i); ASSERT( unsigned(queue.size())==i+1, NULL ); ASSERT( !queue.empty(), NULL ); } tbb::tick_count t0 = tbb::tick_count::now(); NativeParallelFor( nthread, body ); tbb::tick_count t1 = tbb::tick_count::now(); double timing = (t1-t0).seconds(); REMARK("prefill=%d capacity=%d threads=%d time = %g = %g nsec/operation\n", int(prefill), int(capacity), nthread, timing, timing/(2*M*nthread)*1.E9); int sum = 0; for( int k=0; k<nthread; ++k ) sum += Sum[k]; int expected = int(nthread*((M-1)*M/2) + ((prefill-1)*prefill)/2); for( int i=int(prefill); --i>=0; ) { ASSERT( !queue.empty(), NULL ); T f; bool result = queue.try_pop(f); ASSERT( result, NULL ); ASSERT( int(queue.size())==i, NULL ); sum += f.serial-1; } ASSERT( queue.empty(), "The queue should be empty" ); ASSERT( queue.size()==0, "The queue should have zero size" ); if( sum!=expected ) REPORT("sum=%d expected=%d\n",sum,expected); ASSERT( T::get_n_constructed()==T::get_n_destroyed(), NULL ); // TODO: checks by counting allocators success = true; if( nthread>1 && prefill==0 ) { // Check that pop_if_present got sufficient exercise for( int k=0; k<2; ++k ) { #if (_WIN32||_WIN64) // The TBB library on Windows seems to have a tough time generating // the desired interleavings for pop_if_present, so the code tries longer, and settles // for fewer desired interleavings. const int max_trial = 100; const int min_requirement = 20; #else const int min_requirement = 100; const int max_trial = 20; #endif /* _WIN32||_WIN64 */ if( PopKind[k]<min_requirement ) { if( trial>=max_trial ) { if( Verbose ) REPORT("Warning: %d threads had only %ld pop_if_present operations %s after %d trials (expected at least %d). " "This problem may merely be unlucky scheduling. " "Investigate only if it happens repeatedly.\n", nthread, long(PopKind[k]), k==0?"failed":"succeeded", max_trial, min_requirement); else REPORT("Warning: the number of %s pop_if_present operations is less than expected for %d threads. Investigate if it happens repeatedly.\n", k==0?"failed":"succeeded", nthread ); } else { success = false; } } } } } } class Bar { state_t state; public: static size_t construction_num, destruction_num; ptrdiff_t my_id; Bar() : state(LIVE), my_id(-1) {} Bar(size_t _i) : state(LIVE), my_id(_i) { construction_num++; } Bar( const Bar& a_bar ) : state(LIVE) { ASSERT( a_bar.state==LIVE, NULL ); my_id = a_bar.my_id; construction_num++; } ~Bar() { ASSERT( state==LIVE, NULL ); state = DEAD; my_id = DEAD; destruction_num++; } void operator=( const Bar& a_bar ) { ASSERT( a_bar.state==LIVE, NULL ); ASSERT( state==LIVE, NULL ); my_id = a_bar.my_id; } friend bool operator==(const Bar& bar1, const Bar& bar2 ) ; } ; size_t Bar::construction_num = 0; size_t Bar::destruction_num = 0; bool operator==(const Bar& bar1, const Bar& bar2) { ASSERT( bar1.state==LIVE, NULL ); ASSERT( bar2.state==LIVE, NULL ); return bar1.my_id == bar2.my_id; } class BarIterator { Bar* bar_ptr; BarIterator(Bar* bp_) : bar_ptr(bp_) {} public: ~BarIterator() {} BarIterator& operator=( const BarIterator& other ) { bar_ptr = other.bar_ptr; return *this; } Bar& operator*() const { return *bar_ptr; } BarIterator& operator++() { ++bar_ptr; return *this; } Bar* operator++(int) { Bar* result = &operator*(); operator++(); return result; } friend bool operator==(const BarIterator& bia, const BarIterator& bib) ; friend bool operator!=(const BarIterator& bia, const BarIterator& bib) ; template<typename CQ, typename T, typename TIter, typename CQ_EX, typename T_EX> friend void TestConstructors (); } ; bool operator==(const BarIterator& bia, const BarIterator& bib) { return bia.bar_ptr==bib.bar_ptr; } bool operator!=(const BarIterator& bia, const BarIterator& bib) { return bia.bar_ptr!=bib.bar_ptr; } #if TBB_USE_EXCEPTIONS class Bar_exception : public std::bad_alloc { public: virtual const char *what() const throw() { return "making the entry invalid"; } virtual ~Bar_exception() throw() {} }; class BarEx { static int count; public: state_t state; typedef enum { PREPARATION, COPY_CONSTRUCT } mode_t; static mode_t mode; ptrdiff_t my_id; ptrdiff_t my_tilda_id; static int button; BarEx() : state(LIVE), my_id(-1), my_tilda_id(-1) {} BarEx(size_t _i) : state(LIVE), my_id(_i), my_tilda_id(my_id^(-1)) {} BarEx( const BarEx& a_bar ) : state(LIVE) { ASSERT( a_bar.state==LIVE, NULL ); my_id = a_bar.my_id; if( mode==PREPARATION ) if( !( ++count % 100 ) ) throw Bar_exception(); my_tilda_id = a_bar.my_tilda_id; } ~BarEx() { ASSERT( state==LIVE, NULL ); state = DEAD; my_id = DEAD; } static void set_mode( mode_t m ) { mode = m; } void operator=( const BarEx& a_bar ) { ASSERT( a_bar.state==LIVE, NULL ); ASSERT( state==LIVE, NULL ); my_id = a_bar.my_id; my_tilda_id = a_bar.my_tilda_id; } friend bool operator==(const BarEx& bar1, const BarEx& bar2 ) ; } ; int BarEx::count = 0; BarEx::mode_t BarEx::mode = BarEx::PREPARATION; bool operator==(const BarEx& bar1, const BarEx& bar2) { ASSERT( bar1.state==LIVE, NULL ); ASSERT( bar2.state==LIVE, NULL ); ASSERT( (bar1.my_id ^ bar1.my_tilda_id) == -1, NULL ); ASSERT( (bar2.my_id ^ bar2.my_tilda_id) == -1, NULL ); return bar1.my_id==bar2.my_id && bar1.my_tilda_id==bar2.my_tilda_id; } #endif /* TBB_USE_EXCEPTIONS */ template<typename CQ, typename T, typename TIter, typename CQ_EX, typename T_EX> void TestConstructors () { CQ src_queue; typename CQ::const_iterator dqb; typename CQ::const_iterator dqe; typename CQ::const_iterator iter; for( size_t size=0; size<1001; ++size ) { for( size_t i=0; i<size; ++i ) src_queue.push(T(i+(i^size))); typename CQ::const_iterator sqb( src_queue.unsafe_begin() ); typename CQ::const_iterator sqe( src_queue.unsafe_end() ); CQ dst_queue(sqb, sqe); ASSERT(src_queue.size()==dst_queue.size(), "different size"); src_queue.clear(); } T bar_array[1001]; for( size_t size=0; size<1001; ++size ) { for( size_t i=0; i<size; ++i ) bar_array[i] = T(i+(i^size)); const TIter sab(bar_array+0); const TIter sae(bar_array+size); CQ dst_queue2(sab, sae); ASSERT( size==unsigned(dst_queue2.size()), NULL ); ASSERT( sab==TIter(bar_array+0), NULL ); ASSERT( sae==TIter(bar_array+size), NULL ); dqb = dst_queue2.unsafe_begin(); dqe = dst_queue2.unsafe_end(); TIter v_iter(sab); for( ; dqb != dqe; ++dqb, ++v_iter ) ASSERT( *dqb == *v_iter, "unexpected element" ); ASSERT( v_iter==sae, "different size?" ); } src_queue.clear(); CQ dst_queue3( src_queue ); ASSERT( src_queue.size()==dst_queue3.size(), NULL ); ASSERT( 0==dst_queue3.size(), NULL ); int k=0; for( size_t i=0; i<1001; ++i ) { T tmp_bar; src_queue.push(T(++k)); src_queue.push(T(++k)); src_queue.try_pop(tmp_bar); CQ dst_queue4( src_queue ); ASSERT( src_queue.size()==dst_queue4.size(), NULL ); dqb = dst_queue4.unsafe_begin(); dqe = dst_queue4.unsafe_end(); iter = src_queue.unsafe_begin(); for( ; dqb != dqe; ++dqb, ++iter ) ASSERT( *dqb == *iter, "unexpected element" ); ASSERT( iter==src_queue.unsafe_end(), "different size?" ); } CQ dst_queue5( src_queue ); ASSERT( src_queue.size()==dst_queue5.size(), NULL ); dqb = dst_queue5.unsafe_begin(); dqe = dst_queue5.unsafe_end(); iter = src_queue.unsafe_begin(); for( ; dqb != dqe; ++dqb, ++iter ) ASSERT( *dqb == *iter, "unexpected element" ); for( size_t i=0; i<100; ++i) { T tmp_bar; src_queue.push(T(i+1000)); src_queue.push(T(i+1000)); src_queue.try_pop(tmp_bar); dst_queue5.push(T(i+1000)); dst_queue5.push(T(i+1000)); dst_queue5.try_pop(tmp_bar); } ASSERT( src_queue.size()==dst_queue5.size(), NULL ); dqb = dst_queue5.unsafe_begin(); dqe = dst_queue5.unsafe_end(); iter = src_queue.unsafe_begin(); for( ; dqb != dqe; ++dqb, ++iter ) ASSERT( *dqb == *iter, "unexpected element" ); ASSERT( iter==src_queue.unsafe_end(), "different size?" ); #if <API key> || <API key> REPORT("Known issue: part of the constructor test is skipped.\n"); #elif TBB_USE_EXCEPTIONS k = 0; typename CQ_EX::size_type n_elements=0; CQ_EX src_queue_ex; for( size_t size=0; size<1001; ++size ) { T_EX tmp_bar_ex; typename CQ_EX::size_type n_successful_pushes=0; T_EX::set_mode( T_EX::PREPARATION ); try { src_queue_ex.push(T_EX(k+(k^size))); ++n_successful_pushes; } catch (...) { } ++k; try { src_queue_ex.push(T_EX(k+(k^size))); ++n_successful_pushes; } catch (...) { } ++k; src_queue_ex.try_pop(tmp_bar_ex); n_elements += (n_successful_pushes - 1); ASSERT( src_queue_ex.size()==n_elements, NULL); T_EX::set_mode( T_EX::COPY_CONSTRUCT ); CQ_EX dst_queue_ex( src_queue_ex ); ASSERT( src_queue_ex.size()==dst_queue_ex.size(), NULL ); typename CQ_EX::const_iterator dqb_ex = dst_queue_ex.unsafe_begin(); typename CQ_EX::const_iterator dqe_ex = dst_queue_ex.unsafe_end(); typename CQ_EX::const_iterator iter_ex = src_queue_ex.unsafe_begin(); for( ; dqb_ex != dqe_ex; ++dqb_ex, ++iter_ex ) ASSERT( *dqb_ex == *iter_ex, "unexpected element" ); ASSERT( iter_ex==src_queue_ex.unsafe_end(), "different size?" ); } #endif /* TBB_USE_EXCEPTIONS */ #if <API key> // Testing work of move constructors src_queue.clear(); typedef typename CQ::size_type qsize_t; for( qsize_t size = 0; size < 1001; ++size ) { for( qsize_t i = 0; i < size; ++i ) src_queue.push( T(i + (i ^ size)) ); std::vector<const T*> locations(size); typename CQ::const_iterator qit = src_queue.unsafe_begin(); for( qsize_t i = 0; i < size; ++i, ++qit ) locations[i] = &(*qit); qsize_t size_of_queue = src_queue.size(); CQ dst_queue( std::move(src_queue) ); ASSERT( src_queue.empty() && src_queue.size() == 0, "not working move constructor?" ); ASSERT( size == size_of_queue && size_of_queue == dst_queue.size(), "not working move constructor?" ); qit = dst_queue.unsafe_begin(); for( qsize_t i = 0; i < size; ++i, ++qit ) ASSERT( locations[i] == &(*qit), "there was data movement during move constructor" ); for( qsize_t i = 0; i < size; ++i ) { T test(i + (i ^ size)); T popped; bool pop_result = dst_queue.try_pop( popped ); ASSERT( pop_result, NULL ); ASSERT( test == popped, NULL ); } } #endif /* <API key> */ } #if <API key> template<class T> class allocator: public tbb::<API key><T> { public: size_t m_unique_id; allocator() : m_unique_id( 0 ) {} allocator(size_t unique_id) { m_unique_id = unique_id; } template<typename U> allocator(const allocator<U>& a) throw() { m_unique_id = a.m_unique_id; } template<typename U> struct rebind { typedef allocator<U> other; }; friend bool operator==(const allocator& lhs, const allocator& rhs) { return lhs.m_unique_id == rhs.m_unique_id; } }; // Checks operability of the queue the data was moved from template<typename T, typename CQ> void <API key>( CQ& queue ) { const size_t size = 10; std::vector<T> v(size); for( size_t i = 0; i < size; ++i ) v[i] = T( i * i + i ); FillTest<push_op>(queue, v); EmptyTest<try_pop_op>(queue, v); <API key>(queue, v); } template<class CQ, class T> void <API key>() { T::construction_num = T::destruction_num = 0; CQ src_queue( allocator<T>(0) ); const size_t size = 10; for( size_t i = 0; i < size; ++i ) src_queue.push( T(i + (i ^ size)) ); ASSERT( T::construction_num == 2 * size, NULL ); ASSERT( T::destruction_num == size, NULL ); const T* locations[size]; typename CQ::const_iterator qit = src_queue.unsafe_begin(); for( size_t i = 0; i < size; ++i, ++qit ) locations[i] = &(*qit); // Ensuring allocation operation takes place during move when allocators are different CQ dst_queue( std::move(src_queue), allocator<T>(1) ); ASSERT( T::construction_num == 2 * size + size, NULL ); ASSERT( T::destruction_num == 2 * size + size, NULL ); <API key><T>( src_queue ); qit = dst_queue.unsafe_begin(); for( size_t i = 0; i < size; ++i, ++qit ) { ASSERT( locations[i] != &(*qit), "item was not moved" ); locations[i] = &(*qit); } T::construction_num = T::destruction_num = 0; // Ensuring there is no allocation operation during move with equal allocators CQ dst_queue2( std::move(dst_queue), allocator<T>(1) ); ASSERT( T::construction_num == 0, NULL ); ASSERT( T::destruction_num == 0, NULL ); <API key><T>( dst_queue ); qit = dst_queue2.unsafe_begin(); for( size_t i = 0; i < size; ++i, ++qit ) { ASSERT( locations[i] == &(*qit), "item was moved" ); } for( size_t i = 0; i < size; ++i) { T test(i + (i ^ size)); T popped; bool pop_result = dst_queue2.try_pop( popped ); ASSERT( pop_result, NULL ); ASSERT( test == popped, NULL ); } ASSERT( dst_queue2.empty(), NULL ); ASSERT( dst_queue2.size() == 0, NULL ); } void <API key>() { REMARK("Testing move constructors with specified allocators..."); <API key>< <API key>< Bar, allocator<Bar> >, Bar >(); <API key>< tbb::<API key>< Bar, allocator<Bar> >, Bar >(); REMARK(" work\n"); } #endif /* <API key> */ template<typename Iterator1, typename Iterator2> void TestIteratorAux( Iterator1 i, Iterator2 j, int size ) { // Now test iteration Iterator1 old_i; for( int k=0; k<size; ++k ) { ASSERT( i!=j, NULL ); ASSERT( !(i==j), NULL ); Foo f; if( k&1 ) { // Test pre-increment f = *old_i++; // Test assignment i = old_i; } else { // Test post-increment f=*i++; if( k<size-1 ) { // Test "->" ASSERT( k+2==i->serial, NULL ); } // Test assignment old_i = i; } ASSERT( k+1==f.serial, NULL ); } ASSERT( !(i!=j), NULL ); ASSERT( i==j, NULL ); } template<typename Iterator1, typename Iterator2> void <API key>( Iterator2 j ) { Iterator1 i(j); ASSERT( i==j, NULL ); ASSERT( !(i!=j), NULL ); Iterator1 k; k = j; ASSERT( k==j, NULL ); ASSERT( !(k!=j), NULL ); } template<typename Iterator, typename T> void TestIteratorTraits() { AssertSameType( static_cast<typename Iterator::difference_type*>(0), static_cast<ptrdiff_t*>(0) ); AssertSameType( static_cast<typename Iterator::value_type*>(0), static_cast<T*>(0) ); AssertSameType( static_cast<typename Iterator::pointer*>(0), static_cast<T**>(0) ); AssertSameType( static_cast<typename Iterator::iterator_category*>(0), static_cast<std::<API key>*>(0) ); T x; typename Iterator::reference xr = x; typename Iterator::pointer xp = &x; ASSERT( &xr==xp, NULL ); } //! Test the iterators for concurrent_queue template<typename CQ> void TestIterator() { CQ queue; const CQ& const_queue = queue; for( int j=0; j<500; ++j ) { TestIteratorAux( queue.unsafe_begin() , queue.unsafe_end() , j ); TestIteratorAux( const_queue.unsafe_begin(), const_queue.unsafe_end(), j ); TestIteratorAux( const_queue.unsafe_begin(), queue.unsafe_end() , j ); TestIteratorAux( queue.unsafe_begin() , const_queue.unsafe_end(), j ); Foo f; f.serial = j+1; queue.push(f); } <API key><typename CQ::const_iterator>( const_queue.unsafe_begin() ); <API key><typename CQ::const_iterator>( queue.unsafe_begin() ); <API key><typename CQ::iterator>( queue.unsafe_begin() ); TestIteratorTraits<typename CQ::const_iterator, const Foo>(); TestIteratorTraits<typename CQ::iterator, Foo>(); } template<typename CQ> void <API key>() { AssertSameType( typename CQ::value_type(), Foo() ); Foo f; const Foo g; typename CQ::reference r = f; ASSERT( &r==&f, NULL ); ASSERT( !r.is_const(), NULL ); typename CQ::const_reference cr = g; ASSERT( &cr==&g, NULL ); ASSERT( cr.is_const(), NULL ); } template<typename CQ, typename T> void TestEmptyQueue() { const CQ queue; ASSERT( queue.size()==0, NULL ); ASSERT( queue.capacity()>0, NULL ); ASSERT( size_t(queue.capacity())>=size_t(-1)/(sizeof(void*)+sizeof(T)), NULL ); } template<typename CQ,typename T> void TestFullQueue() { for( int n=0; n<10; ++n ) { T::clear_counters(); CQ queue; queue.set_capacity(n); for( int i=0; i<=n; ++i ) { T f; f.serial = i; bool result = queue.try_push( f ); ASSERT( result==(i<n), NULL ); } for( int i=0; i<=n; ++i ) { T f; bool result = queue.try_pop( f ); ASSERT( result==(i<n), NULL ); ASSERT( !result || f.serial==i, NULL ); } ASSERT( T::get_n_constructed()==T::get_n_destroyed(), NULL ); } } template<typename CQ> void TestClear() { FooConstructed = 0; FooDestroyed = 0; const unsigned int n=5; CQ queue; const int q_capacity=10; queue.set_capacity(q_capacity); for( size_t i=0; i<n; ++i ) { Foo f; f.serial = int(i); queue.push( f ); } ASSERT( unsigned(queue.size())==n, NULL ); queue.clear(); ASSERT( queue.size()==0, NULL ); for( size_t i=0; i<n; ++i ) { Foo f; f.serial = int(i); queue.push( f ); } ASSERT( unsigned(queue.size())==n, NULL ); queue.clear(); ASSERT( queue.size()==0, NULL ); for( size_t i=0; i<n; ++i ) { Foo f; f.serial = int(i); queue.push( f ); } ASSERT( unsigned(queue.size())==n, NULL ); } template<typename T> struct <API key>: NoAssign { tbb::<API key><T>& queue; const int nthread; <API key>( tbb::<API key><T>& q, int n ) : queue(q), nthread(n) {} void operator()( int k ) const { if( k==0 ) { int number_of_pops = nthread-1; // Wait for all pops to pend. while( queue.size()>-number_of_pops ) { __TBB_Yield(); } for( int i=0; ; ++i ) { ASSERT( queue.size()==i-number_of_pops, NULL ); ASSERT( queue.empty()==(queue.size()<=0), NULL ); if( i==number_of_pops ) break; // Satisfy another pop queue.push( T() ); } } else { // Pop item from queue T item; queue.pop(item); } } }; //! Test a queue with a negative size. template<typename T> void TestNegativeQueue( int nthread ) { tbb::<API key><T> queue; NativeParallelFor( nthread, <API key><T>(queue,nthread) ); } #if TBB_USE_EXCEPTIONS template<typename CQ,typename A1,typename A2,typename T> void TestExceptionBody() { enum methods { m_push = 0, m_pop }; REMARK("Testing exception safety\n"); MaxFooCount = 5; // verify 'clear()' on exception; queue's destructor calls its clear() // Do test on queues of two different types at the same time to // catch problem with incorrect sharing between templates. { CQ queue0; tbb::concurrent_queue<int,A1> queue1; for( int i=0; i<2; ++i ) { bool caught = false; try { A2::init_counters(); A2::set_limits(N/2); for( int k=0; k<N; k++ ) { if( i==0 ) push(queue0, T(), i); else queue1.push( k ); } } catch (...) { caught = true; } ASSERT( caught, "call to push should have thrown exception" ); } } REMARK("... queue destruction test passed\n"); try { int n_pushed=0, n_popped=0; for(int t = 0; t <= 1; t++)// exception type -- 0 : from allocator(), 1 : from Foo's constructor { CQ queue_test; for( int m=m_push; m<=m_pop; m++ ) { // concurrent_queue internally rebinds the allocator to one with 'char' A2::init_counters(); if(t) MaxFooCount = MaxFooCount + 400; else A2::set_limits(N/2); try { switch(m) { case m_push: for( int k=0; k<N; k++ ) { push( queue_test, T(), k ); n_pushed++; } break; case m_pop: n_popped=0; for( int k=0; k<n_pushed; k++ ) { T elt; queue_test.try_pop( elt ); n_popped++; } n_pushed = 0; A2::set_limits(); break; } if( !t && m==m_push ) ASSERT(false, "should throw an exception"); } catch ( Foo_exception & ) { switch(m) { case m_push: { ASSERT( ptrdiff_t(queue_test.size())==n_pushed, "incorrect queue size" ); long tc = MaxFooCount; MaxFooCount = 0; for( int k=0; k<(int)tc; k++ ) { push( queue_test, T(), k ); n_pushed++; } MaxFooCount = tc; } break; case m_pop: MaxFooCount = 0; // disable exception n_pushed -= (n_popped+1); // including one that threw an exception ASSERT( n_pushed>=0, "n_pushed cannot be less than 0" ); for( int k=0; k<1000; k++ ) { push( queue_test, T(), k ); n_pushed++; } ASSERT( !queue_test.empty(), "queue must not be empty" ); ASSERT( ptrdiff_t(queue_test.size())==n_pushed, "queue size must be equal to n pushed" ); for( int k=0; k<n_pushed; k++ ) { T elt; queue_test.try_pop( elt ); } ASSERT( queue_test.empty(), "queue must be empty" ); ASSERT( queue_test.size()==0, "queue must be empty" ); break; } } catch ( std::bad_alloc & ) { A2::set_limits(); // disable exception from allocator size_t size = queue_test.size(); switch(m) { case m_push: ASSERT( size>0, "incorrect queue size"); break; case m_pop: if( !t ) ASSERT( false, "should not throw an exceptin" ); break; } } REMARK("... for t=%d and m=%d, exception test passed\n", t, m); } } } catch(...) { ASSERT(false, "unexpected exception"); } } #endif /* TBB_USE_EXCEPTIONS */ void TestExceptions() { #if <API key> REPORT("Known issue: exception safety test is skipped.\n"); #elif TBB_USE_EXCEPTIONS typedef <API key><std::allocator<FooEx>, size_t> allocator_t; typedef <API key><std::allocator<char>, size_t> allocator_char_t; TestExceptionBody<<API key><FooEx, allocator_t>,allocator_t,allocator_char_t,FooEx>(); TestExceptionBody<tbb::<API key><FooEx, allocator_t>,allocator_t,allocator_char_t,FooEx>(); #endif /* TBB_USE_EXCEPTIONS */ } template<typename CQ, typename T> struct TestQueueElements: NoAssign { CQ& queue; const int nthread; TestQueueElements( CQ& q, int n ) : queue(q), nthread(n) {} void operator()( int k ) const { for( int i=0; i<1000; ++i ) { if( (i&0x1)==0 ) { ASSERT( T(k)<T(nthread), NULL ); queue.push( T(k) ); } else { // Pop item from queue T item = 0; queue.try_pop(item); ASSERT( item<=T(nthread), NULL ); } } } }; //! Test concurrent queue with primitive data type template<typename CQ, typename T> void TestPrimitiveTypes( int nthread, T exemplar ) { CQ queue; for( int i=0; i<100; ++i ) queue.push( exemplar ); NativeParallelFor( nthread, TestQueueElements<CQ,T>(queue,nthread) ); } #include "harness_m128.h" #if HAVE_m128 || HAVE_m256 //! Test concurrent queue with vector types /** Type Queue should be a queue of ClassWithSSE/ClassWithAVX. */ template<typename ClassWithVectorType, typename Queue> void TestVectorTypes() { Queue q1; for( int i=0; i<100; ++i ) { // VC8 does not properly align a temporary value; to work around, use explicit variable ClassWithVectorType bar(i); q1.push(bar); } // Copy the queue Queue q2 = q1; // Check that elements of the copy are correct typename Queue::const_iterator ci = q2.unsafe_begin(); for( int i=0; i<100; ++i ) { ClassWithVectorType foo = *ci; ClassWithVectorType bar(i); ASSERT( *ci==bar, NULL ); ++ci; } for( int i=0; i<101; ++i ) { ClassWithVectorType tmp; bool b = q1.try_pop( tmp ); ASSERT( b==(i<100), NULL ); ClassWithVectorType bar(i); ASSERT( !b || tmp==bar, NULL ); } } #endif /* HAVE_m128 || HAVE_m256 */ void TestEmptiness() { REMARK(" Test Emptiness\n"); TestEmptyQueue<ConcQWithCapacity<char>, char>(); TestEmptyQueue<ConcQWithCapacity<Foo>, Foo>(); TestEmptyQueue<tbb::<API key><char>, char>(); TestEmptyQueue<tbb::<API key><Foo>, Foo>(); } void TestFullness() { REMARK(" Test Fullness\n"); TestFullQueue<ConcQWithCapacity<Foo>,Foo>(); TestFullQueue<tbb::<API key><Foo>,Foo>(); } void TestClearWorks() { REMARK(" Test concurrent_queue::clear() works\n"); TestClear<ConcQWithCapacity<Foo> >(); TestClear<tbb::<API key><Foo> >(); } void <API key>() { REMARK(" Test concurrent_queue's types work\n"); <API key><tbb::concurrent_queue<Foo> >(); <API key><tbb::<API key><Foo> >(); } void <API key>() { REMARK(" Test concurrent_queue's iterators work\n"); TestIterator<tbb::concurrent_queue<Foo> >(); TestIterator<tbb::<API key><Foo> >(); } #if TBB_USE_EXCEPTIONS #define BAR_EX BarEx #else #define BAR_EX Empty /* passed as template arg but should not be used */ #endif class Empty; void <API key>() { REMARK(" Test concurrent_queue's constructors work\n"); TestConstructors<<API key><Bar>,Bar,BarIterator,<API key><BAR_EX>,BAR_EX>(); TestConstructors<tbb::<API key><Bar>,Bar,BarIterator,tbb::<API key><BAR_EX>,BAR_EX>(); } void <API key>() { REMARK(" Test concurrent_queue works with primitive types\n"); TestPrimitiveTypes<tbb::concurrent_queue<char>, char>( MaxThread, (char)1 ); TestPrimitiveTypes<tbb::concurrent_queue<int>, int>( MaxThread, (int)-12 ); TestPrimitiveTypes<tbb::concurrent_queue<float>, float>( MaxThread, (float)-1.2f ); TestPrimitiveTypes<tbb::concurrent_queue<double>, double>( MaxThread, (double)-4.3 ); TestPrimitiveTypes<tbb::<API key><char>, char>( MaxThread, (char)1 ); TestPrimitiveTypes<tbb::<API key><int>, int>( MaxThread, (int)-12 ); TestPrimitiveTypes<tbb::<API key><float>, float>( MaxThread, (float)-1.2f ); TestPrimitiveTypes<tbb::<API key><double>, double>( MaxThread, (double)-4.3 ); } void <API key>() { REMARK(" Test concurrent_queue works with SSE data\n"); #if HAVE_m128 TestVectorTypes<ClassWithSSE, tbb::concurrent_queue<ClassWithSSE> >(); TestVectorTypes<ClassWithSSE, tbb::<API key><ClassWithSSE> >(); #endif /* HAVE_m128 */ #if HAVE_m256 if( have_AVX() ) { TestVectorTypes<ClassWithAVX, tbb::concurrent_queue<ClassWithAVX> >(); TestVectorTypes<ClassWithAVX, tbb::<API key><ClassWithAVX> >(); } #endif /* HAVE_m256 */ } void <API key>() { REMARK(" Test concurrent_queue's concurrent push and pop\n"); for( int nthread=MinThread; nthread<=MaxThread; ++nthread ) { REMARK(" Testing with %d thread(s)\n", nthread ); TestNegativeQueue<Foo>(nthread); for( size_t prefill=0; prefill<64; prefill+=(1+prefill/3) ) { TestPushPop<ConcQPushPopWrapper<Foo>,Foo>(prefill,ptrdiff_t(-1),nthread); TestPushPop<ConcQPushPopWrapper<Foo>,Foo>(prefill,ptrdiff_t(1),nthread); TestPushPop<ConcQPushPopWrapper<Foo>,Foo>(prefill,ptrdiff_t(2),nthread); TestPushPop<ConcQPushPopWrapper<Foo>,Foo>(prefill,ptrdiff_t(10),nthread); TestPushPop<ConcQPushPopWrapper<Foo>,Foo>(prefill,ptrdiff_t(100),nthread); } for( size_t prefill=0; prefill<64; prefill+=(1+prefill/3) ) { TestPushPop<tbb::<API key><Foo>,Foo>(prefill,ptrdiff_t(-1),nthread); TestPushPop<tbb::<API key><Foo>,Foo>(prefill,ptrdiff_t(1),nthread); TestPushPop<tbb::<API key><Foo>,Foo>(prefill,ptrdiff_t(2),nthread); TestPushPop<tbb::<API key><Foo>,Foo>(prefill,ptrdiff_t(10),nthread); TestPushPop<tbb::<API key><Foo>,Foo>(prefill,ptrdiff_t(100),nthread); } } } #if TBB_USE_EXCEPTIONS tbb::atomic<size_t> num_pushed; tbb::atomic<size_t> num_popped; tbb::atomic<size_t> failed_pushes; tbb::atomic<size_t> failed_pops; class SimplePushBody { tbb::<API key><int>* q; int max; public: SimplePushBody(tbb::<API key><int>* _q, int hi_thr) : q(_q), max(hi_thr) {} void operator()(int thread_id) const { if (thread_id == max) { Harness::Sleep(50); q->abort(); return; } try { q->push(42); ++num_pushed; } catch ( tbb::user_abort& ) { ++failed_pushes; } } }; class SimplePopBody { tbb::<API key><int>* q; int max; public: SimplePopBody(tbb::<API key><int>* _q, int hi_thr) : q(_q), max(hi_thr) {} void operator()(int thread_id) const { int e; if (thread_id == max) { Harness::Sleep(50); q->abort(); return; } try { q->pop(e); ++num_popped; } catch ( tbb::user_abort& ) { ++failed_pops; } } }; #endif /* TBB_USE_EXCEPTIONS */ void TestAbort() { #if TBB_USE_EXCEPTIONS for (int nthreads=MinThread; nthreads<=MaxThread; ++nthreads) { REMARK("Testing Abort on %d thread(s).\n", nthreads); REMARK("...testing pushing to zero-sized queue\n"); tbb::<API key><int> iq1; iq1.set_capacity(0); for (int i=0; i<10; ++i) { num_pushed = num_popped = failed_pushes = failed_pops = 0; SimplePushBody my_push_body1(&iq1, nthreads); NativeParallelFor( nthreads+1, my_push_body1 ); ASSERT(num_pushed == 0, "no elements should have been pushed to zero-sized queue"); ASSERT((int)failed_pushes == nthreads, "All threads should have failed to push an element to zero-sized queue"); } REMARK("...testing pushing to small-sized queue\n"); tbb::<API key><int> iq2; iq2.set_capacity(2); for (int i=0; i<10; ++i) { num_pushed = num_popped = failed_pushes = failed_pops = 0; SimplePushBody my_push_body2(&iq2, nthreads); NativeParallelFor( nthreads+1, my_push_body2 ); ASSERT(num_pushed <= 2, "at most 2 elements should have been pushed to queue of size 2"); if (nthreads >= 2) ASSERT((int)failed_pushes == nthreads-2, "nthreads-2 threads should have failed to push an element to queue of size 2"); int e; while (iq2.try_pop(e)) ; } REMARK("...testing popping from small-sized queue\n"); tbb::<API key><int> iq3; iq3.set_capacity(2); for (int i=0; i<10; ++i) { num_pushed = num_popped = failed_pushes = failed_pops = 0; iq3.push(42); iq3.push(42); SimplePopBody my_pop_body(&iq3, nthreads); NativeParallelFor( nthreads+1, my_pop_body); ASSERT(num_popped <= 2, "at most 2 elements should have been popped from queue of size 2"); if (nthreads >= 2) ASSERT((int)failed_pops == nthreads-2, "nthreads-2 threads should have failed to pop an element from queue of size 2"); else { int e; iq3.pop(e); } } REMARK("...testing pushing and popping from small-sized queue\n"); tbb::<API key><int> iq4; int cap = nthreads/2; if (!cap) cap=1; iq4.set_capacity(cap); for (int i=0; i<10; ++i) { num_pushed = num_popped = failed_pushes = failed_pops = 0; SimplePushBody my_push_body2(&iq4, nthreads); NativeParallelFor( nthreads+1, my_push_body2 ); ASSERT((int)num_pushed <= cap, "at most cap elements should have been pushed to queue of size cap"); if (nthreads >= cap) ASSERT((int)failed_pushes == nthreads-cap, "nthreads-cap threads should have failed to push an element to queue of size cap"); SimplePopBody my_pop_body(&iq4, nthreads); NativeParallelFor( nthreads+1, my_pop_body); ASSERT((int)num_popped <= cap, "at most cap elements should have been popped from queue of size cap"); if (nthreads >= cap) ASSERT((int)failed_pops == nthreads-cap, "nthreads-cap threads should have failed to pop an element from queue of size cap"); else { int e; while (iq4.try_pop(e)) ; } } } #endif } #if <API key> struct <API key> { static size_t <API key>; static size_t <API key>; static size_t <API key>; static size_t <API key>; <API key>() {} <API key>(const <API key>&) { ++<API key>; } <API key>(<API key>&&) { ++<API key>; } <API key>& operator=(<API key> const&) { ++<API key>; return *this; } <API key>& operator=(<API key>&&) { ++<API key>; return *this; } }; size_t <API key>::<API key> = 0; size_t <API key>::<API key> = 0; size_t <API key>::<API key> = 0; size_t <API key>::<API key> = 0; template <class CQ, push_t push_op, pop_t pop_op> void TestMoveSupport() { size_t &mcct = <API key>::<API key>; size_t &ccct = <API key>::<API key>; size_t &cact = <API key>::<API key>; size_t &mact = <API key>::<API key>; mcct = ccct = cact = mact = 0; CQ q; ASSERT(mcct == 0, "Value must be zero-initialized"); ASSERT(ccct == 0, "Value must be zero-initialized"); ASSERT(pusher<push_op>::push( q, <API key>() ), NULL); ASSERT(mcct == 1, "Not working push(T&&) or try_push(T&&)?"); ASSERT(ccct == 0, "Copying of arg occurred during push(T&&) or try_push(T&&)"); <API key> ob; ASSERT(pusher<push_op>::push( q, std::move(ob) ), NULL); ASSERT(mcct == 2, "Not working push(T&&) or try_push(T&&)?"); ASSERT(ccct == 0, "Copying of arg occurred during push(T&&) or try_push(T&&)"); ASSERT(cact == 0, "Copy assignment called during push(T&&) or try_push(T&&)"); ASSERT(mact == 0, "Move assignment called during push(T&&) or try_push(T&&)"); bool result = popper<pop_op>::pop( q, ob ); ASSERT(result, NULL); ASSERT(cact == 0, "Copy assignment called during try_pop(T&&)"); ASSERT(mact == 1, "Move assignment was not called during try_pop(T&&)"); } void <API key>() { REMARK("Testing Move Support in Push/Pop..."); TestMoveSupport< tbb::concurrent_queue<<API key>>, push_op, try_pop_op >(); TestMoveSupport< tbb::<API key><<API key>>, push_op, pop_op >(); TestMoveSupport< tbb::<API key><<API key>>, try_push_op, try_pop_op >(); REMARK(" works.\n"); } #if <API key> class <API key> { public: <API key>( int a = 0 ) : m_a( a ), m_str( "" ) {} <API key>( const std::string& str ) : m_a( 0 ), m_str( str ) {} <API key>( int a, const std::string& str ) : m_a( a ), m_str( str ) {} int get_a() const { return m_a; } std::string get_str() const { return m_str; } private: int m_a; std::string m_str; }; enum emplace_t { emplace_op, try_emplace_op }; template< emplace_t emplace_op > struct emplacer { template< typename CQ, typename... Args> static void emplace( CQ& queue, Args&&... val ) { queue.emplace( std::forward<Args>( val )... ); } }; template<> struct emplacer< try_emplace_op > { template<typename CQ, typename... Args> static void emplace( CQ& queue, Args&&... val ) { bool result = queue.try_emplace( std::forward<Args>( val )... ); ASSERT( result, "try_emplace error\n" ); } }; template<typename CQ, emplace_t emplace_op> void TestEmplaceInQueue() { CQ cq; std::string test_str = "I'm being emplaced!"; { emplacer<emplace_op>::emplace( cq, 5 ); ASSERT( cq.size() == 1, NULL ); <API key> popped( -1 ); bool result = cq.try_pop( popped ); ASSERT( result, NULL ); ASSERT( popped.get_a() == 5, NULL ); ASSERT( popped.get_str() == std::string( "" ), NULL ); } ASSERT( cq.empty(), NULL ); { <API key> popped( -1 ); emplacer<emplace_op>::emplace( cq, std::string(test_str) ); bool result = cq.try_pop( popped ); ASSERT( result, NULL ); ASSERT( popped.get_a() == 0, NULL ); ASSERT( popped.get_str() == test_str, NULL ); } ASSERT( cq.empty(), NULL ); { <API key> popped( -1, "" ); emplacer<emplace_op>::emplace( cq, 5, std::string(test_str) ); bool result = cq.try_pop( popped ); ASSERT( result, NULL ); ASSERT( popped.get_a() == 5, NULL ); ASSERT( popped.get_str() == test_str, NULL ); } } void TestEmplace() { REMARK("Testing support for 'emplace' method..."); TestEmplaceInQueue< <API key><<API key>>, emplace_op >(); TestEmplaceInQueue< tbb::<API key><<API key>>, emplace_op >(); TestEmplaceInQueue< tbb::<API key><<API key>>, try_emplace_op >(); REMARK(" works.\n"); } #endif /* <API key> */ #endif /* <API key> */ template <typename Queue> void Examine(Queue q, const std::vector<typename Queue::value_type> &vec) { typedef typename Queue::value_type value_type; AssertEquality(q, vec); const Queue cq = q; AssertEquality(cq, vec); q.clear(); AssertEmptiness(q); FillTest<push_op>(q, vec); EmptyTest<try_pop_op>(q, vec); <API key>(q, vec); typename Queue::allocator_type a = q.get_allocator(); value_type *ptr = a.allocate(1); ASSERT(ptr, NULL); a.deallocate(ptr, 1); } template <typename Queue, typename QueueDebugAlloc> void TypeTester(const std::vector<typename Queue::value_type> &vec) { typedef typename std::vector<typename Queue::value_type>::const_iterator iterator; ASSERT(vec.size() >= 5, "Array should have at least 5 elements"); // Construct an empty queue. Queue q1; for (iterator it = vec.begin(); it != vec.end(); ++it) q1.push(*it); Examine(q1, vec); // Copying constructor. Queue q3(q1); Examine(q3, vec); // Construct with non-default allocator. QueueDebugAlloc q4; for (iterator it = vec.begin(); it != vec.end(); ++it) q4.push(*it); Examine(q4, vec); // Copying constructor with the same allocator type. QueueDebugAlloc q5(q4); Examine(q5, vec); // Construction with given allocator instance. typename QueueDebugAlloc::allocator_type a; QueueDebugAlloc q6(a); for (iterator it = vec.begin(); it != vec.end(); ++it) q6.push(*it); Examine(q6, vec); // Construction with copying iteration range and given allocator instance. QueueDebugAlloc q7(q1.unsafe_begin(), q1.unsafe_end(), a); Examine<QueueDebugAlloc>(q7, vec); } template <typename value_type> void TestTypes(const std::vector<value_type> &vec) { TypeTester< <API key><value_type>, <API key><value_type, debug_allocator<value_type> > >(vec); TypeTester< tbb::<API key><value_type>, tbb::<API key><value_type, debug_allocator<value_type> > >(vec); } void TestTypes() { const int NUMBER = 10; std::vector<int> arrInt; for (int i = 0; i < NUMBER; ++i) arrInt.push_back(i); std::vector< tbb::atomic<int> > arrTbb; for (int i = 0; i < NUMBER; ++i) { tbb::atomic<int> a; a = i; arrTbb.push_back(a); } TestTypes(arrInt); TestTypes(arrTbb); #if <API key> std::vector< std::shared_ptr<int> > arrShr; for (int i = 0; i < NUMBER; ++i) arrShr.push_back(std::make_shared<int>(i)); std::vector< std::weak_ptr<int> > arrWk; std::copy(arrShr.begin(), arrShr.end(), std::back_inserter(arrWk)); TestTypes(arrShr); TestTypes(arrWk); #else REPORT("Known issue: C++11 smart pointer tests are skipped.\n"); #endif /* <API key> */ } int TestMain () { TestEmptiness(); TestFullness(); TestClearWorks(); <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); // Test concurrent operations <API key>(); TestExceptions(); TestAbort(); #if <API key> <API key>(); <API key>(); #if <API key> TestEmplace(); #endif /* <API key> */ #endif /* <API key> */ TestTypes(); return Harness::Done; }
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.CosmosDB.Models { using Newtonsoft.Json; using System.Linq; <summary> The access keys for the given database account. </summary> public partial class <API key> : <API key> { <summary> Initializes a new instance of the <API key> class. </summary> public <API key>() { CustomInit(); } <summary> Initializes a new instance of the <API key> class. </summary> <param name="<API key>">Base 64 encoded value of the primary read-only key.</param> <param name="<API key>">Base 64 encoded value of the secondary read-only key.</param> <param name="primaryMasterKey">Base 64 encoded value of the primary read-write key.</param> <param name="secondaryMasterKey">Base 64 encoded value of the secondary read-write key.</param> public <API key>(string <API key> = default(string), string <API key> = default(string), string primaryMasterKey = default(string), string secondaryMasterKey = default(string)) : base(<API key>, <API key>) { PrimaryMasterKey = primaryMasterKey; SecondaryMasterKey = secondaryMasterKey; CustomInit(); } <summary> An initialization method that performs custom operations like setting defaults </summary> partial void CustomInit(); <summary> Gets base 64 encoded value of the primary read-write key. </summary> [JsonProperty(PropertyName = "primaryMasterKey")] public string PrimaryMasterKey { get; private set; } <summary> Gets base 64 encoded value of the secondary read-write key. </summary> [JsonProperty(PropertyName = "secondaryMasterKey")] public string SecondaryMasterKey { get; private set; } } }
#include <assert.h> #include <string.h> #include "py/nlr.h" #include "py/runtime.h" #if MICROPY_PY_UHASHLIB #include "crypto-algorithms/sha256.h" #if <API key> #include "lib/axtls/crypto/crypto.h" #endif typedef struct _mp_obj_hash_t { mp_obj_base_t base; char state[0]; } mp_obj_hash_t; STATIC mp_obj_t hash_update(mp_obj_t self_in, mp_obj_t arg); STATIC mp_obj_t hash_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(CRYAL_SHA256_CTX)); o->base.type = type; sha256_init((CRYAL_SHA256_CTX*)o->state); if (n_args == 1) { hash_update(MP_OBJ_FROM_PTR(o), args[0]); } return MP_OBJ_FROM_PTR(o); } #if <API key> STATIC mp_obj_t sha1_update(mp_obj_t self_in, mp_obj_t arg); STATIC mp_obj_t sha1_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(SHA1_CTX)); o->base.type = type; SHA1_Init((SHA1_CTX*)o->state); if (n_args == 1) { sha1_update(MP_OBJ_FROM_PTR(o), args[0]); } return MP_OBJ_FROM_PTR(o); } #endif STATIC mp_obj_t hash_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); sha256_update((CRYAL_SHA256_CTX*)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } <API key>(hash_update_obj, hash_update); #if <API key> STATIC mp_obj_t sha1_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); SHA1_Update((SHA1_CTX*)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } <API key>(sha1_update_obj, sha1_update); #endif STATIC mp_obj_t hash_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, SHA256_BLOCK_SIZE); sha256_final((CRYAL_SHA256_CTX*)self->state, (byte*)vstr.buf); return <API key>(&mp_type_bytes, &vstr); } <API key>(hash_digest_obj, hash_digest); #if <API key> STATIC mp_obj_t sha1_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, SHA1_SIZE); SHA1_Final((byte*)vstr.buf, (SHA1_CTX*)self->state); return <API key>(&mp_type_bytes, &vstr); } <API key>(sha1_digest_obj, sha1_digest); #endif STATIC const mp_rom_map_elem_t <API key>[] = { { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&hash_update_obj) }, { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&hash_digest_obj) }, }; STATIC <API key>(hash_locals_dict, <API key>); STATIC const mp_obj_type_t sha256_type = { { &mp_type_type }, .name = MP_QSTR_sha256, .make_new = hash_make_new, .locals_dict = (void*)&hash_locals_dict, }; #if <API key> STATIC const mp_rom_map_elem_t <API key>[] = { { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&sha1_update_obj) }, { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&sha1_digest_obj) }, }; STATIC <API key>(sha1_locals_dict, <API key>); STATIC const mp_obj_type_t sha1_type = { { &mp_type_type }, .name = MP_QSTR_sha1, .make_new = sha1_make_new, .locals_dict = (void*)&sha1_locals_dict, }; #endif STATIC const mp_rom_map_elem_t <API key>[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uhashlib) }, { MP_ROM_QSTR(MP_QSTR_sha256), MP_ROM_PTR(&sha256_type) }, #if <API key> { MP_ROM_QSTR(MP_QSTR_sha1), MP_ROM_PTR(&sha1_type) }, #endif }; STATIC <API key>(<API key>, <API key>); const mp_obj_module_t mp_module_uhashlib = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t*)&<API key>, }; #include "crypto-algorithms/sha256.c" #endif //MICROPY_PY_UHASHLIB
// NSString+XHLaunchAd.h // XHLaunchAdExample #import <Foundation/Foundation.h> @interface NSString (XHLaunchAd) @property(nonatomic,assign,readonly)BOOL xh_isURLString; @property(nonatomic,copy,readonly,nonnull)NSString *xh_videoName; @property(nonatomic,copy,readonly,nonnull)NSString *xh_md5String; -(BOOL)<API key>:(nonnull NSString *)subString; @end
package net import ( "io" ) const ( bufferSize = 4 * 1024 ) // ReaderToChan dumps all content from a given reader to a chan by constantly reading it until EOF. func ReaderToChan(stream chan<- []byte, reader io.Reader) error { for { buffer := make([]byte, bufferSize) nBytes, err := reader.Read(buffer) if nBytes > 0 { stream <- buffer[:nBytes] } if err != nil { return err } } } // ChanToWriter dumps all content from a given chan to a writer until the chan is closed. func ChanToWriter(writer io.Writer, stream <-chan []byte) error { for buffer := range stream { _, err := writer.Write(buffer) if err != nil { return err } } return nil }
{{<div}} {{$div}} {{>template}} {{/div}} {{/div}}
using System; using System.Collections.Generic; namespace Orleans.Providers.Streams.Common { <summary> Object pool that roughly ensures only a specified number of the objects are allowed to be allocated. When more objects are allocated then is specified, previously allocated objects will be signaled to be purged in order. When objects are signaled, they should be returned to the pool. How this is done is an implementation detail of the object. </summary> <typeparam name="T"></typeparam> public class FixedSizeObjectPool<T> : ObjectPool<T> where T : PooledResource<T> { private const int MinObjectCount = 3; // 1MB <summary> Queue of objects that have been allocated and are currently in use. Tracking these is necessary for keeping a fixed size. These are used to reclaim allocated resources by signaling purges which should eventually return the resource to the pool. Protected for test reasons </summary> protected readonly Queue<T> usedObjects = new Queue<T>(); private readonly object locker = new object(); private readonly int maxObjectCount; <summary> Manages a memory pool of poolSize blocks. Whenever we've allocated more blocks than the poolSize, we signal the oldest allocated block to purge itself and return to the pool. </summary> <param name="poolSize"></param> <param name="factoryFunc"></param> public FixedSizeObjectPool(int poolSize, Func<T> factoryFunc) : base(factoryFunc, poolSize) { if (poolSize < MinObjectCount) { throw new <API key>("poolSize", "Minimum object count is " + MinObjectCount); } maxObjectCount = poolSize; } <summary> Allocates a resource from the pool. </summary> <returns></returns> public override T Allocate() { T obj; lock (locker) { // if we've used all we are allowed, signal object it has been purged and should be returned to the pool if (usedObjects.Count >= maxObjectCount) { usedObjects.Dequeue().SignalPurge(); } obj = base.Allocate(); // track used objects usedObjects.Enqueue(obj); } return obj; } <summary> Returns a resource to the pool to be reused </summary> <param name="resource"></param> public override void Free(T resource) { lock (locker) { base.Free(resource); } } } }
'use strict'; var BigNumber = require('../../type/BigNumber'); var Range = require('../../type/Range'); var Index = require('../../type/Index'); var isNumber = require('../../util/number').isNumber; /** * Attach a transform function to math.index * Adds a property transform containing the transform function. * * This transform creates a one-based index instead of a zero-based index * @param {Object} math */ module.exports = function (math) { var transform = function () { var args = []; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; // change from one-based to zero based, and convert BigNumber to number if (arg instanceof Range) { arg.start arg.end -= (arg.step > 0 ? 0 : 2); } else if (isNumber(arg)) { arg } else if (arg instanceof BigNumber) { arg = arg.toNumber() - 1; } else { throw new TypeError('Ranges must be a Number or Range'); } args[i] = arg; } var res = new Index(); Index.apply(res, args); return res; }; math.index.transform = transform; return transform; };
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Security.Models { using Newtonsoft.Json; using System.Linq; public partial class <API key> { <summary> Initializes a new instance of the <API key> class. </summary> public <API key>() { CustomInit(); } <summary> Initializes a new instance of the <API key> class. </summary> <param name="date">Aggregation of IoT Security solution device alert metrics by date.</param> <param name="devicesMetrics">Device alert count by severity.</param> public <API key>(System.DateTime? date = default(System.DateTime?), IoTSeverityMetrics devicesMetrics = default(IoTSeverityMetrics)) { Date = date; DevicesMetrics = devicesMetrics; CustomInit(); } <summary> An initialization method that performs custom operations like setting defaults </summary> partial void CustomInit(); <summary> Gets or sets aggregation of IoT Security solution device alert metrics by date. </summary> [JsonProperty(PropertyName = "date")] public System.DateTime? Date { get; set; } <summary> Gets or sets device alert count by severity. </summary> [JsonProperty(PropertyName = "devicesMetrics")] public IoTSeverityMetrics DevicesMetrics { get; set; } } }
package com.greenlemonmobile.app.ebook.books.imagezoom.graphics; import android.graphics.Bitmap; /** * Base interface used in the {@link ImageViewTouchBase} view * @author alessandro * */ public interface IBitmapDrawable { Bitmap getBitmap(); }
// This file is part of OpenCV project. #ifndef <API key> #define <API key> #include "../cvdef.h" namespace cv { namespace utils { class <API key> { protected: <API key>() {} virtual ~<API key>() {} public: virtual uint64_t getCurrentUsage() const = 0; virtual uint64_t getTotalUsage() const = 0; virtual uint64_t <API key>() const = 0; virtual uint64_t getPeakUsage() const = 0; /** set peak usage = current usage */ virtual void resetPeakUsage() = 0; }; }} // namespace #endif // <API key>
define("ace/snippets/typescript",["require","exports","module"],function(e,t,n){"use strict";t.snippetText="",t.scope="typescript"}); (function() { window.require(["ace/snippets/typescript"], function(m) { if (typeof module == "object") { module.exports = m; } }); })();
package fixtures.azurespecials.implementation; import com.microsoft.azure.AzureClient; import com.microsoft.azure.AzureServiceClient; import com.microsoft.azure.RestClient; import com.microsoft.rest.credentials.<API key>; import fixtures.azurespecials.ApiVersionDefaults; import fixtures.azurespecials.ApiVersionLocals; import fixtures.azurespecials.<API key>; import fixtures.azurespecials.Headers; import fixtures.azurespecials.Odatas; import fixtures.azurespecials.SkipUrlEncodings; import fixtures.azurespecials.<API key>; import fixtures.azurespecials.<API key>; import fixtures.azurespecials.XMsClientRequestIds; /** * Initializes a new instance of the <API key> class. */ public final class <API key> extends AzureServiceClient implements <API key> { /** the {@link AzureClient} used for long running operations. */ private AzureClient azureClient; /** * Gets the {@link AzureClient} used for long running operations. * @return the azure client; */ public AzureClient getAzureClient() { return this.azureClient; } /** The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. */ private String subscriptionId; /** * Gets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. * * @return the subscriptionId value. */ public String subscriptionId() { return this.subscriptionId; } /** * Sets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. * * @param subscriptionId the subscriptionId value. * @return the service client itself */ public <API key> withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /** The api version, which appears in the query, the value is always '2015-07-01-preview'. */ private String apiVersion; /** * Gets The api version, which appears in the query, the value is always '2015-07-01-preview'. * * @return the apiVersion value. */ public String apiVersion() { return this.apiVersion; } /** Gets or sets the preferred language for the response. */ private String acceptLanguage; /** * Gets Gets or sets the preferred language for the response. * * @return the acceptLanguage value. */ public String acceptLanguage() { return this.acceptLanguage; } /** * Sets Gets or sets the preferred language for the response. * * @param acceptLanguage the acceptLanguage value. * @return the service client itself */ public <API key> withAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; return this; } /** Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. */ private int <API key>; /** * Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @return the <API key> value. */ public int <API key>() { return this.<API key>; } /** * Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @param <API key> the <API key> value. * @return the service client itself */ public <API key> <API key>(int <API key>) { this.<API key> = <API key>; return this; } /** When set to true a unique <API key> value is generated and included in each request. Default is true. */ private boolean <API key>; /** * Gets When set to true a unique <API key> value is generated and included in each request. Default is true. * * @return the <API key> value. */ public boolean <API key>() { return this.<API key>; } /** * Sets When set to true a unique <API key> value is generated and included in each request. Default is true. * * @param <API key> the <API key> value. * @return the service client itself */ public <API key> <API key>(boolean <API key>) { this.<API key> = <API key>; return this; } /** * The XMsClientRequestIds object to access its operations. */ private XMsClientRequestIds xMsClientRequestIds; /** * Gets the XMsClientRequestIds object to access its operations. * @return the XMsClientRequestIds object. */ public XMsClientRequestIds xMsClientRequestIds() { return this.xMsClientRequestIds; } /** * The <API key> object to access its operations. */ private <API key> <API key>; /** * Gets the <API key> object to access its operations. * @return the <API key> object. */ public <API key> <API key>() { return this.<API key>; } /** * The <API key> object to access its operations. */ private <API key> <API key>; /** * Gets the <API key> object to access its operations. * @return the <API key> object. */ public <API key> <API key>() { return this.<API key>; } /** * The ApiVersionDefaults object to access its operations. */ private ApiVersionDefaults apiVersionDefaults; /** * Gets the ApiVersionDefaults object to access its operations. * @return the ApiVersionDefaults object. */ public ApiVersionDefaults apiVersionDefaults() { return this.apiVersionDefaults; } /** * The ApiVersionLocals object to access its operations. */ private ApiVersionLocals apiVersionLocals; /** * Gets the ApiVersionLocals object to access its operations. * @return the ApiVersionLocals object. */ public ApiVersionLocals apiVersionLocals() { return this.apiVersionLocals; } /** * The SkipUrlEncodings object to access its operations. */ private SkipUrlEncodings skipUrlEncodings; /** * Gets the SkipUrlEncodings object to access its operations. * @return the SkipUrlEncodings object. */ public SkipUrlEncodings skipUrlEncodings() { return this.skipUrlEncodings; } /** * The Odatas object to access its operations. */ private Odatas odatas; /** * Gets the Odatas object to access its operations. * @return the Odatas object. */ public Odatas odatas() { return this.odatas; } /** * The Headers object to access its operations. */ private Headers headers; /** * Gets the Headers object to access its operations. * @return the Headers object. */ public Headers headers() { return this.headers; } /** * Initializes an instance of <API key> client. * * @param credentials the management credentials for Azure */ public <API key>(<API key> credentials) { this("http://localhost", credentials); } /** * Initializes an instance of <API key> client. * * @param baseUrl the base URL of the host * @param credentials the management credentials for Azure */ public <API key>(String baseUrl, <API key> credentials) { this(new RestClient.Builder() .withBaseUrl(baseUrl) .withCredentials(credentials) .build()); } /** * Initializes an instance of <API key> client. * * @param restClient the REST client to connect to Azure. */ public <API key>(RestClient restClient) { super(restClient); initialize(); } protected void initialize() { this.apiVersion = "2015-07-01-preview"; this.acceptLanguage = "en-US"; this.<API key> = 30; this.<API key> = true; this.xMsClientRequestIds = new <API key>(restClient().retrofit(), this); this.<API key> = new <API key>(restClient().retrofit(), this); this.<API key> = new <API key>(restClient().retrofit(), this); this.apiVersionDefaults = new <API key>(restClient().retrofit(), this); this.apiVersionLocals = new <API key>(restClient().retrofit(), this); this.skipUrlEncodings = new <API key>(restClient().retrofit(), this); this.odatas = new OdatasImpl(restClient().retrofit(), this); this.headers = new HeadersImpl(restClient().retrofit(), this); this.azureClient = new AzureClient(this); } /** * Gets the User-Agent header for the client. * * @return the user agent string. */ @Override public String userAgent() { return String.format("Azure-SDK-For-Java/%s (%s)", getClass().getPackage().<API key>(), "<API key>, 2015-07-01-preview"); } }
package org.jabref.benchmarks; import java.io.IOException; import java.io.StringReader; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import org.jabref.Globals; import org.jabref.logic.exporter.<API key>; import org.jabref.logic.exporter.SavePreferences; import org.jabref.logic.exporter.StringSaveSession; import org.jabref.logic.formatter.bibtexfields.<API key>; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.layout.format.HTMLChars; import org.jabref.logic.layout.format.<API key>; import org.jabref.logic.search.SearchQuery; import org.jabref.model.Defaults; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.database.<API key>; import org.jabref.model.entry.BibEntry; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.groups.KeywordGroup; import org.jabref.model.groups.WordKeywordGroup; import org.jabref.model.metadata.MetaData; import org.jabref.preferences.JabRefPreferences; import org.openjdk.jmh.Main; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.RunnerException; @State(Scope.Thread) public class Benchmarks { private String bibtexString; private final BibDatabase database = new BibDatabase(); private String <API key>; private String <API key>; @Setup public void init() throws Exception { Globals.prefs = JabRefPreferences.getInstance(); Random randomizer = new Random(); for (int i = 0; i < 1000; i++) { BibEntry entry = new BibEntry(); entry.setCiteKey("id" + i); entry.setField("title", "This is my title " + i); entry.setField("author", "Firstname Lastname and FirstnameA LastnameA and FirstnameB LastnameB" + i); entry.setField("journal", "Journal Title " + i); entry.setField("keyword", "testkeyword"); entry.setField("year", "1" + i); entry.setField("rnd", "2" + randomizer.nextInt()); database.insertEntry(entry); } <API key><StringSaveSession> databaseWriter = new <API key><>(StringSaveSession::new); StringSaveSession saveSession = databaseWriter.savePartOfDatabase( new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(), new SavePreferences()); bibtexString = saveSession.getStringValue(); <API key> = "{A} \\textbf{bold} approach {\\it to} ${{\\Sigma}}{\\Delta}$ modulator \\textsuperscript{2} \\$"; <API key> = "<b>&Ouml;sterreich</b> &#8211; &amp; characters &#x2aa2; <i>italic</i>"; } @Benchmark public ParserResult parse() throws IOException { BibtexParser parser = new BibtexParser(Globals.prefs.<API key>()); return parser.parse(new StringReader(bibtexString)); } @Benchmark public String write() throws Exception { <API key><StringSaveSession> databaseWriter = new <API key><>(StringSaveSession::new); StringSaveSession saveSession = databaseWriter.savePartOfDatabase( new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(), new SavePreferences()); return saveSession.getStringValue(); } @Benchmark public List<BibEntry> search() { // FIXME: Reuse SearchWorker here SearchQuery searchQuery = new SearchQuery("Journal Title 500", false, false); return database.getEntries().stream().filter(searchQuery::isMatch).collect(Collectors.toList()); } @Benchmark public List<BibEntry> parallelSearch() { // FIXME: Reuse SearchWorker here SearchQuery searchQuery = new SearchQuery("Journal Title 500", false, false); return database.getEntries().parallelStream().filter(searchQuery::isMatch).collect(Collectors.toList()); } @Benchmark public BibDatabaseMode <API key>() { return <API key>.inferMode(database); } @Benchmark public String <API key>() { <API key> f = new <API key>(); return f.format(<API key>); } @Benchmark public String <API key>() { HTMLChars f = new HTMLChars(); return f.format(<API key>); } @Benchmark public String <API key>() { <API key> f = new <API key>(); return f.format(<API key>); } @Benchmark public boolean <API key>() throws ParseException { KeywordGroup group = new WordKeywordGroup("testGroup", GroupHierarchyType.INDEPENDENT, "keyword", "testkeyword", false, ',', false); return group.containsAll(database.getEntries()); } public static void main(String[] args) throws IOException, RunnerException { Main.main(args); } }
<?php namespace Sylius\Component\Order\Model; use Doctrine\Common\Collections\Collection; use Sylius\Component\Resource\Model\<API key>; use Sylius\Component\Resource\Model\<API key>; use Sylius\Component\Sequence\Model\<API key>; interface OrderInterface extends AdjustableInterface, <API key>, <API key>, <API key> { const STATE_CART = 'cart'; const STATE_CART_LOCKED = 'cart_locked'; const STATE_PENDING = 'pending'; const STATE_CONFIRMED = 'confirmed'; const STATE_SHIPPED = 'shipped'; const STATE_ABANDONED = 'abandoned'; const STATE_CANCELLED = 'cancelled'; const STATE_RETURNED = 'returned'; /** * Has the order been completed by user and can be handled. * * @return Boolean */ public function isCompleted(); /** * Mark the order as completed. */ public function complete(); /** * Return completion date. * * @return \DateTime */ public function getCompletedAt(); /** * Set completion time. * * @param null|\DateTime $completedAt */ public function setCompletedAt(\DateTime $completedAt = null); /** * Get order items. * * @return Collection|OrderItemInterface[] An array or collection of OrderItemInterface */ public function getItems(); /** * Set items. * * @param Collection|OrderItemInterface[] $items */ public function setItems(Collection $items); /** * Returns number of order items. * * @return integer */ public function countItems(); /** * Adds item to order. * * @param OrderItemInterface $item */ public function addItem(OrderItemInterface $item); /** * Remove item from order. * * @param OrderItemInterface $item */ public function removeItem(OrderItemInterface $item); /** * Has item in order? * * @param OrderItemInterface $item * * @return Boolean */ public function hasItem(OrderItemInterface $item); /** * Get items total. * * @return integer */ public function getItemsTotal(); /** * Calculate items total based on the items * unit prices and quantities. */ public function calculateItemsTotal(); /** * Get order total. * * @return integer */ public function getTotal(); /** * Set total. * * @param integer $total */ public function setTotal($total); /** * Calculate total. * Items total + Adjustments total. */ public function calculateTotal(); /** * Alias of {@link countItems()}. * * @deprecated To be removed in 1.0. Use {@link countItems()} instead. */ public function getTotalItems(); /** * Returns total quantity of items in cart. * * @return integer */ public function getTotalQuantity(); /** * Checks whether the cart is empty or not. * * @return Boolean */ public function isEmpty(); /** * Clears all items in cart. */ public function clearItems(); /** * Get order state. * * @return string */ public function getState(); /** * Set order state. * * @param string $state */ public function setState($state); }
<?php namespace Assetic\Test\Filter; use Assetic\Asset\FileAsset; use Assetic\Filter\UglifyJs2Filter; use Symfony\Component\Process\ProcessBuilder; /** * @group integration */ class UglifyJs2FilterTest extends FilterTestCase { private $asset; private $filter; protected function setUp() { $uglifyjsBin = $this->findExecutable('uglifyjs', 'UGLIFYJS2_BIN'); $nodeBin = $this->findExecutable('node', 'NODE_BIN'); if (!$uglifyjsBin) { $this->markTestSkipped('Unable to find `uglifyjs` executable.'); } // verify uglifyjs version $pb = new ProcessBuilder($nodeBin ? array($nodeBin, $uglifyjsBin) : array($uglifyjsBin)); $pb->add('--version'); if (isset($_SERVER['NODE_PATH'])) { $pb->setEnv('NODE_PATH', $_SERVER['NODE_PATH']); } if (0 !== $pb->getProcess()->run()) { $this->markTestSkipped('Incorrect version of UglifyJs'); } $this->asset = new FileAsset(__DIR__.'/fixtures/uglifyjs/script.js'); $this->asset->load(); $this->filter = new UglifyJs2Filter($uglifyjsBin, $nodeBin); } protected function tearDown() { $this->asset = null; $this->filter = null; } public function testUglify() { $this->filter->filterDump($this->asset); $this->assertContains('function', $this->asset->getContent());
<?php namespace PayPal\Common; class PPReflectionUtil { /** * @var array|ReflectionMethod[] */ private static $propertiesRefl = array(); /** * @var array|string[] */ private static $propertiesType = array(); /** * * @param string $class * @param string $propertyName */ public static function getPropertyClass($class, $propertyName) { if (($annotations = self::propertyAnnotations($class, $propertyName)) && isset($annotations['return'])) { // $param = substr($annotations['param'], 0, -2); $param = $annotations['return']; } if(isset($param)) { $anno = explode(' ', $param); return $anno[0]; } else { return 'string'; } } /** * @param string $class * @param string $propertyName * @throws RuntimeException * @return string */ public static function propertyAnnotations($class, $propertyName) { $class = is_object($class) ? get_class($class) : $class; if (!class_exists('ReflectionProperty')) { throw new \RuntimeException("Property type of " . $class . "::{$propertyName} cannot be resolved"); } if ($annotations =& self::$propertiesType[$class][$propertyName]) { return $annotations; } if (!($refl =& self::$propertiesRefl[$class][$propertyName])) { $getter = method_exists($class, "get" . ucfirst($propertyName)) ? "get". ucfirst($propertyName) : "get". preg_replace("/([_-\s]?([a-z0-9]+))/e", "ucwords('\\2')", $propertyName); $refl = new \ReflectionMethod($class, $getter); self::$propertiesRefl[$class][$propertyName] = $refl; } // todo: smarter regexp if (!preg_match_all('~\@([^\s@\(]+)[\t ]*(?:\(?([^\n@]+)\)?)?~i', $refl->getDocComment(), $annots, PREG_PATTERN_ORDER)) { return NULL; } foreach ($annots[1] as $i => $annot) { $annotations[strtolower($annot)] = empty($annots[2][$i]) ? TRUE : rtrim($annots[2][$i], " \t\n\r)"); } return $annotations; } }
// #docplaster // #docregion import { Component } from '@angular/core'; import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser'; @Component({ selector: 'app-bypass-security', templateUrl: './bypass-security.component.html', }) export class <API key> { dangerousUrl: string; trustedUrl: SafeUrl; dangerousVideoUrl!: string; videoUrl!: SafeResourceUrl; // #docregion trust-url constructor(private sanitizer: DomSanitizer) { // javascript: URLs are dangerous if attacker controlled. // Angular sanitizes them in data binding, but you can // explicitly tell Angular to trust this value: this.dangerousUrl = 'javascript:alert("Hi there")'; this.trustedUrl = sanitizer.<API key>(this.dangerousUrl); // #enddocregion trust-url this.updateVideoUrl('PUBnlbjZFAI'); } // #docregion trust-video-url updateVideoUrl(id: string) { // Appending an ID to a YouTube URL is safe. // Always make sure to construct SafeValue objects as // close as possible to the input data so // that it's easier to check if the value is safe. this.dangerousVideoUrl = 'https: this.videoUrl = this.sanitizer.<API key>(this.dangerousVideoUrl); } // #enddocregion trust-video-url }
% % System: ECLiPSe Constraint Logic Programming System % Version: $Id: heaps.pl,v 1.1 2008/06/30 17:43:46 jschimpf Exp $ % % Copyright: This library has been adapted from code from the Edinburgh % DEC-10 Prolog Library, whose copyright notice says: % % These files are all in the "public domain" so you can % use them freely, copy them, incorporate them into % programs of your own and so forth without payment. % The work of producing them in the first place and of % organising them as detailed here has been funded over % the years at Edinburgh University mainly by the % Science and Engineering Research Council. Their % dissemination has been encouraged by the Alvey Special % Interest Group: Artificial Intelligence. We would % appreciate it if you were to acknowledge these bodies % when you use or re-distribute any of these files. % % File : HEAPS.PL % Author : R.A.O'Keefe % Updated: 29 November 1983 % Purpose: Implement heaps in Prolog. :- module(heaps). % ECLiPSe header :- export add_to_heap/4, get_from_heap/4, heap_size/2, heap_to_list/2, list_to_heap/2, min_of_heap/3, min_of_heap/5. :- comment(summary, "Implement heaps in Prolog"). :- comment(author, "R.A.O'Keefe"). :- comment(copyright, 'This file is in the public domain'). :- comment(date, "29 November 1983"). :- comment(desc, html("<P> A heap is a labelled binary tree where the key of each node is less than or equal to the keys of its sons. The point of a heap is that we can keep on adding new elements to the heap and we can keep on taking out the minimum element. If there are N elements total, the total time is O(NlgN). If you know all the elements in advance, you are better off doing a merge-sort, but this file is for when you want to do say a best-first search, and have no idea when you start how many elements there will be, let alone what they are. </P><P> A heap is represented as a triple t(N, Free, Tree) where N is the number of elements in the tree, Free is a list of integers which specifies unused positions in the tree, and Tree is a tree made of <PRE> t terms for empty subtrees and t(Key,Datum,Lson,Rson) terms for the rest </PRE> The nodes of the tree are notionally numbered like this: <PRE> 1 2 3 4 6 5 7 8 12 10 14 9 13 11 15 .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. </PRE> The idea is that if the maximum number of elements that have been in the heap so far is M, and the tree currently has K elements, the tree is some subtreee of the tree of this form having exactly M elements, and the Free list is a list of K-M integers saying which of the positions in the M-element tree are currently unoccupied. This free list is needed to ensure that the cost of passing N elements through the heap is O(NlgM) instead of O(NlgN). For M say 100 and N say 10^4 this means a factor of two. The cost of the free list is slight. The storage cost of a heap in a copying Prolog (which Dec-10 Prolog is not) is 2K+3M words. </P> ")). :- comment(add_to_heap/4, [ summary:"inserts the new Key-Datum pair into the heap", template:"add_to_heap(+OldHeap, +Key, +Datum, -NewHeap)", desc:html(" inserts the new Key-Datum pair into the heap. The insertion is not stable, that is, if you insert several pairs with the same Key it is not defined which of them will come out first, and it is possible for any of them to come out first depending on the history of the heap. If you need a stable heap, you could add a counter to the heap and include the counter at the time of insertion in the key. If the free list is empty, the tree will be grown, otherwise one of the empty slots will be re-used. (I use imperative programming language, but the heap code is as pure as the trees code, you can create any number of variants starting from the same heap, and they will share what common structure they can without interfering with each other.) ")]). add_to_heap(t(M,[],OldTree), Key, Datum, t(N,[],NewTree)) :- !, N is M+1, add_to_heap(N, Key, Datum, OldTree, NewTree). add_to_heap(t(M,[H|T],OldTree), Key, Datum, t(N,T,NewTree)) :- N is M+1, add_to_heap(H, Key, Datum, OldTree, NewTree). add_to_heap(1, Key, Datum, _, t(Key,Datum,t,t)) :- !. add_to_heap(N, Key, Datum, t(K1,D1,L1,R1), t(K2,D2,L2,R2)) :- E is N mod 2, M is N sort2(Key, Datum, K1, D1, K2, D2, K3, D3), add_to_heap(E, M, K3, D3, L1, R1, L2, R2). add_to_heap(0, N, Key, Datum, L1, R, L2, R) :- !, add_to_heap(N, Key, Datum, L1, L2). add_to_heap(1, N, Key, Datum, L, R1, L, R2) :- !, add_to_heap(N, Key, Datum, R1, R2). sort2(Key1, Datum1, Key2, Datum2, Key1, Datum1, Key2, Datum2) :- Key1 @< Key2, !. sort2(Key1, Datum1, Key2, Datum2, Key2, Datum2, Key1, Datum1). :- comment(get_from_heap/4, [ summary:"returns the Key-Datum pair in OldHeap with the smallest Key", template:"get_from_heap(+OldHeap, ?Key, ?Datum, -NewHeap)", desc:html(" returns the Key-Datum pair in OldHeap with the smallest Key, and also a New Heap which is the Old Heap with that pair deleted. The easy part is picking off the smallest element. The hard part is repairing the heap structure. repair_heap/4 takes a pair of heaps and returns a new heap built from their elements, and the position number of the gap in the new tree. Note that repair_heap is *not* tail-recursive. ")]). get_from_heap(t(N,Free,t(Key,Datum,L,R)), Key, Datum, t(M,[Hole|Free],Tree)) :- M is N-1, repair_heap(L, R, Tree, Hole). repair_heap(t(K1,D1,L1,R1), t(K2,D2,L2,R2), t(K2,D2,t(K1,D1,L1,R1),R3), N) :- K2 @< K1, !, repair_heap(L2, R2, R3, M), N is 2*M+1. repair_heap(t(K1,D1,L1,R1), t(K2,D2,L2,R2), t(K1,D1,L3,t(K2,D2,L2,R2)), N) :- !, repair_heap(L1, R1, L3, M), N is 2*M. repair_heap(t(K1,D1,L1,R1), t, t(K1,D1,L3,t), N) :- !, repair_heap(L1, R1, L3, M), N is 2*M. repair_heap(t, t(K2,D2,L2,R2), t(K2,D2,t,R3), N) :- !, repair_heap(L2, R2, R3, M), N is 2*M+1. repair_heap(t, t, t, 1) :- !. :- comment(heap_size/2, [ summary:"reports the number of elements currently in the heap", template:"heap_size(+Heap, ?Size)"]). heap_size(t(Size,_,_), Size). :- comment(heap_to_list/2, [ summary:"returns the current set of Key-Datum pairs in the Heap as a List.", template:"heap_to_list(+Heap, -List)", desc:html(" returns the current set of Key-Datum pairs in the Heap as a List, sorted into ascending order of Keys. This is included simply because I think every data structure foo ought to have a foo_to_list and list_to_foo relation (where, of course, it makes sense!) so that conversion between arbitrary data structures is as easy as possible. This predicate is basically just a merge sort, where we can exploit the fact that the tops of the subtrees are smaller than their descendants. ")]). heap_to_list(t(_,_,Tree), List) :- heap_tree_to_list(Tree, List). heap_tree_to_list(t, []) :- !. heap_tree_to_list(t(Key,Datum,Lson,Rson), [Key-Datum|Merged]) :- heap_tree_to_list(Lson, Llist), heap_tree_to_list(Rson, Rlist), heap_tree_to_list(Llist, Rlist, Merged). heap_tree_to_list([H1|T1], [H2|T2], [H2|T3]) :- H2 @< H1, !, heap_tree_to_list([H1|T1], T2, T3). heap_tree_to_list([H1|T1], T2, [H1|T3]) :- !, heap_tree_to_list(T1, T2, T3). heap_tree_to_list([], T, T) :- !. heap_tree_to_list(T, [], T). :- comment(list_to_heap/2, [ summary:"takes a list of Key-Datum pairs and forms them into a heap", template:"list_to_heap(+List, -Heap)", desc:html(" takes a list of Key-Datum pairs (such as keysort could be used to sort) and forms them into a heap. We could do that a wee bit faster by keysorting the list and building the tree directly, but this algorithm makes it obvious that the result is a heap, and could be adapted for use when the ordering predicate is not @< and hence keysort is inapplicable. ")]). list_to_heap(List, Heap) :- list_to_heap(List, 0, t, Heap). list_to_heap([], N, Tree, t(N,[],Tree)) :- !. list_to_heap([Key-Datum|Rest], M, OldTree, Heap) :- N is M+1, add_to_heap(N, Key, Datum, OldTree, MidTree), list_to_heap(Rest, N, MidTree, Heap). :- comment(min_of_heap/3, [ summary:"returns the Key-Datum pair at the top of the heap", template:"min_of_heap(+Heap, ?Key, ?Datum)", desc:html(" returns the Key-Datum pair at the top of the heap (which is of course the pair with the smallest Key), but does not remove it from the heap. It fails if the heap is empty. ")]). :- comment(min_of_heap/5, [ summary:"returns the smallest and second smallest pairs in the heap", template:"min_of_heap(+Heap, ?Key1, ?Datum1, ?Key2, ?Datum2)", desc:html(" returns the smallest (Key1) and second smallest (Key2) pairs in the heap, without deleting them. It fails if the heap does not have at least two elements. ")]). min_of_heap(t(_,_,t(Key,Datum,_,_)), Key, Datum). min_of_heap(t(_,_,t(Key1,Datum1,Lson,Rson)), Key1, Datum1, Key2, Datum2) :- min_of_heap(Lson, Rson, Key2, Datum2). min_of_heap(t(Ka,_Da,_,_), t(Kb,Db,_,_), Kb, Db) :- Kb @< Ka, !. min_of_heap(t(Ka,Da,_,_), _, Ka, Da). min_of_heap(t, t(Kb,Db,_,_), Kb, Db).
"use strict"; var <API key> = require("@babel/runtime/helpers/<API key>"); var <API key> = require("@babel/runtime/helpers/<API key>"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = <API key>(require("react")); var _createSvgIcon = <API key>(require("../../utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); /** * @ignore - internal component. */ var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z" }), 'Star'); exports.default = _default;
package org.eclipse.smarthome.core.library.items; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.core.library.CoreItemFactory; import org.eclipse.smarthome.core.library.types.<API key>; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.core.types.UnDefType; /** * A DimmerItem can be used as a switch (ON/OFF), but it also accepts percent values * to reflect the dimmed state. * * @author Kai Kreuzer - Initial contribution and API * @author Markus Rathgeb - Support more types for getStateAs * */ @NonNullByDefault public class DimmerItem extends SwitchItem { private static List<Class<? extends State>> acceptedDataTypes = new ArrayList<Class<? extends State>>(); private static List<Class<? extends Command>> <API key> = new ArrayList<Class<? extends Command>>(); static { acceptedDataTypes.add(PercentType.class); acceptedDataTypes.add(OnOffType.class); acceptedDataTypes.add(UnDefType.class); <API key>.add(PercentType.class); <API key>.add(OnOffType.class); <API key>.add(<API key>.class); <API key>.add(RefreshType.class); } public DimmerItem(String name) { super(CoreItemFactory.DIMMER, name); } /* package */ DimmerItem(String type, String name) { super(type, name); } public void send(PercentType command) { internalSend(command); } @Override public List<Class<? extends State>> <API key>() { return Collections.unmodifiableList(acceptedDataTypes); } @Override public List<Class<? extends Command>> <API key>() { return Collections.unmodifiableList(<API key>); } @Override public void setState(State state) { if (isAcceptedState(acceptedDataTypes, state)) { // try conversion State convertedState = state.as(PercentType.class); if (convertedState != null) { applyState(convertedState); } else { applyState(state); } } else { logSetTypeError(state); } } }
blueberry=$(date -d "$(stat -c $(%z) blueberry.exe)")
#ifndef <API key> #define <API key> /* The last SGI STL release we merged with */ #define __SGI_STL 0x330 /* STLport version */ #define _STLPORT_MAJOR 5 #define _STLPORT_MINOR 1 #define _STLPORT_PATCHLEVEL 5 #define _STLPORT_VERSION 0x515 #endif /* <API key> */
#include <linux/dma-mapping.h> #include <linux/types.h> #include <linux/dmapool.h> #include <linux/delay.h> #include <sound/core.h> #include <asm/mach-ath79/ar71xx_regs.h> #include <asm/mach-ath79/ath79.h> #include "ath79-pcm.h" #include "ath79-i2s.h" spinlock_t ath79_pcm_lock; static struct dma_pool *ath79_pcm_cache; void ath79_mbox_reset(void) { u32 t; spin_lock(&ath79_pcm_lock); t = ath79_reset_rr(<API key>); t |= AR934X_RESET_MBOX; ath79_reset_wr(<API key>, t); udelay(50); t &= ~(AR934X_RESET_MBOX); ath79_reset_wr(<API key>, t); spin_unlock(&ath79_pcm_lock); } void <API key>(u32 mask) { ath79_dma_wr(<API key>, mask); udelay(50); /* Datasheet says we should reset the stereo controller whenever * we reset the MBOX DMA controller */ ath79_stereo_reset(); } void <API key>(u32 mask) { u32 t; spin_lock(&ath79_pcm_lock); t = ath79_dma_rr(<API key>); t |= mask; ath79_dma_wr(<API key>, t); spin_unlock(&ath79_pcm_lock); } void <API key>(u32 mask) { ath79_dma_wr(<API key>, mask); ath79_reset_wr(<API key>, ~(MISC_INT_DMA)); /* Flush these two registers */ ath79_dma_rr(<API key>); ath79_reset_rr(<API key>); } void <API key>(struct ath79_pcm_rt_priv *rtpriv) { if (rtpriv->direction == <API key>) { ath79_dma_wr(<API key>, <API key>); ath79_dma_rr(<API key>); } else { ath79_dma_wr(<API key>, <API key>); ath79_dma_rr(<API key>); } } void ath79_mbox_dma_stop(struct ath79_pcm_rt_priv *rtpriv) { if (rtpriv->direction == <API key>) { ath79_dma_wr(<API key>, <API key>); ath79_dma_rr(<API key>); } else { ath79_dma_wr(<API key>, <API key>); ath79_dma_rr(<API key>); } /* Delay for the dynamically calculated max time based on sample size, channel, sample rate + margin to ensure that the DMA engine will be truly idle. */ mdelay(rtpriv->delay_time); } void <API key>(void) { ath79_mbox_reset(); <API key>(<API key> | <API key>); } void <API key>(struct ath79_pcm_rt_priv *rtpriv) { struct ath79_pcm_desc *desc; u32 t; if (rtpriv->direction == <API key>) { /* Request the DMA channel to the controller */ t = ath79_dma_rr(<API key>); ath79_dma_wr(<API key>, t | <API key> | (6 << <API key>)); /* The direction is indicated from the DMA engine perspective * i.e. we'll be using the RX registers for Playback and * the TX registers for capture */ desc = list_first_entry(&rtpriv->dma_head, struct ath79_pcm_desc, list); ath79_dma_wr(<API key>, (u32) desc->phys); <API key>(<API key>); } else { /* Request the DMA channel to the controller */ t = ath79_dma_rr(<API key>); ath79_dma_wr(<API key>, t | <API key> | (6 << <API key>)); desc = list_first_entry(&rtpriv->dma_head, struct ath79_pcm_desc, list); ath79_dma_wr(<API key>, (u32) desc->phys); <API key>(<API key>); } } int ath79_mbox_dma_map(struct ath79_pcm_rt_priv *rtpriv, dma_addr_t baseaddr, int period_bytes,int bufsize) { struct list_head *head = &rtpriv->dma_head; struct ath79_pcm_desc *desc, *prev; dma_addr_t desc_p; unsigned int offset = 0; spin_lock(&ath79_pcm_lock); rtpriv->elapsed_size = 0; /* We loop until we have enough buffers to map the requested DMA area */ do { /* Allocate a descriptor and insert it into the DMA ring */ desc = dma_pool_alloc(ath79_pcm_cache, GFP_KERNEL, &desc_p); if(!desc) { return -ENOMEM; } memset(desc, 0, sizeof(struct ath79_pcm_desc)); desc->phys = desc_p; list_add_tail(&desc->list, head); desc->OWN = 1; desc->rsvd1 = desc->rsvd2 = desc->rsvd3 = desc->EOM = 0; /* buffer size may not be a multiple of period_bytes */ if (bufsize >= offset + period_bytes) { desc->size = period_bytes; } else { desc->size = bufsize - offset; } desc->BufPtr = baseaddr + offset; /* For now, we assume the buffer is always full * -->length == size */ desc->length = desc->size; /* We need to make sure we are not the first descriptor. * If we are, prev doesn't point to a struct ath79_pcm_desc */ if (desc->list.prev != head) { prev = list_entry(desc->list.prev, struct ath79_pcm_desc, list); prev->NextPtr = desc->phys; } offset += desc->size; } while (offset < bufsize); /* Once all the descriptors have been created, we can close the loop * by pointing from the last one to the first one */ desc = list_first_entry(head, struct ath79_pcm_desc, list); prev = list_entry(head->prev, struct ath79_pcm_desc, list); prev->NextPtr = desc->phys; spin_unlock(&ath79_pcm_lock); return 0; } void <API key>(struct ath79_pcm_rt_priv *rtpriv) { struct list_head *head = &rtpriv->dma_head; struct ath79_pcm_desc *desc, *n; spin_lock(&ath79_pcm_lock); <API key>(desc, n, head, list) { list_del(&desc->list); dma_pool_free(ath79_pcm_cache, desc, desc->phys); } spin_unlock(&ath79_pcm_lock); return; } int ath79_mbox_dma_init(struct device *dev) { int ret = 0; /* Allocate a DMA pool to store the MBOX descriptor */ ath79_pcm_cache = dma_pool_create("ath79_pcm_pool", dev, sizeof(struct ath79_pcm_desc), 4, 0); if (!ath79_pcm_cache) ret = -ENOMEM; return ret; } void ath79_mbox_dma_exit(void) { dma_pool_destroy(ath79_pcm_cache); ath79_pcm_cache = NULL; }
package ome.server.itests; // Java imports // Third-party libraries import org.testng.annotations.Test; // <API key> dependencies import ome.model.core.Image; import ome.model.meta.Event; import ome.parameters.Filter; import ome.parameters.Parameters; public class ImmutabilityTest extends <API key> { @Test public void <API key>() throws Exception { loginRoot(); Image i = new_Image("immutable creation"); i = iUpdate.saveAndReturnObject(i); Event oldEvent = i.getDetails().getCreationEvent(); Event newEvent = iQuery.findByQuery( "select e from Event e where id != :id", new Parameters( new Filter().page(0, 1)).addId(oldEvent.getId())); i.getDetails().setCreationEvent(newEvent); // This fails because it gets silently copied to our new instance. See: // i = iUpdate.saveAndReturnObject(i); // assertEquals( i.getDetails().getCreationEvent().getId(), // oldEvent.getId()); // Saving and reacquiring to be sure. iUpdate.saveObject(i); // unfortunately still not working properly i = iQuery.refresh(i); i = iQuery.get(i.getClass(), i.getId()); assertEquals(i.getDetails().getCreationEvent().getId(), oldEvent .getId()); } }
#include "core/capabilities/ActionsCapability.h" Capabilities::ActionsCapability::ActionsCapability() : Capabilities::Capability() { //nothing to do } Capabilities::ActionsCapability::ActionsCapability( const QList<QAction*> &actions ) : Capabilities::Capability() , m_actions( actions ) { //nothing to do } Capabilities::ActionsCapability::~ActionsCapability() { //nothing to do. } QList<QAction *> Capabilities::ActionsCapability::actions() const { return m_actions; } #include "ActionsCapability.moc"
/* PR target/95211 target/95256 */ /* { dg-do compile { target { ! ia32 } } } */ /* { dg-options "-O2 -ftree-slp-vectorize -march=skylake-avx512" } */ extern float f[4]; extern long long l[2]; extern long long ul[2]; void fix_128 (void) { l[0] = f[0]; l[1] = f[1]; } void fixuns_128 (void) { ul[0] = f[0]; ul[1] = f[1]; } void float_128 (void) { f[0] = l[0]; f[1] = l[1]; } void floatuns_128 (void) { f[0] = ul[0]; f[1] = ul[1]; } /* { dg-final { <API key> "vcvttps2qq" 2 } } */ /* { dg-final { <API key> "vcvtqq2ps" 2 } } */
#include "native_thread.cpp" #include "nsk_tools.cpp" #include "jni_tools.cpp" #include "jvmti_tools.cpp" #include "agent_tools.cpp" #include "<API key>.cpp" #include "Injector.cpp" #include "JVMTITools.cpp" #include "<API key>.cpp"
// <API key>: GPL-2.0 #define pr_fmt(fmt) "OF: overlay: " fmt #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/of_fdt.h> #include <linux/string.h> #include <linux/ctype.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/libfdt.h> #include <linux/err.h> #include <linux/idr.h> #include "of_private.h" /** * struct target - info about current target node as recursing through overlay * @np: node where current level of overlay will be applied * @in_livetree: @np is a node in the live devicetree * * Used in the algorithm to create the portion of a changeset that describes * an overlay fragment, which is a devicetree subtree. Initially @np is a node * in the live devicetree where the overlay subtree is targeted to be grafted * into. When recursing to the next level of the overlay subtree, the target * also recurses to the next level of the live devicetree, as long as overlay * subtree node also exists in the live devicetree. When a node in the overlay * subtree does not exist at the same level in the live devicetree, target->np * points to a newly allocated node, and all subsequent targets in the subtree * will be newly allocated nodes. */ struct target { struct device_node *np; bool in_livetree; }; /** * struct fragment - info about fragment nodes in overlay expanded device tree * @target: target of the overlay operation * @overlay: pointer to the __overlay__ node */ struct fragment { struct device_node *overlay; struct device_node *target; }; /** * struct overlay_changeset * @id: changeset identifier * @ovcs_list: list on which we are located * @fdt: FDT that was unflattened to create @overlay_tree * @overlay_tree: expanded device tree that contains the fragment nodes * @count: count of fragment structures * @fragments: fragment nodes in the overlay expanded device tree * @symbols_fragment: last element of @fragments[] is the __symbols__ node * @cset: changeset to apply fragments to live device tree */ struct overlay_changeset { int id; struct list_head ovcs_list; const void *fdt; struct device_node *overlay_tree; int count; struct fragment *fragments; bool symbols_fragment; struct of_changeset cset; }; /* flags are sticky - once set, do not reset */ static int <API key>; #define DTSF_APPLY_FAIL 0x01 #define DTSF_REVERT_FAIL 0x02 /* * If a changeset apply or revert encounters an error, an attempt will * be made to undo partial changes, but may fail. If the undo fails * we do not know the state of the devicetree. */ static int devicetree_corrupt(void) { return <API key> & (DTSF_APPLY_FAIL | DTSF_REVERT_FAIL); } static int <API key>(struct overlay_changeset *ovcs, struct target *target, const struct device_node *overlay_node); /* * of_resolve_phandles() finds the largest phandle in the live tree. * of_overlay_apply() may add a larger phandle to the live tree. * Do not allow race between two overlays being applied simultaneously: * mutex_lock(&<API key>) * of_resolve_phandles() * of_overlay_apply() * mutex_unlock(&<API key>) */ static DEFINE_MUTEX(<API key>); void <API key>(void) { mutex_lock(&<API key>); } void <API key>(void) { mutex_unlock(&<API key>); } static LIST_HEAD(ovcs_list); static DEFINE_IDR(ovcs_idr); static <API key>(<API key>); /** * <API key>() - Register notifier for overlay operations * @nb: Notifier block to register * * Register for notification on overlay operations on device tree nodes. The * reported actions definied by @of_reconfig_change. The notifier callback * furthermore receives a pointer to the affected device tree node. * * Note that a notifier callback is not supposed to store pointers to a device * tree node or its content beyond @<API key> corresponding to the * respective node it received. */ int <API key>(struct notifier_block *nb) { return <API key>(&<API key>, nb); } EXPORT_SYMBOL_GPL(<API key>); /** * <API key>() - Unregister notifier for overlay operations * @nb: Notifier block to unregister */ int <API key>(struct notifier_block *nb) { return <API key>(&<API key>, nb); } EXPORT_SYMBOL_GPL(<API key>); static char *<API key>[] = { "pre-apply", "post-apply", "pre-remove", "post-remove", }; static int overlay_notify(struct overlay_changeset *ovcs, enum <API key> action) { struct <API key> nd; int i, ret; for (i = 0; i < ovcs->count; i++) { struct fragment *fragment = &ovcs->fragments[i]; nd.target = fragment->target; nd.overlay = fragment->overlay; ret = <API key>(&<API key>, action, &nd); if (ret == NOTIFY_OK || ret == NOTIFY_STOP) return 0; if (ret) { ret = notifier_to_errno(ret); pr_err("overlay changeset %s notifier error %d, target: %pOF\n", <API key>[action], ret, nd.target); return ret; } } return 0; } static struct property *<API key>( struct overlay_changeset *ovcs, const struct property *prop) { struct fragment *fragment; struct property *new_prop; struct device_node *fragment_node; struct device_node *overlay_node; const char *path; const char *path_tail; const char *target_path; int k; int overlay_name_len; int path_len; int path_tail_len; int target_path_len; if (!prop->value) return NULL; if (strnlen(prop->value, prop->length) >= prop->length) return NULL; path = prop->value; path_len = strlen(path); if (path_len < 1) return NULL; fragment_node = <API key>(ovcs->overlay_tree, path + 1); overlay_node = <API key>(fragment_node, "__overlay__/"); of_node_put(fragment_node); of_node_put(overlay_node); for (k = 0; k < ovcs->count; k++) { fragment = &ovcs->fragments[k]; if (fragment->overlay == overlay_node) break; } if (k >= ovcs->count) return NULL; overlay_name_len = snprintf(NULL, 0, "%pOF", fragment->overlay); if (overlay_name_len > path_len) return NULL; path_tail = path + overlay_name_len; path_tail_len = strlen(path_tail); target_path = kasprintf(GFP_KERNEL, "%pOF", fragment->target); if (!target_path) return NULL; target_path_len = strlen(target_path); new_prop = kzalloc(sizeof(*new_prop), GFP_KERNEL); if (!new_prop) goto <API key>; new_prop->name = kstrdup(prop->name, GFP_KERNEL); new_prop->length = target_path_len + path_tail_len + 1; new_prop->value = kzalloc(new_prop->length, GFP_KERNEL); if (!new_prop->name || !new_prop->value) goto err_free_new_prop; strcpy(new_prop->value, target_path); strcpy(new_prop->value + target_path_len, path_tail); <API key>(new_prop, OF_DYNAMIC); return new_prop; err_free_new_prop: kfree(new_prop->name); kfree(new_prop->value); kfree(new_prop); <API key>: kfree(target_path); return NULL; } /** * <API key>() - add @overlay_prop to overlay changeset * @ovcs: overlay changeset * @target: where @overlay_prop will be placed * @overlay_prop: property to add or update, from overlay tree * @is_symbols_prop: 1 if @overlay_prop is from node "/__symbols__" * * If @overlay_prop does not already exist in live devicetree, add changeset * entry to add @overlay_prop in @target, else add changeset entry to update * value of @overlay_prop. * * @target may be either in the live devicetree or in a new subtree that * is contained in the changeset. * * Some special properties are not added or updated (no error returned): * "name", "phandle", "linux,phandle". * * Properties "#address-cells" and "#size-cells" are not updated if they * are already in the live tree, but if present in the live tree, the values * in the overlay must match the values in the live tree. * * Update of property in symbols node is not allowed. * * Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if * invalid @overlay. */ static int <API key>(struct overlay_changeset *ovcs, struct target *target, struct property *overlay_prop, bool is_symbols_prop) { struct property *new_prop = NULL, *prop; int ret = 0; if (target->in_livetree) if (!of_prop_cmp(overlay_prop->name, "name") || !of_prop_cmp(overlay_prop->name, "phandle") || !of_prop_cmp(overlay_prop->name, "linux,phandle")) return 0; if (target->in_livetree) prop = of_find_property(target->np, overlay_prop->name, NULL); else prop = NULL; if (prop) { if (!of_prop_cmp(prop->name, "#address-cells")) { if (!of_prop_val_eq(prop, overlay_prop)) { pr_err("ERROR: changing value of #address-cells is not allowed in %pOF\n", target->np); ret = -EINVAL; } return ret; } else if (!of_prop_cmp(prop->name, "#size-cells")) { if (!of_prop_val_eq(prop, overlay_prop)) { pr_err("ERROR: changing value of #size-cells is not allowed in %pOF\n", target->np); ret = -EINVAL; } return ret; } } if (is_symbols_prop) { if (prop) return -EINVAL; new_prop = <API key>(ovcs, overlay_prop); } else { new_prop = __of_prop_dup(overlay_prop, GFP_KERNEL); } if (!new_prop) return -ENOMEM; if (!prop) { if (!target->in_livetree) { new_prop->next = target->np->deadprops; target->np->deadprops = new_prop; } ret = <API key>(&ovcs->cset, target->np, new_prop); } else { ret = <API key>(&ovcs->cset, target->np, new_prop); } if (!of_node_check_flag(target->np, OF_OVERLAY)) pr_err("WARNING: memory leak will occur if overlay removed, property: %pOF/%s\n", target->np, new_prop->name); if (ret) { kfree(new_prop->name); kfree(new_prop->value); kfree(new_prop); } return ret; } /** * add_changeset_node() - add @node (and children) to overlay changeset * @ovcs: overlay changeset * @target: where @node will be placed in live tree or changeset * @node: node from within overlay device tree fragment * * If @node does not already exist in @target, add changeset entry * to add @node in @target. * * If @node already exists in @target, and the existing node has * a phandle, the overlay node is not allowed to have a phandle. * * If @node has child nodes, add the children recursively via * <API key>(). * * NOTE_1: A live devicetree created from a flattened device tree (FDT) will * not contain the full path in node->full_name. Thus an overlay * created from an FDT also will not contain the full path in * node->full_name. However, a live devicetree created from Open * Firmware may have the full path in node->full_name. * * add_changeset_node() follows the FDT convention and does not include * the full path in node->full_name. Even though it expects the overlay * to not contain the full path, it uses kbasename() to remove the * full path should it exist. It also uses kbasename() in comparisons * to nodes in the live devicetree so that it can apply an overlay to * a live devicetree created from Open Firmware. * * NOTE_2: Multiple mods of created nodes not supported. * * Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if * invalid @overlay. */ static int add_changeset_node(struct overlay_changeset *ovcs, struct target *target, struct device_node *node) { const char *node_kbasename; const __be32 *phandle; struct device_node *tchild; struct target target_child; int ret = 0, size; node_kbasename = kbasename(node->full_name); <API key>(target->np, tchild) if (!of_node_cmp(node_kbasename, kbasename(tchild->full_name))) break; if (!tchild) { tchild = __of_node_dup(NULL, node_kbasename); if (!tchild) return -ENOMEM; tchild->parent = target->np; tchild->name = __of_get_property(node, "name", NULL); if (!tchild->name) tchild->name = "<NULL>"; /* ignore obsolete "linux,phandle" */ phandle = __of_get_property(node, "phandle", &size); if (phandle && (size == 4)) tchild->phandle = be32_to_cpup(phandle); of_node_set_flag(tchild, OF_OVERLAY); ret = <API key>(&ovcs->cset, tchild); if (ret) return ret; target_child.np = tchild; target_child.in_livetree = false; ret = <API key>(ovcs, &target_child, node); of_node_put(tchild); return ret; } if (node->phandle && tchild->phandle) { ret = -EINVAL; } else { target_child.np = tchild; target_child.in_livetree = target->in_livetree; ret = <API key>(ovcs, &target_child, node); } of_node_put(tchild); return ret; } /** * <API key>() - add level of overlay changeset * @ovcs: overlay changeset * @target: where to place @overlay_node in live tree * @overlay_node: node from within an overlay device tree fragment * * Add the properties (if any) and nodes (if any) from @overlay_node to the * @ovcs->cset changeset. If an added node has child nodes, they will * be added recursively. * * Do not allow symbols node to have any children. * * Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if * invalid @overlay_node. */ static int <API key>(struct overlay_changeset *ovcs, struct target *target, const struct device_node *overlay_node) { struct device_node *child; struct property *prop; int ret; <API key>(overlay_node, prop) { ret = <API key>(ovcs, target, prop, 0); if (ret) { pr_debug("Failed to apply prop @%pOF/%s, err=%d\n", target->np, prop->name, ret); return ret; } } <API key>(overlay_node, child) { ret = add_changeset_node(ovcs, target, child); if (ret) { pr_debug("Failed to apply node @%pOF/%pOFn, err=%d\n", target->np, child, ret); of_node_put(child); return ret; } } return 0; } /* * Add the properties from __overlay__ node to the @ovcs->cset changeset. */ static int <API key>(struct overlay_changeset *ovcs, struct target *target, const struct device_node *<API key>) { struct property *prop; int ret; <API key>(<API key>, prop) { ret = <API key>(ovcs, target, prop, 1); if (ret) { pr_debug("Failed to apply symbols prop @%pOF/%s, err=%d\n", target->np, prop->name, ret); return ret; } } return 0; } static int <API key>(struct overlay_changeset *ovcs, struct of_changeset_entry *ce_1) { struct of_changeset_entry *ce_2; char *fn_1, *fn_2; int node_path_match; if (ce_1->action != <API key> && ce_1->action != <API key>) return 0; ce_2 = ce_1; <API key>(ce_2, &ovcs->cset.entries, node) { if ((ce_2->action != <API key> && ce_2->action != <API key>) || of_node_cmp(ce_1->np->full_name, ce_2->np->full_name)) continue; fn_1 = kasprintf(GFP_KERNEL, "%pOF", ce_1->np); fn_2 = kasprintf(GFP_KERNEL, "%pOF", ce_2->np); node_path_match = !strcmp(fn_1, fn_2); kfree(fn_1); kfree(fn_2); if (node_path_match) { pr_err("ERROR: multiple fragments add and/or delete node %pOF\n", ce_1->np); return -EINVAL; } } return 0; } static int find_dup_cset_prop(struct overlay_changeset *ovcs, struct of_changeset_entry *ce_1) { struct of_changeset_entry *ce_2; char *fn_1, *fn_2; int node_path_match; if (ce_1->action != <API key> && ce_1->action != <API key> && ce_1->action != <API key>) return 0; ce_2 = ce_1; <API key>(ce_2, &ovcs->cset.entries, node) { if ((ce_2->action != <API key> && ce_2->action != <API key> && ce_2->action != <API key>) || of_node_cmp(ce_1->np->full_name, ce_2->np->full_name)) continue; fn_1 = kasprintf(GFP_KERNEL, "%pOF", ce_1->np); fn_2 = kasprintf(GFP_KERNEL, "%pOF", ce_2->np); node_path_match = !strcmp(fn_1, fn_2); kfree(fn_1); kfree(fn_2); if (node_path_match && !of_prop_cmp(ce_1->prop->name, ce_2->prop->name)) { pr_err("ERROR: multiple fragments add, update, and/or delete property %pOF/%s\n", ce_1->np, ce_1->prop->name); return -EINVAL; } } return 0; } /** * <API key>() - check for duplicate entries * @ovcs: Overlay changeset * * Check changeset @ovcs->cset for multiple {add or delete} node entries for * the same node or duplicate {add, delete, or update} properties entries * for the same property. * * Returns 0 on success, or -EINVAL if duplicate changeset entry found. */ static int <API key>(struct overlay_changeset *ovcs) { struct of_changeset_entry *ce_1; int dup_entry = 0; list_for_each_entry(ce_1, &ovcs->cset.entries, node) { dup_entry |= <API key>(ovcs, ce_1); dup_entry |= find_dup_cset_prop(ovcs, ce_1); } return dup_entry ? -EINVAL : 0; } /** * build_changeset() - populate overlay changeset in @ovcs from @ovcs->fragments * @ovcs: Overlay changeset * * Create changeset @ovcs->cset to contain the nodes and properties of the * overlay device tree fragments in @ovcs->fragments[]. If an error occurs, * any portions of the changeset that were successfully created will remain * in @ovcs->cset. * * Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if * invalid overlay in @ovcs->fragments[]. */ static int build_changeset(struct overlay_changeset *ovcs) { struct fragment *fragment; struct target target; int fragments_count, i, ret; /* * if there is a symbols fragment in ovcs->fragments[i] it is * the final element in the array */ if (ovcs->symbols_fragment) fragments_count = ovcs->count - 1; else fragments_count = ovcs->count; for (i = 0; i < fragments_count; i++) { fragment = &ovcs->fragments[i]; target.np = fragment->target; target.in_livetree = true; ret = <API key>(ovcs, &target, fragment->overlay); if (ret) { pr_debug("fragment apply failed '%pOF'\n", fragment->target); return ret; } } if (ovcs->symbols_fragment) { fragment = &ovcs->fragments[ovcs->count - 1]; target.np = fragment->target; target.in_livetree = true; ret = <API key>(ovcs, &target, fragment->overlay); if (ret) { pr_debug("symbols fragment apply failed '%pOF'\n", fragment->target); return ret; } } return <API key>(ovcs); } /* * Find the target node using a number of different strategies * in order of preference: * * 1) "target" property containing the phandle of the target * 2) "target-path" property containing the path of the target */ static struct device_node *find_target(struct device_node *info_node) { struct device_node *node; const char *path; u32 val; int ret; ret = <API key>(info_node, "target", &val); if (!ret) { node = <API key>(val); if (!node) pr_err("find target, node: %pOF, phandle 0x%x not found\n", info_node, val); return node; } ret = <API key>(info_node, "target-path", &path); if (!ret) { node = <API key>(path); if (!node) pr_err("find target, node: %pOF, path '%s' not found\n", info_node, path); return node; } pr_err("find target, node: %pOF, no target property\n", info_node); return NULL; } /** * <API key>() - initialize overlay changeset from overlay tree * @ovcs: Overlay changeset to build * @fdt: the FDT that was unflattened to create @tree * @tree: Contains all the overlay fragments and overlay fixup nodes * * Initialize @ovcs. Populate @ovcs->fragments with node information from * the top level of @tree. The relevant top level nodes are the fragment * nodes and the __symbols__ node. Any other top level node will be ignored. * * Returns 0 on success, -ENOMEM if memory allocation failure, -EINVAL if error * detected in @tree, or -ENOSPC if idr_alloc() error. */ static int <API key>(struct overlay_changeset *ovcs, const void *fdt, struct device_node *tree) { struct device_node *node, *overlay_node; struct fragment *fragment; struct fragment *fragments; int cnt, id, ret; /* * Warn for some issues. Can not return -EINVAL for these until * <API key>() is fixed to pass these checks. */ if (!of_node_check_flag(tree, OF_DYNAMIC)) pr_debug("%s() tree is not dynamic\n", __func__); if (!of_node_check_flag(tree, OF_DETACHED)) pr_debug("%s() tree is not detached\n", __func__); if (!of_node_is_root(tree)) pr_debug("%s() tree is not root\n", __func__); ovcs->overlay_tree = tree; ovcs->fdt = fdt; INIT_LIST_HEAD(&ovcs->ovcs_list); of_changeset_init(&ovcs->cset); id = idr_alloc(&ovcs_idr, ovcs, 1, 0, GFP_KERNEL); if (id <= 0) return id; cnt = 0; /* fragment nodes */ <API key>(tree, node) { overlay_node = <API key>(node, "__overlay__"); if (overlay_node) { cnt++; of_node_put(overlay_node); } } node = <API key>(tree, "__symbols__"); if (node) { cnt++; of_node_put(node); } fragments = kcalloc(cnt, sizeof(*fragments), GFP_KERNEL); if (!fragments) { ret = -ENOMEM; goto err_free_idr; } cnt = 0; <API key>(tree, node) { overlay_node = <API key>(node, "__overlay__"); if (!overlay_node) continue; fragment = &fragments[cnt]; fragment->overlay = overlay_node; fragment->target = find_target(node); if (!fragment->target) { of_node_put(fragment->overlay); ret = -EINVAL; goto err_free_fragments; } cnt++; } /* * if there is a symbols fragment in ovcs->fragments[i] it is * the final element in the array */ node = <API key>(tree, "__symbols__"); if (node) { ovcs->symbols_fragment = 1; fragment = &fragments[cnt]; fragment->overlay = node; fragment->target = <API key>("/__symbols__"); if (!fragment->target) { pr_err("symbols in overlay, but not in live tree\n"); ret = -EINVAL; goto err_free_fragments; } cnt++; } if (!cnt) { pr_err("no fragments or symbols in overlay\n"); ret = -EINVAL; goto err_free_fragments; } ovcs->id = id; ovcs->count = cnt; ovcs->fragments = fragments; return 0; err_free_fragments: kfree(fragments); err_free_idr: idr_remove(&ovcs_idr, id); pr_err("%s() failed, ret = %d\n", __func__, ret); return ret; } static void <API key>(struct overlay_changeset *ovcs) { int i; if (ovcs->cset.entries.next) <API key>(&ovcs->cset); if (ovcs->id) idr_remove(&ovcs_idr, ovcs->id); for (i = 0; i < ovcs->count; i++) { of_node_put(ovcs->fragments[i].target); of_node_put(ovcs->fragments[i].overlay); } kfree(ovcs->fragments); /* * There should be no live pointers into ovcs->overlay_tree and * ovcs->fdt due to the policy that overlay notifiers are not allowed * to retain pointers into the overlay devicetree. */ kfree(ovcs->overlay_tree); kfree(ovcs->fdt); kfree(ovcs); } /* * internal documentation * * of_overlay_apply() - Create and apply an overlay changeset * @fdt: the FDT that was unflattened to create @tree * @tree: Expanded overlay device tree * @ovcs_id: Pointer to overlay changeset id * * Creates and applies an overlay changeset. * * If an error occurs in a pre-apply notifier, then no changes are made * to the device tree. * * A non-zero return value will not have created the changeset if error is from: * - parameter checks * - building the changeset * - overlay changeset pre-apply notifier * * If an error is returned by an overlay changeset pre-apply notifier * then no further overlay changeset pre-apply notifier will be called. * * A non-zero return value will have created the changeset if error is from: * - overlay changeset entry notifier * - overlay changeset post-apply notifier * * If an error is returned by an overlay changeset post-apply notifier * then no further overlay changeset post-apply notifier will be called. * * If more than one notifier returns an error, then the last notifier * error to occur is returned. * * If an error occurred while applying the overlay changeset, then an * attempt is made to revert any changes that were made to the * device tree. If there were any errors during the revert attempt * then the state of the device tree can not be determined, and any * following attempt to apply or remove an overlay changeset will be * refused. * * Returns 0 on success, or a negative error number. Overlay changeset * id is returned to *ovcs_id. */ static int of_overlay_apply(const void *fdt, struct device_node *tree, int *ovcs_id) { struct overlay_changeset *ovcs; int ret = 0, ret_revert, ret_tmp; /* * As of this point, fdt and tree belong to the overlay changeset. * overlay changeset code is responsible for freeing them. */ if (devicetree_corrupt()) { pr_err("devicetree state suspect, refuse to apply overlay\n"); kfree(fdt); kfree(tree); ret = -EBUSY; goto out; } ovcs = kzalloc(sizeof(*ovcs), GFP_KERNEL); if (!ovcs) { kfree(fdt); kfree(tree); ret = -ENOMEM; goto out; } <API key>(); mutex_lock(&of_mutex); ret = of_resolve_phandles(tree); if (ret) goto err_free_tree; ret = <API key>(ovcs, fdt, tree); if (ret) goto err_free_tree; /* * after overlay_notify(), ovcs->overlay_tree related pointers may have * leaked to drivers, so can not kfree() tree, aka ovcs->overlay_tree; * and can not free fdt, aka ovcs->fdt */ ret = overlay_notify(ovcs, <API key>); if (ret) { pr_err("overlay changeset pre-apply notify error %d\n", ret); goto <API key>; } ret = build_changeset(ovcs); if (ret) goto <API key>; ret_revert = 0; ret = <API key>(&ovcs->cset, &ret_revert); if (ret) { if (ret_revert) { pr_debug("overlay changeset revert error %d\n", ret_revert); <API key> |= DTSF_APPLY_FAIL; } goto <API key>; } <API key>(); ret = <API key>(&ovcs->cset); if (ret) pr_err("overlay apply changeset entry notify error %d\n", ret); /* notify failure is not fatal, continue */ list_add_tail(&ovcs->ovcs_list, &ovcs_list); *ovcs_id = ovcs->id; ret_tmp = overlay_notify(ovcs, <API key>); if (ret_tmp) { pr_err("overlay changeset post-apply notify error %d\n", ret_tmp); if (!ret) ret = ret_tmp; } goto out_unlock; err_free_tree: kfree(fdt); kfree(tree); <API key>: <API key>(ovcs); out_unlock: mutex_unlock(&of_mutex); <API key>(); out: pr_debug("%s() err=%d\n", __func__, ret); return ret; } int <API key>(const void *overlay_fdt, u32 overlay_fdt_size, int *ovcs_id) { const void *new_fdt; int ret; u32 size; struct device_node *overlay_root; *ovcs_id = 0; ret = 0; if (overlay_fdt_size < sizeof(struct fdt_header) || fdt_check_header(overlay_fdt)) { pr_err("Invalid overlay_fdt header\n"); return -EINVAL; } size = fdt_totalsize(overlay_fdt); if (overlay_fdt_size < size) return -EINVAL; /* * Must create permanent copy of FDT because <API key>() * will create pointers to the passed in FDT in the unflattened tree. */ new_fdt = kmemdup(overlay_fdt, size, GFP_KERNEL); if (!new_fdt) return -ENOMEM; <API key>(new_fdt, NULL, &overlay_root); if (!overlay_root) { pr_err("unable to unflatten overlay_fdt\n"); ret = -EINVAL; goto out_free_new_fdt; } ret = of_overlay_apply(new_fdt, overlay_root, ovcs_id); if (ret < 0) { /* * new_fdt and overlay_root now belong to the overlay * changeset. * overlay changeset code is responsible for freeing them. */ goto out; } return 0; out_free_new_fdt: kfree(new_fdt); out: return ret; } EXPORT_SYMBOL_GPL(<API key>); /* * Find @np in @tree. * * Returns 1 if @np is @tree or is contained in @tree, else 0 */ static int find_node(struct device_node *tree, struct device_node *np) { struct device_node *child; if (tree == np) return 1; <API key>(tree, child) { if (find_node(child, np)) { of_node_put(child); return 1; } } return 0; } /* * Is @remove_ce_node a child of, a parent of, or the same as any * node in an overlay changeset more topmost than @remove_ovcs? * * Returns 1 if found, else 0 */ static int <API key>(struct overlay_changeset *remove_ovcs, struct device_node *remove_ce_node) { struct overlay_changeset *ovcs; struct of_changeset_entry *ce; <API key>(ovcs, &ovcs_list, ovcs_list) { if (ovcs == remove_ovcs) break; list_for_each_entry(ce, &ovcs->cset.entries, node) { if (find_node(ce->np, remove_ce_node)) { pr_err("%s: #%d overlaps with #%d @%pOF\n", __func__, remove_ovcs->id, ovcs->id, remove_ce_node); return 1; } if (find_node(remove_ce_node, ce->np)) { pr_err("%s: #%d overlaps with #%d @%pOF\n", __func__, remove_ovcs->id, ovcs->id, remove_ce_node); return 1; } } } return 0; } /* * We can safely remove the overlay only if it's the top-most one. * Newly applied overlays are inserted at the tail of the overlay list, * so a top most overlay is the one that is closest to the tail. * * The topmost check is done by exploiting this property. For each * affected device node in the log list we check if this overlay is * the one closest to the tail. If another overlay has affected this * device node and is closest to the tail, then removal is not permited. */ static int <API key>(struct overlay_changeset *remove_ovcs) { struct of_changeset_entry *remove_ce; list_for_each_entry(remove_ce, &remove_ovcs->cset.entries, node) { if (<API key>(remove_ovcs, remove_ce->np)) { pr_err("overlay #%d is not topmost\n", remove_ovcs->id); return 0; } } return 1; } /** * of_overlay_remove() - Revert and free an overlay changeset * @ovcs_id: Pointer to overlay changeset id * * Removes an overlay if it is permissible. @ovcs_id was previously returned * by <API key>(). * * If an error occurred while attempting to revert the overlay changeset, * then an attempt is made to re-apply any changeset entry that was * reverted. If an error occurs on re-apply then the state of the device * tree can not be determined, and any following attempt to apply or remove * an overlay changeset will be refused. * * A non-zero return value will not revert the changeset if error is from: * - parameter checks * - overlay changeset pre-remove notifier * - overlay changeset entry revert * * If an error is returned by an overlay changeset pre-remove notifier * then no further overlay changeset pre-remove notifier will be called. * * If more than one notifier returns an error, then the last notifier * error to occur is returned. * * A non-zero return value will revert the changeset if error is from: * - overlay changeset entry notifier * - overlay changeset post-remove notifier * * If an error is returned by an overlay changeset post-remove notifier * then no further overlay changeset post-remove notifier will be called. * * Returns 0 on success, or a negative error number. *ovcs_id is set to * zero after reverting the changeset, even if a subsequent error occurs. */ int of_overlay_remove(int *ovcs_id) { struct overlay_changeset *ovcs; int ret, ret_apply, ret_tmp; ret = 0; if (devicetree_corrupt()) { pr_err("suspect devicetree state, refuse to remove overlay\n"); ret = -EBUSY; goto out; } mutex_lock(&of_mutex); ovcs = idr_find(&ovcs_idr, *ovcs_id); if (!ovcs) { ret = -ENODEV; pr_err("remove: Could not find overlay #%d\n", *ovcs_id); goto out_unlock; } if (!<API key>(ovcs)) { ret = -EBUSY; goto out_unlock; } ret = overlay_notify(ovcs, <API key>); if (ret) { pr_err("overlay changeset pre-remove notify error %d\n", ret); goto out_unlock; } list_del(&ovcs->ovcs_list); /* * Disable phandle cache. Avoids race condition that would arise * from removing cache entry when the associated node is deleted. */ <API key>(); ret_apply = 0; ret = <API key>(&ovcs->cset, &ret_apply); <API key>(); if (ret) { if (ret_apply) <API key> |= DTSF_REVERT_FAIL; goto out_unlock; } ret = <API key>(&ovcs->cset); if (ret) pr_err("overlay remove changeset entry notify error %d\n", ret); /* notify failure is not fatal, continue */ *ovcs_id = 0; ret_tmp = overlay_notify(ovcs, <API key>); if (ret_tmp) { pr_err("overlay changeset post-remove notify error %d\n", ret_tmp); if (!ret) ret = ret_tmp; } <API key>(ovcs); out_unlock: mutex_unlock(&of_mutex); out: pr_debug("%s() err=%d\n", __func__, ret); return ret; } EXPORT_SYMBOL_GPL(of_overlay_remove); /** * <API key>() - Reverts and frees all overlay changesets * * Removes all overlays from the system in the correct order. * * Returns 0 on success, or a negative error number */ int <API key>(void) { struct overlay_changeset *ovcs, *ovcs_n; int ret; /* the tail of list is guaranteed to be safe to remove */ <API key>(ovcs, ovcs_n, &ovcs_list, ovcs_list) { ret = of_overlay_remove(&ovcs->id); if (ret) return ret; } return 0; } EXPORT_SYMBOL_GPL(<API key>);
<?php $lan = array ( 'This page can only be called from the commandline' => '', 'Bounce processing error' => '', 'Bounce Processing info' => '', 'error' => '', 'info' => '', 'system message bounced, user marked unconfirmed' => '', 'Bounced system message' => '', 'User marked unconfirmed' => '', 'View Bounce' => '', 'Cannot create POP3 connection to' => ' POP3 ', 'Cannot open mailbox file' => '', 'bounces to fetch from the mailbox' => '', 'Please do not interrupt this process' => '', 'bounces to process' => '', 'Processing first' => '', 'bounces' => '', 'Running in test mode, not deleting messages from mailbox' => '', 'Processed messages will be deleted from mailbox' => '', 'Deleting message' => '', 'Closing mailbox, and purging messages' => '', 'IMAP is not included in your PHP installation, cannot continue' => ' PHP IMAP ', 'Check out' => '', 'Bounce mechanism not properly configured' => '', 'bounce_protocol not supported' => ' bounce_protocol', 'Identifying consecutive bounces' => '', 'Nothing to do' => '', 'Process Killed by other process' => '', 'User' => '', 'has consecutive bounces' => '', 'over threshold, user marked unconfirmed' => '', 'Auto Unsubscribed' => '', 'User auto unsubscribed for' => '', 'consecutive bounces' => '', 'of' => '', 'users processed' => '', 'processing first' => '', 'Report:' => '', 'Below are users who have been marked unconfirmed. The number in [' => ' [] () ', 'Processing bounces based on active bounce rules' => '', 'Auto Blacklisted' => '', 'User auto blacklisted for' => '', 'bounce rule' => '', 'system message bounced, but unknown user' => '', 'bounces processed by advanced processing' => '', 'bounces were not matched by advanced processing rules' => '', 'Report of advanced bounce processing:' => '', ); ?>
<?php // $Header: /cvsroot/html2ps/box.text.php,v 1.56 2007/05/07 12:15:53 Konstantin Exp $ require_once(HTML2PS_DIR.'box.inline.simple.php'); // TODO: from my POV, it wll be better to pass the font- or CSS-controlling object to the constructor // instead of using globally visible functions in 'show'. define('SYMBOL_NBSP', chr(160)); class TextBox extends SimpleInlineBox { var $words; var $encodings; var $hyphens; var $_widths; var $_word_widths; var $_wrappable; var $wrapped; function TextBox() { $this->SimpleInlineBox(); $this->words = array(); $this->encodings = array(); $this->hyphens = array(); $this->_word_widths = array(); $this->_wrappable = array(); $this->wrapped = null; $this->_widths = array(); $this->font_size = 0; $this->ascender = 0; $this->descender = 0; $this->width = 0; $this->height = 0; } /** * Check if given subword contains soft hyphens and calculate */ function _make_wrappable(&$driver, $base_width, $font_name, $font_size, $subword_index) { $hyphens = $this->hyphens[$subword_index]; $wrappable = array(); foreach ($hyphens as $hyphen) { $<API key> = $hyphen; $<API key> = $base_width + $driver->stringwidth(substr($this->words[$subword_index], 0, $<API key>), $font_name, $this->encodings[$subword_index], $font_size); $subword_full_width = $<API key> + $driver->stringwidth('-', $font_name, "iso-8859-1", $font_size); $wrappable[] = array($subword_index, $<API key>, $<API key>, $subword_full_width); }; return $wrappable; } function get_content() { return join('', array_map(array($this, '<API key>'), $this->words, $this->encodings)); } function <API key>($word, $encoding) { $manager_encoding =& ManagerEncoding::get(); return $manager_encoding->toUTF8($word, $encoding); } function get_height() { return $this->height; } function put_height($value) { $this->height = $value; } // Apply 'line-height' CSS property; modifies the default_baseline value // (NOT baseline, as it is calculated - and is overwritten - in the close_line // method of container box // Note that underline position (or 'descender' in terms of PDFLIB) - // so, simple that space of text box under the baseline - is scaled too // when 'line-height' is applied function _apply_line_height() { $height = $this->get_height(); $under = $height - $this->default_baseline; $line_height = $this->getCSSProperty(CSS_LINE_HEIGHT); if ($height > 0) { $scale = $line_height->apply($this->ascender + $this->descender) / ($this->ascender + $this->descender); } else { $scale = 0; }; // Calculate the height delta of the text box $delta = $height * ($scale-1); $this->put_height(($this->ascender + $this->descender)*$scale); $this->default_baseline = $this->default_baseline + $delta/2; } function _get_font_name(&$viewport, $subword_index) { if (isset($this->_cache[CACHE_TYPEFACE][$subword_index])) { return $this->_cache[CACHE_TYPEFACE][$subword_index]; }; $font_resolver =& $viewport->get_font_resolver(); $font = $this->getCSSProperty(CSS_FONT); $typeface = $font_resolver->getTypefaceName($font->family, $font->weight, $font->style, $this->encodings[$subword_index]); $this->_cache[CACHE_TYPEFACE][$subword_index] = $typeface; return $typeface; } function add_subword($raw_subword, $encoding, $hyphens) { $text_transform = $this->getCSSProperty(CSS_TEXT_TRANSFORM); switch ($text_transform) { case <API key>: $subword = ucwords($raw_subword); break; case <API key>: $subword = strtoupper($raw_subword); break; case <API key>: $subword = strtolower($raw_subword); break; case <API key>: $subword = $raw_subword; break; } $this->words[] = $subword; $this->encodings[] = $encoding; $this->hyphens[] = $hyphens; } function &create($text, $encoding, &$pipeline) { $box =& TextBox::create_empty($pipeline); $box->add_subword($text, $encoding, array()); return $box; } function &create_empty(&$pipeline) { $box =& new TextBox(); $css_state = $pipeline->getCurrentCSSState(); $box->readCSS($css_state); $css_state = $pipeline->getCurrentCSSState(); return $box; } function readCSS(&$state) { parent::readCSS($state); $this->_readCSSLengths($state, array(CSS_TEXT_INDENT, CSS_LETTER_SPACING)); } // Inherited from GenericFormattedBox function get_descender() { return $this->descender; } function get_ascender() { return $this->ascender; } function get_baseline() { return $this->baseline; } function <API key>(&$context) { return $this->get_full_width(); } function get_min_width(&$context) { return $this->get_full_width(); } function get_max_width(&$context) { return $this->get_full_width(); } // Checks if current inline box should cause a line break inside the parent box // @param $parent reference to a parent box // @param $content flow context // @return true if line break occurred; false otherwise function maybe_line_break(&$parent, &$context) { if (!$parent->line_break_allowed()) { return false; }; $last =& $parent->last_in_line(); if ($last) { // Check if last box was a note call box. Punctuation marks // after a note-call box should not be wrapped to new line, // while "plain" words may be wrapped. if ($last->is_note_call() && $this->is_punctuation()) { return false; }; }; // Calculate the x-coordinate of this box right edge $right_x = $this->get_full_width() + $parent->_current_x; $need_break = false; // Check for right-floating boxes // If upper-right corner of this inline box is inside of some float, wrap the line $float = $context->point_in_floats($right_x, $parent->_current_y); if ($float) { $need_break = true; }; // No floats; check if we had run out the right edge of container // TODO: nobr-before, nobr-after if (($right_x > $parent->get_right()+EPSILON)) { // Now check if parent line box contains any other boxes; // if not, we should draw this box unless we have a floating box to the left $first = $parent->get_first(); $ti = $this->getCSSProperty(CSS_TEXT_INDENT); $indent_offset = $ti->calculate($parent); if ($parent->_current_x > $parent->get_left() + $indent_offset + EPSILON) { $need_break = true; }; } // As close-line will not change the current-Y parent coordinate if no // items were in the line box, we need to offset this explicitly in this case if ($parent->line_box_empty() && $need_break) { $parent->_current_y -= $this->get_height(); }; if ($need_break) { // Check if current box contains soft hyphens and use them, breaking word into parts $size = count($this->_wrappable); if ($size > 0) { $width_delta = $right_x - $parent->get_right(); if (!is_null($float)) { $width_delta = $right_x - $float->get_left_margin(); }; $this->_find_soft_hyphen($parent, $width_delta); }; $parent->close_line($context); // Check if parent inline boxes have left padding/margins and add them to current_x $element = $this->parent; while (!is_null($element) && is_a($element,"GenericInlineBox")) { $parent->_current_x += $element->get_extra_left(); $element = $element->parent; }; }; return $need_break; } function _find_soft_hyphen(&$parent, $width_delta) { /** * Now we search for soft hyphen closest to the right margin */ $size = count($this->_wrappable); for ($i=$size-1; $i>=0; $i $wrappable = $this->_wrappable[$i]; if ($this->get_width() - $wrappable[3] > $width_delta) { $this->save_wrapped($wrappable, $parent, $context); $parent->append_line($this); return; }; }; } function save_wrapped($wrappable, &$parent, &$context) { $this->wrapped = array($wrappable, $parent->_current_x + $this->get_extra_left(), $parent->_current_y - $this->get_extra_top()); } function reflow(&$parent, &$context) { // Check if we need a line break here (possilble several times in a row, if we // have a long word and a floating box intersecting with this word // To prevent infinite loop, we'll use a limit of 100 sequental line feeds $i=0; do { $i++; } while ($this->maybe_line_break($parent, $context) && $i < 100); // Determine the baseline position and height of the text-box using line-height CSS property $this->_apply_line_height(); // set default baseline $this->baseline = $this->default_baseline; // append current box to parent line box $parent->append_line($this); // Determine coordinates of upper-left _margin_ corner $this->guess_corner($parent); // Offset parent current X coordinate if (!is_null($this->wrapped)) { $parent->_current_x += $this->get_full_width() - $this->wrapped[0][2]; } else { $parent->_current_x += $this->get_full_width(); }; // Extends parents height $parent->extend_height($this->get_bottom()); // Update the value of current collapsed margin; pure text (non-span) // boxes always have zero margin $context-><API key>(); $context-><API key>( 0 ); } function <API key>() { return $this->wrapped[0][3]; } function getWrappedWidth() { return $this->wrapped[0][2]; } function reflow_text(&$driver) { $num_words = count($this->words); /** * Empty text box */ if ($num_words == 0) { return true; }; /** * A simple assumption is made: fonts used for different encodings * have equal ascender/descender values (while they have the same * typeface, style and weight). */ $font_name = $this->_get_font_name($driver, 0); /** * Get font vertical metrics */ $ascender = $driver->font_ascender($font_name, $this->encodings[0]); if (is_null($ascender)) { error_log("TextBox::reflow_text: cannot get font ascender"); return null; }; $descender = $driver->font_descender($font_name, $this->encodings[0]); if (is_null($descender)) { error_log("TextBox::reflow_text: cannot get font descender"); return null; }; /** * Setup box size */ $font = $this->getCSSProperty(CSS_FONT_SIZE); $font_size = $font->getPoints(); // Both ascender and descender should make $font_size // as it is not guaranteed that $ascender + $descender == 1, // we should normalize the result $koeff = $font_size / ($ascender + $descender); $this->ascender = $ascender * $koeff; $this->descender = $descender * $koeff; $this->default_baseline = $this->ascender; $this->height = $this->ascender + $this->descender; /** * Determine box width */ if ($font_size > 0) { $width = 0; for ($i=0; $i<$num_words; $i++) { $font_name = $this->_get_font_name($driver, $i); $current_width = $driver->stringwidth($this->words[$i], $font_name, $this->encodings[$i], $font_size); $this->_word_widths[] = $current_width; // Add information about soft hyphens $this->_wrappable = array_merge($this->_wrappable, $this->_make_wrappable($driver, $width, $font_name, $font_size, $i)); $width += $current_width; }; $this->width = $width; } else { $this->width = 0; }; $letter_spacing = $this->getCSSProperty(CSS_LETTER_SPACING); if ($letter_spacing->getPoints() != 0) { $this->_widths = array(); for ($i=0; $i<$num_words; $i++) { $num_chars = strlen($this->words[$i]); for ($j=0; $j<$num_chars; $j++) { $this->_widths[] = $driver->stringwidth($this->words[$i]{$j}, $font_name, $this->encodings[$i], $font_size); }; $this->width += $letter_spacing->getPoints()*$num_chars; }; }; return true; } function show(&$driver) { /** * Check if font-size have been set to 0; in this case we should not draw this box at all */ $font_size = $this->getCSSProperty(CSS_FONT_SIZE); if ($font_size->getPoints() == 0) { return true; } // Check if current text box will be cut-off by the page edge // Get Y coordinate of the top edge of the box $top = $this->get_top_margin(); // Get Y coordinate of the bottom edge of the box $bottom = $this->get_bottom_margin(); $top_inside = $top >= $driver->getPageBottom()-EPSILON; $bottom_inside = $bottom >= $driver->getPageBottom()-EPSILON; if (!$top_inside && !$bottom_inside) { return true; } return $this->_showText($driver); } function _showText(&$driver) { if (!is_null($this->wrapped)) { return $this->_showTextWrapped($driver); } else { return $this->_showTextNormal($driver); }; } function _showTextWrapped(&$driver) { // draw generic box parent::show($driver); $font_size = $this->getCSSProperty(CSS_FONT_SIZE); $decoration = $this->getCSSProperty(CSS_TEXT_DECORATION); // draw text decoration $driver->decoration($decoration['U'], $decoration['O'], $decoration['T']); $letter_spacing = $this->getCSSProperty(CSS_LETTER_SPACING); // Output text with the selected font // note that we're using $default_baseline; // the alignment offset - the difference between baseline and default_baseline values // is taken into account inside the get_top/get_bottom functions $current_char = 0; $left = $this->wrapped[1]; $top = $this->get_top() - $this->default_baseline; $num_words = count($this->words); /** * First part of wrapped word (before hyphen) */ for ($i=0; $i<$this->wrapped[0][0]; $i++) { // Activate font $status = $driver->setfont($this->_get_font_name($driver, $i), $this->encodings[$i], $font_size->getPoints()); if (is_null($status)) { error_log("TextBox::show: setfont call failed"); return null; }; $driver->show_xy($this->words[$i], $left, $this->wrapped[2] - $this->default_baseline); $left += $this->_word_widths[$i]; }; $index = $this->wrapped[0][0]; $status = $driver->setfont($this->_get_font_name($driver, $index), $this->encodings[$index], $font_size->getPoints()); if (is_null($status)) { error_log("TextBox::show: setfont call failed"); return null; }; $driver->show_xy(substr($this->words[$index],0,$this->wrapped[0][1])."-", $left, $this->wrapped[2] - $this->default_baseline); /** * Second part of wrapped word (after hyphen) */ $left = $this->get_left(); $top = $this->get_top(); $driver->show_xy(substr($this->words[$index],$this->wrapped[0][1]), $left, $top - $this->default_baseline); $size = count($this->words); for ($i = $this->wrapped[0][0]+1; $i<$size; $i++) { // Activate font $status = $driver->setfont($this->_get_font_name($driver, $i), $this->encodings[$i], $font_size->getPoints()); if (is_null($status)) { error_log("TextBox::show: setfont call failed"); return null; }; $driver->show_xy($this->words[$i], $left, $top - $this->default_baseline); $left += $this->_word_widths[$i]; }; return true; } function _showTextNormal(&$driver) { // draw generic box parent::show($driver); $font_size = $this->getCSSProperty(CSS_FONT_SIZE); $decoration = $this->getCSSProperty(CSS_TEXT_DECORATION); // draw text decoration $driver->decoration($decoration['U'], $decoration['O'], $decoration['T']); $letter_spacing = $this->getCSSProperty(CSS_LETTER_SPACING); if ($letter_spacing->getPoints() == 0) { // Output text with the selected font // note that we're using $default_baseline; // the alignment offset - the difference between baseline and default_baseline values // is taken into account inside the get_top/get_bottom functions $size = count($this->words); $left = $this->get_left(); for ($i=0; $i<$size; $i++) { // Activate font $status = $driver->setfont($this->_get_font_name($driver, $i), $this->encodings[$i], $font_size->getPoints()); if (is_null($status)) { error_log("TextBox::show: setfont call failed"); return null; }; $driver->show_xy($this->words[$i], $left, $this->get_top() - $this->default_baseline); $left += $this->_word_widths[$i]; }; } else { $current_char = 0; $left = $this->get_left(); $top = $this->get_top() - $this->default_baseline; $num_words = count($this->words); for ($i=0; $i<$num_words; $i++) { $num_chars = strlen($this->words[$i]); for ($j=0; $j<$num_chars; $j++) { $status = $driver->setfont($this->_get_font_name($driver, $i), $this->encodings[$i], $font_size->getPoints()); $driver->show_xy($this->words[$i]{$j}, $left, $top); $left += $this->_widths[$current_char] + $letter_spacing->getPoints(); $current_char++; }; }; }; return true; } function show_fixed(&$driver) { $font_size = $this->getCSSProperty(CSS_FONT_SIZE); // Check if font-size have been set to 0; in this case we should not draw this box at all if ($font_size->getPoints() == 0) { return true; } return $this->_showText($driver); } function offset($dx, $dy) { parent::offset($dx, $dy); // Note that horizonal offset should be called explicitly from text-align routines // otherwise wrapped part will be offset twice (as offset is called both for // wrapped and non-wrapped parts). if (!is_null($this->wrapped)) { $this->offset_wrapped($dx, $dy); }; } function offset_wrapped($dx, $dy) { $this->wrapped[1] += $dx; $this->wrapped[2] += $dy; } function reflow_whitespace(&$linebox_started, &$previous_whitespace) { $linebox_started = true; $previous_whitespace = false; return; } function is_null() { return false; } } ?>